-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler0.c
More file actions
1724 lines (1556 loc) · 37.5 KB
/
compiler0.c
File metadata and controls
1724 lines (1556 loc) · 37.5 KB
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
// Copyright 2022, Brian Swetland <swetland@frotz.net>
// Licensed under the Apache License, Version 2.0.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
// builtin types
#define nil 0
typedef uint32_t u32;
typedef int32_t i32;
typedef uint8_t u8;
typedef uint32_t token_t;
void error(const char *fmt, ...);
// ------------------------------------------------------------------
// structures
typedef struct String String;
typedef struct Symbol Symbol;
typedef struct Scope Scope;
typedef struct Type Type;
struct String {
String *next;
u32 len;
char text[0];
};
struct Symbol {
Symbol *next;
String *name;
Type *type;
u32 kind;
};
enum {
SYMBOL_VAR,
SYMBOL_FLD, // struct field
SYMBOL_PTR, // struct *field
SYMBOL_DEF, // enum
SYMBOL_FN,
};
struct Scope {
Scope *parent;
Symbol *first;
Symbol *last;
u32 kind;
};
enum {
SCOPE_GLOBAL,
SCOPE_FUNC,
SCOPE_BLOCK,
SCOPE_LOOP,
SCOPE_STRUCT,
};
struct Type {
Type *next;
String *name;
Type *of; // for: slice, array, ptr
Symbol *fields; // for: struct
u32 kind;
u32 count; // for: arrays
};
enum {
TYPE_VOID,
TYPE_BOOL,
TYPE_U8,
TYPE_U32,
// TYPE_NIL,
// TYPE_POINTER,
TYPE_ARRAY,
TYPE_SLICE,
TYPE_STR,
TYPE_STRUCT,
// TYPE_FUNC,
TYPE_ENUM,
TYPE_UNDEFINED,
};
typedef struct Ctx Ctx;
// ------------------------------------------------------------------
// compiler global context
struct Ctx {
const char* filename; // filename of active source
const char* outname; // base name for output files
int fd;
FILE *fp_decl; // output files
FILE *fp_type;
FILE *fp_impl;
int nl_decl; // flag to update #line
int nl_type;
int nl_impl;
u8 iobuffer[1024]; // scanner file io buffer
u32 ionext;
u32 iolast;
u32 linenumber; // line number of most recent line
u32 lineoffset; // position of start of most recent line
u32 byteoffset; // position of the most recent character
u32 flags;
u32 cc; // scanner: next character
token_t tok; // most recent token
u32 num; // used for tNUM
char tmp[256]; // used for tIDN, tSTR;
String *ident; // used for tIDN
String *stringlist; // all strings
Type *typelist; // all types
Scope *scope; // scope stack
Scope *fn; // args of active function being parsed
Scope global;
String *idn_if; // identifier strings
String *idn_fn;
String *idn_for;
String *idn_var;
String *idn_nil;
String *idn_new;
String *idn_case;
String *idn_else;
String *idn_enum;
String *idn_true;
String *idn_break;
String *idn_while;
String *idn_false;
String *idn_switch;
String *idn_struct;
String *idn_return;
String *idn_continue;
Type *type_void; // base types
Type *type_bool;
Type *type_str;
Type *type_u32;
Type *type_i32;
Type *type_u8;
char *outptr;
char outbuf[4096];
};
Ctx ctx;
// ------------------------------------------------------------------
String *string_make(const char* text, u32 len) {
// obviously this wants to be a hash table
String *str = ctx.stringlist;
while (str != nil) {
if ((str->len == len) && (memcmp(text, str->text, len) == 0)) {
return str;
}
str = str->next;
}
str = malloc(sizeof(String) + len + 1);
str->len = len;
memcpy(str->text, text, len);
str->text[len] = 0;
str->next = ctx.stringlist;
ctx.stringlist = str;
return str;
}
String *string_make_n(const char* s, ...) {
va_list ap;
va_start(ap, s);
char text[1024];
char *next = text;
do {
size_t len = strlen(s);
memcpy(next, s, len);
next += len;
} while ((s = va_arg(ap, const char*)) != NULL);
va_end(ap);
return string_make(text, next - text);
}
Scope *scope_push(u32 kind) {
Scope *scope = malloc(sizeof(Scope));
scope->first = nil;
scope->last = nil;
scope->parent = ctx.scope;
scope->kind = kind;
ctx.scope = scope;
return scope;
}
Scope *scope_pop(void) {
Scope *scope = ctx.scope;
ctx.scope = scope->parent;
return scope;
}
Scope *scope_find(u32 scope_kind) {
Scope *scope = ctx.scope;
while (scope != nil) {
if (scope->kind == scope_kind) {
return scope;
}
scope = scope->parent;
}
return nil;
}
Symbol *symbol_find_in(String *name, Scope *scope) {
for (Symbol *sym = scope->first; sym != nil; sym = sym->next) {
if (sym->name == name) {
return sym;
}
}
return nil;
}
// find the first surrounding scope of a specified kind
Symbol *symbol_find(String *name) {
for (Scope *scope = ctx.scope; scope != nil; scope = scope->parent) {
Symbol *sym = symbol_find_in(name, scope);
if (sym != nil) {
return sym;
}
}
return nil;
}
Symbol *symbol_make_in_scope(String *name, Type *type, Scope *scope) {
Symbol *sym = malloc(sizeof(Symbol));
sym->name = name;
sym->type = type;
sym->next = nil;
sym->kind = SYMBOL_VAR;
if (scope->first == nil) {
scope->first = sym;
} else {
scope->last->next = sym;
}
scope->last = sym;
return sym;
}
Symbol *symbol_make_global(String *name, Type *type) {
return symbol_make_in_scope(name, type, &ctx.global);
}
Symbol *symbol_make(String *name, Type *type) {
return symbol_make_in_scope(name, type, ctx.scope);
}
Type *type_make(String *name, u32 kind, Type *of, Symbol *fields, u32 count) {
Type *type = malloc(sizeof(Type));
type->name = name;
type->of = of;
type->fields = fields;
type->kind = kind;
type->count = count;
if (name != nil) {
type->next = ctx.typelist;
ctx.typelist = type;
} else {
type->next = nil;
}
return type;
}
Type *type_find(String *name) {
for (Type *t = ctx.typelist; t != nil; t = t->next) {
if (t->name == name) {
return t;
}
}
return nil;
}
Symbol *type_find_field(Type *type, String *name) {
if (type->kind != TYPE_STRUCT) {
error("not a struct");
}
for (Symbol *s = type->fields; s != nil; s = s->next) {
if (s->name == name) {
return s;
}
}
error("struct has no such field '%s'", name->text);
return nil;
}
// ================================================================
enum {
cfVisibleEOL = 1,
cfAbortOnError = 2,
cfTraceCodeGen = 3,
};
void ctx_init() {
memset(&ctx, 0, sizeof(ctx));
// pre-intern keywords
ctx.idn_if = string_make("if", 2);
ctx.idn_fn = string_make("fn", 2);
ctx.idn_for = string_make("for", 3);
ctx.idn_var = string_make("var", 3);
ctx.idn_nil = string_make("nil", 3);
ctx.idn_new = string_make("new", 3);
ctx.idn_case = string_make("case", 4);
ctx.idn_else = string_make("else", 4);
ctx.idn_enum = string_make("enum", 4);
ctx.idn_true = string_make("true", 4);
ctx.idn_break = string_make("break", 5);
ctx.idn_while = string_make("while", 5);
ctx.idn_false = string_make("false", 5);
ctx.idn_switch = string_make("switch", 6);
ctx.idn_struct = string_make("struct", 6);
ctx.idn_return = string_make("return", 6);
ctx.idn_continue = string_make("continue", 8);
ctx.type_void = type_make(string_make("void", 4), TYPE_VOID, nil, nil, 0);
ctx.type_bool = type_make(string_make("bool", 4), TYPE_BOOL, nil, nil, 0);
ctx.type_str = type_make(string_make("str", 3), TYPE_STR, nil, nil, 0);
ctx.type_u32 = type_make(string_make("u32", 3), TYPE_U32, nil, nil, 0);
ctx.type_i32 = type_make(string_make("i32", 3), TYPE_U32, nil, nil, 0);
ctx.type_u8 = type_make(string_make("u8", 2), TYPE_U8, nil, nil, 0);
ctx.scope = &(ctx.global);
ctx.outptr = ctx.outbuf;
}
void dump_file_line(const char* fn, u32 offset);
void dump_error_ctxt();
void error(const char *fmt, ...) {
va_list ap;
fprintf(stderr,"\n%s:%d: ", ctx.filename, ctx.linenumber);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
if (ctx.linenumber > 0) {
// dump_file_line(ctx.filename, ctx.lineoffset);
}
fprintf(stderr, "\n");
#if 0
dump_error_ctxt();
#endif
if (ctx.flags & cfAbortOnError) {
abort();
} else {
exit(1);
}
}
#define DECL ctx.fp_decl
#define TYPE ctx.fp_type
#define IMPL ctx.fp_impl
void emit(FILE* fp, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(fp, fmt, ap);
va_end(ap);
}
int indent = 0;
void emit_impl(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
int n = vsnprintf(ctx.outptr, sizeof(ctx.outbuf) - (ctx.outptr - ctx.outbuf), fmt, ap);
va_end(ap);
ctx.outptr += n;
if (fmt[strlen(fmt) - 1] == '\n') {
unsigned len = ctx.outptr - ctx.outbuf;
// any }s reduce the indent level of the current line
for (unsigned n = 0; n < len; n++) {
if (ctx.outbuf[n] == '}') indent--;
}
for (int n = 0; n < indent; n++) {
fwrite(" ", 1, 4, ctx.fp_impl);
}
fwrite(ctx.outbuf, 1, len, ctx.fp_impl);
// any {s increase the indent level of the next line
for (unsigned n = 0; n < len; n++) {
if (ctx.outbuf[n] == '{') indent++;
}
ctx.outptr = ctx.outbuf;
ctx.outbuf[0] = 0;
}
}
void emit_impl_str(void) {
u32 n = 0;
emit_impl("(void*) \"");
while (n < 256) {
u32 ch = ctx.tmp[n];
if (ch == 0) {
break;
} else if ((ch < ' ') || (ch > '~') || (ch == '"') || (ch == '\\')) {
emit_impl("\\x%02x", ch);
} else {
emit_impl("%c", ch);
}
n++;
}
emit_impl("\"");
}
#define emit_decl(fmt...) emit(DECL, fmt)
#define emit_type(fmt...) emit(TYPE, fmt)
#define KEEP_PARENS 0x10000
unsigned emit_impl_oparen(void) {
unsigned idx = ctx.outptr - ctx.outbuf;
*ctx.outptr++ = '(';
*ctx.outptr = 0;
return idx;
}
void emit_impl_cparen(unsigned idx) {
if (idx & KEEP_PARENS) {
*ctx.outptr++ = ')';
*ctx.outptr = 0;
} else {
unsigned len = ctx.outptr - ctx.outbuf;
idx &= 0xFFFF;
memmove(ctx.outbuf + idx, ctx.outbuf + idx + 1, len - idx);
ctx.outptr--;
}
}
void emit_impl_typename(Type* type, int ref);
void ctx_open_source(const char* filename) {
ctx.filename = filename;
ctx.linenumber = 0;
if (ctx.fd >= 0) {
close(ctx.fd);
}
ctx.fd = open(filename, O_RDONLY);
if (ctx.fd < 0) {
error("cannot open file '%s'", filename);
}
ctx.ionext = 0;
ctx.iolast = 0;
ctx.linenumber = 1;
ctx.lineoffset = 0;
ctx.byteoffset = 0;
}
void ctx_open_output(void) {
char tmp[1024];
ctx.nl_decl = 1;
ctx.nl_type = 1;
ctx.nl_impl = 1;
sprintf(tmp, "%s.decl.h", ctx.outname);
if ((ctx.fp_decl = fopen(tmp, "w")) == NULL) {
error("cannot open output '%s'", tmp);
}
sprintf(tmp, "%s.type.h", ctx.outname);
if ((ctx.fp_type = fopen(tmp, "w")) == NULL) {
error("cannot open output '%s'", tmp);
}
sprintf(tmp, "%s.impl.c", ctx.outname);
if ((ctx.fp_impl = fopen(tmp, "w")) == NULL) {
error("cannot open output '%s'", tmp);
}
emit_impl("#include <builtin.type.h>\n");
emit_impl("#include \"%s.type.h\"\n", ctx.outname);
emit_impl("#include \"%s.decl.h\"\n", ctx.outname);
}
// ================================================================
// lexical scanner
// token classes (tok & tcMASK)
enum {
tcRELOP = 0x08, tcADDOP = 0x10, tcMULOP = 0x18,
tcAEQOP = 0x20, tcMEQOP = 0x28, tcMASK = 0xF8,
};
enum {
// EndMarks, Braces, Brackets Parens
tEOF, tEOL, tOBRACE, tCBRACE, tOBRACK, tCBRACK, tOPAREN, tCPAREN,
// RelOps (do not reorder)
tEQ, tNE, tLT, tLE, tGT, tGE, tx0E, tx0F,
// AddOps (do not reorder)
tPLUS, tMINUS, tPIPE, tCARET, tx14, tx15, tx16, tx17,
// MulOps (do not reorder)
tSTAR, tSLASH, tPERCENT, tAMP, tLEFT, tRIGHT, tx1E, tx1F,
// AsnOps (do not reorder)
tADDEQ, tSUBEQ, tOREQ, tXOREQ, tx24, tx25, tx26, tx27,
tMULEQ, tDIVEQ, tMODEQ, tANDEQ, tLSEQ, tRSEQ, t2E, t2F,
// Various, UnaryNot, LogicalOps,
tSEMI, tCOLON, tDOT, tCOMMA, tNOT, tAND, tOR, tBANG,
tASSIGN, tINC, tDEC,
tAT,
// Keywords
tNEW, tFN, tSTRUCT, tVAR, tENUM,
tIF, tELSE, tWHILE,
tBREAK, tCONTINUE, tRETURN,
tFOR, tSWITCH, tCASE,
tTRUE, tFALSE, tNIL,
tIDN, tNUM, tSTR,
// used internal to the lexer but never returned
tSPC, tINV, tDQT, tSQT, tMSC,
};
const char *tnames[] = {
"<EOF>", "<EOL>", "{", "}", "[", "]", "(", ")",
"==", "!=", "<", "<=", ">", ">=", "", "",
"+", "-", "|", "^", "", "", "", "",
"*", "/", "%", "&", "<<", ">>", "", "",
"+=", "-=", "|=", "^=", "", "", "", "",
"*=", "/=", "%=", "&=", "<<=", ">>=", "", "",
";", ":", ".", ",", "~", "&&", "||", "!",
"=", "++", "--",
"@",
"new", "fn", "struct", "var", "enum",
"if", "else", "while",
"break", "continue", "return",
"for", "switch", "case",
"true", "false", "nil",
"<ID>", "<NUM>", "<STR>",
"<SPC>", "<INV>", "<DQT>", "<SQT>", "<MSC>",
};
u8 lextab[256] = {
tEOF, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tSPC, tEOL, tSPC, tINV, tSPC, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tSPC, tBANG, tDQT, tMSC, tMSC, tPERCENT, tAMP, tSQT,
tOPAREN, tCPAREN, tSTAR, tPLUS, tCOMMA, tMINUS, tDOT, tSLASH,
tNUM, tNUM, tNUM, tNUM, tNUM, tNUM, tNUM, tNUM,
tNUM, tNUM, tCOLON, tSEMI, tLT, tASSIGN, tGT, tMSC,
tAT, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN,
tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN,
tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN,
tIDN, tIDN, tIDN, tOBRACK, tMSC, tCBRACK, tCARET, tIDN,
tMSC, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN,
tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN,
tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN, tIDN,
tIDN, tIDN, tIDN, tOBRACE, tPIPE, tCBRACE, tNOT, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
tINV, tINV, tINV, tINV, tINV, tINV, tINV, tINV,
};
i32 unhex(u32 ch) {
if ((ch >= '0') && (ch <= '9')) {
return ch - '0';
}
if ((ch >= 'a') && (ch <= 'f')) {
return ch - 'a' + 10;
}
if ((ch >= 'A') && (ch <= 'F')) {
return ch - 'A' + 10;
}
return -1;
}
u32 scan() {
while (ctx.ionext == ctx.iolast) {
if (ctx.fd < 0) {
ctx.cc = 0;
return ctx.cc;
}
int r = read(ctx.fd, ctx.iobuffer, sizeof(ctx.iobuffer));
if (r <= 0) {
ctx.fd = -1;
} else {
ctx.iolast = r;
ctx.ionext = 0;
}
}
ctx.cc = ctx.iobuffer[ctx.ionext];
ctx.ionext++;
ctx.byteoffset++;
return ctx.cc;
}
u32 unescape(u32 n) {
if (n == 'n') {
return 10;
} else if (n == 'r') {
return 13;
} else if (n == 't') {
return 9;
} else if (n == '"') {
return '"';
} else if (n == '\'') {
return '\'';
} else if (n == '\\') {
return '\\';
} else if (n == 'x') {
int x0 = unhex(scan());
int x1 = unhex(scan());
if ((x0 < 0) || (x1 < 0)) {
error("invalid hex escape");
}
return (x0 << 4) | x1;
} else {
error("invalid escape 0x%02x", n);
return 0;
}
}
token_t scan_string(u32 cc, u32 nc) {
u32 n = 0;
while (true) {
if (nc == '"') {
nc = scan();
break;
} else if (nc == 0) {
error("unterminated string");
} else if (nc == '\\') {
ctx.tmp[n] = unescape(scan());
} else {
ctx.tmp[n] = nc;
}
nc = scan();
n++;
if (n == 255) {
error("constant string too large");
}
}
ctx.tmp[n] = 0;
return tSTR;
}
token_t scan_keyword(u32 len) {
ctx.tmp[len] = 0;
String *idn = string_make(ctx.tmp, len);
ctx.ident = idn;
if (len == 2) {
if (idn == ctx.idn_if) { return tIF; };
if (idn == ctx.idn_fn) { return tFN; }
} else if (len == 3) {
if (idn == ctx.idn_for) { return tFOR; }
if (idn == ctx.idn_var) { return tVAR; }
if (idn == ctx.idn_nil) { return tNIL; }
if (idn == ctx.idn_new) { return tNEW; }
} else if (len == 4) {
if (idn == ctx.idn_case) { return tCASE; }
if (idn == ctx.idn_else) { return tELSE; }
if (idn == ctx.idn_enum) { return tENUM; }
if (idn == ctx.idn_true) { return tTRUE; }
} else if (len == 5) {
if (idn == ctx.idn_break) { return tBREAK; }
if (idn == ctx.idn_while) { return tWHILE; }
if (idn == ctx.idn_false) { return tFALSE; }
} else if (len == 6) {
if (idn == ctx.idn_switch) { return tSWITCH; }
if (idn == ctx.idn_struct) { return tSTRUCT; }
if (idn == ctx.idn_return) { return tRETURN; }
} else if (len == 8) {
if (idn == ctx.idn_continue) { return tCONTINUE; }
}
return tIDN;
}
token_t scan_number(u32 cc, u32 nc) {
u32 n = 1;
u32 val = cc - '0';
if ((cc == '0') && (nc == 'b')) { // binary
nc = scan();
while ((nc == '0') || (nc == '1')) {
val = (val << 1) | (nc - '0');
nc = scan();
n++;
if (n == 34) {
error("binary constant too large");
}
}
} else if ((cc == '0') && (nc == 'x')) { // hex
nc = scan();
while (true) {
int tmp = unhex(nc);
if (tmp == -1) {
break;
}
val = (val << 4) | tmp;
nc = scan();
n++;
if (n == 10) {
error("hex constant too large");
}
}
} else { // decimal
while (lextab[nc] == tNUM) {
u32 tmp = (val * 10) + (nc - '0');
if (tmp <= val) {
error("decimal constant too large");
}
val = tmp;
nc = scan();
n++;
}
}
ctx.num = val;
return tNUM;
}
token_t scan_ident(u32 cc, u32 nc) {
ctx.tmp[0] = cc;
u32 n = 1;
while (true) {
u32 tok = lextab[nc];
if ((tok == tIDN) || (tok == tNUM)) {
ctx.tmp[n] = nc;
n++;
if (n == 32) { error("identifier too large"); }
nc = scan();
} else {
break;
}
}
return scan_keyword(n);
}
token_t _next() {
u8 nc = ctx.cc;
while (true) {
u8 cc = nc;
nc = scan();
u32 tok = lextab[cc];
if (tok == tNUM) { // 0..9
return scan_number(cc, nc);
} else if (tok == tIDN) { // _ A..Z a..z
return scan_ident(cc, nc);
} else if (tok == tDQT) { // "
return scan_string(cc, nc);
} else if (tok == tSQT) { // '
ctx.num = nc;
if (nc == '\\') {
ctx.num = unescape(scan());
}
nc = scan();
if (nc != '\'') {
error("unterminated character constant");
}
nc = scan();
return tNUM;
} else if (tok == tPLUS) {
if (nc == '+') { tok = tINC; nc = scan(); }
} else if (tok == tMINUS) {
if (nc == '-') { tok = tDEC; nc = scan(); }
} else if (tok == tAMP) {
if (nc == '&') { tok = tAND; nc = scan(); }
} else if (tok == tPIPE) {
if (nc == '|') { tok = tOR; nc = scan(); }
} else if (tok == tGT) {
if (nc == '=') { tok = tGE; nc = scan(); }
else if (nc == '>') { tok = tRIGHT; nc = scan(); }
} else if (tok == tLT) {
if (nc == '=') { tok = tLE; nc = scan(); }
else if (nc == '<') { tok = tLEFT; nc = scan(); }
} else if (tok == tASSIGN) {
if (nc == '=') { tok = tEQ; nc = scan(); }
} else if (tok == tBANG) {
if (nc == '=') { tok = tNE; nc = scan(); }
} else if (tok == tSLASH) {
if (nc == '/') {
// comment -- consume until EOL or EOF
while ((nc != '\n') && (nc != 0)) {
nc = scan();
}
continue;
}
} else if (tok == tEOL) {
ctx.linenumber++;
ctx.lineoffset = ctx.byteoffset;
if (ctx.flags & cfVisibleEOL) {
return tEOL;
}
continue;
} else if (tok == tSPC) {
continue;
} else if ((tok == tMSC) || (tok == tINV)) {
error("unknown character 0x%02x", cc);
}
// if we're an AddOp or MulOp, followed by an '='
if (((tok & 0xF0) == 0x10) && (nc == '=')) {
nc = scan();
// transform us to a XEQ operation
tok = tok + 0x10;
}
return tok;
}
}
void token_printstr(FILE *fp) {
u32 n = 0;
printf("\"");
while (n < 256) {
u32 ch = ctx.tmp[n];
if (ch == 0) {
break;
} else if ((ch < ' ') || (ch > '~')) {
fprintf(fp, "\\x%02x", ch);
} else if ((ch == '"') || (ch == '\\')) {
fprintf(fp, "\\%c", ch);
} else {
fprintf(fp, "%c", ch);
}
n++;
}
printf("\"");
}
void token_print(FILE *fp) {
if (ctx.tok == tNUM) {
fprintf(fp, "#%u ", ctx.num);
} else if (ctx.tok == tIDN) {
fprintf(fp, "@%s ", ctx.tmp);
} else if (ctx.tok == tEOL) {
fprintf(fp, "\n");
} else if (ctx.tok == tSTR) {
token_printstr(fp);
} else {
fprintf(fp, "%s ", tnames[ctx.tok]);
}
}
token_t next() {
#if 1
return (ctx.tok = _next());
#else
ctx.tok = _next();
token_print(stderr);
fprintf(stderr,"\n");
return ctx.tok;
#endif
}
void expected(const char* what) {
error("expected %s, found %s", what, tnames[ctx.tok]);
}
void expect(token_t tok) {
if (ctx.tok != tok) {
error("expected %s, found %s", tnames[tok], tnames[ctx.tok]);
}
}
void require(token_t tok) {
expect(tok);
next();
}
String *parse_name(const char* what) {
if (ctx.tok != tIDN) {
error("expected %s, found %s %u", what, tnames[ctx.tok], ctx.tok);
}
String *str = ctx.ident;
next();
return str;
}
void parse_expr(void);
// fwd_ref_ok indicates that an undefined typename
// may be treated as a forward reference. This is
// only used for pointers (because their size does
// not depend on their target).
Type *parse_type(bool fwd_ref_ok);
int is_type(const char* typename) {
String *name = ctx.ident;
Symbol *sym = symbol_find(name);
if (sym == nil) {
error("undefined identifier '%s'", name->text);
}
return !strcmp(sym->type->name->text, typename);
}
void parse_fn_call(String *name, int n) {
emit_impl("fn_%s(", name->text);
if (n > 0) {
emit_impl("$$%d%s", n - 1, ctx.tok == tCPAREN ? "" : ", ");
}
while (ctx.tok != tCPAREN) {
parse_expr();
if (ctx.tok != tCPAREN) {
require(tCOMMA);
emit_impl(", ");
}
}
next();
emit_impl(")");
}
// special handling for statements that are function calls
// allows for chained method calls sufficient for stuff like:
// error("cannot read @, code @").s(filename).n(status);
void parse_fn_statement(Symbol *sym) {
next();
Type *type = sym->type;
int isvoid = (type->kind == TYPE_VOID);
int n = 0;
if (!isvoid) {
// stash retval in a temporary in case we need it
emit_impl("{ t$%s%s $$%d = ", type->name->text, type->kind == TYPE_STRUCT ? "*" : "", n);
}
goto first;
while (ctx.tok == tDOT) {
next();
if (ctx.tok != tIDN) {
error("expected method name");
}
// mangle full method name
String *mname = string_make_n(type->name->text, "$", ctx.ident->text, NULL);
sym = symbol_find(mname);
if (sym == nil) {
error("unknown method %s", mname->text);
}
type = sym->type;
next();
n++;
emit_impl("; t$%s%s $$%d = ", type->name->text, type->kind == TYPE_STRUCT ? "*" : "", n);
first:
require(tOPAREN);
parse_fn_call(sym->name, n);
}
if (!isvoid) {
emit_impl("; }");
}
emit_impl(";\n");
}
void parse_ident(void) {
String *name = ctx.ident;
Symbol *sym = symbol_find(name);
next();
if (sym == nil) {
error("undefined identifier '%s'", name->text);
}
if (sym->kind == SYMBOL_DEF) {
emit_impl("c$%s", sym->name->text);
return;
}
if (ctx.tok == tOPAREN) {
// function call
next();
parse_fn_call(name, 0);
} else {
// variable access