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) => "Use `Slice.make<T>(n)` for a zero-filled slice.",
440            (GoMakeKind::Slice, _) => {
441                "For `make([]T, 0, c)` use `Slice.new<T>().reserve(c)`. For a nonzero length, use `Slice.make<T>(n)` and `reserve` the extra capacity."
442            }
443            (GoMakeKind::Channel, 0) => "Use `Channel.new<T>()`.",
444            (GoMakeKind::Channel, _) => "Use `Channel.buffered<T>(n)`.",
445            (GoMakeKind::Map, _) => "Use `Map.new<K, V>()`.",
446        };
447
448        let span = callee.get_span();
449        if !self.too_many_errors() {
450            self.errors.push(
451                ParseError::new("Syntax error", span, "Lisette has no `make` builtin")
452                    .with_parse_code("go_make_builtin")
453                    .with_help(help),
454            );
455        }
456
457        self.consume_balanced_parens();
458
459        Some(Expression::Unit {
460            ty: Type::uninferred(),
461            span: self.span_from_offset(span.byte_offset),
462        })
463    }
464
465    fn classify_go_make(&self) -> Option<GoMakeKind> {
466        let first = self.stream.peek_ahead(1);
467        let second = self.stream.peek_ahead(2);
468
469        if first.kind == LeftSquareBracket
470            && second.kind == RightSquareBracket
471            && self.stream.peek_ahead(3).kind == Identifier
472        {
473            return Some(GoMakeKind::Slice);
474        }
475
476        if first.kind == Identifier && first.text == "chan" && second.kind == Identifier {
477            return Some(GoMakeKind::Channel);
478        }
479
480        if first.kind == Identifier
481            && first.text == "map"
482            && second.kind == LeftSquareBracket
483            && self.go_map_type_has_value()
484        {
485            return Some(GoMakeKind::Map);
486        }
487
488        None
489    }
490
491    fn go_map_type_has_value(&self) -> bool {
492        let mut offset = 2;
493        let mut depth = 0usize;
494        loop {
495            match self.stream.peek_ahead(offset).kind {
496                EOF => return false,
497                LeftSquareBracket => depth += 1,
498                RightSquareBracket => {
499                    depth -= 1;
500                    if depth == 0 {
501                        return self.stream.peek_ahead(offset + 1).kind == Identifier;
502                    }
503                }
504                _ => {}
505            }
506            offset += 1;
507        }
508    }
509
510    fn scan_go_make_args(&self) -> usize {
511        let mut offset = 1;
512        let mut paren = 1usize;
513        let mut bracket = 0usize;
514        let mut commas = 0usize;
515        loop {
516            match self.stream.peek_ahead(offset).kind {
517                EOF => break,
518                LeftParen => paren += 1,
519                RightParen => {
520                    paren -= 1;
521                    if paren == 0 {
522                        break;
523                    }
524                }
525                LeftSquareBracket => bracket += 1,
526                RightSquareBracket => bracket = bracket.saturating_sub(1),
527                Comma if paren == 1 && bracket == 0 => commas += 1,
528                _ => {}
529            }
530            offset += 1;
531        }
532        commas
533    }
534
535    fn consume_balanced_parens(&mut self) {
536        let mut depth = 0usize;
537        while !self.at_eof() {
538            let kind = self.current_token().kind;
539            self.next();
540            match kind {
541                LeftParen => depth += 1,
542                RightParen => {
543                    depth = depth.saturating_sub(1);
544                    if depth == 0 {
545                        break;
546                    }
547                }
548                _ => {}
549            }
550        }
551    }
552
553    fn collect_call_args(&mut self) -> (Vec<Expression>, Option<Expression>) {
554        self.ensure(LeftParen);
555        let mut args = vec![];
556
557        while !self.at_eof() && !self.is(RightParen) {
558            if self.handle_fn_as_lambda_in_call(&mut args) {
559                continue;
560            }
561            if self.at_item_boundary()
562                && !matches!(self.stream.peek_ahead(1).kind, RightParen | Comma)
563            {
564                break;
565            }
566            let arg = self.parse_expression();
567            if self.is(Ellipsis) {
568                self.next();
569                self.expect_comma_or(RightParen);
570                if !self.is(RightParen) && !self.at_eof() {
571                    self.track_error(
572                        "argument after spread",
573                        "The `spread...` must be the last argument in the call.",
574                    );
575                    while !self.at_eof() && !self.is(RightParen) {
576                        self.next();
577                    }
578                }
579                self.advance_if(RightParen);
580                return (args, Some(arg));
581            }
582            args.push(arg);
583            self.expect_comma_or(RightParen);
584        }
585
586        self.advance_if(RightParen);
587        (args, None)
588    }
589
590    fn handle_fn_as_lambda_in_call(&mut self, args: &mut Vec<Expression>) -> bool {
591        if !(self.is(Function) && self.stream.peek_ahead(1).kind == LeftParen) {
592            return false;
593        }
594        let span = self.track_fn_as_lambda_error();
595        self.resync_on_error();
596        args.push(Expression::Unit {
597            ty: Type::uninferred(),
598            span,
599        });
600        true
601    }
602
603    fn parse_fn_as_lambda_recovery(&mut self) -> Expression {
604        let start = self.current_token();
605        self.track_fn_as_lambda_error();
606
607        self.ensure(Function);
608        let params = self.parse_function_params(ParamMode::Strict);
609        let return_annotation = self.parse_function_return_annotation();
610
611        let body = if self.is(LeftCurlyBrace) {
612            self.parse_block_expression()
613        } else {
614            Expression::NoOp
615        };
616
617        Expression::Lambda {
618            params,
619            return_annotation,
620            body: body.into(),
621            ty: Type::uninferred(),
622            span: self.span_from_tokens(start),
623        }
624    }
625
626    fn track_fn_as_lambda_error(&mut self) -> Span {
627        let start = self.current_token();
628        let span = Span::new(self.file_id, start.byte_offset, start.byte_length + 1);
629        let error = ParseError::new("Syntax error", span, "expected a lambda")
630            .with_parse_code("fn_as_lambda")
631            .with_help("Use a lambda instead: `|x| x * 2`");
632        self.errors.push(error);
633        span
634    }
635
636    pub fn parse_type_args(&mut self) -> Vec<Annotation> {
637        self.ensure(LeftAngleBracket);
638
639        let mut type_args = vec![];
640
641        loop {
642            if self.at_eof() {
643                break;
644            }
645
646            // A turbofish arg is a type or an integer size (the `N` in `Array.new<T, N>()`).
647            if self.at_size_position_value() {
648                type_args.push(self.parse_size_type_arg());
649            } else {
650                type_args.push(self.parse_annotation());
651            }
652
653            if self.is_right_angle_like() {
654                break;
655            }
656
657            self.ensure(Comma);
658        }
659
660        if !self.advance_if_right_angle() {
661            self.ensure(RightAngleBracket);
662        }
663
664        type_args
665    }
666
667    pub fn parse_binary_operator(&mut self) -> BinaryOperator {
668        let operator = match self.current_token().kind {
669            Plus => BinaryOperator::Addition,
670            Minus => BinaryOperator::Subtraction,
671            Star => BinaryOperator::Multiplication,
672            Slash => BinaryOperator::Division,
673            Ampersand => BinaryOperator::BitwiseAnd,
674            Pipe => BinaryOperator::BitwiseOr,
675            Caret => BinaryOperator::BitwiseXor,
676            AndNot => BinaryOperator::BitwiseAndNot,
677            ShiftLeft => BinaryOperator::ShiftLeft,
678            ShiftRight => BinaryOperator::ShiftRight,
679            LeftAngleBracket => BinaryOperator::LessThan,
680            LessThanOrEqual => BinaryOperator::LessThanOrEqual,
681            RightAngleBracket => BinaryOperator::GreaterThan,
682            GreaterThanOrEqual => BinaryOperator::GreaterThanOrEqual,
683            Percent => BinaryOperator::Remainder,
684            EqualDouble => BinaryOperator::Equal,
685            NotEqual => BinaryOperator::NotEqual,
686            AmpersandDouble => BinaryOperator::And,
687            PipeDouble => BinaryOperator::Or,
688            Pipeline => {
689                self.has_desugarables = true;
690                BinaryOperator::Pipeline
691            }
692
693            _ => {
694                self.track_error(format!(
695                    "expected binary operator, found {}",
696                    self.current_token().kind
697                ), "Binary operators: `+`, `-`, `*`, `/`, `%`, `&`, `|`, `^`, `&^`, `<<`, `>>`, `==`, `!=`, `<`, `>`, `<=`, `>=`, `&&`, `||`.");
698                BinaryOperator::Addition // meaningless fallback
699            }
700        };
701
702        self.next();
703
704        operator
705    }
706
707    fn parse_parenthesized_expression(&mut self) -> Expression {
708        let start = self.current_token();
709
710        let (expressions, has_trailing_comma) =
711            self.collect_delimited_expressions(LeftParen, RightParen);
712        let span = self.span_from_tokens(start);
713
714        match expressions.len() {
715            0 => Expression::Unit {
716                ty: Type::uninferred(),
717                span,
718            },
719            1 => {
720                if has_trailing_comma {
721                    self.error_tuple_arity(1, span);
722                }
723                let expression = expressions.into_iter().next().expect("len is 1");
724                Expression::Paren {
725                    ty: Type::uninferred(),
726                    expression: expression.into(),
727                    span,
728                }
729            }
730            n => {
731                if n > MAX_TUPLE_ARITY {
732                    self.error_tuple_arity(n, span);
733                }
734                Expression::Tuple {
735                    ty: Type::uninferred(),
736                    elements: expressions,
737                    span,
738                }
739            }
740        }
741    }
742
743    pub fn parse_try(&mut self, expression: Expression) -> Expression {
744        let start_offset = expression.get_span().byte_offset;
745
746        self.ensure(QuestionMark);
747
748        Expression::Propagate {
749            ty: Type::uninferred(),
750            expression: expression.into(),
751            span: self.span_from_offset(start_offset),
752        }
753    }
754
755    fn parse_lambda(&mut self) -> Expression {
756        let start = self.current_token();
757
758        let params = if self.is(Pipe) {
759            self.parse_lambda_params()
760        } else {
761            self.next();
762            vec![]
763        };
764
765        let has_return_type = self.is(Arrow);
766        let return_annotation = if has_return_type {
767            self.next();
768            self.parse_annotation()
769        } else {
770            Annotation::Unknown
771        };
772
773        if has_return_type && self.current_token().kind != LeftCurlyBrace {
774            self.track_error(
775                "not allowed",
776                "A lambda with a return type requires a block body",
777            );
778        }
779
780        let body = self.parse_expression();
781
782        Expression::Lambda {
783            params,
784            return_annotation,
785            body: body.into(),
786            ty: Type::uninferred(),
787            span: self.span_from_tokens(start),
788        }
789    }
790
791    pub fn parse_block_expression(&mut self) -> Expression {
792        let start = self.current_token();
793
794        self.ensure(LeftCurlyBrace);
795
796        if self.looks_like_map_literal() {
797            let key_span = self.span_from_token(self.current_token());
798            self.consume_to_matching_close_brace();
799            self.error_map_literal_not_supported(key_span);
800            return Expression::Block {
801                ty: Type::uninferred(),
802                items: vec![],
803                span: self.span_from_tokens(start),
804            };
805        }
806
807        if !self.enter_recursion() {
808            let span = self.span_from_token(self.current_token());
809            let mut brace_depth = 1u32;
810            while brace_depth > 0 && !self.at_eof() {
811                match self.current_token().kind {
812                    LeftCurlyBrace => brace_depth += 1,
813                    RightCurlyBrace => brace_depth -= 1,
814                    _ => {}
815                }
816                if brace_depth > 0 {
817                    self.next();
818                }
819            }
820            self.advance_if(RightCurlyBrace);
821            return Expression::Block {
822                ty: Type::uninferred(),
823                items: vec![],
824                span,
825            };
826        }
827
828        let mut items = vec![];
829
830        while self.is_not(RightCurlyBrace) && !self.too_many_errors() {
831            let position = self.position();
832            let item = self.parse_block_item();
833
834            self.advance_if(Semicolon);
835
836            items.push(item);
837            if self.position() == position {
838                self.next();
839            }
840        }
841
842        let span = self.close_brace_span(start, start);
843
844        self.leave_recursion();
845
846        Expression::Block {
847            ty: Type::uninferred(),
848            items,
849            span,
850        }
851    }
852
853    pub(crate) fn parse_function_params(&mut self, mode: ParamMode) -> Vec<Binding> {
854        self.ensure(LeftParen);
855
856        let mut params = vec![];
857
858        while self.is_not(RightParen) {
859            params.push(self.parse_binding_with_type(mode, params.is_empty()));
860            self.expect_comma_or(RightParen);
861        }
862
863        self.ensure(RightParen);
864
865        params
866    }
867
868    pub fn parse_lambda_params(&mut self) -> Vec<Binding> {
869        self.ensure(Pipe);
870
871        let mut params = vec![];
872
873        while self.is_not(Pipe) {
874            let is_mut = self.advance_if(Mut);
875            let mut binding = self.parse_binding();
876            binding.mutable = is_mut;
877            params.push(binding);
878            self.expect_comma_or(Pipe);
879        }
880
881        self.ensure(Pipe);
882
883        params
884    }
885
886    pub(crate) fn parse_function(
887        &mut self,
888        doc: Option<std::string::String>,
889        attributes: Vec<Attribute>,
890        param_mode: ParamMode,
891    ) -> Expression {
892        let start = self.current_token();
893
894        self.ensure(Function);
895
896        let name_token = self.current_token();
897        let name_span = Span::new(self.file_id, name_token.byte_offset, name_token.byte_length);
898
899        let name = self.read_identifier_sequence();
900
901        let name_span = Span::new(name_span.file_id, name_span.byte_offset, name.len() as u32);
902
903        let generics = self.parse_generics();
904        let params = self.parse_function_params(param_mode);
905        let return_annotation = self.parse_function_return_annotation();
906
907        let body = if self.is(LeftCurlyBrace) {
908            self.parse_block_expression()
909        } else {
910            Expression::NoOp
911        };
912
913        Expression::Function {
914            doc,
915            attributes,
916            name,
917            name_span,
918            generics,
919            params,
920            return_annotation,
921            return_type: Type::uninferred(),
922            visibility: Visibility::Private,
923            body: body.into(),
924            ty: Type::uninferred(),
925            span: self.span_from_tokens(start),
926        }
927    }
928
929    pub fn parse_field_access(&mut self, expression: Expression) -> Expression {
930        self.ensure(Dot);
931
932        let expression_start = expression.get_span().byte_offset;
933        let start = self.current_token();
934
935        if self.advance_if(Star) {
936            return Expression::Unary {
937                ty: Type::uninferred(),
938                operator: UnaryOperator::Deref,
939                expression: expression.into(),
940                span: self.span_from_tokens(start),
941            };
942        }
943
944        if self.is(Integer) {
945            let text = self.current_token().text;
946            let index: u32 = text.parse().unwrap_or_else(|_| {
947                self.track_error(
948                    format!("tuple index '{}' is too large", text),
949                    "Maximum index is `4294967295`.",
950                );
951                0
952            });
953
954            self.ensure(Integer);
955
956            return Expression::DotAccess {
957                ty: Type::uninferred(),
958                expression: expression.into(),
959                member: index.to_string().into(),
960                span: self.span_from_offset(expression_start),
961                dot_access_kind: None,
962                receiver_coercion: None,
963            };
964        }
965
966        let field = self.current_token().text;
967
968        self.ensure(Identifier);
969
970        Expression::DotAccess {
971            ty: Type::uninferred(),
972            expression: expression.into(),
973            member: field.into(),
974            span: self.span_from_offset(expression_start),
975            dot_access_kind: None,
976            receiver_coercion: None,
977        }
978    }
979
980    pub fn collect_delimited_expressions(
981        &mut self,
982        open: TokenKind,
983        close: TokenKind,
984    ) -> (Vec<Expression>, bool) {
985        self.ensure(open);
986
987        let mut expressions = vec![];
988        let mut has_trailing_comma = false;
989        loop {
990            if self.at_eof() || self.is(close) {
991                break;
992            }
993
994            if self.is(Function) && self.stream.peek_ahead(1).kind == LeftParen {
995                let span = self.track_fn_as_lambda_error();
996                self.resync_on_error();
997                expressions.push(Expression::Unit {
998                    ty: Type::uninferred(),
999                    span,
1000                });
1001                continue;
1002            }
1003
1004            if self.at_item_boundary() {
1005                let next = self.stream.peek_ahead(1).kind;
1006                if next != close && next != Comma {
1007                    break;
1008                }
1009            }
1010            expressions.push(self.parse_expression());
1011            has_trailing_comma = self.is(Comma);
1012            self.expect_comma_or(close);
1013        }
1014
1015        self.advance_if(close);
1016
1017        (expressions, has_trailing_comma)
1018    }
1019
1020    fn make_expression_name(&mut self, expression: &Expression) -> EcoString {
1021        let mut parts = Vec::new();
1022        let mut current = expression;
1023
1024        loop {
1025            match current {
1026                Expression::Identifier { value, .. } => {
1027                    parts.push(value.clone());
1028                    break;
1029                }
1030                Expression::DotAccess {
1031                    expression, member, ..
1032                } => {
1033                    parts.push(member.clone());
1034                    current = expression;
1035                }
1036                _ => {
1037                    self.track_error(
1038                        "unexpected expression",
1039                        "Expected an identifier or dotted path.",
1040                    );
1041                    return "_".into();
1042                }
1043            }
1044        }
1045
1046        parts.reverse();
1047        parts.join(".").into()
1048    }
1049
1050    pub fn parse_let(&mut self) -> Expression {
1051        let start = self.current_token();
1052
1053        self.ensure(Let);
1054
1055        let assert = self.is(Assert);
1056        if assert {
1057            self.next(); // consume `assert`
1058        }
1059
1060        let (mutable, mut_span) = if self.is(Mut) {
1061            let mut_token = self.current_token();
1062            let span = Span::new(self.file_id, mut_token.byte_offset, mut_token.byte_length);
1063            self.next(); // consume `mut`
1064            (true, Some(span))
1065        } else {
1066            (false, None)
1067        };
1068
1069        if assert && let Some(span) = mut_span {
1070            self.track_error_at(
1071                span,
1072                "`let assert` cannot be combined with `mut`",
1073                "`let assert` binds a refutable pattern. Remove `mut`",
1074            );
1075        }
1076
1077        let binding = self.parse_binding_allowing_or();
1078
1079        if !self.is(Equal)
1080            && let Some(Annotation::Constructor { span, .. }) = binding.annotation.as_ref()
1081        {
1082            self.error_missing_initializer(*span);
1083            let stub_span = self.span_from_tokens(start);
1084            return Expression::Let {
1085                binding: Box::new(binding),
1086                value: Box::new(Expression::Block {
1087                    ty: Type::uninferred(),
1088                    items: vec![],
1089                    span: stub_span,
1090                }),
1091                mutable,
1092                mut_span,
1093                else_block: None,
1094                else_span: None,
1095                assert,
1096                typed_pattern: None,
1097                ty: Type::uninferred(),
1098                span: stub_span,
1099            };
1100        }
1101
1102        self.ensure(Equal);
1103
1104        let expression = self.parse_expression();
1105
1106        let (else_block, else_span) = if self.is(Else) {
1107            let else_token = self.current_token();
1108            let span = Span::new(self.file_id, else_token.byte_offset, else_token.byte_length);
1109            self.next(); // consume `else`
1110            (Some(Box::new(self.parse_block_expression())), Some(span))
1111        } else {
1112            (None, None)
1113        };
1114
1115        if assert && else_block.is_some() {
1116            self.track_error_at(
1117                else_span.expect("else_block implies else_span"),
1118                "`let assert` cannot have an `else` block",
1119                "`let assert` already fails the test on mismatch. Remove the `else`",
1120            );
1121        }
1122
1123        Expression::Let {
1124            binding: Box::new(binding),
1125            value: expression.into(),
1126            mutable,
1127            mut_span,
1128            else_block,
1129            else_span,
1130            assert,
1131            typed_pattern: None,
1132            ty: Type::uninferred(),
1133            span: self.span_from_tokens(start),
1134        }
1135    }
1136
1137    pub fn parse_import(&mut self) -> Expression {
1138        let start = self.current_token();
1139
1140        self.ensure(Import);
1141
1142        let alias = if self.current_token().kind == Identifier {
1143            let alias_token = self.current_token();
1144            let alias_text = alias_token.text;
1145            let alias_span = Span::new(
1146                self.file_id,
1147                alias_token.byte_offset,
1148                alias_token.byte_length,
1149            );
1150
1151            if alias_text == "_" {
1152                self.next();
1153                Some(ImportAlias::Blank(alias_span))
1154            } else if self.stream.peek_ahead(1).kind == String {
1155                self.next();
1156                Some(ImportAlias::Named(alias_text.into(), alias_span))
1157            } else {
1158                None
1159            }
1160        } else {
1161            None
1162        };
1163
1164        let name_token = self.current_token();
1165
1166        if name_token.kind != String {
1167            let (label, help) = if name_token.kind == Identifier
1168                && self.stream.peek_ahead(1).kind == Colon
1169            {
1170                let module_name = name_token.text;
1171                (
1172                    "expected double quotes".to_string(),
1173                    format!(
1174                        "Wrap the import path in double quotes: `import \"{0}:...\"`",
1175                        module_name
1176                    ),
1177                )
1178            } else if name_token.kind == Identifier {
1179                let module_name = name_token.text;
1180                (
1181                    "expected double quotes".to_string(),
1182                    format!(
1183                        "Wrap the import path in double quotes: `import \"{}\"`",
1184                        module_name
1185                    ),
1186                )
1187            } else {
1188                (
1189                    "expected module path".to_string(),
1190                    "Wrap the import path in double quotes, e.g. `import \"go:os\"`".to_string(),
1191                )
1192            };
1193
1194            self.track_error(label, help);
1195            self.resync_on_error();
1196            return Expression::Unit {
1197                ty: Type::uninferred(),
1198                span: self.span_from_tokens(start),
1199            };
1200        }
1201
1202        self.next();
1203
1204        let raw = name_token.text;
1205        let unquoted: &str = if raw.len() >= 2 && raw.starts_with('"') && raw.ends_with('"') {
1206            &raw[1..raw.len() - 1]
1207        } else {
1208            debug_assert!(
1209                false,
1210                "lexer produced String token without quotes: {:?}",
1211                raw
1212            );
1213            raw
1214        };
1215
1216        if alias.is_none() && self.is(As) && self.stream.peek_ahead(1).kind == Identifier {
1217            let as_token = self.current_token();
1218            let alias_identifier = self.stream.peek_ahead(1);
1219            self.next();
1220            self.next();
1221            self.error_import_alias_after_path(
1222                self.span_from_tokens(as_token),
1223                alias_identifier.text,
1224                unquoted,
1225            );
1226        }
1227
1228        let name: EcoString = unquoted.into();
1229        let name_span = Span::new(self.file_id, name_token.byte_offset, name_token.byte_length);
1230
1231        Expression::ModuleImport {
1232            name,
1233            name_span,
1234            alias,
1235            span: self.span_from_tokens(start),
1236        }
1237    }
1238
1239    pub fn parse_assignment(&mut self) -> Expression {
1240        let start = self.current_token();
1241
1242        let lhs = self.parse_expression();
1243
1244        let compound_operator = match self.current_token().kind {
1245            PlusEqual => Some(BinaryOperator::Addition),
1246            MinusEqual => Some(BinaryOperator::Subtraction),
1247            StarEqual => Some(BinaryOperator::Multiplication),
1248            SlashEqual => Some(BinaryOperator::Division),
1249            PercentEqual => Some(BinaryOperator::Remainder),
1250            AmpersandEqual => Some(BinaryOperator::BitwiseAnd),
1251            PipeEqual => Some(BinaryOperator::BitwiseOr),
1252            CaretEqual => Some(BinaryOperator::BitwiseXor),
1253            AndNotEqual => Some(BinaryOperator::BitwiseAndNot),
1254            ShiftLeftEqual => Some(BinaryOperator::ShiftLeft),
1255            ShiftRightEqual => Some(BinaryOperator::ShiftRight),
1256            _ => None,
1257        };
1258
1259        if let Some(operator) = compound_operator {
1260            if !self.is_valid_assignment_target(&lhs) {
1261                self.track_error(
1262                    "invalid assignment target",
1263                    "Only variables, fields, and indices can be assigned to.",
1264                );
1265                self.next();
1266                let _rhs = self.parse_expression();
1267                return lhs;
1268            }
1269            self.next();
1270            let rhs = self.parse_expression();
1271            return Expression::Assignment {
1272                target: lhs.into(),
1273                value: rhs.into(),
1274                compound_operator: Some(operator),
1275                span: self.span_from_tokens(start),
1276            };
1277        }
1278
1279        if self.current_token().kind == Colon && self.stream.peek_ahead(1).kind == Equal {
1280            let span = Span::new(self.file_id, self.current_token().byte_offset, 2);
1281            self.track_error_at(
1282                span,
1283                "Go-style short declaration",
1284                "Use `let x = ...` instead of `:=` for variable declarations",
1285            );
1286            self.next();
1287            self.next();
1288            let _ = self.parse_expression();
1289            return lhs;
1290        }
1291
1292        if !self.is(Equal) {
1293            return lhs;
1294        }
1295
1296        if !self.is_valid_assignment_target(&lhs) {
1297            self.track_error(
1298                "invalid assignment target",
1299                "Only variables, fields, and indices can be assigned to.",
1300            );
1301        }
1302
1303        self.ensure(Equal);
1304
1305        Expression::Assignment {
1306            target: lhs.into(),
1307            value: self.parse_expression().into(),
1308            compound_operator: None,
1309            span: self.span_from_tokens(start),
1310        }
1311    }
1312
1313    pub(super) fn is_valid_assignment_target(&self, expression: &Expression) -> bool {
1314        use Expression::*;
1315
1316        matches!(
1317            expression,
1318            Identifier { .. }
1319                | DotAccess { .. }
1320                | IndexedAccess { .. }
1321                | Unary {
1322                    operator: UnaryOperator::Deref,
1323                    ..
1324                }
1325        )
1326    }
1327
1328    fn parse_format_string(&mut self) -> Expression {
1329        let start = self.current_token();
1330        self.ensure(FormatStringStart);
1331
1332        let mut parts = Vec::new();
1333
1334        loop {
1335            if self.at_eof() || self.at_item_boundary() {
1336                break;
1337            }
1338            match self.current_token().kind {
1339                FormatStringText => {
1340                    let text = self.current_token().text;
1341                    self.next();
1342                    parts.push(FormatStringPart::Text(cook_string_contents(text)));
1343                }
1344                FormatStringInterpolationStart => {
1345                    self.ensure(FormatStringInterpolationStart);
1346                    let expression = self.parse_expression();
1347                    parts.push(FormatStringPart::Expression(Box::new(expression)));
1348                    if self.is(Colon) {
1349                        let start_offset = self.current_token().byte_offset;
1350                        self.next();
1351                        while !self.at_eof()
1352                            && !self.is(FormatStringInterpolationEnd)
1353                            && !self.is(FormatStringEnd)
1354                            && !self.at_item_boundary()
1355                        {
1356                            self.next();
1357                        }
1358                        let span = self.span_from_offset(start_offset);
1359                        let error = ParseError::new(
1360                            "Format specifiers not supported",
1361                            span,
1362                            "not supported in format strings",
1363                        )
1364                        .with_parse_code("format_specifier")
1365                        .with_help(
1366                            "Use `fmt.Sprintf` for formatted output, e.g. `fmt.Sprintf(\"%02x\", n)`",
1367                        );
1368                        self.errors.push(error);
1369                    }
1370                    self.advance_if(FormatStringInterpolationEnd);
1371                }
1372                FormatStringEnd => {
1373                    self.ensure(FormatStringEnd);
1374                    break;
1375                }
1376                _ => break,
1377            }
1378        }
1379
1380        Expression::Literal {
1381            literal: Literal::FormatString(parts),
1382            ty: Type::uninferred(),
1383            span: self.span_from_tokens(start),
1384        }
1385    }
1386
1387    pub fn parse_task(&mut self) -> Expression {
1388        let start = self.current_token();
1389
1390        self.ensure(Task);
1391
1392        let expression = if self.is(LeftCurlyBrace) {
1393            self.parse_block_expression()
1394        } else {
1395            self.parse_expression()
1396        };
1397
1398        if !matches!(
1399            expression,
1400            Expression::Call { .. } | Expression::Block { .. }
1401        ) {
1402            let span = expression.get_span();
1403            let error = ParseError::new("Invalid `task`", span, "expected `()`")
1404                .with_parse_code("task_missing_parens")
1405                .with_help("Add parens to call the function");
1406
1407            self.errors.push(error);
1408        }
1409
1410        Expression::Task {
1411            expression: Box::new(expression),
1412            ty: Type::uninferred(),
1413            span: self.span_from_tokens(start),
1414        }
1415    }
1416
1417    pub fn parse_defer(&mut self) -> Expression {
1418        let start = self.current_token();
1419
1420        self.ensure(Defer);
1421
1422        let expression = if self.is(LeftCurlyBrace) {
1423            self.parse_block_expression()
1424        } else {
1425            self.parse_expression()
1426        };
1427
1428        if !matches!(
1429            expression,
1430            Expression::Call { .. } | Expression::Block { .. }
1431        ) {
1432            let span = expression.get_span();
1433            let error = ParseError::new("Invalid `defer`", span, "expected `()`")
1434                .with_parse_code("defer_missing_parens")
1435                .with_help("Add parens to call the function");
1436
1437            self.errors.push(error);
1438        }
1439
1440        Expression::Defer {
1441            expression: Box::new(expression),
1442            ty: Type::uninferred(),
1443            span: self.span_from_tokens(start),
1444        }
1445    }
1446
1447    pub fn parse_try_block(&mut self) -> Expression {
1448        let start = self.current_token();
1449        let try_keyword_span = Span::new(self.file_id, start.byte_offset, start.byte_length);
1450
1451        self.ensure(Try);
1452
1453        if !self.is(LeftCurlyBrace) {
1454            let span = self.span_from_tokens(start);
1455            let error = ParseError::new("Invalid `try`", span, "requires a block")
1456                .with_parse_code("syntax_error")
1457                .with_help("Use `try { expression }` instead of `try expression`");
1458            self.errors.push(error);
1459            let expression = self.parse_expression();
1460            return Expression::TryBlock {
1461                items: vec![expression],
1462                ty: Type::uninferred(),
1463                try_keyword_span,
1464                span: self.span_from_tokens(start),
1465            };
1466        }
1467
1468        let brace_token = self.current_token();
1469        self.ensure(LeftCurlyBrace);
1470
1471        if !self.enter_recursion() {
1472            let span = self.span_from_token(self.current_token());
1473            let mut brace_depth = 1u32;
1474            while brace_depth > 0 && !self.at_eof() {
1475                match self.current_token().kind {
1476                    LeftCurlyBrace => brace_depth += 1,
1477                    RightCurlyBrace => brace_depth -= 1,
1478                    _ => {}
1479                }
1480                if brace_depth > 0 {
1481                    self.next();
1482                }
1483            }
1484            self.advance_if(RightCurlyBrace);
1485            return Expression::TryBlock {
1486                items: vec![],
1487                ty: Type::uninferred(),
1488                try_keyword_span,
1489                span,
1490            };
1491        }
1492
1493        let mut items = vec![];
1494
1495        while self.is_not(RightCurlyBrace) && !self.too_many_errors() {
1496            let position = self.position();
1497            let item = self.parse_block_item();
1498
1499            self.advance_if(Semicolon);
1500
1501            items.push(item);
1502            if self.position() == position {
1503                self.next();
1504            }
1505        }
1506
1507        let span = self.close_brace_span(start, brace_token);
1508
1509        self.leave_recursion();
1510
1511        Expression::TryBlock {
1512            items,
1513            ty: Type::uninferred(),
1514            try_keyword_span,
1515            span,
1516        }
1517    }
1518
1519    pub fn parse_recover_block(&mut self) -> Expression {
1520        let start = self.current_token();
1521        let recover_keyword_span = Span::new(self.file_id, start.byte_offset, start.byte_length);
1522
1523        self.ensure(Recover);
1524
1525        if !self.is(LeftCurlyBrace) {
1526            let span = self.span_from_tokens(start);
1527            let error = ParseError::new("Invalid `recover`", span, "requires a block")
1528                .with_parse_code("syntax_error")
1529                .with_help("Use `recover { expression }` instead of `recover expression`");
1530            self.errors.push(error);
1531            let expression = self.parse_expression();
1532            return Expression::RecoverBlock {
1533                items: vec![expression],
1534                ty: Type::uninferred(),
1535                recover_keyword_span,
1536                span: self.span_from_tokens(start),
1537            };
1538        }
1539
1540        let brace_token = self.current_token();
1541        self.ensure(LeftCurlyBrace);
1542
1543        if !self.enter_recursion() {
1544            let span = self.span_from_token(self.current_token());
1545            let mut brace_depth = 1u32;
1546            while brace_depth > 0 && !self.at_eof() {
1547                match self.current_token().kind {
1548                    LeftCurlyBrace => brace_depth += 1,
1549                    RightCurlyBrace => brace_depth -= 1,
1550                    _ => {}
1551                }
1552                if brace_depth > 0 {
1553                    self.next();
1554                }
1555            }
1556            self.advance_if(RightCurlyBrace);
1557            return Expression::RecoverBlock {
1558                items: vec![],
1559                ty: Type::uninferred(),
1560                recover_keyword_span,
1561                span,
1562            };
1563        }
1564
1565        let mut items = vec![];
1566
1567        while self.is_not(RightCurlyBrace) && !self.too_many_errors() {
1568            let position = self.position();
1569            let item = self.parse_block_item();
1570
1571            self.advance_if(Semicolon);
1572
1573            items.push(item);
1574            if self.position() == position {
1575                self.next();
1576            }
1577        }
1578
1579        let span = self.close_brace_span(start, brace_token);
1580
1581        self.leave_recursion();
1582
1583        Expression::RecoverBlock {
1584            items,
1585            ty: Type::uninferred(),
1586            recover_keyword_span,
1587            span,
1588        }
1589    }
1590
1591    pub fn parse_select(&mut self) -> Expression {
1592        let start = self.current_token();
1593
1594        self.ensure(Select);
1595        self.ensure(LeftCurlyBrace);
1596
1597        let mut arms = Vec::new();
1598
1599        while self.is_not(RightCurlyBrace) {
1600            let arm = self.parse_select_arm();
1601            arms.push(arm);
1602
1603            if self.is(RightCurlyBrace) {
1604                break;
1605            }
1606
1607            self.ensure(Comma);
1608        }
1609
1610        self.ensure(RightCurlyBrace);
1611
1612        Expression::Select {
1613            arms,
1614            ty: Type::uninferred(),
1615            span: self.span_from_tokens(start),
1616        }
1617    }
1618
1619    fn parse_select_arm(&mut self) -> SelectArm {
1620        match self.current_token().kind {
1621            Let => {
1622                self.ensure(Let);
1623                let binding = self.parse_pattern();
1624                self.ensure(Equal);
1625                let receive_expression = Box::new(self.parse_expression());
1626                self.ensure(ArrowDouble);
1627                let body = Box::new(self.parse_expression());
1628                SelectArm {
1629                    pattern: SelectArmPattern::Receive {
1630                        binding: Box::new(binding),
1631                        typed_pattern: None,
1632                        receive_expression,
1633                        body,
1634                    },
1635                }
1636            }
1637            Match => {
1638                let match_expression = self.parse_match();
1639                if let Expression::Match { subject, arms, .. } = match_expression {
1640                    SelectArm {
1641                        pattern: SelectArmPattern::MatchReceive {
1642                            receive_expression: subject,
1643                            arms,
1644                        },
1645                    }
1646                } else {
1647                    self.ensure(ArrowDouble);
1648                    let body = Box::new(self.parse_expression());
1649                    SelectArm {
1650                        pattern: SelectArmPattern::Send {
1651                            send_expression: Box::new(match_expression),
1652                            body,
1653                        },
1654                    }
1655                }
1656            }
1657            Identifier if self.current_token().text == "_" => {
1658                self.next();
1659                self.ensure(ArrowDouble);
1660                let body = Box::new(self.parse_expression());
1661                SelectArm {
1662                    pattern: SelectArmPattern::WildCard { body },
1663                }
1664            }
1665            _ => {
1666                let send_expression = Box::new(self.parse_expression());
1667                self.ensure(ArrowDouble);
1668                let body = Box::new(self.parse_expression());
1669                SelectArm {
1670                    pattern: SelectArmPattern::Send {
1671                        send_expression,
1672                        body,
1673                    },
1674                }
1675            }
1676        }
1677    }
1678
1679    pub fn with_control_flow_header<F, R>(&mut self, f: F) -> R
1680    where
1681        F: FnOnce(&mut Self) -> R,
1682    {
1683        let old = self.in_control_flow_header;
1684        self.in_control_flow_header = true;
1685        let result = f(self);
1686        self.in_control_flow_header = old;
1687        result
1688    }
1689
1690    fn keyword_in_value_position(&self) -> bool {
1691        if !self.current_token().kind.is_keyword() {
1692            return false;
1693        }
1694
1695        match self.current_token().kind {
1696            Return | Break | Continue => false,
1697
1698            Match | If | Task | Defer | Try | Recover | Select | Loop | Function => matches!(
1699                self.stream.peek_ahead(1).kind,
1700                RightParen
1701                    | Comma
1702                    | Dot
1703                    | Semicolon
1704                    | RightCurlyBrace
1705                    | RightSquareBracket
1706                    | ArrowDouble
1707                    | QuestionMark
1708                    | EOF
1709                    | Plus
1710                    | Star
1711                    | Slash
1712                    | Percent
1713                    | EqualDouble
1714                    | NotEqual
1715                    | LeftAngleBracket
1716                    | RightAngleBracket
1717                    | LessThanOrEqual
1718                    | GreaterThanOrEqual
1719                    | AmpersandDouble
1720                    | Ampersand
1721                    | Pipe
1722                    | Caret
1723                    | AndNot
1724                    | ShiftLeft
1725                    | ShiftRight
1726                    | Pipeline
1727                    | Equal
1728                    | PlusEqual
1729                    | MinusEqual
1730                    | StarEqual
1731                    | SlashEqual
1732                    | PercentEqual
1733                    | AmpersandEqual
1734                    | PipeEqual
1735                    | CaretEqual
1736                    | AndNotEqual
1737                    | ShiftLeftEqual
1738                    | ShiftRightEqual
1739                    | DotDot
1740                    | DotDotEqual
1741                    | As
1742            ),
1743
1744            _ => true,
1745        }
1746    }
1747
1748    fn recover_keyword_as_identifier(&mut self) -> Expression {
1749        let token = self.current_token();
1750        let keyword = token.text.to_string();
1751        let span = self.span_from_token(token);
1752        let error = if token.kind == Var {
1753            ParseError::new("Syntax error", span, "expected `let`")
1754                .with_parse_code("expected_let")
1755                .with_help("Use `let` to declare a variable: `let x = 0`")
1756        } else {
1757            ParseError::new("Reserved keyword", span, "reserved keyword")
1758                .with_parse_code("keyword_as_identifier")
1759                .with_help(format!("Rename `{}`", keyword))
1760        };
1761        self.errors.push(error);
1762        self.next();
1763        Expression::Identifier {
1764            value: keyword.into(),
1765            ty: Type::uninferred(),
1766            span,
1767            binding_id: None,
1768            qualified: None,
1769        }
1770    }
1771
1772    fn looks_like_map_literal(&self) -> bool {
1773        let first = self.current_token().kind;
1774        let second = self.stream.peek_ahead(1).kind;
1775        matches!(first, String | RawString | Integer | Float) && second == Colon
1776    }
1777
1778    fn consume_to_matching_close_brace(&mut self) {
1779        let mut brace_depth = 1u32;
1780        while brace_depth > 0 && !self.at_eof() {
1781            match self.current_token().kind {
1782                LeftCurlyBrace => brace_depth += 1,
1783                RightCurlyBrace => brace_depth -= 1,
1784                _ => {}
1785            }
1786            if brace_depth > 0 {
1787                self.next();
1788            }
1789        }
1790        self.advance_if(RightCurlyBrace);
1791    }
1792
1793    fn recover_unexpected_backtick(&mut self) -> Expression {
1794        let token = self.current_token();
1795        let token_span = self.span_from_token(token);
1796        let opening_span = Span::new(self.file_id, token.byte_offset, 1);
1797        let error = ParseError::new("Unexpected backtick", opening_span, "not allowed here")
1798            .with_parse_code("unexpected_backtick")
1799            .with_help(
1800                "Use a regular string `\"...\"` or a raw string `r\"...\"` for single- or multi-line strings. Backticks in Lisette are reserved for struct-tag attributes.",
1801            );
1802        self.errors.push(error);
1803        self.next();
1804        Expression::Literal {
1805            literal: Literal::String {
1806                value: std::string::String::new(),
1807                raw: true,
1808            },
1809            ty: Type::uninferred(),
1810            span: token_span,
1811        }
1812    }
1813}
1814
1815#[cfg(test)]
1816mod tests {
1817    use crate::ast::{Annotation, BinaryOperator, Expression};
1818    use crate::build_ast;
1819
1820    fn count_nodes(expression: &Expression) -> usize {
1821        1 + expression.children().iter().map(count_nodes).sum::<usize>()
1822    }
1823
1824    fn first_assignment(expression: &Expression) -> Option<&Expression> {
1825        if matches!(expression, Expression::Assignment { .. }) {
1826            return Some(expression);
1827        }
1828        expression.children().iter().find_map(first_assignment)
1829    }
1830
1831    #[test]
1832    fn compound_assignment_stores_only_the_rhs() {
1833        let result = build_ast("fn f() {\n let mut x = 0\n x += 5\n}", 0);
1834        assert!(result.errors.is_empty(), "{:?}", result.errors);
1835
1836        let assignment = result
1837            .ast
1838            .iter()
1839            .find_map(first_assignment)
1840            .expect("an assignment");
1841        let Expression::Assignment {
1842            value,
1843            compound_operator,
1844            ..
1845        } = assignment
1846        else {
1847            unreachable!()
1848        };
1849
1850        assert_eq!(*compound_operator, Some(BinaryOperator::Addition));
1851        assert!(
1852            matches!(value.as_ref(), Expression::Literal { .. }),
1853            "value should hold only the rhs, not a duplicated `x + 5`: {value:?}"
1854        );
1855    }
1856
1857    #[test]
1858    fn function_type_annotation_captures_per_param_mutability() {
1859        let result = build_ast("fn run(action: fn(mut Bar, Baz) -> ()) {}", 0);
1860        assert!(result.errors.is_empty(), "{:?}", result.errors);
1861
1862        let Some(Expression::Function { params, .. }) = result
1863            .ast
1864            .iter()
1865            .find(|item| matches!(item, Expression::Function { .. }))
1866        else {
1867            unreachable!("expected a top-level function")
1868        };
1869        let Some(Annotation::Function {
1870            param_mutability, ..
1871        }) = &params[0].annotation
1872        else {
1873            panic!(
1874                "expected a function-type annotation, got {:?}",
1875                params[0].annotation
1876            )
1877        };
1878
1879        assert_eq!(param_mutability, &vec![true, false]);
1880    }
1881
1882    #[test]
1883    fn lambda_parameter_can_be_mut() {
1884        let result = build_ast("fn f() {\n  let g = |mut x: int| x\n  let _ = g\n}", 0);
1885        assert!(result.errors.is_empty(), "{:?}", result.errors);
1886
1887        fn find_lambda(expression: &Expression) -> Option<&Expression> {
1888            if matches!(expression, Expression::Lambda { .. }) {
1889                return Some(expression);
1890            }
1891            expression
1892                .children()
1893                .iter()
1894                .find_map(|child| find_lambda(child))
1895        }
1896
1897        let Some(Expression::Lambda { params, .. }) = result.ast.iter().find_map(find_lambda)
1898        else {
1899            unreachable!("expected a lambda")
1900        };
1901
1902        assert_eq!(params.len(), 1);
1903        assert!(
1904            params[0].mutable,
1905            "`mut x` lambda parameter should be mutable"
1906        );
1907    }
1908
1909    #[test]
1910    fn nested_compound_assignments_stay_linear() {
1911        let depth = 14;
1912        let source = format!(
1913            "fn f() {{ {}x{} }}",
1914            "{".repeat(depth),
1915            "}.f += 1".repeat(depth),
1916        );
1917        let result = build_ast(&source, 0);
1918        assert!(result.errors.is_empty(), "{:?}", result.errors);
1919
1920        let nodes: usize = result.ast.iter().map(count_nodes).sum();
1921        assert!(
1922            nodes < 20 * depth,
1923            "nested compound assignments grew super-linearly: {nodes} nodes at depth {depth}",
1924        );
1925    }
1926}