forked from ksco/chibicc-riscv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.c
2487 lines (2086 loc) · 64.2 KB
/
parse.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
// This file contains a recursive descent parser for C.
//
// Most functions in this file are named after the symbols they are
// supposed to read from an input token list. For example, stmt() is
// responsible for reading a statement from a token list. The function
// then construct an AST node representing a statement.
//
// Each function conceptually returns two values, an AST node and
// remaining part of the input tokens. Since C doesn't support
// multiple return values, the remaining tokens are returned to the
// caller via a pointer argument.
//
// Input tokens are represented by a linked list. Unlike many recursive
// descent parsers, we don't have the notion of the "input token stream".
// Most parsing functions don't change the global state of the parser.
// So it is very easy to lookahead arbitrary number of tokens in this
// parser.
#include "chibicc.h"
// Scope for local variables, global variables, typedefs
// or enum constants
typedef struct VarScope VarScope;
struct VarScope {
VarScope *next;
char *name;
Obj *var;
Type *type_def;
Type *enum_ty;
int enum_val;
};
// Scope for struct, union or enum tags
typedef struct TagScope TagScope;
struct TagScope {
TagScope *next;
char *name;
Type *ty;
};
// Represents a block scope.
typedef struct Scope Scope;
struct Scope {
Scope *next;
// C has two block scopes; one is for variables/typedefs and
// the other is for struct/union/enum tags.
VarScope *vars;
TagScope *tags;
};
// Variable attributes such as typedef or extern.
typedef struct {
bool is_typedef;
bool is_static;
bool is_extern;
int align;
} VarAttr;
// This struct represents a variable initializer. Since initializers
// can be nested (e.g. `int x[2][2] = {{1, 2}, {3, 4}}`), this struct
// is a tree data structure.
typedef struct Initializer Initializer;
struct Initializer {
Initializer *next;
Type *ty;
Token *tok;
bool is_flexible;
// If it's not an aggregate type and has an initializer,
// `expr` has an initialization expression.
Node *expr;
// If it's an initializer for an aggregate type (e.g. array or struct),
// `children` has initializers for its children.
Initializer **children;
};
// For local variable initializer.
typedef struct InitDesg InitDesg;
struct InitDesg {
InitDesg *next;
int idx;
Member *member;
Obj *var;
};
// All local variable instances created during parsing are
// accumulated to this list.
static Obj *locals;
// Likewise, global variables are accumulated to this list.
static Obj *globals;
static Scope *scope = &(Scope){};
// Points to the function object the parser is currently parsing.
static Obj *current_fn;
// Lists of all goto statements and labels in the curent function.
static Node *gotos;
static Node *labels;
// Current "goto" and "continue" jump targets.
static char *brk_label;
static char *cont_label;
// Points to a node representing a switch if we are parsing
// a switch statement. Otherwise, NULL.
static Node *current_switch;
static bool is_typename(Token *tok);
static Type *declspec(Token **rest, Token *tok, VarAttr *attr);
static Type *typename(Token **rest, Token *tok);
static Type *enum_specifier(Token **rest, Token *tok);
static Type *type_suffix(Token **rest, Token *tok, Type *ty);
static Type *declarator(Token **rest, Token *tok, Type *ty);
static Node *declaration(Token **rest, Token *tok, Type *basety, VarAttr *attr);
static void initializer2(Token **rest, Token *tok, Initializer *init);
static Initializer *initializer(Token **rest, Token *tok, Type *ty, Type **new_ty);
static Node *lvar_initializer(Token **rest, Token *tok, Obj *var);
static void gvar_initializer(Token **rest, Token *tok, Obj *var);
static Node *compound_stmt(Token **rest, Token *tok);
static Node *stmt(Token **rest, Token *tok);
static Node *expr_stmt(Token **rest, Token *tok);
static Node *expr(Token **rest, Token *tok);
static int64_t eval(Node *node);
static int64_t eval2(Node *node, char **label);
static int64_t eval_rval(Node *node, char **label);
static Node *assign(Token **rest, Token *tok);
static Node *logor(Token **rest, Token *tok);
static double eval_double(Node *node);
static Node *conditional(Token **rest, Token *tok);
static Node *logand(Token **rest, Token *tok);
static Node *bitor(Token **rest, Token *tok);
static Node *bitxor(Token **rest, Token *tok);
static Node *bitand(Token **rest, Token *tok);
static Node *equality(Token **rest, Token *tok);
static Node *relational(Token **rest, Token *tok);
static Node *shift(Token **rest, Token *tok);
static Node *add(Token **rest, Token *tok);
static Node *new_add(Node *lhs, Node *rhs, Token *tok);
static Node *new_sub(Node *lhs, Node *rhs, Token *tok);
static Node *mul(Token **rest, Token *tok);
static Node *cast(Token **rest, Token *tok);
static Type *struct_decl(Token **rest, Token *tok);
static Type *union_decl(Token **rest, Token *tok);
static Node *postfix(Token **rest, Token *tok);
static Node *funcall(Token **rest, Token *tok, Node *node);
static Node *unary(Token **rest, Token *tok);
static Node *primary(Token **rest, Token *tok);
static Token *parse_typedef(Token *tok, Type *basety);
static bool is_function(Token *tok);
static Token *function(Token *tok, Type *basety, VarAttr *attr);
static Token *global_variable(Token *tok, Type *basety, VarAttr *attr);
static void enter_scope(void) {
Scope *sc = calloc(1, sizeof(Scope));
sc->next = scope;
scope = sc;
}
static void leave_scope(void) {
scope = scope->next;
}
// Find a variable by name.
static VarScope *find_var(Token *tok) {
for (Scope *sc = scope; sc; sc = sc->next)
for (VarScope *sc2 = sc->vars; sc2; sc2 = sc2->next)
if (equal(tok, sc2->name))
return sc2;
return NULL;
}
static Type *find_tag(Token *tok) {
for (Scope *sc = scope; sc; sc = sc->next)
for (TagScope *sc2 = sc->tags; sc2; sc2 = sc2->next)
if (equal(tok, sc2->name))
return sc2->ty;
return NULL;
}
static Node *new_node(NodeKind kind, Token *tok) {
Node *node = calloc(1, sizeof(Node));
node->kind = kind;
node->tok = tok;
return node;
}
static Node *new_binary(NodeKind kind, Node *lhs, Node *rhs, Token *tok) {
Node *node = new_node(kind, tok);
node->lhs = lhs;
node->rhs = rhs;
return node;
}
static Node *new_unary(NodeKind kind, Node *expr, Token *tok) {
Node *node = new_node(kind, tok);
node->lhs = expr;
return node;
}
static Node *new_num(int64_t val, Token *tok) {
Node *node = new_node(ND_NUM, tok);
node->val = val;
return node;
}
static Node *new_long(int64_t val, Token *tok) {
Node *node = new_node(ND_NUM, tok);
node->val = val;
node->ty = ty_long;
return node;
}
static Node *new_ulong(long val, Token *tok) {
Node *node = new_node(ND_NUM, tok);
node->val = val;
node->ty = ty_ulong;
return node;
}
static Node *new_var_node(Obj *var, Token *tok) {
Node *node = new_node(ND_VAR, tok);
node->var = var;
return node;
}
Node *new_cast(Node *expr, Type *ty) {
add_type(expr);
Node *node = calloc(1, sizeof(Node));
node->kind = ND_CAST;
node->tok = expr->tok;
node->lhs = expr;
node->ty = copy_type(ty);
return node;
}
static VarScope *push_scope(char *name) {
VarScope *sc = calloc(1, sizeof(VarScope));
sc->name = name;
sc->next = scope->vars;
scope->vars = sc;
return sc;
}
static Initializer *new_initializer(Type *ty, bool is_flexible) {
Initializer *init = calloc(1, sizeof(Initializer));
init->ty = ty;
if (ty->kind == TY_ARRAY) {
if (is_flexible && ty->size < 0) {
init->is_flexible = true;
return init;
}
init->children = calloc(ty->array_len, sizeof(Initializer *));
for (int i = 0; i < ty->array_len; i++)
init->children[i] = new_initializer(ty->base, false);
return init;
}
if (ty->kind == TY_STRUCT || ty->kind == TY_UNION) {
// Count the number of struct members.
int len = 0;
for (Member *mem = ty->members; mem; mem = mem->next)
len++;
init->children = calloc(len, sizeof(Initializer *));
for (Member *mem = ty->members; mem; mem = mem->next) {
if (is_flexible && ty->is_flexible && !mem->next) {
Initializer *child = calloc(1, sizeof(Initializer));
child->ty = mem->ty;
child->is_flexible = true;
init->children[mem->idx] = child;
} else {
init->children[mem->idx] = new_initializer(mem->ty, false);
}
}
return init;
}
return init;
}
static Obj *new_var(char *name, Type *ty) {
Obj *var = calloc(1, sizeof(Obj));
var->name = name;
var->ty = ty;
var->align = ty->align;
push_scope(name)->var = var;
return var;
}
static Obj *new_lvar(char *name, Type *ty) {
Obj *var = new_var(name, ty);
var->is_local = true;
var->next = locals;
locals = var;
return var;
}
static Obj *new_gvar(char *name, Type *ty) {
Obj *var = new_var(name, ty);
var->next = globals;
var->is_static = true;
var->is_definition = true;
globals = var;
return var;
}
static char *new_unique_name(void) {
static int id = 0;
return format(".L..%d", id++);
}
static Obj *new_anon_gvar(Type *ty) {
return new_gvar(new_unique_name(), ty);
}
static Obj *new_string_literal(char *p, Type *ty) {
Obj *var = new_anon_gvar(ty);
var->init_data = p;
return var;
}
static char *get_ident(Token *tok) {
if (tok->kind != TK_IDENT)
error_tok(tok, "expected an identifier");
return strndup(tok->loc, tok->len);
}
static Type *find_typedef(Token *tok) {
if (tok->kind == TK_IDENT) {
VarScope *sc = find_var(tok);
if (sc)
return sc->type_def;
}
return NULL;
}
static void push_tag_scope(Token *tok, Type *ty) {
TagScope *sc = calloc(1, sizeof(TagScope));
sc->name = strndup(tok->loc, tok->len);
sc->ty = ty;
sc->next = scope->tags;
scope->tags = sc;
}
// declspec = ("void" | "_Bool" | "char" | "short" | "int" | "long"
// | "typedef" | "static" | "extern"
// | "signed" | "unsigned"
// | struct-decl | union-decl | typedef-name
// | enum-specifier
// | "const" | "volatile" | "auto" | "register" | "restrict"
// | "__restrict" | "__restrict__" | "_Noreturn")+
//
// The order of typenames in a type-specifier doesn't matter. For
// example, `int long static` means the same as `static long int`.
// That can also be written as `static long` because you can omit
// `int` if `long` or `short` are specified. However, something like
// `char int` is not a valid type specifier. We have to accept only a
// limited combinations of the typenames.
//
// In this function, we count the number of occurrences of each typename
// while keeping the "current" type object that the typenames up
// until that point represent. When we reach a non-typename token,
// we returns the current type object.
static Type *declspec(Token **rest, Token *tok, VarAttr *attr) {
// We use a single integer as counters for all typenames.
// For example, bits 0 and 1 represents how many times we saw the
// keyword "void" so far. With this, we can use a switch statement
// as you can see below.
enum {
VOID = 1 << 0,
BOOL = 1 << 2,
CHAR = 1 << 4,
SHORT = 1 << 6,
INT = 1 << 8,
LONG = 1 << 10,
FLOAT = 1 << 12,
DOUBLE = 1 << 14,
OTHER = 1 << 16,
SIGNED = 1 << 17,
UNSIGNED = 1 << 18,
};
Type *ty = ty_int;
int counter = 0;
while (is_typename(tok)) {
// Handle storage class specifiers.
if (equal(tok, "typedef") || equal(tok, "static") || equal(tok, "extern")) {
if (!attr)
error_tok(tok, "storage class specifier is not allowed in this context");
if (equal(tok, "typedef"))
attr->is_typedef = true;
else if (equal(tok, "static"))
attr->is_static = true;
else
attr->is_extern = true;
if (attr->is_typedef && attr->is_static + attr->is_extern > 1)
error_tok(tok, "typedef may not be used together with static or extern");
tok = tok->next;
continue;
}
// These keywords are recognized but ignored.
if (consume(&tok, tok, "const") || consume(&tok, tok, "volatile") ||
consume(&tok, tok, "auto") || consume(&tok, tok, "register") ||
consume(&tok, tok, "restrict") || consume(&tok, tok, "__restrict") ||
consume(&tok, tok, "__restrict__") || consume(&tok, tok, "_Noreturn"))
continue;
if (equal(tok, "_Alignas")) {
if (!attr)
error_tok(tok, "_Alignas is not allowed in this context");
tok = skip(tok->next, "(");
if (is_typename(tok))
attr->align = typename(&tok, tok)->align;
else
attr->align = const_expr(&tok, tok);
tok = skip(tok, ")");
continue;
}
// Handle user-defined types.
Type *ty2 = find_typedef(tok);
if (equal(tok, "struct") || equal(tok, "union") || equal(tok, "enum") || ty2) {
if (counter)
break;
if (equal(tok, "struct")) {
ty = struct_decl(&tok, tok->next);
} else if (equal(tok, "union")) {
ty = union_decl(&tok, tok->next);
} else if (equal(tok, "enum")) {
ty = enum_specifier(&tok, tok->next);
} else {
ty = ty2;
tok = tok->next;
}
counter += OTHER;
continue;
}
// Handle built-in types.
if (equal(tok, "void"))
counter += VOID;
else if (equal(tok, "_Bool"))
counter += BOOL;
else if (equal(tok, "char"))
counter += CHAR;
else if (equal(tok, "short"))
counter += SHORT;
else if (equal(tok, "int"))
counter += INT;
else if (equal(tok, "long"))
counter += LONG;
else if (equal(tok, "float"))
counter += FLOAT;
else if (equal(tok, "double"))
counter += DOUBLE;
else if (equal(tok, "signed"))
counter |= SIGNED;
else if (equal(tok, "unsigned"))
counter |= UNSIGNED;
else
unreachable();
switch (counter) {
case VOID:
ty = ty_void;
break;
case BOOL:
ty = ty_bool;
break;
case CHAR:
case SIGNED + CHAR:
ty = ty_char;
break;
case UNSIGNED + CHAR:
ty = ty_uchar;
break;
case SHORT:
case SHORT + INT:
case SIGNED + SHORT:
case SIGNED + SHORT + INT:
ty = ty_short;
break;
case UNSIGNED + SHORT:
case UNSIGNED + SHORT + INT:
ty = ty_ushort;
break;
case INT:
case SIGNED:
case SIGNED + INT:
ty = ty_int;
break;
case UNSIGNED:
case UNSIGNED + INT:
ty = ty_uint;
break;
case LONG:
case LONG + INT:
case LONG + LONG:
case LONG + LONG + INT:
case SIGNED + LONG:
case SIGNED + LONG + INT:
case SIGNED + LONG + LONG:
case SIGNED + LONG + LONG + INT:
ty = ty_long;
break;
case UNSIGNED + LONG:
case UNSIGNED + LONG + INT:
case UNSIGNED + LONG + LONG:
case UNSIGNED + LONG + LONG + INT:
ty = ty_ulong;
break;
case FLOAT:
ty = ty_float;
break;
case DOUBLE:
case LONG + DOUBLE:
ty = ty_double;
break;
default:
error_tok(tok, "invalid type");
}
tok = tok->next;
}
*rest = tok;
return ty;
}
// func-params = ("void" | param ("," param)* ("," "...")?)? ")"
// param = declspec declarator
static Type *func_params(Token **rest, Token *tok, Type *ty) {
if (equal(tok, "void") && equal(tok->next, ")")) {
*rest = tok->next->next;
return func_type(ty);
}
Type head = {};
Type *cur = &head;
bool is_variadic = false;
while (!equal(tok, ")")) {
if (cur != &head)
tok = skip(tok, ",");
if (equal(tok, "...")) {
is_variadic = true;
tok = tok->next;
skip(tok, ")");
break;
}
Type *ty2 = declspec(&tok, tok, NULL);
ty2 = declarator(&tok, tok, ty2);
Token *name = ty2->name;
if (ty2->kind == TY_ARRAY) {
// "array of T" is converted to "pointer to T" only in the parameter
// context. For example, *argv[] is converted to **argv by this.
ty2 = pointer_to(ty2->base);
ty2->name = name;
} else if (ty2->kind == TY_FUNC) {
// Likewise, a function is converted to a pointer to a function
// only in the parameter context.
ty2 = pointer_to(ty2);
ty2->name = name;
}
cur = cur->next = copy_type(ty2);
}
if (cur == &head)
is_variadic = true;
ty = func_type(ty);
ty->params = head.next;
ty->is_variadic = is_variadic;
*rest = tok->next;
return ty;
}
// array-dimensions = ("static" | "restrict")* const-expr? "]" type-suffix
static Type *array_dimensions(Token **rest, Token *tok, Type *ty) {
while (equal(tok, "static") || equal(tok, "restrict"))
tok = tok->next;
if (equal(tok, "]")) {
ty = type_suffix(rest, tok->next, ty);
return array_of(ty, -1);
}
int sz = const_expr(&tok, tok);
tok = skip(tok, "]");
ty = type_suffix(rest, tok, ty);
return array_of(ty, sz);
}
// type-suffix = "(" func-params
// | "[" array-dimensions
// | ε
static Type *type_suffix(Token **rest, Token *tok, Type *ty) {
if (equal(tok, "("))
return func_params(rest, tok->next, ty);
if (equal(tok, "["))
return array_dimensions(rest, tok->next, ty);
*rest = tok;
return ty;
}
// pointers = ("*" ("const" | "volatile" | "restrict")*)*
static Type *pointers(Token **rest, Token *tok, Type *ty) {
while (consume(&tok, tok, "*")) {
ty = pointer_to(ty);
while (equal(tok, "const") || equal(tok, "volatile") || equal(tok, "restrict") ||
equal(tok, "__restrict") || equal(tok, "__restrict__"))
tok = tok->next;
}
*rest = tok;
return ty;
}
// declarator = pointers ("(" ident ")" | "(" declarator ")" | ident) type-suffix
static Type *declarator(Token **rest, Token *tok, Type *ty) {
ty = pointers(&tok, tok, ty);
if (equal(tok, "(")) {
Token *start = tok;
Type dummy = {};
declarator(&tok, start->next, &dummy);
tok = skip(tok, ")");
ty = type_suffix(rest, tok, ty);
return declarator(&tok, start->next, ty);
}
Token *name = NULL;
Token *name_pos = tok;
if (tok->kind == TK_IDENT) {
name = tok;
tok = tok->next;
}
ty = type_suffix(rest, tok, ty);
ty->name = name;
ty->name_pos = name_pos;
return ty;
}
// abstract-declarator = pointers ("(" abstract-declarator ")")? type-suffix
static Type *abstract_declarator(Token **rest, Token *tok, Type *ty) {
ty = pointers(&tok, tok, ty);
if (equal(tok, "(")) {
Token *start = tok;
Type dummy = {};
abstract_declarator(&tok, start->next, &dummy);
tok = skip(tok, ")");
ty = type_suffix(rest, tok, ty);
return abstract_declarator(&tok, start->next, ty);
}
return type_suffix(rest, tok, ty);
}
// type-name = declspec abstract-declarator
static Type *typename(Token **rest, Token *tok) {
Type *ty = declspec(&tok, tok, NULL);
return abstract_declarator(rest, tok, ty);
}
static bool is_end(Token *tok) {
return equal(tok, "}") || (equal(tok, ",") && equal(tok->next, "}"));
}
static bool consume_end(Token **rest, Token *tok) {
if (equal(tok, "}")) {
*rest = tok->next;
return true;
}
if (equal(tok, ",") && equal(tok->next, "}")) {
*rest = tok->next->next;
return true;
}
return false;
}
// enum-specifier = ident? "{" enum-list? "}"
// | ident ("{" enum-list? "}")?
//
// enum-list = ident ("=" num)? ("," ident ("=" num)?)* ","?
static Type *enum_specifier(Token **rest, Token *tok) {
Type *ty = enum_type();
// Read a struct tag.
Token *tag = NULL;
if (tok->kind == TK_IDENT) {
tag = tok;
tok = tok->next;
}
if (tag && !equal(tok, "{")) {
Type *ty = find_tag(tag);
if (!ty)
error_tok(tag, "unknown enum type");
if (ty->kind != TY_ENUM)
error_tok(tag, "not an enum tag");
*rest = tok;
return ty;
}
tok = skip(tok, "{");
// Read an enum-list.
int i = 0;
int val = 0;
while (!consume_end(rest, tok)) {
if (i++ > 0)
tok = skip(tok, ",");
char *name = get_ident(tok);
tok = tok->next;
if (equal(tok, "="))
val = const_expr(&tok, tok->next);
VarScope *sc = push_scope(name);
sc->enum_ty = ty;
sc->enum_val = val++;
}
if (tag)
push_tag_scope(tag, ty);
return ty;
}
// declaration = declspec (declarator ("=" expr)? ("," declarator ("=" expr)?)*)? ";"
static Node *declaration(Token **rest, Token *tok, Type *basety, VarAttr *attr) {
Node head = {};
Node *cur = &head;
int i = 0;
while (!equal(tok, ";")) {
if (i++ > 0)
tok = skip(tok, ",");
Type *ty = declarator(&tok, tok, basety);
if (ty->kind == TY_VOID)
error_tok(tok, "variable declared void");
if (!ty->name)
error_tok(ty->name_pos, "variable name omitted");
if (attr && attr->is_static) {
// static local variable
Obj *var = new_anon_gvar(ty);
push_scope(get_ident(ty->name))->var = var;
if (equal(tok, "="))
gvar_initializer(&tok, tok->next, var);
continue;
}
Obj *var = new_lvar(get_ident(ty->name), ty);
if (attr && attr->align)
var->align = attr->align;
if (equal(tok, "=")) {
Node *expr = lvar_initializer(&tok, tok->next, var);
cur = cur->next = new_unary(ND_EXPR_STMT, expr, tok);
}
if (var->ty->size < 0)
error_tok(ty->name, "variable has incomplete type");
if (var->ty->kind == TY_VOID)
error_tok(ty->name, "variable declared void");
}
Node *node = new_node(ND_BLOCK, tok);
node->body = head.next;
*rest = tok->next;
return node;
}
static Token *skip_excess_element(Token *tok) {
if (equal(tok, "{")) {
tok = skip_excess_element(tok->next);
return skip(tok, "}");
}
assign(&tok, tok);
return tok;
}
// string-initializer = string-literal
static void string_initializer(Token **rest, Token *tok, Initializer *init) {
if (init->is_flexible)
*init = *new_initializer(array_of(init->ty->base, tok->ty->array_len), false);
int len = MIN(init->ty->array_len, tok->ty->array_len);
for (int i = 0; i < len; i++)
init->children[i]->expr = new_num(tok->str[i], tok);
*rest = tok->next;
}
static int count_array_init_elements(Token *tok, Type *ty) {
Initializer *dummy = new_initializer(ty->base, false);
int i = 0;
for (; !consume_end(&tok, tok); i++) {
if (i > 0)
tok = skip(tok, ",");
initializer2(&tok, tok, dummy);
}
return i;
}
// array-initializer1 = "{" initializer ("," initializer)* ","? "}"
static void array_initializer1(Token **rest, Token *tok, Initializer *init) {
tok = skip(tok, "{");
if (init->is_flexible) {
int len = count_array_init_elements(tok, init->ty);
*init = *new_initializer(array_of(init->ty->base, len), false);
}
for (int i = 0; !consume_end(rest, tok); i++) {
if (i > 0)
tok = skip(tok, ",");
if (i < init->ty->array_len)
initializer2(&tok, tok, init->children[i]);
else
tok = skip_excess_element(tok);
}
}
// array-initializer2 = initializer ("," initializer)*
static void array_initializer2(Token **rest, Token *tok, Initializer *init) {
if (init->is_flexible) {
int len = count_array_init_elements(tok, init->ty);
*init = *new_initializer(array_of(init->ty->base, len), false);
}
for (int i = 0; i < init->ty->array_len && !is_end(tok); i++) {
if (i > 0)
tok = skip(tok, ",");
initializer2(&tok, tok, init->children[i]);
}
*rest = tok;
}
// struct-initializer1 = "{" initializer ("," initializer)* ","? "}"
static void struct_initializer1(Token **rest, Token *tok, Initializer *init) {
tok = skip(tok, "{");
Member *mem = init->ty->members;
while (!consume_end(rest, tok)) {
if (mem != init->ty->members)
tok = skip(tok, ",");
if (mem) {
initializer2(&tok, tok, init->children[mem->idx]);
mem = mem->next;
} else {
tok = skip_excess_element(tok);
}
}
}
// struct-initializer2 = initializer ("," initializer)*
static void struct_initializer2(Token **rest, Token *tok, Initializer *init) {
bool first = true;
for (Member *mem = init->ty->members; mem && !is_end(tok); mem = mem->next) {
if (!first)
tok = skip(tok, ",");
first = false;
initializer2(&tok, tok, init->children[mem->idx]);
}
*rest = tok;
}
static void union_initializer(Token **rest, Token *tok, Initializer *init) {
// Unlike structs, union initializers take only one initializer,
// and that initializes the first union member.
if (equal(tok, "{")) {
initializer2(&tok, tok->next, init->children[0]);
consume(&tok, tok, ",");
*rest = skip(tok, "}");
} else {
initializer2(rest, tok, init->children[0]);
}
}
// initializer = string-initializer | array-initializer
// | struct-initializer | union-initializer
// | assign
static void initializer2(Token **rest, Token *tok, Initializer *init) {
if (init->ty->kind == TY_ARRAY && tok->kind == TK_STR) {
string_initializer(rest, tok, init);
return;
}
if (init->ty->kind == TY_ARRAY) {
if (equal(tok, "{"))
array_initializer1(rest, tok, init);
else
array_initializer2(rest, tok, init);
return;
}
if (init->ty->kind == TY_STRUCT) {
if (equal(tok, "{")) {
struct_initializer1(rest, tok, init);
return;
}
// A struct can be initialized with another struct. E.g.
// `struct T x = y;` where y is a variable of type `struct T`.
// Handle that case first.
Node *expr = assign(rest, tok);
add_type(expr);
if (expr->ty->kind == TY_STRUCT) {
init->expr = expr;
return;
}
struct_initializer2(rest, tok, init);
return;
}
if (init->ty->kind == TY_UNION) {
union_initializer(rest, tok, init);
return;
}
if (equal(tok, "{")) {
// An initializer for a scalar variable can be surrounded by
// braces. E.g. `int x = {3};`. Handle that case.
initializer2(&tok, tok->next, init);
*rest = skip(tok, "}");
return;
}
init->expr = assign(rest, tok);
}
static Type *copy_struct_type(Type *ty) {
ty = copy_type(ty);
Member head = {};
Member *cur = &head;
for (Member *mem = ty->members; mem; mem = mem->next) {
Member *m = calloc(1, sizeof(Member));
*m = *mem;
cur = cur->next = m;
}
ty->members = head.next;
return ty;
}
static Initializer *initializer(Token **rest, Token *tok, Type *ty, Type **new_ty) {
Initializer *init = new_initializer(ty, true);
initializer2(rest, tok, init);
if ((ty->kind == TY_STRUCT || ty->kind == TY_UNION) && ty->is_flexible) {
ty = copy_struct_type(ty);
Member *mem = ty->members;
while (mem->next)
mem = mem->next;
mem->ty = init->children[mem->idx]->ty;
ty->size += mem->ty->size;
*new_ty = ty;
return init;
}
*new_ty = init->ty;
return init;