-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathc2_parser_expr.c2
More file actions
941 lines (836 loc) · 28.6 KB
/
c2_parser_expr.c2
File metadata and controls
941 lines (836 loc) · 28.6 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
/* Copyright 2022-2026 Bas van den Berg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module c2_parser;
//import ast_builder local; // BUG: should have to be imported
import ast local;
import c2_prec local;
import constants;
import token local;
import src_loc local;
import ctype local;
import string;
fn Expr* Parser.parseExpr(Parser* p) {
Expr* lhs = p.parseAssignmentExpression();
if (lhs.isInitlistAssignment())
return lhs;
return p.parseRHSOfBinaryExpression(lhs, Prec.Comma);
}
fn Expr* Parser.parseAssignmentExpression(Parser* p) {
Expr* lhs = p.parseCastExpr(false, false);
return p.parseRHSOfBinaryExpression(lhs, Prec.Assignment);
}
const Prec[Kind] BinOpPrecLookup = {
[Comma] = Comma,
[Equal] = Assignment,
[StarEqual] = Assignment,
[SlashEqual] = Assignment,
[PercentEqual] = Assignment,
[PlusEqual] = Assignment,
[MinusEqual] = Assignment,
[LessLessEqual] = Assignment,
[GreaterGreaterEqual] = Assignment,
[AmpEqual] = Assignment,
[CaretEqual] = Assignment,
[PipeEqual] = Assignment,
[Question] = Conditional,
[PipePipe] = LogicalAndOr,
[AmpAmp] = LogicalAndOr,
[ExclaimEqual] = Relational,
[EqualEqual] = Relational,
[LessEqual] = Relational,
[Less] = Relational,
[Greater] = Relational,
[GreaterEqual] = Relational,
[Plus] = Additive,
[Minus] = Additive,
[Pipe] = Bitwise,
[Caret] = Bitwise,
[Amp] = Bitwise,
[LessLess] = Shift,
[GreaterGreater] = Shift,
[Percent] = Multiplicative,
[Slash] = Multiplicative,
[Star] = Multiplicative,
}
// Note: all empty entries are also 0 (= BinaryOpcode.Multiply)
const BinaryOpcode[Kind] BinOpTokenLookup = {
[Star] = Multiply,
[Slash] = Divide,
[Percent] = Remainder,
[Plus] = Add,
[Minus] = Subtract,
[LessLess] = ShiftLeft,
[GreaterGreater] = ShiftRight,
[Less] = LessThan,
[Greater] = GreaterThan,
[LessEqual] = LessEqual,
[GreaterEqual] = GreaterEqual,
[EqualEqual] = Equal,
[ExclaimEqual] = NotEqual,
[Amp] = And,
[Caret] = Xor,
[Pipe] = Or,
[AmpAmp] = LAnd,
[PipePipe] = LOr,
[Equal] = Assign,
[StarEqual] = MulAssign,
[SlashEqual] = DivAssign,
[PercentEqual] = RemAssign,
[PlusEqual] = AddAssign,
[MinusEqual] = SubAssign,
[LessLessEqual] = ShlAssign,
[GreaterGreaterEqual] = ShrAssign,
[AmpEqual] = AndAssign,
[CaretEqual] = XorAssign,
[PipeEqual] = OrAssign,
}
fn Expr* Parser.parseRHSOfBinaryExpression(Parser* p, Expr* lhs, Prec minPrec) {
Prec nextTokPrec = BinOpPrecLookup[p.tok.kind];
SrcLoc colonLoc = 0;
while (1) {
if (nextTokPrec < minPrec) return lhs;
if (p.tok.kind == Comma) return lhs;
Token opToken = p.tok;
p.consumeToken();
Expr* ternaryMiddle = nil;
if (nextTokPrec == Conditional) {
if (p.tok.kind == Colon) {
p.error("TODO conditional expr"); // or warning?
} else {
ternaryMiddle = p.parseExpr();
}
if (p.tok.kind == Colon) {
colonLoc = p.tok.loc;
p.consumeToken();
}
}
if (p.tok.kind == LBrace && opToken.kind == Equal) {
Expr* rhs = p.parseInitList();
BinaryOpcode opcode = Assign;
return p.builder.actOnBinaryOperator(opToken.loc, opcode, lhs, rhs);
}
Expr* rhs = p.parseCastExpr(false, false);
Prec thisPrec = nextTokPrec;
nextTokPrec = BinOpPrecLookup[p.tok.kind];
bool isRightAssoc = (thisPrec == Conditional || thisPrec == Assignment);
if (thisPrec < nextTokPrec || (thisPrec == nextTokPrec && isRightAssoc)) {
rhs = p.parseRHSOfBinaryExpression(rhs, (Prec)(thisPrec + !isRightAssoc));
nextTokPrec = BinOpPrecLookup[p.tok.kind];
}
if (ternaryMiddle) {
lhs = p.builder.actOnConditionalOperator(opToken.loc,
colonLoc,
lhs,
ternaryMiddle,
rhs);
} else {
BinaryOpcode opcode = BinOpTokenLookup[opToken.kind];
lhs = p.builder.actOnBinaryOperator(opToken.loc, opcode, lhs, rhs);
}
}
}
const u8[Kind] CastExprTokenLookup = {
//[Comma] = Prec.Comma,
[Identifier] = 1,
[IntegerLiteral] = 2,
[FloatLiteral] = 3,
[CharLiteral] = 4,
[StringLiteral] = 5,
[LParen] = 6,
[Star] = 7,
[Tilde] = 7,
[Plus] = 7,
[Minus] = 7,
[Exclaim] = 7,
[Amp] = 7,
[PlusPlus] = 7,
[MinusMinus] = 7,
[KW_cast] = 8,
[KW_elemsof] = 9,
[KW_enum_min] = 10,
[KW_enum_max] = 10,
[KW_false] = 11,
[KW_true] = 11,
[KW_nil] = 12,
[KW_offsetof] = 13,
[KW_sizeof] = 14,
[KW_to_container] = 15,
[KW_bool] = 16,
[KW_char] = 16,
[KW_i8] = 16,
[KW_i16] = 16,
[KW_i32] = 16,
[KW_i64] = 16,
[KW_u8] = 16,
[KW_u16] = 16,
[KW_u32] = 16,
[KW_u64] = 16,
[KW_isize] = 16,
[KW_usize] = 16,
[KW_f32] = 16,
[KW_f64] = 16,
}
// Note: tried lookup table, was slower..
fn UnaryOpcode convertTokenToUnaryOpcode(Kind kind) {
switch (kind) {
case Exclaim: return LNot;
case Star: return Deref;
case Amp: return AddrOf;
case PlusPlus: return PreInc;
case Plus: return Plus;
case Minus: return Minus;
case MinusMinus: return PreDec;
case Tilde: return Not;
default:
assert(0);
break;
}
return PreInc;
}
fn Expr* Parser.parseCastExpr(Parser* p, bool /*isUnaryExpr*/, bool /*isAddrOfOp*/) {
// This handles all of cast-expression, unary-expression, postfix-expression,
// and primary-expression. We handle them together like this for efficiency
// and to simplify handling of an expression starting with a '(' token: which
// may be one of a parenthesized expression, cast-expression, compound literal
// expression, or statement expression.
//
// If the parsed tokens consist of a primary-expression, the cases below
// break out of the switch; at the end we call ParsePostfixExpressionSuffix
// to handle the postfix expression suffixes. Cases that cannot be followed
// by postfix exprs should return without invoking
// ParsePostfixExpressionSuffix.
Kind savedKind = p.tok.kind;
Expr* res = nil;
bool couldBeTemplateCall = false;
switch (CastExprTokenLookup[savedKind]) {
case 0: // other
p.error("expected expression");
break;
case 1: // Identifier
// parse all members in a single shot
res = p.parsePureMemberExpr();
couldBeTemplateCall = true;
/*
// Make sure to pass down the right value for isAddressOfOperand.
if (isAddressOfOperand && isPostfixExpressionSuffixStart())
isAddressOfOperand = false;
*/
break;
case 2: // IntegerLiteral
u64 val = p.tok.int_value;
BuiltinKind kind;
if (val <= i32.max)
kind = Int32;
else
if (val <= u32.max && p.tok.getRadix() != Default)
kind = UInt32;
else
if (val <= i64.max)
kind = Int64;
else
kind = UInt64;
res = p.builder.actOnIntegerLiteral(p.tok.loc, p.tok.len, p.tok.int_value, p.tok.getRadix(), kind);
p.consumeToken();
break;
case 3: // FloatLiteral
BuiltinKind kind = p.tok.suffix_F ? Float32 : Float64;
res = p.builder.actOnFloatLiteral(p.tok.loc, p.tok.len, p.tok.float_value, p.tok.getRadix(), kind);
p.consumeToken();
break;
case 4: // CharLiteral
res = p.builder.actOnCharLiteral(p.tok.loc, p.tok.len, p.tok.char_value, p.tok.getRadix());
p.consumeToken();
break;
case 5: // StringLiteral
res = p.parseStringLiteral();
break;
case 6: // LParen
res = p.parseParenExpr();
break;
case 7: // Star, Tilde, Plus, Minus, Exclaim, Amp, PlusPlus, MinusMinus
SrcLoc loc = p.tok.loc;
p.consumeToken();
bool is_addrof_op = (savedKind == Amp);
res = p.parseCastExpr(false, is_addrof_op);
UnaryOpcode opcode = convertTokenToUnaryOpcode(savedKind);
return p.builder.actOnUnaryOperator(loc, opcode, res);
case 8: // KW_cast
res = p.parseExplicitCastExpr();
break;
case 9: // KW_elemsof
res = p.parseElemsof();
break;
case 10: // KW_enum_min, KW_enum_max
return p.parseEnumMinMax(savedKind == KW_enum_min);
case 11: // KW_false, KW_true
res = p.builder.actOnBooleanConstant(p.tok.loc, savedKind == KW_true);
p.consumeToken();
break;
case 12: // KW_nil
res = p.builder.actOnNilExpr(p.tok.loc);
p.consumeToken();
break;
case 13: // KW_offsetof
return p.parseOffsetOfExpr();
case 14: // KW_sizeof
return p.parseSizeof();
case 15: // KW_to_container
res = p.parseToContainerExpr();
break;
case 16: // builtin type
if (p.peekToken(1) == Dot) {
p.addImplicitImport(p.tok.name_idx, false);
res = p.parsePureMemberExpr();
} else {
p.error("expected expression");
}
break;
}
return p.parsePostfixExprSuffix(res, couldBeTemplateCall);
}
fn Expr* Parser.parsePostfixExprSuffix(Parser* p, Expr* lhs, bool couldBeTemplateCall) {
while (1) {
switch (p.tok.kind) {
case Identifier:
return lhs;
case LParen:
// C2: can only be call expr?
lhs = p.parseCallExpr(lhs);
break;
case LSquare:
SrcLoc loc = p.tok.loc;
p.consumeToken();
Expr* idx = p.parseExpr();
if (p.tok.kind == Colon) {
// BitOffset <expr> : <expr>
SrcLoc colon_loc = p.tok.loc;
p.consumeToken();
Expr* rhs = p.parseExpr();
idx = p.builder.actOnBitOffsetExpr(colon_loc, idx, rhs);
}
u32 src_len = p.tok.loc + 1 - loc;
p.expectAndConsume(RSquare);
lhs = p.builder.actOnArraySubscriptExpr(loc, src_len, lhs, idx);
break;
case Dot:
lhs = p.parseImpureMemberExpr(lhs);
break;
case PlusPlus:
lhs = p.builder.actOnUnaryOperator(p.tok.loc, PostInc, lhs);
p.consumeToken();
break;
case MinusMinus:
lhs = p.builder.actOnUnaryOperator(p.tok.loc, PostDec, lhs);
p.consumeToken();
break;
case Less:
if (couldBeTemplateCall && p.isTemplateFunctionCall()) {
p.consumeToken();
TypeRefHolder ref.init();
p.parseTypeSpecifier(&ref);
p.expectAndConsume(Greater);
if (p.tok.kind != LParen) {
p.error("missing argument list for template function call");
}
lhs = p.parseTemplateCallExpr(lhs, &ref);
break;
}
return lhs;
default:
return lhs;
}
}
}
fn Expr* Parser.parseCallExpr(Parser* p, Expr* func) {
SrcLoc loc = p.tok.loc;
p.consumeToken(); // '('
ExprList args.init();
while (p.tok.kind != RParen) {
if (p.tok.kind == Identifier && p.peekToken(1) == Colon) {
SrcLoc nameLoc = p.tok.loc;
u32 name_idx = p.tok.name_idx;
p.consumeToken(); // name
p.consumeToken(); // ':'
Expr* inner = (p.tok.kind == LBrace) ? p.parseInitList() : p.parseExpr();
Expr* arg = p.builder.actOnNamedArgument(nameLoc, name_idx, inner);
args.add(arg);
} else
if (p.tok.kind == LBrace) {
args.add(p.parseInitList());
} else {
args.add(p.parseExpr());
}
if (p.tok.kind != Comma) break;
p.consumeToken();
}
SrcLoc endLoc = p.tok.loc + 1;
p.expectAndConsume(RParen);
Expr* res = p.builder.actOnCallExpr(loc, endLoc, func, args.getExprs(), args.size());
args.free();
return res;
}
fn Expr* Parser.parseTemplateCallExpr(Parser* p, Expr* func, const TypeRefHolder* ref) {
SrcLoc loc = p.tok.loc;
p.consumeToken(); // '('
ExprList args.init();
while (p.tok.kind != RParen) {
args.add(p.parseExpr());
if (p.tok.kind != Comma) break;
p.consumeToken();
}
SrcLoc endLoc = p.tok.loc + 1;
p.expectAndConsume(RParen);
Expr* res = p.builder.actOnTemplateCallExpr(loc, endLoc, func, args.getExprs(), args.size(), ref);
args.free();
return res;
}
fn Expr* Parser.parseImpureMemberExpr(Parser* p, Expr* base) {
// Create simple `MemberExpr` for all parts
for (;;) {
p.consumeToken(); // dot
p.expectIdentifier();
base = p.builder.actOnMemberExpr(base, 0, 0, p.tok.loc, p.tok.name_idx);
p.consumeToken();
if (p.tok.kind != Dot) break;
}
return base;
}
fn Expr* Parser.parsePureMemberExpr(Parser* p) {
SrcLoc loc = p.tok.loc;
u32 name_idx = p.tok.name_idx;
u32 name_len = p.tok.len;
p.consumeToken();
if (p.tok.kind != Dot) return p.builder.actOnIdentifier(loc, name_idx, name_len);
p.consumeToken(); // Dot
p.expectIdentifier();
Expr* lhs = p.builder.actOnMemberExpr(nil, name_idx, name_len, p.tok.loc, p.tok.name_idx);
p.consumeToken();
if (p.tok.kind != Dot) return lhs;
return p.parseImpureMemberExpr(lhs);
}
fn Expr* Parser.parseStringLiteral(Parser* p) {
SrcLoc loc = p.tok.loc;
u32 src_len = p.tok.len;
u32 idx = p.tok.text_idx;
u32 len = p.tok.text_len;
p.consumeToken();
// concatenate multi-strings
if (p.tok.kind == StringLiteral) {
char* tmp = p.multi_string;
const char *p1 = p.pool.idx2str(idx);
if (len > constants.MaxMultiString) {
p.error("multi-string literal too long");
}
string.memcpy(tmp, p1, len);
while (p.tok.kind == StringLiteral) {
const char *p2 = p.pool.idx2str(p.tok.text_idx);
usize len2 = p.tok.text_len;
if (len + len2 > constants.MaxMultiString) {
p.error("multi-string literal too long");
}
string.memcpy(tmp + len, p2, len2);
len += len2;
src_len = p.tok.loc + p.tok.len - loc;
p.consumeToken();
}
idx = p.pool.add(tmp, len, true);
}
return p.builder.actOnStringLiteral(loc, src_len, idx, len);
}
fn Expr* Parser.parseParenExpr(Parser* p) {
SrcLoc loc = p.tok.loc;
p.consumeToken();
if (p.parseAsCastType(0, RParen)) {
TypeRefHolder ref.init();
p.parseTypeSpecifier(&ref);
p.expectAndConsume(RParen);
Expr* expr;
if (p.tok.kind == LBrace) {
// compound literal
expr = p.parseInitList();
} else {
// C cast expression
if (ref.isArray()) p.error("cast to array type is invalid");
expr = p.parseCastExpr(false, false);
}
u32 src_len = p.prev_loc - loc;
return p.builder.actOnExplicitCast(loc, src_len, &ref, expr, true);
}
Expr* res = p.parseExpr();
u32 src_len = p.tok.loc + 1 - loc;
p.expectAndConsume(RParen);
return p.builder.actOnParenExpr(loc, src_len, res);
}
fn bool Parser.isTemplateFunctionCall(Parser* p) {
assert(p.tok.kind == Less);
// check if tokens after < could be type, followed by >(
// longest token line could be mod.type**
// type must start with either a qualifier or an identifier
// or a builtin not followed by a dot.
Kind kind = p.peekToken(1);
if (kind != Identifier) {
if (kind.isQualifier()) return true;
return kind.isTypeKeyword() && (p.peekToken(2) != Dot);
}
u32 stars = 0;
for (u32 ahead = 2; ahead < 8; ahead++) {
switch (p.peekToken(ahead)) {
case Identifier:
if (stars) return false;
break;
case Star:
stars++;
break;
case Dot:
break;
case Greater:
return p.peekToken(ahead + 1) == LParen;
case KW_const:
case KW_volatile:
return true;
default:
return false;
}
}
return false;
}
fn Expr* Parser.parseSizeof(Parser* p) {
SrcLoc loc = p.tok.loc;
p.consumeToken();
p.expectAndConsume(LParen);
Expr* res = nil;
if (p.parseAsType()) {
// argument is unambiguously a type
SrcLoc type_loc = p.tok.loc;
TypeRefHolder ref.init();
p.parseTypeSpecifier(&ref);
u32 src_len = p.prev_loc - type_loc;
res = p.builder.actOnTypeExpr(type_loc, src_len, &ref);
} else {
// argument is an expression or an ambiguous name, parse as expression
res = p.parseExpr();
}
u32 src_len = p.tok.loc + 1 - loc;
p.expectAndConsume(RParen);
return p.builder.actOnBuiltinExpr(loc, src_len, res, Sizeof);
}
fn Expr* Parser.parseElemsof(Parser* p) {
SrcLoc loc = p.tok.loc;
p.consumeToken();
p.expectAndConsume(LParen);
// TODO parse as TypeRefholder (can have module.prefix and array index
Expr* res = p.parseFullIdentifier();
res = p.parsePostfixExprSuffix(res, false);
u32 src_len = p.tok.loc + 1 - loc;
p.expectAndConsume(RParen);
return p.builder.actOnBuiltinExpr(loc, src_len, res, Elemsof);
}
fn Expr* Parser.parseInitValue(Parser* p, bool allow_designators) {
switch (p.tok.kind) {
case LBrace:
return p.parseInitList();
case Dot:
if (!allow_designators) p.error("designator not allowed here");
return p.parseFieldDesignator();
case LSquare:
if (!allow_designators) p.error("designator not allowed here");
return p.parseArrayDesignator();
default:
break;
}
return p.parseAssignmentExpression();
}
fn Expr* Parser.parseInitList(Parser* p) {
SrcLoc loc = p.tok.loc;
p.expectAndConsume(LBrace);
ExprList values.init();
while (p.tok.kind != RBrace) {
Expr* e = p.parseInitValue(true);
values.add(e);
if (p.tok.kind == Comma) {
p.consumeToken();
} else {
break;
}
}
// check for missing comma between array inits. eg: {} {}
if (p.tok.kind == LBrace) p.expect(Comma); // always gives error
SrcLoc endLoc = p.tok.loc + 1;
p.expectAndConsume(RBrace);
Expr* e = p.builder.actOnInitList(loc, endLoc, values.getExprs(), values.size());
values.free();
return e;
}
fn Expr* Parser.parseFieldDesignator(Parser* p) {
SrcLoc loc = p.tok.loc;
p.consumeToken(); // .
p.expectIdentifier();
u32 field = p.tok.name_idx;
p.consumeToken();
p.expectAndConsume(Equal);
Expr* value = p.parseInitValue(false);
return p.builder.actOnFieldDesignatedInit(loc, field, value);
}
fn Expr* Parser.parseArrayDesignator(Parser* p) {
SrcLoc loc = p.tok.loc;
p.consumeToken(); // '['
Expr* designator = p.parseAssignmentExpression();
p.expectAndConsume(RSquare);
p.expectAndConsume(Equal);
Expr* initValue = p.parseInitValue(false);
return p.builder.actOnArrayDesignatedInit(loc, designator, initValue);
}
fn Expr* Parser.parseExplicitCastExpr(Parser* p) {
SrcLoc loc = p.tok.loc;
p.consumeToken();
p.expectAndConsume(Less);
TypeRefHolder ref.init();
p.parseTypeSpecifier(&ref);
p.expectAndConsume(Greater);
if (ref.isArray()) p.error("array types are not allowed here");
p.expectAndConsume(LParen);
Expr* expr = p.parseExpr();
u32 src_len = p.tok.loc + 1 - loc;
p.expectAndConsume(RParen);
return p.builder.actOnExplicitCast(loc, src_len, &ref, expr, false);
}
// Syntax:
// 'enum_min' '(' type-name ')'
// 'enum_max' '(' type-name ')'
fn Expr* Parser.parseEnumMinMax(Parser* p, bool is_min) {
SrcLoc loc = p.tok.loc;
p.consumeToken();
p.expectAndConsume(LParen);
p.expectIdentifier();
// TODO parse as TypeRefHolder
Expr* expr = p.parseExpr();
u32 src_len = p.tok.loc + 1 - loc;
p.expectAndConsume(RParen);
return p.builder.actOnBuiltinExpr(loc, src_len, expr, is_min ? EnumMin : EnumMax);
}
fn Expr* Parser.parseOffsetOfExpr(Parser* p) {
SrcLoc loc = p.tok.loc;
p.consumeToken();
p.expectAndConsume(LParen);
// TODO use TypeRefHolder (modified version to only allow identifiers)
Expr* structExpr = p.parseFullIdentifier();
p.expectAndConsume(Comma);
Expr* member = p.parseFullIdentifier();
u32 src_len = p.tok.loc + 1 - loc;
p.expectAndConsume(RParen);
return p.builder.actOnOffsetOfExpr(loc, src_len, structExpr, member);
}
fn Expr* Parser.parseToContainerExpr(Parser* p) {
SrcLoc loc = p.tok.loc;
p.consumeToken();
p.expectAndConsume(LParen);
Expr* structExpr = p.parseFullIdentifier();
p.expectAndConsume(Comma);
Expr* member = p.parseFullIdentifier();
p.expectAndConsume(Comma);
Expr* pointer = p.parseExpr();
u32 src_len = p.tok.loc + 1 - loc;
p.expectAndConsume(RParen);
return p.builder.actOnToContainerExpr(loc, src_len, structExpr, member, pointer);
}
// Syntax:
// identifier
// identifier.identifier
// identifier.identifier.identifier etc
fn Expr* Parser.parseFullIdentifier(Parser* p) {
p.expectIdentifier();
return p.parsePureMemberExpr();
}
/*
parsing sizeof() is nasty, since the inner argument can be either an Expr or a Type!
The reason we test brackets [] inside a sizeof is that it is potentially ambiguous;
it can be an array (eg Foo[2]) or a subscript expression (a[2]). We assume Foo to be
a type, but it could be a global Constant, in which case an error will be generated later.
i8,u8,. - type
X* - type
Foo<..> - type
test.Foo<..> - type
Foo - identifier (upper case, can be Constant or Type)
f - identifier (lower case)
test.Foo - member (upper case, can be Constant or Type)
f.a - member (lower case)
test.f.a - member (lower case)
Foo[..] - can be Constant element or Type array, assume Type array
test.Foo[..] - can be Constant element or Type array, assume Type array
a[..] - subscript expression
test.a[..] - subscript expression
Foo.a - error (need instantiation, should accept as extension)
test.Foo.a - error (need instantiation, should accept as extension)
a*) - type (but will give error later)
test.a*) - type (but will give error later)
*/
fn bool Parser.parseAsType(Parser* p) {
// type must start with either a qualifier or an identifier
// or a builtin not followed by a dot.
Kind kind = p.tok.kind;
if (kind != Identifier) {
if (kind.isQualifier()) return true;
return kind.isTypeKeyword() && (p.peekToken(1) != Dot);
}
Token t2 = p.tok;
// parse potential member expression
u32 ahead = 1;
while (p.peekToken(ahead) == Dot) {
if (p.peekToken2(ahead + 1, &t2) != Identifier)
return false;
ahead += 2;
}
i32 stars = 0;
for (;; ahead++) {
switch (p.peekToken(ahead)) {
case RParen:
if (stars) return true;
// ambiguous: could be a global constant or a type name
return false; // resolve in analyser
case LSquare:
if (stars) return true; // sizeof(MyType*[...])
// if identifier is not uppercase, argument is not a type
if (!isupper(*p.pool.idx2str(t2.name_idx))) return false;
// ambiguous: could be a global constant element or an array type
return true; // assume array type
case Star:
if (stars) return true; // sizeof(a**...)
stars++;
break;
case Less:
// if identifier is not uppercase, argument is not a type
if (!isupper(*p.pool.idx2str(t2.name_idx))) return false;
// ambiguous: could be a parametric type or a comparison with a global constant
return true; // assume parametric type
case KW_const:
case KW_volatile:
return true;
default:
return false;
}
}
}
/*
Type parser for C style casts and compound literals.
Accepts all type specifications, including parametric types.
Return the number of tokens until and including the closing token.
Return 0 if the expression is not a type specification.
Ambiguities are resolved by checking the token after ')'.
Array syntax is rejected if `brackets` is nil, otherwise `*brackets` is
set if an array type is parsed.
*/
fn u32 Parser.parseAsCastType(Parser* p, u32 ahead, Kind close_tok) {
Token t2 = p.tok;
bool ambiguous = true;
for (;;) {
if (ahead) p.peekToken2(ahead, &t2);
ahead++;
Kind kind = t2.kind;
if (kind.isTypeKeyword() && (p.peekToken(ahead) != Dot)) {
// builtin type, non ambiguous
ambiguous = false;
break;
}
if (kind.isQualifier()) {
// const and volatile qualifiers must introduce a type
ambiguous = false;
continue;
}
// must have an identifier or a member expression
// but still potentially ambiguous.
if (kind != Identifier)
return 0;
while (p.peekToken(ahead) == Dot) {
if (p.peekToken2(ahead + 1, &t2) != Identifier)
return 0;
ahead += 2;
}
break;
}
i32 stars = 0;
while (1) {
switch (p.peekToken(ahead)) {
case Star:
if (stars < 0) return 0;
if (stars > 0) ambiguous = false;
stars++;
ahead++;
break;
case RParen:
if (close_tok != RParen)
return 0;
ahead++;
if (!ambiguous) return ahead;
// disambiguate depending on the next token
switch (p.peekToken(ahead)) {
case Identifier:
case IntegerLiteral:
case FloatLiteral:
case CharLiteral:
case StringLiteral:
case Tilde:
case Exclaim:
case KW_cast:
case KW_elemsof:
case KW_enum_min:
case KW_enum_max:
case KW_false:
case KW_true:
case KW_nil:
case KW_offsetof:
case KW_sizeof:
case KW_to_container:
case LBrace:
return ahead;
case PlusPlus: // ambiguous: (x)++
case MinusMinus: // ambiguous: (x)--
case LParen: // ambiguous: (func)(args)
case Amp: // ambiguous: (func)&b
case Plus: // ambiguous: (func)+b
case Minus: // ambiguous: (func)-b
case Star: // ambiguous: (func)*b
// for ambiguous combinations, rely on identifier case
// (A)(...) is a cast, (a)(...) is a function call
if (!isupper(p.pool.idx2str(t2.name_idx)[0]))
return 0;
return ahead;
default:
break;
}
return 0;
case LSquare:
// skip expression
ahead = p.skipArray(ahead + 1, RSquare);
if (!ahead)
return 0;
stars = -1; // no longer accept stars
break;
case Less:
// parametric type X<type>
ahead = p.parseAsCastType(ahead, Greater);
if (!ahead)
return 0;
stars = 0;
break;
case Greater:
if (close_tok != Greater)
return 0;
ahead++;
return ahead;
default:
return 0;
}
}
}