-
Notifications
You must be signed in to change notification settings - Fork 33
/
lib.c
5982 lines (5087 loc) · 139 KB
/
lib.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2020-2021 Jo-Philipp Wich <jo@mein.io>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
* # Builtin functions
*
* The core namespace is not an actual module but refers to the set of
* builtin functions and properties available to `ucode` scripts.
*
* @module core
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <signal.h>
#include <ctype.h>
#include <errno.h>
#include <math.h>
#include <time.h>
#include <dlfcn.h>
#include <libgen.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fnmatch.h>
#include <assert.h>
#include "json-c-compat.h"
#include "ucode/lexer.h"
#include "ucode/compiler.h"
#include "ucode/vm.h"
#include "ucode/lib.h"
#include "ucode/source.h"
#include "ucode/program.h"
#include "ucode/platform.h"
static void
format_context_line(uc_stringbuf_t *buf, const char *line, size_t off, bool compact)
{
unsigned padlen, i;
const char *p;
for (p = line, padlen = 0; *p != '\n' && *p != '\0'; p++) {
if (compact && (p - line) == (ptrdiff_t)off)
ucv_stringbuf_append(buf, "\033[22m");
switch (*p) {
case '\t':
ucv_stringbuf_append(buf, " ");
if (p < line + off)
padlen += 4;
break;
case '\r':
case '\v':
ucv_stringbuf_append(buf, " ");
if (p < line + off)
padlen++;
break;
default:
ucv_stringbuf_addstr(buf, p, 1);
if (p < line + off)
padlen++;
}
}
if (compact) {
ucv_stringbuf_append(buf, "\033[m\n");
return;
}
ucv_stringbuf_append(buf, "`\n ");
if (padlen < strlen("Near here ^")) {
for (i = 0; i < padlen; i++)
ucv_stringbuf_append(buf, " ");
ucv_stringbuf_append(buf, "^-- Near here\n");
}
else {
ucv_stringbuf_append(buf, "Near here ");
for (i = strlen("Near here "); i < padlen; i++)
ucv_stringbuf_append(buf, "-");
ucv_stringbuf_append(buf, "^\n");
}
}
static char *
source_filename(uc_source_t *src, uint32_t line)
{
const char *name = src->filename ? basename(src->filename) : "[?]";
static char buf[sizeof("xxxxxxxxx.uc:0000000000")];
size_t len = strlen(name);
if (len > 12)
snprintf(buf, sizeof(buf), "...%s:%u", name + (len - 9), line);
else
snprintf(buf, sizeof(buf), "%12s:%u", name, line);
return buf;
}
bool
uc_source_context_format(uc_stringbuf_t *buf, uc_source_t *src, size_t off, bool compact)
{
size_t len, rlen;
bool truncated;
char line[256];
long srcpos;
int eline;
srcpos = ftell(src->fp);
if (srcpos == -1)
return false;
fseek(src->fp, 0, SEEK_SET);
truncated = false;
eline = 1;
rlen = 0;
while (fgets(line, sizeof(line), src->fp)) {
len = strlen(line);
rlen += len;
if (rlen >= off) {
if (compact)
ucv_stringbuf_printf(buf, "\033[2;40;97m%17s %s",
source_filename(src, eline),
truncated ? "..." : "");
else
ucv_stringbuf_printf(buf, "\n `%s",
truncated ? "..." : "");
format_context_line(buf, line, len - (rlen - off) + (truncated ? 3 : 0), compact);
break;
}
truncated = (len > 0 && line[len-1] != '\n');
eline += !truncated;
}
fseek(src->fp, srcpos, SEEK_SET);
return true;
}
bool
uc_error_context_format(uc_stringbuf_t *buf, uc_source_t *src, uc_value_t *stacktrace, size_t off)
{
uc_value_t *e, *fn, *file, *line, *byte;
const char *path;
size_t idx;
for (idx = 0; idx < (stacktrace ? ucv_array_length(stacktrace) : 0); idx++) {
e = ucv_array_get(stacktrace, idx);
fn = ucv_object_get(e, "function", NULL);
file = ucv_object_get(e, "filename", NULL);
if (idx == 0) {
path = (file && strcmp(ucv_string_get(file), "[stdin]"))
? ucv_string_get(file) : NULL;
if (path && fn)
ucv_stringbuf_printf(buf, "In %s(), file %s, ", ucv_string_get(fn), path);
else if (fn)
ucv_stringbuf_printf(buf, "In %s(), ", ucv_string_get(fn));
else if (path)
ucv_stringbuf_printf(buf, "In %s, ", path);
else
ucv_stringbuf_append(buf, "In ");
ucv_stringbuf_printf(buf, "line %" PRId64 ", byte %" PRId64 ":\n",
ucv_int64_get(ucv_object_get(e, "line", NULL)),
ucv_int64_get(ucv_object_get(e, "byte", NULL)));
}
else {
line = ucv_object_get(e, "line", NULL);
byte = ucv_object_get(e, "byte", NULL);
ucv_stringbuf_printf(buf, " called from %s%s (%s",
fn ? "function " : "anonymous function",
fn ? ucv_string_get(fn) : "",
file ? ucv_string_get(file) : "");
if (line && byte)
ucv_stringbuf_printf(buf, ":%" PRId64 ":%" PRId64 ")\n",
ucv_int64_get(line),
ucv_int64_get(byte));
else
ucv_stringbuf_append(buf, "[C])\n");
}
}
return uc_source_context_format(buf, src, off, false);
}
void
uc_error_message_indent(char **msg) {
uc_stringbuf_t *buf = xprintbuf_new();
char *s, *p, *nl;
size_t len;
if (!msg || !*msg)
return;
s = *msg;
len = strlen(s);
while (len > 0 && s[len-1] == '\n')
s[--len] = 0;
for (p = s, nl = strchr(p, '\n'); p != NULL;
p = nl ? nl + 1 : NULL, nl = p ? strchr(p, '\n') : NULL)
{
if (!nl)
ucv_stringbuf_printf(buf, " | %s", p);
else if (nl != p)
ucv_stringbuf_printf(buf, " | %.*s\n", (int)(nl - p), p);
else
ucv_stringbuf_append(buf, " |\n");
}
ucv_stringbuf_append(buf, "\n");
*msg = buf->buf;
free(buf);
free(s);
}
static char *uc_cast_string(uc_vm_t *vm, uc_value_t **v, bool *freeable) {
if (ucv_type(*v) == UC_STRING) {
*freeable = false;
return _ucv_string_get(v);
}
*freeable = true;
return ucv_to_string(vm, *v);
}
static void
uc_vm_ctx_push(uc_vm_t *vm)
{
uc_value_t *ctx = NULL;
if (vm->callframes.count >= 2)
ctx = vm->callframes.entries[vm->callframes.count - 2].ctx;
uc_vm_stack_push(vm, ucv_get(ctx));
}
static uc_value_t *
uc_print_common(uc_vm_t *vm, size_t nargs, FILE *fh)
{
uc_value_t *item;
size_t reslen = 0;
size_t len = 0;
size_t arridx;
char *p;
for (arridx = 0; arridx < nargs; arridx++) {
item = uc_fn_arg(arridx);
if (ucv_type(item) == UC_STRING) {
len = ucv_string_length(item);
reslen += fwrite(ucv_string_get(item), 1, len, fh);
}
else if (item != NULL) {
p = ucv_to_string(vm, item);
len = strlen(p);
reslen += fwrite(p, 1, len, fh);
free(p);
}
}
return ucv_int64_new(reslen);
}
/**
* Print any of the given values to stdout.
*
* The `print()` function writes a string representation of each given argument
* to stdout and returns the amount of bytes written.
*
* String values are printed as-is, integer and double values are printed in
* decimal notation, boolean values are printed as `true` or `false` while
* arrays and objects are converted to their JSON representation before being
* written to the standard output. The `null` value is represented by an empty
* string so `print(null)` would print nothing. Resource values are printed in
* the form `<type address>`, e.g. `<fs.file 0x7f60f0981760>`.
*
* If resource, array or object values contain a `tostring()` function in their
* prototypes, then this function is invoked to obtain an alternative string
* representation of the value.
*
* Examples:
*
* ```javascript
* print(1 != 2); // Will print 'true'
* print(0xff); // Will print '255'
* print(2e3); // Will print '2000'
* print(null); // Will print nothing
* print({ hello: true, world: 123 }); // Will print '{ "hello": true, "world": 123 }'
* print([1,2,3]); // Will print '[ 1, 2, 3 ]'
*
* print(proto({ foo: "bar" }, // Will print 'MyObj'
* { tostring: () => "MyObj" })); // instead of '{ "foo": "bar" }'
*
* ```
*
* Returns the amount of bytes printed.
*
* @function module:core#print
*
* @param {...*} values
* Arbitrary values to print
*
* @returns {number}
*/
static uc_value_t *
uc_print(uc_vm_t *vm, size_t nargs)
{
return uc_print_common(vm, nargs, vm->output);
}
/**
* Determine the length of the given object, array or string.
*
* Returns the length of the given value.
*
* - For strings, the length is the amount of bytes within the string
* - For arrays, the length is the amount of array elements
* - For objects, the length is defined as the amount of keys
*
* Returns `null` if the given argument is not an object, array or string.
*
* @function module:core#length
*
* @param {Object|Array|string} x - The input object, array, or string.
*
* @returns {?number} - The length of the input.
*
* @example
* length("test") // 4
* length([true, false, null, 123, "test"]) // 5
* length({foo: true, bar: 123, baz: "test"}) // 3
* length({}) // 0
* length(true) // null
* length(10.0) // null
*/
static uc_value_t *
uc_length(uc_vm_t *vm, size_t nargs)
{
uc_value_t *arg = uc_fn_arg(0);
switch (ucv_type(arg)) {
case UC_OBJECT:
return ucv_int64_new(ucv_object_length(arg));
case UC_ARRAY:
return ucv_int64_new(ucv_array_length(arg));
case UC_STRING:
return ucv_int64_new(ucv_string_length(arg));
default:
return NULL;
}
}
static int
uc_uniq_ucv_equal(const void *k1, const void *k2);
static uc_value_t *
uc_index(uc_vm_t *vm, size_t nargs, bool right)
{
uc_value_t *stack = uc_fn_arg(0);
uc_value_t *needle = uc_fn_arg(1);
const char *sstr, *nstr, *p;
size_t arridx, slen, nlen;
ssize_t ret = -1;
switch (ucv_type(stack)) {
case UC_ARRAY:
if (right) {
for (arridx = ucv_array_length(stack); arridx > 0; arridx--) {
if (uc_uniq_ucv_equal(ucv_array_get(stack, arridx - 1), needle)) {
ret = (ssize_t)(arridx - 1);
break;
}
}
}
else {
for (arridx = 0, slen = ucv_array_length(stack); arridx < slen; arridx++) {
if (uc_uniq_ucv_equal(ucv_array_get(stack, arridx), needle)) {
ret = (ssize_t)arridx;
break;
}
}
}
return ucv_int64_new(ret);
case UC_STRING:
if (ucv_type(needle) == UC_STRING) {
sstr = ucv_string_get(stack);
slen = ucv_string_length(stack);
nstr = ucv_string_get(needle);
nlen = ucv_string_length(needle);
if (slen == nlen) {
if (memcmp(sstr, nstr, nlen) == 0)
ret = 0;
}
else if (slen > nlen) {
if (right) {
p = sstr + slen - nlen;
do {
if (memcmp(p, nstr, nlen) == 0) {
ret = (ssize_t)(p - sstr);
break;
}
}
while (--p != sstr);
}
else if (nlen > 0) {
p = (const char *)memmem(sstr, slen, nstr, nlen);
if (p)
ret = (ssize_t)(p - sstr);
}
else {
ret = 0;
}
}
}
return ucv_int64_new(ret);
default:
return NULL;
}
}
/**
* Finds the given value passed as the second argument within the array or
* string specified in the first argument.
*
* Returns the first matching array index or first matching string offset or
* `-1` if the value was not found.
*
* Returns `null` if the first argument was neither an array nor a string.
*
* @function module:core#index
*
* @param {Array|string} arr_or_str
* The array or string to search for the value.
*
* @param {*} needle
* The value to find within the array or string.
*
* @returns {?number}
*
* @example
* index("Hello hello hello", "ll") // 2
* index([ 1, 2, 3, 1, 2, 3, 1, 2, 3 ], 2) // 1
* index("foo", "bar") // -1
* index(["Red", "Blue", "Green"], "Brown") // -1
* index(123, 2) // null
*/
static uc_value_t *
uc_lindex(uc_vm_t *vm, size_t nargs)
{
return uc_index(vm, nargs, false);
}
/**
* Finds the given value passed as the second argument within the array or
* string specified in the first argument.
*
* Returns the last matching array index or last matching string offset or
* `-1` if the value was not found.
*
* Returns `null` if the first argument was neither an array nor a string.
*
* @function module:core#rindex
*
* @param {Array|string} arr_or_str
* The array or string to search for the value.
*
* @param {*} needle
* The value to find within the array or string.
*
* @returns {?number}
*
* @example
* rindex("Hello hello hello", "ll") // 14
* rindex([ 1, 2, 3, 1, 2, 3, 1, 2, 3 ], 2) // 7
* rindex("foo", "bar") // -1
* rindex(["Red", "Blue", "Green"], "Brown") // -1
* rindex(123, 2) // null
*/
static uc_value_t *
uc_rindex(uc_vm_t *vm, size_t nargs)
{
return uc_index(vm, nargs, true);
}
static bool
assert_mutable(uc_vm_t *vm, uc_value_t *val)
{
if (ucv_is_constant(val)) {
uc_vm_raise_exception(vm, EXCEPTION_TYPE,
"%s value is immutable",
ucv_typename(val));
return false;
}
return true;
}
static bool
assert_mutable_array(uc_vm_t *vm, uc_value_t *val)
{
if (ucv_type(val) != UC_ARRAY)
return false;
return assert_mutable(vm, val);
}
/**
* Pushes the given argument(s) to the given array.
*
* Returns the last pushed value.
*
* @function module:core#push
*
* @param {Array} arr
* The array to push values to.
*
* @param {...*} [values]
* The values to push.
*
* @returns {*}
*
* @example
* let x = [ 1, 2, 3 ];
* push(x, 4, 5, 6); // 6
* print(x, "\n"); // [ 1, 2, 3, 4, 5, 6 ]
*/
static uc_value_t *
uc_push(uc_vm_t *vm, size_t nargs)
{
uc_value_t *arr = uc_fn_arg(0);
uc_value_t *item = NULL;
size_t arridx;
if (!assert_mutable_array(vm, arr))
return NULL;
for (arridx = 1; arridx < nargs; arridx++) {
item = uc_fn_arg(arridx);
ucv_array_push(arr, ucv_get(item));
}
return ucv_get(item);
}
/**
* Pops the last item from the given array and returns it.
*
* Returns `null` if the array was empty or if a non-array argument was passed.
*
* @function module:core#pop
*
* @param {Array} arr
* The input array.
*
* @returns {*}
*
* @example
* let x = [ 1, 2, 3 ];
* pop(x); // 3
* print(x, "\n"); // [ 1, 2 ]
*/
static uc_value_t *
uc_pop(uc_vm_t *vm, size_t nargs)
{
uc_value_t *arr = uc_fn_arg(0);
if (!assert_mutable_array(vm, arr))
return NULL;
return ucv_array_pop(arr);
}
/**
* Pops the first item from the given array and returns it.
*
* Returns `null` if the array was empty or if a non-array argument was passed.
*
* @function module:core#shift
*
* @param {Array} arr
* The array from which to pop the first item.
*
* @returns {*}
*
* @example
* let x = [ 1, 2, 3 ];
* shift(x); // 1
* print(x, "\n"); // [ 2, 3 ]
*/
static uc_value_t *
uc_shift(uc_vm_t *vm, size_t nargs)
{
uc_value_t *arr = uc_fn_arg(0);
if (!assert_mutable_array(vm, arr))
return NULL;
return ucv_array_shift(arr);
}
/**
* Add the given values to the beginning of the array passed via first argument.
*
* Returns the last value added to the array.
*
* @function module:core#unshift
*
* @param {Array} arr
* The array to which the values will be added.
*
* @param {...*}
* Values to add.
*
* @returns {*}
*
* @example
* let x = [ 3, 4, 5 ];
* unshift(x, 1, 2); // 2
* print(x, "\n"); // [ 1, 2, 3, 4, 5 ]
*/
static uc_value_t *
uc_unshift(uc_vm_t *vm, size_t nargs)
{
uc_value_t *arr = uc_fn_arg(0);
uc_value_t *item;
size_t i;
if (!assert_mutable_array(vm, arr))
return NULL;
for (i = 1; i < nargs; i++) {
item = uc_fn_arg(nargs - i);
ucv_array_unshift(arr, ucv_get(item));
}
return (nargs > 1) ? ucv_get(uc_fn_arg(nargs - 1)) : NULL;
}
/**
* Converts each given numeric value to a byte and return the resulting string.
* Invalid numeric values or values < 0 result in `\0` bytes, values larger than
* 255 are truncated to 255.
*
* Returns a new strings consisting of the given byte values.
*
* @function module:core#chr
*
* @param {...number} n1
* The numeric values.
*
* @returns {string}
*
* @example
* chr(65, 98, 99); // "Abc"
* chr(-1, 300); // string consisting of an `0x0` and a `0xff` byte
*/
static uc_value_t *
uc_chr(uc_vm_t *vm, size_t nargs)
{
uc_value_t *rv = NULL;
size_t idx;
int64_t n;
char *str;
if (!nargs)
return ucv_string_new_length("", 0);
str = xalloc(nargs);
for (idx = 0; idx < nargs; idx++) {
n = ucv_to_integer(uc_fn_arg(idx));
if (n < 0)
n = 0;
else if (n > 255)
n = 255;
str[idx] = (char)n;
}
rv = ucv_string_new_length(str, nargs);
free(str);
return rv;
}
/**
* Raise an exception with the given message and abort execution.
*
* @function module:core#die
*
* @param {string} msg
* The error message.
*
* @throws {Error}
* The error with the given message.
*
* @example
* die(msg);
*/
static uc_value_t *
uc_die(uc_vm_t *vm, size_t nargs)
{
uc_value_t *msg = uc_fn_arg(0);
bool freeable = false;
char *s;
s = msg ? uc_cast_string(vm, &msg, &freeable) : "Died";
uc_vm_raise_exception(vm, EXCEPTION_USER, "%s", s);
if (freeable)
free(s);
return NULL;
}
/**
* Check whether the given key exists within the given object value.
*
* Returns `true` if the given key is present within the object passed as the
* first argument, otherwise `false`.
*
* @function module:core#exists
*
* @param {Object} obj
* The input object.
*
* @param {string} key
* The key to check for existence.
*
* @returns {boolean}
*
* @example
* let x = { foo: true, bar: false, qrx: null };
* exists(x, 'foo'); // true
* exists(x, 'qrx'); // true
* exists(x, 'baz'); // false
*/
static uc_value_t *
uc_exists(uc_vm_t *vm, size_t nargs)
{
uc_value_t *obj = uc_fn_arg(0);
uc_value_t *key = uc_fn_arg(1);
bool found, freeable;
char *k;
if (ucv_type(obj) != UC_OBJECT)
return ucv_boolean_new(false);
k = uc_cast_string(vm, &key, &freeable);
ucv_object_get(obj, k, &found);
if (freeable)
free(k);
return ucv_boolean_new(found);
}
/**
* Terminate the interpreter with the given exit code.
*
* This function does not return.
*
* @function module:core#exit
*
* @param {number} n
* The exit code.
*
* @example
* exit();
* exit(5);
*/
static uc_value_t *
uc_exit(uc_vm_t *vm, size_t nargs)
{
int64_t n = ucv_to_integer(uc_fn_arg(0));
vm->arg.s32 = (int32_t)n;
uc_vm_raise_exception(vm, EXCEPTION_EXIT, "Terminated");
return NULL;
}
/**
* Query an environment variable or then entire environment.
*
* Returns the value of the given environment variable, or - if omitted - a
* dictionary containing all environment variables.
*
* @function module:core#getenv
*
* @param {string} [name]
* The name of the environment variable.
*
* @returns {string|Object<string, string>}
*/
static uc_value_t *
uc_getenv(uc_vm_t *vm, size_t nargs)
{
uc_value_t *key = uc_fn_arg(0), *rv = NULL;
extern char **environ;
char **env = environ;
char *k, *v;
if (!key) {
rv = ucv_object_new(vm);
while (*env) {
v = strchr(*env, '=');
if (v) {
xasprintf(&k, "%.*s", (int)(v - *env), *env);
ucv_object_add(rv, k, ucv_string_new(v + 1));
free(k);
}
env++;
}
}
else if (ucv_type(key) == UC_STRING) {
k = ucv_string_get(key);
v = getenv(k);
if (v)
rv = ucv_string_new(v);
}
return rv;
}
/**
* Filter the array passed as the first argument by invoking the function
* specified in the second argument for each array item.
*
* If the invoked function returns a truthy result, the item is retained,
* otherwise, it is dropped. The filter function is invoked with three
* arguments:
*
* 1. The array value
* 2. The current index
* 3. The array being filtered
*
* (Note that the `map` function behaves similarly to `filter` with respect
* to its `fn` parameters.)
*
* Returns a new array containing only retained items, in the same order as
* the input array.
*
* @function module:core#filter
*
* @param {Array} arr
* The input array.
*
* @param {Function} fn
* The filter function.
*
* @returns {Array}
*
* @example
* // filter out any empty string:
* a = filter(["foo", "", "bar", "", "baz"], length)
* // a = ["foo", "bar", "baz"]
*
* // filter out any non-number type:
* a = filter(["foo", 1, true, null, 2.2], function(v) {
* return (type(v) == "int" || type(v) == "double");
* });
* // a = [1, 2.2]
*/
static uc_value_t *
uc_filter(uc_vm_t *vm, size_t nargs)
{
uc_value_t *obj = uc_fn_arg(0);
uc_value_t *func = uc_fn_arg(1);
uc_value_t *rv, *arr;
size_t arridx, arrlen;
if (ucv_type(obj) != UC_ARRAY)
return NULL;
arr = ucv_array_new(vm);
for (arrlen = ucv_array_length(obj), arridx = 0; arridx < arrlen; arridx++) {
uc_vm_ctx_push(vm);
uc_vm_stack_push(vm, ucv_get(func));
uc_vm_stack_push(vm, ucv_get(ucv_array_get(obj, arridx)));
uc_vm_stack_push(vm, ucv_int64_new(arridx));
uc_vm_stack_push(vm, ucv_get(obj));
if (uc_vm_call(vm, true, 3)) {
ucv_put(arr);
return NULL;
}
rv = uc_vm_stack_pop(vm);
if (ucv_is_truish(rv))
ucv_array_push(arr, ucv_get(ucv_array_get(obj, arridx)));
ucv_put(rv);
}
return arr;
}
/**
* Converts the given hexadecimal string into a number.
*
* Returns the resulting integer value or `NaN` if the input value cannot be
* interpreted as hexadecimal number.
*
* @function module:core#hex
*
* @param {*} x
* The hexadecimal string to be converted.
*
* @returns {number}
*/
static uc_value_t *
uc_hex(uc_vm_t *vm, size_t nargs)
{
uc_value_t *val = uc_fn_arg(0);
char *e, *v;
int64_t n;
v = ucv_string_get(val);
if (!v || !isxdigit(*v))
return ucv_double_new(NAN);
n = strtoll(v, &e, 16);
if (e == v || *e)
return ucv_double_new(NAN);
return ucv_int64_new(n);
}
/**
* Converts the given value to an integer, using an optional base.
*
* Returns `NaN` if the value is not convertible.
*
* @function module:core#int