-
Notifications
You must be signed in to change notification settings - Fork 2
/
compiler.c
2685 lines (2289 loc) · 55.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
/* Here lies the entire c-bytecode-vm compiler. This includes lexing, parsing,
* and code generation. The latter two happen at the same time. */
#include <assert.h>
#include <ctype.h>
#include <libgen.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "agent.h"
#include "builtin_modules.h"
#include "cb_util.h"
#include "compiler.h"
#include "hashmap.h"
#include "module.h"
#include "opcode.h"
#include "struct.h"
#define INITIAL_BYTECODE_SIZE 32
#define LENGTH(ARR) (sizeof(ARR) / sizeof(ARR[0]))
#define VALID_ESCAPES "nrt\"'"
#define TOKEN_TYPE_LIST(X) \
X(TOK_IDENT) \
X(TOK_INT) \
X(TOK_DOUBLE) \
X(TOK_STRING) \
X(TOK_CHAR) \
X(TOK_NULL) \
X(TOK_LEFT_BRACKET) \
X(TOK_RIGHT_BRACKET) \
X(TOK_LEFT_BRACE) \
X(TOK_RIGHT_BRACE) \
X(TOK_LEFT_PAREN) \
X(TOK_RIGHT_PAREN) \
X(TOK_PLUS) \
X(TOK_MINUS) \
X(TOK_STAR) \
X(TOK_SLASH) \
X(TOK_PERCENT) \
X(TOK_STAR_STAR) \
X(TOK_AND) \
X(TOK_PIPE) \
X(TOK_CARET) \
X(TOK_AND_AND) \
X(TOK_PIPE_PIPE) \
X(TOK_SEMICOLON) \
X(TOK_COLON) \
X(TOK_EQUAL) \
X(TOK_EQUAL_EQUAL) \
X(TOK_TILDE) \
X(TOK_BANG) \
X(TOK_BANG_EQUAL) \
X(TOK_LESS_THAN) \
X(TOK_LESS_THAN_EQUAL) \
X(TOK_GREATER_THAN) \
X(TOK_GREATER_THAN_EQUAL) \
X(TOK_COMMA) \
X(TOK_DOT) \
X(TOK_RETURN) \
X(TOK_FUNCTION) \
X(TOK_FOR) \
X(TOK_IF) \
X(TOK_ELSE) \
X(TOK_WHILE) \
X(TOK_BREAK) \
X(TOK_CONTINUE) \
X(TOK_LET) \
X(TOK_TRUE) \
X(TOK_FALSE) \
X(TOK_EXPORT) \
X(TOK_IMPORT) \
X(TOK_STRUCT) \
X(TOK_EOF)
enum token_type {
#define COMMA(V) V,
TOKEN_TYPE_LIST(COMMA)
#undef COMMA
};
/* A structure defining a token located in a source file */
struct token {
/* The type of token */
enum token_type type;
/* The range of source text where the token was found.
* start is inclusive, end is exclusive. */
size_t start, end;
/* The line and column where the token started, mostly for displaying
* to the user */
size_t line, column;
};
/* Opaque lexer state */
typedef struct lex_state {
const char *filename;
size_t current_line, current_column;
const char *ptr;
} lex_state;
static inline lex_state lex_state_new(const char *name)
{
return (lex_state) {
.filename = name,
.current_line = 1,
.current_column = 1,
};
}
#define KW(S, T) { S, sizeof(S) - 1, T }
static struct {
const char *name;
size_t len;
enum token_type type;
} KEYWORDS[] = {
KW("return", TOK_RETURN),
KW("for", TOK_FOR),
KW("while", TOK_WHILE),
KW("function", TOK_FUNCTION),
KW("let", TOK_LET),
KW("if", TOK_IF),
KW("else", TOK_ELSE),
KW("break", TOK_BREAK),
KW("continue", TOK_CONTINUE),
KW("null", TOK_NULL),
KW("true", TOK_TRUE),
KW("false", TOK_FALSE),
KW("export", TOK_EXPORT),
KW("import", TOK_IMPORT),
KW("struct", TOK_STRUCT),
};
#undef KW
/* Get the name of a token type given its value */
static const char *token_type_name(enum token_type t)
{
#define CASE(T) case T: return #T;
switch (t) {
TOKEN_TYPE_LIST(CASE)
default:
return NULL;
}
#undef CASE
}
/* Read the next token from the given input string */
static int next_token(lex_state *state, const char *input, struct token *dest)
{
const char *start_of_token;
int is_double, c;
unsigned i, len;
assert(state != NULL);
assert(input != NULL);
assert(dest != NULL);
if (state->ptr == NULL) {
state->current_line = state->current_column = 1;
state->ptr = input;
}
/* Print an error message and location data */
#define ERROR(message, ...) \
fprintf(stderr, "Error in %s at %zu:%zu: " message "\n", \
state->filename, state->current_line, state->current_column, \
##__VA_ARGS__)
#define NEXT() (state->current_column += 1, *state->ptr++)
#define PEEK() (*state->ptr)
#define TOKEN(TYPE) ({ dest->type = (TYPE); goto end; })
#define OR2(SND, A, B) ({ \
if (PEEK() == (SND)) { \
(void) NEXT(); \
TOKEN(B); \
} else { \
TOKEN(A); \
} \
})
start_of_token = state->ptr;
while (PEEK()) {
start_of_token = state->ptr;
dest->line = state->current_line;
dest->column = state->current_column;
switch ((c = NEXT())) {
/* Skip whitespace, but count newlines */
case '\n':
state->current_line += 1;
state->current_column = 1;
continue;
case ' ':
case '\t':
case '\r':
continue;
/* Skip comments */
case '#':
while (PEEK() != '\n') NEXT();
continue;
case '+': TOKEN(TOK_PLUS);
case '-': TOKEN(TOK_MINUS);
case '/': TOKEN(TOK_SLASH);
case '^': TOKEN(TOK_CARET);
case '[': TOKEN(TOK_LEFT_BRACKET);
case ']': TOKEN(TOK_RIGHT_BRACKET);
case '{': TOKEN(TOK_LEFT_BRACE);
case '}': TOKEN(TOK_RIGHT_BRACE);
case '(': TOKEN(TOK_LEFT_PAREN);
case ')': TOKEN(TOK_RIGHT_PAREN);
case '%': TOKEN(TOK_PERCENT);
case ';': TOKEN(TOK_SEMICOLON);
case ':': TOKEN(TOK_COLON);
case ',': TOKEN(TOK_COMMA);
case '~': TOKEN(TOK_TILDE);
case '.': TOKEN(TOK_DOT);
case '=': OR2('=', TOK_EQUAL, TOK_EQUAL_EQUAL);
case '*': OR2('*', TOK_STAR, TOK_STAR_STAR);
case '&': OR2('&', TOK_AND, TOK_AND_AND);
case '|': OR2('|', TOK_PIPE, TOK_PIPE_PIPE);
case '<': OR2('=', TOK_LESS_THAN, TOK_LESS_THAN_EQUAL);
case '>': OR2('=', TOK_GREATER_THAN, TOK_GREATER_THAN_EQUAL);
case '!': OR2('=', TOK_BANG, TOK_BANG_EQUAL);
case '0' ... '9':
if (PEEK() == 'x') {
NEXT();
while ((c = PEEK()) && isxdigit(c))
NEXT();
TOKEN(TOK_INT);
}
is_double = 0;
while ((c = PEEK())) {
if (c == '.' && !is_double) {
is_double = 1;
} else if (c == '.' && is_double) {
ERROR("Unexpected '.'");
return 1;
} else if (!isdigit(c)) {
break;
}
(void) NEXT();
}
if (is_double)
TOKEN(TOK_DOUBLE);
else
TOKEN(TOK_INT);
case '_':
case 'a' ... 'z':
case 'A' ... 'Z':
len = 0;
while ((c = PEEK())) {
len += 1;
if (isalnum(c) || c == '_');
else break;
(void) NEXT();
}
/* Check if it was a keyword */
for (i = 0; i < LENGTH(KEYWORDS); i += 1) {
if (len != KEYWORDS[i].len)
continue;
if (!strncmp(start_of_token,
KEYWORDS[i].name,
len))
TOKEN(KEYWORDS[i].type);
}
TOKEN(TOK_IDENT);
#define READ_ESCAPE_SEQUENCE(C) ({ \
if (c == '\\') { \
if (strchr(VALID_ESCAPES, PEEK())) { \
(void) NEXT(); \
} else { \
ERROR("Unrecognized escape sequence"); \
return 1; \
} \
} \
})
case '\'':
c = NEXT();
READ_ESCAPE_SEQUENCE(c);
if ((c = NEXT()) != '\'') {
ERROR("Expected '\\'', got '%c'", c);
return 1;
}
TOKEN(TOK_CHAR);
case '"':
while ((c = NEXT()) != '"') {
READ_ESCAPE_SEQUENCE(c);
if (c == '\n') {
state->current_line += 1;
state->current_column = 1;
}
}
TOKEN(TOK_STRING);
default:
ERROR("Invalid token '%c'", c);
return 1;
}
#undef READ_ESCAPE_SEQUENCE
}
/* end of input */
TOKEN(TOK_EOF);
#undef NEXT
#undef PEEK
#undef TOKEN
#undef OR2
#undef ERROR
end:
dest->end = state->ptr - input;
dest->start = start_of_token - input;
return 0;
}
struct binding {
struct binding *next;
ssize_t name;
size_t index;
int is_upvalue;
};
struct scope {
struct scope *parent;
struct binding *locals,
*upvalues;
size_t num_locals,
num_upvalues;
};
static struct scope scope_new()
{
return (struct scope) {
.parent = NULL,
.locals = NULL,
.upvalues = NULL,
.num_locals = 0,
.num_upvalues = 0,
};
}
static void scope_free(struct scope s)
{
struct binding *current, *tmp;
#define FREE_LIST(L) \
do { \
if (L) { \
current = (L); \
while (current) { \
tmp = current; \
current = current->next; \
free(tmp); \
} \
} \
} while (0)
FREE_LIST(s.locals);
FREE_LIST(s.upvalues);
#undef FREE_LIST
}
static size_t scope_add_binding(struct scope *s, ssize_t name, int upvalue)
{
size_t id;
struct binding *new_binding;
new_binding = malloc(sizeof(struct binding));
new_binding->name = name;
new_binding->is_upvalue = upvalue;
if (upvalue) {
id = new_binding->index = s->num_upvalues++;
new_binding->next = s->upvalues;
s->upvalues = new_binding;
} else {
id = new_binding->index = s->num_locals++;
new_binding->next = s->locals;
s->locals = new_binding;
}
return id;
}
static struct binding *scope_get_binding(struct scope *s, size_t name)
{
struct binding *binding;
#define SEARCH(L) \
do { \
if (!(L)) \
break; \
binding = (L); \
while (binding) { \
if ((size_t) binding->name == name) \
return binding; \
binding = binding->next; \
} \
} while (0)
SEARCH(s->locals);
SEARCH(s->upvalues);
#undef SEARCH
return NULL;
}
static int scope_has_binding(struct scope *s, size_t name)
{
return scope_get_binding(s, name) != NULL;
}
static int scope_parent_has_binding(struct scope *s, size_t name)
{
if (!s->parent)
return 0;
return scope_has_binding(s->parent, name)
|| scope_parent_has_binding(s->parent, name);
}
static inline size_t tok_len(struct token *tok)
{
return tok->end - tok->start;
}
struct pending_address {
struct pending_address *next;
size_t label, address;
};
struct cb_bytecode *cb_bytecode_new()
{
struct cb_bytecode *bc;
bc = malloc(sizeof(struct cb_bytecode));
bc->code = NULL;
bc->size = bc->len = 0;
bc->label_addresses = NULL;
bc->label_addr_size = bc->label_addr_len = 0;
bc->pending_addresses = NULL;
return bc;
}
CB_INLINE cb_instruction cb_bytecode_get(struct cb_bytecode *bc, size_t idx)
{
return bc->code[idx];
}
CB_INLINE size_t cb_bytecode_len(struct cb_bytecode *bc)
{
return bc->len;
}
void cb_bytecode_free(struct cb_bytecode *bc)
{
struct pending_address *current, *tmp;
current = bc->pending_addresses;
while (current) {
tmp = current;
current = current->next;
free(tmp);
}
if (bc->code)
free(bc->code);
if (bc->label_addresses)
free(bc->label_addresses);
free(bc);
}
static size_t bytecode_label(struct cb_bytecode *bc)
{
if (bc->label_addr_size <= bc->label_addr_len) {
bc->label_addr_size = bc->label_addr_size == 0
? 4
: bc->label_addr_size << 1;
bc->label_addresses = realloc(bc->label_addresses,
bc->label_addr_size * sizeof(size_t));
}
bc->label_addresses[bc->label_addr_len++] = -1;
return bc->label_addr_len - 1;
}
static void bytecode_update_size_t(struct cb_bytecode *bc, size_t idx,
size_t value)
{
bc->code[idx] = value;
}
static void bytecode_mark_label(struct cb_bytecode *bc, size_t label)
{
struct pending_address *current, *tmp, **prev;
assert(label < bc->label_addr_len);
bc->label_addresses[label] = bc->len;
prev = &bc->pending_addresses;
current = bc->pending_addresses;
while (current) {
tmp = current;
current = current->next;
if (tmp->label == label) {
bytecode_update_size_t(bc, tmp->address, bc->len);
*prev = current;
free(tmp);
} else {
prev = &tmp->next;
}
}
}
static void bytecode_push(struct cb_bytecode *bc, cb_instruction byte)
{
assert(bc != NULL);
if (bc->size <= bc->len) {
bc->size = bc->size == 0
? INITIAL_BYTECODE_SIZE
: bc->size << 2;
bc->code = realloc(bc->code, bc->size * sizeof(cb_instruction));
}
bc->code[bc->len++] = byte;
}
static void bytecode_push_size_t(struct cb_bytecode *bc, size_t value)
{
bytecode_push(bc, value);
}
static void bytecode_address_of(struct cb_bytecode *bc, size_t label)
{
size_t value;
struct pending_address *addr;
assert(label < bc->label_addr_len);
if (bc->label_addresses[label] == -1) {
value = 0;
addr = malloc(sizeof(struct pending_address));
addr->label = label;
addr->address = bc->len;
addr->next = bc->pending_addresses;
bc->pending_addresses = addr;
} else {
value = bc->label_addresses[label];
}
bytecode_push_size_t(bc, value);
}
static int bytecode_finalize(struct cb_bytecode *bc)
{
if (bc->pending_addresses != NULL) {
fprintf(stderr, "Missing label\n");
return 1;
}
if (bc->label_addresses) {
free(bc->label_addresses);
bc->label_addresses = NULL;
}
bc->code = realloc(bc->code, bc->size * sizeof(cb_instruction));
bc->label_addr_size = bc->label_addr_len = 0;
return 0;
}
struct bytecode_snapshot {
size_t len, label_addr_len;
struct pending_address *pending_addresses;
};
static void bytecode_snapshot(const struct cb_bytecode *bc,
struct bytecode_snapshot *snap)
{
snap->len = bc->len;
snap->label_addr_len = bc->label_addr_len;
snap->pending_addresses = bc->pending_addresses;
}
static void bytecode_restore(struct cb_bytecode *bc,
struct bytecode_snapshot *snap)
{
struct pending_address *tmp;
bc->len = snap->len;
bc->label_addr_len = snap->label_addr_len;
while (bc->pending_addresses
&& bc->pending_addresses != snap->pending_addresses) {
tmp = bc->pending_addresses;
bc->pending_addresses = tmp->next;
free(tmp);
}
}
struct function_state {
size_t start_label;
size_t end_label;
size_t *free_variables;
size_t free_var_len, free_var_size;
};
void fstate_add_freevar(struct function_state *fstate, size_t free_var)
{
if (fstate->free_var_len >= fstate->free_var_size) {
fstate->free_var_size = fstate->free_var_size == 0
? 4
: fstate->free_var_size << 1;
fstate->free_variables = realloc(fstate->free_variables,
fstate->free_var_size * sizeof(size_t));
}
fstate->free_variables[fstate->free_var_len++] = free_var;
}
struct loop_state {
size_t continue_label;
size_t break_label;
};
struct cstate {
struct cb_bytecode *bytecode;
const char *input;
const char *filename;
int did_peek;
struct token peeked;
lex_state lex_state;
cb_modspec *modspec;
struct scope *scope;
int is_global;
struct function_state *function_state;
struct loop_state *loop_state;
cb_hashmap *imported;
};
struct cstate_snapshot {
struct bytecode_snapshot bytecode;
int did_peek;
struct token peeked;
lex_state lex_state;
int is_global;
};
static void cstate_snapshot(struct cstate *st, struct cstate_snapshot *snap)
{
bytecode_snapshot(st->bytecode, &snap->bytecode);
snap->did_peek = st->did_peek;
snap->peeked = st->peeked;
snap->lex_state = st->lex_state;
snap->is_global = st->is_global;
}
static void cstate_restore(struct cstate *st, struct cstate_snapshot *snap)
{
bytecode_restore(st->bytecode, &snap->bytecode);
st->did_peek = snap->did_peek;
st->peeked = snap->peeked;
st->lex_state = snap->lex_state;
st->is_global = snap->is_global;
}
static struct cstate cstate_default(int with_bytecode)
{
return (struct cstate) {
.bytecode = with_bytecode ? cb_bytecode_new() : NULL,
.input = NULL,
.filename = "<script>",
.did_peek = 0,
.lex_state = lex_state_new("<script>"),
.modspec = NULL,
.is_global = 1,
.scope = NULL,
.function_state = NULL,
.loop_state = NULL,
.imported = cb_hashmap_new(),
};
}
/* NOTE: does not free bytecode or input */
static void cstate_free(struct cstate state)
{
if (state.modspec)
cb_modspec_free(state.modspec);
cb_hashmap_free(state.imported);
}
struct cstate *cb_compile_state_new(const char *name, cb_modspec *modspec,
cb_bytecode *bc)
{
struct cstate *st;
st = malloc(sizeof(struct cstate));
*st = cstate_default(0);
st->bytecode = bc;
st->lex_state.filename = name;
st->filename = name;
st->modspec = modspec;
return st;
}
void cb_compile_state_free(struct cstate *st)
{
st->modspec = NULL; /* FIXME: This modspec-freeing mess seems bad */
cstate_free(*st);
free(st);
}
void cb_compile_state_reset(struct cstate *st, const char *code,
cb_modspec *modspec)
{
st->lex_state = lex_state_new(st->lex_state.filename);
st->input = code;
st->modspec = modspec;
st->did_peek = 0;
}
static int resolve_binding(struct cstate *s, size_t name, struct binding *out)
{
struct binding *binding;
struct function_state *fstate;
unsigned i;
int found;
if (!s->scope)
return 0;
binding = scope_get_binding(s->scope, name);
if (binding) {
*out = *binding;
return 1;
}
if (scope_parent_has_binding(s->scope, name)) {
fstate = s->function_state;
assert(fstate != NULL);
found = 0;
for (i = 0; i < fstate->free_var_len; i += 1) {
if (fstate->free_variables[i] == name) {
found = 1;
break;
}
}
if (found) {
out->is_upvalue = 1;
out->name = name;
out->index = i;
} else {
out->is_upvalue = 1;
out->name = name;
out->index = s->scope->num_upvalues
+ s->function_state->free_var_len;
fstate_add_freevar(fstate, name);
}
return 1;
}
return 0;
}
static inline const char *tok_start(struct cstate *state, struct token *tok)
{
return state->input + tok->start;
}
static inline size_t intern_ident(struct cstate *state, struct token *tok)
{
assert(tok->type == TOK_IDENT);
return cb_agent_intern_string(tok_start(state, tok), tok_len(tok));
}
static struct token *peek(struct cstate *state, int *ok)
{
if (state->did_peek) {
*ok = 1;
return &state->peeked;
}
state->did_peek = 1;
*ok = !next_token(&state->lex_state, state->input, &state->peeked);
return &state->peeked;
}
static struct token next(struct cstate *state, int *ok)
{
struct token tok;
if (state->did_peek) {
*ok = 1;
state->did_peek = 0;
return state->peeked;
} else {
*ok = !next_token(&state->lex_state, state->input, &tok);
return tok;
}
}
/* These macros are expected to be used only within functions with a cstate*
* variable named state */
#define PEEK() ({ \
int _ok; \
struct token *_tok; \
_tok = peek(state, &_ok); \
if (!_ok) \
return 1; \
_tok; \
})
#define NEXT() ({ \
int _ok; \
struct token _tok = next(state, &_ok); \
if (!_ok) \
return 1; \
_tok; \
})
#define MATCH_P(TYPE) ({ \
struct token *tok = PEEK(); \
tok && tok->type != TOK_EOF && tok->type == (TYPE); \
})
#define MAYBE_CONSUME(TYPE) (MATCH_P(TYPE) ? (NEXT(), 1) : 0)
#define EXPECT(TYPE) ({ \
struct token *_tok = PEEK(); \
enum token_type typ = (TYPE); \
if (!_tok || _tok->type != typ) { \
enum token_type actual = _tok ? _tok->type \
: TOK_EOF; \
ERROR_AT_P(_tok, "Expected '%s', got '%s'", \
token_type_name(typ), \
token_type_name(actual)); \
return 1; \
} \
NEXT(); \
})
#define ERROR_AT_P(TOK, MSG, ...) ({ \
if (TOK) { \
ERROR_AT(*(TOK), MSG, ##__VA_ARGS__); \
} else { \
fprintf(stderr, "Error in %s at EOF: " MSG "\n", \
state->filename, ##__VA_ARGS__); \
} \
})
#define ERROR_AT(TOK, MSG, ...) ({ \
fprintf(stderr, "Error in %s at %zu:%zu: " MSG "\n", \
state->filename, (TOK).line, (TOK).column, \
##__VA_ARGS__); \
})
#define APPEND(B) (bytecode_push(state->bytecode, (B)))
#define APPEND_SIZE_T(S) (bytecode_push_size_t(state->bytecode, (S)))
#define LABEL() (bytecode_label(state->bytecode))
#define MARK(L) (bytecode_mark_label(state->bytecode, (L)))
#define ADDR_OF(L) (bytecode_address_of(state->bytecode, (L)))
#define UPDATE(IDX, VAL) (bytecode_update_size_t(state->bytecode, (IDX), \
(VAL)))
/* Propagate errors */
#define X(V) ({ if (V) return 1; })
static int compile_statement(struct cstate *);
static int compile_let_statement(struct cstate *, int export);
static int compile_function_statement(struct cstate *, int export);
static int compile_if_statement(struct cstate *);
static int compile_for_statement(struct cstate *);
static int compile_while_statement(struct cstate *);
static int compile_break_statement(struct cstate *);
static int compile_continue_statement(struct cstate *);
static int compile_return_statement(struct cstate *);
static int compile_export_statement(struct cstate *);
static int compile_import_statement(struct cstate *);
static int compile_struct_statement(struct cstate *, int export);
static int compile_expression_statement(struct cstate *);
static int compile_expression(struct cstate *);
static int compile(struct cstate *state, size_t name_id, int final)
{
struct token *tok;
struct bytecode_snapshot before;
int had_module;
bytecode_snapshot(state->bytecode, &before);
if (state->modspec) {
had_module = 1;
APPEND(OP_ENTER_MODULE);
APPEND_SIZE_T(cb_modspec_id(state->modspec));
} else {
had_module = 0;
state->modspec = cb_modspec_new(name_id);
APPEND(OP_INIT_MODULE);
APPEND_SIZE_T(cb_modspec_id(state->modspec));
}
while ((tok = PEEK()) && tok->type != TOK_EOF) {
if (compile_statement(state))
goto err;
}
EXPECT(TOK_EOF);
assert(state->modspec && "Missing modspec while compiling");
if (had_module) {
APPEND(OP_EXIT_MODULE);
} else {
APPEND(OP_END_MODULE);
cb_agent_add_modspec(state->modspec);
}
state->modspec = NULL;
if (final) {
APPEND(OP_HALT);
bytecode_finalize(state->bytecode);
}
return 0;
err:
bytecode_restore(state->bytecode, &before);
if (!had_module)
cb_agent_unreserve_modspec_id(cb_modspec_id(state->modspec));
return 1;
}
static int compile_statement(struct cstate *state)
{
switch (PEEK()->type) {
case TOK_LET:
X(compile_let_statement(state, 0));
break;
case TOK_FUNCTION:
X(compile_function_statement(state, 0));
break;
case TOK_IF:
X(compile_if_statement(state));
break;
case TOK_FOR:
X(compile_for_statement(state));
break;
case TOK_WHILE:
X(compile_while_statement(state));
break;
case TOK_BREAK:
X(compile_break_statement(state));
break;
case TOK_CONTINUE:
X(compile_continue_statement(state));
break;
case TOK_RETURN:
X(compile_return_statement(state));
break;
case TOK_EXPORT:
X(compile_export_statement(state));
break;
case TOK_IMPORT:
X(compile_import_statement(state));
break;
case TOK_STRUCT:
X(compile_struct_statement(state, 0));
break;
default:
X(compile_expression_statement(state));
break;
}
return 0;
}
static void export_name(struct cstate *state, size_t name)
{
cb_modspec_add_export(state->modspec, name);
}
static int declare_name(struct cstate *state, size_t name_id, int export)
{
size_t binding_id;
if (state->is_global) {
APPEND(OP_DECLARE_GLOBAL);
APPEND_SIZE_T(name_id);