-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathparser.c
1838 lines (1763 loc) · 61.6 KB
/
parser.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <string.h>
#include <stdio.h>
#include "common.h"
#include "parser.h"
#include "options.h"
#include "memory.h"
#include "debug.h"
#include "vm.h"
#ifdef NDEBUG
#define TRACE_START(name) (void)0
#define TRACE_END(name) (void)0
#else
#define TRACE_START(name) _trace_start(name)
#define TRACE_END(name) _trace_end(name)
#endif
static int traceLvl = 0;
const char traceNesting[] = " ";
static GetMoreSourceFn getMoreSourceFn = NULL;
static void printTraceNesting() {
for (int i = 0; i < traceLvl; i++) {
fprintf(stderr, traceNesting);
}
}
static void _trace_start(const char *name) {
if (CLOX_OPTION_T(traceParserCalls)) {
printTraceNesting();
fprintf(stderr, "[-- <%s> --]\n", name);
traceLvl += 1;
}
}
static void _trace_end(const char *name) {
if (CLOX_OPTION_T(traceParserCalls)) {
traceLvl -= 1;
printTraceNesting();
fprintf(stderr, "[-- </%s> --]\n", name);
}
}
static Parser *current = NULL;
// initialize/reinitialize parser
void initParser(Parser *p) {
p->hadError = false;
p->panicMode = false;
p->aborted = false;
memset(&p->errJmpBuf, 0, sizeof(jmp_buf));
memset(&p->current, 0, sizeof(Token));
memset(&p->previous, 0, sizeof(Token));
vec_init(&p->peekBuf);
vec_init(&p->v_errMessages);
p->inCallExpr = false;
}
void freeParser(Parser *p) {
vec_clear(&p->v_errMessages);
vec_clear(&p->peekBuf);
initParser(p);
}
static void errorAt(Token *token, const char *message) {
ASSERT(message);
if (current->panicMode) { return; }
current->panicMode = true;
ObjString *str = hiddenString("", 0, NEWOBJ_FLAG_NONE);
pushCStringFmt(str, "[Parse Error], (line %d) Error", token->line);
if (token->type == TOKEN_EOF) {
pushCStringFmt(str, " at end");
} else if (token->type == TOKEN_ERROR) {
// Nothing.
} else {
pushCStringFmt(str, " at '%.*s'", token->length, tokStr(token));
}
pushCStringFmt(str, ": %s\n", message);
vec_push(¤t->v_errMessages, str);
current->hadError = true;
longjmp(current->errJmpBuf, JUMP_PERFORMED);
}
static void error(const char *message) {
errorAt(¤t->previous, message);
}
static void errorAtCurrent(const char *message) {
errorAt(¤t->current, message);
}
void outputParserErrors(Parser *p, FILE *f) {
ASSERT(p);
ObjString *msg = NULL;
int i = 0;
vec_foreach(&p->v_errMessages, msg, i) {
fprintf(f, "%s", msg->chars);
}
}
static inline bool isCapital(char c) {
return c >= 'A' && c <= 'Z';
}
// takes into account peekbuffer, which scanToken() doesn't.
// NOTE: if looking to peek forward for a token, call `peekTokN`
// instead of this function.
static Token nextToken() {
if (current->peekBuf.length > 0) {
Token val = vec_first(¤t->peekBuf);
vec_splice(¤t->peekBuf, 0, 1);
return val;
} else {
return scanToken();
}
}
// Fill `parser.current` with next token in stream
static void advance() {
current->previous = current->current;
// parse the next non-error token
for (;;) {
current->current = nextToken();
if (current->current.type != TOKEN_ERROR) {
break;
}
fprintf(stderr, "Error\n");
errorAtCurrent(tokStr(¤t->current));
}
}
// Expect current token to be of given type, otherwise error with given
// message.
static void consume(TokenType type, const char *message) {
if (current->current.type == type) {
advance();
return;
}
errorAtCurrent(message);
}
// Check that the current token is of given type
static bool check(TokenType type) {
return current->current.type == type;
}
// peekTokN(1) gives token that nextToken() will return on next call
static Token peekTokN(int n) {
ASSERT(n > 0);
if (current->peekBuf.length < n) {
for (int i = current->peekBuf.length; i < n; i++) {
Token tok = scanToken();
vec_push(¤t->peekBuf, tok);
if (tok.type == TOKEN_EOF) break;
}
return vec_last(¤t->peekBuf);
} else {
return current->peekBuf.data[n-1];
}
}
// If current token is of given type, advance to next.
// Otherwise returns false.
static bool match(TokenType type) {
if (current->aborted) return false;
if (current->current.type == TOKEN_EOF && getMoreSourceFn) {
/*fprintf(stderr, "getMoreSource called from match\n");*/
getMoreSourceFn(&scanner, current);
/*fprintf(stderr, "/getMoreSource called from match\n");*/
if (current->aborted) {
return false;
}
/*fprintf(stderr, "advance\n");*/
advance();
if (current->current.type == TOKEN_EOF) {
current->aborted = true;
return false;
}
/*fprintf(stderr, "/advance\n");*/
if (!check(type)) return false;
return true;
}
if (!check(type)) return false;
advance();
return true;
}
// forward decls
static Node *declaration(void);
static Node *varDeclaration(void);
static Node *funDeclaration(ParseFunctionType);
static Node *expression(void);
static Node *assignment(void);
static Node *logicOr(void);
static Node *logicAnd(void);
static Node *equality(void);
static Node *comparison(void);
static Node *addition(void);
static Node *bitManip(void);
static Node *multiplication(void);
static Node *unary(void);
static Node *call(void);
static Node *primary(void);
static Node *blockStmts(void);
static Node *classOrModuleBody(const char *name);
static Node *statement(void);
static Node *printStatement(void);
static Node *blockStatements(void);
static Node *expressionStatement(bool);
Node *parseExpression(Parser *p) {
Parser *oldCurrent = current;
current = p;
advance(); // prime parser with parser.current
TRACE_START("parseExpression");
Node *ret = expression();
TRACE_END("parseExpression");
current = oldCurrent;
return ret;
}
Node *parseMaybePartialStatement(Parser *p, GetMoreSourceFn fn) {
getMoreSourceFn = fn;
Parser *oldCurrent = current;
current = p;
advance(); // prime parser with parser.current
TRACE_START("parseStatement");
int jumpRes = setjmp(current->errJmpBuf);
if (jumpRes == JUMP_PERFORMED) { // jumped, had error
ASSERT(current->panicMode);
current = (Parser*)oldCurrent;
TRACE_END("parse (error)");
return NULL;
}
Node *ret = declaration();
TRACE_END("parseStatement");
current = oldCurrent;
getMoreSourceFn = NULL;
return ret;
}
Node *parseClass(Parser *p) {
Parser *oldCurrent = current;
current = p;
advance(); // prime parser with parser.current
TRACE_START("parseClass");
Node *ret = classOrModuleBody("classBody");
TRACE_END("parseClass");
current = oldCurrent;
return ret;
}
static bool isAtEnd(void) {
if (current->aborted) return true;
bool isEnd = current->previous.type == TOKEN_EOF || check(TOKEN_EOF);
if (!isEnd) return false;
if (isEnd && getMoreSourceFn == NULL) {
return true;
} else if (isEnd && getMoreSourceFn) {
/*fprintf(stderr, "getMoreSource called from isAtEnd\n");*/
getMoreSourceFn(&scanner, current);
/*fprintf(stderr, "/getMoreSource called from isAtEnd\n");*/
if (current->aborted) {
return true;
}
/*fprintf(stderr, "advance\n");*/
advance();
/*fprintf(stderr, "/advance\n");*/
if (current->current.type == TOKEN_EOF) {
return true;
}
}
return false;
}
// returns program node that contains list of statement nodes
// initScanner(char *src) must be called so the scanner is ready
// to pass us the tokens to parse.
Node *parse(Parser *p) {
if (!vm.inited) {
// if any errors occur, we add ObjStrings to v_errMessages. Object
// creation requires VM initialization
fprintf(stderr, "VM must be initialized (initVM()) before call to parse()\n");
return NULL;
}
initParser(p);
volatile Parser *oldCurrent = current;
current = p;
node_type_t nType = {
.type = NODE_STMT,
.kind = STMTLIST_STMT,
};
Node *ret = createNode(nType, emptyTok(), NULL);
int jumpRes = setjmp(current->errJmpBuf);
if (jumpRes == JUMP_PERFORMED) { // jumped, had error
ASSERT(current->panicMode);
current = (Parser*)oldCurrent;
TRACE_END("parse (error)");
return NULL;
}
advance(); // prime parser with parser.current
TRACE_START("parse");
while (!isAtEnd()) {
Node *stmt = declaration();
ASSERT(stmt->type.type == NODE_STMT);
nodeAddChild(ret, stmt);
}
TRACE_END("parse");
if (CLOX_OPTION_T(printAST)) {
char *output = outputASTString(ret, 0);
fprintf(stdout, "%s", output);
}
current = (Parser*)oldCurrent;
return ret;
}
void nodeAddData(Node *node, void *data, NodeFreeDataCallback freeDataCb) {
node->data = data;
node->freeDataCb = freeDataCb;
}
static void freeSuperTokenCallback(Node *node) {
ASSERT(node->data);
FREE(Token, node->data);
}
static Node *declaration(void) {
TRACE_START("declaration");
if (match(TOKEN_VAR)) {
Node *ret = varDeclaration();
TRACE_END("declaration");
return ret;
}
if (check(TOKEN_FUN) && peekTokN(1).type == TOKEN_IDENTIFIER) {
advance();
Node *ret = funDeclaration(FUNCTION_TYPE_NAMED);
TRACE_END("declaration");
return ret;
}
if (match(TOKEN_CLASS)) {
consume(TOKEN_IDENTIFIER, "Expected class name (identifier) after keyword 'class'");
Token nameTok = current->previous;
if (!isCapital(*tokStr(&nameTok))) {
error("Class name must be a constant (start with a capital letter)");
}
node_type_t classType = {
.type = NODE_STMT,
.kind = CLASS_STMT,
};
Node *classNode = createNode(classType, nameTok, NULL);
if (match(TOKEN_LESS)) {
consume(TOKEN_IDENTIFIER, "Expected class name after '<' in class declaration");
Token superName = current->previous;
nodeAddData(classNode, (void*)copyToken(&superName), freeSuperTokenCallback);
}
consume(TOKEN_LEFT_BRACE, "Expected '{' after class name");
Node *body = classOrModuleBody("classBody"); // block node
consume(TOKEN_RIGHT_BRACE, "Expected '}' to end class body");
nodeAddChild(classNode, body);
TRACE_END("declaration");
return classNode;
}
if (match(TOKEN_MODULE)) {
consume(TOKEN_IDENTIFIER, "Expected module name (identifier) after keyword 'module'");
Token nameTok = current->previous;
if (!isCapital(*tokStr(&nameTok))) {
error("Module name must be a constant (start with a capital letter)");
}
node_type_t modType = {
.type = NODE_STMT,
.kind = MODULE_STMT,
};
Node *modNode = createNode(modType, nameTok, NULL);
consume(TOKEN_LEFT_BRACE, "Expected '{' after module name");
Node *body = classOrModuleBody("moduleBody"); // block node
consume(TOKEN_RIGHT_BRACE, "Expected '}' to end module body");
nodeAddChild(modNode, body);
TRACE_END("declaration");
return modNode;
}
Node *ret = statement();
TRACE_END("declaration");
return ret;
}
static Node *wrapStmtsInBlock(Node *stmtList, Token lbraceTok) {
ASSERT(nodeKind(stmtList) == STMTLIST_STMT);
node_type_t blockType = {
.type = NODE_STMT,
.kind = BLOCK_STMT,
};
Node *ret = createNode(blockType, lbraceTok, NULL);
nodeAddChild(ret, stmtList);
return ret;
}
static Node *statement() {
TRACE_START("statement");
if (match(TOKEN_PRINT)) {
Node *ret = printStatement();
TRACE_END("statement");
return ret;
}
/*if (match(TOKEN_LEFT_BRACE)) {*/
/*Node *stmtList = blockStatements();*/
/*node_type_t blockType = {*/
/*.type = NODE_STMT,*/
/*.kind = BLOCK_STMT,*/
/*};*/
/*Node *block = createNode(blockType, current->previous, NULL);*/
/*nodeAddChild(block, stmtList);*/
/*TRACE_END("statement");*/
/*return block;*/
/*}*/
if (match(TOKEN_FOREACH)) {
Token foreachTok = current->previous;
node_type_t foreachT = {
.type = NODE_STMT,
.kind = FOREACH_STMT
};
Node *foreachNode = createNode(foreachT, foreachTok, NULL);
consume(TOKEN_LEFT_PAREN, "Expect '(' after keyword 'foreach'");
node_type_t varTokT = {
.type = NODE_OTHER,
.kind = TOKEN_NODE
};
while (match(TOKEN_IDENTIFIER)) {
Token varTok = current->previous;
if (isCapital(*tokStr(&varTok))) {
error("Can't set constants in a foreach loop");
}
Node *varNode = createNode(varTokT, varTok, NULL);
nodeAddChild(foreachNode, varNode);
if (match(TOKEN_IN)) {
break;
} else if (match(TOKEN_COMMA)) { // continue
} else {
errorAtCurrent("Unexpected token in foreach statement");
}
}
nodeAddChild(foreachNode, expression());
consume(TOKEN_RIGHT_PAREN, "Expect ')' after 'foreach' statement variables");
consume(TOKEN_LEFT_BRACE, "Expect '{' after 'foreach' statement variables");
Token lbraceTok = current->previous;
Node *foreachStmtList = blockStatements();
Node *foreachBlock = wrapStmtsInBlock(foreachStmtList, lbraceTok);
nodeAddChild(foreachNode, foreachBlock);
TRACE_END("statement");
return foreachNode;
}
if (match(TOKEN_IF)) {
Token ifTok = current->previous;
consume(TOKEN_LEFT_PAREN, "Expected '(' after keyword 'if'");
node_type_t ifType = {
.type = NODE_STMT,
.kind = IF_STMT,
};
Node *ifNode = createNode(ifType, ifTok, NULL);
Node *cond = expression();
consume(TOKEN_RIGHT_PAREN, "Expected ')' to end 'if' condition");
consume(TOKEN_LEFT_BRACE, "Expected '{' after 'if' condition");
Token lbraceTok = current->previous;
nodeAddChild(ifNode, cond);
Node *ifStmtList = blockStatements();
Node *ifBlock = wrapStmtsInBlock(ifStmtList, lbraceTok);
nodeAddChild(ifNode, ifBlock);
if (match(TOKEN_ELSE)) {
Token elseTok = current->previous;
if (check(TOKEN_IF)) { // else if
Node *elseStmt = statement();
nodeAddChild(ifNode, elseStmt);
} else {
consume(TOKEN_LEFT_BRACE, "Expected '{' after 'else'");
Node *elseStmtList = blockStatements();
Node *elseBlock = wrapStmtsInBlock(elseStmtList, elseTok);
nodeAddChild(ifNode, elseBlock);
}
}
TRACE_END("statement");
return ifNode;
}
if (match(TOKEN_WHILE)) {
Token whileTok = current->previous;
consume(TOKEN_LEFT_PAREN, "Expected '(' after keyword 'while'");
Node *cond = expression();
consume(TOKEN_RIGHT_PAREN, "Expected ')' after 'while' condition");
consume(TOKEN_LEFT_BRACE, "Expected '{' after while");
Token lbraceTok = current->previous;
Node *blockStmtList = blockStatements();
node_type_t whileT = {
.type = NODE_STMT,
.kind = WHILE_STMT,
};
Node *whileBlock = wrapStmtsInBlock(blockStmtList, lbraceTok);
Node *whileNode = createNode(whileT, whileTok, NULL);
nodeAddChild(whileNode, cond);
nodeAddChild(whileNode, whileBlock);
TRACE_END("statement");
return whileNode;
}
// for (var i = 0; i < n; i++) { }
if (match(TOKEN_FOR)) {
node_type_t forT = {
.type = NODE_STMT,
.kind = FOR_STMT,
};
Token forTok = current->previous;
Node *forNode = createNode(forT, forTok, NULL);
consume(TOKEN_LEFT_PAREN, "Expected '(' after keyword 'for'");
Node *initializer = NULL; // can be null
if (match(TOKEN_SEMICOLON)) {
// leave NULL
} else {
if (check(TOKEN_VAR)) {
initializer = declaration();
} else {
initializer = expressionStatement(true);
}
}
nodeAddChild(forNode, initializer);
Node *expr = NULL;
if (match(TOKEN_SEMICOLON)) {
// leave NULL
} else {
expr = expression();
consume(TOKEN_SEMICOLON, "Expected ';' after test expression in 'for'");
}
nodeAddChild(forNode, expr);
Node *incrExpr = NULL;
if (check(TOKEN_RIGHT_PAREN)) {
// leave NULL
} else {
incrExpr = expressionStatement(false);
}
nodeAddChild(forNode, incrExpr);
consume(TOKEN_RIGHT_PAREN, "Expected ')' after 'for' increment/decrement expression");
consume(TOKEN_LEFT_BRACE, "Expected '{' after 'for'");
Token lbraceTok = current->previous;
Node *blockStmtList = blockStatements();
Node *forBlock = wrapStmtsInBlock(blockStmtList, lbraceTok);
nodeAddChild(forNode, forBlock);
TRACE_END("statement");
return forNode;
}
// try { } [catch ([Prefix::+]Error e) { }]+
if (match(TOKEN_TRY)) {
Token tryTok = current->previous;
node_type_t nType = {
.type = NODE_STMT,
.kind = TRY_STMT,
};
TRACE_START("tryStatement");
Node *_try = createNode(nType, tryTok, NULL);
consume(TOKEN_LEFT_BRACE, "Expected '{' after keyword 'try'");
Token lbraceTok = current->previous;
Node *stmtList = blockStatements();
Node *tryBlock = wrapStmtsInBlock(stmtList, lbraceTok);
nodeAddChild(_try, tryBlock);
int numCatches = 0;
while (match(TOKEN_CATCH)) {
numCatches++;
Token catchTok = current->previous;
consume(TOKEN_LEFT_PAREN, "Expected '(' after keyword 'catch'");
Node *catchExpr = expression(); // should be constant expression (can be fully qualified)
Token identToken;
bool foundIdentToken = false;
if (match(TOKEN_IDENTIFIER)) { // should be variable
identToken = current->previous;
foundIdentToken = true;
}
consume(TOKEN_RIGHT_PAREN, "Expected ')' to end 'catch' expression");
consume(TOKEN_LEFT_BRACE, "Expected '{' after 'catch' expression");
lbraceTok = current->previous;
Node *catchStmtList = blockStatements();
Node *catchBlock = wrapStmtsInBlock(catchStmtList, lbraceTok);
node_type_t catchT = {
.type = NODE_STMT,
.kind = CATCH_STMT,
};
Node *catchStmt = createNode(catchT, catchTok, NULL);
nodeAddChild(catchStmt, catchExpr);
if (foundIdentToken) {
node_type_t varT = {
.type = NODE_EXPR,
.kind = VARIABLE_EXPR,
};
Node *varExpr = createNode(varT, identToken, NULL);
nodeAddChild(catchStmt, varExpr); // variable to be bound to in block
}
nodeAddChild(catchStmt, catchBlock);
nodeAddChild(_try, catchStmt);
}
// try { ... } catch { ... } else { ... }
if (match(TOKEN_ELSE)) {
if (numCatches == 0) {
errorAtCurrent("Try needs at least one catch statement with else");
}
Token elseTok = current->previous;
consume(TOKEN_LEFT_BRACE, "Expected '{' after keyword 'else'");
Token lbraceTok = current->previous;
Node *elseStmtList = blockStatements();
Node *elseBlock = wrapStmtsInBlock(elseStmtList, lbraceTok);
node_type_t tryElseT = {
.type = NODE_STMT,
.kind = TRY_ELSE_STMT,
};
Node *elseStmt = createNode(tryElseT, elseTok, NULL);
nodeAddChild(elseStmt, elseBlock);
nodeAddChild(_try, elseStmt);
}
// try { ... } ensure { ... }
if (match(TOKEN_ENSURE)) {
Token ensureTok = current->previous;
consume(TOKEN_LEFT_BRACE, "Expected '{' after keyword 'ensure'");
Token lbraceTok = current->previous;
Node *ensureStmtList = blockStatements();
Node *ensureBlock = wrapStmtsInBlock(ensureStmtList, lbraceTok);
node_type_t ensureT = {
.type = NODE_STMT,
.kind = ENSURE_STMT,
};
Node *ensureStmt = createNode(ensureT, ensureTok, NULL);
nodeAddChild(ensureStmt, ensureBlock);
nodeAddChild(_try, ensureStmt);
}
TRACE_END("tryStatement");
TRACE_END("statement");
return _try;
}
if (match(TOKEN_THROW)) {
Token throwTok = current->previous;
Node *expr = expression();
consume(TOKEN_SEMICOLON, "Expected ';' to end 'throw' statement");
node_type_t throwT = {
.type = NODE_STMT,
.kind = THROW_STMT,
};
Node *_throw = createNode(throwT, throwTok, NULL);
nodeAddChild(_throw, expr);
TRACE_END("statement");
return _throw;
}
if (match(TOKEN_CONTINUE)) {
Token contTok = current->previous;
node_type_t contT = {
.type = NODE_STMT,
.kind = CONTINUE_STMT,
};
Node *cont = createNode(contT, contTok, NULL);
consume(TOKEN_SEMICOLON, "Expected ';' after keyword 'continue'");
TRACE_END("statement");
return cont;
}
if (match(TOKEN_BREAK)) {
Token breakTok = current->previous;
node_type_t breakT = {
.type = NODE_STMT,
.kind = BREAK_STMT,
};
Node *breakNode = createNode(breakT, breakTok, NULL);
consume(TOKEN_SEMICOLON, "Expected ';' after keyword 'break'");
TRACE_END("statement");
return breakNode;
}
if (match(TOKEN_RETURN)) {
Token retTok = current->previous;
node_type_t retT = {
.type = NODE_STMT,
.kind = RETURN_STMT,
};
Node *retNode = createNode(retT, retTok, NULL);
if (match(TOKEN_SEMICOLON)) { // do nothing, no child
} else {
Node *retExpr = expression();
nodeAddChild(retNode, retExpr);
consume(TOKEN_SEMICOLON, "Expected ';' to end 'return' statement");
}
TRACE_END("statement");
return retNode;
}
if (match(TOKEN_IN)) {
Token inTok = current->previous;
node_type_t inT = {
.type = NODE_STMT,
.kind = IN_STMT,
};
Node *inNode = createNode(inT, inTok, NULL);
consume(TOKEN_LEFT_PAREN, "Expected '(' after keyword 'in'");
Node *expr = expression();
nodeAddChild(inNode, expr);
consume(TOKEN_RIGHT_PAREN, "Expected ')' after 'in' expression");
consume(TOKEN_LEFT_BRACE, "Expected '{' after 'in' expression");
Node *body = classOrModuleBody("inBody");
consume(TOKEN_RIGHT_BRACE, "Expected '}' to end in body");
nodeAddChild(inNode, body);
TRACE_END("statement");
return inNode;
}
Node *ret = expressionStatement(true);
TRACE_END("statement");
return ret;
}
// 'print' is already parsed.
static Node *printStatement() {
TRACE_START("printStatement");
node_type_t printType = {
.type = NODE_STMT,
.kind = PRINT_STMT,
};
Node *printNode = createNode(printType, current->previous, NULL);
Node *expr = expression();
consume(TOKEN_SEMICOLON, "Expected ';' after 'print' statement");
nodeAddChild(printNode, expr);
TRACE_END("printStatement");
return printNode;
}
// '{' is already parsed. Parse up until and including the ending '}'
static Node *blockStatements() {
TRACE_START("blockStatements");
node_type_t stmtListT = {
.type = NODE_STMT,
.kind = STMTLIST_STMT,
};
Node *stmtList = createNode(stmtListT, current->previous, NULL);
while (!isAtEnd() && !check(TOKEN_RIGHT_BRACE)) {
Node *decl = declaration();
nodeAddChild(stmtList, decl);
}
consume(TOKEN_RIGHT_BRACE, "Expected '}' to end block statement");
TRACE_END("blockStatements");
return stmtList;
}
static Node *expressionStatement(bool expectSemi) {
TRACE_START("expressionStatement");
Token tok = current->current;
Node *expr = expression();
node_type_t stmtT = {
.type = NODE_STMT,
.kind = EXPR_STMT,
};
Node *exprStmt = createNode(stmtT, tok, NULL);
nodeAddChild(exprStmt, expr);
if (expectSemi) {
consume(TOKEN_SEMICOLON, "Expected ';' after expression");
}
TRACE_END("expressionStatement");
return exprStmt;
}
// '{' already parsed. Continue parsing up to and including closing '}'
static Node *classOrModuleBody(const char *debugName) {
TRACE_START(debugName);
Token lbraceTok = current->previous;
node_type_t nType = {
.type = NODE_STMT,
.kind = STMTLIST_STMT,
};
Node *stmtListNode = createNode(nType, lbraceTok, NULL);
while (!isAtEnd() && !check(TOKEN_RIGHT_BRACE)) {
Node *decl;
if (check(TOKEN_IDENTIFIER) && peekTokN(1).type == TOKEN_LEFT_PAREN) {
decl = funDeclaration(FUNCTION_TYPE_METHOD);
} else if (check(TOKEN_IDENTIFIER) && peekTokN(1).type == TOKEN_EQUAL &&
peekTokN(2).type == TOKEN_LEFT_PAREN) {
decl = funDeclaration(FUNCTION_TYPE_SETTER);
} else if (check(TOKEN_IDENTIFIER) && peekTokN(1).type == TOKEN_LEFT_BRACE) {
decl = funDeclaration(FUNCTION_TYPE_GETTER);
} else if (check(TOKEN_CLASS) && peekTokN(1).type == TOKEN_IDENTIFIER && peekTokN(2).type == TOKEN_LEFT_PAREN) {
advance();
decl = funDeclaration(FUNCTION_TYPE_CLASS_METHOD);
} else {
decl = declaration();
}
nodeAddChild(stmtListNode, decl);
}
node_type_t blockType = {
.type = NODE_STMT,
.kind = BLOCK_STMT,
};
Node *block = createNode(blockType, lbraceTok, NULL);
nodeAddChild(block, stmtListNode);
TRACE_END(debugName);
return block;
}
// TOKEN_VAR is already consumed.
static Node *varDeclaration(void) {
TRACE_START("varDeclaration");
consume(TOKEN_IDENTIFIER, "Expected identifier after keyword 'var'");
Token identTok = current->previous;
if (isCapital(*tokStr(&identTok))) {
error("Variable names cannot start with a capital letter. That's for constants.");
}
node_type_t nType = {
.type = NODE_STMT,
.kind = VAR_STMT,
};
Node *varDecl = createNode(nType, identTok, NULL);
while (match(TOKEN_COMMA)) {
consume(TOKEN_IDENTIFIER, "Expected identifier (variable name) "
"after ',' in var declaration");
Token tok = current->previous;
Node *varNext = createNode(nType, tok, NULL);
nodeAddChild(varDecl, varNext);
}
if (match(TOKEN_EQUAL)) {
Node *expr = expression();
nodeAddChild(varDecl, expr);
} else {
// uninitialized variable, set to nil later on
}
consume(TOKEN_SEMICOLON, "Expected ';' after variable declaration");
TRACE_END("varDeclaration");
return varDecl;
}
static Node *expression(void) {
TRACE_START("expression");
Node *splatCall = NULL;
Node *toBlockCall = NULL;
if (current->inCallExpr && match(TOKEN_STAR)) {
node_type_t splatType = {
.type = NODE_EXPR,
.kind = SPLAT_EXPR
};
splatCall = createNode(splatType, current->previous, NULL);
}
if (match(TOKEN_AMP)) {
node_type_t toBlockT = {
.type = NODE_EXPR,
.kind = TO_BLOCK_EXPR
};
toBlockCall = createNode(toBlockT, current->previous, NULL);
}
Node *expr = assignment();
if (splatCall != NULL) {
nodeAddChild(splatCall, expr);
expr = splatCall;
} else if (toBlockCall != NULL) {
nodeAddChild(toBlockCall, expr);
expr = toBlockCall;
}
TRACE_END("expression");
return expr;
}
static vec_nodep_t *createNodeVec(void) {
vec_nodep_t *paramNodes = ALLOCATE(vec_nodep_t, 1);
vec_init(paramNodes);
return paramNodes;
}
static void freeParamNodesDataCb(Node *node) {
ASSERT(node->data);
vec_nodep_t *params = (vec_nodep_t*)node->data;
Node *param; int pidx = 0;
vec_foreach(params, param, pidx) {
freeNode(param, true);
}
vec_deinit(params);
FREE(vec_nodep_t, params);
}
// FUN keyword has already been parsed, for regular functions
static Node *funDeclaration(ParseFunctionType fnType) {
TRACE_START("funDeclaration");
Token nameTok = current->previous;
if (fnType != FUNCTION_TYPE_ANON && fnType != FUNCTION_TYPE_BLOCK) {
consume(TOKEN_IDENTIFIER, "Expect function name (identifier) after 'fun' keyword");
nameTok = current->previous;
}
if (fnType == FUNCTION_TYPE_SETTER) {
consume(TOKEN_EQUAL, "Expect '=' after setter method name");
}
vec_nodep_t *paramNodes = createNodeVec();
int numParams = 0;
int lastParamKind = -1;
bool inKwargs = false;
if (fnType != FUNCTION_TYPE_GETTER) {
if (fnType == FUNCTION_TYPE_BLOCK && check(TOKEN_LEFT_BRACE)) { // no args for block
// do nothing
} else {
consume(TOKEN_LEFT_PAREN, "Expect '(' after function name (identifier)");
}
while (true) {
if (match(TOKEN_IDENTIFIER)) { // regular/default/kwarg param
Token paramTok = current->previous;
node_type_t nType = {
.type = NODE_OTHER,
.kind = PARAM_NODE_REGULAR,
};
Node *n = NULL;
if (match(TOKEN_EQUAL)) { // default argument
if (inKwargs) {
errorAtCurrent("keyword parameters need to be final parameters");
}
nType.kind = PARAM_NODE_DEFAULT_ARG;
n = createNode(nType, paramTok, NULL);
Node *argExpr = expression();
nodeAddChild(n, argExpr);
} else if (match(TOKEN_COLON)) {
if (!inKwargs) inKwargs = true;
nType.kind = PARAM_NODE_KWARG;
n = createNode(nType, paramTok, NULL);
if (check(TOKEN_RIGHT_PAREN) || check(TOKEN_COMMA)) { // required keyword arg, no defaults
// no children
} else {
Node *argExpr = expression();
nodeAddChild(n, argExpr);
}
} else {
if (inKwargs) {
errorAtCurrent("keyword parameters need to be final parameters");
}
n = createNode(nType, paramTok, NULL);
}
vec_push(paramNodes, n);
numParams++;
lastParamKind = nType.kind;
if (!match(TOKEN_COMMA)) {
break;
}
} else if (match(TOKEN_STAR)) { // splat param
if (inKwargs) {
errorAtCurrent("keyword parameters need to be final parameters");
}
consume(TOKEN_IDENTIFIER, "Expect splat parameter to have a name");
Token paramTok = current->previous;
node_type_t nType = {
.type = NODE_OTHER,
.kind = PARAM_NODE_SPLAT,
};
Node *n = createNode(nType, paramTok, NULL);
vec_push(paramNodes, n);
numParams++;
lastParamKind = nType.kind;
if (!match(TOKEN_COMMA)) {
break;
}
} else if (match(TOKEN_AMP)) { // block param
consume(TOKEN_IDENTIFIER, "Expect block parameter to have a name");
Token paramTok = current->previous;
node_type_t nType = {
.type = NODE_OTHER,
.kind = PARAM_NODE_BLOCK,
};
Node *n = createNode(nType, paramTok, NULL);
vec_push(paramNodes, n);
numParams++;
lastParamKind = nType.kind;
if (!check(TOKEN_RIGHT_PAREN)) {
error("Expected block parameter to be last parameter");
}
} else {
break;
}
}
if (fnType == FUNCTION_TYPE_SETTER) {
if (numParams != 1 || lastParamKind != PARAM_NODE_REGULAR) {
errorAt(¤t->previous, "Expect a single regular parameter for setter function");
}
}
if (fnType == FUNCTION_TYPE_BLOCK && numParams == 0 && check(TOKEN_LEFT_BRACE)) {
// do nothing
} else {
consume(TOKEN_RIGHT_PAREN, "Expect ')' after function parameters");
}
}
consume(TOKEN_LEFT_BRACE, "Expect '{' after function parameter list");
Token lbrace = current->previous;
Node *stmtList = blockStmts();
node_type_t blockType = {
.type = NODE_STMT,
.kind = BLOCK_STMT,
};
Node *blockNode = createNode(blockType, lbrace, NULL);
nodeAddChild(blockNode, stmtList);
node_type_t funcType;
if (fnType == FUNCTION_TYPE_NAMED) {
funcType = (node_type_t){
.type = NODE_STMT,
.kind = FUNCTION_STMT,