forked from cesanta/v7
/
v7.c
1123 lines (962 loc) · 31.3 KB
/
v7.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) 2004-2013 Sergey Lyubka <valenok@gmail.com>
// Copyright (c) 2013-2014 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, as set out in <http://cesanta.com/products.html>.
#include "v7.h"
#include <sys/stat.h>
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#define vsnprintf _vsnprintf
#endif
#define MAX_STRING_LITERAL_LENGTH 500
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
#define CHECK(cond, code) do { if (!(cond)) return (code); } while (0)
#define TRY(call) do { enum v7_err e = call; CHECK(e == V7_OK, e); } while (0)
#define RO_OBJ(t) {0, 0, t, 0, VAL_RO|STR_RO|PROP_RO, {0}}
#define SET_RO_PROP(obj, name, type, attr, initializer) \
do { \
static struct v7_val key = RO_OBJ(V7_STR); \
static struct v7_val val = RO_OBJ(type); \
static struct v7_prop prop = {NULL, &key, &val}; \
key.v.str.buf = (char *) (name); \
key.v.str.len = strlen(key.v.str.buf); \
val.v.attr = (initializer); \
prop.next = obj.v.props; \
obj.v.props = ∝ \
} while (0)
// Possible values for struct v7_val::flags
enum { VAL_RO = 1, STR_RO = 2, PROP_RO = 4 };
// Forward declarations
static enum v7_err parse_expression(struct v7 *);
static enum v7_err parse_statement(struct v7 *, int *is_return);
// Static variables
static struct v7_val s_object_proto = RO_OBJ(V7_OBJ);
static struct v7_val s_string_proto = RO_OBJ(V7_OBJ);
static void Str_length(struct v7_val *this_obj, struct v7_val *result) {
result->type = V7_NUM;
result->v.num = this_obj->v.str.len;
}
static void Str_charCodeAt(struct v7 *v7, struct v7_val *this_obj,
struct v7_val *result, struct v7_val **args,
int num_args) {
double idx = num_args > 0 && args[0]->type == V7_NUM ? args[0]->v.num : NAN;
const struct v7_str *str = &this_obj->v.str;
(void) v7;
result->type = V7_NUM;
result->v.num = NAN;
if (!isnan(idx) && this_obj->type == V7_STR && fabs(idx) < str->len) {
result->v.num = ((unsigned char *) str->buf)[(int) idx];
}
}
static void init_prototypes(void) {
static int prototypes_initialized;
if (prototypes_initialized) return;
prototypes_initialized++;
s_string_proto.proto = &s_object_proto;
SET_RO_PROP(s_object_proto, "MAX_VALUE", V7_NUM, num, LONG_MAX);
SET_RO_PROP(s_object_proto, "MIN_VALUE", V7_NUM, num, LONG_MIN);
SET_RO_PROP(s_string_proto, "length", V7_RO_PROP, prop_func, Str_length);
SET_RO_PROP(s_string_proto, "charCodeAt", V7_C_FUNC, c_func, Str_charCodeAt);
}
struct v7 *v7_create(void) {
struct v7 *v7 = NULL;
size_t i;
if ((v7 = (struct v7 *) calloc(1, sizeof(*v7))) == NULL) return NULL;
for (i = 0; i < ARRAY_SIZE(v7->scopes); i++) {
v7->scopes[i].type = V7_OBJ;
v7->scopes[i].flags = VAL_RO;
}
init_prototypes();
v7_set_obj(v7, v7_get_root_namespace(v7), "Object", &s_object_proto);
v7_set_obj(v7, v7_get_root_namespace(v7), "String", &s_string_proto);
return v7;
}
static void unlink_val(struct v7_val **head, struct v7_val *v) {
for (; *head != NULL; head = &head[0]->next) {
if (*head == v) {
head[0] = head[0]->next;
break;
}
}
}
static void free_val(struct v7 *v7, struct v7_val *v) {
v->ref_count--;
assert(v->ref_count >= 0);
if (v->ref_count > 0) return;
if (v->type == V7_OBJ && !(v->flags & PROP_RO)) {
struct v7_prop *p, *tmp;
for (p = v->v.props; p != NULL; p = tmp) {
tmp = p->next;
free_val(v7, p->key);
free_val(v7, p->val);
free(p);
}
v->v.props = NULL;
} else if (v->type == V7_STR && !(v->flags & STR_RO)) {
free(v->v.str.buf);
} else if (v->type == V7_FUNC && !(v->flags & STR_RO)) {
free(v->v.func);
}
unlink_val(&v7->values, v);
if (!(v->flags & VAL_RO)) free(v);
}
struct v7_val *v7_get_root_namespace(struct v7 *v7) {
return &v7->scopes[0];
}
static enum v7_err inc_stack(struct v7 *v7, int incr) {
int i;
CHECK(v7->sp + incr < (int) ARRAY_SIZE(v7->stack), V7_STACK_OVERFLOW);
CHECK(v7->sp + incr >= 0, V7_STACK_UNDERFLOW);
// Free values pushed on stack (like string literals and functions)
for (i = 0; incr < 0 && i < -incr && i < v7->sp; i++) {
free_val(v7, v7->stack[v7->sp - (i + 1)]);
v7->stack[v7->sp - (i + 1)] = NULL;
}
v7->sp += incr;
return V7_OK;
}
void v7_destroy(struct v7 **v7) {
size_t i;
if (v7 == NULL || v7[0] == NULL) return;
assert(v7[0]->sp >= 0);
inc_stack(v7[0], -v7[0]->sp);
for (i = 0; i < ARRAY_SIZE(v7[0]->scopes); i++) {
v7[0]->scopes[i].ref_count = 1; // Force free_val() below to free memory
free_val(v7[0], &v7[0]->scopes[i]);
}
free(v7[0]);
v7[0] = NULL;
}
struct v7_val **v7_top(struct v7 *v7) {
return &v7->stack[v7->sp];
}
int v7_sp(struct v7 *v7) {
return (int) (v7_top(v7) - v7->stack);
}
static int v7_is_true(const struct v7_val *v) {
return (v->type == V7_BOOL || v->type == V7_NUM) && v->v.num != 0.0;
}
static void obj_v7_to_string(const struct v7_val *v, char *buf, int bsiz) {
const struct v7_prop *m;
int n = snprintf(buf, bsiz, "%s", "{");
for (m = v->v.props; m != NULL && n < bsiz - 1; m = m->next) {
if (m != v->v.props) n += snprintf(buf + n , bsiz - n, "%s", ", ");
v7_to_string(m->key, buf + n, bsiz - n);
n = (int) strlen(buf);
n += snprintf(buf + n , bsiz - n, "%s", ": ");
v7_to_string(m->val, buf + n, bsiz - n);
n = (int) strlen(buf);
}
n += snprintf(buf + n, bsiz - n, "%s", "}");
}
const char *v7_to_string(const struct v7_val *v, char *buf, int bsiz) {
switch (v->type) {
case V7_NUM:
snprintf(buf, bsiz, "%lg", v->v.num);
break;
case V7_BOOL:
snprintf(buf, bsiz, "%s", v->v.num ? "true" : "false");
break;
case V7_UNDEF:
snprintf(buf, bsiz, "%s", "undefined");
break;
case V7_NULL:
snprintf(buf, bsiz, "%s", "null");
break;
case V7_OBJ:
obj_v7_to_string(v, buf, bsiz);
break;
case V7_STR:
snprintf(buf, bsiz, "%.*s", (int) v->v.str.len, v->v.str.buf);
break;
case V7_FUNC:
snprintf(buf, bsiz, "'function%s'", v->v.func);
break;
case V7_C_FUNC:
snprintf(buf, bsiz, "'c_function_at_%p'", v->v.c_func);
break;
default:
snprintf(buf, bsiz, "??");
break;
}
buf[bsiz - 1] = '\0';
return buf;
}
static char *v7_strdup(const char *ptr, unsigned long len) {
char *p = (char *) malloc(len + 1);
if (p == NULL) return NULL;
memcpy(p, ptr, len);
p[len] = '\0';
return p;
}
struct v7_val *v7_mkval(struct v7 *v7, enum v7_type type) {
struct v7_val *v = (struct v7_val *) calloc(1, sizeof(*v));
if (v != NULL) {
v->type = type;
v->next = v7->values;
v7->values = v;
switch (type) {
case V7_STR: v->proto = &s_string_proto; break;
default: v->proto = &s_object_proto; break;
}
}
return v;
}
static struct v7_val *v7_mkval_str(struct v7 *v7, const char *buf,
unsigned long len) {
struct v7_val *v = v7_mkval(v7, V7_STR);
v->v.str.len = len;
v->v.str.buf = v7_strdup(buf, len);
return v;
}
enum v7_err v7_push(struct v7 *v7, struct v7_val *v) {
v->ref_count++;
TRY(inc_stack(v7, 1));
v7->stack[v7->sp - 1] = v;
return V7_OK;
}
enum v7_err v7_make_and_push(struct v7 *v7, enum v7_type type) {
struct v7_val *v = v7_mkval(v7, type);
CHECK(v != NULL, V7_OUT_OF_MEMORY);
return v7_push(v7, v);
}
static enum v7_err do_arithmetic_op(struct v7 *v7, int op) {
struct v7_val **v = v7_top(v7) - 2;
double a, b, res = 0;
if (v7->no_exec) return V7_OK;
CHECK(v7->sp >= 2, V7_STACK_UNDERFLOW);
CHECK(v[0]->type == V7_NUM && v[1]->type == V7_NUM, V7_TYPE_MISMATCH);
a = v[0]->v.num;
b = v[1]->v.num;
switch (op) {
case '+': res = a + b; break;
case '-': res = a - b; break;
case '*': res = a * b; break;
case '/': res = a / b; break;
}
TRY(inc_stack(v7, -2));
TRY(v7_make_and_push(v7, V7_NUM));
v7_top(v7)[-1]->v.num = res;
return V7_OK;
}
static struct v7_val str_to_val(const char *buf, size_t len) {
struct v7_val v;
v.type = V7_STR;
v.v.str.buf = (char *) buf;
v.v.str.len = len;
return v;
}
struct v7_val v7_str_to_val(const char *buf) {
return str_to_val((char *) buf, strlen(buf));
}
static int cmp(const struct v7_val *a, const struct v7_val *b) {
return a->type == V7_STR &&
a->type == b->type &&
a->v.str.len == b->v.str.len &&
memcmp(a->v.str.buf, b->v.str.buf, a->v.str.len) == 0;
}
static struct v7_prop *v7_get(struct v7_val *obj, const struct v7_val *key) {
struct v7_prop *m;
for (; obj != NULL; obj = obj->proto) {
if (obj->type != V7_OBJ) continue;
for (m = obj->v.props; m != NULL; m = m->next) {
if (cmp(m->key, key)) return m;
}
}
return NULL;
}
static struct v7_val *get2(struct v7_val *obj, const struct v7_val *key) {
struct v7_prop *m = v7_get(obj, key);
return (m == NULL) ? NULL : m->val;
}
struct v7_val *v7_lookup(struct v7_val *obj, const char *key) {
struct v7_val k = v7_str_to_val(key);
return get2(obj, &k);
}
static enum v7_err v7_make_and_push_string(struct v7 *v7, const char *s,
unsigned long len, int do_copy) {
struct v7_val **v = v7_top(v7);
TRY(v7_make_and_push(v7, V7_STR));
v[0]->v.str.len = len;
v[0]->v.str.buf = do_copy ? v7_strdup(s, len) : (char *) s;
v[0]->flags = do_copy ? 0 : STR_RO;
return V7_OK;
}
static struct v7_prop *vinsert(struct v7 *v7, struct v7_prop **h,
struct v7_val *key) {
struct v7_prop *m;
if ((m = (struct v7_prop *) calloc(1, sizeof(*m))) != NULL) {
key->ref_count++;
m->key = key;
m->val = v7_mkval(v7, V7_UNDEF);
m->val->ref_count++;
m->next = *h;
*h = m;
}
return m;
}
static struct v7_val *find(struct v7 *v7, struct v7_val *key) {
struct v7_val *v;
int i;
if (v7->no_exec) return NULL;
// Search for the name, traversing scopes up to the top level scope
for (i = v7->current_scope; i >= 0; i--) {
if ((v = get2(&v7->scopes[i], key)) != NULL) return v;
}
return NULL;
}
enum v7_err v7_set(struct v7 *v7, struct v7_val *obj, struct v7_val *k,
struct v7_val *v) {
struct v7_prop *m = NULL;
CHECK(obj != NULL && obj->type == V7_OBJ, V7_TYPE_MISMATCH);
// Find attribute inside object
if ((m = v7_get(obj, k)) == NULL) {
m = vinsert(v7, &obj->v.props, k);
CHECK(m != NULL, V7_OUT_OF_MEMORY);
}
if (m != NULL) {
struct v7_val *tmp = m->val;
v->ref_count++;
m->val = v;
free_val(v7, tmp); // Deallocate previous value
}
return V7_OK;
}
enum v7_err v7_set_func(struct v7 *v7, struct v7_val *obj,
const char *key, v7_func_t c_func) {
struct v7_val *k = v7_mkval_str(v7, key, strlen(key));
struct v7_val *v = v7_mkval(v7, V7_C_FUNC);
CHECK(k != NULL && v != NULL, V7_OUT_OF_MEMORY);
v->v.c_func = c_func;
return v7_set(v7, obj, k, v);
}
enum v7_err v7_set_num(struct v7 *v7, struct v7_val *obj,
const char *key, double num) {
struct v7_val *k = v7_mkval_str(v7, key, strlen(key));
struct v7_val *v = v7_mkval(v7, V7_NUM);
CHECK(k != NULL && v != NULL, V7_OUT_OF_MEMORY);
v->v.num = num;
return v7_set(v7, obj, k, v);
}
enum v7_err v7_set_str(struct v7 *v7, struct v7_val *obj,
const char *key, const char *str, unsigned long len) {
struct v7_val *k = v7_mkval_str(v7, key, strlen(key));
struct v7_val *v = v7_mkval_str(v7, str, len);
CHECK(k != NULL && v != NULL, V7_OUT_OF_MEMORY);
return v7_set(v7, obj, k, v);
}
enum v7_err v7_set_obj(struct v7 *v7, struct v7_val *obj, const char *key,
struct v7_val *val) {
struct v7_val *k = v7_mkval_str(v7, key, strlen(key));
CHECK(k != NULL, V7_OUT_OF_MEMORY);
return v7_set(v7, obj, k, val);
}
static int is_alpha(int ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
static int is_digit(int ch) {
return ch >= '0' && ch <= '9';
}
static int is_alnum(int ch) {
return is_digit(ch) || is_alpha(ch);
}
static int is_space(int ch) {
return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
}
static void skip_whitespaces_and_comments(struct v7 *v7) {
const char *s = v7->cursor, *p = NULL;
while (s != p && *s != '\0' && (is_space(*s) || *s == '/')) {
p = s;
while (*s != '\0' && is_space(*s)) {
if (*s == '\n') v7->line_no++;
s++;
}
if (s[0] == '/' && s[1] == '/') {
s += 2;
while (s[0] != '\0' && s[0] != '\n') s++;
}
if (s[0] == '/' && s[1] == '*') {
s += 2;
while (s[0] != '\0' && !(s[-1] == '/' && s[-2] == '*')) {
if (s[0] == '\n') v7->line_no++;
s++;
}
}
}
v7->cursor = s;
}
static enum v7_err match(struct v7 *v7, int ch) {
CHECK(*v7->cursor++ == ch, V7_SYNTAX_ERROR);
skip_whitespaces_and_comments(v7);
return V7_OK;
}
static int test_and_skip_char(struct v7 *v7, int ch) {
if (*v7->cursor == ch) {
v7->cursor++;
skip_whitespaces_and_comments(v7);
return 1;
}
return 0;
}
static int test_token(struct v7 *v7, const char *kw, unsigned long kwlen) {
return kwlen == v7->tok_len && memcmp(v7->tok, kw, kwlen) == 0;
}
// number = { digit }
static enum v7_err parse_num(struct v7 *v7) {
double value = 0;
int is_negative = 0;
if (*v7->cursor == '-') {
is_negative = 1;
TRY(match(v7, *v7->cursor));
}
CHECK(is_digit(*v7->cursor), V7_SYNTAX_ERROR);
v7->tok = v7->cursor;
while (is_digit(*v7->cursor)) {
value *= 10;
value += *v7->cursor++ - '0';
}
if (is_negative) {
value = -value;
}
v7->tok_len = (unsigned long) (v7->cursor - v7->tok);
skip_whitespaces_and_comments(v7);
if (!v7->no_exec) {
TRY(v7_make_and_push(v7, V7_NUM));
v7_top(v7)[-1]->v.num = value;
}
return V7_OK;
}
// identifier = letter { letter | digit }
static enum v7_err parse_identifier(struct v7 *v7) {
CHECK(is_alpha(*v7->cursor) || *v7->cursor == '_', V7_SYNTAX_ERROR);
v7->tok = v7->cursor;
v7->cursor++;
while (is_alnum(*v7->cursor) || *v7->cursor == '_') v7->cursor++;
v7->tok_len = (unsigned long) (v7->cursor - v7->tok);
skip_whitespaces_and_comments(v7);
return V7_OK;
}
static enum v7_err parse_return_statement(struct v7 *v7) {
if (*v7->cursor == ';' || *v7->cursor == '}') {
if (!v7->no_exec) TRY(v7_make_and_push(v7, V7_UNDEF));
} else {
TRY(parse_expression(v7));
}
return V7_OK;
}
static enum v7_err parse_compound_statement(struct v7 *v7) {
if (*v7->cursor == '{') {
int old_sp = v7->sp;
match(v7, '{');
while (*v7->cursor != '}') {
if (v7->sp > old_sp) inc_stack(v7, old_sp - v7->sp);
TRY(parse_statement(v7, NULL));
}
match(v7, '}');
} else {
TRY(parse_statement(v7, NULL));
}
return V7_OK;
}
// function_defition = "function" "(" func_params ")" "{" func_body "}"
static enum v7_err parse_function_definition(struct v7 *v7, struct v7_val **v,
int num_params) {
int i = 0, old_no_exec = v7->no_exec, old_sp = v7->sp;
const char *src = v7->cursor;
// If 'v' (func to call) is NULL, that means we're just parsing function
// definition to save it's body.
v7->no_exec = v == NULL;
TRY(match(v7, '('));
// Initialize new scope
if (!v7->no_exec) {
v7->current_scope++;
CHECK(v7->current_scope < (int) ARRAY_SIZE(v7->scopes),
V7_RECURSION_TOO_DEEP);
CHECK(v7->scopes[v7->current_scope].v.props == NULL, V7_INTERNAL_ERROR);
CHECK(v7->scopes[v7->current_scope].type == V7_OBJ, V7_INTERNAL_ERROR);
}
while (*v7->cursor != ')') {
TRY(parse_identifier(v7));
if (!v7->no_exec) {
struct v7_val *key = v7_mkval_str(v7, v7->tok, v7->tok_len);
struct v7_val *val = i < num_params ? v[i + 1] : v7_mkval(v7, V7_UNDEF);
v7_set(v7, &v7->scopes[v7->current_scope], key, val);
}
i++;
if (!test_and_skip_char(v7, ',')) break;
}
TRY(match(v7, ')'));
TRY(match(v7, '{'));
while (*v7->cursor != '}') {
int is_return_statement = 0;
inc_stack(v7, old_sp - v7->sp); // Clean up the stack from prev stmt
TRY(parse_statement(v7, &is_return_statement));
if (is_return_statement) break; // Leave statement value on stack
}
if (v7->no_exec) {
TRY(v7_make_and_push(v7, V7_FUNC));
v7_top(v7)[-1]->v.func = v7_strdup(src, (v7->cursor + 1) - src);
}
TRY(match(v7, '}'));
// Deinitialize scope
if (!v7->no_exec) {
v7->scopes[v7->current_scope].ref_count = 1; // Force free_val() below
free_val(v7, &v7->scopes[v7->current_scope]);
v7->current_scope--;
assert(v7->current_scope >= 0);
}
v7->no_exec = old_no_exec;
return V7_OK;
}
enum v7_err v7_call(struct v7 *v7, int num_args) {
struct v7_val **top = v7_top(v7), **v = top - (num_args + 1), *f = v[0];
if (v7->no_exec) return V7_OK;
CHECK(v7->sp > num_args, V7_INTERNAL_ERROR);
CHECK(f->type == V7_FUNC || f->type == V7_C_FUNC, V7_CALLED_NON_FUNCTION);
// Return value will substitute function objest on a stack
v[0] = v7_mkval(v7, V7_UNDEF); // Set return value to 'undefined'
v[0]->ref_count++;
if (f->type == V7_FUNC) {
const char *src = v7->cursor;
v7->cursor = f->v.func; // Move control flow to function body
TRY(parse_function_definition(v7, v, num_args)); // Execute function body
v7->cursor = src; // Return control flow
if (v7_top(v7) > top) { // If function body pushed some value on stack,
free_val(v7, v[0]);
v[0] = top[0]; // use that value as return value
v[0]->ref_count++;
}
} else if (f->type == V7_C_FUNC) {
f->v.c_func(v7, v7->cur_obj, v[0], v + 1, num_args);
}
free_val(v7, f);
TRY(inc_stack(v7, - (int) (v7_top(v7) - (v + 1)))); // Clean up stack
return V7_OK;
}
// function_call = expression "(" { expression} ")"
static enum v7_err parse_function_call(struct v7 *v7) {
struct v7_val **v = v7_top(v7) - 1;
int num_args = 0;
CHECK(v7->no_exec || v[0]->type == V7_FUNC || v[0]->type == V7_C_FUNC,
V7_CALLED_NON_FUNCTION);
// Push arguments on stack
TRY(match(v7, '('));
while (*v7->cursor != ')') {
parse_expression(v7);
test_and_skip_char(v7, ',');
num_args++;
}
TRY(match(v7, ')'));
if (!v7->no_exec) {
TRY(v7_call(v7, num_args));
}
return V7_OK;
}
static enum v7_err parse_string_literal(struct v7 *v7) {
char buf[MAX_STRING_LITERAL_LENGTH];
const char *begin = v7->cursor++;
struct v7_val *v;
size_t i = 0;
TRY(v7_make_and_push(v7, V7_STR));
v = v7_top(v7)[-1];
// Scan string literal into the buffer, handle escape sequences
while (*v7->cursor != *begin && *v7->cursor != '\0') {
switch (*v7->cursor) {
case '\\':
v7->cursor++;
switch (*v7->cursor) {
case 'n': buf[i++] = '\n'; break;
case 't': buf[i++] = '\t'; break;
case '\\': buf[i++] = '\\'; break;
default: if (*v7->cursor == *begin) buf[i++] = *begin; break;
}
break;
default:
buf[i++] = *v7->cursor;
break;
}
if (i >= sizeof(buf) - 1) i = sizeof(buf) - 1;
v7->cursor++;
}
v->v.str.len = v7->no_exec ? 0 : i;
v->v.str.buf = v7->no_exec ? NULL : v7_strdup(buf, v->v.str.len);
TRY(match(v7, *begin));
skip_whitespaces_and_comments(v7);
return V7_OK;
}
static enum v7_err parse_object_literal(struct v7 *v7) {
TRY(v7_make_and_push(v7, V7_OBJ));
TRY(match(v7, '{'));
while (*v7->cursor != '}') {
if (*v7->cursor == '\'' || *v7->cursor == '"') {
TRY(parse_string_literal(v7));
} else {
TRY(parse_identifier(v7));
TRY(v7_make_and_push_string(v7, v7->tok, v7->tok_len, 1));
}
TRY(match(v7, ':'));
TRY(parse_expression(v7));
if (!v7->no_exec) {
struct v7_val **v = v7_top(v7) - 3;
CHECK(v[0]->type == V7_OBJ, V7_TYPE_MISMATCH);
v7_set(v7, v[0], v[1], v[2]);
inc_stack(v7, -2);
}
test_and_skip_char(v7, ',');
}
TRY(match(v7, '}'));
return V7_OK;
}
// variable = identifier { '.' identifier | '[' expression ']' }
static enum v7_err parse_variable(struct v7 *v7) {
struct v7_val **v = NULL, key = str_to_val(v7->tok, v7->tok_len);
struct v7_val *ns = find(v7, &key), ro_prop;
if (!v7->no_exec) {
TRY(v7_make_and_push(v7, V7_UNDEF));
v = v7_top(v7);
}
while (*v7->cursor == '.' || *v7->cursor == '[') {
int ch = *v7->cursor;
TRY(match(v7, ch));
CHECK(v7->no_exec || ns != NULL, V7_SYNTAX_ERROR);
v7->cur_obj = ns;
if (ch == '.') {
TRY(parse_identifier(v7));
if (!v7->no_exec) {
key = str_to_val(v7->tok, v7->tok_len);
ns = get2(ns, &key);
if (ns != NULL && ns->type == V7_RO_PROP) {
ns->v.prop_func(v7->cur_obj, &ro_prop);
ns = &ro_prop;
}
}
} else {
TRY(parse_expression(v7));
TRY(match(v7, ']'));
if (!v7->no_exec) {
ns = get2(ns, v7_top(v7)[-1]);
if (ns != NULL && ns->type == V7_RO_PROP) {
ns->v.prop_func(v7->cur_obj, &ro_prop);
ns = &ro_prop;
}
TRY(inc_stack(v7, -1));
}
}
}
if (v != NULL && ns != NULL) {
free_val(v7, v[-1]);
v[-1] = ns;
v[-1]->ref_count++;
}
return V7_OK;
}
static enum v7_err del_key(struct v7 *v7, struct v7_val *obj,
const struct v7_val *key) {
struct v7_prop **p;
CHECK(obj->type == V7_OBJ, V7_TYPE_MISMATCH);
for (p = &obj->v.props; *p != NULL; p = &p[0]->next) {
if (cmp(key, p[0]->key)) {
struct v7_prop *next = p[0]->next;
free_val(v7, p[0]->key);
free_val(v7, p[0]->val);
free(p[0]);
p[0] = next;
break;
}
}
return V7_OK;
}
static enum v7_err parse_delete(struct v7 *v7) {
struct v7_val key;
TRY(parse_expression(v7));
key = str_to_val(v7->tok, v7->tok_len); // Must go after parse_expression
TRY(del_key(v7, v7->cur_obj, &key));
return V7_OK;
}
// factor = number | string_literal | "(" expression ")" |
// variable | "this" | "null" | "true" | "false" |
// "{" object_literal "}" |
// "[" array_literal "]" |
// function_definition |
// function_call
static enum v7_err parse_factor(struct v7 *v7) {
int old_sp = v7_sp(v7);
if (*v7->cursor == '(') {
TRY(match(v7, '('));
TRY(parse_expression(v7));
TRY(match(v7, ')'));
} else if (*v7->cursor == '\'' || *v7->cursor == '"') {
TRY(parse_string_literal(v7));
} else if (*v7->cursor == '{') {
TRY(parse_object_literal(v7));
} else if (is_alpha(*v7->cursor) || *v7->cursor == '_') {
TRY(parse_identifier(v7));
if (test_token(v7, "this", 4)) {
inc_stack(v7, 1);
v7_top(v7)[-1] = &v7->scopes[v7->current_scope];
} else if (test_token(v7, "null", 4)) {
TRY(v7_make_and_push(v7, V7_NULL));
} else if (test_token(v7, "true", 4)) {
TRY(v7_make_and_push(v7, V7_BOOL));
v7_top(v7)[-1]->v.num = 1;
} else if (test_token(v7, "false", 5)) {
TRY(v7_make_and_push(v7, V7_BOOL));
v7_top(v7)[-1]->v.num = 0;
} else if (test_token(v7, "function", 8)) {
TRY(parse_function_definition(v7, NULL, 0));
} else if (test_token(v7, "delete", 6)) {
TRY(parse_delete(v7));
} else {
TRY(parse_variable(v7));
}
} else {
TRY(parse_num(v7));
}
if (*v7->cursor == '(') {
TRY(parse_function_call(v7));
}
// Don't leave anything on stack if no execution flag is set
if (v7->no_exec) {
inc_stack(v7, old_sp - v7->sp);
}
return V7_OK;
}
// term = factor { mul_op factor }
// mul_op = "*" | "/"
static enum v7_err parse_term(struct v7 *v7) {
TRY(parse_factor(v7));
while (*v7->cursor == '*' || *v7->cursor == '/') {
int ch = *v7->cursor;
TRY(match(v7, ch));
TRY(parse_factor(v7));
TRY(do_arithmetic_op(v7, ch));
}
return V7_OK;
}
enum { OP_XX, OP_GT, OP_LT, OP_GE, OP_LE, OP_EQ };
static int is_logical_op(const char *s) {
switch (s[0]) {
case '>': return s[1] == '=' ? OP_GE : OP_GT;
case '<': return s[1] == '=' ? OP_LE : OP_LT;
case '=': return s[1] == '=' ? OP_EQ : OP_XX;
default: return OP_XX;
}
}
static enum v7_err do_logical_op(struct v7 *v7, int op) {
struct v7_val **v = v7_top(v7) - 2;
if (v7->no_exec) return V7_OK;
CHECK(v[0]->type == V7_NUM && v[1]->type == V7_NUM, V7_TYPE_MISMATCH);
switch (op) {
case OP_GT: v[0]->v.num = v[0]->v.num > v[1]->v.num ? 1.0 : 0.0; break;
case OP_GE: v[0]->v.num = v[0]->v.num >= v[1]->v.num ? 1.0 : 0.0; break;
case OP_LT: v[0]->v.num = v[0]->v.num < v[1]->v.num ? 1.0 : 0.0; break;
case OP_LE: v[0]->v.num = v[0]->v.num <= v[1]->v.num ? 1.0 : 0.0; break;
case OP_EQ: v[0]->v.num = v[0]->v.num == v[1]->v.num ? 1.0 : 0.0; break;
}
TRY(inc_stack(v7, -1));
return V7_OK;
}
static enum v7_err parse_assignment(struct v7 *v7, struct v7_val *obj) {
const char *tok = v7->tok;
unsigned long tok_len = v7->tok_len;
struct v7_val **top = v7_top(v7);
TRY(match(v7, '='));
TRY(parse_expression(v7));
if (!v7->no_exec) {
TRY(v7_make_and_push_string(v7, tok, tok_len, 1));
v7_set(v7, obj, top[1], top[0]);
CHECK(v7_top(v7) - top > 1, V7_INTERNAL_ERROR);
CHECK(v7->sp > 1, V7_STACK_UNDERFLOW);
free_val(v7, top[-1]);
top[-1] = top[0];
top[-1]->ref_count++;
inc_stack(v7, (int) (top - v7_top(v7)));
}
return V7_OK;
}
// expression = term { add_op term } |
// expression "?" expression ":" expression
// expression logical_op expression
// variable "=" expression
// add_op = "+" | "-"
static enum v7_err parse_expression(struct v7 *v7) {
#ifdef V7_DEBUG
const char *stmt_str = v7->cursor;
#endif
int op;
v7->cur_obj = &v7->scopes[v7->current_scope];
TRY(parse_term(v7));
while (*v7->cursor == '-' || *v7->cursor == '+') {
int ch = *v7->cursor;
TRY(match(v7, ch));
TRY(parse_term(v7));
TRY(do_arithmetic_op(v7, ch));
}
if ((op = is_logical_op(v7->cursor)) > OP_XX) {
v7->cursor += op == OP_LT || op == OP_GT ? 1 : 2;
skip_whitespaces_and_comments(v7);
TRY(parse_expression(v7));
TRY(do_logical_op(v7, op));
}
// Parse assignment
if (*v7->cursor == '=') {
//printf("=> cur_obj: %p\n", cur_obj);
TRY(parse_assignment(v7, v7->cur_obj));
}
// Parse ternary operator
if (*v7->cursor == '?') {
int condition_true = v7_is_true(v7_top(v7)[-1]);
int old_no_exec = v7->no_exec;
TRY(match(v7, '?'));
v7->no_exec = old_no_exec || !condition_true;
TRY(parse_expression(v7));
TRY(match(v7, ':'));
v7->no_exec = old_no_exec || condition_true;
TRY(parse_expression(v7));
v7->no_exec = old_no_exec;
}
return V7_OK;
}
// declaration = "var" identifier [ "=" expression ] [ "," { i [ "=" e ] } ]
static enum v7_err parse_declaration(struct v7 *v7) {
int sp = v7_sp(v7);
do {
inc_stack(v7, sp - v7_sp(v7)); // Clean up the stack after prev decl
TRY(parse_identifier(v7));
if (*v7->cursor == '=') {
if (!v7->no_exec) v7_make_and_push(v7, V7_UNDEF);
TRY(parse_assignment(v7, &v7->scopes[v7->current_scope]));
}
} while (test_and_skip_char(v7, ','));
return V7_OK;
}
static enum v7_err parse_if_statement(struct v7 *v7) {
int old_no_exec = v7->no_exec;
TRY(match(v7, '('));
TRY(parse_expression(v7));
TRY(match(v7, ')'));