Skip to main content

lisette_syntax/parse/
expressions.rs

1use ecow::EcoString;
2
3use super::strings::cook_string_contents;
4use super::{MAX_TUPLE_ARITY, ParamMode, ParseError, Parser};
5use crate::ast::{
6    Annotation, Attribute, BinaryOperator, Binding, Expression, FormatStringPart, ImportAlias,
7    Literal, SelectArm, SelectArmPattern, Span, StructFieldAssignment, StructSpread, UnaryOperator,
8    Visibility,
9};
10use crate::lex::TokenKind::{self, *};
11use crate::types::Type;
12
13#[derive(Clone, Copy)]
14enum GoMakeKind {
15    Slice,
16    Channel,
17    Map,
18}
19
20impl<'source> Parser<'source> {
21    pub fn parse_expression(&mut self) -> Expression {
22        if !self.enter_recursion() {
23            let span = self.span_from_token(self.current_token());
24            self.resync_on_error();
25            return Expression::Unit {
26                ty: Type::uninferred(),
27                span,
28            };
29        }
30        let result = self.pratt_parse(0);
31        self.leave_recursion();
32        result
33    }
34
35    pub fn parse_atomic_expression(&mut self) -> Expression {
36        if self.keyword_in_value_position() {
37            return self.recover_keyword_as_identifier();
38        }
39
40        match self.current_token().kind {
41            Integer | Imaginary | Boolean | Char | String | RawString | Float => {
42                self.parse_literal()
43            }
44            FormatStringStart => self.parse_format_string(),
45            LeftParen => self.parse_parenthesized_expression(),
46            LeftCurlyBrace => self.parse_block_expression(),
47            LeftSquareBracket => self.parse_slice_literal(),
48            Identifier => self.parse_identifier(),
49            Function if self.stream.peek_ahead(1).kind == LeftParen => {
50                self.parse_fn_as_lambda_recovery()
51            }
52            Function => self.parse_function(None, vec![], ParamMode::Strict),
53            Match => self.parse_match(),
54            If => self.parse_if(),
55            Pipe | PipeDouble => self.parse_lambda(),
56            Task => self.parse_task(),
57            Defer => self.parse_defer(),
58            Try => self.parse_try_block(),
59            Recover => self.parse_recover_block(),
60            Select => self.parse_select(),
61            Loop => self.parse_loop(),
62            Return => self.parse_return(false),
63            Break => self.parse_break(),
64            Continue => self.parse_continue(),
65            DotDot | DotDotEqual => self.parse_range(None, self.current_token()),
66
67            LeftAngleBracket
68                if self.stream.peek_ahead(1).kind == Minus
69                    && self.current_token().byte_offset + self.current_token().byte_length
70                        == self.stream.peek_ahead(1).byte_offset =>
71            {
72                let start = self.current_token();
73                let span = Span::new(self.file_id, start.byte_offset, start.byte_length + 1);
74                self.track_error_at(
75                    span,
76                    "invalid syntax for channel receive",
77                    "Use `select { let v = ch.receive() => ... }` to receive from a channel",
78                );
79                self.resync_on_error();
80                Expression::Unit {
81                    ty: Type::uninferred(),
82                    span,
83                }
84            }
85
86            Backtick => self.recover_unexpected_backtick(),
87
88            _ => self.unexpected_token("expr"),
89        }
90    }
91
92    pub fn parse_range(
93        &mut self,
94        start: Option<Box<Expression>>,
95        span_start: crate::lex::Token<'source>,
96    ) -> Expression {
97        if matches!(start.as_deref(), Some(Expression::Range { .. })) {
98            self.track_error("not allowed", "Chained range operators are not supported");
99        }
100
101        let inclusive = self.is(DotDotEqual);
102
103        self.next();
104
105        let has_end = !matches!(
106            self.current_token().kind,
107            RightCurlyBrace
108                | RightSquareBracket
109                | RightParen
110                | LeftCurlyBrace
111                | Semicolon
112                | Comma
113                | EOF
114        );
115
116        if inclusive && !has_end {
117            self.track_error(
118                "expected end value",
119                "Inclusive ranges require an end value.",
120            );
121        }
122
123        let end = if has_end {
124            Some(Box::new(self.parse_range_end()))
125        } else {
126            None
127        };
128
129        Expression::Range {
130            start,
131            end,
132            inclusive,
133            ty: Type::uninferred(),
134            span: self.span_from_tokens(span_start),
135        }
136    }
137
138    fn parse_literal(&mut self) -> Expression {
139        let start = self.current_token();
140
141        let literal = match self.current_token().kind {
142            Integer => {
143                let text = self.current_token().text;
144                let literal = self.parse_integer_text(text);
145                self.next();
146                literal
147            }
148            Float => {
149                let raw = self.current_token().text;
150                let cleaned = raw.replace('_', "");
151                let f: f64 = cleaned.parse().unwrap_or_else(|_| {
152                    self.track_error(
153                        format!("float literal '{}' is out of range", raw),
154                        "Value must be a valid 64-bit floating point number.",
155                    );
156                    0.0
157                });
158                let text = if raw.contains('e') || raw.contains('E') || raw.contains('_') {
159                    Some(raw.to_string())
160                } else {
161                    None
162                };
163                self.next();
164                Literal::Float { value: f, text }
165            }
166            Imaginary => {
167                let text = self.current_token().text;
168                let coef: f64 = text[..text.len() - 1]
169                    .replace('_', "")
170                    .parse()
171                    .unwrap_or_else(|_| {
172                        self.track_error(
173                            format!("imaginary literal '{}' is out of range", text),
174                            "Value must be a valid 64-bit floating point number.",
175                        );
176                        0.0
177                    });
178                self.next();
179                Literal::Imaginary(coef)
180            }
181            Boolean => {
182                let b = self.current_token().text == "true";
183                self.next();
184                Literal::Boolean(b)
185            }
186            String => {
187                let s = self.current_token().text;
188                self.next();
189                let s_stripped = if s.len() >= 2 && s.starts_with('"') && s.ends_with('"') {
190                    &s[1..s.len() - 1]
191                } else {
192                    debug_assert!(false, "lexer produced String token without quotes: {:?}", s);
193                    s
194                };
195                Literal::String {
196                    value: cook_string_contents(s_stripped),
197                    raw: false,
198                }
199            }
200            RawString => {
201                let s = self.current_token().text;
202                self.next();
203                let s_stripped = if s.len() >= 3 && s.starts_with("r\"") && s.ends_with('"') {
204                    &s[2..s.len() - 1]
205                } else if s.len() >= 2 && s.starts_with("r\"") {
206                    // unterminated raw string — strip prefix only
207                    &s[2..]
208                } else {
209                    debug_assert!(
210                        false,
211                        "lexer produced RawString token without prefix: {:?}",
212                        s
213                    );
214                    s
215                };
216                Literal::String {
217                    value: cook_string_contents(s_stripped),
218                    raw: true,
219                }
220            }
221            Char => {
222                let c = self.current_token().text;
223                self.next();
224                let c_stripped = if c.len() >= 2 && c.starts_with('\'') && c.ends_with('\'') {
225                    &c[1..c.len() - 1]
226                } else {
227                    debug_assert!(false, "lexer produced Char token without quotes: {:?}", c);
228                    c
229                };
230                Literal::Char(c_stripped.to_string())
231            }
232            _ => return self.unexpected_token("literal"),
233        };
234
235        Expression::Literal {
236            literal,
237            ty: Type::uninferred(),
238            span: self.span_from_tokens(start),
239        }
240    }
241
242    fn parse_slice_literal(&mut self) -> Expression {
243        let start = self.current_token();
244        let (expressions, _) =
245            self.collect_delimited_expressions(LeftSquareBracket, RightSquareBracket);
246
247        Expression::Literal {
248            literal: Literal::Slice(expressions),
249            ty: Type::uninferred(),
250            span: self.span_from_tokens(start),
251        }
252    }
253
254    fn parse_identifier(&mut self) -> Expression {
255        let start = self.current_token();
256        let text = self.current_token().text;
257
258        if text == "go" {
259            let next = self.stream.peek_ahead(1).kind;
260            if next == LeftCurlyBrace || next == Identifier {
261                self.track_error(
262                    "invalid syntax",
263                    "Use `task { ... }` or `task my_function()` to spawn a concurrent task.",
264                );
265            }
266        }
267
268        self.ensure(Identifier);
269
270        Expression::Identifier {
271            value: text.into(),
272            ty: Type::uninferred(),
273            span: self.span_from_tokens(start),
274            binding_id: None,
275            qualified: None,
276        }
277    }
278
279    pub fn parse_struct_call(&mut self, expression: Expression) -> Expression {
280        let name = self.make_expression_name(&expression);
281        let name_span = expression.get_span();
282        let start_offset = name_span.byte_offset; // Start from the name, not the brace
283
284        self.ensure(LeftCurlyBrace);
285
286        let mut field_assignments = vec![];
287        let mut spread = StructSpread::None;
288        let mut seen_fields: Vec<(EcoString, Span)> = vec![];
289
290        while self.is_not(RightCurlyBrace) {
291            if self.is(DotDot) {
292                if spread.is_some() {
293                    self.track_error(
294                        "spread must be last",
295                        "Move the `..spread` to the end of the struct.",
296                    );
297                    break;
298                }
299
300                let dotdot_token = self.current_token();
301                let dotdot_span = self.span_from_token(dotdot_token);
302                self.ensure(DotDot);
303
304                if self.is(RightCurlyBrace) || self.is(Comma) {
305                    spread = StructSpread::Autofill { span: dotdot_span };
306                } else {
307                    spread = StructSpread::From(Box::new(self.parse_expression()));
308                }
309
310                self.expect_comma_or(RightCurlyBrace);
311                continue;
312            }
313
314            if spread.is_some() {
315                self.track_error(
316                    "field after spread",
317                    "The `..spread` must be the last element in a struct expression. Move explicit fields before the spread.",
318                );
319                break;
320            }
321
322            let field_name_token = self.current_token();
323            let field_name_span = self.span_from_token(field_name_token);
324            let field_name = self.read_identifier();
325
326            if let Some((_, first_span)) = seen_fields.iter().find(|(n, _)| n == &field_name) {
327                self.error_duplicate_struct_field(&field_name, *first_span, field_name_span);
328            } else {
329                seen_fields.push((field_name.clone(), field_name_span));
330            }
331
332            let field_value = if self.advance_if(Colon) {
333                self.parse_expression()
334            } else {
335                Expression::Identifier {
336                    value: field_name.clone(),
337                    ty: Type::uninferred(),
338                    span: self.span_from_tokens(field_name_token),
339                    binding_id: None,
340                    qualified: None,
341                }
342            };
343
344            field_assignments.push(StructFieldAssignment {
345                name: field_name,
346                name_span: field_name_span,
347                value: Box::new(field_value),
348            });
349
350            self.expect_comma_or(RightCurlyBrace);
351        }
352
353        self.ensure(RightCurlyBrace);
354
355        Expression::StructCall {
356            ty: Type::uninferred(),
357            name,
358            field_assignments,
359            spread,
360            span: self.span_from_offset(start_offset),
361        }
362    }
363
364    pub fn parse_index_expression(&mut self, expression: Expression) -> Expression {
365        let start = self.current_token();
366
367        self.ensure(LeftSquareBracket);
368
369        let index_start = self.current_token();
370        let lower = if self.is(Colon) {
371            None
372        } else {
373            Some(Box::new(self.parse_expression()))
374        };
375
376        let mut from_colon_syntax = false;
377        let index = if self.is(Colon) {
378            from_colon_syntax = true;
379            self.next();
380            let upper = if self.is(RightSquareBracket) {
381                None
382            } else {
383                Some(Box::new(self.parse_expression()))
384            };
385            Expression::Range {
386                start: lower,
387                end: upper,
388                inclusive: false,
389                ty: Type::uninferred(),
390                span: self.span_from_tokens(index_start),
391            }
392        } else {
393            *lower.expect("non-colon index must have a lower expression")
394        };
395
396        self.ensure(RightSquareBracket);
397
398        Expression::IndexedAccess {
399            ty: Type::uninferred(),
400            expression: expression.into(),
401            index: index.into(),
402            span: self.span_from_tokens(start),
403            from_colon_syntax,
404        }
405    }
406
407    pub fn parse_function_call(
408        &mut self,
409        expression: Expression,
410        raw_type_args: Vec<Annotation>,
411    ) -> Expression {
412        let start_offset = expression.get_span().byte_offset;
413
414        if raw_type_args.is_empty()
415            && matches!(&expression, Expression::Identifier { value, qualified: None, .. } if value == "make")
416            && let Some(recovered) = self.try_go_make_shim(&expression)
417        {
418            return recovered;
419        }
420
421        let (args, spread) = self.collect_call_args();
422
423        Expression::Call {
424            ty: Type::uninferred(),
425            expression: expression.into(),
426            args,
427            spread: spread.into(),
428            raw_type_args,
429            resolved_type_args: Vec::new(),
430            span: self.span_from_offset(start_offset),
431            call_kind: None,
432        }
433    }
434
435    fn try_go_make_shim(&mut self, callee: &Expression) -> Option<Expression> {
436        let kind = self.classify_go_make()?;
437        let help = match (kind, self.scan_go_make_args()) {
438            (GoMakeKind::Slice, 0) => "Use `Slice.new<T>()` for an empty slice.",
439            (GoMakeKind::Slice, 1) => {
440                "Use `slices.Repeat([value], n)` after importing `go:slices`."
441            }
442            (GoMakeKind::Slice, _) => {
443                "Use `slices.Grow(Slice.new<T>(), capacity)` after importing `go:slices`."
444            }
445            (GoMakeKind::Channel, 0) => "Use `Channel.new<T>()`.",
446            (GoMakeKind::Channel, _) => "Use `Channel.buffered<T>(n)`.",
447            (GoMakeKind::Map, _) => "Use `Map.new<K, V>()`.",
448        };
449
450        let span = callee.get_span();
451        if !self.too_many_errors() {
452            self.errors.push(
453                ParseError::new("Syntax error", span, "Lisette has no `make` builtin")
454                    .with_parse_code("go_make_builtin")
455                    .with_help(help),
456            );
457        }
458
459        self.consume_balanced_parens();
460
461        Some(Expression::Unit {
462            ty: Type::uninferred(),
463            span: self.span_from_offset(span.byte_offset),
464        })
465    }
466
467    fn classify_go_make(&self) -> Option<GoMakeKind> {
468        let first = self.stream.peek_ahead(1);
469        let second = self.stream.peek_ahead(2);
470
471        if first.kind == LeftSquareBracket
472            && second.kind == RightSquareBracket
473            && self.stream.peek_ahead(3).kind == Identifier
474        {
475            return Some(GoMakeKind::Slice);
476        }
477
478        if first.kind == Identifier && first.text == "chan" && second.kind == Identifier {
479            return Some(GoMakeKind::Channel);
480        }
481
482        if first.kind == Identifier
483            && first.text == "map"
484            && second.kind == LeftSquareBracket
485            && self.go_map_type_has_value()
486        {
487            return Some(GoMakeKind::Map);
488        }
489
490        None
491    }
492
493    fn go_map_type_has_value(&self) -> bool {
494        let mut offset = 2;
495        let mut depth = 0usize;
496        loop {
497            match self.stream.peek_ahead(offset).kind {
498                EOF => return false,
499                LeftSquareBracket => depth += 1,
500                RightSquareBracket => {
501                    depth -= 1;
502                    if depth == 0 {
503                        return self.stream.peek_ahead(offset + 1).kind == Identifier;
504                    }
505                }
506                _ => {}
507            }
508            offset += 1;
509        }
510    }
511
512    fn scan_go_make_args(&self) -> usize {
513        let mut offset = 1;
514        let mut paren = 1usize;
515        let mut bracket = 0usize;
516        let mut commas = 0usize;
517        loop {
518            match self.stream.peek_ahead(offset).kind {
519                EOF => break,
520                LeftParen => paren += 1,
521                RightParen => {
522                    paren -= 1;
523                    if paren == 0 {
524                        break;
525                    }
526                }
527                LeftSquareBracket => bracket += 1,
528                RightSquareBracket => bracket = bracket.saturating_sub(1),
529                Comma if paren == 1 && bracket == 0 => commas += 1,
530                _ => {}
531            }
532            offset += 1;
533        }
534        commas
535    }
536
537    fn consume_balanced_parens(&mut self) {
538        let mut depth = 0usize;
539        while !self.at_eof() {
540            let kind = self.current_token().kind;
541            self.next();
542            match kind {
543                LeftParen => depth += 1,
544                RightParen => {
545                    depth = depth.saturating_sub(1);
546                    if depth == 0 {
547                        break;
548                    }
549                }
550                _ => {}
551            }
552        }
553    }
554
555    fn collect_call_args(&mut self) -> (Vec<Expression>, Option<Expression>) {
556        self.ensure(LeftParen);
557        let mut args = vec![];
558
559        while !self.at_eof() && !self.is(RightParen) {
560            if self.handle_fn_as_lambda_in_call(&mut args) {
561                continue;
562            }
563            if self.at_item_boundary()
564                && !matches!(self.stream.peek_ahead(1).kind, RightParen | Comma)
565            {
566                break;
567            }
568            let arg = self.parse_expression();
569            if self.is(Ellipsis) {
570                self.next();
571                self.expect_comma_or(RightParen);
572                if !self.is(RightParen) && !self.at_eof() {
573                    self.track_error(
574                        "argument after spread",
575                        "The `spread...` must be the last argument in the call.",
576                    );
577                    while !self.at_eof() && !self.is(RightParen) {
578                        self.next();
579                    }
580                }
581                self.advance_if(RightParen);
582                return (args, Some(arg));
583            }
584            args.push(arg);
585            self.expect_comma_or(RightParen);
586        }
587
588        self.advance_if(RightParen);
589        (args, None)
590    }
591
592    fn handle_fn_as_lambda_in_call(&mut self, args: &mut Vec<Expression>) -> bool {
593        if !(self.is(Function) && self.stream.peek_ahead(1).kind == LeftParen) {
594            return false;
595        }
596        let span = self.track_fn_as_lambda_error();
597        self.resync_on_error();
598        args.push(Expression::Unit {
599            ty: Type::uninferred(),
600            span,
601        });
602        true
603    }
604
605    fn parse_fn_as_lambda_recovery(&mut self) -> Expression {
606        let start = self.current_token();
607        self.track_fn_as_lambda_error();
608
609        self.ensure(Function);
610        let params = self.parse_function_params(ParamMode::Strict);
611        let return_annotation = self.parse_function_return_annotation();
612
613        let body = if self.is(LeftCurlyBrace) {
614            self.parse_block_expression()
615        } else {
616            Expression::NoOp
617        };
618
619        Expression::Lambda {
620            params,
621            return_annotation,
622            body: body.into(),
623            ty: Type::uninferred(),
624            span: self.span_from_tokens(start),
625        }
626    }
627
628    fn track_fn_as_lambda_error(&mut self) -> Span {
629        let start = self.current_token();
630        let span = Span::new(self.file_id, start.byte_offset, start.byte_length + 1);
631        let error = ParseError::new("Syntax error", span, "expected a lambda")
632            .with_parse_code("fn_as_lambda")
633            .with_help("Use a lambda instead: `|x| x * 2`");
634        self.errors.push(error);
635        span
636    }
637
638    pub fn parse_type_args(&mut self) -> Vec<Annotation> {
639        self.ensure(LeftAngleBracket);
640
641        let mut type_args = vec![];
642
643        loop {
644            if self.at_eof() {
645                break;
646            }
647
648            // A turbofish arg is a type or an integer size (the `N` in `Array.new<T, N>()`).
649            if self.at_size_position_value() {
650                type_args.push(self.parse_size_type_arg());
651            } else {
652                type_args.push(self.parse_annotation());
653            }
654
655            if self.is_right_angle_like() {
656                break;
657            }
658
659            self.ensure(Comma);
660        }
661
662        if !self.advance_if_right_angle() {
663            self.ensure(RightAngleBracket);
664        }
665
666        type_args
667    }
668
669    pub fn parse_binary_operator(&mut self) -> BinaryOperator {
670        let operator = match self.current_token().kind {
671            Plus => BinaryOperator::Addition,
672            Minus => BinaryOperator::Subtraction,
673            Star => BinaryOperator::Multiplication,
674            Slash => BinaryOperator::Division,
675            Ampersand => BinaryOperator::BitwiseAnd,
676            Pipe => BinaryOperator::BitwiseOr,
677            Caret => BinaryOperator::BitwiseXor,
678            AndNot => BinaryOperator::BitwiseAndNot,
679            ShiftLeft => BinaryOperator::ShiftLeft,
680            ShiftRight => BinaryOperator::ShiftRight,
681            LeftAngleBracket => BinaryOperator::LessThan,
682            LessThanOrEqual => BinaryOperator::LessThanOrEqual,
683            RightAngleBracket => BinaryOperator::GreaterThan,
684            GreaterThanOrEqual => BinaryOperator::GreaterThanOrEqual,
685            Percent => BinaryOperator::Remainder,
686            EqualDouble => BinaryOperator::Equal,
687            NotEqual => BinaryOperator::NotEqual,
688            AmpersandDouble => BinaryOperator::And,
689            PipeDouble => BinaryOperator::Or,
690            Pipeline => {
691                self.has_desugarables = true;
692                BinaryOperator::Pipeline
693            }
694
695            _ => {
696                self.track_error(format!(
697                    "expected binary operator, found {}",
698                    self.current_token().kind
699                ), "Binary operators: `+`, `-`, `*`, `/`, `%`, `&`, `|`, `^`, `&^`, `<<`, `>>`, `==`, `!=`, `<`, `>`, `<=`, `>=`, `&&`, `||`.");
700                BinaryOperator::Addition // meaningless fallback
701            }
702        };
703
704        self.next();
705
706        operator
707    }
708
709    fn parse_parenthesized_expression(&mut self) -> Expression {
710        let start = self.current_token();
711
712        let (expressions, has_trailing_comma) =
713            self.collect_delimited_expressions(LeftParen, RightParen);
714        let span = self.span_from_tokens(start);
715
716        match expressions.len() {
717            0 => Expression::Unit {
718                ty: Type::uninferred(),
719                span,
720            },
721            1 => {
722                if has_trailing_comma {
723                    self.error_tuple_arity(1, span);
724                }
725                let expression = expressions.into_iter().next().expect("len is 1");
726                Expression::Paren {
727                    ty: Type::uninferred(),
728                    expression: expression.into(),
729                    span,
730                }
731            }
732            n => {
733                if n > MAX_TUPLE_ARITY {
734                    self.error_tuple_arity(n, span);
735                }
736                Expression::Tuple {
737                    ty: Type::uninferred(),
738                    elements: expressions,
739                    span,
740                }
741            }
742        }
743    }
744
745    pub fn parse_try(&mut self, expression: Expression) -> Expression {
746        let start_offset = expression.get_span().byte_offset;
747
748        self.ensure(QuestionMark);
749
750        Expression::Propagate {
751            ty: Type::uninferred(),
752            expression: expression.into(),
753            span: self.span_from_offset(start_offset),
754        }
755    }
756
757    fn parse_lambda(&mut self) -> Expression {
758        let start = self.current_token();
759
760        let params = if self.is(Pipe) {
761            self.parse_lambda_params()
762        } else {
763            self.next();
764            vec![]
765        };
766
767        let has_return_type = self.is(Arrow);
768        let return_annotation = if has_return_type {
769            self.next();
770            self.parse_annotation()
771        } else {
772            Annotation::Unknown
773        };
774
775        if has_return_type && self.current_token().kind != LeftCurlyBrace {
776            self.track_error(
777                "not allowed",
778                "A lambda with a return type requires a block body",
779            );
780        }
781
782        let body = self.parse_expression();
783
784        Expression::Lambda {
785            params,
786            return_annotation,
787            body: body.into(),
788            ty: Type::uninferred(),
789            span: self.span_from_tokens(start),
790        }
791    }
792
793    pub fn parse_block_expression(&mut self) -> Expression {
794        let start = self.current_token();
795
796        self.ensure(LeftCurlyBrace);
797
798        if self.looks_like_map_literal() {
799            let key_span = self.span_from_token(self.current_token());
800            self.consume_to_matching_close_brace();
801            self.error_map_literal_not_supported(key_span);
802            return Expression::Block {
803                ty: Type::uninferred(),
804                items: vec![],
805                span: self.span_from_tokens(start),
806            };
807        }
808
809        if !self.enter_recursion() {
810            let span = self.span_from_token(self.current_token());
811            let mut brace_depth = 1u32;
812            while brace_depth > 0 && !self.at_eof() {
813                match self.current_token().kind {
814                    LeftCurlyBrace => brace_depth += 1,
815                    RightCurlyBrace => brace_depth -= 1,
816                    _ => {}
817                }
818                if brace_depth > 0 {
819                    self.next();
820                }
821            }
822            self.advance_if(RightCurlyBrace);
823            return Expression::Block {
824                ty: Type::uninferred(),
825                items: vec![],
826                span,
827            };
828        }
829
830        let mut items = vec![];
831
832        while self.is_not(RightCurlyBrace) && !self.too_many_errors() {
833            let position = self.position();
834            let item = self.parse_block_item();
835
836            self.advance_if(Semicolon);
837
838            items.push(item);
839            if self.position() == position {
840                self.next();
841            }
842        }
843
844        let span = self.close_brace_span(start, start);
845
846        self.leave_recursion();
847
848        Expression::Block {
849            ty: Type::uninferred(),
850            items,
851            span,
852        }
853    }
854
855    pub(crate) fn parse_function_params(&mut self, mode: ParamMode) -> Vec<Binding> {
856        self.ensure(LeftParen);
857
858        let mut params = vec![];
859
860        while self.is_not(RightParen) {
861            params.push(self.parse_binding_with_type(mode));
862            self.expect_comma_or(RightParen);
863        }
864
865        self.ensure(RightParen);
866
867        params
868    }
869
870    pub fn parse_lambda_params(&mut self) -> Vec<Binding> {
871        self.ensure(Pipe);
872
873        let mut params = vec![];
874
875        while self.is_not(Pipe) {
876            let is_mut = self.advance_if(Mut);
877            let mut binding = self.parse_binding();
878            binding.mutable = is_mut;
879            params.push(binding);
880            self.expect_comma_or(Pipe);
881        }
882
883        self.ensure(Pipe);
884
885        params
886    }
887
888    pub(crate) fn parse_function(
889        &mut self,
890        doc: Option<std::string::String>,
891        attributes: Vec<Attribute>,
892        param_mode: ParamMode,
893    ) -> Expression {
894        let start = self.current_token();
895
896        self.ensure(Function);
897
898        let name_token = self.current_token();
899        let name_span = Span::new(self.file_id, name_token.byte_offset, name_token.byte_length);
900
901        let name = self.read_identifier_sequence();
902
903        let name_span = Span::new(name_span.file_id, name_span.byte_offset, name.len() as u32);
904
905        let generics = self.parse_generics();
906        let params = self.parse_function_params(param_mode);
907        let return_annotation = self.parse_function_return_annotation();
908
909        let body = if self.is(LeftCurlyBrace) {
910            self.parse_block_expression()
911        } else {
912            Expression::NoOp
913        };
914
915        Expression::Function {
916            doc,
917            attributes,
918            name,
919            name_span,
920            generics,
921            params,
922            return_annotation,
923            return_type: Type::uninferred(),
924            visibility: Visibility::Private,
925            body: body.into(),
926            ty: Type::uninferred(),
927            span: self.span_from_tokens(start),
928        }
929    }
930
931    pub fn parse_field_access(&mut self, expression: Expression) -> Expression {
932        self.ensure(Dot);
933
934        let expression_start = expression.get_span().byte_offset;
935        let start = self.current_token();
936
937        if self.advance_if(Star) {
938            return Expression::Unary {
939                ty: Type::uninferred(),
940                operator: UnaryOperator::Deref,
941                expression: expression.into(),
942                span: self.span_from_tokens(start),
943            };
944        }
945
946        if self.is(Integer) {
947            let text = self.current_token().text;
948            let index: u32 = text.parse().unwrap_or_else(|_| {
949                self.track_error(
950                    format!("tuple index '{}' is too large", text),
951                    "Maximum index is `4294967295`.",
952                );
953                0
954            });
955
956            self.ensure(Integer);
957
958            return Expression::DotAccess {
959                ty: Type::uninferred(),
960                expression: expression.into(),
961                member: index.to_string().into(),
962                span: self.span_from_offset(expression_start),
963                dot_access_kind: None,
964                receiver_coercion: None,
965            };
966        }
967
968        let field = self.current_token().text;
969
970        self.ensure(Identifier);
971
972        Expression::DotAccess {
973            ty: Type::uninferred(),
974            expression: expression.into(),
975            member: field.into(),
976            span: self.span_from_offset(expression_start),
977            dot_access_kind: None,
978            receiver_coercion: None,
979        }
980    }
981
982    pub fn collect_delimited_expressions(
983        &mut self,
984        open: TokenKind,
985        close: TokenKind,
986    ) -> (Vec<Expression>, bool) {
987        self.ensure(open);
988
989        let mut expressions = vec![];
990        let mut has_trailing_comma = false;
991        loop {
992            if self.at_eof() || self.is(close) {
993                break;
994            }
995
996            if self.is(Function) && self.stream.peek_ahead(1).kind == LeftParen {
997                let span = self.track_fn_as_lambda_error();
998                self.resync_on_error();
999                expressions.push(Expression::Unit {
1000                    ty: Type::uninferred(),
1001                    span,
1002                });
1003                continue;
1004            }
1005
1006            if self.at_item_boundary() {
1007                let next = self.stream.peek_ahead(1).kind;
1008                if next != close && next != Comma {
1009                    break;
1010                }
1011            }
1012            expressions.push(self.parse_expression());
1013            has_trailing_comma = self.is(Comma);
1014            self.expect_comma_or(close);
1015        }
1016
1017        self.advance_if(close);
1018
1019        (expressions, has_trailing_comma)
1020    }
1021
1022    fn make_expression_name(&mut self, expression: &Expression) -> EcoString {
1023        let mut parts = Vec::new();
1024        let mut current = expression;
1025
1026        loop {
1027            match current {
1028                Expression::Identifier { value, .. } => {
1029                    parts.push(value.clone());
1030                    break;
1031                }
1032                Expression::DotAccess {
1033                    expression, member, ..
1034                } => {
1035                    parts.push(member.clone());
1036                    current = expression;
1037                }
1038                _ => {
1039                    self.track_error(
1040                        "unexpected expression",
1041                        "Expected an identifier or dotted path.",
1042                    );
1043                    return "_".into();
1044                }
1045            }
1046        }
1047
1048        parts.reverse();
1049        parts.join(".").into()
1050    }
1051
1052    pub fn parse_let(&mut self) -> Expression {
1053        let start = self.current_token();
1054
1055        self.ensure(Let);
1056
1057        let assert = self.is(Assert);
1058        if assert {
1059            self.next(); // consume `assert`
1060        }
1061
1062        let (mutable, mut_span) = if self.is(Mut) {
1063            let mut_token = self.current_token();
1064            let span = Span::new(self.file_id, mut_token.byte_offset, mut_token.byte_length);
1065            self.next(); // consume `mut`
1066            (true, Some(span))
1067        } else {
1068            (false, None)
1069        };
1070
1071        if assert && let Some(span) = mut_span {
1072            self.track_error_at(
1073                span,
1074                "`let assert` cannot be combined with `mut`",
1075                "`let assert` binds a refutable pattern. Remove `mut`",
1076            );
1077        }
1078
1079        let binding = self.parse_binding_allowing_or();
1080
1081        if !self.is(Equal)
1082            && let Some(Annotation::Constructor { span, .. }) = binding.annotation.as_ref()
1083        {
1084            self.error_missing_initializer(*span);
1085            let stub_span = self.span_from_tokens(start);
1086            return Expression::Let {
1087                binding: Box::new(binding),
1088                value: Box::new(Expression::Block {
1089                    ty: Type::uninferred(),
1090                    items: vec![],
1091                    span: stub_span,
1092                }),
1093                mutable,
1094                mut_span,
1095                else_block: None,
1096                else_span: None,
1097                assert,
1098                typed_pattern: None,
1099                ty: Type::uninferred(),
1100                span: stub_span,
1101            };
1102        }
1103
1104        self.ensure(Equal);
1105
1106        let expression = self.parse_expression();
1107
1108        let (else_block, else_span) = if self.is(Else) {
1109            let else_token = self.current_token();
1110            let span = Span::new(self.file_id, else_token.byte_offset, else_token.byte_length);
1111            self.next(); // consume `else`
1112            (Some(Box::new(self.parse_block_expression())), Some(span))
1113        } else {
1114            (None, None)
1115        };
1116
1117        if assert && else_block.is_some() {
1118            self.track_error_at(
1119                else_span.expect("else_block implies else_span"),
1120                "`let assert` cannot have an `else` block",
1121                "`let assert` already fails the test on mismatch. Remove the `else`",
1122            );
1123        }
1124
1125        Expression::Let {
1126            binding: Box::new(binding),
1127            value: expression.into(),
1128            mutable,
1129            mut_span,
1130            else_block,
1131            else_span,
1132            assert,
1133            typed_pattern: None,
1134            ty: Type::uninferred(),
1135            span: self.span_from_tokens(start),
1136        }
1137    }
1138
1139    pub fn parse_import(&mut self) -> Expression {
1140        let start = self.current_token();
1141
1142        self.ensure(Import);
1143
1144        let alias = if self.current_token().kind == Identifier {
1145            let alias_token = self.current_token();
1146            let alias_text = alias_token.text;
1147            let alias_span = Span::new(
1148                self.file_id,
1149                alias_token.byte_offset,
1150                alias_token.byte_length,
1151            );
1152
1153            if alias_text == "_" {
1154                self.next();
1155                Some(ImportAlias::Blank(alias_span))
1156            } else if self.stream.peek_ahead(1).kind == String {
1157                self.next();
1158                Some(ImportAlias::Named(alias_text.into(), alias_span))
1159            } else {
1160                None
1161            }
1162        } else {
1163            None
1164        };
1165
1166        let name_token = self.current_token();
1167
1168        if name_token.kind != String {
1169            let (label, help) = if name_token.kind == Identifier
1170                && self.stream.peek_ahead(1).kind == Colon
1171            {
1172                let module_name = name_token.text;
1173                (
1174                    "expected double quotes".to_string(),
1175                    format!(
1176                        "Wrap the import path in double quotes: `import \"{0}:...\"`",
1177                        module_name
1178                    ),
1179                )
1180            } else if name_token.kind == Identifier {
1181                let module_name = name_token.text;
1182                (
1183                    "expected double quotes".to_string(),
1184                    format!(
1185                        "Wrap the import path in double quotes: `import \"{}\"`",
1186                        module_name
1187                    ),
1188                )
1189            } else {
1190                (
1191                    "expected module path".to_string(),
1192                    "Wrap the import path in double quotes, e.g. `import \"go:os\"`".to_string(),
1193                )
1194            };
1195
1196            self.track_error(label, help);
1197            self.resync_on_error();
1198            return Expression::Unit {
1199                ty: Type::uninferred(),
1200                span: self.span_from_tokens(start),
1201            };
1202        }
1203
1204        self.next();
1205
1206        let raw = name_token.text;
1207        let unquoted: &str = if raw.len() >= 2 && raw.starts_with('"') && raw.ends_with('"') {
1208            &raw[1..raw.len() - 1]
1209        } else {
1210            debug_assert!(
1211                false,
1212                "lexer produced String token without quotes: {:?}",
1213                raw
1214            );
1215            raw
1216        };
1217
1218        if alias.is_none() && self.is(As) && self.stream.peek_ahead(1).kind == Identifier {
1219            let as_token = self.current_token();
1220            let alias_identifier = self.stream.peek_ahead(1);
1221            self.next();
1222            self.next();
1223            self.error_import_alias_after_path(
1224                self.span_from_tokens(as_token),
1225                alias_identifier.text,
1226                unquoted,
1227            );
1228        }
1229
1230        let name: EcoString = unquoted.into();
1231        let name_span = Span::new(self.file_id, name_token.byte_offset, name_token.byte_length);
1232
1233        Expression::ModuleImport {
1234            name,
1235            name_span,
1236            alias,
1237            span: self.span_from_tokens(start),
1238        }
1239    }
1240
1241    pub fn parse_assignment(&mut self) -> Expression {
1242        let start = self.current_token();
1243
1244        let lhs = self.parse_expression();
1245
1246        let compound_operator = match self.current_token().kind {
1247            PlusEqual => Some(BinaryOperator::Addition),
1248            MinusEqual => Some(BinaryOperator::Subtraction),
1249            StarEqual => Some(BinaryOperator::Multiplication),
1250            SlashEqual => Some(BinaryOperator::Division),
1251            PercentEqual => Some(BinaryOperator::Remainder),
1252            AmpersandEqual => Some(BinaryOperator::BitwiseAnd),
1253            PipeEqual => Some(BinaryOperator::BitwiseOr),
1254            CaretEqual => Some(BinaryOperator::BitwiseXor),
1255            AndNotEqual => Some(BinaryOperator::BitwiseAndNot),
1256            ShiftLeftEqual => Some(BinaryOperator::ShiftLeft),
1257            ShiftRightEqual => Some(BinaryOperator::ShiftRight),
1258            _ => None,
1259        };
1260
1261        if let Some(operator) = compound_operator {
1262            if !self.is_valid_assignment_target(&lhs) {
1263                self.track_error(
1264                    "invalid assignment target",
1265                    "Only variables, fields, and indices can be assigned to.",
1266                );
1267                self.next();
1268                let _rhs = self.parse_expression();
1269                return lhs;
1270            }
1271            self.next();
1272            let rhs = self.parse_expression();
1273            return Expression::Assignment {
1274                target: lhs.into(),
1275                value: rhs.into(),
1276                compound_operator: Some(operator),
1277                span: self.span_from_tokens(start),
1278            };
1279        }
1280
1281        if self.current_token().kind == Colon && self.stream.peek_ahead(1).kind == Equal {
1282            let span = Span::new(self.file_id, self.current_token().byte_offset, 2);
1283            self.track_error_at(
1284                span,
1285                "Go-style short declaration",
1286                "Use `let x = ...` instead of `:=` for variable declarations",
1287            );
1288            self.next();
1289            self.next();
1290            let _ = self.parse_expression();
1291            return lhs;
1292        }
1293
1294        if !self.is(Equal) {
1295            return lhs;
1296        }
1297
1298        if !self.is_valid_assignment_target(&lhs) {
1299            self.track_error(
1300                "invalid assignment target",
1301                "Only variables, fields, and indices can be assigned to.",
1302            );
1303        }
1304
1305        self.ensure(Equal);
1306
1307        Expression::Assignment {
1308            target: lhs.into(),
1309            value: self.parse_expression().into(),
1310            compound_operator: None,
1311            span: self.span_from_tokens(start),
1312        }
1313    }
1314
1315    pub(super) fn is_valid_assignment_target(&self, expression: &Expression) -> bool {
1316        use Expression::*;
1317
1318        matches!(
1319            expression,
1320            Identifier { .. }
1321                | DotAccess { .. }
1322                | IndexedAccess { .. }
1323                | Unary {
1324                    operator: UnaryOperator::Deref,
1325                    ..
1326                }
1327        )
1328    }
1329
1330    fn parse_format_string(&mut self) -> Expression {
1331        let start = self.current_token();
1332        self.ensure(FormatStringStart);
1333
1334        let mut parts = Vec::new();
1335
1336        loop {
1337            if self.at_eof() || self.at_item_boundary() {
1338                break;
1339            }
1340            match self.current_token().kind {
1341                FormatStringText => {
1342                    let text = self.current_token().text;
1343                    self.next();
1344                    parts.push(FormatStringPart::Text(cook_string_contents(text)));
1345                }
1346                FormatStringInterpolationStart => {
1347                    self.ensure(FormatStringInterpolationStart);
1348                    let expression = self.parse_expression();
1349                    parts.push(FormatStringPart::Expression(Box::new(expression)));
1350                    if self.is(Colon) {
1351                        let start_offset = self.current_token().byte_offset;
1352                        self.next();
1353                        while !self.at_eof()
1354                            && !self.is(FormatStringInterpolationEnd)
1355                            && !self.is(FormatStringEnd)
1356                            && !self.at_item_boundary()
1357                        {
1358                            self.next();
1359                        }
1360                        let span = self.span_from_offset(start_offset);
1361                        let error = ParseError::new(
1362                            "Format specifiers not supported",
1363                            span,
1364                            "not supported in format strings",
1365                        )
1366                        .with_parse_code("format_specifier")
1367                        .with_help(
1368                            "Use `fmt.Sprintf` for formatted output, e.g. `fmt.Sprintf(\"%02x\", n)`",
1369                        );
1370                        self.errors.push(error);
1371                    }
1372                    self.advance_if(FormatStringInterpolationEnd);
1373                }
1374                FormatStringEnd => {
1375                    self.ensure(FormatStringEnd);
1376                    break;
1377                }
1378                _ => break,
1379            }
1380        }
1381
1382        Expression::Literal {
1383            literal: Literal::FormatString(parts),
1384            ty: Type::uninferred(),
1385            span: self.span_from_tokens(start),
1386        }
1387    }
1388
1389    pub fn parse_task(&mut self) -> Expression {
1390        let start = self.current_token();
1391
1392        self.ensure(Task);
1393
1394        let expression = if self.is(LeftCurlyBrace) {
1395            self.parse_block_expression()
1396        } else {
1397            self.parse_expression()
1398        };
1399
1400        if !matches!(
1401            expression,
1402            Expression::Call { .. } | Expression::Block { .. }
1403        ) {
1404            let span = expression.get_span();
1405            let error = ParseError::new("Invalid `task`", span, "expected `()`")
1406                .with_parse_code("task_missing_parens")
1407                .with_help("Add parens to call the function");
1408
1409            self.errors.push(error);
1410        }
1411
1412        Expression::Task {
1413            expression: Box::new(expression),
1414            ty: Type::uninferred(),
1415            span: self.span_from_tokens(start),
1416        }
1417    }
1418
1419    pub fn parse_defer(&mut self) -> Expression {
1420        let start = self.current_token();
1421
1422        self.ensure(Defer);
1423
1424        let expression = if self.is(LeftCurlyBrace) {
1425            self.parse_block_expression()
1426        } else {
1427            self.parse_expression()
1428        };
1429
1430        if !matches!(
1431            expression,
1432            Expression::Call { .. } | Expression::Block { .. }
1433        ) {
1434            let span = expression.get_span();
1435            let error = ParseError::new("Invalid `defer`", span, "expected `()`")
1436                .with_parse_code("defer_missing_parens")
1437                .with_help("Add parens to call the function");
1438
1439            self.errors.push(error);
1440        }
1441
1442        Expression::Defer {
1443            expression: Box::new(expression),
1444            ty: Type::uninferred(),
1445            span: self.span_from_tokens(start),
1446        }
1447    }
1448
1449    pub fn parse_try_block(&mut self) -> Expression {
1450        let start = self.current_token();
1451        let try_keyword_span = Span::new(self.file_id, start.byte_offset, start.byte_length);
1452
1453        self.ensure(Try);
1454
1455        if !self.is(LeftCurlyBrace) {
1456            let span = self.span_from_tokens(start);
1457            let error = ParseError::new("Invalid `try`", span, "requires a block")
1458                .with_parse_code("syntax_error")
1459                .with_help("Use `try { expression }` instead of `try expression`");
1460            self.errors.push(error);
1461            let expression = self.parse_expression();
1462            return Expression::TryBlock {
1463                items: vec![expression],
1464                ty: Type::uninferred(),
1465                try_keyword_span,
1466                span: self.span_from_tokens(start),
1467            };
1468        }
1469
1470        let brace_token = self.current_token();
1471        self.ensure(LeftCurlyBrace);
1472
1473        if !self.enter_recursion() {
1474            let span = self.span_from_token(self.current_token());
1475            let mut brace_depth = 1u32;
1476            while brace_depth > 0 && !self.at_eof() {
1477                match self.current_token().kind {
1478                    LeftCurlyBrace => brace_depth += 1,
1479                    RightCurlyBrace => brace_depth -= 1,
1480                    _ => {}
1481                }
1482                if brace_depth > 0 {
1483                    self.next();
1484                }
1485            }
1486            self.advance_if(RightCurlyBrace);
1487            return Expression::TryBlock {
1488                items: vec![],
1489                ty: Type::uninferred(),
1490                try_keyword_span,
1491                span,
1492            };
1493        }
1494
1495        let mut items = vec![];
1496
1497        while self.is_not(RightCurlyBrace) && !self.too_many_errors() {
1498            let position = self.position();
1499            let item = self.parse_block_item();
1500
1501            self.advance_if(Semicolon);
1502
1503            items.push(item);
1504            if self.position() == position {
1505                self.next();
1506            }
1507        }
1508
1509        let span = self.close_brace_span(start, brace_token);
1510
1511        self.leave_recursion();
1512
1513        Expression::TryBlock {
1514            items,
1515            ty: Type::uninferred(),
1516            try_keyword_span,
1517            span,
1518        }
1519    }
1520
1521    pub fn parse_recover_block(&mut self) -> Expression {
1522        let start = self.current_token();
1523        let recover_keyword_span = Span::new(self.file_id, start.byte_offset, start.byte_length);
1524
1525        self.ensure(Recover);
1526
1527        if !self.is(LeftCurlyBrace) {
1528            let span = self.span_from_tokens(start);
1529            let error = ParseError::new("Invalid `recover`", span, "requires a block")
1530                .with_parse_code("syntax_error")
1531                .with_help("Use `recover { expression }` instead of `recover expression`");
1532            self.errors.push(error);
1533            let expression = self.parse_expression();
1534            return Expression::RecoverBlock {
1535                items: vec![expression],
1536                ty: Type::uninferred(),
1537                recover_keyword_span,
1538                span: self.span_from_tokens(start),
1539            };
1540        }
1541
1542        let brace_token = self.current_token();
1543        self.ensure(LeftCurlyBrace);
1544
1545        if !self.enter_recursion() {
1546            let span = self.span_from_token(self.current_token());
1547            let mut brace_depth = 1u32;
1548            while brace_depth > 0 && !self.at_eof() {
1549                match self.current_token().kind {
1550                    LeftCurlyBrace => brace_depth += 1,
1551                    RightCurlyBrace => brace_depth -= 1,
1552                    _ => {}
1553                }
1554                if brace_depth > 0 {
1555                    self.next();
1556                }
1557            }
1558            self.advance_if(RightCurlyBrace);
1559            return Expression::RecoverBlock {
1560                items: vec![],
1561                ty: Type::uninferred(),
1562                recover_keyword_span,
1563                span,
1564            };
1565        }
1566
1567        let mut items = vec![];
1568
1569        while self.is_not(RightCurlyBrace) && !self.too_many_errors() {
1570            let position = self.position();
1571            let item = self.parse_block_item();
1572
1573            self.advance_if(Semicolon);
1574
1575            items.push(item);
1576            if self.position() == position {
1577                self.next();
1578            }
1579        }
1580
1581        let span = self.close_brace_span(start, brace_token);
1582
1583        self.leave_recursion();
1584
1585        Expression::RecoverBlock {
1586            items,
1587            ty: Type::uninferred(),
1588            recover_keyword_span,
1589            span,
1590        }
1591    }
1592
1593    pub fn parse_select(&mut self) -> Expression {
1594        let start = self.current_token();
1595
1596        self.ensure(Select);
1597        self.ensure(LeftCurlyBrace);
1598
1599        let mut arms = Vec::new();
1600
1601        while self.is_not(RightCurlyBrace) {
1602            let arm = self.parse_select_arm();
1603            arms.push(arm);
1604
1605            if self.is(RightCurlyBrace) {
1606                break;
1607            }
1608
1609            self.ensure(Comma);
1610        }
1611
1612        self.ensure(RightCurlyBrace);
1613
1614        Expression::Select {
1615            arms,
1616            ty: Type::uninferred(),
1617            span: self.span_from_tokens(start),
1618        }
1619    }
1620
1621    fn parse_select_arm(&mut self) -> SelectArm {
1622        match self.current_token().kind {
1623            Let => {
1624                self.ensure(Let);
1625                let binding = self.parse_pattern();
1626                self.ensure(Equal);
1627                let receive_expression = Box::new(self.parse_expression());
1628                self.ensure(ArrowDouble);
1629                let body = Box::new(self.parse_expression());
1630                SelectArm {
1631                    pattern: SelectArmPattern::Receive {
1632                        binding: Box::new(binding),
1633                        typed_pattern: None,
1634                        receive_expression,
1635                        body,
1636                    },
1637                }
1638            }
1639            Match => {
1640                let match_expression = self.parse_match();
1641                if let Expression::Match { subject, arms, .. } = match_expression {
1642                    SelectArm {
1643                        pattern: SelectArmPattern::MatchReceive {
1644                            receive_expression: subject,
1645                            arms,
1646                        },
1647                    }
1648                } else {
1649                    self.ensure(ArrowDouble);
1650                    let body = Box::new(self.parse_expression());
1651                    SelectArm {
1652                        pattern: SelectArmPattern::Send {
1653                            send_expression: Box::new(match_expression),
1654                            body,
1655                        },
1656                    }
1657                }
1658            }
1659            Identifier if self.current_token().text == "_" => {
1660                self.next();
1661                self.ensure(ArrowDouble);
1662                let body = Box::new(self.parse_expression());
1663                SelectArm {
1664                    pattern: SelectArmPattern::WildCard { body },
1665                }
1666            }
1667            _ => {
1668                let send_expression = Box::new(self.parse_expression());
1669                self.ensure(ArrowDouble);
1670                let body = Box::new(self.parse_expression());
1671                SelectArm {
1672                    pattern: SelectArmPattern::Send {
1673                        send_expression,
1674                        body,
1675                    },
1676                }
1677            }
1678        }
1679    }
1680
1681    pub fn with_control_flow_header<F, R>(&mut self, f: F) -> R
1682    where
1683        F: FnOnce(&mut Self) -> R,
1684    {
1685        let old = self.in_control_flow_header;
1686        self.in_control_flow_header = true;
1687        let result = f(self);
1688        self.in_control_flow_header = old;
1689        result
1690    }
1691
1692    fn keyword_in_value_position(&self) -> bool {
1693        if !self.current_token().kind.is_keyword() {
1694            return false;
1695        }
1696
1697        match self.current_token().kind {
1698            Return | Break | Continue => false,
1699
1700            Match | If | Task | Defer | Try | Recover | Select | Loop | Function => matches!(
1701                self.stream.peek_ahead(1).kind,
1702                RightParen
1703                    | Comma
1704                    | Dot
1705                    | Semicolon
1706                    | RightCurlyBrace
1707                    | RightSquareBracket
1708                    | ArrowDouble
1709                    | QuestionMark
1710                    | EOF
1711                    | Plus
1712                    | Star
1713                    | Slash
1714                    | Percent
1715                    | EqualDouble
1716                    | NotEqual
1717                    | LeftAngleBracket
1718                    | RightAngleBracket
1719                    | LessThanOrEqual
1720                    | GreaterThanOrEqual
1721                    | AmpersandDouble
1722                    | Ampersand
1723                    | Pipe
1724                    | Caret
1725                    | AndNot
1726                    | ShiftLeft
1727                    | ShiftRight
1728                    | Pipeline
1729                    | Equal
1730                    | PlusEqual
1731                    | MinusEqual
1732                    | StarEqual
1733                    | SlashEqual
1734                    | PercentEqual
1735                    | AmpersandEqual
1736                    | PipeEqual
1737                    | CaretEqual
1738                    | AndNotEqual
1739                    | ShiftLeftEqual
1740                    | ShiftRightEqual
1741                    | DotDot
1742                    | DotDotEqual
1743                    | As
1744            ),
1745
1746            _ => true,
1747        }
1748    }
1749
1750    fn recover_keyword_as_identifier(&mut self) -> Expression {
1751        let token = self.current_token();
1752        let keyword = token.text.to_string();
1753        let span = self.span_from_token(token);
1754        let error = if token.kind == Var {
1755            ParseError::new("Syntax error", span, "expected `let`")
1756                .with_parse_code("expected_let")
1757                .with_help("Use `let` to declare a variable: `let x = 0`")
1758        } else {
1759            ParseError::new("Reserved keyword", span, "reserved keyword")
1760                .with_parse_code("keyword_as_identifier")
1761                .with_help(format!("Rename `{}`", keyword))
1762        };
1763        self.errors.push(error);
1764        self.next();
1765        Expression::Identifier {
1766            value: keyword.into(),
1767            ty: Type::uninferred(),
1768            span,
1769            binding_id: None,
1770            qualified: None,
1771        }
1772    }
1773
1774    fn looks_like_map_literal(&self) -> bool {
1775        let first = self.current_token().kind;
1776        let second = self.stream.peek_ahead(1).kind;
1777        matches!(first, String | RawString | Integer | Float) && second == Colon
1778    }
1779
1780    fn consume_to_matching_close_brace(&mut self) {
1781        let mut brace_depth = 1u32;
1782        while brace_depth > 0 && !self.at_eof() {
1783            match self.current_token().kind {
1784                LeftCurlyBrace => brace_depth += 1,
1785                RightCurlyBrace => brace_depth -= 1,
1786                _ => {}
1787            }
1788            if brace_depth > 0 {
1789                self.next();
1790            }
1791        }
1792        self.advance_if(RightCurlyBrace);
1793    }
1794
1795    fn recover_unexpected_backtick(&mut self) -> Expression {
1796        let token = self.current_token();
1797        let token_span = self.span_from_token(token);
1798        let opening_span = Span::new(self.file_id, token.byte_offset, 1);
1799        let error = ParseError::new("Unexpected backtick", opening_span, "not allowed here")
1800            .with_parse_code("unexpected_backtick")
1801            .with_help(
1802                "Use a regular string `\"...\"` or a raw string `r\"...\"` for single- or multi-line strings. Backticks in Lisette are reserved for struct-tag attributes.",
1803            );
1804        self.errors.push(error);
1805        self.next();
1806        Expression::Literal {
1807            literal: Literal::String {
1808                value: std::string::String::new(),
1809                raw: true,
1810            },
1811            ty: Type::uninferred(),
1812            span: token_span,
1813        }
1814    }
1815}
1816
1817#[cfg(test)]
1818mod tests {
1819    use crate::ast::{Annotation, BinaryOperator, Expression};
1820    use crate::build_ast;
1821
1822    fn count_nodes(expression: &Expression) -> usize {
1823        1 + expression.children().iter().map(count_nodes).sum::<usize>()
1824    }
1825
1826    fn first_assignment(expression: &Expression) -> Option<&Expression> {
1827        if matches!(expression, Expression::Assignment { .. }) {
1828            return Some(expression);
1829        }
1830        expression.children().iter().find_map(first_assignment)
1831    }
1832
1833    #[test]
1834    fn compound_assignment_stores_only_the_rhs() {
1835        let result = build_ast("fn f() {\n let mut x = 0\n x += 5\n}", 0);
1836        assert!(result.errors.is_empty(), "{:?}", result.errors);
1837
1838        let assignment = result
1839            .ast
1840            .iter()
1841            .find_map(first_assignment)
1842            .expect("an assignment");
1843        let Expression::Assignment {
1844            value,
1845            compound_operator,
1846            ..
1847        } = assignment
1848        else {
1849            unreachable!()
1850        };
1851
1852        assert_eq!(*compound_operator, Some(BinaryOperator::Addition));
1853        assert!(
1854            matches!(value.as_ref(), Expression::Literal { .. }),
1855            "value should hold only the rhs, not a duplicated `x + 5`: {value:?}"
1856        );
1857    }
1858
1859    #[test]
1860    fn function_type_annotation_captures_per_param_mutability() {
1861        let result = build_ast("fn run(action: fn(mut Bar, Baz) -> ()) {}", 0);
1862        assert!(result.errors.is_empty(), "{:?}", result.errors);
1863
1864        let Some(Expression::Function { params, .. }) = result
1865            .ast
1866            .iter()
1867            .find(|item| matches!(item, Expression::Function { .. }))
1868        else {
1869            unreachable!("expected a top-level function")
1870        };
1871        let Some(Annotation::Function {
1872            param_mutability, ..
1873        }) = &params[0].annotation
1874        else {
1875            panic!(
1876                "expected a function-type annotation, got {:?}",
1877                params[0].annotation
1878            )
1879        };
1880
1881        assert_eq!(param_mutability, &vec![true, false]);
1882    }
1883
1884    #[test]
1885    fn lambda_parameter_can_be_mut() {
1886        let result = build_ast("fn f() {\n  let g = |mut x: int| x\n  let _ = g\n}", 0);
1887        assert!(result.errors.is_empty(), "{:?}", result.errors);
1888
1889        fn find_lambda(expression: &Expression) -> Option<&Expression> {
1890            if matches!(expression, Expression::Lambda { .. }) {
1891                return Some(expression);
1892            }
1893            expression
1894                .children()
1895                .iter()
1896                .find_map(|child| find_lambda(child))
1897        }
1898
1899        let Some(Expression::Lambda { params, .. }) = result.ast.iter().find_map(find_lambda)
1900        else {
1901            unreachable!("expected a lambda")
1902        };
1903
1904        assert_eq!(params.len(), 1);
1905        assert!(
1906            params[0].mutable,
1907            "`mut x` lambda parameter should be mutable"
1908        );
1909    }
1910
1911    #[test]
1912    fn nested_compound_assignments_stay_linear() {
1913        let depth = 14;
1914        let source = format!(
1915            "fn f() {{ {}x{} }}",
1916            "{".repeat(depth),
1917            "}.f += 1".repeat(depth),
1918        );
1919        let result = build_ast(&source, 0);
1920        assert!(result.errors.is_empty(), "{:?}", result.errors);
1921
1922        let nodes: usize = result.ast.iter().map(count_nodes).sum();
1923        assert!(
1924            nodes < 20 * depth,
1925            "nested compound assignments grew super-linearly: {nodes} nodes at depth {depth}",
1926        );
1927    }
1928}