/
compiler.c
4146 lines (3631 loc) · 136 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
/**
* @file compiler.c
* @brief Single-pass bytecode compiler.
*
* Kuroko's compiler is still very reminiscent of its CLox roots and uses
* the same parsing strategy, so if you have read the third chapter of
* Bob's "Crafting Interpreters", this should should be fairly easy to
* understand. One important thing that Kuroko's compiler does differently
* is implement rewinding, which allows for conservative reparsing and
* recompilation of subexpressions that have already been parsed. This is
* used to compile ternaries, multiple assignments, and the expression value
* in generator and comprehension expressions.
*
* Kuroko has several levels of parse precedence, including three different
* levels indicative of assignments. Most expressions start from the TERNARY
* or COMMA level, but top-level expression statements and assignment values
* start at the highest level of ASSIGNMENT, which allows for multiple
* assignment targets. Expressions parsed from the MUST_ASSIGN level are
* assignment targets in a multiple assignment. Expression parsed from
* the CAN_ASSIGN level are single assignment targets.
*
* String compilation manages escape sequence processing, so string tokens
* received from the scanner are not directly converted to string constants.
* F-strings are compiled as expressions generating a regular string.
*
* Kuroko's bytecode supports variable operand sizes using paired "short" and
* "long" opcodes. To ease the output of these opcodes, the EMIT_OPERAND_OP
* macro will generate the appropriate opcode given an operand.
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <kuroko/kuroko.h>
#include <kuroko/compiler.h>
#include <kuroko/memory.h>
#include <kuroko/scanner.h>
#include <kuroko/object.h>
#include <kuroko/debug.h>
#include <kuroko/vm.h>
#include <kuroko/util.h>
#include "private.h"
#include "opcode_enum.h"
/**
* @brief Token parser state.
*
* The parser is fairly simplistic, requiring essentially
* no lookahead. 'previous' is generally the currently-parsed
* token: whatever was matched by @ref match. 'current' is the
* token to be parsed, and can be examined with @ref check.
*/
typedef struct {
KrkToken current; /**< @brief Token to be parsed. */
KrkToken previous; /**< @brief Last token matched, consumed, or advanced over. */
char hadError; /**< @brief Flag indicating if the parser encountered an error. */
unsigned int eatingWhitespace; /**< @brief Depth of whitespace-ignoring parse functions. */
} Parser;
/**
* @brief Parse precedence ladder.
*
* Lower values (values listed first) bind more loosely than
* higher values (values listed later).
*/
typedef enum {
PREC_NONE,
PREC_ASSIGNMENT, /**< `=` */
PREC_COMMA, /**< `,` */
PREC_MUST_ASSIGN,/**< Multple assignment target */
PREC_CAN_ASSIGN, /**< Single assignment target, inside parens */
PREC_DEL_TARGET, /**< Like above, but del target list */
PREC_TERNARY, /**< TrueBranch `if` Condition `else` FalseBranch */
PREC_OR, /**< `or` */
PREC_AND, /**< `and` */
PREC_NOT, /**< `not` */
PREC_COMPARISON, /**< `< > <= >= in not in` */
PREC_BITOR, /**< `|` */
PREC_BITXOR, /**< `^` */
PREC_BITAND, /**< `&` */
PREC_SHIFT, /**< `<< >>` */
PREC_SUM, /**< `+ -` */
PREC_TERM, /**< `* / %` */
PREC_FACTOR, /**< `+ - ~ !` */
PREC_EXPONENT, /**< `**` */
PREC_PRIMARY, /**< `. () []` */
} Precedence;
/**
* @brief Expression type.
*
* Determines how an expression should be compiled.
*/
typedef enum {
EXPR_NORMAL, /**< This expression can not be an assignment target. */
EXPR_CAN_ASSIGN, /**< This expression may be an assignment target, check for assignment operators at the end. */
EXPR_ASSIGN_TARGET, /**< This expression is definitely an assignment target or chained to one. */
EXPR_DEL_TARGET, /**< This expression is in the target list of a 'del' statement. */
EXPR_METHOD_CALL, /**< This expression is the parameter list of a method call; only used by @ref dot and @ref call */
EXPR_CLASS_PARAMETERS,
} ExpressionType;
struct RewindState;
struct GlobalState;
/**
* @brief Subexpression parser function.
*
* Used by the parse rule table for infix and prefix expression
* parser functions. The argument passed is the @ref ExpressionType
* to compile the expression as.
*/
typedef void (*ParseFn)(struct GlobalState *, int, struct RewindState *);
/**
* @brief Parse rule table entry.
*
* Maps tokens to prefix and infix rules. Precedence values here
* are for the infix parsing.
*/
typedef struct {
ParseFn prefix; /**< @brief Parse function to call when this token appears at the start of an expression. */
ParseFn infix; /**< @brief Parse function to call when this token appears after an expression. */
Precedence precedence; /**< @brief Precedence ordering for Pratt parsing, @ref Precedence */
} ParseRule;
/**
* @brief Local variable reference.
*
* Tracks the names and scope depth of local variables.
* Locals are mapped to stack locations by their index
* in the compiler's locals array.
*/
typedef struct {
KrkToken name; /**< @brief Token that provided the name for this variable. */
ssize_t depth; /**< @brief Stack depth, or -1 if uninitialized. */
char isCaptured; /**< @brief Flag indicating if the variable is captured by a closure. */
} Local;
/**
* @brief Closure upvalue reference.
*
* Tracks references to local variables from enclosing scopes.
*/
typedef struct {
size_t index; /**< @brief Enclosing local index or upvalue index. */
char isLocal; /**< @brief Flag indicating if @ref index is a local or upvalue index. */
KrkToken name; /**< @brief Name for direct lookup. Mainly for non-automatically-populated upvalue cells. */
} Upvalue;
/**
* @brief Function compilation type.
*
* Determines the context of the function being compiled,
* as different kinds of functions have different semantics.
*/
typedef enum {
TYPE_FUNCTION, /**< Normal 'def' function. */
TYPE_MODULE, /**< Top level of a script. */
TYPE_METHOD, /**< Class method with `self` binding. */
TYPE_INIT, /**< Class \__init__ */
TYPE_LAMBDA, /**< Lambda expression body, must be a single expression. */
TYPE_STATIC, /**< Static class method, no `self` binding. */
TYPE_CLASS, /**< Class body, not a normal series of declarations. */
TYPE_CLASSMETHOD, /**< Class method, binds first argument to the class. */
TYPE_COROUTINE, /**< `await def` function. */
TYPE_COROUTINE_METHOD, /**< `await def` class method. */
} FunctionType;
/**
* @brief Linked list of indices.
*
* Primarily used to track the indices of class properties
* so that they can be referenced again later. @ref ind
* will be the index of an identifier constant.
*/
struct IndexWithNext {
size_t ind; /**< @brief Index of an identifier constant. */
struct IndexWithNext * next; /**< @brief Linked list next pointer. */
};
/**
* @brief Tracks 'break' and 'continue' statements.
*/
struct LoopExit {
int offset; /**< @brief Offset of the jump expression to patch. */
KrkToken token; /**< @brief Token for this exit statement, so its location can be printed in an error message. */
};
/**
* @brief Subcompiler state.
*
* Each function is compiled in its own context, with its
* own codeobject, locals, type, scopes, etc.
*/
typedef struct Compiler {
struct Compiler * enclosing; /**< @brief Enclosing function compiler, or NULL for a module. */
KrkCodeObject * codeobject; /**< @brief Bytecode emitter */
FunctionType type; /**< @brief Type of function being compiled. */
size_t scopeDepth; /**< @brief Depth of nested scope blocks. */
size_t localCount; /**< @brief Total number of local variables. */
size_t localsSpace; /**< @brief Space in the locals array. */
Local * locals; /**< @brief Array of local variable references. */
size_t upvaluesSpace; /**< @brief Space in the upvalues array. */
Upvalue * upvalues; /**< @brief Array of upvalue references. Count is stored in the codeobject. */
size_t loopLocalCount; /**< @brief Tracks how many locals to pop off the stack when exiting a loop. */
size_t breakCount; /**< @brief Number of break statements. */
size_t breakSpace; /**< @brief Space in breaks array. */
struct LoopExit * breaks; /**< @brief Array of loop exit instruction indices for break statements. */
size_t continueCount; /**< @brief Number of continue statements. */
size_t continueSpace; /**< @brief Space in continues array. */
struct LoopExit * continues; /**< @brief Array of loop exit instruction indices for continue statements. */
size_t localNameCapacity; /**< @brief How much space is available in the codeobject's local names table. */
struct IndexWithNext * properties; /**< @brief Linked list of class property constant indices. */
struct Compiler * enclosed; /**< @brief Subcompiler we are enclosing, need for type annotation compilation. */
size_t annotationCount; /**< @brief Number of type annotations found while compiling function signature. */
int delSatisfied; /**< @brief Flag indicating if a 'del' target has been completed. */
size_t optionsFlags; /**< @brief Special __options__ imports; similar to __future__ in Python */
int unnamedArgs; /**< @brief Number of positional arguments that will not be assignable through keywords */
} Compiler;
#define OPTIONS_FLAG_COMPILE_TIME_BUILTINS (1 << 0)
#define OPTIONS_FLAG_NO_IMPLICIT_SELF (1 << 1)
/**
* @brief Class compilation context.
*
* Allows for things like @ref super to be bound correctly.
* Also allows us to establish qualified names for functions
* and nested class definitions.
*/
typedef struct ClassCompiler {
struct ClassCompiler * enclosing; /**< @brief Enclosing class scope. */
KrkToken name; /**< @brief Name of the current class. */
int hasAnnotations; /**< @brief Flag indicating if an annotation dictionary has been attached to this class. */
} ClassCompiler;
/**
* @brief Bytecode emitter backtracking breadcrumb.
*
* Records the state of the bytecode emitter so it may be rewound
* when an expression needs to be re-parsed. Allows us to implement
* backtracking to compile the inner expression of a comprehension,
* the left hand side of a ternary, or the targets list of a
* complex assignment.
*
* We rewind the bytecode, line mapping, and constants table,
* so that we don't keep around duplicate constants or debug info.
*/
typedef struct ChunkRecorder {
size_t count; /**< @brief Offset into the bytecode */
size_t lines; /**< @brief Offset into the line map */
size_t constants; /**< @brief Number of constants in the constants table */
} ChunkRecorder;
/**
* @brief Compiler emit and parse state prior to this expression.
*
* Used to rewind the parser for ternary and comma expressions.
*/
typedef struct RewindState {
ChunkRecorder before; /**< @brief Bytecode and constant table output offsets. */
KrkScanner oldScanner; /**< @brief Scanner cursor state. */
Parser oldParser; /**< @brief Previous/current tokens. */
} RewindState;
typedef struct GlobalState {
KrkInstance inst; /**< @protected @brief Base instance */
Parser parser; /**< @brief Parser state */
KrkScanner scanner; /**< @brief Scanner state */
Compiler * current; /**< @brief Current compiler (in-progress code object) state */
ClassCompiler * currentClass; /**< @brief Current in-progress class definition (or NULL) */
} GlobalState;
static void _GlobalState_gcscan(KrkInstance * _self) {
struct GlobalState * self = (void*)_self;
Compiler * compiler = self->current;
while (compiler != NULL) {
if (compiler->enclosed && compiler->enclosed->codeobject) krk_markObject((KrkObj*)compiler->enclosed->codeobject);
krk_markObject((KrkObj*)compiler->codeobject);
compiler = compiler->enclosing;
}
}
static void _GlobalState_gcsweep(KrkInstance * _self) {
/* nothing to do? */
}
#define currentChunk() (&state->current->codeobject->chunk)
#define EMIT_OPERAND_OP(opc, arg) do { if (arg < 256) { emitBytes(opc, arg); } \
else { emitBytes(opc ## _LONG, arg >> 16); emitBytes(arg >> 8, arg); } } while (0)
static int isMethod(int type) {
return type == TYPE_METHOD || type == TYPE_INIT || type == TYPE_COROUTINE_METHOD;
}
static int isCoroutine(int type) {
return type == TYPE_COROUTINE || type == TYPE_COROUTINE_METHOD;
}
static char * calculateQualName(struct GlobalState * state) {
static char space[1024]; /* We'll just truncate if we need to */
space[1023] = '\0';
char * writer = &space[1023];
#define WRITE(s) do { \
size_t len = strlen(s); \
if (writer - len < space) goto _exit; \
writer -= len; \
memcpy(writer, s, len); \
} while (0)
WRITE(state->current->codeobject->name->chars);
/* Go up by _compiler_, ignore class compilers as we don't need them. */
Compiler * ptr = state->current->enclosing;
while (ptr->enclosing) { /* Ignores the top level module */
if (ptr->type != TYPE_CLASS) {
/* We must be the locals of a function. */
WRITE("<locals>.");
}
WRITE(".");
WRITE(ptr->codeobject->name->chars);
ptr = ptr->enclosing;
}
_exit:
return writer;
}
static ChunkRecorder recordChunk(KrkChunk * in) {
return (ChunkRecorder){in->count, in->linesCount, in->constants.count};
}
static void rewindChunk(KrkChunk * out, ChunkRecorder from) {
out->count = from.count;
out->linesCount = from.lines;
out->constants.count = from.constants;
}
static size_t renameLocal(struct GlobalState * state, size_t ind, KrkToken name);
static void initCompiler(struct GlobalState * state, Compiler * compiler, FunctionType type) {
compiler->enclosing = state->current;
state->current = compiler;
compiler->codeobject = NULL;
compiler->type = type;
compiler->scopeDepth = 0;
compiler->enclosed = NULL;
compiler->codeobject = krk_newCodeObject();
compiler->localCount = 0;
compiler->localsSpace = 8;
compiler->locals = GROW_ARRAY(Local,NULL,0,8);
compiler->upvaluesSpace = 0;
compiler->upvalues = NULL;
compiler->breakCount = 0;
compiler->breakSpace = 0;
compiler->breaks = NULL;
compiler->continueCount = 0;
compiler->continueSpace = 0;
compiler->continues = NULL;
compiler->loopLocalCount = 0;
compiler->localNameCapacity = 0;
compiler->properties = NULL;
compiler->annotationCount = 0;
compiler->delSatisfied = 0;
compiler->unnamedArgs = 0;
compiler->optionsFlags = compiler->enclosing ? compiler->enclosing->optionsFlags : 0;
if (type != TYPE_MODULE) {
state->current->codeobject->name = krk_copyString(state->parser.previous.start, state->parser.previous.length);
char * qualname = calculateQualName(state);
state->current->codeobject->qualname = krk_copyString(qualname, strlen(qualname));
}
if (isMethod(type) && !(compiler->optionsFlags & OPTIONS_FLAG_NO_IMPLICIT_SELF)) {
Local * local = &state->current->locals[state->current->localCount++];
local->depth = 0;
local->isCaptured = 0;
local->name.start = "self";
local->name.length = 4;
renameLocal(state, 0, local->name);
state->current->codeobject->requiredArgs = 1;
state->current->codeobject->potentialPositionals = 1;
}
if (type == TYPE_CLASS) {
Local * local = &state->current->locals[state->current->localCount++];
local->depth = 0;
local->isCaptured = 0;
local->name.start = "";
local->name.length = 0;
renameLocal(state, 0, local->name);
state->current->codeobject->requiredArgs = 1;
state->current->codeobject->potentialPositionals = 1;
}
if (isCoroutine(type)) state->current->codeobject->obj.flags |= KRK_OBJ_FLAGS_CODEOBJECT_IS_COROUTINE;
}
static void rememberClassProperty(struct GlobalState * state, size_t ind) {
struct IndexWithNext * me = malloc(sizeof(struct IndexWithNext));
me->ind = ind;
me->next = state->current->properties;
state->current->properties = me;
}
static void parsePrecedence(struct GlobalState * state, Precedence precedence);
static ParseRule * getRule(KrkTokenType type);
/* These need to be forward declared or the ordering just gets really confusing... */
static void defDeclaration(struct GlobalState * state);
static void asyncDeclaration(struct GlobalState * state, int);
static void statement(struct GlobalState * state);
static void declaration(struct GlobalState * state);
static KrkToken classDeclaration(struct GlobalState * state);
static void declareVariable(struct GlobalState * state);
static void string(struct GlobalState * state, int exprType, RewindState *rewind);
static KrkToken decorator(struct GlobalState * state, size_t level, FunctionType type);
static void complexAssignment(struct GlobalState * state, ChunkRecorder before, KrkScanner oldScanner, Parser oldParser, size_t targetCount, int parenthesized, size_t argBefore, size_t argAfter);
static void complexAssignmentTargets(struct GlobalState * state, KrkScanner oldScanner, Parser oldParser, size_t targetCount, int parenthesized, size_t argBefore, size_t argAfter);
static int invalidTarget(struct GlobalState * state, int exprType, const char * description);
static void call(struct GlobalState * state, int exprType, RewindState *rewind);
static void finishError(struct GlobalState * state, KrkToken * token) {
if (!token->linePtr) token->linePtr = token->start;
size_t i = 0;
while (token->linePtr[i] && token->linePtr[i] != '\n') i++;
krk_attachNamedObject(&AS_INSTANCE(krk_currentThread.currentException)->fields, "line", (KrkObj*)krk_copyString(token->linePtr, i));
krk_attachNamedObject(&AS_INSTANCE(krk_currentThread.currentException)->fields, "file", (KrkObj*)currentChunk()->filename);
krk_attachNamedValue (&AS_INSTANCE(krk_currentThread.currentException)->fields, "lineno", INTEGER_VAL(token->line));
krk_attachNamedValue (&AS_INSTANCE(krk_currentThread.currentException)->fields, "colno", INTEGER_VAL(token->col));
krk_attachNamedValue (&AS_INSTANCE(krk_currentThread.currentException)->fields, "width", INTEGER_VAL(token->literalWidth));
if (state->current->codeobject->name) {
krk_attachNamedObject(&AS_INSTANCE(krk_currentThread.currentException)->fields, "func", (KrkObj*)state->current->codeobject->name);
} else {
KrkValue name = NONE_VAL();
krk_tableGet(&krk_currentThread.module->fields, vm.specialMethodNames[METHOD_NAME], &name);
krk_attachNamedValue(&AS_INSTANCE(krk_currentThread.currentException)->fields, "func", name);
}
state->parser.hadError = 1;
}
#ifdef KRK_NO_DOCUMENTATION
# define raiseSyntaxError(token, ...) do { if (state->parser.hadError) break; krk_runtimeError(vm.exceptions->syntaxError, "syntax error"); finishError(state,token); } while (0)
#else
# define raiseSyntaxError(token, ...) do { if (state->parser.hadError) break; krk_runtimeError(vm.exceptions->syntaxError, __VA_ARGS__); finishError(state,token); } while (0)
#endif
#define error(...) raiseSyntaxError(&state->parser.previous, __VA_ARGS__)
#define errorAtCurrent(...) raiseSyntaxError(&state->parser.current, __VA_ARGS__)
static void _advance(struct GlobalState * state) {
state->parser.previous = state->parser.current;
for (;;) {
state->parser.current = krk_scanToken(&state->scanner);
if (state->parser.eatingWhitespace &&
(state->parser.current.type == TOKEN_INDENTATION || state->parser.current.type == TOKEN_EOL)) continue;
if (state->parser.current.type == TOKEN_RETRY) continue;
if (state->parser.current.type != TOKEN_ERROR) break;
errorAtCurrent("%s", state->parser.current.start);
break;
}
}
#define advance() _advance(state)
static void _skipToEnd(struct GlobalState * state) {
while (state->parser.current.type != TOKEN_EOF) advance();
}
#define skipToEnd() _skipToEnd(state)
static void _startEatingWhitespace(struct GlobalState * state) {
state->parser.eatingWhitespace++;
if (state->parser.current.type == TOKEN_INDENTATION || state->parser.current.type == TOKEN_EOL) advance();
}
#define startEatingWhitespace() _startEatingWhitespace(state)
static void _stopEatingWhitespace(struct GlobalState * state) {
if (state->parser.eatingWhitespace == 0) {
error("Internal scanner error: Invalid nesting of `startEatingWhitespace`/`stopEatingWhitespace` calls.");
}
state->parser.eatingWhitespace--;
}
#define stopEatingWhitespace() _stopEatingWhitespace(state)
static void _consume(struct GlobalState * state, KrkTokenType type, const char * message) {
if (state->parser.current.type == type) {
advance();
return;
}
if (state->parser.current.type == TOKEN_EOL || state->parser.current.type == TOKEN_EOF) {
state->parser.current = state->parser.previous;
}
errorAtCurrent("%s", message);
}
#define consume(...) _consume(state,__VA_ARGS__)
static int _check(struct GlobalState * state, KrkTokenType type) {
return state->parser.current.type == type;
}
#define check(t) _check(state,t)
static int _match(struct GlobalState * state, KrkTokenType type) {
if (!check(type)) return 0;
advance();
return 1;
}
#define match(t) _match(state,t)
static int identifiersEqual(KrkToken * a, KrkToken * b) {
return (a->length == b->length && memcmp(a->start, b->start, a->length) == 0);
}
static KrkToken _syntheticToken(struct GlobalState * state, const char * text) {
KrkToken token;
token.start = text;
token.length = (int)strlen(text);
token.line = state->parser.previous.line;
return token;
}
#define syntheticToken(t) _syntheticToken(state,t)
static void _emitByte(struct GlobalState * state, uint8_t byte) {
krk_writeChunk(currentChunk(), byte, state->parser.previous.line);
}
#define emitByte(b) _emitByte(state,b)
static void _emitBytes(struct GlobalState * state, uint8_t byte1, uint8_t byte2) {
emitByte(byte1);
emitByte(byte2);
}
#define emitBytes(a,b) _emitBytes(state,a,b)
static void emitReturn(struct GlobalState * state) {
if (state->current->type != TYPE_LAMBDA && state->current->type != TYPE_CLASS) {
emitByte(OP_NONE);
}
emitByte(OP_RETURN);
}
static KrkCodeObject * endCompiler(struct GlobalState * state) {
KrkCodeObject * function = state->current->codeobject;
for (size_t i = 0; i < function->localNameCount; i++) {
if (function->localNames[i].deathday == 0) {
function->localNames[i].deathday = currentChunk()->count;
}
}
function->localNames = GROW_ARRAY(KrkLocalEntry, function->localNames, \
state->current->localNameCapacity, function->localNameCount); /* Shorten this down for runtime */
if (state->current->continueCount) { state->parser.previous = state->current->continues[0].token; error("continue without loop"); }
if (state->current->breakCount) { state->parser.previous = state->current->breaks[0].token; error("break without loop"); }
emitReturn(state);
/* Attach contants for arguments */
for (int i = 0; i < function->potentialPositionals; ++i) {
if (i < state->current->unnamedArgs) {
krk_writeValueArray(&function->positionalArgNames, NONE_VAL());
continue;
}
KrkValue value = OBJECT_VAL(krk_copyString(state->current->locals[i].name.start, state->current->locals[i].name.length));
krk_push(value);
krk_writeValueArray(&function->positionalArgNames, value);
krk_pop();
}
size_t args = function->potentialPositionals;
if (function->obj.flags & KRK_OBJ_FLAGS_CODEOBJECT_COLLECTS_ARGS) {
KrkValue value = OBJECT_VAL(krk_copyString(state->current->locals[args].name.start,
state->current->locals[args].name.length));
krk_push(value);
krk_writeValueArray(&function->positionalArgNames, value);
krk_pop();
args++;
}
for (int i = 0; i < function->keywordArgs; ++i) {
KrkValue value = OBJECT_VAL(krk_copyString(state->current->locals[i+args].name.start,
state->current->locals[i+args].name.length));
krk_push(value);
krk_writeValueArray(&function->keywordArgNames, value);
krk_pop();
}
args += function->keywordArgs;
if (function->obj.flags & KRK_OBJ_FLAGS_CODEOBJECT_COLLECTS_KWS) {
KrkValue value = OBJECT_VAL(krk_copyString(state->current->locals[args].name.start,
state->current->locals[args].name.length));
krk_push(value);
krk_writeValueArray(&function->keywordArgNames, value);
krk_pop();
args++;
}
function->totalArguments = function->potentialPositionals + function->keywordArgs + !!(function->obj.flags & KRK_OBJ_FLAGS_CODEOBJECT_COLLECTS_ARGS) + !!(function->obj.flags & KRK_OBJ_FLAGS_CODEOBJECT_COLLECTS_KWS);
#ifndef KRK_NO_DISASSEMBLY
if ((krk_currentThread.flags & KRK_THREAD_ENABLE_DISASSEMBLY) && !state->parser.hadError) {
krk_disassembleCodeObject(stderr, function, function->name ? function->name->chars : "(module)");
}
#endif
state->current = state->current->enclosing;
return function;
}
static void freeCompiler(Compiler * compiler) {
FREE_ARRAY(Local,compiler->locals, compiler->localsSpace);
FREE_ARRAY(Upvalue,compiler->upvalues, compiler->upvaluesSpace);
FREE_ARRAY(struct LoopExit,compiler->breaks, compiler->breakSpace);
FREE_ARRAY(struct LoopExit,compiler->continues, compiler->continueSpace);
while (compiler->properties) {
void * tmp = compiler->properties;
compiler->properties = compiler->properties->next;
free(tmp);
}
}
static size_t _emitConstant(struct GlobalState * state, KrkValue value) {
return krk_writeConstant(currentChunk(), value, state->parser.previous.line);
}
#define emitConstant(v) _emitConstant(state,v)
static int isMangleable(const char * name, size_t len) {
return (len > 2 && name[0] == '_' && name[1] == '_' && name[len-1] != '_' && (len < 4 || name[len-2] != '_'));
}
static ssize_t identifierConstant(struct GlobalState * state, KrkToken * name) {
if (state->currentClass && isMangleable(name->start, name->length)) {
/* Mangle it */
const char * className = state->currentClass->name.start;
size_t classLength = state->currentClass->name.length;
while (classLength && *className == '_') {
classLength--;
className++;
}
struct StringBuilder sb = {0};
krk_pushStringBuilderFormat(&sb,"_%.*s%.*s",
(int)classLength, className,
(int)name->length, name->start);
return krk_addConstant(currentChunk(), krk_finishStringBuilder(&sb));
}
return krk_addConstant(currentChunk(), OBJECT_VAL(krk_copyString(name->start, name->length)));
}
static ssize_t nonidentifierTokenConstant(struct GlobalState * state, KrkToken * name) {
return krk_addConstant(currentChunk(), OBJECT_VAL(krk_copyString(name->start, name->length)));
}
static ssize_t resolveLocal(struct GlobalState * state, Compiler * compiler, KrkToken * name) {
for (ssize_t i = compiler->localCount - 1; i >= 0; i--) {
Local * local = &compiler->locals[i];
if (identifiersEqual(name, &local->name)) {
if (local->depth == -1) {
error("Invalid recursive reference in declaration initializer");
}
if (local->depth == -2) {
continue;
}
return i;
}
}
return -1;
}
static size_t renameLocal(struct GlobalState * state, size_t ind, KrkToken name) {
if (state->current->codeobject->localNameCount + 1 > state->current->localNameCapacity) {
size_t old = state->current->localNameCapacity;
state->current->localNameCapacity = GROW_CAPACITY(old);
state->current->codeobject->localNames = GROW_ARRAY(KrkLocalEntry, state->current->codeobject->localNames, old, state->current->localNameCapacity);
}
state->current->codeobject->localNames[state->current->codeobject->localNameCount].id = ind;
state->current->codeobject->localNames[state->current->codeobject->localNameCount].birthday = currentChunk()->count;
state->current->codeobject->localNames[state->current->codeobject->localNameCount].deathday = 0;
state->current->codeobject->localNames[state->current->codeobject->localNameCount].name = krk_copyString(name.start, name.length);
return state->current->codeobject->localNameCount++;
}
static size_t addLocal(struct GlobalState * state, KrkToken name) {
if (state->current->localCount + 1 > state->current->localsSpace) {
size_t old = state->current->localsSpace;
state->current->localsSpace = GROW_CAPACITY(old);
state->current->locals = GROW_ARRAY(Local,state->current->locals,old,state->current->localsSpace);
}
size_t out = state->current->localCount;
Local * local = &state->current->locals[state->current->localCount++];
local->name = name;
local->depth = -1;
local->isCaptured = 0;
if (name.length) {
renameLocal(state, out, name);
}
return out;
}
static void declareVariable(struct GlobalState * state) {
if (state->current->scopeDepth == 0) return;
KrkToken * name = &state->parser.previous;
/* Detect duplicate definition */
for (ssize_t i = state->current->localCount - 1; i >= 0; i--) {
Local * local = &state->current->locals[i];
if (local->depth != -1 && local->depth < (ssize_t)state->current->scopeDepth) break;
if (identifiersEqual(name, &local->name)) {
error("Duplicate definition for local '%.*s' in this scope.", (int)name->literalWidth, name->start);
}
}
addLocal(state, *name);
}
static ssize_t parseVariable(struct GlobalState * state, const char * errorMessage) {
consume(TOKEN_IDENTIFIER, errorMessage);
declareVariable(state);
if (state->current->scopeDepth > 0) return 0;
if ((state->current->optionsFlags & OPTIONS_FLAG_COMPILE_TIME_BUILTINS) && *state->parser.previous.start != '_') {
KrkValue value;
if (krk_tableGet_fast(&vm.builtins->fields, krk_copyString(state->parser.previous.start, state->parser.previous.length), &value)) {
error("Conflicting declaration of global '%.*s' is invalid when 'compile_time_builtins' is enabled.",
(int)state->parser.previous.length, state->parser.previous.start);
return 0;
}
}
return identifierConstant(state, &state->parser.previous);
}
static void markInitialized(struct GlobalState * state) {
if (state->current->scopeDepth == 0) return;
state->current->locals[state->current->localCount - 1].depth = state->current->scopeDepth;
}
static size_t anonymousLocal(struct GlobalState * state) {
size_t val = addLocal(state, syntheticToken(""));
markInitialized(state);
return val;
}
static void defineVariable(struct GlobalState * state, size_t global) {
if (state->current->scopeDepth > 0) {
markInitialized(state);
return;
}
EMIT_OPERAND_OP(OP_DEFINE_GLOBAL, global);
}
static void number(struct GlobalState * state, int exprType, RewindState *rewind) {
const char * start = state->parser.previous.start;
invalidTarget(state, exprType, "literal");
for (size_t j = 0; j < state->parser.previous.length; ++j) {
if (state->parser.previous.start[j] == '.') {
double value = strtod(start, NULL);
emitConstant(FLOATING_VAL(value));
return;
}
}
/* If we got here, it's an integer of some sort. */
KrkValue result = krk_parse_int(start, state->parser.previous.literalWidth, 0);
if (IS_NONE(result)) {
error("invalid numeric literal");
return;
}
emitConstant(result);
}
static int _emitJump(struct GlobalState * state, uint8_t opcode) {
emitByte(opcode);
emitBytes(0xFF, 0xFF);
return currentChunk()->count - 2;
}
#define emitJump(o) _emitJump(state,o)
static void _patchJump(struct GlobalState * state, int offset) {
int jump = currentChunk()->count - offset - 2;
if (jump > 0xFFFF) error("Jump offset is too large for opcode.");
currentChunk()->code[offset] = (jump >> 8) & 0xFF;
currentChunk()->code[offset + 1] = (jump) & 0xFF;
}
#define patchJump(o) _patchJump(state,o)
static void compareChained(struct GlobalState * state, int inner) {
KrkTokenType operatorType = state->parser.previous.type;
if (operatorType == TOKEN_NOT) consume(TOKEN_IN, "'in' must follow infix 'not'");
int invert = (operatorType == TOKEN_IS && match(TOKEN_NOT));
ParseRule * rule = getRule(operatorType);
parsePrecedence(state, (Precedence)(rule->precedence + 1));
if (getRule(state->parser.current.type)->precedence == PREC_COMPARISON) {
emitByte(OP_SWAP);
emitBytes(OP_DUP, 1);
}
switch (operatorType) {
case TOKEN_BANG_EQUAL: emitBytes(OP_EQUAL, OP_NOT); break;
case TOKEN_EQUAL_EQUAL: emitByte(OP_EQUAL); break;
case TOKEN_GREATER: emitByte(OP_GREATER); break;
case TOKEN_GREATER_EQUAL: emitByte(OP_GREATER_EQUAL); break;
case TOKEN_LESS: emitByte(OP_LESS); break;
case TOKEN_LESS_EQUAL: emitByte(OP_LESS_EQUAL); break;
case TOKEN_IS: emitByte(OP_IS); if (invert) emitByte(OP_NOT); break;
case TOKEN_IN: emitByte(OP_INVOKE_CONTAINS); break;
case TOKEN_NOT: emitBytes(OP_INVOKE_CONTAINS, OP_NOT); break;
default: error("Invalid binary comparison operator?"); break;
}
if (getRule(state->parser.current.type)->precedence == PREC_COMPARISON) {
size_t exitJump = emitJump(OP_JUMP_IF_FALSE_OR_POP);
advance();
compareChained(state, 1);
patchJump(exitJump);
if (getRule(state->parser.current.type)->precedence != PREC_COMPARISON) {
if (!inner) {
emitBytes(OP_SWAP,OP_POP);
}
}
} else if (inner) {
emitByte(OP_JUMP);
emitBytes(0,2);
}
}
static void compare(struct GlobalState * state, int exprType, RewindState *rewind) {
compareChained(state, 0);
invalidTarget(state, exprType, "operator");
}
static void binary(struct GlobalState * state, int exprType, RewindState *rewind) {
KrkTokenType operatorType = state->parser.previous.type;
ParseRule * rule = getRule(operatorType);
parsePrecedence(state, (Precedence)(rule->precedence + (rule->precedence != PREC_EXPONENT)));
invalidTarget(state, exprType, "operator");
switch (operatorType) {
case TOKEN_PIPE: emitByte(OP_BITOR); break;
case TOKEN_CARET: emitByte(OP_BITXOR); break;
case TOKEN_AMPERSAND: emitByte(OP_BITAND); break;
case TOKEN_LEFT_SHIFT: emitByte(OP_SHIFTLEFT); break;
case TOKEN_RIGHT_SHIFT: emitByte(OP_SHIFTRIGHT); break;
case TOKEN_PLUS: emitByte(OP_ADD); break;
case TOKEN_MINUS: emitByte(OP_SUBTRACT); break;
case TOKEN_ASTERISK: emitByte(OP_MULTIPLY); break;
case TOKEN_POW: emitByte(OP_POW); break;
case TOKEN_SOLIDUS: emitByte(OP_DIVIDE); break;
case TOKEN_DOUBLE_SOLIDUS: emitByte(OP_FLOORDIV); break;
case TOKEN_MODULO: emitByte(OP_MODULO); break;
case TOKEN_IN: emitByte(OP_EQUAL); break;
case TOKEN_AT: emitByte(OP_MATMUL); break;
default: return;
}
}
static int matchAssignment(struct GlobalState * state) {
return (state->parser.current.type >= TOKEN_EQUAL && state->parser.current.type <= TOKEN_MODULO_EQUAL) ? (advance(), 1) : 0;
}
static int checkEndOfDel(struct GlobalState * state) {
if (check(TOKEN_COMMA) || check(TOKEN_EOL) || check(TOKEN_EOF) || check(TOKEN_SEMICOLON)) {
state->current->delSatisfied = 1;
return 1;
}
return 0;
}
static int matchComplexEnd(struct GlobalState * state) {
return match(TOKEN_COMMA) ||
match(TOKEN_EQUAL) ||
match(TOKEN_RIGHT_PAREN);
}
static int invalidTarget(struct GlobalState * state, int exprType, const char * description) {
if (exprType == EXPR_CAN_ASSIGN && matchAssignment(state)) {
error("Can not assign to %s", description);
return 0;
}
if (exprType == EXPR_DEL_TARGET && checkEndOfDel(state)) {
error("Can not delete %s", description);
return 0;
}
return 1;
}
static void assignmentValue(struct GlobalState * state) {
KrkTokenType type = state->parser.previous.type;
if (type == TOKEN_PLUS_PLUS || type == TOKEN_MINUS_MINUS) {
emitConstant(INTEGER_VAL(1));
} else {
parsePrecedence(state, PREC_COMMA); /* But adding a tuple is maybe not defined */
}
switch (type) {
case TOKEN_PIPE_EQUAL: emitByte(OP_INPLACE_BITOR); break;
case TOKEN_CARET_EQUAL: emitByte(OP_INPLACE_BITXOR); break;
case TOKEN_AMP_EQUAL: emitByte(OP_INPLACE_BITAND); break;
case TOKEN_LSHIFT_EQUAL: emitByte(OP_INPLACE_SHIFTLEFT); break;
case TOKEN_RSHIFT_EQUAL: emitByte(OP_INPLACE_SHIFTRIGHT); break;
case TOKEN_PLUS_EQUAL: emitByte(OP_INPLACE_ADD); break;
case TOKEN_PLUS_PLUS: emitByte(OP_INPLACE_ADD); break;
case TOKEN_MINUS_EQUAL: emitByte(OP_INPLACE_SUBTRACT); break;
case TOKEN_MINUS_MINUS: emitByte(OP_INPLACE_SUBTRACT); break;
case TOKEN_ASTERISK_EQUAL: emitByte(OP_INPLACE_MULTIPLY); break;
case TOKEN_POW_EQUAL: emitByte(OP_INPLACE_POW); break;
case TOKEN_SOLIDUS_EQUAL: emitByte(OP_INPLACE_DIVIDE); break;
case TOKEN_DSOLIDUS_EQUAL: emitByte(OP_INPLACE_FLOORDIV); break;
case TOKEN_MODULO_EQUAL: emitByte(OP_INPLACE_MODULO); break;
case TOKEN_AT_EQUAL: emitByte(OP_INPLACE_MATMUL); break;
default:
error("Unexpected operand in assignment");
break;
}
}
static void expression(struct GlobalState * state) {
parsePrecedence(state, PREC_CAN_ASSIGN);
}
static void sliceExpression(struct GlobalState * state) {
int isSlice = 0;
if (match(TOKEN_COLON)) {
emitByte(OP_NONE);
isSlice = 1;
} else {
parsePrecedence(state, PREC_CAN_ASSIGN);
}
if (isSlice || match(TOKEN_COLON)) {
/* We have the start value, which is either something or None */
if (check(TOKEN_RIGHT_SQUARE) || check(TOKEN_COMMA)) {
/* foo[x:] */
emitByte(OP_NONE);
EMIT_OPERAND_OP(OP_SLICE, 2);
} else {
if (check(TOKEN_COLON)) {
/* foo[x::... */
emitByte(OP_NONE);
} else {
/* foo[x:e... */
parsePrecedence(state, PREC_CAN_ASSIGN);
}
if (match(TOKEN_COLON) && !check(TOKEN_RIGHT_SQUARE) && !check(TOKEN_COMMA)) {
/* foo[x:e:s] */
parsePrecedence(state, PREC_CAN_ASSIGN);
EMIT_OPERAND_OP(OP_SLICE, 3);
} else {
/* foo[x:e] */
EMIT_OPERAND_OP(OP_SLICE, 2);
}
}
}
}
static void getitem(struct GlobalState * state, int exprType, RewindState *rewind) {
sliceExpression(state);