This repository has been archived by the owner on Apr 5, 2024. It is now read-only.
forked from ocen-lang/ocen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.oc
1768 lines (1524 loc) · 55.8 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 @ast::nodes::*
import @ast::program::{ Namespace, Program }
import @lexer::Lexer
import @types::{ Type, BaseType, FunctionType, ArrayType }
import std::span::Span
import std::map::Map
import std::vector::Vector
import @tokens::{ Token, TokenType }
import @ast::scopes::{ Symbol, SymbolType, Template }
import @errors::Error
import std::libc::{ calloc, free }
import @utils::directory_exists
@compiler c_include "libgen.h"
def dirname(path: str): str extern
def basename(path: str): str extern
struct Parser {
tokens: &Vector<&Token>
curr: u32
curr_func: &Function
program: &Program
ns: &Namespace
}
def Parser::make(program: &Program, ns: &Namespace): Parser {
return Parser(
tokens: null,
curr: 0,
curr_func: null,
program: program,
ns: ns
)
}
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 => .tokens.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::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 {
.curr += 1
}
return true
}
return false
}
def Parser::consume_newline_or(&this, type: TokenType) {
if .token_is(type) {
.curr += 1
} else if not .token().seen_newline {
.error_msg(`Expected {type.str()} or newline`)
.program.exit_with_errors()
}
}
def Parser::consume(&this, type: TokenType): &Token {
let tok = .token()
if not .consume_if(type) {
.error_msg(`Expected TokenType::{type.str()}`)
.program.exit_with_errors()
}
return tok
}
def Parser::consume_end_of_statement(&this) {
if .token_is(TokenType::CloseCurly) return
.consume_newline_or(TokenType::Semicolon)
}
// 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
}
Fn => {
let start_span = .token().span
.consume(TokenType::Fn)
.consume(TokenType::OpenParen)
let params = Vector<&Variable>::new()
while not .token_is(TokenType::CloseParen) {
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(BaseType::Function, start_span.join(close.span))
type.u.func = FunctionType(null, params, return_type)
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)
yield typ
}
else => {
.unhandled_type("parse_type")
yield Type::new_unresolved_base(BaseType::Error, .token().span)
}
}
def Parser::parse_scoped_identifier(&this, consume_template: bool = true): &AST {
let tok = .consume(TokenType::Identifier)
let node = AST::new(ASTType::Identifier, tok.span)
node.u.ident.name = tok.text
while true {
match .token().type {
TokenType::ColonColon => {
.consume(TokenType::ColonColon)
let name = .consume(TokenType::Identifier)
let lookup = AST::new(ASTType::NSLookup, node.span.join(name.span))
lookup.u.lookup = NSLookup(node, name.text, name.span)
node = lookup
}
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(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(ASTType::Error, node.span)
}
}
}
let end = .consume(TokenType::GreaterThan)
let spec = AST::new(ASTType::Specialization, node.span.join(end.span))
spec.u.spec = Specialization(base: node, 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 {
if fstr.text[i] == '\\' {
i += 1
} else if fstr.text[i] == '{' {
if count == 0 {
let part = fstr.text.substring(cur_start, i - cur_start)
format_parts.push(part)
cur_start = i + 1
}
count += 1
} else if fstr.text[i] == '}' {
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
}
} else if fstr.text[i] == ':' {
// 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
}
}
}
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(ASTType::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)
lexer.loc = fstr_start
lexer.loc.col += start + 1
let tokens = lexer.lex()
for error : lexer.errors.iter() {
.error(error)
}
lexer.errors.free()
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(&this): &AST {
let op = .consume(TokenType::Match)
let expr = .parse_expression(end_type: TokenType::OpenCurly)
let node = AST::new(ASTType::Match, op.span.join(expr.span))
node.u.match_stmt.expr = expr
let cases = Vector<&MatchCase>::new()
.consume(TokenType::OpenCurly)
while not .token_is(TokenType::CloseCurly) {
if .token_is(TokenType::Else) {
node.u.match_stmt.defolt_span = .token().span
.consume(TokenType::Else)
.consume(TokenType::FatArrow)
node.u.match_stmt.defolt = .parse_statement()
} else {
let cond = .parse_atom(TokenType::Line)
let body = null as &AST
if not .consume_if(TokenType::Line) {
.consume(TokenType::FatArrow)
body = .parse_statement()
if not .token_is(TokenType::CloseCurly) {
.consume_newline_or(TokenType::Comma)
}
}
let _case = MatchCase::new(cond, body)
cases.push(_case)
}
}
node.span = op.span.join(.token().span)
.consume(TokenType::CloseCurly)
node.u.match_stmt.cases = cases
return node
}
def Parser::parse_literal_suffix_type(&this, suffix: &Token): &Type {
if not suffix? return null
let ident = AST::new(ASTType::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 {
.consume(TokenType::OpenParen)
let args = Vector<&Argument>::new()
while not .token_is(TokenType::CloseParen) {
let label = null as str
let label_span = Span::default()
let expr = .parse_expression(end_type: TokenType::Comma)
if expr.type == ASTType::Identifier and .token_is(TokenType::Colon) {
.consume(TokenType::Colon)
label = expr.u.ident.name
label_span = expr.span
expr = .parse_expression(end_type: TokenType::Comma)
}
args.push(Argument::new(label, label_span, expr))
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
return call
}
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(ASTType::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 = null as &Type
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)
node.u.var_decl.var = var
if .consume_if(TokenType::Equals) {
node.u.var_decl.init = .parse_expression(end_type: TokenType::Newline)
}
.consume_newline_or(TokenType::Semicolon)
return node
}
def Parser::parse_atom(&this, end_type: TokenType): &AST {
let node = null as &AST
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(ASTType::Null, tok.span)
}
TokenType::IntLiteral => {
node = AST::new(ASTType::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(ASTType::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(ASTType::StringLiteral, .token().span)
let tok = .consume(TokenType::StringLiteral)
node.u.string_literal = tok.text
}
TokenType::CharLiteral => {
node = AST::new(ASTType::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(ASTType::BoolLiteral, tok.span)
node.u.bool_literal = tok.type == TokenType::True
}
TokenType::OpenParen => {
.consume(TokenType::OpenParen)
node = .parse_expression(end_type: TokenType::CloseParen)
.consume(TokenType::CloseParen)
}
TokenType::Dot => {
let tok = .consume(TokenType::Dot)
let ident = .consume(TokenType::Identifier)
if not .curr_func? or not .curr_func.is_method or .curr_func.is_static {
.error(Error::new(tok.span, "Cannot use dot shorthand outside of a method"))
return AST::new(ASTType::Error, tok.span)
}
let lhs = AST::new(ASTType::Identifier, tok.span)
lhs.u.ident.name = "this"
node = AST::new(ASTType::Member, tok.span.join(ident.span))
node.u.member.lhs = lhs
node.u.member.rhs_name = ident.text
node.u.member.rhs_span = ident.span
}
else => {
.unhandled_type("parse_expression")
node = AST::new(ASTType::Error, .token().span)
.curr += 1
}
}
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 => {
.consume(TokenType::Dot)
let name = .consume(TokenType::Identifier)
let member = AST::new(ASTType::Member, node.span.join(name.span))
member.u.member.lhs = node
member.u.member.rhs_name = name.text
member.u.member.rhs_span = name.span
node = member
}
TokenType::Question => {
let tok = .consume(TokenType::Question)
let op = AST::new(ASTType::IsNotNull, node.span.join(tok.span))
op.u.unary = node
node = op
}
TokenType::OpenSquare => {
.consume(TokenType::OpenSquare)
let index = .parse_expression(end_type: TokenType::CloseSquare)
let close = .consume(TokenType::CloseSquare)
let op = AST::new(ASTType::Index, node.span.join(close.span))
op.u.binary.lhs = node
op.u.binary.rhs = index
node = op
}
TokenType::MinusMinus | TokenType::PlusPlus => {
let span = node.span.join(.token().span)
let op = if .token_is(TokenType::MinusMinus) {
.consume(TokenType::MinusMinus)
yield ASTType::PostDecrement
} else {
.consume(TokenType::PlusPlus)
yield ASTType::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(ASTType::Address, amp.span.join(expr.span))
node.u.unary = expr
return node
}
TokenType::MinusMinus | TokenType::PlusPlus => {
let start_span = .token().span
let op = if .token_is(TokenType::MinusMinus) {
.consume(TokenType::MinusMinus)
yield ASTType::PreDecrement
} else {
.consume(TokenType::PlusPlus)
yield ASTType::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(ASTType::SizeOf, start.span.join(close.span))
node.u.size_of_type = type
return node
}
TokenType::Star => {
let star = .consume(TokenType::Star)
let expr = .parse_prefix(end_type)
let node = AST::new(ASTType::Dereference, star.span.join(expr.span))
node.u.unary = expr
return node
}
TokenType::Minus => {
let minus = .consume(TokenType::Minus)
let expr = .parse_prefix(end_type)
let node = AST::new(ASTType::Negate, minus.span.join(expr.span))
node.u.unary = expr
return node
}
TokenType::Not => {
let tok = .consume(TokenType::Not)
let expr = .parse_prefix(end_type)
let node = AST::new(ASTType::Not, tok.span.join(expr.span))
node.u.unary = expr
return node
}
TokenType::Tilde => {
let tok = .consume(TokenType::Tilde)
let expr = .parse_prefix(end_type)
let node = AST::new(ASTType::BitwiseNot, tok.span.join(expr.span))
node.u.unary = expr
return node
}
else => return .parse_postfix(end_type)
}
}
def Parser::parse_cast(&this, end_type: TokenType): &AST {
let lhs = .parse_prefix(end_type)
while .token_is(TokenType::As) {
if .token_is(end_type) break
let tok = .consume(TokenType::As)
let type_node = .parse_type()
let op = AST::new(ASTType::Cast, lhs.span.join(type_node.span))
op.u.cast.lhs = lhs
op.u.cast.to = type_node
lhs = op
}
return lhs
}
def Parser::parse_term(&this, end_type: TokenType): &AST {
let lhs = .parse_cast(end_type)
while .token_is(TokenType::Star) or
.token_is(TokenType::Slash) or
.token_is(TokenType::Percent) {
if .token_is(end_type) break
let op = ASTType::from_token(.token().type)
.curr += 1
let rhs = .parse_cast(end_type)
lhs = AST::new_binop(op, lhs, rhs)
}
return lhs
}
def Parser::parse_additive(&this, end_type: TokenType): &AST {
let lhs = .parse_term(end_type)
while .token_is(TokenType::Plus) or .token_is(TokenType::Minus) {
if .token_is(end_type) break
let op = ASTType::from_token(.token().type)
.curr += 1
let rhs = .parse_term(end_type)
lhs = AST::new_binop(op, lhs, rhs)
}
return lhs
}
def Parser::parse_shift(&this, end_type: TokenType): &AST {
let lhs = .parse_additive(end_type)
while .token_is(TokenType::LessThan) or
.token_is(TokenType::GreaterThan) {
let next_token = .tokens.at(.curr + 1)
if .token().type != next_token.type then break
if .token_is(end_type) break
let op = if next_token.type == TokenType::LessThan {
yield ASTType::LeftShift
} else {
yield ASTType::RightShift
}
.curr += 2
let rhs = .parse_additive(end_type)
lhs = AST::new_binop(op, lhs, rhs)
}
return lhs
}
def Parser::parse_bw_and(&this, end_type: TokenType): &AST {
let lhs = .parse_shift(end_type)
while .token_is(TokenType::Ampersand) {
if .token_is(end_type) break
let op = ASTType::from_token(.token().type)
.curr += 1
let rhs = .parse_shift(end_type)
lhs = AST::new_binop(op, lhs, rhs)
}
return lhs
}
def Parser::parse_bw_xor(&this, end_type: TokenType): &AST {
let lhs = .parse_bw_and(end_type)
while .token_is(TokenType::Caret) {
if .token_is(end_type) break
let op = ASTType::from_token(.token().type)
.curr += 1
let rhs = .parse_bw_and(end_type)
lhs = AST::new_binop(op, lhs, rhs)
}
return lhs
}
def Parser::parse_bw_or(&this, end_type: TokenType): &AST {
let lhs = .parse_bw_xor(end_type)
while .token_is(TokenType::Line) {
if .token_is(end_type) break
let op = ASTType::from_token(.token().type)
.curr += 1
let rhs = .parse_bw_xor(end_type)
lhs = AST::new_binop(op, lhs, rhs)
}
return lhs
}
def Parser::parse_relational(&this, end_type: TokenType): &AST {
let operands = Vector<&AST>::new()
let operators = Vector<&Token>::new()
operands.push(.parse_bw_or(end_type))
while .token_is(TokenType::LessThan) or
.token_is(TokenType::GreaterThan) or
.token_is(TokenType::LessThanEquals) or
.token_is(TokenType::GreaterThanEquals) or
.token_is(TokenType::EqualEquals) or
.token_is(TokenType::NotEquals) {
if .token_is(end_type) break
operators.push(.token())
.curr += 1
let term = .parse_bw_or(end_type)
operands.push(term)
}
if operators.size == 0 then return operands.at(0)
let root = null as &AST
for let i = 0; i < operators.size; i += 1 {
let tok = operators.at(i)
let lhs = operands.at(i)
let rhs = operands.at(i+1)
let op = AST::new_binop(ASTType::from_token(tok.type), lhs, rhs)
if root? {
root = AST::new_binop(ASTType::And, root, op)
} else {
root = op
}
}
operands.free()
operators.free()
return root
}
def Parser::parse_logical_and(&this, end_type: TokenType): &AST {
let lhs = .parse_relational(end_type)
while .token_is(TokenType::And) {
if .token_is(end_type) break
let op = ASTType::from_token(.token().type)
.curr += 1
let rhs = .parse_relational(end_type)
lhs = AST::new_binop(op, lhs, rhs)
}
return lhs
}
def Parser::parse_logical_or(&this, end_type: TokenType): &AST {
let lhs = .parse_logical_and(end_type)
while .token_is(TokenType::Or) {
if .token_is(end_type) break
let op = ASTType::from_token(.token().type)
.curr += 1
let rhs = .parse_logical_and(end_type)
lhs = AST::new_binop(op, lhs, rhs)
}
return lhs
}
def Parser::parse_expression(&this, end_type: TokenType): &AST {
let lhs = .parse_logical_or(end_type)
while .token_is(TokenType::Equals) or
.token_is(TokenType::PlusEquals) or
.token_is(TokenType::MinusEquals) or
.token_is(TokenType::StarEquals) or
.token_is(TokenType::SlashEquals) {
if .token_is(end_type) break
let op = ASTType::from_token(.token().type)
.curr += 1
let rhs = .parse_expression(end_type)
lhs = AST::new_binop(op, lhs, rhs)
}
return lhs
}
def Parser::parse_if(&this): &AST {
let start_span = .token().span
.consume(TokenType::If)
let cond = .parse_expression(end_type: TokenType::Newline)
.consume_if(TokenType::Then)
let body = .parse_statement()
let end_span = body.span
let els = null as &AST
if .consume_if(TokenType::Else) {
els = .parse_statement()
end_span = els.span
}
let node = AST::new(ASTType::If, start_span.join(end_span))
node.u.if_stmt.cond = cond
node.u.if_stmt.body = body
node.u.if_stmt.els = els
return node
}
//* Parse for-each loops syntax sugar
//*
//* This function is responsible for parsing
//*
//* for i : expr {
//* ...
//* }
//*
//* and converting it into
//*
//* for let __iter = expr; __iter.has_value(); __iter.next() {
//* let i = __iter.get();
//* {
//* ...
//* }
//* }
def Parser::parse_for_each(&this, start_span: Span): &AST {
let name = .consume(Identifier)
.consume(TokenType::Colon)
let expr = .parse_expression(end_type: TokenType::Newline)
let iter_var_name = "__iter"
let init = {
let node = AST::new(ASTType::VarDeclaration, expr.span)
let var = Variable::new(null)
var.sym = Symbol::from_local_variable(iter_var_name, var, name.span)
node.u.var_decl.var = var
node.u.var_decl.init = expr
yield node
}
let cond = {
let iter_name = AST::new(ASTType::Identifier, expr.span)
iter_name.u.ident.name = iter_var_name
let member = AST::new(ASTType::Member, expr.span)
member.u.member.lhs = iter_name
member.u.member.rhs_name = "has_value"
member.u.member.rhs_span = expr.span
let node = AST::new(ASTType::Call, expr.span)
node.u.call.callee = member
node.u.call.args = Vector<&Argument>::new()
yield node
}
let step = {
let iter_name = AST::new(ASTType::Identifier, expr.span)
iter_name.u.ident.name = iter_var_name
let member = AST::new(ASTType::Member, expr.span)
member.u.member.lhs = iter_name
member.u.member.rhs_name = "next"
member.u.member.rhs_span = expr.span
let node = AST::new(ASTType::Call, expr.span)
node.u.call.callee = member
node.u.call.args = Vector<&Argument>::new()
yield node
}
let loop_var_decl = {
let var = Variable::new(null)
var.sym = Symbol::from_local_variable(name.text, var, name.span)
let iter_name = AST::new(ASTType::Identifier, name.span)
iter_name.u.ident.name = iter_var_name
let member = AST::new(ASTType::Member, expr.span)
member.u.member.lhs = iter_name
member.u.member.rhs_name = "cur"
member.u.member.rhs_span = expr.span
let call = AST::new(ASTType::Call, expr.span)
call.u.call.callee = member
call.u.call.args = Vector<&Argument>::new()
let node = AST::new(ASTType::VarDeclaration, expr.span)
node.u.var_decl.var = var
node.u.var_decl.init = call
yield node
}
let inner_body = .parse_block()
let statements = Vector<&AST>::new()
statements.push(loop_var_decl)
statements.push(inner_body)
let body = AST::new(ASTType::Block, inner_body.span)
body.u.block.statements = statements
let node = AST::new(ASTType::For, start_span.join(body.span))
node.u.loop.init = init
node.u.loop.cond = cond
node.u.loop.step = step
node.u.loop.body = body
return node
}
def Parser::parse_for(&this): &AST {
let tok = .consume(TokenType::For)
if .token_is(Identifier) and .peek(1).type == TokenType::Colon {
return .parse_for_each(start_span: tok.span)
}
let init = null as &AST
if .token_is(TokenType::Let) {
init = .parse_statement()
} else {
init = .parse_expression(end_type: TokenType::Semicolon)
.consume(TokenType::Semicolon)
}
let cond = .parse_expression(end_type: TokenType::Semicolon)
.consume(TokenType::Semicolon)
let step = .parse_expression(end_type: TokenType::OpenCurly)
let body = .parse_block()
let node = AST::new(ASTType::For, tok.span.join(body.span))
node.u.loop.init = init
node.u.loop.cond = cond
node.u.loop.step = step
node.u.loop.body = body
return node
}
def Parser::parse_statement(&this): &AST {
let node = null as &AST
let start_span = .token().span
match .token().type {
TokenType::OpenCurly => node = .parse_block()
TokenType::Return => {
.consume(TokenType::Return)
let expr = null as &AST
if not .token().seen_newline {
expr = .parse_expression(end_type: TokenType::Newline)
}
node = AST::new_unop(ASTType::Return, start_span.join(.token().span), expr)
.consume_end_of_statement()
}
TokenType::Yield => {
.consume(TokenType::Yield)
let expr = .parse_expression(end_type: TokenType::Newline)
node = AST::new_unop(ASTType::Yield, start_span.join(.token().span), expr)
.consume_end_of_statement()
}
TokenType::Break => {