-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathparser.rs
3411 lines (2949 loc) · 126 KB
/
parser.rs
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
#![cfg_attr(feature = "panic_on_parser_error", allow(unreachable_code))]
use crate::{
ast::{Ast, AstIndex},
constant_pool::{ConstantIndex, ConstantPoolBuilder},
error::{Error, ErrorKind, ExpectedIndentation, InternalError, Result, SyntaxError},
node::*,
StringFormatOptions,
};
use koto_lexer::{LexedToken, Lexer, Span, StringType, Token};
use std::{
collections::HashSet,
iter::Peekable,
str::{Chars, FromStr},
};
// Contains info about the current frame, representing either the module's top level or a function
#[derive(Debug, Default)]
struct Frame {
// If a frame contains yield then it represents a generator function
contains_yield: bool,
// IDs that have been assigned within the current frame
ids_assigned_in_frame: HashSet<ConstantIndex>,
// IDs and chain roots which were accessed when not locally assigned at the time of access
accessed_non_locals: HashSet<ConstantIndex>,
// While expressions are being parsed we keep track of lhs assignments and rhs accesses.
// At the end of a multi-assignment expression (see `finalize_id_accesses`),
// accessed IDs that weren't locally assigned at the time of access are then counted as
// non-local accesses.
pending_accesses: HashSet<ConstantIndex>,
pending_assignments: HashSet<ConstantIndex>,
}
impl Frame {
// The number of local values declared within the frame
fn local_count(&self) -> usize {
self.ids_assigned_in_frame.len()
}
// Non-locals accessed in a nested frame need to be declared as also accessed in this
// frame. This ensures that captures from the outer frame will be available when
// creating the nested inner frame.
fn add_nested_accessed_non_locals(&mut self, nested_frame: &Frame) {
for non_local in nested_frame.accessed_non_locals.iter() {
if !self.pending_assignments.contains(non_local) {
self.add_id_access(*non_local);
}
}
}
// Declare that an id has been accessed within the frame
fn add_id_access(&mut self, id: ConstantIndex) {
self.pending_accesses.insert(id);
}
// Declare that an id is being assigned to within the frame
fn add_local_id_assignment(&mut self, id: ConstantIndex) {
self.pending_assignments.insert(id);
// While an assignment expression is being parsed, the LHS id is counted as an access
// until the assignment operator is encountered.
self.pending_accesses.remove(&id);
}
// At the end of an expression, determine which RHS accesses are non-local
fn finalize_id_accesses(&mut self) {
for id in self.pending_accesses.drain() {
if !self.ids_assigned_in_frame.contains(&id) {
self.accessed_non_locals.insert(id);
}
}
self.ids_assigned_in_frame
.extend(self.pending_assignments.drain());
}
}
// The set of rules that can modify how an expression is parsed
#[derive(Clone, Copy, Debug)]
struct ExpressionContext {
// e.g.
//
// match x
// foo.bar if x == 0 then...
//
// Without the flag, `if f == 0...` would be parsed as being an argument for a call to foo.bar.
allow_space_separated_call: bool,
// e.g. f = |x|
// x + x
// This function can have an indented body.
//
// foo
// bar,
// baz
// This function call can be broken over lines.
//
// while x < f y
// ...
// Here, `f y` can't be broken over lines as the while expression expects an indented block.
allow_linebreaks: bool,
// When true, a map block is allowed in the current context.
// e.g.
//
// x = foo: 42
// ^~~ A map block requires an indented block, so here the flag should be false
//
// return
// foo: 41
// ^~~ A colon following the foo identifier signifies the start of a map block.
// Consuming tokens through the indentation sets the flag to true,
// see consume_until_next_token()
//
// x = ||
// foo: 42
// ^~~ The first line in an indented block will have the flag set to true to allow the
// block to be parsed as a map, see parse_indented_block().
allow_map_block: bool,
// The indentation rules for the current context
expected_indentation: Indentation,
}
// The indentation that should be expected on following lines for an expression to continue
#[derive(Clone, Copy, Debug)]
enum Indentation {
// Indentation isn't required on following lines
// (e.g. in a comma separated braced expression)
Flexible,
// Indentation should match the expected indentation
// (e.g. in an indented block, each line should start with the same indentation)
Equal(usize),
// Indentation should be greater than the current indentation
Greater,
// Indentation should be greater than the specified indentation
GreaterThan(usize),
// Indentation should be greater than or equal to the specified indentation
GreaterOrEqual(usize),
}
impl ExpressionContext {
fn permissive() -> Self {
Self {
allow_space_separated_call: true,
allow_linebreaks: true,
allow_map_block: false,
expected_indentation: Indentation::Greater,
}
}
fn restricted() -> Self {
Self {
allow_space_separated_call: false,
allow_linebreaks: false,
allow_map_block: false,
expected_indentation: Indentation::Greater,
}
}
fn inline() -> Self {
Self {
allow_space_separated_call: true,
allow_linebreaks: false,
allow_map_block: false,
expected_indentation: Indentation::Greater,
}
}
// After a keyword like `yield` or `return`.
// Like inline(), but inherits allow_linebreaks
fn start_new_expression(&self) -> Self {
Self {
allow_space_separated_call: true,
allow_linebreaks: self.allow_linebreaks,
allow_map_block: false,
expected_indentation: Indentation::Greater,
}
}
// At the start of a braced expression
// e.g.
// x = [f x, y] # A single entry list is created with the result of calling `f(x, y)`
fn braced_items_start() -> Self {
Self {
allow_space_separated_call: true,
allow_linebreaks: true,
allow_map_block: false,
expected_indentation: Indentation::Flexible,
}
}
// After the first item in a braced expression
// Space-separated calls aren't allowed after the first entry,
// otherwise confusing expressions like the following would be accepted:
// x = [1, 2, foo 3, 4, 5]
// # This would be parsed as [1, 2, foo(3, 4, 5)]
fn braced_items_continued() -> Self {
Self {
allow_space_separated_call: false,
allow_linebreaks: true,
allow_map_block: false,
expected_indentation: Indentation::Flexible,
}
}
// e.g.
// [
// foo
// .bar()
// # ^ here we're allowing an indented chain to be started
// ]
fn chain_start(&self) -> Self {
use Indentation::*;
let expected_indentation = match self.expected_indentation {
Flexible | Equal(_) => Greater,
other => other,
};
Self {
allow_space_separated_call: self.allow_space_separated_call,
allow_linebreaks: self.allow_linebreaks,
allow_map_block: false,
expected_indentation,
}
}
fn with_expected_indentation(&self, expected_indentation: Indentation) -> Self {
Self {
expected_indentation,
..*self
}
}
}
/// Koto's parser
pub struct Parser<'source> {
source: &'source str,
ast: Ast,
constants: ConstantPoolBuilder,
lexer: Lexer<'source>,
current_token: LexedToken,
current_line: u32,
frame_stack: Vec<Frame>,
}
impl<'source> Parser<'source> {
/// Takes in a source script, and produces an Ast
pub fn parse(source: &'source str) -> Result<Ast> {
let capacity_guess = source.len() / 4;
let mut parser = Parser {
source,
ast: Ast::with_capacity(capacity_guess),
constants: ConstantPoolBuilder::default(),
lexer: Lexer::new(source),
current_token: LexedToken::default(),
current_line: 0,
frame_stack: Vec::new(),
};
parser.consume_main_block()?;
parser.ast.set_constants(parser.constants.build());
Ok(parser.ast)
}
// Parses the main 'top-level' block
fn consume_main_block(&mut self) -> Result<AstIndex> {
self.frame_stack.push(Frame::default());
let start_span = self.current_span();
let mut context = ExpressionContext::permissive();
context.expected_indentation = Indentation::Equal(0);
let mut body = AstVec::new();
while self.peek_token_with_context(&context).is_some() {
self.consume_until_token_with_context(&context);
let Some(expression) = self.parse_line(&ExpressionContext::permissive())? else {
return self.consume_token_and_error(SyntaxError::ExpectedExpression);
};
body.push(expression);
match self.peek_next_token_on_same_line() {
Some(Token::NewLine) => continue,
None => break,
_ => return self.consume_token_and_error(SyntaxError::UnexpectedToken),
}
}
// Check that all tokens were consumed
self.consume_until_token_with_context(&ExpressionContext::permissive());
if self.peek_token().is_some() {
return self.consume_token_and_error(SyntaxError::UnexpectedToken);
}
let result = self.push_node_with_start_span(
Node::MainBlock {
body,
local_count: self.frame()?.local_count(),
},
start_span,
)?;
self.frame_stack.pop();
Ok(result)
}
// Attempts to parse an indented block after the current position
//
// e.g.
// my_function = |x, y| # <- Here at entry
// x = y + 1 # | < indented block
// foo x # | < indented block
fn parse_indented_block(&mut self) -> Result<Option<AstIndex>> {
let block_context = ExpressionContext::permissive();
let start_indent = self.current_indent();
match self.peek_token_with_context(&block_context) {
Some(peeked) if peeked.info.indent > start_indent => {}
_ => return Ok(None), // No indented block found
}
let block_context = self
.consume_until_token_with_context(&block_context)
.unwrap(); // Safe to unwrap here given that we've just peeked
let start_span = self.current_span();
let mut block = AstVec::new();
loop {
let line_context = ExpressionContext {
allow_map_block: block.is_empty(),
..ExpressionContext::permissive()
};
let Some(expression) = self.parse_line(&line_context)? else {
// At this point we've peeked to check that the line is either the start of the
// block, or a continuation with the same indentation as the block.
return self.consume_token_and_error(SyntaxError::UnexpectedToken);
};
block.push(expression);
match self.peek_next_token_on_same_line() {
None => break,
Some(Token::NewLine) => {}
_ => return self.consume_token_and_error(SyntaxError::UnexpectedToken),
}
// Peek ahead to see if the indented block continues after this line
if self.peek_token_with_context(&block_context).is_none() {
break;
}
self.consume_until_token_with_context(&block_context);
}
// If the block is a single expression then it doesn't need to be wrapped in a Block node
if block.len() == 1 {
Ok(Some(*block.first().unwrap()))
} else {
self.push_node_with_start_span(Node::Block(block), start_span)
.map(Some)
}
}
// Parses expressions from the start of a line
fn parse_line(&mut self, context: &ExpressionContext) -> Result<Option<AstIndex>> {
self.parse_expressions(context, TempResult::No)
}
// Parse a comma separated series of expressions
//
// If only a single expression is encountered then that expression's node is the result.
//
// Otherwise, for multiple expressions, the result of the expression can be temporary
// (i.e. not assigned to an identifier) in which case a TempTuple is generated,
// otherwise the result will be a Tuple.
fn parse_expressions(
&mut self,
context: &ExpressionContext,
temp_result: TempResult,
) -> Result<Option<AstIndex>> {
let mut expression_context = ExpressionContext {
allow_space_separated_call: true,
..*context
};
let start_line = self.current_line;
let Some(first) = self.parse_expression(&expression_context)? else {
return Ok(None);
};
let mut expressions = astvec![first];
let mut encountered_linebreak = false;
let mut encountered_comma = false;
while let Some(Token::Comma) = self.peek_next_token_on_same_line() {
self.consume_next_token_on_same_line();
encountered_comma = true;
if !encountered_linebreak && self.current_line > start_line {
// e.g.
// x, y =
// 1, # <- We're here,
// # following values should have at least this level of indentation.
// 0,
expression_context = expression_context
.with_expected_indentation(Indentation::GreaterOrEqual(self.current_indent()));
encountered_linebreak = true;
}
if let Some(next_expression) =
self.parse_expression_start(&expressions, 0, &expression_context)?
{
match self.ast.node(next_expression).node {
Node::Assign { .. } | Node::MultiAssign { .. } => {
// Assignments will have consumed all of the comma-separated expressions
// encountered so far as the LHS of the assignment, so we can exit here.
return Ok(Some(next_expression));
}
_ => {}
}
let next_expression = match self.peek_next_token_on_same_line() {
Some(Token::Range | Token::RangeInclusive) => {
self.consume_range(Some(next_expression), context)?
}
_ => next_expression,
};
expressions.push(next_expression);
}
}
self.frame_mut()?.finalize_id_accesses();
if expressions.len() == 1 && !encountered_comma {
Ok(Some(first))
} else {
let result = match temp_result {
TempResult::No => Node::Tuple(expressions),
TempResult::Yes => Node::TempTuple(expressions),
};
Ok(Some(self.push_node(result)?))
}
}
// Parses a single expression
//
// Unlike parse_expressions() (which will consume a comma-separated series of expressions),
// parse_expression() will stop when a comma is encountered.
fn parse_expression(&mut self, context: &ExpressionContext) -> Result<Option<AstIndex>> {
self.parse_expression_with_min_precedence(0, context)
}
// Parses a single expression with a specified minimum operator precedence
fn parse_expression_with_min_precedence(
&mut self,
min_precedence: u8,
context: &ExpressionContext,
) -> Result<Option<AstIndex>> {
let result = self.parse_expression_start(&[], min_precedence, context)?;
match self.peek_next_token_on_same_line() {
Some(Token::Range | Token::RangeInclusive) => {
self.consume_range(result, context).map(Some)
}
_ => Ok(result),
}
}
// Parses a term, and then checks to see if the expression is continued
//
// When parsing comma-separated expressions, the previous expressions are passed in so that
// if an assignment operator is encountered then the overall expression is treated as a
// multi-assignment.
fn parse_expression_start(
&mut self,
previous_expressions: &[AstIndex],
min_precedence: u8,
context: &ExpressionContext,
) -> Result<Option<AstIndex>> {
let entry_line = self.current_line;
// Look ahead to get the indent of the first token in the expression.
// We need to look ahead here because the term may contain its own indentation,
// so it may end with different indentation.
let Some(start_info) = self.peek_token_with_context(context) else {
return Ok(None);
};
let Some(expression_start) = self.parse_term(context)? else {
return Ok(None);
};
let start_span = *self.ast.span(self.ast.node(expression_start).span);
let continuation_context = if self.current_line > entry_line {
match context.expected_indentation {
Indentation::Equal(indent)
| Indentation::GreaterThan(indent)
| Indentation::GreaterOrEqual(indent) => {
// If the context has a fixed indentation requirement, then allow the
// indentation for the continued expression to grow or stay the same
context.with_expected_indentation(Indentation::GreaterOrEqual(indent))
}
Indentation::Greater | Indentation::Flexible => {
// Indentation within an arithmetic expression shouldn't be able to continue
// with decreased indentation
context.with_expected_indentation(Indentation::GreaterOrEqual(
start_info.info.indent,
))
}
}
} else {
*context
};
self.parse_expression_continued(
expression_start,
start_span,
previous_expressions,
min_precedence,
&continuation_context,
)
}
// Parses the continuation of an expression_context
//
// Checks for an operator, and then parses the following expressions as the RHS of a binary
// operation.
fn parse_expression_continued(
&mut self,
expression_start: AstIndex,
start_span: Span,
previous_expressions: &[AstIndex],
min_precedence: u8,
context: &ExpressionContext,
) -> Result<Option<AstIndex>> {
let start_line = self.current_line;
let start_indent = self.current_indent();
if let Some(assignment_expression) =
self.parse_assign_expression(expression_start, previous_expressions, context)?
{
return Ok(Some(assignment_expression));
} else if let Some(next) = self.peek_token_with_context(context) {
if let Some((left_priority, right_priority)) = operator_precedence(next.token) {
if left_priority >= min_precedence {
let (op, _) = self.consume_token_with_context(context).unwrap();
// Move on to the token after the operator
if self.peek_token_with_context(context).is_none() {
return self.error(ExpectedIndentation::RhsExpression);
}
self.consume_until_token_with_context(context).unwrap();
let rhs_context = if self.current_line > start_line {
match context.expected_indentation {
Indentation::Equal(indent)
| Indentation::GreaterThan(indent)
| Indentation::GreaterOrEqual(indent) => {
// If the context has a fixed indentation requirement, then allow
// the indentation for the continued expression to grow or stay the
// same.
context
.with_expected_indentation(Indentation::GreaterOrEqual(indent))
}
Indentation::Greater | Indentation::Flexible => {
// Indentation within an arithmetic expression shouldn't be able to
// continue with decreased indentation.
context.with_expected_indentation(Indentation::GreaterOrEqual(
start_indent,
))
}
}
} else {
*context
};
let Some(rhs) =
self.parse_expression_start(&[], right_priority, &rhs_context)?
else {
return self.error(ExpectedIndentation::RhsExpression);
};
use Token::*;
let ast_op = match op {
Add => AstBinaryOp::Add,
Subtract => AstBinaryOp::Subtract,
Multiply => AstBinaryOp::Multiply,
Divide => AstBinaryOp::Divide,
Remainder => AstBinaryOp::Remainder,
AddAssign => AstBinaryOp::AddAssign,
SubtractAssign => AstBinaryOp::SubtractAssign,
MultiplyAssign => AstBinaryOp::MultiplyAssign,
DivideAssign => AstBinaryOp::DivideAssign,
RemainderAssign => AstBinaryOp::RemainderAssign,
Equal => AstBinaryOp::Equal,
NotEqual => AstBinaryOp::NotEqual,
Greater => AstBinaryOp::Greater,
GreaterOrEqual => AstBinaryOp::GreaterOrEqual,
Less => AstBinaryOp::Less,
LessOrEqual => AstBinaryOp::LessOrEqual,
And => AstBinaryOp::And,
Or => AstBinaryOp::Or,
Arrow => AstBinaryOp::Pipe,
_ => unreachable!(), // The list of tokens here matches the operators in
// operator_precedence()
};
let op_node = self.push_node_with_start_span(
Node::BinaryOp {
op: ast_op,
lhs: expression_start,
rhs,
},
start_span,
)?;
return self.parse_expression_continued(
op_node,
start_span,
&[],
min_precedence,
&rhs_context,
);
}
}
}
Ok(Some(expression_start))
}
// Parses an assignment expression
//
// In a multi-assignment expression the LHS can be a series of targets. The last target in the
// series will be passed in as `lhs`, with the previous targets passed in as `previous_lhs`.
//
// If the assignment is an export then operators other than `=` will be rejected.
fn parse_assign_expression(
&mut self,
lhs: AstIndex,
previous_lhs: &[AstIndex],
context: &ExpressionContext,
) -> Result<Option<AstIndex>> {
match self
.peek_token_with_context(context)
.map(|token| token.token)
{
Some(Token::Assign) => {}
_ => return Ok(None),
}
let mut targets = AstVec::with_capacity(previous_lhs.len() + 1);
for lhs_expression in previous_lhs.iter().chain(std::iter::once(&lhs)) {
// Note which identifiers are being assigned to
match self.ast.node(*lhs_expression).node.clone() {
Node::Id(id_index, ..) => {
self.frame_mut()?.add_local_id_assignment(id_index);
}
Node::Meta { .. } | Node::Chain(_) | Node::Wildcard(..) => {}
_ => return self.error(SyntaxError::ExpectedAssignmentTarget),
}
targets.push(*lhs_expression);
}
if targets.is_empty() {
return self.error(InternalError::MissingAssignmentTarget);
}
// Consume the `=` token
self.consume_token_with_context(context);
let assign_span = self.current_span();
let single_target = targets.len() == 1;
let temp_result = if single_target {
TempResult::No
} else {
TempResult::Yes
};
if let Some(rhs) = self.parse_expressions(context, temp_result)? {
let node = if single_target {
Node::Assign {
target: *targets.first().unwrap(),
expression: rhs,
}
} else {
Node::MultiAssign {
targets,
expression: rhs,
}
};
Ok(Some(self.push_node_with_span(node, assign_span)?))
} else {
self.consume_token_on_same_line_and_error(ExpectedIndentation::AssignmentExpression)
}
}
// Peeks the next token and dispatches to the relevant parsing functions
fn parse_term(&mut self, context: &ExpressionContext) -> Result<Option<AstIndex>> {
use Node::*;
let start_span = self.current_span();
let start_indent = self.current_indent();
let Some(peeked) = self.peek_token_with_context(context) else {
return Ok(None);
};
let result = match peeked.token {
Token::Null => {
self.consume_token_with_context(context);
self.push_node(Null)
}
Token::True => {
self.consume_token_with_context(context);
self.push_node(BoolTrue)
}
Token::False => {
self.consume_token_with_context(context);
self.push_node(BoolFalse)
}
Token::RoundOpen => self.consume_tuple(context),
Token::Number => self.consume_number(false, context),
Token::StringStart { .. } => {
let string = self.parse_string(context)?.unwrap();
let string_node = self.push_node_with_span(Str(string.string), string.span)?;
if string.context.allow_map_block
&& self.peek_next_token_on_same_line() == Some(Token::Colon)
{
self.consume_map_block(string_node, start_span, &string.context)
} else {
self.check_for_chain_after_node(string_node, &string.context)
}
}
Token::Id => self.consume_id_expression(context),
Token::Self_ => self.consume_self_expression(context),
Token::At => {
let map_block_allowed =
context.allow_map_block || peeked.info.indent > start_indent;
let meta_context = self.consume_until_token_with_context(context).unwrap();
// Safe to unwrap here, parse_meta_key would error on invalid key
let meta_key = self.parse_meta_key()?.unwrap();
if map_block_allowed
&& matches!(
self.peek_token_with_context(context),
Some(PeekInfo {
token: Token::Colon,
..
})
)
{
self.consume_map_block(meta_key, start_span, &meta_context)
} else {
match self.parse_assign_expression(meta_key, &[], &meta_context)? {
Some(result) => self.push_node(Node::Export(result)),
None => self
.consume_token_and_error(SyntaxError::ExpectedAssignmentAfterMetaKey),
}
}
}
Token::Wildcard => {
let maybe_id = self.consume_wildcard(context)?;
self.push_node(Node::Wildcard(maybe_id, None))
}
Token::SquareOpen => self.consume_list(context),
Token::CurlyOpen => self.consume_map_with_braces(context),
Token::If => self.consume_if_expression(context),
Token::Match => self.consume_match_expression(context),
Token::Switch => self.consume_switch_expression(context),
Token::Function => self.consume_function(context),
Token::Subtract => match self.peek_token_n(peeked.peek_count + 1) {
Some(token) if token.is_whitespace_including_newline() => return Ok(None),
Some(Token::Number) => {
self.consume_token_with_context(context); // Token::Subtract
self.consume_number(true, context)
}
Some(_) => {
self.consume_token_with_context(context); // Token::Subtract
if let Some(term) = self.parse_term(&ExpressionContext::restricted())? {
self.push_node(Node::UnaryOp {
op: AstUnaryOp::Negate,
value: term,
})
} else {
self.consume_token_and_error(SyntaxError::ExpectedExpression)
}
}
None => return Ok(None),
},
Token::Not => {
self.consume_token_with_context(context);
if let Some(expression) = self.parse_expression(&ExpressionContext {
allow_space_separated_call: true,
expected_indentation: Indentation::Greater,
..*context
})? {
self.push_node(Node::UnaryOp {
op: AstUnaryOp::Not,
value: expression,
})
} else {
self.consume_token_and_error(SyntaxError::ExpectedExpression)
}
}
Token::Yield => {
self.consume_token_with_context(context);
let start_span = self.current_span();
if let Some(expression) =
self.parse_expressions(&context.start_new_expression(), TempResult::No)?
{
self.frame_mut()?.contains_yield = true;
self.push_node_with_start_span(Node::Yield(expression), start_span)
} else {
self.consume_token_and_error(SyntaxError::ExpectedExpression)
}
}
Token::Loop => self.consume_loop_block(context),
Token::For => self.consume_for_loop(context),
Token::While => self.consume_while_loop(context),
Token::Until => self.consume_until_loop(context),
Token::Break => {
self.consume_token_with_context(context);
let break_value =
self.parse_expressions(&context.start_new_expression(), TempResult::No)?;
self.push_node(Node::Break(break_value))
}
Token::Continue => {
self.consume_token_with_context(context);
self.push_node(Node::Continue)
}
Token::Return => {
self.consume_token_with_context(context);
let start_span = self.current_span();
let return_value =
self.parse_expressions(&context.start_new_expression(), TempResult::No)?;
self.push_node_with_start_span(Node::Return(return_value), start_span)
}
Token::Throw => self.consume_throw_expression(),
Token::Debug => self.consume_debug_expression(),
Token::From | Token::Import => self.consume_import(context),
Token::Export => self.consume_export(context),
Token::Try => self.consume_try_expression(context),
Token::Let => self.consume_let_expression(context),
// Reserved keywords
Token::Await => self.consume_token_and_error(SyntaxError::ReservedKeyword),
Token::Const => self.consume_token_and_error(SyntaxError::ReservedKeyword),
// An error occurred in the lexer
Token::Error => self.consume_token_and_error(SyntaxError::LexerError),
_ => return Ok(None),
};
result.map(Some)
}
// Parses a function
//
// e.g.
// f = |x, y| x + y
// # ^ You are here
fn consume_function(&mut self, context: &ExpressionContext) -> Result<AstIndex> {
self.consume_token_with_context(context); // Token::Function
let span_start = self.current_span().start;
// Parse function's args
let mut arg_nodes = AstVec::new();
let mut arg_ids = AstVec::new();
let mut is_variadic = false;
let args_context = ExpressionContext::braced_items_continued();
while self.peek_token_with_context(&args_context).is_some() {
self.consume_until_token_with_context(&args_context);
match self.parse_id_or_wildcard(&args_context)? {
Some(IdOrWildcard::Id(constant_index)) => {
arg_ids.push(constant_index);
let arg_span = self.current_span();
let type_hint = self.parse_type_hint(&args_context)?;
arg_nodes.push(
self.push_node_with_span(Node::Id(constant_index, type_hint), arg_span)?,
);
if self.peek_token() == Some(Token::Ellipsis) {
if type_hint.is_some() {
return self.consume_token_and_error(SyntaxError::UnexpectedToken);
}
self.consume_token();
is_variadic = true;
break;
}
}
Some(IdOrWildcard::Wildcard(maybe_id)) => {
let arg_span = self.current_span();
let type_hint = self.parse_type_hint(&args_context)?;
arg_nodes.push(
self.push_node_with_span(Node::Wildcard(maybe_id, type_hint), arg_span)?,
);
}
None => match self.peek_token() {
Some(Token::Self_) => {
self.consume_token();
return self.error(SyntaxError::SelfArg);
}
Some(Token::RoundOpen) => {
self.consume_token();
let nested_span_start = self.current_span();
let tuple_args = self.parse_nested_function_args(&mut arg_ids)?;
self.expect_and_consume_token(
Token::RoundClose,
SyntaxError::ExpectedCloseParen.into(),
&args_context,
)?;
arg_nodes.push(self.push_node_with_start_span(
Node::Tuple(tuple_args),
nested_span_start,
)?);
}
_ => break,
},
}
if matches!(
self.peek_token_with_context(&args_context),
Some(PeekInfo {
token: Token::Comma,
..
})
) {
self.consume_token_with_context(&args_context);
} else {
break;
}
}
// Check for function args end
self.expect_and_consume_token(
Token::Function,
SyntaxError::ExpectedFunctionArgsEnd.into(),
&args_context,
)?;
// Check for output type hint
let output_type = if self.peek_next_token_on_same_line() == Some(Token::Arrow) {
self.consume_token_with_context(&args_context); // ->
let Some((output_type, _)) = self.parse_id(&args_context)? else {
return self.consume_token_and_error(SyntaxError::ExpectedType);
};
Some(self.push_node(Node::Type(output_type))?)
} else {
None
};
// Function body
let mut function_frame = Frame::default();
function_frame.ids_assigned_in_frame.extend(arg_ids.iter());
self.frame_stack.push(function_frame);
let body = if let Some(block) = self.parse_indented_block()? {
block
} else {
self.consume_until_next_token_on_same_line();
if let Some(body) = self.parse_line(&ExpressionContext::permissive())? {
body
} else {
return self.consume_token_and_error(ExpectedIndentation::FunctionBody);
}
};
let function_frame = self
.frame_stack
.pop()
.ok_or_else(|| self.make_error(InternalError::MissingFrame))?;
self.frame_mut()?
.add_nested_accessed_non_locals(&function_frame);
let local_count = function_frame.local_count();
let span_end = self.current_span().end;
self.ast.push(
Node::Function(Function {
args: arg_nodes,