-
Notifications
You must be signed in to change notification settings - Fork 1
/
compiler.c
1323 lines (1112 loc) · 38.1 KB
/
compiler.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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "compiler.h"
#include "disasm.h"
#include "memory.h"
#include "scanner.h"
typedef struct {
Token current;
Token previous;
bool hadError;
bool panicMode;
} Parser;
typedef enum {
PREC_NONE,
PREC_ASSIGNMENT, // =
PREC_OR, // or
PREC_AND, // and
PREC_EQUALITY, // == !=
PREC_COMPARISON, // < > <= >=
PREC_TERM, // + -
PREC_FACTOR, // * \ /
PREC_UNARY, // ! -
PREC_POSTFIX, // . () [] @ ^
} Precedence;
typedef void (*ParseFn)(bool canAssign);
typedef struct {
ParseFn prefix;
ParseFn infix;
Precedence precedence;
} ParseRule;
typedef struct {
Token name; // 12 bytes
int8_t depth; // implicit padding byte on 68k forces struct size 16 to
bool isCaptured; // allow shift instead of multiplication in offset calculation
} Local;
typedef enum {
TYPE_SCRIPT,
TYPE_FUN,
TYPE_LAMBDA,
TYPE_METHOD, // last 2 types allowed in classes only
TYPE_INIT,
} FunctionType;
typedef struct LoopInfo {
struct LoopInfo* enclosing;
int8_t scopeDepth;
int8_t breakCount;
int16_t breaks[MAX_BREAKS];
} LoopInfo;
typedef struct Compiler {
struct Compiler* enclosing;
ObjFunction* target;
FunctionType type;
Local locals[MAX_LOCALS];
Upvalue upvalues[MAX_UPVALUES];
int8_t scopeDepth;
uint8_t localCount;
LoopInfo* currentLoop;
} Compiler;
typedef struct ClassCompiler {
struct ClassCompiler* enclosing;
bool hasSuperclass;
} ClassCompiler;
static Parser parser;
static Compiler* currentComp;
static ClassCompiler* currentClass;
static Chunk* currentChunk(void) {
return ¤tComp->target->chunk;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Error reporting
////////////////////////////////////////////////////////////////////////////////////////////////////
static void errorAt(Token* token, const char* message) {
if (parser.panicMode)
return;
parser.panicMode = true;
printf("[line %d] Error", token->line);
if (token->type == TOKEN_EOF)
putstr(" at end");
else if (token->type != TOKEN_ERROR) {
// IDE68K's printf("%.*s") is broken
putstr(" at '");
putstrn(token->length, token->start);
putstr("'");
}
printf(": %s\n", message);
parser.hadError = true;
}
static void error(const char* message) {
errorAt(&parser.previous, message);
}
static void errorAtCurrent(const char* message) {
errorAt(&parser.current, message);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Token matching
////////////////////////////////////////////////////////////////////////////////////////////////////
static void advance(void) {
parser.previous = parser.current;
for (;;) {
parser.current = scanToken();
if (parser.current.type != TOKEN_ERROR)
break;
errorAtCurrent(parser.current.start);
}
}
static void consume(TokenType expected, const char* message) {
if (parser.current.type == expected) {
advance();
return;
}
errorAtCurrent(message);
}
static void consumeExp(TokenType expected, const char* context) {
if (parser.current.type == expected) {
advance();
return;
}
sprintf(buffer, "Expect '%c' %s %s.",
TOKEN_CHARS[expected],
expected == TOKEN_LEFT_BRACE || expected == TOKEN_LEFT_PAREN ? "before" : "after",
context);
errorAtCurrent(buffer);
}
static bool check(TokenType expected) {
return parser.current.type == expected;
}
static bool match(TokenType expected) {
if (parser.current.type != expected)
return false;
advance();
return true;
}
static void synchronize(void) {
parser.panicMode = false;
while (parser.current.type != TOKEN_EOF) {
if (parser.previous.type == TOKEN_SEMICOLON ||
parser.current.type >= TOKEN_BREAK) // Tokens to synchronize on
return;
advance();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Code emitting
////////////////////////////////////////////////////////////////////////////////////////////////////
static void emitByte(int byte) {
writeChunk(currentChunk(), byte, parser.previous.line);
}
static void emit2Bytes(int byte1, int byte2) {
emitByte(byte1);
emitByte(byte2);
}
static void emit3Bytes(int byte1, int byte2, int byte3) {
emitByte(byte1);
emitByte(byte2);
emitByte(byte3);
}
static void emitLoop(int loopStart) {
int offset;
emitByte(OP_LOOP);
offset = currentChunk()->count - loopStart + 2;
if (offset > UINT16_MAX)
error("Jump too large.");
emit2Bytes(offset >> 8, offset);
}
static int emitJump(int instruction) {
emit3Bytes(instruction, 0xff, 0xff);
return currentChunk()->count - 2;
}
static void emitReturn(void) {
if (currentComp->type == TYPE_INIT)
emit3Bytes(OP_GET_LOCAL, 0, OP_RETURN);
else
emitByte(OP_RETURN_NIL);
}
static int makeConstant(Value value) {
int constant = addConstant(currentChunk(), value);
if (constant > UINT8_MAX) {
error("Too many constants in one chunk.");
return 0;
}
return constant;
}
static void emitConstant(Value value) {
if (value == INT_VAL(0)) emitByte(OP_ZERO);
else if (value == INT_VAL(1)) emitByte(OP_ONE);
else emit2Bytes(OP_CONSTANT, makeConstant(value));
}
static void patchJump(int offset) {
// -2 to adjust for the bytecode for the jump offset itself.
int jump = currentChunk()->count - offset - 2;
if (jump > UINT16_MAX)
error("Jump too large.");
currentChunk()->code[offset] = jump >> 8;
currentChunk()->code[offset + 1] = jump;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Compiler scoping
////////////////////////////////////////////////////////////////////////////////////////////////////
static void initCompiler(Compiler* compiler, FunctionType type) {
Local* local;
compiler->enclosing = currentComp;
compiler->target = NULL;
compiler->type = type;
compiler->localCount = 0;
compiler->scopeDepth = 0;
compiler->target = makeFunction();
compiler->currentLoop = NULL;
currentComp = compiler;
if (type != TYPE_SCRIPT) {
if (type == TYPE_LAMBDA)
currentComp->target->name = INT_VAL(vm.lambdaCount++);
else
currentComp->target->name =
OBJ_VAL(makeString(parser.previous.start, parser.previous.length));
}
local = ¤tComp->locals[currentComp->localCount++];
local->depth = 0;
local->isCaptured = false;
if (type >= TYPE_METHOD) {
local->name.start = "this";
local->name.length = 4;
} else {
local->name.start = "";
local->name.length = 0;
}
}
static ObjFunction* endCompiler(bool returnExpr) {
ObjFunction* function = currentComp->target;
if (returnExpr)
emitByte(OP_RETURN);
else
emitReturn();
freezeChunk(currentChunk());
#ifdef LOX_DBG
if (vm.debug_print_code && !parser.hadError)
disassembleChunk(currentChunk(), functionName(function));
#endif
currentComp = currentComp->enclosing;
return function;
}
static void beginScope(void) {
currentComp->scopeDepth++;
}
static void endScope(void) {
currentComp->scopeDepth--;
while (currentComp->localCount > 0 &&
currentComp->locals[currentComp->localCount - 1].depth > currentComp->scopeDepth) {
if (currentComp->locals[currentComp->localCount - 1].isCaptured)
emitByte(OP_CLOSE_UPVALUE);
else
emitByte(OP_POP);
currentComp->localCount--;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Forward declarations
////////////////////////////////////////////////////////////////////////////////////////////////////
static void expression(void);
static void statement(bool topLevel);
static void declaration(bool topLevel);
static void function(FunctionType type);
static void parsePrecedence(Precedence precedence);
static int argumentList(bool* isVarArg, TokenType terminator);
static int identifierConstant(Token* name);
static void binary(bool canAssign);
////////////////////////////////////////////////////////////////////////////////////////////////////
// Expressions
////////////////////////////////////////////////////////////////////////////////////////////////////
static void call(bool canAssign) {
bool isVarArg = false;
int argCount = argumentList(&isVarArg, TOKEN_RIGHT_PAREN);
if (isVarArg)
emit2Bytes(OP_VCALL, argCount);
else if (argCount <= 2)
emitByte(OP_CALL0 + argCount); // special case 0, 1, or 2 args
else
emit2Bytes(OP_CALL, argCount);
}
static void dot(bool canAssign) {
int pname;
int argCount;
bool isVarArg = false;
consume(TOKEN_IDENTIFIER, "Expect property name after '.'.");
pname = identifierConstant(&parser.previous);
if (canAssign && match(TOKEN_EQUAL)) {
expression();
emit2Bytes(OP_SET_PROPERTY, pname);
} else if (match(TOKEN_LEFT_PAREN)) {
argCount = argumentList(&isVarArg, TOKEN_RIGHT_PAREN);
emit3Bytes(isVarArg ? OP_VINVOKE : OP_INVOKE, pname, argCount);
} else
emit2Bytes(OP_GET_PROPERTY, pname);
}
static void slice(bool canAssign) {
if (match(TOKEN_RIGHT_BRACKET))
emitConstant(INT_VAL(INT32_MAX>>1));
else {
expression();
consumeExp(TOKEN_RIGHT_BRACKET, "slice");
}
if (canAssign && match(TOKEN_EQUAL)) {
error("Invalid assignment target.");
return;
} else
emitByte(OP_GET_SLICE);
}
static void index_(bool canAssign) {
if (match(TOKEN_COLON)) {
emitConstant(INT_VAL(0));
slice(canAssign);
} else {
expression();
if (match(TOKEN_COLON))
slice(canAssign);
else {
consumeExp(TOKEN_RIGHT_BRACKET, "index");
if (canAssign && match(TOKEN_EQUAL)) {
expression();
emitByte(OP_SET_INDEX);
} else
emitByte(OP_GET_INDEX);
}
}
}
static void iter(bool canAssign) {
TokenType accessor = parser.previous.type;
if (canAssign && match(TOKEN_EQUAL)) {
if (accessor == TOKEN_HAT) {
expression();
emitByte(OP_SET_ITVAL);
} else
error("Invalid assignment target.");
} else
emitByte(accessor == TOKEN_HAT ? OP_GET_ITVAL : OP_GET_ITKEY);
}
static void litNil(bool canAssign) {
emitByte(OP_NIL);
}
static void litFalse(bool canAssign) {
emitByte(OP_FALSE);
}
static void litTrue(bool canAssign) {
emitByte(OP_TRUE);
}
static void grouping(bool canAssign) {
expression();
consumeExp(TOKEN_RIGHT_PAREN, "expression");
}
static void intNum(bool canAssign) {
Value value = parseInt(parser.previous.start, false);
emitConstant(value);
}
static void realNum(bool canAssign) {
Value value;
errno = 0;
value = makeReal(strToReal(parser.previous.start, NULL));
if (errno != 0)
error("Real constant overflow.");
emitConstant(value);
}
static void string(bool canAssign) {
// Redundant code in IDE68K without str local variable?
ObjString* str = makeString(parser.previous.start + 1, parser.previous.length - 2);
emitConstant(OBJ_VAL(str));
}
static int identifierConstant(Token* name) {
// Redundant code in IDE68K without str local variable?
ObjString* str = makeString(name->start, name->length);
return makeConstant(OBJ_VAL(str));
}
static void list(bool canAssign) {
bool isVarArg = false;
int argCount = argumentList(&isVarArg, TOKEN_RIGHT_BRACKET);
emit2Bytes(isVarArg ? OP_VLIST : OP_LIST, argCount);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Variable handling
////////////////////////////////////////////////////////////////////////////////////////////////////
static bool identifiersEqual(Token* a, Token* b) {
if (a->length != b->length)
return false;
return fix_memcmp(a->start, b->start, a->length) == 0;
}
static int resolveLocal(Compiler* compiler, Token* name) {
int i;
Local* local;
for (i = compiler->localCount - 1; i >= 0; i--) {
local = &compiler->locals[i];
if (identifiersEqual(name, &local->name)) {
if (local->depth == -1)
error("Can't read local variable in its own initializer.");
return i;
}
}
return -1;
}
static int addUpvalue(Compiler* compiler, int index, bool isLocal) {
int upvalueCount = compiler->target->upvalueCount;
Upvalue newUpvalue = isLocal ? (index | LOCAL_MASK) : index;
int i;
for (i = 0; i < upvalueCount; i++)
if (compiler->upvalues[i] == newUpvalue)
return i;
if (upvalueCount == MAX_UPVALUES) {
error("Too many upvalues in function.");
return 0;
}
compiler->upvalues[upvalueCount] = newUpvalue;
return compiler->target->upvalueCount++;
}
static int resolveUpvalue(Compiler* compiler, Token* name) {
int local, upvalue;
if (compiler->enclosing == NULL)
return -1;
local = resolveLocal(compiler->enclosing, name);
if (local != -1) {
compiler->enclosing->locals[local].isCaptured = true;
return addUpvalue(compiler, local, true);
}
upvalue = resolveUpvalue(compiler->enclosing, name);
if (upvalue != -1)
return addUpvalue(compiler, upvalue, false);
return -1;
}
static void addLocal(Token name) {
Local* local;
if (currentComp->localCount == MAX_LOCALS) {
error("Too many local variables in function.");
return;
}
local = ¤tComp->locals[currentComp->localCount++];
local->name = name;
local->depth = -1;
local->isCaptured = false;
}
static void declareVariable(void) {
Token* name;
int i;
Local* local;
if (currentComp->scopeDepth == 0)
return;
name = &parser.previous;
for (i = currentComp->localCount - 1; i >= 0; i--) {
local = ¤tComp->locals[i];
if (local->depth != -1 && local->depth < currentComp->scopeDepth)
break;
if (identifiersEqual(name, &local->name))
error("Already a variable with this name in this scope.");
}
addLocal(*name);
}
static void namedVariable(Token name, bool canAssign) {
int getOp, setOp;
int arg = resolveLocal(currentComp, &name);
if (arg != -1) {
getOp = OP_GET_LOCAL;
setOp = OP_SET_LOCAL;
} else if ((arg = resolveUpvalue(currentComp, &name)) != -1) {
getOp = OP_GET_UPVALUE;
setOp = OP_SET_UPVALUE;
} else {
arg = identifierConstant(&name);
getOp = OP_GET_GLOBAL;
setOp = OP_SET_GLOBAL;
}
if (canAssign && match(TOKEN_EQUAL)) {
expression();
emit2Bytes(setOp, arg);
} else
emit2Bytes(getOp, arg);
}
static void variable(bool canAssign) {
namedVariable(parser.previous, canAssign);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Expressions continued
////////////////////////////////////////////////////////////////////////////////////////////////////
static Token syntheticToken(const char* text) {
Token token;
token.start = text;
token.length = (int)strlen(text);
return token;
}
static void keySuper(bool canAssign) {
int mname;
int argCount;
bool isVarArg = false;
if (currentClass == NULL)
error("Can't use 'super' outside of a class.");
else if (!currentClass->hasSuperclass)
error("Can't use 'super' in a class with no superclass.");
consumeExp(TOKEN_DOT, "'super'");
consume(TOKEN_IDENTIFIER, "Expect superclass method name.");
mname = identifierConstant(&parser.previous);
namedVariable(syntheticToken("this"), false);
if (match(TOKEN_LEFT_PAREN)) {
argCount = argumentList(&isVarArg, TOKEN_RIGHT_PAREN);
namedVariable(syntheticToken("super"), false);
emit3Bytes(isVarArg ? OP_VSUPER_INVOKE : OP_SUPER_INVOKE, mname, argCount);
} else {
namedVariable(syntheticToken("super"), false);
emit2Bytes(OP_GET_SUPER, mname);
}
}
static void keyThis(bool canAssign) {
if (currentClass == NULL) {
error("Can't use 'this' outside of a class.");
return;
}
variable(false);
}
static void opAnd(bool canAssign) {
int endJump = emitJump(OP_JUMP_AND);
parsePrecedence(PREC_AND);
patchJump(endJump);
}
static void opOr(bool canAssign) {
int endJump = emitJump(OP_JUMP_OR);
parsePrecedence(PREC_OR);
patchJump(endJump);
}
static void not(bool canAssign) {
parsePrecedence(PREC_UNARY);
emitByte(OP_NOT);
}
static void negative(bool canAssign) {
emitConstant(INT_VAL(0));
parsePrecedence(PREC_UNARY);
emitByte(OP_SUB);
}
static void lambda(bool canAssign) {
function(TYPE_LAMBDA);
}
static void buildThunk(void) {
Compiler compiler;
ObjFunction* function;
int i;
initCompiler(&compiler, TYPE_LAMBDA);
beginScope();
expression();
function = endCompiler(true);
emit2Bytes(OP_CLOSURE, makeConstant(OBJ_VAL(function)));
for (i = 0; i < function->upvalueCount; i++)
emitByte(compiler.upvalues[i]);
}
static void handler(bool canAssign) {
consumeExp(TOKEN_LEFT_PAREN, "expression");
buildThunk();
consumeExp(TOKEN_COLON, "expression");
expression();
consumeExp(TOKEN_RIGHT_PAREN, "handler");
emitByte(OP_CALL_HAND);
}
static void ifExpr(bool canAssign) {
int thenJump, elseJump;
consumeExp(TOKEN_LEFT_PAREN, "condition");
expression();
consumeExp(TOKEN_COLON, "condition");
thenJump = emitJump(OP_JUMP_FALSE);
expression();
consumeExp(TOKEN_COLON, "consequent");
elseJump = emitJump(OP_JUMP);
patchJump(thenJump);
expression();
patchJump(elseJump);
consumeExp(TOKEN_RIGHT_PAREN, "alternative");
}
static void dynvar(bool canAssign) {
int vname;
consumeExp(TOKEN_LEFT_PAREN, "variable");
consume(TOKEN_IDENTIFIER, "Expect variable.");
vname = identifierConstant(&parser.previous);
consumeExp(TOKEN_EQUAL, "variable");
expression();
consumeExp(TOKEN_COLON, "binding");
buildThunk();
consumeExp(TOKEN_RIGHT_PAREN, "expression");
emit2Bytes(OP_CALL_BIND, vname);
}
#define X {NULL, NULL, PREC_NONE} // Coded explicitly, not by Pratt parsing rule
#define PRE(rule) {rule, NULL, PREC_NONE} // Using prefix rule only
static const ParseRule rules[] = {
// Keep same order as TokenType enum values in scanner.h
// since C89 doesn't support array init by index values.
// single character punctuation ***********************************
/* [TOKEN_LEFT_PAREN] = */ {grouping, call, PREC_POSTFIX},
/* [TOKEN_RIGHT_PAREN] = */ X,
/* [TOKEN_LEFT_BRACE] = */ X,
/* [TOKEN_RIGHT_BRACE] = */ X,
/* [TOKEN_LEFT_BRACKET] = */ {list, index_, PREC_POSTFIX},
/* [TOKEN_RIGHT_BRACKET] = */ X,
/* [TOKEN_COMMA] = */ X,
/* [TOKEN_DOT] = */ {NULL, dot, PREC_POSTFIX},
/* [TOKEN_SEMICOLON] = */ X,
/* [TOKEN_COLON] = */ X,
/* [TOKEN_EQUAL] = */ X,
// single character operators *************************************
/* [TOKEN_PLUS] = */ {NULL, binary, PREC_TERM},
/* [TOKEN_MINUS] = */ {negative, binary, PREC_TERM},
/* [TOKEN_STAR] = */ {NULL, binary, PREC_FACTOR},
/* [TOKEN_SLASH] = */ {NULL, binary, PREC_FACTOR},
/* [TOKEN_BACKSLASH] = */ {NULL, binary, PREC_FACTOR},
/* [TOKEN_AT] = */ {NULL, iter, PREC_POSTFIX},
/* [TOKEN_HAT] = */ {NULL, iter, PREC_POSTFIX},
/* [TOKEN_BANG] = */ PRE(not),
/* [TOKEN_GREATER] = */ {NULL, binary, PREC_COMPARISON},
/* [TOKEN_LESS] = */ {NULL, binary, PREC_COMPARISON},
// double character operators *************************************
/* [TOKEN_BANG_EQUAL] = */ {NULL, binary, PREC_EQUALITY},
/* [TOKEN_EQUAL_EQUAL] = */ {NULL, binary, PREC_EQUALITY},
/* [TOKEN_GREATER_EQUAL] = */ {NULL, binary, PREC_COMPARISON},
/* [TOKEN_LESS_EQUAL] = */ {NULL, binary, PREC_COMPARISON},
/* [TOKEN_DOT_DOT] = */ X,
/* [TOKEN_ARROW] = */ X,
// literals *******************************************************
/* [TOKEN_IDENTIFIER] = */ PRE(variable),
/* [TOKEN_STRING] = */ PRE(string),
/* [TOKEN_INT] = */ PRE(intNum),
/* [TOKEN_REAL] = */ PRE(realNum),
// specials *******************************************************
/* [TOKEN_ERROR] = */ X,
/* [TOKEN_EOF] = */ X,
// non-syncing keywords *******************************************
/* [TOKEN_AND] = */ {NULL, opAnd, PREC_AND},
/* [TOKEN_DYNVAR] = */ PRE(dynvar),
/* [TOKEN_ELSE] = */ X,
/* [TOKEN_FALSE] = */ PRE(litFalse),
/* [TOKEN_HANDLE] = */ PRE(handler),
/* [TOKEN_NIL] = */ PRE(litNil),
/* [TOKEN_OR] = */ {NULL, opOr, PREC_OR},
/* [TOKEN_SUPER] = */ PRE(keySuper),
/* [TOKEN_THIS] = */ PRE(keyThis),
/* [TOKEN_TRUE] = */ PRE(litTrue),
/* [TOKEN_WHEN] = */ X,
// syncing keywords ***********************************************
/* [TOKEN_BREAK] = */ X,
/* [TOKEN_CASE] = */ X,
/* [TOKEN_CLASS] = */ X,
/* [TOKEN_FOR] = */ X,
/* [TOKEN_FUN] = */ PRE(lambda),
/* [TOKEN_IF] = */ PRE(ifExpr),
/* [TOKEN_PRINT] = */ X,
/* [TOKEN_RETURN] = */ X,
/* [TOKEN_VAR] = */ X,
/* [TOKEN_WHILE] = */ X,
};
#define getRule(type) (&rules[type])
static void binary(bool canAssign) {
TokenType operatorType = parser.previous.type;
const ParseRule* rule = getRule(operatorType);
parsePrecedence((Precedence)(rule->precedence + 1));
switch (operatorType) {
case TOKEN_BANG_EQUAL: emit2Bytes(OP_EQUAL, OP_NOT); break;
case TOKEN_EQUAL_EQUAL: emitByte(OP_EQUAL); break;
case TOKEN_GREATER: emit2Bytes(OP_SWAP, OP_LESS); break;
case TOKEN_LESS_EQUAL: emit3Bytes(OP_SWAP, OP_LESS, OP_NOT); break;
case TOKEN_LESS: emitByte(OP_LESS); break;
case TOKEN_GREATER_EQUAL: emit2Bytes(OP_LESS, OP_NOT); break;
case TOKEN_PLUS: emitByte(OP_ADD); break;
case TOKEN_MINUS: emitByte(OP_SUB); break;
case TOKEN_STAR: emitByte(OP_MUL); break;
case TOKEN_SLASH: emitByte(OP_DIV); break;
case TOKEN_BACKSLASH: emitByte(OP_MOD); break;
default: return; // Unreachable
}
}
static void parsePrecedence(Precedence precedence) {
ParseFn prefixRule;
ParseFn infixRule;
bool canAssign;
advance();
prefixRule = getRule(parser.previous.type)->prefix;
if (prefixRule == NULL) {
error("Expect expression.");
return;
}
canAssign = precedence <= PREC_ASSIGNMENT;
(*prefixRule)(canAssign);
while (precedence <= getRule(parser.current.type)->precedence) {
advance();
infixRule = getRule(parser.previous.type)->infix;
(*infixRule)(canAssign);
}
if (canAssign && match(TOKEN_EQUAL))
error("Invalid assignment target.");
}
static int parseVariable(const char* errorMessage) {
consume(TOKEN_IDENTIFIER, errorMessage);
declareVariable();
if (currentComp->scopeDepth > 0)
return 0;
return identifierConstant(&parser.previous);
}
static void markInitialized(void) {
if (currentComp->scopeDepth == 0)
return;
currentComp->locals[currentComp->localCount - 1].depth = currentComp->scopeDepth;
}
static void defineVariable(int global) {
if (currentComp->scopeDepth > 0) {
markInitialized();
return;
}
emit2Bytes(OP_DEF_GLOBAL, global);
}
static int argumentList(bool* isVarArg, TokenType terminator) {
int argCount = 0;
if (!check(terminator)) {
do {
if (match(TOKEN_DOT_DOT)) {
// First UNPACK, introduce count of arguments from lists
if (!*isVarArg)
emitConstant(INT_VAL(0));
*isVarArg = true;
expression();
emitByte(OP_UNPACK); // this also adapts list arguments count
} else {
expression();
if (*isVarArg)
emitByte(OP_SWAP); // bubble list arguments count to TOS
if (argCount == UINT8_MAX)
error("Too many arguments.");
argCount++;
}
} while (match(TOKEN_COMMA));
}
consumeExp(terminator, "arguments");
return argCount;
}
static void expression(void) {
CHECK_STACKOVERFLOW
parsePrecedence(PREC_ASSIGNMENT);
}
static void block(void) {
while (!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF))
declaration(false);
consumeExp(TOKEN_RIGHT_BRACE, "block");
}
static void function(FunctionType type) {
Compiler compiler;
ObjFunction* function;
int i;
int parameter;
uint8_t restParm = 0;
CHECK_STACKOVERFLOW
initCompiler(&compiler, type);
beginScope();
consumeExp(TOKEN_LEFT_PAREN, "parameters");
if (!check(TOKEN_RIGHT_PAREN)) {
do {
if (restParm)
errorAtCurrent("No more parameters allowed after rest parameter.");
if (++currentComp->target->arity >= MAX_LOCALS)
errorAtCurrent("Too many parameters.");
if (match(TOKEN_DOT_DOT))
restParm = REST_PARM_MASK;
parameter = parseVariable("Expect parameter name.");
defineVariable(parameter);
} while (match(TOKEN_COMMA));
}
consumeExp(TOKEN_RIGHT_PAREN, "parameters");
currentComp->target->arity |= restParm;
if (match(TOKEN_ARROW)) {
if (type == TYPE_INIT)
error("Can't return a value from an initializer.");
expression();
function = endCompiler(true);
} else {
consumeExp(TOKEN_LEFT_BRACE, "function body");
block();
function = endCompiler(false);
}
emit2Bytes(OP_CLOSURE, makeConstant(OBJ_VAL(function)));
for (i = 0; i < function->upvalueCount; i++)
emitByte(compiler.upvalues[i]);
}
static void method(void) {
int mname;
FunctionType type = TYPE_METHOD;
consume(TOKEN_IDENTIFIER, "Expect method name.");
mname = identifierConstant(&parser.previous);
if (parser.previous.length == 4 && fix_memcmp(parser.previous.start, "init", 4) == 0)
type = TYPE_INIT;
function(type);
emit2Bytes(OP_METHOD, mname);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// Declarations
////////////////////////////////////////////////////////////////////////////////////////////////////
static void classDeclaration(void) {
int nameConstant;
Token className;
ClassCompiler classCompiler;
consume(TOKEN_IDENTIFIER, "Expect class name.");
className = parser.previous;
nameConstant = identifierConstant(&className);
declareVariable();
emit2Bytes(OP_CLASS, nameConstant);
defineVariable(nameConstant);
classCompiler.enclosing = currentClass;
classCompiler.hasSuperclass = false;
currentClass = &classCompiler;
if (match(TOKEN_LESS)) {
// superclass can be any expression!
expression();
beginScope();
addLocal(syntheticToken("super"));
defineVariable(0);
namedVariable(className, false);
emitByte(OP_INHERIT);
classCompiler.hasSuperclass = true;
}
namedVariable(className, false);
consumeExp(TOKEN_LEFT_BRACE, "class body");
while (!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF))
method();
consumeExp(TOKEN_RIGHT_BRACE, "class body");
emitByte(OP_POP);
if (classCompiler.hasSuperclass)
endScope();
currentClass = currentClass->enclosing;
}
static void funDeclaration(void) {
int fname = parseVariable("Expect function name.");
markInitialized();
function(TYPE_FUN);
defineVariable(fname);
}
static void varDeclaration(void) {
int vname;
do {
vname = parseVariable("Expect variable name.");
if (match(TOKEN_EQUAL))
expression();
else
emitByte(OP_NIL);
defineVariable(vname);
} while (match(TOKEN_COMMA));