forked from liexusong/mjs3
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathelk.c
2349 lines (2156 loc) · 77.2 KB
/
elk.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) 2013-2019 Cesanta Software Limited
// All rights reserved
//
// This software is dual-licensed: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation. For the terms of this
// license, see <http://www.gnu.org/licenses/>.
//
// You are free to use this software under the terms of the GNU General
// Public License, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// Alternatively, you can license this software under a commercial
// license, please contact us at https://mdash.net/home/company.html
#ifndef JS_DATA_STACK_SIZE
#define JS_DATA_STACK_SIZE 10
#endif
#ifndef JS_CALL_STACK_SIZE
#define JS_CALL_STACK_SIZE 10
#endif
#ifndef JS_STRING_POOL_SIZE
#define JS_STRING_POOL_SIZE 256
#endif
#ifndef JS_OBJ_POOL_SIZE
#define JS_OBJ_POOL_SIZE 20
#endif
#ifndef JS_PROP_POOL_SIZE
#define JS_PROP_POOL_SIZE 30
#endif
#ifndef JS_ERROR_MESSAGE_SIZE
#define JS_ERROR_MESSAGE_SIZE 40
#endif
#ifndef JS_H
#define JS_H
#if defined(__cplusplus)
extern "C" {
#endif
#if !defined(_MSC_VER) || _MSC_VER >= 1700
#include <stdbool.h>
#include <stdint.h>
#else
typedef int bool;
enum { false = 0, true = 1 };
typedef long intptr_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
typedef unsigned int uint32_t;
typedef unsigned short uint16_t;
typedef unsigned char uint8_t;
#define vsnprintf _vsnprintf
#define snprintf _snprintf
#define _STRINGIFY(x) #x
#define STRINGIFY(x) _STRINGIFY(x)
#define __func__ __FILE__ ":" STRINGIFY(__LINE__)
#pragma warning(disable : 4127)
#pragma warning(disable : 4702)
#endif
typedef uint32_t jstok_t; // JS token
typedef uint32_t jsval_t; // JS value placeholder
typedef uint16_t jslen_t; // String length placeholder
typedef void (*cfn_t)(void); // Native C function, for exporting to JS
typedef uint16_t ind_t;
#define INVALID_INDEX ((ind_t) ~0)
struct elk *js_create(void); // Create instance
void js_destroy(struct elk *); // Destroy instance
jsval_t js_get_global(struct elk *); // Get global namespace object
jsval_t js_eval(struct elk *, const char *buf, int len); // Evaluate expr
jsval_t js_set(struct elk *, jsval_t obj, jsval_t k, jsval_t v); // Set attr
const char *js_stringify(struct elk *, jsval_t v); // Stringify
unsigned long js_size(void); // Get VM size
// Converting from C type to jsval_t
// Use JS_UNDEFINED, JS_NULL, JS_TRUE, JS_FALSE for other scalar types
jsval_t js_mk_obj(struct elk *);
jsval_t js_mk_str(struct elk *, const char *, int len);
jsval_t js_mk_num(float value);
jsval_t js_mk_js_func(struct elk *, const char *, int len);
// Converting from jsval_t to C/C++ types
float js_to_float(jsval_t v); // Unpack number
char *js_to_str(struct elk *, jsval_t, jslen_t *); // Unpack string
#define js_to_float(v) tof(v)
#define js_mk_str(vm, s, n) mk_str(vm, s, n)
#define js_mk_obj(vm) mk_obj(vm)
#define js_mk_num(v) tov(v)
#define js_get_global(vm) ((vm)->call_stack[0])
#define js_stringify(vm, v) tostr(vm, v)
#if defined(__cplusplus)
}
#endif
// VM tunables
///////////////////////////////// IMPLEMENTATION //////////////////////////
//
// 32bit floating-point number: 1 bit sign, 8 bits exponent, 23 bits mantissa
//
// 7f80 0000 = 01111111 10000000 00000000 00000000 = infinity
// ff80 0000 = 11111111 10000000 00000000 00000000 = −infinity
// ffc0 0001 = x1111111 11000000 00000000 00000001 = qNaN (on x86 and ARM)
// ff80 0001 = x1111111 10000000 00000000 00000001 = sNaN (on x86 and ARM)
//
// seeeeeee|emmmmmmm|mmmmmmmm|mmmmmmmm
// 11111111|1ttttvvv|vvvvvvvv|vvvvvvvv
// INF TYPE PAYLOAD
#define IS_FLOAT(v) (((v) &0xff800000) != 0xff800000)
#define MK_VAL(t, p) (0xff800000 | ((jsval_t)(t) << 19) | (p))
#define VAL_TYPE(v) ((js_type_t)(((v) >> 19) & 0x0f))
#define VAL_PAYLOAD(v) ((v) & ~0xfff80000)
#define JS_UNDEFINED MK_VAL(JS_TYPE_UNDEFINED, 0)
#define JS_ERROR MK_VAL(JS_TYPE_ERROR, 0)
#define JS_TRUE MK_VAL(JS_TYPE_TRUE, 0)
#define JS_FALSE MK_VAL(JS_TYPE_FALSE, 0)
#define JS_NULL MK_VAL(JS_TYPE_NULL, 0)
#include <assert.h>
#include <float.h>
#include <math.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// clang-format off
typedef enum {
JS_TYPE_UNDEFINED, JS_TYPE_NULL, JS_TYPE_TRUE, JS_TYPE_FALSE,
JS_TYPE_STRING, JS_TYPE_OBJECT, JS_TYPE_ARRAY, JS_TYPE_FUNCTION,
JS_TYPE_NUMBER, JS_TYPE_ERROR, JS_TYPE_C_FUNCTION, JS_TYPE_C_STRING,
} js_type_t;
// clang-format on
struct prop {
jsval_t key;
jsval_t val;
ind_t flags; // see JS_PROP_* below
ind_t next; // index of the next prop, or INVALID_INDEX if last one
};
#define PROP_ALLOCATED 1
struct obj {
ind_t flags; // see JS_OBJ_* defines below
ind_t props; // index of the first property, or INVALID_INDEX
};
#define OBJ_ALLOCATED 1
#define OBJ_CALL_ARGS 2 // This oject sits in the call stack, holds call args
struct cfunc {
const char *name; // function name
const char *decl; // Declaration of return values and arguments
cfn_t fn; // Pointer to C function
ind_t id; // Function ID
struct cfunc *next; // Next in a chain
};
struct elk {
char error_message[JS_ERROR_MESSAGE_SIZE];
jsval_t data_stack[JS_DATA_STACK_SIZE];
jsval_t call_stack[JS_CALL_STACK_SIZE];
ind_t sp; // Points to the top of the data stack
ind_t csp; // Points to the top of the call stack
ind_t stringbuf_len; // String pool current length
struct obj objs[JS_OBJ_POOL_SIZE]; // Objects pool
struct prop props[JS_PROP_POOL_SIZE]; // Props pool
uint8_t stringbuf[JS_STRING_POOL_SIZE]; // String pool
struct cfunc *cfuncs; // Registered FFI-ed functions
ind_t cfunc_count; // Number of FFI-ed functions
};
#define ARRSIZE(x) ((sizeof(x) / sizeof((x)[0])))
#ifdef JS_DEBUG
#define DEBUG(x) printf x
#else
#define DEBUG(x)
#endif
#define TRY(expr) \
do { \
res = expr; \
if (res == JS_ERROR) return res; \
} while (0)
//////////////////////////////////// HELPERS /////////////////////////////////
static jsval_t vm_err(struct elk *vm, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vsnprintf(vm->error_message, sizeof(vm->error_message), fmt, ap);
va_end(ap);
// DEBUG(( "%s: %s\n", __func__, vm->error_message));
return JS_ERROR;
}
union js_type_holder {
jsval_t v;
float f;
};
static js_type_t js_type(jsval_t v) {
return IS_FLOAT(v) ? JS_TYPE_NUMBER : VAL_TYPE(v);
}
static jsval_t tov(float f) {
union js_type_holder u;
u.f = f;
return u.v;
}
static float tof(jsval_t v) {
union js_type_holder u;
u.v = v;
return u.f;
}
static const char *js_typeof(jsval_t v) {
const char *names[] = {"undefined", "null", "true", "false",
"string", "object", "object", "function",
"number", "error", "cfunc", "cstring",
"?", "?", "?", "?"};
return names[js_type(v)];
}
static struct prop *firstprop(struct elk *vm, jsval_t obj);
static const char *_tos(struct elk *vm, jsval_t v, char *buf, int len) {
js_type_t t = js_type(v);
if (len <= 0 || buf == NULL) return buf;
switch (t) {
case JS_TYPE_NUMBER: {
double f = tof(v), iv;
if (modf(f, &iv) == 0) {
snprintf(buf, len, "%ld", (long) f);
} else {
snprintf(buf, len, "%g", f);
}
break;
}
case JS_TYPE_STRING:
case JS_TYPE_FUNCTION: {
jslen_t n;
const char *ptr = js_to_str(vm, v, &n);
snprintf(buf, len, "\"%.*s\"", n, ptr);
break;
}
case JS_TYPE_ERROR:
snprintf(buf, len, "ERROR: %s", vm->error_message);
break;
case JS_TYPE_OBJECT: {
int n = snprintf(buf, len, "{");
struct prop *prop = firstprop(vm, v);
while (prop != NULL) {
if (n > 1) n += snprintf(buf + n, len - n, ",");
n += strlen(_tos(vm, prop->key, buf + n, len - n));
n += snprintf(buf + n, len - n, ":");
n += strlen(_tos(vm, prop->val, buf + n, len - n));
prop = prop->next == INVALID_INDEX ? NULL : &vm->props[prop->next];
}
n += snprintf(buf + n, len - n, "}");
break;
}
default:
snprintf(buf, len, "%s", js_typeof(v));
break;
}
return buf;
}
const char *tostr(struct elk *vm, jsval_t v) {
static char buf[128];
return _tos(vm, v, buf, sizeof(buf));
}
#ifdef JS_DEBUG
static void vm_dump(const struct elk *vm) {
ind_t i;
printf("[VM] %8s[%4d]: ", "objs", (int) sizeof(vm->objs));
for (i = 0; i < ARRSIZE(vm->objs); i++) {
putchar(vm->objs[i].flags ? 'v' : '-');
}
putchar('\n');
printf("[VM] %8s[%4d]: ", "props", (int) sizeof(vm->props));
for (i = 0; i < ARRSIZE(vm->props); i++) {
putchar(vm->props[i].flags ? 'v' : '-');
}
putchar('\n');
printf("[VM] %8s: %d/%d\n", "strings", vm->stringbuf_len,
(int) sizeof(vm->stringbuf));
printf("[VM] sp %d, csp %d, sb %d\n", vm->sp, vm->csp, vm->stringbuf_len);
}
#else
#define vm_dump(x)
#endif
////////////////////////////////////// VM ////////////////////////////////////
static jsval_t *vm_top(struct elk *vm) {
return &vm->data_stack[vm->sp - 1];
}
#if 0
static void vm_swap(struct elk *vm) {
jsval_t *top = vm_top(vm), v = top[-1];
top[-1] = top[0];
top[0] = v;
}
#endif
static void abandon(struct elk *vm, jsval_t v) {
ind_t j;
js_type_t t = js_type(v);
DEBUG(("%s: %s\n", __func__, tostr(vm, v)));
if (t != JS_TYPE_OBJECT && t != JS_TYPE_STRING && t != JS_TYPE_FUNCTION)
return;
// If this value is still referenced, do nothing
for (j = 0; j < ARRSIZE(vm->props); j++) {
struct prop *prop = &vm->props[j];
if (prop->flags == 0) continue;
if (v == prop->key || v == prop->val) return;
}
// Look at the data stack too
for (j = 0; j < vm->sp; j++)
if (v == vm->data_stack[j]) return;
// vm_dump(vm);
if (t == JS_TYPE_OBJECT) {
ind_t i, obj_index = (ind_t) VAL_PAYLOAD(v);
struct obj *o = &vm->objs[obj_index];
o->flags = 0; // Mark object free
i = o->props;
while (i != INVALID_INDEX) { // Deallocate obj's properties too
struct prop *prop = &vm->props[i];
prop->flags = 0; // Mark property free
assert(js_type(prop->key) == JS_TYPE_STRING);
abandon(vm, prop->key);
abandon(vm, prop->val);
i = prop->next; // Point to the next property
}
} else if (t == JS_TYPE_STRING || t == JS_TYPE_FUNCTION) {
ind_t k, j, i = (ind_t) VAL_PAYLOAD(v); // String begin
ind_t len = (ind_t)(vm->stringbuf[i] + 2); // String length
// printf("abandoning %d %d [%s]\n", (int) i, (int) len, tostr(vm, v));
// Ok, not referenced, deallocate a string
if (i + len == sizeof(vm->stringbuf) || i + len == vm->stringbuf_len) {
// printf("shrink [%s]\n", tostr(vm, v));
vm->stringbuf[i] = 0; // If we're the last string,
vm->stringbuf_len = i; // shrink the buf immediately
} else {
vm->stringbuf[i + len - 1] = 'x'; // Mark string as dead
// Relocate all live strings to the beginning of the buffer
// printf("--> RELOC, %hu %hu\n", vm->stringbuf_len, len);
memmove(&vm->stringbuf[i], &vm->stringbuf[i + len], len);
assert(vm->stringbuf_len >= len);
vm->stringbuf_len = (ind_t)(vm->stringbuf_len - len);
for (j = 0; j < ARRSIZE(vm->props); j++) {
struct prop *prop = &vm->props[j];
if (prop->flags != 0) continue;
k = (ind_t) VAL_PAYLOAD(prop->key);
if (k > i) prop->key = MK_VAL(JS_TYPE_STRING, k - len);
if (js_type(prop->val) == JS_TYPE_STRING) {
k = (ind_t) VAL_PAYLOAD(prop->val);
if (k > i) prop->key = MK_VAL(JS_TYPE_STRING, k - len);
}
}
}
// printf("sbuflen %d\n", (int) vm->stringbuf_len);
}
}
static jsval_t vm_push(struct elk *vm, jsval_t v) {
if (vm->sp < ARRSIZE(vm->data_stack)) {
DEBUG(("%s: %s\n", __func__, tostr(vm, v)));
vm->data_stack[vm->sp] = v;
vm->sp++;
return JS_TRUE;
} else {
return vm_err(vm, "stack overflow");
}
}
static jsval_t vm_drop(struct elk *vm) {
if (vm->sp > 0) {
DEBUG(("%s: %s\n", __func__, tostr(vm, *vm_top(vm))));
vm->sp--;
abandon(vm, vm->data_stack[vm->sp]);
return JS_TRUE;
} else {
return vm_err(vm, "stack underflow");
}
}
static jsval_t mk_str(struct elk *vm, const char *p, int n) {
jslen_t len = n < 0 ? (jslen_t) strlen(p) : (jslen_t) n;
// printf("%s [%.*s], %d\n", __func__, n, p, (int) vm->stringbuf_len);
if (len > 0xff) {
return vm_err(vm, "string is too long");
} else if ((size_t) len + 2 > sizeof(vm->stringbuf) - vm->stringbuf_len) {
return vm_err(vm, "string OOM");
} else {
jsval_t v = MK_VAL(JS_TYPE_STRING, vm->stringbuf_len);
vm->stringbuf[vm->stringbuf_len++] = (uint8_t)(len & 0xff); // save length
if (p) memmove(&vm->stringbuf[vm->stringbuf_len], p, len); // copy data
vm->stringbuf_len = (ind_t)(vm->stringbuf_len + len);
vm->stringbuf[vm->stringbuf_len++] = 0; // nul-terminate
return v;
}
}
char *js_to_str(struct elk *vm, jsval_t v, jslen_t *len) {
uint8_t *p = vm->stringbuf + VAL_PAYLOAD(v);
if (len != NULL) *len = p[0];
return (char *) p + 1;
}
static jsval_t js_concat(struct elk *vm, jsval_t v1, jsval_t v2) {
jsval_t v = JS_ERROR;
jslen_t n1, n2;
char *p1 = js_to_str(vm, v1, &n1), *p2 = js_to_str(vm, v2, &n2);
if ((v = mk_str(vm, NULL, n1 + n2)) != JS_ERROR) {
char *p = js_to_str(vm, v, NULL);
memmove(p, p1, n1);
memmove(p + n1, p2, n2);
}
return v;
}
#if 0
static jsval_t mk_cfunc(struct elk *vm, ind_t i) {
ind_t i;
for (i = 0; i < ARRSIZE(vm->cfuncs); i++) {
if (vm->cfuncs[i].fn != NULL) continue;
return MK_VAL(JS_TYPE_C_FUNCTION, i);
}
return vm_err(vm, "cfunc OOM");
}
#endif
static jsval_t mk_obj(struct elk *vm) {
ind_t i;
// Start iterating from 1, because object 0 is always a global object
for (i = 1; i < ARRSIZE(vm->objs); i++) {
if (vm->objs[i].flags != 0) continue;
vm->objs[i].flags = OBJ_ALLOCATED;
vm->objs[i].props = INVALID_INDEX;
return MK_VAL(JS_TYPE_OBJECT, i);
}
return vm_err(vm, "obj OOM");
}
static jsval_t mk_func(struct elk *vm, const char *code, int len) {
jsval_t v = mk_str(vm, code, len);
if (v != JS_ERROR) {
v &= ~((jsval_t) 0x0f << 19);
v |= (jsval_t) JS_TYPE_FUNCTION << 19;
}
return v;
}
static jsval_t create_scope(struct elk *vm) {
jsval_t scope;
if (vm->csp >= ARRSIZE(vm->call_stack) - 1) {
return vm_err(vm, "Call stack OOM");
}
if ((scope = mk_obj(vm)) == JS_ERROR) return JS_ERROR;
DEBUG(("%s\n", __func__));
vm->call_stack[vm->csp] = scope;
vm->csp++;
return scope;
}
static jsval_t delete_scope(struct elk *vm) {
if (vm->csp <= 0 || vm->csp >= ARRSIZE(vm->call_stack)) {
return vm_err(vm, "Corrupt call stack");
} else {
DEBUG(("%s\n", __func__));
vm->csp--;
abandon(vm, vm->call_stack[vm->csp]);
return JS_TRUE;
}
}
static struct prop *firstprop(struct elk *vm, jsval_t obj) {
ind_t obj_index = (ind_t) VAL_PAYLOAD(obj);
struct obj *o = &vm->objs[obj_index];
if (obj_index >= ARRSIZE(vm->objs)) return NULL;
return o->props == INVALID_INDEX ? NULL : &vm->props[o->props];
}
// Lookup property in a given object
static jsval_t *findprop(struct elk *vm, jsval_t obj, const char *ptr,
jslen_t len) {
struct prop *prop = firstprop(vm, obj);
while (prop != NULL) {
jslen_t n = 0;
char *key = js_to_str(vm, prop->key, &n);
if (n == len && memcmp(key, ptr, n) == 0) return &prop->val;
prop = prop->next == INVALID_INDEX ? NULL : &vm->props[prop->next];
}
return NULL;
}
// Lookup variable
static jsval_t *lookup(struct elk *vm, const char *ptr, jslen_t len) {
ind_t i;
for (i = vm->csp; i > 0; i--) {
jsval_t scope = vm->call_stack[i - 1];
jsval_t *prop = findprop(vm, scope, ptr, len);
// printf(" lookup scope %d %s [%.*s] %p\n", (int) i, tostr(vm, scope),
//(int) len, ptr, prop);
if (prop != NULL) return prop;
}
return NULL;
}
// Lookup variable and push its value on stack on success
static jsval_t lookup_and_push(struct elk *vm, const char *ptr, jslen_t len) {
jsval_t *vp = lookup(vm, ptr, len);
if (vp != NULL) return vm_push(vm, *vp);
return vm_err(vm, "[%.*s] undefined", len, ptr);
}
jsval_t js_set(struct elk *vm, jsval_t obj, jsval_t key, jsval_t val) {
if (js_type(obj) == JS_TYPE_OBJECT) {
jslen_t len;
const char *ptr = js_to_str(vm, key, &len);
struct prop *prop = firstprop(vm, obj);
while (prop != NULL) {
jslen_t n = 0;
char *key = js_to_str(vm, prop->key, &n);
if (n == len && memcmp(key, ptr, n) == 0) {
// The key already exists. Set the new value
jsval_t old = prop->val;
prop->val = val;
abandon(vm, old);
return JS_TRUE;
}
if (prop->next == INVALID_INDEX) break;
prop = &vm->props[prop->next];
}
ind_t i, obj_index = (ind_t) VAL_PAYLOAD(obj);
struct obj *o = &vm->objs[obj_index];
if (obj_index >= ARRSIZE(vm->objs)) {
return vm_err(vm, "corrupt obj, index %x", obj_index);
}
for (i = 0; i < ARRSIZE(vm->props); i++) {
struct prop *p = &vm->props[i];
if (p->flags != 0) continue;
p->flags = PROP_ALLOCATED;
// Append property to the end of the property list
if (prop == NULL) {
p->next = o->props;
o->props = i;
} else {
assert(prop->next = INVALID_INDEX);
prop->next = i;
p->next = INVALID_INDEX;
}
p->key = key;
p->val = val;
DEBUG(("%s: prop %hu %s -> ", __func__, i, tostr(vm, key)));
DEBUG(("%s\n", tostr(vm, val)));
return JS_TRUE;
}
return vm_err(vm, "props OOM");
}
} else {
return vm_err(vm, "setting prop on non-object");
}
}
static int is_true(struct elk *vm, jsval_t v) {
jslen_t len;
js_type_t t = js_type(v);
return t == JS_TYPE_TRUE || (t == JS_TYPE_NUMBER && tof(v) != 0.0) ||
t == JS_TYPE_OBJECT || t == JS_TYPE_FUNCTION ||
(t == JS_TYPE_STRING && js_to_str(vm, v, &len) && len > 0);
}
////////////////////////////////// TOKENIZER /////////////////////////////////
struct tok {
jstok_t tok, len;
const char *ptr;
float num_value;
};
struct parser {
const char *file_name; // Source code file name
const char *buf; // Nul-terminated source code buffer
const char *pos; // Current position
const char *end; // End position
int line_no; // Line number
jstok_t prev_tok; // Previous token, for prefix increment / decrement
struct tok tok; // Parsed token
int noexec; // Parse only, do not execute
struct elk *vm;
};
#define DT(a, b) ((jstok_t)(a) << 8 | (b))
#define TT(a, b, c) ((jstok_t)(a) << 16 | (jstok_t)(b) << 8 | (c))
#define QT(a, b, c, d) \
((jstok_t)(a) << 24 | (jstok_t)(b) << 16 | (jstok_t)(c) << 8 | (d))
// clang-format off
enum {
TOK_EOF, TOK_INVALID, TOK_NUM, TOK_STR, TOK_IDENT = 200,
TOK_BREAK, TOK_CASE, TOK_CATCH, TOK_CONTINUE, TOK_DEBUGGER, TOK_DEFAULT,
TOK_DELETE, TOK_DO, TOK_ELSE, TOK_FALSE, TOK_FINALLY, TOK_FOR, TOK_FUNCTION,
TOK_IF, TOK_IN, TOK_INSTANCEOF, TOK_NEW, TOK_NULL, TOK_RETURN, TOK_SWITCH,
TOK_THIS, TOK_THROW, TOK_TRUE, TOK_TRY, TOK_TYPEOF, TOK_VAR, TOK_VOID,
TOK_WHILE, TOK_WITH, TOK_LET, TOK_UNDEFINED,
TOK_UNARY_MINUS, TOK_UNARY_PLUS, TOK_POSTFIX_PLUS, TOK_POSTFIX_MINUS,
};
// clang-format on
// We're not relying on the target libc ctype, as it may incorrectly
// handle negative arguments, e.g. isspace(-1).
static int js_is_space(int c) {
return c == ' ' || c == '\r' || c == '\n' || c == '\t' || c == '\f' ||
c == '\v';
}
static int js_is_digit(int c) {
return c >= '0' && c <= '9';
}
static int js_is_alpha(int c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
static int js_is_ident(int c) {
return c == '_' || c == '$' || js_is_alpha(c);
}
// Try to parse a token that can take one or two chars.
static int longtok(struct parser *p, const char *first_chars,
const char *second_chars) {
if (strchr(first_chars, p->pos[0]) == NULL) return TOK_EOF;
if (p->pos + 1 < p->end && p->pos[1] != '\0' &&
strchr(second_chars, p->pos[1]) != NULL) {
p->tok.len++;
p->pos++;
return p->pos[-1] << 8 | p->pos[0];
}
return p->pos[0];
}
// Try to parse a token that takes exactly 3 chars.
static int longtok3(struct parser *p, char a, char b, char c) {
if (p->pos + 2 < p->end && p->pos[0] == a && p->pos[1] == b &&
p->pos[2] == c) {
p->tok.len += 2;
p->pos += 2;
return ((jstok_t) p->pos[-2] << 16) | ((jstok_t) p->pos[-1] << 8) |
p->pos[0];
}
return TOK_EOF;
}
// Try to parse a token that takes exactly 4 chars.
static int longtok4(struct parser *p, char a, char b, char c, char d) {
if (p->pos + 3 < p->end && p->pos[0] == a && p->pos[1] == b &&
p->pos[2] == c && p->pos[3] == d) {
p->tok.len += 3;
p->pos += 3;
return ((jstok_t) p->pos[-3] << 24) | ((jstok_t) p->pos[-2] << 16) |
((jstok_t) p->pos[-1] << 8) | p->pos[0];
}
return TOK_EOF;
}
static int getnum(struct parser *p) {
if (p->pos[0] == '0' && p->pos[1] == 'x') {
// MSVC6 strtod cannot parse 0x... numbers, thus this ugly workaround.
p->tok.num_value = (float) strtoul(p->pos + 2, (char **) &p->pos, 16);
} else {
p->tok.num_value = (float) strtod(p->pos, (char **) &p->pos);
}
p->tok.len = p->pos - p->tok.ptr;
p->pos--;
return TOK_NUM;
}
static int is_reserved_word_token(const char *s, int len) {
const char *reserved[] = {
"break", "case", "catch", "continue", "debugger", "default",
"delete", "do", "else", "false", "finally", "for",
"function", "if", "in", "instanceof", "new", "null",
"return", "switch", "this", "throw", "true", "try",
"typeof", "var", "void", "while", "with", "let",
"undefined", NULL};
int i;
if (!js_is_alpha(s[0])) return 0;
for (i = 0; reserved[i] != NULL; i++) {
if (len == (int) strlen(reserved[i]) && strncmp(s, reserved[i], len) == 0)
return i + 1;
}
return 0;
}
static int getident(struct parser *p) {
while (js_is_ident(p->pos[0]) || js_is_digit(p->pos[0])) p->pos++;
p->tok.len = p->pos - p->tok.ptr;
p->pos--;
return TOK_IDENT;
}
static int getstr(struct parser *p) {
int quote = *p->pos++;
p->tok.ptr++;
while (p->pos[0] != '\0' && p->pos < p->end && p->pos[0] != quote) {
if (p->pos[0] == '\\' && p->pos[1] != '\0' &&
(p->pos[1] == quote || strchr("bfnrtv\\", p->pos[1]) != NULL)) {
p->pos += 2;
} else {
p->pos++;
}
}
p->tok.len = p->pos - p->tok.ptr;
return TOK_STR;
}
static void skip_spaces_and_comments(struct parser *p) {
const char *pos;
do {
pos = p->pos;
while (p->pos < p->end && js_is_space(p->pos[0])) {
if (p->pos[0] == '\n') p->line_no++;
p->pos++;
}
if (p->pos + 1 < p->end && p->pos[0] == '/' && p->pos[1] == '/') {
while (p->pos[0] != '\0' && p->pos[0] != '\n') p->pos++;
}
if (p->pos + 4 < p->end && p->pos[0] == '/' && p->pos[1] == '*') {
p->pos += 2;
while (p->pos < p->end && p->pos[0] != '\0') {
if (p->pos[0] == '\n') p->line_no++;
if (p->pos + 1 < p->end && p->pos[0] == '*' && p->pos[1] == '/') {
p->pos += 2;
break;
}
p->pos++;
}
}
} while (pos < p->pos);
}
static jstok_t pnext(struct parser *p) {
jstok_t tmp, tok = TOK_INVALID;
skip_spaces_and_comments(p);
p->tok.ptr = p->pos;
p->tok.len = 1;
if (p->pos[0] == '\0' || p->pos >= p->end) tok = TOK_EOF;
if (js_is_digit(p->pos[0])) {
tok = getnum(p);
} else if (p->pos[0] == '\'' || p->pos[0] == '"') {
tok = getstr(p);
} else if (js_is_ident(p->pos[0])) {
tok = getident(p);
// NOTE: getident() has side effects on `p`, and `is_reserved_word_token()`
// relies on them. Since in C the order of evaluation of the operands is
// undefined, `is_reserved_word_token()` should be called in a separate
// statement.
tok += is_reserved_word_token(p->tok.ptr, p->tok.len);
} else if (strchr(",.:;{}[]()?", p->pos[0]) != NULL) {
tok = p->pos[0];
} else if ((tmp = longtok3(p, '<', '<', '=')) != TOK_EOF ||
(tmp = longtok3(p, '>', '>', '=')) != TOK_EOF ||
(tmp = longtok4(p, '>', '>', '>', '=')) != TOK_EOF ||
(tmp = longtok3(p, '>', '>', '>')) != TOK_EOF ||
(tmp = longtok3(p, '=', '=', '=')) != TOK_EOF ||
(tmp = longtok3(p, '!', '=', '=')) != TOK_EOF ||
(tmp = longtok(p, "&", "&=")) != TOK_EOF ||
(tmp = longtok(p, "|", "|=")) != TOK_EOF ||
(tmp = longtok(p, "<", "<=")) != TOK_EOF ||
(tmp = longtok(p, ">", ">=")) != TOK_EOF ||
(tmp = longtok(p, "-", "-=")) != TOK_EOF ||
(tmp = longtok(p, "+", "+=")) != TOK_EOF) {
tok = tmp;
} else if ((tmp = longtok(p, "^~+-%/*<>=!|&", "=")) != TOK_EOF) {
tok = tmp;
}
if (p->pos < p->end && p->pos[0] != '\0') p->pos++;
p->prev_tok = p->tok.tok;
p->tok.tok = tok;
// DEBUG(( "%s: tok %d [%c] [%.*s]\n", __func__, tok, tok,
// (int) (p->end - p->pos), p->pos));
return p->tok.tok;
}
////////////////////////////////// PARSER /////////////////////////////////
static jsval_t parse_statement_list(struct parser *p, jstok_t endtok);
static jsval_t parse_expr(struct parser *p);
static jsval_t parse_statement(struct parser *p);
#define EXPECT(p, t) \
do { \
if ((p)->tok.tok != (t)) \
return vm_err((p)->vm, "%s: expecting '%c'", __func__, (t)); \
} while (0)
static struct parser mk_parser(struct elk *vm, const char *buf, int len) {
struct parser p;
memset(&p, 0, sizeof(p));
p.line_no = 1;
p.buf = p.pos = buf;
p.end = buf + len;
p.vm = vm;
return p;
}
// clang-format off
static jstok_t s_assign_ops[] = {
'=', DT('+', '='), DT('-', '='), DT('*', '='), DT('/', '='), DT('%', '='),
TT('<', '<', '='), TT('>', '>', '='), QT('>', '>', '>', '='), DT('&', '='),
DT('^', '='), DT('|', '='), TOK_EOF
};
// clang-format on
static jstok_t s_postfix_ops[] = {DT('+', '+'), DT('-', '-'), TOK_EOF};
static jstok_t s_unary_ops[] = {'!', '~', DT('+', '+'), DT('-', '-'),
TOK_TYPEOF, '-', '+', TOK_EOF};
static jstok_t s_equality_ops[] = {
DT('=', '+'), DT('!', '='), TT('=', '=', '='), TT('=', '=', '='), TOK_EOF};
static jstok_t s_cmp_ops[] = {DT('<', '='), '<', '>', DT('>', '='), TOK_EOF};
static jstok_t findtok(const jstok_t *toks, jstok_t tok) {
int i = 0;
while (tok != toks[i] && toks[i] != TOK_EOF) i++;
return toks[i];
}
static float do_arith_op(float f1, float f2, jsval_t op) {
// clang-format off
switch (op) {
case '+': return f1 + f2;
case '-': return f1 - f2;
case '*': return f1 * f2;
case '/': return f1 / f2;
case '%': return (float) ((long) f1 % (long) f2);
case '^': return (float) ((jsval_t) f1 ^ (jsval_t) f2);
case '|': return (float) ((jsval_t) f1 | (jsval_t) f2);
case '&': return (float) ((jsval_t) f1 & (jsval_t) f2);
case DT('>','>'): return (float) ((long) f1 >> (long) f2);
case DT('<','<'): return (float) ((long) f1 << (long) f2);
case TT('>','>', '>'): return (float) ((jsval_t) f1 >> (jsval_t) f2);
}
// clang-format on
return 0;
}
static jsval_t do_assign_op(struct elk *vm, jstok_t op) {
jsval_t *t = vm_top(vm);
struct prop *prop = &vm->props[(ind_t) tof(t[-1])];
if (js_type(prop->val) != JS_TYPE_NUMBER || js_type(t[0]) != JS_TYPE_NUMBER)
return vm_err(vm, "please no");
t[-1] = prop->val = tov(do_arith_op(tof(prop->val), tof(t[0]), op));
vm_drop(vm);
return prop->val;
}
static jsval_t do_op(struct parser *p, int op) {
jsval_t *top = vm_top(p->vm), a = top[-1], b = top[0];
if (p->noexec) return JS_TRUE;
DEBUG(("%s: sp %d op %c %d\n", __func__, p->vm->sp, op, op));
DEBUG((" top-1 %s\n", tostr(p->vm, b)));
DEBUG((" top-2 %s\n", tostr(p->vm, a)));
switch (op) {
case '+':
if (js_type(a) == JS_TYPE_STRING && js_type(b) == JS_TYPE_STRING) {
jsval_t v = js_concat(p->vm, a, b);
if (v == JS_ERROR) return v;
vm_drop(p->vm);
vm_drop(p->vm);
vm_push(p->vm, v);
break;
}
// clang-format off
case '-': case '*': case '/': case '%': case '^': case '&': case '|':
case DT('>', '>'): case DT('<', '<'): case TT('>', '>', '>'):
// clang-format on
if (js_type(a) == JS_TYPE_NUMBER && js_type(b) == JS_TYPE_NUMBER) {
jsval_t v = tov(do_arith_op(tof(a), tof(b), op));
vm_drop(p->vm);
vm_drop(p->vm);
vm_push(p->vm, v);
} else {
return vm_err(p->vm, "apples to apples please");
}
break;
/* clang-format off */
case DT('-', '='): return do_assign_op(p->vm, '-');
case DT('+', '='): return do_assign_op(p->vm, '+');
case DT('*', '='): return do_assign_op(p->vm, '*');
case DT('/', '='): return do_assign_op(p->vm, '/');
case DT('%', '='): return do_assign_op(p->vm, '%');
case DT('&', '='): return do_assign_op(p->vm, '&');
case DT('|', '='): return do_assign_op(p->vm, '|');
case DT('^', '='): return do_assign_op(p->vm, '^');
case TT('<', '<', '='): return do_assign_op(p->vm, DT('<', '<'));
case TT('>', '>', '='): return do_assign_op(p->vm, DT('>', '>'));
case QT('>', '>', '>', '='): return do_assign_op(p->vm, TT('>', '>', '>'));
case ',': break;
/* clang-format on */
case TOK_POSTFIX_MINUS:
case TOK_POSTFIX_PLUS: {
struct prop *prop = &p->vm->props[(ind_t) tof(b)];
if (js_type(prop->val) != JS_TYPE_NUMBER)
return vm_err(p->vm, "please no");
top[0] = prop->val;
prop->val = tov(tof(prop->val) + ((op == TOK_POSTFIX_PLUS) ? 1 : -1));
break;
}
case '!':
top[0] = is_true(p->vm, top[0]) ? JS_FALSE : JS_TRUE;
break;
case '~':
if (js_type(top[0]) != JS_TYPE_NUMBER) return vm_err(p->vm, "noo");
top[0] = tov((float) (~(long) tof(top[0])));
break;
case TOK_UNARY_PLUS:
break;
case TOK_UNARY_MINUS:
top[0] = tov(-tof(top[0]));
break;
// static jstok_t s_unary_ops[] = {'!', '~', DT('+', '+'), DT('-',
// '-'),
// TOK_TYPEOF, '-', '+', TOK_EOF};
case TOK_TYPEOF:
top[0] = mk_str(p->vm, js_typeof(top[0]), -1);
break;
#if 0
case '=': {
jsval_t obj = p->vm->call_stack[p->vm->csp - 1];
jsval_t res = js_set(p->vm, obj, a, b);
top[0] = a;
top[-1] = b;
if (res == JS_ERROR) return res;
return vm_drop(p->vm);
}
#endif
default:
return vm_err(p->vm, "Unknown op: %c (%d)", op, op);
}
return JS_TRUE;
}
typedef jsval_t bpf_t(struct parser *p, int prev_op);
static jsval_t parse_ltr_binop(struct parser *p, bpf_t f1, bpf_t f2,
const jstok_t *ops, jstok_t prev_op) {
jsval_t res = JS_TRUE;
TRY(f1(p, TOK_EOF));
if (prev_op != TOK_EOF) TRY(do_op(p, prev_op));
if (findtok(ops, p->tok.tok) != TOK_EOF) {
int op = p->tok.tok;
pnext(p);
TRY(f2(p, op));
}
return res;
}
static jsval_t parse_rtl_binop(struct parser *p, bpf_t f1, bpf_t f2,
const jstok_t *ops, jstok_t prev_op) {
jsval_t res = JS_TRUE;
(void) prev_op;
TRY(f1(p, TOK_EOF));
if (findtok(ops, p->tok.tok) != TOK_EOF) {
int op = p->tok.tok;
pnext(p);
TRY(f2(p, TOK_EOF));
TRY(do_op(p, op));
}
return res;
}