-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.c
1493 lines (1287 loc) · 35.1 KB
/
parser.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "ast_node.h"
#include "cimple.h"
#include "tokenizer.h"
#include "type.h"
// Scope for struct or union tags
typedef struct TagScope TagScope;
struct TagScope
{
TagScope *next;
const Token *name;
Type *type;
};
// Scope for local vars, global vars, typedefs or enum constants
typedef struct VarScope VarScope;
struct VarScope
{
VarScope *next;
char *name;
size_t name_len;
const Obj *var;
Type *type_def;
Type *enum_type;
int enum_val;
};
// 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;
} VarAttr;
static Scope global_scope = {NULL};
static Scope *scopes = &global_scope;
// 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;
// Points to the function object the parser is currently parsing.
static Obj *current_fn;
static bool is_typename(const Token *tok);
static Type *enum_specifier(const Token **rest, const Token *tok);
static Type *struct_decl(const Token **rest, const Token *tok);
static Type *union_decl(const Token **rest, const Token *tok);
static Type *declspec(const Token **rest, const Token *tok, VarAttr *attr);
static Type *declarator(const Token **rest, const Token *tok, Type *type);
static BlockNode *declaration(const Token **rest, const Token *tok,
Type *base_type);
static BlockNode *compound_stmt(const Token **rest, const Token *tok);
static Node *stmt(const Token **rest, const Token *tok);
static Node *expr_stmt(const Token **rest, const Token *tok);
static Node *expr(const Token **rest, const Token *tok);
static Node *assign(const Token **rest, const Token *tok);
static Node *equality(const Token **rest, const Token *tok);
static Node *comparison(const Token **rest, const Token *tok);
static Node *term(const Token **rest, const Token *tok);
static Node *new_add(Node *lhs, Node *rhs, const Token *tok);
static Node *new_sub(Node *lhs, Node *rhs, const Token *tok);
static Node *factor(const Token **rest, const Token *tok);
static Node *cast(const Token **rest, const Token *tok);
static Node *postfix(const Token **rest, const Token *tok);
static Node *unary(const Token **rest, const Token *tok);
static Node *primary(const Token **rest, const Token *tok);
static const Token *parse_typedef(const Token *tok, Type *base_type);
static Node *new_long_num_node(int64_t val, const Token *tok)
{
Node *node = new_num_node(val, tok);
node->type = long_type();
return node;
}
static void enter_scope(void)
{
Scope *sc = calloc(1, sizeof(Scope));
sc->next = scopes;
scopes = sc;
}
static void free_scope(Scope *scope)
{
// free Var scopes
VarScope *var_scope = scope->vars;
while (var_scope)
{
VarScope *dead_var_scope = var_scope;
var_scope = var_scope->next;
free(dead_var_scope);
}
// free tag scopes
TagScope *tag_scope = scope->tags;
while (tag_scope)
{
TagScope *dead_var_scope = tag_scope;
tag_scope = tag_scope->next;
free(dead_var_scope);
}
free(scope);
}
static void leave_scope(void)
{
Scope *dead_scope = scopes;
scopes = scopes->next;
free_scope(dead_scope);
}
// Find a variable by name.
static VarScope *find_var(const Token *tok)
{
for (Scope *sc = scopes; sc; sc = sc->next)
{
for (VarScope *vsc = sc->vars; vsc; vsc = vsc->next)
{
if (equal(tok, vsc->name, vsc->name_len))
return vsc;
}
}
return NULL;
}
static Type *find_tag(const Token *tok)
{
for (Scope *sc = scopes; sc; sc = sc->next)
for (TagScope *tag_sc = sc->tags; tag_sc; tag_sc = tag_sc->next)
if (tok->len == tag_sc->name->len &&
strncmp(tok->loc, tag_sc->name->loc, tok->len) == 0)
return tag_sc->type;
return NULL;
}
static void push_tag_scope(const Token *tok, Type *type)
{
TagScope *sc = calloc(1, sizeof(TagScope));
sc->name = tok;
sc->type = type;
sc->next = scopes->tags;
scopes->tags = sc;
}
static VarScope *push_scope(char *name, size_t name_len)
{
VarScope *sc = calloc(1, sizeof(VarScope));
sc->name = name;
sc->name_len = name_len;
sc->next = scopes->vars;
scopes->vars = sc;
return sc;
}
static Obj *new_var(Type *type, char *name, size_t len)
{
Obj *var = calloc(1, sizeof(Obj));
var->name = name;
var->name_length = len;
var->type = type;
push_scope(name, len)->var = var;
return var;
}
static Obj *new_lvar(Type *type, char *name, size_t name_len)
{
Obj *var = new_var(type, name, name_len);
var->is_local = true;
var->next = locals;
locals = var;
return var;
}
static Obj *new_gvar(Type *type, char *name, size_t name_len)
{
Obj *var = new_var(type, name, name_len);
var->next = globals;
globals = var;
return var;
}
static char *new_unique_name()
{
static int id = 0;
return format(".L..%d", id++);
}
static Obj *new_anon_gvar(Type *type)
{
char *unique_name = new_unique_name();
return new_gvar(type, unique_name, strlen(unique_name));
}
static Obj *new_string_literal(char *str, Type *type)
{
Obj *var = new_anon_gvar(type);
var->init_data = str;
return var;
}
static char *get_ident(const Token *tok)
{
if (tok->kind != TOKEN_IDENT)
{
error_tok(tok, "expected an identifier");
}
// TODO: optimize this (maybe we don't need a null-terminated string)
return strndup(tok->loc, tok->len);
}
static Type *find_typedef(const Token *tok)
{
if (check(tok, TOKEN_IDENT))
{
VarScope *sc = find_var(tok);
if (sc)
return sc->type_def;
}
return NULL;
}
static int64_t get_number(const Token *tok)
{
if (tok->kind != TOKEN_NUM)
{
error_tok(tok, "expected a number");
}
return tok->val;
}
// declspec = ("void" | "_Bool" | "char" | "short" | "int" | "long"
// | "typedef" | "static"
// | struct-decl | union-decl | typedef-name | enum-specifier)+
//
// 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(const Token **rest, const 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,
OTHER = 1 << 12,
};
Type *type = int_type();
int counter = 0;
while (is_typename(tok))
{
// Handle storage class specifiers
if (check(tok, TOKEN_TYPEDEF) || check(tok, TOKEN_STATIC))
{
if (!attr)
{
error_tok(tok, "storage class specifier is not allowed in this context");
}
if (check(tok, TOKEN_TYPEDEF))
attr->is_typedef = true;
else
attr->is_static = true;
if (attr->is_typedef && attr->is_static)
error_tok(tok, "typedef and static may not be used together");
tok = tok->next;
continue;
}
// Handle user-defined types.
Type *type_def = find_typedef(tok);
if (check(tok, TOKEN_STRUCT) || check(tok, TOKEN_UNION) || check(tok, TOKEN_ENUM) || type_def)
{
if (counter != 0)
break;
if (check(tok, TOKEN_STRUCT))
{
type = struct_decl(&tok, tok->next);
}
else if (check(tok, TOKEN_UNION))
{
type = union_decl(&tok, tok->next);
}
else if (check(tok, TOKEN_ENUM))
{
type = enum_specifier(&tok, tok->next);
}
else
{ // if(type_def)
type = type_def;
tok = tok->next;
}
counter += OTHER;
continue;
}
// Handle built-in types.
switch (tok->kind)
{
case TOKEN_VOID:
counter += VOID;
break;
case TOKEN_BOOL:
counter += BOOL;
break;
case TOKEN_CHAR:
counter += CHAR;
break;
case TOKEN_SHORT:
counter += SHORT;
break;
case TOKEN_INT:
counter += INT;
break;
case TOKEN_LONG:
counter += LONG;
break;
default:
unreachable();
}
switch (counter)
{
case VOID:
type = void_type();
break;
case BOOL:
type = bool_type();
break;
case CHAR:
type = char_type();
break;
case SHORT:
case SHORT + INT:
type = short_type();
break;
case INT:
type = int_type();
break;
case LONG:
case LONG + INT:
case LONG + LONG:
type = long_type();
break;
default:
error_tok(tok, "invalid type %d", tok->kind);
}
tok = tok->next;
}
*rest = tok;
return type;
}
// func-params = (param ("," param)*)? ")"
// param = declspec declarator
static Type *func_params(const Token **rest, const Token *tok,
Type *return_type)
{
Type head = {0};
Type *cur = &head;
while (!check(tok, TOKEN_RIGHT_PAREN))
{
if (cur != &head)
{
tok = consume(tok, TOKEN_COMMA);
}
Type *base_type = declspec(&tok, tok, NULL);
Type *type = declarator(&tok, tok, base_type);
cur = cur->next = type;
}
Type *type = func_type(return_type);
type->params = head.next;
*rest = tok->next;
return type;
}
// type-suffix = "(" func-params
// | "[" num "]" type-suffix
// | ε
static Type *type_suffix(const Token **rest, const Token *tok, Type *type)
{
if (match(&tok, tok, TOKEN_LEFT_PAREN))
return func_params(rest, tok, type);
if (match(&tok, tok, TOKEN_LEFT_BRACKET))
{
int array_count = get_number(tok);
tok = consume(tok, TOKEN_NUM);
tok = consume(tok, TOKEN_RIGHT_BRACKET);
type = type_suffix(rest, tok, type);
return array_of(type, array_count);
}
*rest = tok;
return type;
}
// declarator = "*"* ( ident | "(" ident ")" | "(" declarator ")" ) type-suffix
static Type *declarator(const Token **rest, const Token *tok, Type *type)
{
while (match(&tok, tok, TOKEN_STAR))
{
type = pointer_to(type);
}
if (match(&tok, tok, TOKEN_LEFT_PAREN))
{
const Token *start = tok;
Type dummy = {0};
declarator(&tok, start, &dummy);
tok = consume(tok, TOKEN_RIGHT_PAREN);
type = type_suffix(rest, tok, type);
return declarator(&tok, start, type);
}
if (tok->kind != TOKEN_IDENT)
error_tok(tok, "expected a variable name");
type = type_suffix(rest, tok->next, type);
type->name = tok;
return type;
}
// abstract-declarator = "*"* ("(" abstract-declarator ")")? type-suffix
static Type *abstract_declarator(const Token **rest, const Token *tok,
Type *type)
{
while (match(&tok, tok, TOKEN_STAR))
{
type = pointer_to(type);
}
if (match(&tok, tok, TOKEN_LEFT_PAREN))
{
const Token *start = tok;
Type dummy = {0};
abstract_declarator(&tok, start, &dummy);
tok = consume(tok, TOKEN_RIGHT_PAREN);
type = type_suffix(rest, tok, type);
return abstract_declarator(&tok, start, type);
}
return type_suffix(rest, tok, type);
}
// type-name = declspec abstract-declarator
static Type *typename(const Token **rest, const Token *tok)
{
Type *type = declspec(&tok, tok, NULL);
return abstract_declarator(rest, tok, type);
}
// enum-specifier = ident? "{" enum-list? "}"
// | ident ("{" enum-list? "}")?
//
// enum-list = ident ("=" num)? ("," ident ("=" num)?)*
static Type *enum_specifier(const Token **rest, const Token *tok)
{
// Read a struct tag.
const Token *tag = NULL;
if (check(tok, TOKEN_IDENT))
{
tag = tok;
tok = tok->next;
}
if (tag && !check(tok, TOKEN_LEFT_BRACE))
{
Type *type = find_tag(tag);
if (!type)
error_tok(tag, "unknown enum type");
if (type->kind != TYPE_ENUM)
error_tok(tag, "not an enum tag");
*rest = tok;
return type;
}
tok = consume(tok, TOKEN_LEFT_BRACE);
Type *type = enum_type();
// Read an enum-list.
int i = 0;
int enum_val = 0;
while (!check(tok, TOKEN_RIGHT_BRACE))
{
if (i++ > 0)
tok = consume(tok, TOKEN_COMMA);
char *name = get_ident(tok);
VarScope *sc = push_scope(name, tok->len);
sc->enum_type = type;
tok = tok->next;
if (check(tok, TOKEN_EQUAL))
{
enum_val = get_number(tok->next);
tok = tok->next->next;
}
sc->enum_val = enum_val++;
}
*rest = tok->next;
if (tag)
push_tag_scope(tag, type);
return type;
}
// declaration = declspec (declarator ("=" expr)? ("," declarator ("="
// expr)?)*)? ";"
static BlockNode *declaration(const Token **rest, const Token *tok,
Type *base_type)
{
Node head = {0};
Node *cur = &head;
int i = 0;
while (!check(tok, TOKEN_SEMICOLON))
{
if (i++ > 0)
tok = consume(tok, TOKEN_COMMA);
Type *type = declarator(&tok, tok, base_type);
if (type->kind == TYPE_VOID)
{
error_tok(tok, "variable declared void");
}
Obj *var = new_lvar(type, get_ident(type->name), type->name->len);
if (!check(tok, TOKEN_EQUAL))
continue;
Node *lhs = new_var_node(var, type->name);
Node *rhs = assign(&tok, tok->next);
Node *node = new_binary_node(NODE_ASSIGN, lhs, rhs, tok);
cur = cur->next = new_unary_node(NODE_EXPR_STMT, node, tok);
}
BlockNode *node = new_block_node(head.next, tok);
*rest = tok->next;
return node;
}
// Returns true if a given token represents a type.
static bool is_typename(const Token *tok)
{
switch (tok->kind)
{
case TOKEN_VOID:
case TOKEN_BOOL:
case TOKEN_CHAR:
case TOKEN_SHORT:
case TOKEN_INT:
case TOKEN_LONG:
case TOKEN_STRUCT:
case TOKEN_UNION:
case TOKEN_TYPEDEF:
case TOKEN_ENUM:
case TOKEN_STATIC:
return true;
default:
return find_typedef(tok) != NULL;
}
}
// stmt = "return" expr ";"
// | "if" "(" expr ")" stmt ("else" stmt)?
// | "for" "(" expr-stmt expr? ";" expr? ")" stmt
// | "while" "(" expr ")" stmt
// | "{" compound-stmt
// | expr-stmt
static Node *stmt(const Token **rest, const Token *tok)
{
if (check(tok, TOKEN_RETURN))
{
Node *return_expr = expr(&tok, tok->next);
add_type(return_expr);
Node *node = new_unary_node(NODE_RETURN, new_cast_node(return_expr, current_fn->type->return_type), tok);
*rest = consume(tok, TOKEN_SEMICOLON);
return node;
}
if (check(tok, TOKEN_IF))
{
const Token *start = tok;
tok = consume(tok->next, TOKEN_LEFT_PAREN);
Node *cond_expr = expr(&tok, tok);
tok = consume(tok, TOKEN_RIGHT_PAREN);
Node *then_stmt = stmt(&tok, tok);
Node *else_stmt;
if (check(tok, TOKEN_ELSE))
{
else_stmt = stmt(&tok, tok->next);
}
else
{
else_stmt = NULL;
}
Node *node = new_if_node(cond_expr, then_stmt, else_stmt, start);
*rest = tok;
return node;
}
if (check(tok, TOKEN_FOR))
{
const Token *start = tok;
tok = consume(tok->next, TOKEN_LEFT_PAREN);
enter_scope();
Node *init_expr;
if (is_typename(tok))
{
Type *base_type = declspec(&tok, tok, NULL);
init_expr = (Node *)declaration(&tok, tok, base_type);
}
else
{
init_expr = expr_stmt(&tok, tok);
}
Node *cond_expr;
if (!check(tok, TOKEN_SEMICOLON))
cond_expr = expr(&tok, tok);
else
cond_expr = NULL;
tok = consume(tok, TOKEN_SEMICOLON);
Node *inc_expr;
if (!check(tok, TOKEN_RIGHT_PAREN))
inc_expr = expr(&tok, tok);
else
inc_expr = NULL;
tok = consume(tok, TOKEN_RIGHT_PAREN);
Node *body_stmt = stmt(rest, tok);
Node *node = new_for_node(init_expr, cond_expr, inc_expr, body_stmt, start);
leave_scope();
return node;
}
if (check(tok, TOKEN_WHILE))
{
const Token *start = tok;
tok = consume(tok->next, TOKEN_LEFT_PAREN);
Node *cond_expr = expr(&tok, tok);
tok = consume(tok, TOKEN_RIGHT_PAREN);
Node *body_stmt = stmt(rest, tok);
Node *node = new_for_node(NULL, cond_expr, NULL, body_stmt, start);
return node;
}
if (match(&tok, tok, TOKEN_LEFT_BRACE))
{
return (Node *)compound_stmt(rest, tok);
}
return expr_stmt(rest, tok);
}
// compound-stmt = (typedef | declaration | stmt)* "}"
static BlockNode *compound_stmt(const Token **rest, const Token *tok)
{
Node head = {0};
Node *cur = &head;
enter_scope();
while (!check(tok, TOKEN_RIGHT_BRACE))
{
if (is_typename(tok))
{
VarAttr attr = {0};
Type *base_type = declspec(&tok, tok, &attr);
if (attr.is_typedef)
{
tok = parse_typedef(tok, base_type);
continue;
}
cur = cur->next = (Node *)declaration(&tok, tok, base_type);
}
else
{
cur = cur->next = stmt(&tok, tok);
}
add_type(cur);
}
leave_scope();
BlockNode *node = new_block_node(head.next, tok);
*rest = tok->next;
return node;
}
// expr-stmt = expr? ";"
static Node *expr_stmt(const Token **rest, const Token *tok)
{
if (match(rest, tok, TOKEN_SEMICOLON))
{
// empty expression
return (Node *)new_block_node(NULL, tok);
}
const Token *start = tok;
Node *node = expr(&tok, tok);
node = new_unary_node(NODE_EXPR_STMT, node, start);
*rest = consume(tok, TOKEN_SEMICOLON);
return node;
}
// expr = assign ("," expr)?
static Node *expr(const Token **rest, const Token *tok)
{
Node *node = assign(&tok, tok);
if (check(tok, TOKEN_COMMA))
return new_binary_node(NODE_COMMA, node, expr(rest, tok->next), tok);
*rest = tok;
return node;
}
// assign = equality (assign-op assign)?
// assign-op = "=" | "+=" | "-=" | "*=" | "/="
static Node *assign(const Token **rest, const Token *tok)
{
Node *node = equality(&tok, tok);
if (check(tok, TOKEN_EQUAL))
return new_binary_node(NODE_ASSIGN, node, assign(rest, tok->next), tok);
if (check(tok, TOKEN_PLUS_EQUAL))
{
Node *lhs = node;
Node *rhs = new_add(lhs, assign(rest, tok->next), tok);
return new_binary_node(NODE_ASSIGN, lhs, rhs, tok);
}
if (check(tok, TOKEN_MINUS_EQUAL))
{
Node *lhs = node;
Node *rhs = new_sub(lhs, assign(rest, tok->next), tok);
return new_binary_node(NODE_ASSIGN, lhs, rhs, tok);
}
if (check(tok, TOKEN_STAR_EQUAL))
{
Node *lhs = node;
Node *rhs = new_binary_node(NODE_MUL, lhs, assign(rest, tok->next), tok);
return new_binary_node(NODE_ASSIGN, lhs, rhs, tok);
}
if (check(tok, TOKEN_SLASH_EQUAL))
{
Node *lhs = node;
Node *rhs = new_binary_node(NODE_DIV, lhs, assign(rest, tok->next), tok);
return new_binary_node(NODE_ASSIGN, lhs, rhs, tok);
}
*rest = tok;
return node;
}
// equality = comparison ("==" comparison | "!=" comparison)*
static Node *equality(const Token **rest, const Token *tok)
{
Node *node = comparison(&tok, tok);
for (;;)
{
const Token *start = tok;
if (check(tok, TOKEN_EQUAL_EQUAL))
{
node = new_binary_node(NODE_EQ, node, comparison(&tok, tok->next), start);
continue;
}
if (check(tok, TOKEN_BANG_EQUAL))
{
node = new_binary_node(NODE_NE, node, comparison(&tok, tok->next), start);
continue;
}
*rest = tok;
return node;
}
}
// comparison = term ("<" term | "<=" term | ">" term | ">=" term)*
static Node *comparison(const Token **rest, const Token *tok)
{
Node *node = term(&tok, tok);
for (;;)
{
const Token *start = tok;
if (check(tok, TOKEN_LESS))
{
node = new_binary_node(NODE_LT, node, term(&tok, tok->next), start);
continue;
}
if (check(tok, TOKEN_LESS_EQUAL))
{
node = new_binary_node(NODE_LE, node, term(&tok, tok->next), start);
continue;
}
if (check(tok, TOKEN_GREATER))
{
node = new_binary_node(NODE_LT, term(&tok, tok->next), node, start);
continue;
}
if (check(tok, TOKEN_GREATER_EQUAL))
{
node = new_binary_node(NODE_LE, term(&tok, tok->next), node, start);
continue;
}
*rest = tok;
return node;
}
}
// In C, `+` operator is overloaded to perform the pointer arithmetic.
// If p is a pointer, p+n adds not n but sizeof(*p)*n to the value of p,
// so that p+n points to the location n elements (not bytes) ahead of p.
// In other words, we need to scale an integer value before adding to a
// pointer value. This function takes care of the scaling.
static Node *new_add(Node *lhs, Node *rhs, const Token *tok)
{
add_type(lhs);
add_type(rhs);
// num + num
if (is_integer(lhs->type) && is_integer(rhs->type))
return new_binary_node(NODE_ADD, lhs, rhs, tok);
if (lhs->type->base && rhs->type->base)
error_tok(tok, "invalid operands");
// Canonicalize `num + ptr` to `ptr + num`.
if (!lhs->type->base && rhs->type->base)
{
Node *tmp = lhs;
lhs = rhs;
rhs = tmp;
}
if (rhs->tag == NODE_TAG_NUM)
{
((NumNode *)rhs)->val *= lhs->type->base->size;
}
else
{
// ptr + num
rhs = new_binary_node(NODE_MUL, rhs, new_long_num_node(lhs->type->base->size, tok),
tok); // TODO: make this a right left (<<) by n instead
}
return new_binary_node(NODE_ADD, lhs, rhs, tok);
}
// Like `+`, `-` is overloaded for the pointer type.
static Node *new_sub(Node *lhs, Node *rhs, const Token *tok)
{
add_type(lhs);
add_type(rhs);
// num - num
if (is_integer(lhs->type) && is_integer(rhs->type))
return new_binary_node(NODE_SUB, lhs, rhs, tok);
// ptr - num
if (lhs->type->base && is_integer(rhs->type))
{
if (rhs->tag == NODE_TAG_NUM)
{
((NumNode *)rhs)->val *= lhs->type->base->size;
}
else
{
rhs = new_binary_node(NODE_MUL,
rhs,
new_long_num_node(lhs->type->base->size, tok),
tok); // TODO: make this a right left (<<) by n instead
}
add_type(rhs);
Node *node = new_binary_node(NODE_SUB, lhs, rhs, tok);
node->type = lhs->type;
return node;
}
// ptr - ptr, which returns how many elements are between the two.
if (lhs->type->base && rhs->type->base)
{
Node *node = new_binary_node(NODE_SUB, lhs, rhs, tok);
node->type = int_type();
// TODO: make this a right shift (>>) by n instead
return new_binary_node(NODE_DIV, node,
new_num_node(lhs->type->base->size, tok), tok);
}
error_tok(tok, "invalid operands");
return NULL; // unreachable
}
// term = factor ("+" factor | "-" factor)*
static Node *term(const Token **rest, const Token *tok)
{
Node *node = factor(&tok, tok);
for (;;)
{
const Token *start = tok;
if (check(tok, TOKEN_PLUS))
{
node = new_add(node, factor(&tok, tok->next), start);
continue;
}
if (check(tok, TOKEN_MINUS))
{
node = new_sub(node, factor(&tok, tok->next), start);
continue;
}
*rest = tok;
return node;
}
}
// factor = cast ("*" cast | "/" cast)*
static Node *factor(const Token **rest, const Token *tok)
{
Node *node = cast(&tok, tok);
for (;;)
{
const Token *start = tok;
if (check(tok, TOKEN_STAR))
{
node = new_binary_node(NODE_MUL, node, cast(&tok, tok->next), start);
continue;
}
if (check(tok, TOKEN_SLASH))
{
node = new_binary_node(NODE_DIV, node, cast(&tok, tok->next), start);