-
Notifications
You must be signed in to change notification settings - Fork 7
/
parser.oc
2841 lines (2469 loc) · 94.1 KB
/
parser.oc
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
//* The parser
import std::buffer::{ Buffer }
import std::map::{ Map }
import std::span::{ Span, Location }
import std::vector::{ Vector }
import std::mem
import std::fs
import @ast::nodes::{ * }
import @ast::program::{ Namespace, Program }
import @ast::operators::{ Operator }
import @ast::scopes::{ Symbol, SymbolType, Template, EnumField }
import @attributes::{ Attribute, AttributeType }
import @errors::Error
import @lexer::Lexer
import @tokens::{ Token, TokenType }
import @types::{ Type, BaseType, FunctionType, ArrayType, MapShorthandType }
import @utils::directory_exists
@compiler c_include "libgen.h"
[extern] def dirname(path: str): str
[extern] def basename(path: str): str
struct Parser {
tokens: &Vector<&Token>
curr: u32
curr_func: &Function
program: &Program
ns: &Namespace
attrs: &Vector<&Attribute>
attrs_span: Span
attrs_start_tok: &Token
//! The span of the last expression that caused an error
prev_expr_error_span: Span
}
def Parser::make(program: &Program, ns: &Namespace): Parser {
return Parser(
tokens: null,
curr: 0,
curr_func: null,
program: program,
ns: ns,
attrs: Vector<&Attribute>::new(),
attrs_span: Span::default(),
attrs_start_tok: null,
prev_expr_error_span: Span::default(),
)
}
def Parser::free(&this) {
// FIXME: Actually free the attributes, not just the vector
// Also do this in `.clear_attributes()`
.attrs.free()
}
def Parser::peek(&this, off: i32 = 1): &Token {
let idx = .curr as i32 + off
assert 0i32 <= idx < (.tokens.size as i32)
return .tokens.at(idx as u32)
}
def Parser::error_msg(&this, msg: str): &Error {
let err = Error::new(.token().span, msg)
.program.errors.push(err)
return err
}
def Parser::error(&this, err: &Error): &Error {
.program.errors.push(err)
return err
}
def Parser::unhandled_type(&this, func: str) {
.error_msg(`Unexpected token in {func}: {.token().type.str()}`)
}
def Parser::token(&this): &Token {
if .curr >= .tokens.size {
.curr = .tokens.size - 1
// If we run out of tokens without an error, report one.
.error_msg("Unexpected end of file")
.program.get_error_context().jump_back(1)
}
return .tokens.unchecked_at(.curr as u32)
}
def Parser::token_is(&this, type: TokenType): bool {
if type == TokenType::Newline {
return .token().seen_newline
}
return .token().type == type
}
def Parser::token_is_eof_or(&this, type: TokenType): bool {
if .token_is(TokenType::EOF) return true
return .token_is(type)
}
def Parser::token_is_identifier(&this, name: str): bool => .token().is_identifier(name)
def Parser::peek_token_is(&this, off: u32, type: TokenType): bool {
if .curr + off >= .tokens.size return false
let tok = .tokens.at(.curr + off)
return tok.type == type
}
def Parser::consume_if(&this, type: TokenType): bool {
if .token_is(type) {
// Newline tokens are special because they don't consume a token.
if type != TokenType::Newline {
if .curr < .tokens.size - 1 then .curr += 1
}
return true
}
return false
}
def Parser::consume_newline_or(&this, type: TokenType) {
if .token_is(type) {
if .curr < .tokens.size - 1 then .curr += 1
} else if not .token().seen_newline {
.error_msg(`Expected {type.str()} or newline`)
.program.get_error_context().jump_back(1)
}
}
def Parser::consume_tokens_until_newline(&this) {
while not .token().seen_newline {
if .token_is(TokenType::EOF) break
.curr += 1
}
}
def Parser::consume(&this, type: TokenType): &Token {
let tok = .token()
if not .consume_if(type) {
.error_msg(`Expected TokenType::{type.str()}`)
.program.get_error_context().jump_back(1)
}
return tok
}
def Parser::is_end_of_statement(&this): bool {
if .token_is(TokenType::CloseCurly) return true
if .token_is(TokenType::Semicolon) return true
if .token().seen_newline return true
return false
}
def Parser::consume_end_of_statement(&this) {
if .token_is(TokenType::CloseCurly) return
.consume_newline_or(TokenType::Semicolon)
}
def Parser::clear_attributes(&this) {
for attr in .attrs.iter() {
mem::free(attr)
}
.attrs.clear()
.attrs_start_tok = null
}
def Parser::is_compound_operator(&this, op: Operator): bool => match op {
LeftShift => .token_is(LessThan) and .peek_token_is(1, LessThan)
RightShift => .token_is(GreaterThan) and .peek_token_is(1, GreaterThan)
LeftShiftEquals => .token_is(LessThan) and .peek_token_is(1, LessThanEquals)
RightShiftEquals => .token_is(GreaterThan) and .peek_token_is(1, GreaterThanEquals)
else => false
}
def Parser::consume_compound_operator(&this, op: Operator): Span {
let span = .token().span
match op {
LeftShift => { .consume(LessThan); .consume(LessThan); }
RightShift => { .consume(GreaterThan); .consume(GreaterThan); }
LeftShiftEquals => { .consume(LessThan); .consume(LessThanEquals); }
RightShiftEquals => { .consume(GreaterThan); .consume(GreaterThanEquals); }
else => {
.error(Error::new(span, f"Unknown operator {op} in Parser::consume_compound_operator"))
}
}
let prev_token = .tokens[.curr - 1]
return span.join(prev_token.span)
}
// NOTE: The parser _always_ returns an `Unresolved` base type, with the name of the type stored in
// the `name` field. The typechecker is responsible for resolving this, even for the built-in types.
def Parser::parse_type(&this): &Type => match .token().type {
Identifier => {
let ident = .parse_scoped_identifier()
let name = if ident.type == ASTType::Identifier then ident.u.ident.name else "<unresolved>"
let typ = Type::new_unresolved(name, ident.span)
typ.u.unresolved = ident
yield typ
}
Ampersand => {
let amp = .consume(Ampersand)
let base = .parse_type()
let typ = Type::new_resolved(BaseType::Pointer, amp.span.join(base.span))
typ.u.ptr = base
yield typ
}
AtSign | Fn => {
let start_span = .token().span
let base_type = match .token().type {
AtSign => {
// FIXME: Currently we don't have a way to "branch" to anything else
// if we decide to use @ as shorthand for more types. This needs
// to be refactored, possibly by moving logic in top-level match
// branches into separate functions.
.consume(TokenType::AtSign)
.consume(TokenType::Fn)
yield BaseType::Closure
}
Fn => {
.consume(TokenType::Fn)
yield BaseType::FunctionPtr
}
else => std::panic("unreachable")
}
.consume(TokenType::OpenParen)
let params = Vector<&Variable>::new()
let is_variadic = false
while not .token_is_eof_or(TokenType::CloseParen) {
if .token_is(TokenType::Ellipsis) {
.consume(TokenType::Ellipsis)
is_variadic = true
break
}
let param_type = .parse_type()
// No names for parameters needed for function types
let var = Variable::new(param_type)
var.sym = Symbol::from_local_variable("", var, param_type.span)
params.push(var)
if not .token_is(TokenType::CloseParen) {
.consume(TokenType::Comma)
}
}
let close = .consume(TokenType::CloseParen)
let return_type: &Type
if .consume_if(TokenType::Colon) {
return_type = .parse_type()
} else {
return_type = Type::new_unresolved_base(BaseType::Void, start_span)
}
let type = Type::new_resolved(base_type, start_span.join(close.span))
type.u.func = FunctionType(null, params, return_type, is_variadic)
yield type
}
OpenSquare => {
let start_span = .token().span
.consume(TokenType::OpenSquare)
let elem_type = .parse_type()
.consume(TokenType::Semicolon)
let size_expr = .parse_expression(end_type: TokenType::CloseSquare)
let close = .consume(TokenType::CloseSquare)
let typ = Type::new_resolved(BaseType::Array, start_span.join(close.span))
typ.u.arr = ArrayType(elem_type, size_expr, size_known: false, size: 0)
yield typ
}
Dollar => {
let dollar = .consume(Dollar)
yield match .token().type {
OpenSquare => {
.consume(OpenSquare)
let elem_type = .parse_type()
let close = .consume(CloseSquare)
let typ = Type::new_resolved(VectorShorthand, dollar.span.join(close.span))
typ.u.ptr = elem_type
.import_from_stdlib("vector", typ.span)
yield typ
}
OpenCurly => {
.consume(OpenCurly)
let key_type = .parse_type()
.consume(Colon)
let value_type = .parse_type()
let close = .consume(CloseCurly)
let typ = Type::new_resolved(MapShorthand, dollar.span.join(close.span))
typ.u.map_types = MapShorthandType(key: key_type, value: value_type)
.import_from_stdlib("compact_map", typ.span)
yield typ
}
else => {
.error(Error::new(.token().span, "Unexpected token after `$`"))
yield null
}
}
}
else => {
.unhandled_type("parse_type")
yield Type::new_unresolved_base(BaseType::Error, .token().span)
}
}
def Parser::parse_identifier(&this): &AST {
let tok = .consume(TokenType::Identifier)
let node = AST::new(Identifier, tok.span)
node.u.ident.name = tok.text
return node
}
def Parser::parse_scoped_identifier(&this, consume_template: bool = true): &AST {
let node = .parse_identifier()
while true {
match .token().type {
TokenType::ColonColon => {
let colons = .consume(TokenType::ColonColon)
let lookup = AST::new(NSLookup, node.span)
lookup.u.lookup.lhs = node
node = lookup
if .token_is(Newline) or not .token_is(Identifier) {
let span = Span(colons.span.end, colons.span.end)
.error(Error::new(span, "Expected identifier after `::`"))
node.span.end = .token().span.start
} else {
let name = .consume(TokenType::Identifier)
node.span = node.span.join(name.span)
node.u.lookup.rhs_name = name.text
node.u.lookup.rhs_span = name.span
}
}
TokenType::LessThan => {
if not consume_template return node
// FIXME: Is there a more robust way to do this?
// We want to be able to differentiate between a `<` that starts a specialization and
// a `<` that is part of a less-than comparison before typechecking, I don't know of
// the best way to do this, but here's a couple heuristics:
// 1. Make sure that we don't have a space between the identifier and the `<`
let prev_token = .tokens.at(.curr as u32 - 1)
if not .token().span.starts_right_after(prev_token.span) {
return node
}
// 2. Make sure the token after that isn't a `.`
let next_next_token = .tokens.at(.curr as u32 + 2)
if next_next_token.type == TokenType::Dot {
return node
}
// Okay... so we're kinda-sorta sure that this is a specialization, let's parse it.
let start = .consume(TokenType::LessThan)
let args = Vector<&Type>::new()
while not .token_is_eof_or(TokenType::GreaterThan) {
args.push(.parse_type())
if not .token_is(TokenType::GreaterThan) {
if not .consume_if(TokenType::Comma) {
.error(Error::new_note(
.token().span, "Parsing template specialization: expected `,` or `>`",
"If you're comparing values, put a space before the `<` earlier"
))
return AST::new(Error, node.span)
}
}
}
let end = .consume(TokenType::GreaterThan)
let spec = AST::new(Specialization, node.span.join(end.span))
spec.u.spec = Specialization(
base: node,
parsed_template_args: args,
template_args: args,
)
node = spec
}
else => return node
}
}
return null // unreachable
}
def Parser::parse_format_string(&this): &AST {
let fstr = .consume(TokenType::FormatStringLiteral)
let fstr_len = fstr.text.len()
let expr_parts = Vector<str>::new()
let expr_start = Vector<u32>::new()
let format_parts = Vector<str>::new()
let specifiers = Vector<str>::new()
let specifier_loc = 0
let specifier_found = false
let count = 0
let cur_start = 0
for let i = 0; i < fstr_len; i += 1 {
match fstr.text[i] {
'\\' => i += 1
'{' => {
if count == 0 {
let part = fstr.text.substring(cur_start, i - cur_start)
format_parts.push(part)
cur_start = i + 1
}
count += 1
}
'}' => {
count -= 1
if count == 0 {
if specifier_loc > 0 {
let len = specifier_loc - cur_start
let part = fstr.text.substring(cur_start, len)
expr_parts.push(part)
expr_start.push(cur_start)
specifier_loc += 1
while specifier_loc < i and fstr.text[specifier_loc] == ' ' {
specifier_loc += 1
}
if specifier_loc == i {
let loc = fstr.span.start;
loc.col += specifier_loc + 1
let span = Span(loc, loc)
.error(Error::new(span, "Expected format specifier"))
return null
}
let spec = fstr.text.substring(specifier_loc, i - specifier_loc)
specifiers.push(spec)
} else {
let part = fstr.text.substring(cur_start, i - cur_start)
expr_parts.push(part)
expr_start.push(cur_start)
specifiers.push(null)
}
cur_start = i + 1
specifier_loc = 0
specifier_found = false
} else if count < 0 {
.error(Error::new(fstr.span, "Unmatched '}' in format string"))
return null
}
}
':' => {
// TODO: Handle errors properly (actually, maybe just add an assert)
if count == 1 and fstr.text[i - 1] != ':' and fstr.text[i + 1] != ':' {
specifier_loc = i
specifier_found = true
}
}
else => {}
}
}
if count != 0 {
.error(Error::new(fstr.span, "Unmatched '{' in format string"))
return null
}
let part = fstr.text.substring(cur_start, fstr_len - cur_start)
format_parts.push(part)
let node = AST::new(FormatStringLiteral, fstr.span)
node.u.fmt_str.parts = format_parts
let fstr_start = fstr.span.start
let expr_nodes = Vector<&AST>::new()
for let i = 0; i < expr_parts.size; i += 1 {
let part = expr_parts.at(i)
let start = expr_start.at(i)
let lexer = Lexer::make(part, fstr_start.filename, .program.errors)
lexer.loc = fstr_start
lexer.loc.col += start + 1
let tokens = lexer.lex()
let sub_parser = Parser::make(.program, .ns)
sub_parser.tokens = tokens
sub_parser.curr = 0
sub_parser.curr_func = .curr_func
let expr = sub_parser.parse_expression(end_type: TokenType::CloseCurly)
if not sub_parser.token_is(TokenType::EOF) {
.error(Error::new(expr.span, "Invalid expression in format string"))
}
expr_nodes.push(expr)
}
node.u.fmt_str.exprs = expr_nodes
node.u.fmt_str.specs = specifiers
expr_parts.free()
expr_start.free()
return node
}
def Parser::parse_match_case_conds(&this, end_type: TokenType): &Vector<&MatchCond> {
let conds = Vector<&MatchCond>::new()
while not .token_is_eof_or(end_type) {
let expr = .parse_atom(TokenType::Line)
let args: &Vector<&MatchCondArg> = null
if .consume_if(OpenParen) {
args = Vector<&MatchCondArg>::new()
while not .token_is_eof_or(CloseParen) {
let name = .consume(Identifier)
let var = Variable::new(null)
var.sym = Symbol::from_local_variable(name.text, var, name.span)
args.push(@new MatchCondArg(var))
if not .consume_if(Comma) {
break
}
}
.consume(CloseParen)
}
conds.push(MatchCond::new(expr, args))
if not .consume_if(Line) then break
}
return conds
}
def Parser::parse_match(&this): &AST {
let op = .consume(TokenType::Match)
let expr = .parse_expression(end_type: TokenType::OpenCurly)
let node = AST::new(Match, op.span.join(expr.span))
node.u.match_stmt.expr = expr
node.u.match_stmt.match_span = op.span
let cases = Vector<MatchCase>::new()
node.u.match_stmt.cases = cases
if not .token_is(TokenType::OpenCurly) {
.error(Error::new(.token().span, "Expected '{' after match expression"))
return node
}
.consume(TokenType::OpenCurly)
while not .token_is_eof_or(TokenType::CloseCurly) {
if .token_is(TokenType::Else) {
node.u.match_stmt.defolt_span = .token().span
.consume(TokenType::Else)
if not .consume_if(TokenType::FatArrow) {
.error(Error::new(.token().span, "Expected => after match case"))
}
node.u.match_stmt.defolt = .parse_statement()
} else {
let conds = .parse_match_case_conds(TokenType::FatArrow)
if not .consume_if(TokenType::FatArrow) {
.error(Error::new(.token().span, "Expected => after match case"))
}
let body = .parse_statement()
if not .token_is(TokenType::CloseCurly) {
.consume_newline_or(TokenType::Comma)
}
let _case = MatchCase(conds, body)
cases.push(_case)
}
.consume_if(TokenType::Comma)
}
node.span = op.span.join(.token().span)
.consume(TokenType::CloseCurly)
node.u.match_stmt.cases = cases
return node
}
//! Resets the parser state to the start of a top-level block
def Parser::sync_toplevel(&this) {
while not (
.token_is(TokenType::CloseCurly) or // End of block
.token_is(TokenType::OpenSquare) or // Start of attribute
.token_is(TokenType::Import) or // Start of import
.token_is(TokenType::Def) or // Start of function
.token_is(TokenType::Let) or // Start of variable
.token_is(TokenType::Const) or // Start of constant
.token_is(TokenType::Struct) or // Start of struct
.token_is(TokenType::Enum) or // Start of enum
.token_is(TokenType::AtSign) or // Start of compiler directive
.token_is(TokenType::EOF) // EOF
) {
.curr += 1
}
}
def Parser::parse_literal_suffix_type(&this, suffix: &Token): &Type {
if not suffix? return null
let ident = AST::new(Identifier, suffix.span)
ident.u.ident.name = suffix.text
let typ = Type::new_unresolved(suffix.text, suffix.span)
typ.u.unresolved = ident
return typ
}
def Parser::parse_call(&this, callee: &AST): &AST {
let start = .consume(TokenType::OpenParen)
let args = Vector<&Argument>::new()
while not .token_is_eof_or(TokenType::CloseParen) {
let label_tok: &Token = null
if .token_is(Identifier) and .peek_token_is(1, Colon) {
label_tok = .consume(TokenType::Identifier)
.consume(TokenType::Colon)
}
let expr = .parse_expression(end_type: TokenType::Comma)
args.push(Argument::new(expr, label_tok))
if not .token_is(TokenType::CloseParen) {
.consume(TokenType::Comma)
}
}
let end = .consume(TokenType::CloseParen)
let call_type = ASTType::Call
let call = AST::new(call_type, callee.span.join(end.span))
call.u.call.callee = callee
call.u.call.args = args
call.u.call.open_paren_span = start.span
call.u.call.close_paren_span = end.span
return call
}
//* We also allow array literals when initializing a variable, so treat them separately.
def Parser::parse_var_initializer(&this): &AST {
if .token_is(TokenType::OpenSquare) {
let start = .consume(TokenType::OpenSquare)
let elements = Vector<&AST>::new()
while not .token_is_eof_or(TokenType::CloseSquare) {
elements.push(.parse_var_initializer())
if not .token_is(TokenType::CloseSquare) {
.consume(TokenType::Comma)
}
}
let close = .consume(TokenType::CloseSquare)
let node = AST::new(ArrayLiteral, start.span.join(close.span))
node.u.array_literal.elements = elements
return node
}
return .parse_expression(TokenType::Newline)
}
def Parser::parse_var_declaration(&this): &AST {
let start = .consume(TokenType::Let)
let name = .consume(TokenType::Identifier)
let end_span = name.span
let type: &Type = null
if .consume_if(TokenType::Colon) {
type = .parse_type()
end_span = type.span
}
let init: &AST = null
if .consume_if(TokenType::Equals) {
init = .parse_var_initializer()
end_span = init.span
}
.consume_end_of_statement()
let node = AST::new(VarDeclaration, start.span.join(end_span))
let var = Variable::new(type)
var.sym = Symbol::from_local_variable(name.text, var, name.span)
var.default_value = init
node.u.var_decl = var
return node
}
def Parser::parse_global_value(&this, is_const: bool): &AST {
let start_token = if is_const {
yield .consume(TokenType::Const)
} else {
yield .consume(TokenType::Let)
}
let node = AST::new(VarDeclaration, .token().span)
let name = if .token_is(TokenType::Identifier) {
yield .consume(TokenType::Identifier)
} else {
.error(Error::new(.token().span, "Expected identifier"))
return node
}
let type: &Type = null
if .consume_if(TokenType::Colon) { type = .parse_type(); }
let var = Variable::new(type)
var.sym = Symbol::new_with_parent(Variable, .ns, .ns.sym, name.text, name.span)
var.sym.u.var = var
if is_const {
var.sym.type = SymbolType::Constant
}
.parse_extern_into_symbol(var.sym)
for attr in .attrs.iter() {
match attr.type {
Extern => .get_extern_from_attr(var.sym, attr)
Atomic => var.is_atomic = true
else => .error(Error::new(attr.span, "Unexpected attribute for variable"))
}
}
node.u.var_decl = var
if .consume_if(TokenType::Equals) {
if is_const {
var.default_value = .parse_expression(end_type: TokenType::Newline)
} else {
var.default_value = .parse_var_initializer()
}
}
.consume_newline_or(TokenType::Semicolon)
return node
}
def Parser::parse_atom(&this, end_type: TokenType): &AST {
let node: &AST = null
match .token().type {
TokenType::If => node = .parse_if()
TokenType::Match => node = .parse_match()
TokenType::OpenCurly => node = .parse_block()
TokenType::FormatStringLiteral => node = .parse_format_string()
TokenType::Null => {
let tok = .consume(TokenType::Null)
node = AST::new(Null, tok.span)
}
TokenType::IntLiteral => {
node = AST::new(IntLiteral, .token().span)
let tok = .consume(TokenType::IntLiteral)
node.u.num_literal = NumLiteral(
text: tok.text,
suffix: .parse_literal_suffix_type(tok.suffix)
)
}
TokenType::FloatLiteral => {
node = AST::new(FloatLiteral, .token().span)
let tok = .consume(TokenType::FloatLiteral)
node.u.num_literal = NumLiteral(
text: tok.text,
suffix: .parse_literal_suffix_type(tok.suffix)
)
}
TokenType::StringLiteral => {
node = AST::new(StringLiteral, .token().span)
let tok = .consume(TokenType::StringLiteral)
node.u.string_literal = tok.text
}
TokenType::CharLiteral => {
node = AST::new(CharLiteral, .token().span)
let tok = .consume(TokenType::CharLiteral)
node.u.char_literal = tok.text
}
TokenType::Identifier => node = .parse_scoped_identifier()
TokenType::True | TokenType::False => {
let tok = .consume(.token().type)
node = AST::new(BoolLiteral, tok.span)
node.u.bool_literal = tok.type == TokenType::True
}
TokenType::OpenParen => {
let start = .consume(TokenType::OpenParen)
node = .parse_expression(end_type: TokenType::CloseParen)
let end = .consume(TokenType::CloseParen)
node.span = start.span.join(end.span)
}
TokenType::Dot => {
let tok = .consume(TokenType::Dot)
if not .curr_func? or not .curr_func.kind == Method or .curr_func.is_static {
.error(Error::new(tok.span, "Cannot use dot shorthand outside of a method"))
return AST::new(Error, tok.span)
}
let lhs = AST::new(Identifier, tok.span)
lhs.u.ident.name = "this"
node = AST::new(Member, tok.span)
node.u.member.lhs = lhs
node.u.member.dot_shorthand = true
if not .token_is(TokenType::Identifier) {
.error(Error::new(.token().span, "Expected identifier after `.`"))
node.span.end = .token().span.start
} else {
let ident = .consume(TokenType::Identifier)
node.span = tok.span.join(ident.span)
node.u.member.rhs_name = ident.text
node.u.member.rhs_span = ident.span
}
}
TokenType::EOF => {
.error(Error::new(.token().span, "Unexpected end of file"))
return AST::new(Error, .token().span)
}
TokenType::Line => {
let start_loc = .token().span.start
let closure_func = .parse_closure()
let node = AST::new(CreateClosure, closure_func.span)
node.u.closure = closure_func
let closure_name = `_Closure_{.program.closures.size}`
.program.closures.push(closure_func)
let parent_sym = if {
.curr_func? => .curr_func.sym
else => .ns.sym
}
let sym = Symbol::new_with_parent(Closure, .ns, parent_sym, closure_name, Span(start_loc, start_loc))
sym.u.func = closure_func
closure_func.sym = sym
return node
}
TokenType::Dollar => {
let dollar = .consume(Dollar)
match .token().type {
OpenSquare => {
let start = .consume(TokenType::OpenSquare)
let elements = Vector<&AST>::new()
while not .token_is_eof_or(TokenType::CloseSquare) {
elements.push(.parse_var_initializer())
if not .token_is(TokenType::CloseSquare) {
.consume(TokenType::Comma)
}
}
let close = .consume(TokenType::CloseSquare)
let node = AST::new(VectorLiteral, dollar.span.join(close.span))
node.u.vec_literal.elements = elements
node.u.vec_literal.start_span = dollar.span.join(start.span)
.import_from_stdlib("vector", node.span)
return node
}
OpenCurly => {
let start = .consume(TokenType::OpenCurly)
let elements: $[MapLiteralPair] = $[]
while not .token_is_eof_or(TokenType::CloseCurly) {
let key = .parse_expression(TokenType::Colon)
.consume(TokenType::Colon)
let value = .parse_expression(TokenType::Comma)
if not .token_is(TokenType::CloseCurly) {
.consume(TokenType::Comma)
}
elements += MapLiteralPair(key, value)
}
let close = .consume(TokenType::CloseCurly)
let node = AST::new(MapLiteral, dollar.span.join(close.span))
node.u.map_literal.elements = elements
node.u.map_literal.start_span = dollar.span.join(start.span)
.import_from_stdlib("compact_map", node.span)
return node
}
else => {
.error(Error::new(.token().span, f"Unexpected token: {.token().type}"))
}
}
}
else => {
let prev_span = .tokens[.curr - 1].span
let cur_span = .token().span
let err_span = Span(prev_span.end, cur_span.start)
if not .token_is(end_type) {
.curr += 1
err_span = cur_span
.unhandled_type("parse_expression")
// We want to try to be error-tolerant, and not consume the token
// If we can avoid it (this may be an incomplete expression). However,
// if we see the same error multiple times, then we bail.
} else if .prev_expr_error_span == err_span {
.curr += 1
} else {
.prev_expr_error_span = err_span
.unhandled_type("parse_expression")
}
node = AST::new(Error, err_span)
}
}
return node
}
def Parser::parse_postfix(&this, end_type: TokenType): &AST {
let node = .parse_atom(end_type)
let running = true
while running {
if .token_is(end_type) break
match .token().type {
TokenType::OpenParen => node = .parse_call(node)
TokenType::Dot | TokenType::QuestionDot => {
if .token_is(end_type) break
let op = .consume(.token().type)
let member = match op.type {
QuestionDot => AST::new(TryMember, node.span)
Dot => AST::new(Member, node.span)
else => std::panic("Unreachable")
}
member.u.member.lhs = node
node = member
if .token_is(end_type) or not .token_is(TokenType::Identifier) {
.error(Error::new(.token().span, "Expected identifier after `.`"))
node.span.end = .token().span.start
} else {
let ident = .consume(TokenType::Identifier)
node.span = node.span.join(ident.span)
node.u.member.rhs_name = ident.text
node.u.member.rhs_span = ident.span
}
}
TokenType::Question => {
let tok = .consume(TokenType::Question)
node = AST::new_unop(IsNotNull, node.span.join(tok.span), node)
}
TokenType::OpenSquare => {
let open = .consume(TokenType::OpenSquare)
let index = .parse_expression(end_type: TokenType::CloseSquare)
let close = .consume(TokenType::CloseSquare)
// Contructing the binop here manually to properly handle the
// spans of `]` being _after_ the index expression.
let op = AST::new(BinaryOp, node.span.join(close.span))
op.u.binary.op = Index
op.u.binary.lhs = node
op.u.binary.rhs = index
op.u.binary.op_span = open.span
node = op
}
TokenType::MinusMinus | TokenType::PlusPlus => {
let span = node.span.join(.token().span)
let op = if .token_is(TokenType::MinusMinus) {
.consume(TokenType::MinusMinus)
yield Operator::PostDecrement
} else {
.consume(TokenType::PlusPlus)
yield Operator::PostIncrement
}
node = AST::new_unop(op, span, node)
}
else => running = false
}
}
return node
}
def Parser::parse_prefix(&this, end_type: TokenType): &AST {
match .token().type {
TokenType::Ampersand => {
let amp = .consume(TokenType::Ampersand)
let expr = .parse_prefix(end_type)
let node = AST::new_unop(Operator::Address, amp.span.join(expr.span), expr)
return node
}
TokenType::MinusMinus | TokenType::PlusPlus => {
let start_span = .token().span
let op = if .token_is(TokenType::MinusMinus) {
.consume(TokenType::MinusMinus)
yield Operator::PreDecrement
} else {
.consume(TokenType::PlusPlus)
yield Operator::PreIncrement
}
let expr = .parse_prefix(end_type)
return AST::new_unop(op, start_span.join(expr.span), expr)
}
TokenType::SizeOf => {
let start = .consume(TokenType::SizeOf)
.consume(TokenType::OpenParen)
let type = .parse_type()
let close = .consume(TokenType::CloseParen)
let node = AST::new(SizeOf, start.span.join(close.span))
node.u.size_of_type = type
return node
}
// Special compiler operations
TokenType::AtSign => {
let atsign = .consume(TokenType::AtSign)
if not .token_is(TokenType::Identifier) {
.error(Error::new(.token().span, "Expected compiler operation after @"))
return AST::new(Error, atsign.span)
}