-
Notifications
You must be signed in to change notification settings - Fork 3
/
key.c
2423 lines (2264 loc) · 69.1 KB
/
key.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
/* ********************************************************************** */
/* KeyLang: A Scripting Language in the Key of C */
/* ********************************************************************** */
#include "key.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <stdarg.h>
#include <ctype.h>
#include <errno.h>
#define TRACK_USAGES (1) /* boolean; record usage statistics */
#define ERROR_BUFLEN (128) /* length of error message buffer */
#define TOKEN_BUFLEN (1024) /* max length of a token */
#define INTERN_BUFLEN (16 * 1024) /* interned string storage */
#define GLOBAL_MAX (1024) /* max number of global variables */
#define OPER_DEPTH (128) /* operand stack size */
#define SCOPE_DEPTH (512) /* local scope stack size */
#define EXEC_DEPTH (380) /* exec stack size (make keyenv ~16384 bytes) */
#define Q(EX) do{ keyret rv_ = (EX); if (rv_ != KEY_OK) return rv_; }while(0)
#define keyval_end() ((keyval){ .type=(KEY_END) })
#define keyval_mark() ((keyval){ .type=(KEY_MARK) })
#define keyval_bcode(V) ((keyval){ .type=(KEY_BCODE), .bval=(V) })
#define keyval_native(V) ((keyval){ .type=(KEY_NAT), .eval=(V) })
#define keyval_func(V) ((keyval){ .type=(KEY_FUNC), .fval=(V) })
#define STREQ(A,B) ( (A) == (B) || !strcmp((A),(B)) )
/* ********************************************************************** */
/* ********************************************************************** */
typedef enum token_e {
TOK_EOF = 0,
/* lexical only */
TOK_ADD_A, TOK_AND_A, TOK_COAL_A, TOK_CBRACE, TOK_CBRACK, TOK_COLON,
TOK_CPAREN, TOK_DEC, TOK_DIV_A, TOK_DOT, TOK_ELSE, TOK_INC, TOK_LOGAND_A,
TOK_LOGOR_A, TOK_LSH_A, TOK_MOD_A, TOK_MUL_A, TOK_OBRACE, TOK_OPAREN,
TOK_OR_A, TOK_RSH_A, TOK_SEMI, TOK_SUB_A, TOK_USH_A, TOK_XOR_A,
/* lexical and ast */
TOK_ADD, TOK_AND, TOK_ASSIGN, TOK_BREAK, TOK_COAL, TOK_COMMA, TOK_CONT,
TOK_DIV, TOK_DO, TOK_EQ, TOK_FOR, TOK_FUNC, TOK_GE, TOK_GT, TOK_IDENT,
TOK_IF, TOK_IS, TOK_ISNOT, TOK_INT, TOK_LOGAND, TOK_LOGNOT, TOK_LOGOR,
TOK_LE, TOK_LSH, TOK_LT, TOK_MOD, TOK_MUL, TOK_OBRACK, TOK_OR, TOK_NE,
TOK_NOT, TOK_QUEST, TOK_RETURN, TOK_RSH, TOK_SUB, TOK_STRING, TOK_TYPEOF,
TOK_UNDEF, TOK_USH, TOK_VAR, TOK_VARARGS, TOK_WHILE, TOK_XOR,
/* ast only */
TOK_LIST, TOK_NEG, TOK_FUNCX, TOK_M_ASSIGN, TOK_M_CALL, TOK_POSTCOMMA,
TOK_OBJECT, TOK_ARRAY
} token_t;
static char *
tok_name(token_t tk)
{
static char * names[] = {
"eof",
"+=", "&=", "?\?=", "}", "]", ":",
")", "--", "/=", ".", "else", "++", "&&=",
"||=", "<<=", "%=", "*=", "{", "(",
"|=", ">>=", ";", "-=", ">>>=", "^=",
"+", "&", "=", "break", "?\?", ",", "continue",
"/", "do", "==", "for", "fn", ">=", ">", "identifier",
"if", "is", "isnot", "integer", "&&", "!", "||",
"<=", "<<", "<", "%", "*", "[", "|", "!=",
"~", "?", "return", ">>", "-", "string", "typeof",
"undef", ">>>", "var", "...", "while", "^",
"list", "-", "fn", ".=", ".()", ",,",
"object", "array"
};
return names[tk];
}
typedef struct node node;
struct node {
token_t type;
union {
int ival;
const char * sval;
};
node * first;
node * second;
node * third;
node * fourth;
node * chain;
};
typedef struct stack stack;
struct stack {
int cap;
int len;
#if TRACK_USAGES
int max;
#endif
keyval * buf;
};
struct keyenv {
stack oper;
stack scope;
stack exec;
keyval * root; /* bytecode allocation pointer */
keyval buf[]; /* all the stack space */
};
static keyret bcode_load(keyenv * e);
static keyret bcode_assign(keyenv * e);
static keyret bcode_dup(keyenv * e);
static keyret bcode_index(keyenv * e);
static keyret bcode_pop(keyenv * e);
static keyret bcode_if(keyenv * e);
static keyret bcode_ifelse(keyenv * e);
static keyret bcode_doloop(keyenv * e);
static keyret bcode_loop(keyenv * e);
static keyret bcode_break(keyenv * e);
static keyret bcode_continue(keyenv * e);
static keyret bcode_call(keyenv * e);
static keyret bcode_return(keyenv * e);
static keyret bcode_var(keyenv * e);
static keyret bcode_defargs(keyenv * e);
static keyret bcode_varargs(keyenv * e);
static keyret bcode_add(keyenv * e);
static keyret bcode_sub(keyenv * e);
static keyret bcode_mul(keyenv * e);
static keyret bcode_div(keyenv * e);
static keyret bcode_mod(keyenv * e);
static keyret bcode_and(keyenv * e);
static keyret bcode_or(keyenv * e);
static keyret bcode_xor(keyenv * e);
static keyret bcode_lsh(keyenv * e);
static keyret bcode_rsh(keyenv * e);
static keyret bcode_ush(keyenv * e);
static keyret bcode_eq(keyenv * e);
static keyret bcode_ne(keyenv * e);
static keyret bcode_gt(keyenv * e);
static keyret bcode_lt(keyenv * e);
static keyret bcode_ge(keyenv * e);
static keyret bcode_le(keyenv * e);
static keyret bcode_is(keyenv * e);
static keyret bcode_isnot(keyenv * e);
static keyret bcode_not(keyenv * e);
static keyret bcode_lognot(keyenv * e);
static keyret bcode_neg(keyenv * e);
static keyret bcode_isdef(keyenv * e);
static keyret bcode_typeof(keyenv * e);
static keyret bcode_coal(keyenv * e);
static keyret bcode_logand(keyenv * e);
static keyret bcode_logor(keyenv * e);
/* ********************************************************************** */
/* Errors */
/* ********************************************************************** */
char key_errmsg[ERROR_BUFLEN] = "";
#define ERRMSG_LIMIT (key_errmsg + ERROR_BUFLEN)
keyret
key_error(const char * fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(key_errmsg, ERROR_BUFLEN, fmt, ap);
va_end(ap);
return KEY_ERROR;
}
keyret
key_type_error(keyval a)
{
if (a.type == KEY_STR) return key_error("unexpected string: '%s'", a.sval);
if (a.type == KEY_INT) return key_error("unexpected integer: '%d'", a.ival);
return key_error("unexpected type: %s", keyval_typename(a.type));
}
keyret
key_type_require(keyval a, keytype type)
{
if (a.type == type) return KEY_OK;
return key_error("unexpected type: have %s, expected %s",
keyval_typename(a.type), keyval_typename(type));
}
keyret
key_type_require_fn(keyval a)
{
if (a.type == KEY_FUNC || a.type == KEY_NAT) return KEY_OK;
return key_type_require(a, KEY_FUNC);
}
/* ********************************************************************** */
/* String Internment */
/* ********************************************************************** */
#if TRACK_USAGES
static size_t intern_max;
#endif
static char internbuf[INTERN_BUFLEN];
#define INTERN_LIMIT (internbuf + INTERN_BUFLEN)
keyret
key_intern(const char ** dst, const char * src)
{
char * p = internbuf;
size_t n;
if (!src || !*src) { *dst = ""; return KEY_OK; }
if (src >= internbuf && src < INTERN_LIMIT) { *dst = src; return KEY_OK; }
while (*p) {
if (!strcmp(p, src)) { *dst = p; return KEY_OK; }
p += strlen(p) + 1;
}
n = strlen(src) + 1;
if ((size_t)(INTERN_LIMIT - p) <= n)
return key_error("out of internment room for '%s'", src);
strcpy(p, src);
*(p + n) = '\0'; /* double zero at end makes it all work */
*dst = p;
#if TRACK_USAGES
n = (size_t)((p + n) - internbuf);
if (intern_max < n) intern_max = n;
#endif
return KEY_OK;
}
/* ********************************************************************** */
/* Tokenizer */
/* ********************************************************************** */
size_t
key_escape(char * dst, size_t dstlen, const char * src)
{
size_t i = 0;
const char * p;
#define OUT(C) do{ if (i < dstlen) dst[i] = (C); ++i; }while(0)
for (p = src; *p; ++p) {
switch (*p) {
case '\\': OUT('\\'); OUT('\\'); break;
case '\n': OUT('\\'); OUT('n'); break;
case '\r': OUT('\\'); OUT('r'); break;
case '\t': OUT('\\'); OUT('t'); break;
case '\"': OUT('\\'); OUT('\"'); break;
case '\'': OUT('\\'); OUT('\''); break;
default: OUT(*p); break;
}
}
#undef OUT
if (i < dstlen) dst[i] = '\0'; else dst[dstlen - 1] = '\0';
return i;
}
static int isword(int c) {
return isalnum(c) || c == '_' || c == '$' || c == '@' || c >= 0x80;
}
struct lexer {
const char * input; /* source text */
const char * inp; /* read pointer into input */
const char * fname; /* name of input 'file' */
int line; /* line currently being tokenized */
char * tokp; /* write pointer into token buffer */
char * buf; /* caller-supplied token buffer */
char * limit; /* one-past-end of token buffer */
};
static struct lexer lexer;
#define APPEND(c) (*(lexer.tokp)++ = (char)(c))
#define ZERO() (*(lexer.tokp) = '\0')
#define OUTOFROOM() (lexer.tokp >= lexer.limit)
static keyret tokerror(const char * fmt, ...) KEY_FORMAT(1, 2);
static keyret
tokerror(const char * fmt, ...)
{
va_list ap;
char * p = key_errmsg;
if (lexer.fname)
p += snprintf(p, ERROR_BUFLEN, "%s:%d: ", lexer.fname, lexer.line);
va_start(ap, fmt);
vsnprintf(p, (size_t)(ERRMSG_LIMIT - p), fmt, ap);
va_end(ap);
return KEY_ERROR;
}
static void
lexer_init(const char * src, const char * fname, int line)
{
lexer.input = lexer.inp = src;
lexer.fname = fname;
lexer.line = line;
lexer.buf = lexer.limit = lexer.tokp = NULL;
}
static int nextChar(void) {
int c = *lexer.inp;
if (!c) return EOF;
if (c == '\n') lexer.line++;
lexer.inp++;
return c;
}
static void ungetChar(void) {
if (*--lexer.inp == '\n') lexer.line--;
}
static keyret
gatherString(int quote)
{
int sawslashcr = 0;
int c;
while ((c = nextChar()) != quote) {
if (c == '\\') {
switch (c = nextChar()) {
case EOF: return tokerror("unexpected end of file");
case 'n': APPEND('\n'); break;
case 'r': APPEND('\r'); break;
case 't': APPEND('\t'); break;
case '\r': sawslashcr = 1; break;
case '\n': break;
default: APPEND(c); break;
}
} else if (sawslashcr) {
if (c != '\n') APPEND(c);
sawslashcr = 0;
} else if (c == EOF) {
return tokerror("unexpected end of file");
} else {
APPEND(c);
}
if (OUTOFROOM()) return tokerror("string too long");
}
ZERO();
return KEY_OK;
}
static keyret
gatherWord(int c)
{
APPEND(c);
while ((c = nextChar()) != EOF) {
if (!isword(c)) { ungetChar(); break; }
APPEND(c);
if (OUTOFROOM()) return tokerror("token too long");
}
ZERO();
return KEY_OK;
}
static void
skipComment(int type)
{
int c;
if (type == '*') {
int sawstar = 0;
while ((c = nextChar()) != EOF) {
if (sawstar && c == '/') break;
sawstar = (c == '*');
}
} else { /* / */
while ((c = nextChar()) != EOF && c != '\n') /**/;
}
}
static keyret
lexer_next(token_t * type, char * buf, size_t buflen)
{
int c;
lexer.buf = lexer.tokp = buf;
lexer.limit = buf + buflen;
#define EQ(S) ( !strcmp(lexer.buf, (S)) )
while ((c = nextChar()) != EOF) {
int d;
if (c <= ' ' || isspace(c)) continue;
if (c != '/') break;
d = nextChar();
if (d == '/' || d == '*') { skipComment(d); continue; }
ungetChar();
break;
}
if (c == EOF) { *type = TOK_EOF; return KEY_OK; }
if (isdigit(c)) { Q(gatherWord(c)); *type = TOK_INT; return KEY_OK; }
if (isword(c)) {
Q(gatherWord(c));
if (EQ("break")) *type = TOK_BREAK;
else if (EQ("continue")) *type = TOK_CONT;
else if (EQ("do")) *type = TOK_DO;
else if (EQ("else")) *type = TOK_ELSE;
else if (EQ("fn")) *type = TOK_FUNC;
else if (EQ("for")) *type = TOK_FOR;
else if (EQ("if")) *type = TOK_IF;
else if (EQ("is")) *type = TOK_IS;
else if (EQ("isnot")) *type = TOK_ISNOT;
else if (EQ("return")) *type = TOK_RETURN;
else if (EQ("typeof")) *type = TOK_TYPEOF;
else if (EQ("undef")) *type = TOK_UNDEF;
else if (EQ("var")) *type = TOK_VAR;
else if (EQ("while")) *type = TOK_WHILE;
else *type = TOK_IDENT;
return KEY_OK;
}
if (c == '\'' || c == '\"') {
Q(gatherString(c));
*type = TOK_STRING;
return KEY_OK;
}
switch (c) {
case ',': *type = TOK_COMMA; break;
case '(': *type = TOK_OPAREN; break;
case ')': *type = TOK_CPAREN; break;
case '[': *type = TOK_OBRACK; break;
case ']': *type = TOK_CBRACK; break;
case '{': *type = TOK_OBRACE; break;
case '}': *type = TOK_CBRACE; break;
case ';': *type = TOK_SEMI; break;
case ':': *type = TOK_COLON; break;
case '~': *type = TOK_NOT; break;
case '.': {
c = nextChar();
if (c == '.') {
c = nextChar();
if (c == '.') { *type = TOK_VARARGS; break; }
ungetChar();
}
ungetChar();
*type = TOK_DOT;
break;
}
#define MAYBE(C,T) if (c == (C)) { *type = (T); break; }
#define ONEOREQ(EQ,NE) do{ \
c = nextChar(); MAYBE('=', (EQ)); ungetChar(); *type = (NE); \
}while(0)
case '+': {
c = nextChar();
MAYBE('+', TOK_INC);
MAYBE('=', TOK_ADD_A);
ungetChar(); *type = TOK_ADD;
break;
}
case '-': {
c = nextChar();
MAYBE('-', TOK_DEC);
MAYBE('=', TOK_SUB_A);
ungetChar(); *type = TOK_SUB;
break;
}
case '*': { ONEOREQ(TOK_MUL_A, TOK_MUL); break; }
case '/': { ONEOREQ(TOK_DIV_A, TOK_DIV); break; }
case '%': { ONEOREQ(TOK_MOD_A, TOK_MOD); break; }
case '!': { ONEOREQ(TOK_NE, TOK_LOGNOT); break; }
case '=': { ONEOREQ(TOK_EQ, TOK_ASSIGN); break; }
case '^': { ONEOREQ(TOK_XOR_A, TOK_XOR); break; }
case '&': {
c = nextChar();
if (c == '&') { ONEOREQ(TOK_LOGAND_A, TOK_LOGAND); break; }
MAYBE('=', TOK_AND_A);
ungetChar(); *type = TOK_AND;
break;
}
case '|': {
c = nextChar();
if (c == '|') { ONEOREQ(TOK_LOGOR_A, TOK_LOGOR); break; }
MAYBE('=', TOK_OR_A);
ungetChar(); *type = TOK_OR;
break;
}
case '<': {
c = nextChar();
if (c == '<') { ONEOREQ(TOK_LSH_A, TOK_LSH); break; }
MAYBE('=', TOK_LE);
ungetChar(); *type = TOK_LT;
break;
}
case '>': {
c = nextChar();
if (c == '>') {
c = nextChar();
if (c == '>') { ONEOREQ(TOK_USH_A, TOK_USH); break; }
MAYBE('=', TOK_RSH_A);
ungetChar(); *type = TOK_RSH;
break;
}
MAYBE('=', TOK_GE);
ungetChar(); *type = TOK_GT;
break;
}
case '?': {
c = nextChar();
if (c == '?') { ONEOREQ(TOK_COAL_A, TOK_COAL); break; }
ungetChar(); *type = TOK_QUEST;
break;
}
default: { return tokerror("unexpected character '%c'", c); }
}
strcpy(lexer.buf, tok_name(*type));
#undef EQ
#undef MAYBE
#undef ONEOREQ
return KEY_OK;
}
/* ********************************************************************** */
/* AST Node */
/* ********************************************************************** */
struct parser {
token_t type; /* type of look-ahead token */
char buf[TOKEN_BUFLEN]; /* text of look-ahead token */
int loopDepth; /* break/continue only allowed inside while */
int funcDepth; /* return only allowed inside functions */
node * chain; /* for cleanup on error */
};
static struct parser parser;
static void
node_delete_chain(node * n)
{
if (n) {
node * m = n->chain;
free(n);
node_delete_chain(m);
}
}
static node *
node_new(token_t t, node * k0, node * k1, node * k2, node * k3)
{
node * n = malloc(sizeof(node));
if (!n) { perror("node_new"); exit(2); }
n->type = t;
n->sval = NULL;
n->first = k0;
n->second = k1;
n->third = k2;
n->fourth = k3;
n->chain = parser.chain;
parser.chain = n;
return n;
}
#define node_new0(T) node_new((T), NULL, NULL, NULL, NULL)
#define node_new1(T,A) node_new((T), (A), NULL, NULL, NULL)
#define node_new2(T,A,B) node_new((T), (A), (B), NULL, NULL)
#define node_new3(T,A,B,C) node_new((T), (A), (B), (C), NULL)
#define node_new4(T,A,B,C,D) node_new((T), (A), (B), (C), (D) )
#define node_new_undef() node_new0(TOK_UNDEF)
static node * node_new_int(int i) {
node * n = node_new0(TOK_INT);
n->ival = i;
return n;
}
static node * node_new_string(token_t t, const char * s) {
node * n = node_new0(t);
n->sval = s;
return n;
}
static keyret
convert_int(int * n, const char * txt)
{
char * endp = NULL;
long int i;
errno = 0;
i = strtol(txt, &endp, 0);
if (errno || !endp || *endp) return tokerror("invalid integer");
#if LONG_MAX > INT_MAX
if (i > INT_MAX || i < INT_MIN) return tokerror("invalid integer");
#endif
*n = (int)i;
return KEY_OK;
}
/* ********************************************************************** */
/* Parse into AST */
/* ********************************************************************** */
#define NEXT() lexer_next(&parser.type, parser.buf, TOKEN_BUFLEN)
#define isType(T) (parser.type == T)
#define MATCH(T) int found_ = 0; Q(consume((T), &found_)); if (found_)
static keyret parseExpr(node ** n);
static keyret parseAssign(node ** n);
static keyret parseStatement(node ** n);
static keyret parseStatements(node ** n);
static keyret parseFunction(node ** n, int isexpr);
static keyret consume(token_t tk, int * found) {
*found = (parser.type == tk);
if (*found) return NEXT();
return KEY_OK;
}
static keyret expect(token_t tk) {
if (parser.type == tk) return NEXT();
return tokerror("unexpected '%s', expected '%s'", parser.buf, tok_name(tk));
}
static keyret require(node * n, const char * name) {
if (!n) return tokerror("missing %s", name);
return KEY_OK;
}
static keyret requireIdent(node * n) {
if (!n || n->type != TOK_IDENT) return tokerror("missing identifier");
return KEY_OK;
}
static keyret checkAssign(node * n) {
if (n->first->type == TOK_OBRACK) n->type = TOK_M_ASSIGN;
else return requireIdent(n->first);
return KEY_OK;
}
static keyret newIntern(node ** n, token_t t) {
const char * p = NULL;
Q(key_intern(&p, parser.buf));
*n = node_new_string(t, p);
return NEXT();
}
static keyret newInt(node ** n) {
int v = 0;
Q(convert_int(&v, parser.buf));
*n = node_new_int(v);
return NEXT();
}
static keyret parseIdent(node ** n) {
if (isType(TOK_IDENT)) return newIntern(n, TOK_IDENT);
return KEY_OK;
}
static keyret parseObjectLit(node ** n) {
for (;;) { /* ident : expr ,} */
node * m = NULL;
Q(parseAssign(&m)); if (!m) break;
if (m->type == TOK_IDENT) m->type = TOK_STRING;
*n = node_new2(TOK_LIST, *n, m);
Q(expect(TOK_COLON));
m = NULL;
Q(parseAssign(&m)); Q(require(m, "expression"));
*n = node_new2(TOK_LIST, *n, m);
if (isType(TOK_CBRACE)) break;
Q(expect(TOK_COMMA));
}
*n = node_new1(TOK_OBJECT, *n);
return expect(TOK_CBRACE);
}
static keyret parseArrayLit(node ** n) {
for (;;) { /* expr ,] */
node * m = NULL;
Q(parseAssign(&m)); if (!m) break;
*n = node_new2(TOK_LIST, *n, m);
if (isType(TOK_CBRACK)) break;
Q(expect(TOK_COMMA));
}
*n = node_new1(TOK_ARRAY, *n);
return expect(TOK_CBRACK);
}
static keyret parsePrimary(node ** n) {
if (isType(TOK_IDENT)) { return newIntern(n, TOK_IDENT); }
else if (isType(TOK_INT)) { return newInt(n); }
else if (isType(TOK_STRING)) { return newIntern(n, TOK_STRING); }
else if (isType(TOK_UNDEF)) { *n = node_new_undef(); return NEXT(); }
else if (isType(TOK_FUNC)) { Q(NEXT()); return parseFunction(n, 1); }
else if (isType(TOK_OBRACE)) { Q(NEXT()); return parseObjectLit(n); }
else if (isType(TOK_OBRACK)) { Q(NEXT()); return parseArrayLit(n); }
else if (isType(TOK_OPAREN)) {
Q(NEXT());
Q(parseExpr(n));
return expect(TOK_CPAREN);
}
return KEY_OK;
}
static keyret parseCallArgs(node ** n) {
Q(parseAssign(n));
while (*n) {
MATCH(TOK_COMMA) {
node * m = NULL;
Q(parseAssign(&m)); Q(require(m, "argument"));
*n = node_new2(TOK_LIST, *n, m);
continue;
}
break;
}
return KEY_OK;
}
static keyret parseMember(node ** n) {
Q(parsePrimary(n));
while (*n) {
{ MATCH(TOK_DOT) {
node * m = NULL;
Q(parseIdent(&m));
m->type = TOK_STRING;
*n = node_new2(TOK_OBRACK, *n, m);
continue;
} }
{ MATCH(TOK_OBRACK) {
node * m = NULL;
Q(parseExpr(&m)); Q(require(m, "expression"));
Q(expect(TOK_CBRACK));
*n = node_new2(TOK_OBRACK, *n, m);
continue;
} }
break;
}
return KEY_OK;
}
static keyret parsePostfix(node ** n) {
Q(parseMember(n));
while (*n) {
{ MATCH(TOK_INC) { /* expr++ -> expr ,, expr += 1 */
node * m = *n;
Q(require(*n, "expression"));
*n = node_new2(TOK_ASSIGN, *n, node_new2(TOK_ADD, *n, node_new_int(1)));
Q(checkAssign(*n));
*n = node_new2(TOK_POSTCOMMA, m, *n);
continue;
} }
{ MATCH(TOK_DEC) { /* expr-- -> expr ,, expr -= 1 */
node * m = *n;
Q(require(*n, "expression"));
*n = node_new2(TOK_ASSIGN, *n, node_new2(TOK_SUB, *n, node_new_int(1)));
Q(checkAssign(*n));
*n = node_new2(TOK_POSTCOMMA, m, *n);
continue;
} }
{ MATCH(TOK_OPAREN) {
node * m = NULL;
Q(parseCallArgs(&m));
Q(expect(TOK_CPAREN));
if ((*n)->type == TOK_OBRACK) {
*n = node_new2(TOK_M_CALL, *n, m);
} else {
*n = node_new2(TOK_OPAREN, *n, m);
}
continue;
} }
break;
}
return KEY_OK;
}
static keyret parsePrefix(node ** n) {
if (isType(TOK_INC)) { /* ++expr -> expr += 1 */
Q(NEXT());
Q(parsePrefix(n)); Q(require(*n, "expression"));
*n = node_new2(TOK_ASSIGN, *n, node_new2(TOK_ADD, *n, node_new_int(1)));
Q(checkAssign(*n));
} else if (isType(TOK_DEC)) { /* --expr -> expr -= 1 */
Q(NEXT());
Q(parsePrefix(n)); Q(require(*n, "expression"));
*n = node_new2(TOK_ASSIGN, *n, node_new2(TOK_SUB, *n, node_new_int(1)));
Q(checkAssign(*n));
} else if (isType(TOK_TYPEOF) || isType(TOK_NOT) || isType(TOK_LOGNOT) ||
isType(TOK_QUEST) || isType(TOK_SUB) || isType(TOK_ADD)) {
token_t type = parser.type;
if (type == TOK_SUB) type = TOK_NEG;
Q(NEXT());
Q(parsePrefix(n)); Q(require(*n, "expression"));
if (type != TOK_ADD) *n = node_new1(type, *n);
} else {
Q(parsePostfix(n));
}
return KEY_OK;
}
static keyret parseInfixMul(node ** n) {
Q(parsePrefix(n));
while (*n) {
if (isType(TOK_MUL) || isType(TOK_DIV) || isType(TOK_MOD)) {
token_t type = parser.type;
node * m = NULL;
Q(NEXT());
Q(parsePrefix(&m)); Q(require(m, "expression"));
*n = node_new2(type, *n, m);
continue;
}
break;
}
return KEY_OK;
}
static keyret parseInfixAdd(node ** n) {
Q(parseInfixMul(n));
while (*n) {
if (isType(TOK_ADD) || isType(TOK_SUB)) {
token_t type = parser.type;
node * m = NULL;
Q(NEXT());
Q(parseInfixMul(&m)); Q(require(m, "expression"));
*n = node_new2(type, *n, m);
continue;
}
break;
}
return KEY_OK;
}
static keyret parseInfixBit(node ** n) {
Q(parseInfixAdd(n));
while (*n) {
if (isType(TOK_LSH) || isType(TOK_RSH) || isType(TOK_USH) ||
isType(TOK_AND) || isType(TOK_OR) || isType(TOK_XOR)) {
token_t type = parser.type;
node * m = NULL;
Q(NEXT());
Q(parseInfixAdd(&m)); Q(require(m, "expression"));
*n = node_new2(type, *n, m);
continue;
}
break;
}
return KEY_OK;
}
static keyret parseInfixCmp(node ** n) {
Q(parseInfixBit(n));
while (*n) {
if (isType(TOK_LT) || isType(TOK_LE) || isType(TOK_GT) ||
isType(TOK_GE) || isType(TOK_EQ) || isType(TOK_NE) ||
isType(TOK_IS) || isType(TOK_ISNOT)) {
token_t type = parser.type;
node * m = NULL;
Q(NEXT());
Q(parseInfixBit(&m)); Q(require(m, "expression"));
*n = node_new2(type, *n, m);
continue;
}
break;
}
return KEY_OK;
}
static keyret parseShortfix(node ** n) {
Q(parseInfixCmp(n));
while (*n) {
if (isType(TOK_LOGAND) || isType(TOK_LOGOR) || isType(TOK_COAL)) {
token_t type = parser.type;
node * m = NULL;
Q(NEXT());
Q(parseInfixCmp(&m)); Q(require(m, "expression"));
*n = node_new2(type, *n, m);
continue;
}
break;
}
return KEY_OK;
}
static keyret parseCond(node ** n) {
Q(parseShortfix(n));
if (*n && isType(TOK_QUEST)) {
node * t = NULL;
node * f = NULL;
Q(NEXT());
Q(parseAssign(&t)); Q(require(t, "expression"));
Q(expect(TOK_COLON));
Q(parseAssign(&f)); Q(require(f, "expression"));
*n = node_new3(TOK_IF, *n, t, f);
}
return KEY_OK;
}
static keyret parseAssign(node ** n) {
Q(parseCond(n));
if (*n) {
if (isType(TOK_ASSIGN)) {
node * m = NULL;
Q(NEXT());
Q(parseAssign(&m)); Q(require(m, "expression"));
*n = node_new2(TOK_ASSIGN, *n, m);
} else if (isType(TOK_ADD_A) || isType(TOK_SUB_A) ||
isType(TOK_MUL_A) || isType(TOK_DIV_A) || isType(TOK_MOD_A) ||
isType(TOK_AND_A) || isType(TOK_OR_A) || isType(TOK_XOR_A) ||
isType(TOK_LSH_A) || isType(TOK_RSH_A) || isType(TOK_USH_A) ||
isType(TOK_LOGAND_A) || isType(TOK_LOGOR_A) || isType(TOK_COAL_A)) {
token_t type = parser.type;
node * m = NULL;
Q(NEXT());
Q(parseAssign(&m)); Q(require(m, "expression"));
switch (type) {
case TOK_ADD_A: type = TOK_ADD; break;
case TOK_SUB_A: type = TOK_SUB; break;
case TOK_MUL_A: type = TOK_MUL; break;
case TOK_DIV_A: type = TOK_DIV; break;
case TOK_MOD_A: type = TOK_MOD; break;
case TOK_AND_A: type = TOK_AND; break;
case TOK_OR_A: type = TOK_OR; break;
case TOK_XOR_A: type = TOK_XOR; break;
case TOK_LSH_A: type = TOK_LSH; break;
case TOK_RSH_A: type = TOK_RSH; break;
case TOK_USH_A: type = TOK_USH; break;
case TOK_LOGAND_A: type = TOK_LOGAND; break;
case TOK_LOGOR_A: type = TOK_LOGOR; break;
case TOK_COAL_A: type = TOK_COAL; break;
default: type = TOK_EOF; break;
}
/* n op= m -> n = n op m */
*n = node_new2(TOK_ASSIGN, *n, node_new2(type, *n, m));
}
if ((*n)->type == TOK_ASSIGN) Q(checkAssign(*n));
}
return KEY_OK;
}
static keyret parseExpr(node ** n) {
Q(parseAssign(n));
while (*n) {
{ MATCH(TOK_COMMA) {
node * m = NULL;
Q(parseAssign(&m)); Q(require(m, "expression"));
*n = node_new2(TOK_COMMA, *n, m);
continue;
} }
break;
}
return KEY_OK;
}
static keyret parseVarOne(node ** n) {
node * name = NULL;
node * value = NULL;
Q(parseIdent(&name)); Q(requireIdent(name));
{ MATCH(TOK_ASSIGN) {
Q(parseAssign(&value));
Q(require(value, "expression"));
} }
*n = node_new2(TOK_VAR, name, value);
return KEY_OK;
}
static keyret parseVar(node ** n) {
Q(parseVarOne(n));
while (*n) {
{ MATCH(TOK_COMMA) {
node * m = NULL;
Q(parseVarOne(&m)); Q(require(m, "declaration"));
*n = node_new2(TOK_LIST, *n, m);
continue;
} }
break;
}
return expect(TOK_SEMI);
}
static keyret parseIf(node ** n) {
node * cond = NULL;
node * body = NULL;
Q(expect(TOK_OPAREN));
Q(parseExpr(&cond)); Q(require(cond, "condition"));
Q(expect(TOK_CPAREN));
Q(parseStatement(&body)); Q(require(body, "statement"));
*n = node_new2(TOK_IF, cond, body);
{ MATCH(TOK_ELSE) {
Q(parseStatement(&((*n)->third)));
Q(require((*n)->third, "statement"));
} }
return KEY_OK;
}
static keyret parseFunctionArglistOne(node ** n, int * va) {
node * m = NULL;
Q(parseIdent(&m));
if (!m && !*n) return KEY_OK; /* empty list */
Q(requireIdent(m));
m->type = TOK_STRING;
*n = node_new2(TOK_LIST, *n, m);
{ MATCH(TOK_VARARGS) {
*n = node_new1(TOK_VARARGS, *n);
*va = 1; /* '...' must be last in list */
} }
return KEY_OK;
}
static keyret parseFunctionArglist(node ** n) {
int va = 0;
Q(parseFunctionArglistOne(n, &va));
while (*n && !va) {
{ MATCH(TOK_COMMA) {
Q(parseFunctionArglistOne(n, &va));
continue;
} }
break;
}
return KEY_OK;
}
static keyret makeName(node ** n) {
static unsigned int anon_id = 0;
char buf[64];
const char * p;
snprintf(buf, sizeof(buf), "__anon_%u__", ++anon_id);
Q(key_intern(&p, buf));
*n = node_new_string(TOK_IDENT, p);
return KEY_OK;
}
static keyret parseFunction(node ** n, int isexpr) {
node * name = NULL;
node * args = NULL;
node * body = NULL;
Q(parseIdent(&name));
if (!isexpr) Q(requireIdent(name));
else if (!name) Q(makeName(&name));
Q(expect(TOK_OPAREN));
Q(parseFunctionArglist(&args));
Q(expect(TOK_CPAREN));
parser.funcDepth++;
Q(parseStatement(&body)); Q(require(body, "statement"));
parser.funcDepth--;
token_t type = isexpr ? TOK_FUNCX : TOK_FUNC;
*n = node_new3(type, name, args, body);
return KEY_OK;
}
static keyret parseDo(node ** n) {
node * body = NULL;
node * cond = NULL;
parser.loopDepth++;
Q(parseStatement(&body)); Q(require(body, "statement"));