-
Notifications
You must be signed in to change notification settings - Fork 43
/
vm.c
5000 lines (4481 loc) · 177 KB
/
vm.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
#include <assert.h>
#include <dlfcn.h>
#include <inttypes.h>
#include <math.h>
#include <pthread.h>
#include <stdarg.h>
#include <time.h>
#include <string.h>
#ifdef HAVE_POLL_H
#include <sys/poll.h>
#endif
// REALPATH(3)
#include <limits.h>
#include <stdlib.h>
// GETTIMEOFDAY(2)
#include <sys/time.h>
#include <ffi.h>
// ..., FMEMOPEN(3)
#include <stdio.h>
#ifdef __APPLE__
#include "fmemopen.h"
#endif
// OPEN(2), LSEEK(2), WAIT(2)
// #define _POSIX_SOURCE
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <signal.h>
// READ(2), LSEEK(2), FORK(2), EXECVE(2), DUP2(2), SYSCONF(3)
#include <unistd.h>
// SOCKET(2), ...
#include <sys/socket.h>
// DIR
#include <dirent.h>
#include <errno.h>
#include <pcre.h>
#include "ngs.h"
#include "vm.h"
#include "ast.h"
#include "compile.h"
#include "syntax.h"
#include "syntax.auto.h"
extern char **environ;
// in syntax.include
void position_to_line_col(yycontext *yy, int pos, int result[]);
// in obj.c:
VALUE value_type(VM *vm, VALUE val);
char BYTECODE_SIGNATURE[] = "NGS BYTECODE";
char *opcodes_names[] = {
"HALT",
"PUSH_NULL",
"PUSH_FALSE",
"PUSH_TRUE",
"PUSH_INT32",
"PUSH_INT64",
"PUSH_REAL",
"PUSH_L8_STR",
"PUSH_L32_STR",
"DUP",
"POP",
"XCHG",
"RESOLVE_GLOBAL",
"PATCH",
"FETCH_GLOBAL",
"STORE_GLOBAL",
"FETCH_LOCAL",
"STORE_LOCAL",
"CALL",
"CALL_EXC",
"CALL_ARR",
"RET",
"JMP",
"JMP_TRUE",
"JMP_FALSE",
"MAKE_ARR",
"MAKE_CLOSURE",
"TO_STR",
"MAKE_STR",
"MAKE_STR_IMM",
"MAKE_STR_EXP",
"MAKE_STR_SPLAT_EXP",
"PUSH_EMPTY_STR",
"DEF_GLOBAL_FUNC",
"DEF_LOCAL_FUNC",
"FETCH_UPVAR",
"STORE_UPVAR",
"DEF_UPVAR_FUNC",
"MAKE_HASH",
"TO_BOOL",
"TO_ARR",
"TO_HASH",
"ARR_APPEND",
"ARR_APPEND2",
"ARR_CONCAT",
"GUARD",
"TRY_START",
"TRY_END",
"ARR_REVERSE",
"THROW",
"MAKE_CMDS_PIPELINE",
"MAKE_CMDS_PIPE",
"MAKE_CMD",
"SET_CLOSURE_NAME",
"SET_CLOSURE_DOC",
"SET_CLOSURE_NS",
"HASH_SET",
"HASH_UPDATE",
"PUSH_KWARGS_MARKER",
"MAKE_REDIR",
"SUPER",
"MAKE_MULTIMETHOD",
"MULTIMETHOD_APPEND",
"MULTIMETHOD_REVERSE",
};
#define ASSERT_STACK_SPACE if(ctx->stack_ptr>=MAX_STACK) goto stack_overflow_exception;
#define EXPECT_STACK_DEPTH(n) assert(ctx->stack_ptr >= (n));
#define PUSH(v) ASSERT_STACK_SPACE; ctx->stack[ctx->stack_ptr++] = v
#define PUSH_NOCHECK(v) ctx->stack[ctx->stack_ptr++] = v
#define POP(dst) assert(ctx->stack_ptr); ctx->stack_ptr--; (dst) = ctx->stack[ctx->stack_ptr]
#define POP_NOCHECK(dst) ctx->stack_ptr--; (dst) = ctx->stack[ctx->stack_ptr]
#define FIRST (ctx->stack[ctx->stack_ptr-1])
#define TOP FIRST
#define SECOND (ctx->stack[ctx->stack_ptr-2])
#define THIRD (ctx->stack[ctx->stack_ptr-3])
#define DUP ASSERT_STACK_SPACE; ctx->stack[ctx->stack_ptr] = ctx->stack[ctx->stack_ptr-1]; ctx->stack_ptr++;
#define REMOVE_TOP assert(ctx->stack_ptr); ctx->stack_ptr--
#define REMOVE_TOP_NOCHECK ctx->stack_ptr--
#define REMOVE_TOP_N(n) DEBUG_VM_RUN("Popping %d argument(s) after call from stack\n", (int)(n)); assert(ctx->stack_ptr >= (unsigned int)(n)); ctx->stack_ptr-=(n);
#define REMOVE_TOP_N_NOCHECK(n) DEBUG_VM_RUN("Popping %d argument(s) after call from stack\n", (int)(n)); ctx->stack_ptr-=(n);
#define GLOBALS (vm->globals)
#define THIS_FRAME (ctx->frames[ctx->frame_ptr-1])
#define THIS_FRAME_CLOSURE (THIS_FRAME.closure)
#define DEEPER_FRAME (ctx->frames[ctx->frame_ptr])
#define LOCALS (THIS_FRAME.locals)
#define UPLEVELS CLOSURE_OBJ_UPLEVELS(THIS_FRAME_CLOSURE)
#define ARG(name, type) name = *(type *) &vm->bytecode[ip]; ip += sizeof(type);
#define ARG_LVI ARG(lvi, LOCAL_VAR_INDEX);
#define ARG_GVI ARG(gvi, GLOBAL_VAR_INDEX);
#define ARG_UVI ARG(uvi, UPVAR_INDEX);
#define PUSH_METHOD_EXC(msg, dst, fn) \
VALUE e; \
e = make_normal_type_instance(vm->InvalidArgument); \
set_normal_type_instance_field(e, make_string("message"), make_string(msg)); \
set_normal_type_instance_field(e, make_string("backtrace"), make_backtrace(vm, ctx)); \
set_normal_type_instance_field(e, make_string("target"), dst); \
set_normal_type_instance_field(e, make_string("method"), fn); \
*result = e; \
goto exception;
#define PUSH_METHOD(dst, fn) \
if(IS_NGS_TYPE(dst)) { \
if(!IS_MULMETHOD(NGS_TYPE_CONSTRUCTORS(dst))) { \
PUSH_METHOD_EXC("Can not push method as type constructor is not a MultiMethod", dst, fn); \
} \
push_multimethod_method(NGS_TYPE_CONSTRUCTORS(dst), (fn)); \
} else { \
if(!IS_MULMETHOD(dst)) { \
PUSH_METHOD_EXC("Can not push method into non-MultiMethod. You are defining a method but the variable already exists and it is not a MultiMethod.", dst, fn); \
} \
push_multimethod_method(dst, fn); \
};
// TODO: Exception
#define CONVERTING_OP(test, type) \
assert(ctx->stack_ptr); \
v = TOP; \
if(test(v)) { \
goto main_loop; \
} \
PUSH(v); \
THIS_FRAME.last_ip = ip; \
mr = vm_call(vm, ctx, &ctx->stack[ctx->stack_ptr-2], vm->type, 1, &ctx->stack[ctx->stack_ptr-1]); \
if(mr == METHOD_EXCEPTION) { \
*result = ctx->stack[ctx->stack_ptr-2]; \
goto exception; \
} \
if(mr != METHOD_OK) { \
dump_titled(stderr, "Failed to convert to type", vm->type); \
dump_titled(stderr, "Failed to convert value", ctx->stack[ctx->stack_ptr-1]); \
assert(0 == "Failed to convert"); \
} \
REMOVE_TOP_N(1); \
goto main_loop;
#define METHOD_PARAMS (VALUE *argv, VALUE *result)
#define EXT_METHOD_PARAMS (VM *vm, CTX *ctx, VALUE *argv, VALUE *result)
#define METHOD_RETURN(v) { *result = (v); return METHOD_OK; }
#define THROW_EXCEPTION(t) { *result = make_string(t); return METHOD_EXCEPTION; }
#define THROW_EXCEPTION_INSTANCE(e) { \
set_normal_type_instance_field(e, make_string("backtrace"), make_backtrace(vm, ctx)); \
*result = e; \
return METHOD_EXCEPTION; \
}
#define INT_METHOD(name, op) \
METHOD_RESULT native_ ## name ## _int_int METHOD_PARAMS { \
SET_INT(*result, GET_INT(argv[0]) op GET_INT(argv[1])); \
return METHOD_OK; \
}
#define INT_DIV_METHOD(name, op) \
METHOD_RESULT native_ ## name ## _int_int EXT_METHOD_PARAMS { \
if(GET_INT(argv[1]) == 0) { \
VALUE exc; \
exc = make_normal_type_instance(vm->DivisionByZero); \
THROW_EXCEPTION_INSTANCE(exc); \
} \
SET_INT(*result, GET_INT(argv[0]) op GET_INT(argv[1])); \
return METHOD_OK; \
}
#define INT_CMP_METHOD(name, op) \
METHOD_RESULT native_ ## name ## _int_int METHOD_PARAMS { \
SET_BOOL(*result, GET_INT(argv[0]) op GET_INT(argv[1])); \
return METHOD_OK; \
}
#define REAL_METHOD(name, op) \
METHOD_RESULT native_ ## name ## _real_real METHOD_PARAMS { \
METHOD_RETURN(make_real(GET_REAL(argv[0]) op GET_REAL(argv[1]))); \
}
#define REAL_CMP_METHOD(name, op) \
METHOD_RESULT native_ ## name ## _real_real METHOD_PARAMS { \
SET_BOOL(*result, GET_REAL(argv[0]) op GET_REAL(argv[1])); \
return METHOD_OK; \
}
#define ARG_LEN(n) OBJ_LEN(argv[n])
#define ARG_DATA_PTR(n) OBJ_DATA_PTR(argv[n])
#define BYTECODE_ADD(ptr, type, val) \
*(type *) (ptr) = val; \
(ptr) += sizeof(type);
#define BYTECODE_GET(dst, ptr, type) \
dst = *(type *) (ptr); \
(ptr) += sizeof(type);
INT_METHOD(plus, +)
INT_METHOD(minus, -)
INT_METHOD(mul, *)
INT_METHOD(band, &)
INT_METHOD(bor, |)
INT_METHOD(bxor, ^)
INT_DIV_METHOD(div, /)
INT_DIV_METHOD(mod, %)
INT_CMP_METHOD(less, <)
INT_CMP_METHOD(less_eq, <=)
INT_CMP_METHOD(greater, >)
INT_CMP_METHOD(greater_eq, >=)
INT_CMP_METHOD(eq, ==)
REAL_METHOD(plus, +)
REAL_METHOD(minus, -)
REAL_METHOD(mul, *)
REAL_METHOD(div, /)
REAL_CMP_METHOD(less, <)
REAL_CMP_METHOD(less_eq, <=)
REAL_CMP_METHOD(greater, >)
REAL_CMP_METHOD(greater_eq, >=)
REAL_CMP_METHOD(eq, ==)
METHOD_RESULT native_dump_any METHOD_PARAMS {
dump(stderr, argv[0]);
*result = MAKE_NULL;
return METHOD_OK;
}
METHOD_RESULT native_false METHOD_PARAMS {
(void) argv;
METHOD_RETURN(MAKE_FALSE);
}
METHOD_RESULT native_plus_arr_arr METHOD_PARAMS {
*result = make_array(ARG_LEN(0) + ARG_LEN(1));
memcpy(ARRAY_ITEMS(*result)+0, ARG_DATA_PTR(0), sizeof(VALUE)*ARG_LEN(0));
memcpy(ARRAY_ITEMS(*result)+ARG_LEN(0), OBJ_DATA_PTR(argv[1]), sizeof(VALUE)*ARG_LEN(1));
return METHOD_OK;
}
METHOD_RESULT native_push_arr_any METHOD_PARAMS { array_push(argv[0], argv[1]); METHOD_RETURN(argv[0]); }
METHOD_RESULT native_pop_arr EXT_METHOD_PARAMS {
if(!OBJ_LEN(argv[0])) {
VALUE e;
e = make_normal_type_instance(vm->EmptyArrayFail);
set_normal_type_instance_field(e, make_string("message"), make_string("pop(arr:Arr) failed because of empty array"));
THROW_EXCEPTION_INSTANCE(e);
}
*result = ARRAY_ITEMS(argv[0])[OBJ_LEN(argv[0])-1];
OBJ_LEN(argv[0])--;
return METHOD_OK;
}
METHOD_RESULT native_shift_arr EXT_METHOD_PARAMS {
if(!OBJ_LEN(argv[0])) {
VALUE e;
e = make_normal_type_instance(vm->EmptyArrayFail);
set_normal_type_instance_field(e, make_string("message"), make_string("shift(arr:Arr) failed because of empty array"));
THROW_EXCEPTION_INSTANCE(e);
}
METHOD_RETURN(array_shift(argv[0]));
}
METHOD_RESULT native_shift_arr_any METHOD_PARAMS {
if(!OBJ_LEN(argv[0])) {
METHOD_RETURN(argv[1]);
}
METHOD_RETURN(array_shift(argv[0]));
}
METHOD_RESULT native_index_get_arr_int EXT_METHOD_PARAMS {
int idx, len;
(void) ctx;
len = OBJ_LEN(argv[0]);
idx = GET_INT(argv[1]);
if((idx < 0) || (idx >= len)) {
VALUE e;
e = make_normal_type_instance(vm->IndexNotFound);
set_normal_type_instance_field(e, make_string("container"), argv[0]);
set_normal_type_instance_field(e, make_string("key"), argv[1]);
THROW_EXCEPTION_INSTANCE(e);
}
*result = ARRAY_ITEMS(argv[0])[idx];
return METHOD_OK;
}
METHOD_RESULT native_index_set_arr_int_any EXT_METHOD_PARAMS {
int idx, len;
(void) ctx;
len = OBJ_LEN(argv[0]);
idx = GET_INT(argv[1]);
if((idx < 0) || (idx >= len)) {
VALUE e;
e = make_normal_type_instance(vm->IndexNotFound);
set_normal_type_instance_field(e, make_string("container"), argv[0]);
set_normal_type_instance_field(e, make_string("key"), argv[1]);
THROW_EXCEPTION_INSTANCE(e);
}
ARRAY_ITEMS(argv[0])[idx] = argv[2];
METHOD_RETURN(argv[2]);
}
METHOD_RESULT native_Str_int METHOD_PARAMS {
char s[MAX_INT_TO_STR_LEN];
size_t len;
len = snprintf(s, sizeof(s), "%" PRIiPTR, GET_INT(argv[0]));
if(len >= sizeof(s)) {
THROW_EXCEPTION("ResultTooLarge");
}
*result = make_string(s);
return METHOD_OK;
}
// XXX: Not sure about this whole formatting thing
METHOD_RESULT native_Str_real METHOD_PARAMS {
char s[MAX_REAL_TO_STR_LEN];
char *cut_after=NULL, *p;
size_t len;
len = snprintf(s, sizeof(s), NGS_REAL_FMT, GET_REAL(argv[0]));
if(len >= sizeof(s)) {
THROW_EXCEPTION("ResultTooLarge");
}
p=s;
while(1) {
if(*p==0) {
if(cut_after) {
*(cut_after+1) = '\0';
}
break;
}
if(*p!='0') {
cut_after=p;
}
if(*p=='.') {
cut_after++;
}
p++;
}
*result = make_string(s);
return METHOD_OK;
}
METHOD_RESULT native_Real_int METHOD_PARAMS {
METHOD_RETURN(make_real((NGS_REAL) GET_INT(argv[0])));
}
METHOD_RESULT native_round_real METHOD_PARAMS { METHOD_RETURN(make_real((NGS_REAL) round(GET_REAL(argv[0])))); }
METHOD_RESULT native_trunc_real METHOD_PARAMS { METHOD_RETURN(make_real((NGS_REAL) trunc(GET_REAL(argv[0])))); }
METHOD_RESULT native_floor_real METHOD_PARAMS { METHOD_RETURN(make_real((NGS_REAL) floor(GET_REAL(argv[0])))); }
METHOD_RESULT native_ceil_real METHOD_PARAMS { METHOD_RETURN(make_real((NGS_REAL) ceil(GET_REAL(argv[0])))); }
METHOD_RESULT native_c_pow_real_real EXT_METHOD_PARAMS {
VALUE ret;
int status = 0;
NGS_REAL t = pow(GET_REAL(argv[0]), GET_REAL(argv[1]));
ret = make_array(2);
if(t == NGS_REAL_HUGE_VAL) {
status = 1;
} else if(t == -NGS_REAL_HUGE_VAL) {
status = -1;
}
ARRAY_ITEMS(ret)[0] = MAKE_INT(status);
ARRAY_ITEMS(ret)[1] = make_real((NGS_REAL) t);
METHOD_RETURN(ret);
// ret = make_array_with_values(2, (VALUES *){MAKE_BOOL(ret != HUGE_VAL && ret != -HUGE_VAL), ((NGS_REAL) ret)});
}
// TODO: Handle precision issue around INT_MAX input. Probably around INT_MIN too.
// On my system INT_MAX is 2305843009213693951 and when converted to NGS_REAL becomes 2305843009213693952.0
// "r > (NGS_REAL) NGS_INT_MAX" is false for the numbers below so the if is not entered.
// "Int(2305843009213693952.0)" is -2305843009213693952
// "Int(2305843009213694208.0)" is -2305843009213693952
// Also:
// "Real(INT_MAX) + 1.0 > Real(INT_MAX)" is false
// "Int(Real(INT_MAX))" is -2305843009213693952
// "Int(Real(INT_MAX)) == INT_MIN" is true
METHOD_RESULT native_Int_real EXT_METHOD_PARAMS {
NGS_REAL r = GET_REAL(argv[0]);
// printf("%d\n", 2305843009213694208.0 > 2305843009213693952.0); // 0
if((r > (NGS_REAL) NGS_INT_MAX) || (r < (NGS_REAL) NGS_INT_MIN)) {
VALUE e;
e = make_normal_type_instance(vm->InvalidArgument);
set_normal_type_instance_field(e, make_string("message"), make_string("Could not convert given float to integer: out of supported range."));
set_normal_type_instance_field(e, make_string("value"), argv[0]);
set_normal_type_instance_field(e, make_string("min"), make_real((NGS_REAL) NGS_INT_MIN));
set_normal_type_instance_field(e, make_string("max"), make_real((NGS_REAL) NGS_INT_MAX));
// printf("%ld %f\n", NGS_INT_MAX, (NGS_REAL) (NGS_INT_MAX));
THROW_EXCEPTION_INSTANCE(e);
}
METHOD_RETURN(MAKE_INT((intptr_t) r));
}
METHOD_RESULT native_Int_str_int EXT_METHOD_PARAMS {
char *nptr, *endptr;
long long r;
nptr = obj_to_cstring(argv[0]);
// https://en.cppreference.com/w/c/string/byte/strtol
r = strtoll(nptr, &endptr, GET_INT(argv[1]));
if (
nptr == endptr ||
endptr - nptr < OBJ_LEN(argv[0]) ||
((r == LONG_MAX || r == LONG_MIN || r == LLONG_MAX || r == LLONG_MIN) && errno == ERANGE)) {
VALUE e;
e = make_normal_type_instance(vm->InvalidArgument);
set_normal_type_instance_field(e, make_string("message"), make_string("Could not convert given string to integer."));
THROW_EXCEPTION_INSTANCE(e);
}
METHOD_RETURN(MAKE_INT(r));
}
METHOD_RESULT native_is_any_type EXT_METHOD_PARAMS {
(void) ctx;
SET_BOOL(*result, obj_is_of_type(vm, argv[0], argv[1]));
return METHOD_OK;
}
METHOD_RESULT native_Bool_any METHOD_PARAMS {
// printf("Bool()\n");
// dump(argv[0]);
if(IS_BOOL(argv[0])) METHOD_RETURN(argv[0])
if(IS_INT(argv[0])) METHOD_RETURN(MAKE_BOOL(GET_INT(argv[0])))
if(IS_STRING(argv[0]) || IS_ARRAY(argv[0]) || IS_HASH(argv[0])) METHOD_RETURN(MAKE_BOOL(OBJ_LEN(argv[0])));
if(IS_NULL(argv[0])) METHOD_RETURN(MAKE_BOOL(0));
return METHOD_ARGS_MISMATCH;
}
METHOD_RESULT native_in_any_hash METHOD_PARAMS {
SET_BOOL(*result, get_hash_key(argv[1], argv[0]));
return METHOD_OK;
}
METHOD_RESULT native_hash_any METHOD_PARAMS {
// METHOD_RETURN(MAKE_INT(hash(argv[0])));
SET_INT(*result, hash(argv[0]));
return METHOD_OK;
}
METHOD_RESULT native_keys_hash METHOD_PARAMS {
size_t i;
HASH_OBJECT_ENTRY *e;
*result = make_array(OBJ_LEN(argv[0]));
for(e=HASH_HEAD(argv[0]), i=0; e; e=e->insertion_order_next, i++) {
*(VALUE *)(ARRAY_ITEMS(*result)+i) = e->key;
}
return METHOD_OK;
}
METHOD_RESULT native_values_hash METHOD_PARAMS {
size_t i;
HASH_OBJECT_ENTRY *e;
*result = make_array(OBJ_LEN(argv[0]));
for(e=HASH_HEAD(argv[0]), i=0; e; e=e->insertion_order_next, i++) {
*(VALUE *)(ARRAY_ITEMS(*result)+i) = e->val;
}
return METHOD_OK;
}
METHOD_RESULT native_update_hash_hash METHOD_PARAMS { update_hash(argv[0], argv[1]); METHOD_RETURN(argv[0]); }
METHOD_RESULT native_len METHOD_PARAMS {
*result = MAKE_INT(OBJ_LEN(argv[0]));
return METHOD_OK;
}
METHOD_RESULT native_index_get_hash_any_any METHOD_PARAMS {
HASH_OBJECT_ENTRY *e;
e = get_hash_key(argv[0], argv[1]);
if(!e) {
METHOD_RETURN(argv[2]);
}
*result = e->val;
return METHOD_OK;
}
METHOD_RESULT native_index_get_hash_any EXT_METHOD_PARAMS {
HASH_OBJECT_ENTRY *e;
(void) ctx;
e = get_hash_key(argv[0], argv[1]);
if(!e) {
VALUE exc;
exc = make_normal_type_instance(vm->KeyNotFound);
set_normal_type_instance_field(exc, make_string("container"), argv[0]);
set_normal_type_instance_field(exc, make_string("key"), argv[1]);
THROW_EXCEPTION_INSTANCE(exc);
}
METHOD_RETURN(e->val)
}
METHOD_RESULT native_index_set_hash_any_any METHOD_PARAMS { set_hash_key(argv[0], argv[1], argv[2]); METHOD_RETURN(argv[2]); }
METHOD_RESULT native_index_del_hash_any EXT_METHOD_PARAMS {
if(!del_hash_key(argv[0], argv[1])) {
VALUE exc;
exc = make_normal_type_instance(vm->KeyNotFound);
set_normal_type_instance_field(exc, make_string("container"), argv[0]);
set_normal_type_instance_field(exc, make_string("key"), argv[1]);
THROW_EXCEPTION_INSTANCE(exc);
}
METHOD_RETURN(argv[0])
}
// TODO: factor out common in native_ll_hash_{head,tail}
METHOD_RESULT native_ll_hash_head EXT_METHOD_PARAMS {
VALUE ret;
HASH_OBJECT_ENTRY *e = HASH_HEAD(argv[0]);
if(!e) {
METHOD_RETURN(MAKE_NULL);
};
HASH_ENTRY_OBJECT *heo;
heo = NGS_MALLOC(sizeof(*heo));
assert(heo);
heo->entry = e;
SET_OBJ(ret, heo);
OBJ_TYPE_NUM(ret) = T_LL_HASH_ENTRY;
METHOD_RETURN(ret);
}
METHOD_RESULT native_ll_hash_tail EXT_METHOD_PARAMS {
VALUE ret;
HASH_OBJECT_ENTRY *e = HASH_TAIL(argv[0]);
if(!e) {
METHOD_RETURN(MAKE_NULL);
};
HASH_ENTRY_OBJECT *heo;
heo = NGS_MALLOC(sizeof(*heo));
assert(heo);
heo->entry = e;
SET_OBJ(ret, heo);
OBJ_TYPE_NUM(ret) = T_LL_HASH_ENTRY;
METHOD_RETURN(ret);
}
METHOD_RESULT native_ll_hash_entry_key EXT_METHOD_PARAMS {
HASH_OBJECT_ENTRY *e = ((HASH_ENTRY_OBJECT *)(argv[0].ptr))->entry;
METHOD_RETURN(e->key);
}
METHOD_RESULT native_ll_hash_entry_val EXT_METHOD_PARAMS {
HASH_OBJECT_ENTRY *e = ((HASH_ENTRY_OBJECT *)(argv[0].ptr))->entry;
METHOD_RETURN(e->val);
}
METHOD_RESULT native_ll_hash_entry_next EXT_METHOD_PARAMS {
HASH_OBJECT_ENTRY *e = ((HASH_ENTRY_OBJECT *)(argv[0].ptr))->entry;
if(!e->insertion_order_next) {
METHOD_RETURN(MAKE_NULL);
};
VALUE ret;
HASH_ENTRY_OBJECT *heo;
heo = NGS_MALLOC(sizeof(*heo));
assert(heo);
heo->entry = e->insertion_order_next;
SET_OBJ(ret, heo);
OBJ_TYPE_NUM(ret) = T_LL_HASH_ENTRY;
METHOD_RETURN(ret);
}
METHOD_RESULT native_Hash_nti METHOD_PARAMS {
VALUE ut, item;
HASH_OBJECT_ENTRY *e;
ut = NORMAL_TYPE_INSTANCE_TYPE(argv[0]);
// TODO: round to nearest power of 2?
*result = make_hash(OBJ_LEN(NGS_TYPE_FIELDS(ut)));
for(e=HASH_HEAD(NGS_TYPE_FIELDS(ut)); e; e=e->insertion_order_next) {
if(OBJ_LEN(NORMAL_TYPE_INSTANCE_FIELDS(argv[0])) <= (size_t)GET_INT(e->val)) {
continue;
}
item = ARRAY_ITEMS(NORMAL_TYPE_INSTANCE_FIELDS(argv[0]))[(size_t)GET_INT(e->val)];
if(!IS_UNDEF(item)) {
set_hash_key(*result, e->key, item);
}
}
return METHOD_OK;
}
METHOD_RESULT native_Namespace METHOD_PARAMS {
*result = make_namespace(0);
return METHOD_OK;
};
// TODO: locking for dlerror?
METHOD_RESULT native_c_dlopen_str_int EXT_METHOD_PARAMS {
VALUE v;
CLIB_OBJECT *o;
void *out;
out = dlopen(obj_to_cstring(argv[0]), GET_INT(argv[1]));
if(!out) {
VALUE e;
e = make_normal_type_instance(vm->DlopenFail);
// XXX: Could not find whether we should free the (char *) returned by dlerror()
set_normal_type_instance_field(e, make_string("message"), make_string(dlerror()));
set_normal_type_instance_field(e, make_string("filename"), argv[0]);
THROW_EXCEPTION_INSTANCE(e);
}
o = NGS_MALLOC(sizeof(*o));
assert(o);
o->base.type.num = T_CLIB;
o->base.val.ptr = out;
o->name = argv[0];
SET_OBJ(v, o);
METHOD_RETURN(v);
}
METHOD_RESULT native_in_str_clib METHOD_PARAMS {
METHOD_RETURN(MAKE_BOOL(dlsym(OBJ_DATA_PTR(argv[1]), obj_to_cstring(argv[0]))));
}
METHOD_RESULT native_index_get_clib_str EXT_METHOD_PARAMS {
VALUE v;
CSYM_OBJECT *o;
o = NGS_MALLOC(sizeof(*o));
assert(o);
o->base.type.num = T_CSYM;
o->base.val.ptr = dlsym(OBJ_DATA_PTR(argv[0]), obj_to_cstring(argv[1]));
if(!o->base.val.ptr) {
VALUE e;
e = make_normal_type_instance(vm->Error);
set_normal_type_instance_field(e, make_string("message"), make_string("Failed to dlsym()"));
set_normal_type_instance_field(e, make_string("handle"), argv[0]);
set_normal_type_instance_field(e, make_string("symbol"), argv[1]);
THROW_EXCEPTION_INSTANCE(e);
}
o->lib = argv[0];
o->name = argv[1];
SET_OBJ(v, o);
METHOD_RETURN(v);
}
// OPEN(2)
// TODO: support more flags
// TODO: support providing mode instead of hard-coded 0666
METHOD_RESULT native_c_open_str_str METHOD_PARAMS {
const char *pathname = obj_to_cstring(argv[0]);
const char *flags_str = obj_to_cstring(argv[1]);
int flags = 0;
if(!flags && !strcmp(flags_str, "r")) { flags = O_RDONLY; }
if(!flags && !strcmp(flags_str, "w")) { flags = O_WRONLY | O_CREAT | O_TRUNC; }
if(!flags && !strcmp(flags_str, "a")) { flags = O_WRONLY | O_CREAT | O_APPEND; }
// if(!flags && !strcmp(flags_str, "rw")) { flags = O_RDWR; }
SET_INT(*result, open(pathname, flags, 0666)); // Mode same as in bash
return METHOD_OK;
}
METHOD_RESULT native_c_realpath_str METHOD_PARAMS {
const char *path = obj_to_cstring(argv[0]);
char resolved_path[PATH_MAX + 1];
resolved_path[0] = '\0';
if(realpath(path, resolved_path)) {
*result = make_string(resolved_path);
} else {
*result = MAKE_NULL;
}
METHOD_RETURN(*result);
}
// READ(2)
// TODO: error handling support
METHOD_RESULT native_c_read_int_int METHOD_PARAMS {
// Params: fd, count
char *buf;
size_t count = GET_INT(argv[1]);
ssize_t len;
assert(count <= SSIZE_MAX);
buf = NGS_MALLOC_ATOMIC(count);
assert(buf);
len = read(GET_INT(argv[0]), buf, count);
*result = make_array(2);
ARRAY_ITEMS(*result)[0] = MAKE_INT(len);
if(len >= 0) {
ARRAY_ITEMS(*result)[1] = make_string_of_len(buf, len);
} else {
ARRAY_ITEMS(*result)[1] = (VALUE){.num=V_NULL};
}
METHOD_RETURN(*result);
}
// WRITE(2)
// TODO: error handling support
METHOD_RESULT native_c_write_int_str METHOD_PARAMS { METHOD_RETURN(MAKE_INT(write(GET_INT(argv[0]), OBJ_DATA_PTR(argv[1]), OBJ_LEN(argv[1])))); }
METHOD_RESULT native_c_lseek_int_int_str EXT_METHOD_PARAMS {
off_t offset;
const char *whence_str = obj_to_cstring(argv[2]);
int whence = 0;
(void) ctx;
if(!strcmp(whence_str, "set")) {
whence = SEEK_SET;
} else {
if(!strcmp(whence_str, "cur")) {
whence = SEEK_CUR;
} else {
if(!strcmp(whence_str, "end")) {
whence = SEEK_END;
} else {
VALUE exc;
exc = make_normal_type_instance(vm->InvalidArgument);
set_normal_type_instance_field(exc, make_string("which"), make_string("Third parameter to c_lseek(), 'whence'"));
set_normal_type_instance_field(exc, make_string("given"), argv[2]);
// TODO: Array of expected values maybe?
set_normal_type_instance_field(exc, make_string("expected"), make_string("One of: 'set', 'cur', 'end'"));
THROW_EXCEPTION_INSTANCE(exc);
}
}
}
offset = lseek(GET_INT(argv[0]), GET_INT(argv[1]), whence);
METHOD_RETURN(MAKE_INT(offset));
}
METHOD_RESULT native_c_isatty METHOD_PARAMS { METHOD_RETURN(MAKE_INT(isatty(GET_INT(argv[0])))); }
METHOD_RESULT native_c_close_int METHOD_PARAMS { METHOD_RETURN(MAKE_INT(close(GET_INT(argv[0])))); }
METHOD_RESULT native_c_exit_int METHOD_PARAMS { (void)result; exit(GET_INT(argv[0])); }
METHOD_RESULT native_eq_str_str METHOD_PARAMS {
size_t len;
if(OBJ_LEN(argv[0]) != OBJ_LEN(argv[1])) { METHOD_RETURN(MAKE_BOOL(0)); }
if(OBJ_DATA_PTR(argv[0]) == OBJ_DATA_PTR(argv[1])) { METHOD_RETURN(MAKE_BOOL(1)); }
len = OBJ_LEN(argv[0]);
METHOD_RETURN(MAKE_BOOL(!memcmp(OBJ_DATA_PTR(argv[0]), OBJ_DATA_PTR(argv[1]), len)));
}
METHOD_RESULT native_pos_str_str_int METHOD_PARAMS {
void *p;
int start = GET_INT(argv[2]);
p = ngs_memmem((char *)OBJ_DATA_PTR(argv[0])+start, OBJ_LEN(argv[0])-start, OBJ_DATA_PTR(argv[1]), OBJ_LEN(argv[1]));
if(p) {
METHOD_RETURN(MAKE_INT(p - OBJ_DATA_PTR(argv[0])));
}
METHOD_RETURN(MAKE_NULL);
}
// TODO: make "start" and "end" size_t to simplify the code
// TODO: better than METHOD_ARGS_MISMATCH on include_start != true and include_end != false
#define NATIVE_RANGE_INDEX_SETUP \
if(OBJ_LEN(NORMAL_TYPE_INSTANCE_FIELDS(argv[1])) < 5) return METHOD_ARGS_MISMATCH; \
include_start = ARRAY_ITEMS(NORMAL_TYPE_INSTANCE_FIELDS(argv[1]))[RANGE_FIELD_INCLUDE_START]; \
if(!IS_BOOL(include_start)) return METHOD_ARGS_MISMATCH; \
if(!IS_TRUE(include_start)) return METHOD_ARGS_MISMATCH; \
include_end = ARRAY_ITEMS(NORMAL_TYPE_INSTANCE_FIELDS(argv[1]))[RANGE_FIELD_INCLUDE_END]; \
if(!IS_BOOL(include_end)) return METHOD_ARGS_MISMATCH; \
if(!IS_FALSE(include_end)) return METHOD_ARGS_MISMATCH; \
start = ARRAY_ITEMS(NORMAL_TYPE_INSTANCE_FIELDS(argv[1]))[RANGE_FIELD_START]; \
if(!IS_INT(start)) return METHOD_ARGS_MISMATCH; \
if(GET_INT(start) < 0) { \
exc = make_normal_type_instance(vm->IndexNotFound); \
set_normal_type_instance_field(exc, make_string("message"), make_string("Negative range start")); \
THROW_EXCEPTION_INSTANCE(exc); \
} \
if(((size_t) GET_INT(start)) > OBJ_LEN(argv[0])) { \
exc = make_normal_type_instance(vm->IndexNotFound); \
set_normal_type_instance_field(exc, make_string("message"), make_string("NumRange starts after string/array end")); \
THROW_EXCEPTION_INSTANCE(exc); \
} \
end = ARRAY_ITEMS(NORMAL_TYPE_INSTANCE_FIELDS(argv[1]))[RANGE_FIELD_END]; \
if(IS_NULL(end)) { \
end = MAKE_INT(OBJ_LEN(argv[0])); \
} \
if(!IS_INT(end)) return METHOD_ARGS_MISMATCH; \
if(GET_INT(end) < GET_INT(start)) { \
exc = make_normal_type_instance(vm->InvalidArgument); \
set_normal_type_instance_field(exc, make_string("message"), make_string("NumRange end smaller than range start when calling [](s:Str, r:NumRange)")); \
THROW_EXCEPTION_INSTANCE(exc); \
} \
len = GET_INT(end) - GET_INT(start); \
if(GET_INT(start) + len > OBJ_LEN(argv[0])) { \
exc = make_normal_type_instance(vm->IndexNotFound); \
set_normal_type_instance_field(exc, make_string("message"), make_string("NumRange ends after string end")); \
THROW_EXCEPTION_INSTANCE(exc); \
}
METHOD_RESULT native_index_get_str_range EXT_METHOD_PARAMS {
size_t len;
VALUE start, end, include_start, include_end, exc;
(void) ctx;
NATIVE_RANGE_INDEX_SETUP;
*result = make_string_of_len(NULL, len);
memcpy(OBJ_DATA_PTR(*result), OBJ_DATA_PTR(argv[0]) + GET_INT(start), len);
return METHOD_OK;
}
METHOD_RESULT native_index_set_str_range_str EXT_METHOD_PARAMS {
size_t len, new_total_len;
VALUE start, end, include_start, include_end, exc;
char *old_data;
(void) ctx;
NATIVE_RANGE_INDEX_SETUP;
new_total_len = GET_INT(start) + OBJ_LEN(argv[2]) + (OBJ_LEN(argv[0]) - GET_INT(end));
old_data = OBJ_DATA_PTR(argv[0]);
OBJ_DATA_PTR(argv[0]) = NGS_MALLOC_ATOMIC(new_total_len);
memcpy(OBJ_DATA_PTR(argv[0]), old_data, GET_INT(start));
if(OBJ_LEN(argv[2])) {
memcpy(OBJ_DATA_PTR(argv[0]) + GET_INT(start), OBJ_DATA_PTR(argv[2]), OBJ_LEN(argv[2]));
}
memcpy(OBJ_DATA_PTR(argv[0]) + GET_INT(start) + OBJ_LEN(argv[2]), old_data + GET_INT(end), OBJ_LEN(argv[0]) - GET_INT(end));
OBJ_LEN(argv[0]) = new_total_len;
METHOD_RETURN(argv[2]);
}
// TODO: maybe use vlo->item_size and unify Str and Arr methods
METHOD_RESULT native_index_get_arr_range EXT_METHOD_PARAMS {
size_t len;
VALUE start, end, include_start, include_end, exc;
(void) ctx;
NATIVE_RANGE_INDEX_SETUP;
*result = make_array(len);
memcpy(OBJ_DATA_PTR(*result), &ARRAY_ITEMS(argv[0])[GET_INT(start)], len*sizeof(VALUE));
return METHOD_OK;
}
// TODO: maybe use vlo->item_size and unify Str and Arr methods
METHOD_RESULT native_index_set_arr_range_arr EXT_METHOD_PARAMS {
size_t len, new_total_len;
VALUE start, end, include_start, include_end, exc;
char *old_data;
(void) ctx;
NATIVE_RANGE_INDEX_SETUP;
new_total_len = GET_INT(start) + OBJ_LEN(argv[2]) + (OBJ_LEN(argv[0]) - GET_INT(end));
old_data = OBJ_DATA_PTR(argv[0]);
OBJ_DATA_PTR(argv[0]) = NGS_MALLOC(new_total_len * sizeof(VALUE));
memcpy(&ARRAY_ITEMS(argv[0])[0], old_data, GET_INT(start) * sizeof(VALUE));
if(OBJ_LEN(argv[2])) {
memcpy(&ARRAY_ITEMS(argv[0])[GET_INT(start)], OBJ_DATA_PTR(argv[2]), OBJ_LEN(argv[2]) * sizeof(VALUE));
}
memcpy(&ARRAY_ITEMS(argv[0])[GET_INT(start) + OBJ_LEN(argv[2])], old_data + GET_INT(end) * sizeof(VALUE), (OBJ_LEN(argv[0]) - GET_INT(end)) * sizeof(VALUE));
OBJ_LEN(argv[0]) = new_total_len;
METHOD_RETURN(argv[2]);
}
METHOD_RESULT native_eq_bool_bool METHOD_PARAMS { METHOD_RETURN(MAKE_BOOL(argv[0].num == argv[1].num)); }
METHOD_RESULT native_not_bool METHOD_PARAMS { METHOD_RETURN(MAKE_BOOL(argv[0].num == V_FALSE)); }
// XXX: glibc specific fmemopen()
METHOD_RESULT native_compile_str_str EXT_METHOD_PARAMS {
ast_node *tree = NULL;
yycontext yyctx;
int parse_ok;
(void) ctx;
memset(&yyctx, 0, sizeof(yycontext));
yyctx.fail_pos = -1;
yyctx.fail_rule = "(unknown)";
yyctx.lines = 0;
yyctx.lines_postions[0] = 0;
// printf("PT 1 %p\n", OBJ_DATA_PTR(argv[0]));
if(OBJ_LEN(argv[0]) == 0) {
VALUE exc;
exc = make_normal_type_instance(vm->CompileFail);
set_normal_type_instance_field(exc, make_string("message"), make_string("Empty string was passed as input to compile(). Trying to run an empty file?"));
THROW_EXCEPTION_INSTANCE(exc);
}
yyctx.input_file = fmemopen(OBJ_DATA_PTR(argv[0]), OBJ_LEN(argv[0]), "r");
parse_ok = yyparse(&yyctx);
if(!parse_ok) {
VALUE exc;
char *err = NGS_MALLOC_ATOMIC(1024);
exc = make_normal_type_instance(vm->CompileFail);
set_normal_type_instance_field(exc, make_string("given"), argv[0]);
int *pos_line_col = NGS_MALLOC_ATOMIC(sizeof(int) * 2);
position_to_line_col(&yyctx, yyctx.fail_pos, pos_line_col);
VALUE pos = make_hash(4);
set_hash_key(pos, make_string("file"), argv[1]);
set_hash_key(pos, make_string("absolute"), MAKE_INT(yyctx.fail_pos));
set_hash_key(pos, make_string("line"), MAKE_INT(pos_line_col[0]));
set_hash_key(pos, make_string("column"), MAKE_INT(pos_line_col[1]));
set_normal_type_instance_field(exc, make_string("position"), pos);
set_normal_type_instance_field(exc, make_string("rule"), make_string(yyctx.fail_rule));
THROW_EXCEPTION_INSTANCE(exc);
}
tree = yyctx.__;
IF_DEBUG(COMPILER, print_ast(tree, 0);)
yyrelease(&yyctx);
COMPILATION_RESULT *r = compile(tree, obj_to_cstring(argv[1]));
VALUE ret = make_string_of_len(r->bytecode, r->len);
OBJ_META(ret) = make_hash(1);
set_hash_key(OBJ_META(ret), make_string("warnings"), r->warnings);
METHOD_RETURN(ret);
}
METHOD_RESULT native_load_str_str EXT_METHOD_PARAMS {
size_t ip;
(void) ctx;
ip = vm_load_bytecode(vm, OBJ_DATA_PTR(argv[0]));
METHOD_RETURN(make_closure_obj(ip, 0, 0, 0, 0, 0, NULL, NULL));
}
METHOD_RESULT native_decode_json_str EXT_METHOD_PARAMS {
METHOD_RESULT mr;
(void) ctx;
mr = decode_json(vm, argv[0], result);
if(mr == METHOD_EXCEPTION) {
set_normal_type_instance_field(*result, make_string("backtrace"), make_backtrace(vm, ctx));
}
return mr;
}
METHOD_RESULT native_encode_json_obj EXT_METHOD_PARAMS {
METHOD_RESULT mr;
(void) ctx;
mr = encode_json(argv[0], result);
if(mr == METHOD_EXCEPTION) {
VALUE exc;
// TODO: more specific error
exc = make_normal_type_instance(vm->Error);
// could be big... // set_normal_type_instance_field(exc, make_string("data"), argv[0]);
set_normal_type_instance_field(exc, make_string("message"), *result);
set_normal_type_instance_field(exc, make_string("backtrace"), make_backtrace(vm, ctx));
*result = exc;
}
return mr;
}
METHOD_RESULT native_backtrace EXT_METHOD_PARAMS { (void) argv; METHOD_RETURN(make_backtrace(vm, ctx)); }
METHOD_RESULT native_resolve_instruction_pointer EXT_METHOD_PARAMS { (void) ctx; METHOD_RETURN(resolve_instruction_pointer(vm, GET_INT(argv[0]))); }
METHOD_RESULT native_globals EXT_METHOD_PARAMS {
VALUE ret;
size_t i;
(void) ctx;
(void) argv;
ret = make_hash(256);
for(i=0; i<vm->globals_len; i++) {
if(IS_NOT_UNDEF(vm->globals[i])) {
set_hash_key(ret, make_string(vm->globals_names[i]), vm->globals[i]);
}
}
METHOD_RETURN(ret);
}