Skip to main content

nybl/
parser.rs

1#[cfg(all(feature = "no_std", not(feature = "std")))]
2use alloc::{
3    boxed::Box,
4    format,
5    string::{String, ToString},
6    vec,
7    vec::Vec,
8};
9
10#[cfg(all(feature = "no_std", not(feature = "std")))]
11use alloc::collections::{BTreeMap, BTreeSet};
12#[cfg(any(feature = "std", not(feature = "no_std")))]
13use std::collections::{BTreeMap, BTreeSet};
14
15use crate::error::NyblError;
16use crate::lexer::{
17    I64_MIN_MAGNITUDE_TEXT, SpannedToken, StringPart, Token, integer_literal_out_of_range,
18};
19use crate::naming;
20
21// ─── Naming helpers ─────────────────────────────────────────────────────
22//
23// Enforce the shape rules defined in `nybl::naming` at every
24// identifier-introducing site. Each `ensure_*_name` returns a
25// parse error whose `message` says what the site expects and
26// whose `friendly_hint` offers a concrete rename — cheap to
27// generate, and makes errors read like the compiler wants to
28// help rather than just complain.
29
30fn ident_shape_error_at(
31    site: &str,
32    expected: &str,
33    actual: &str,
34    line: u32,
35    column: Option<core::num::NonZeroU32>,
36) -> NyblError {
37    let actual_label = naming::kind_label(naming::classify(actual));
38    let message = format!(
39        "{site} `{actual}` looks like a {actual_label}, but a {expected} name is required here"
40    );
41    let mut err = NyblError::runtime_at(message, line, column);
42    err.friendly_hint = Some(if site.starts_with("`match` pattern") {
43        naming::pattern_binding_hint(actual)
44    } else {
45        naming::hint_for(expected, actual)
46    });
47    err
48}
49
50fn ident_shape_error(site: &str, expected: &str, actual: &str, line: u32) -> NyblError {
51    ident_shape_error_at(site, expected, actual, line, None)
52}
53
54/// Require a lowercase-first (or leading-underscore) identifier
55/// at a `let` / `fn` / param / field / method / alias /
56/// match-binding / `for-in` / `use` alias site.
57fn ensure_value_name(name: &str, site: &str, line: u32) -> Result<(), NyblError> {
58    ensure_value_name_at(name, site, line, None)
59}
60
61fn ensure_value_name_at(
62    name: &str,
63    site: &str,
64    line: u32,
65    column: Option<core::num::NonZeroU32>,
66) -> Result<(), NyblError> {
67    if naming::is_value_name(name) {
68        Ok(())
69    } else {
70        Err(ident_shape_error_at(site, "value", name, line, column))
71    }
72}
73
74/// Require an uppercase-first identifier at a `struct` / `enum` /
75/// variant site. Both PascalCase and ALL_CAPS are accepted —
76/// `struct Entity {}`, `enum Dir { N, E, S, W }`, and
77/// `struct HTTP {}` all pass.
78fn ensure_type_name(name: &str, site: &str, line: u32) -> Result<(), NyblError> {
79    if naming::is_type_name(name) {
80        Ok(())
81    } else {
82        Err(ident_shape_error(site, "type", name, line))
83    }
84}
85
86/// Require an all-uppercase identifier at a `const` site.
87fn ensure_constant_name(name: &str, site: &str, line: u32) -> Result<(), NyblError> {
88    if naming::is_constant_name(name) {
89        Ok(())
90    } else {
91        Err(ident_shape_error(site, "constant", name, line))
92    }
93}
94
95fn format_pattern_binding_names(names: &BTreeSet<String>) -> String {
96    if names.is_empty() {
97        String::from("no names")
98    } else {
99        names
100            .iter()
101            .map(|name| format!("`{name}`"))
102            .collect::<Vec<_>>()
103            .join(", ")
104    }
105}
106
107fn inconsistent_or_pattern_bindings_error(
108    expected: &BTreeSet<String>,
109    actual: &BTreeSet<String>,
110    alternative: usize,
111    line: u32,
112    column: Option<core::num::NonZeroU32>,
113) -> NyblError {
114    let mut error = NyblError::runtime_at(
115        format!(
116            "`or`-pattern alternative {} binds {}, but alternative 1 binds {}",
117            alternative,
118            format_pattern_binding_names(actual),
119            format_pattern_binding_names(expected),
120        ),
121        line,
122        column,
123    );
124
125    let missing: BTreeSet<String> = expected.difference(actual).cloned().collect();
126    let unexpected: BTreeSet<String> = actual.difference(expected).cloned().collect();
127    let mut differences = Vec::new();
128    if !missing.is_empty() {
129        differences.push(format!(
130            "missing from alternative {}: {}",
131            alternative,
132            format_pattern_binding_names(&missing),
133        ));
134    }
135    if !unexpected.is_empty() {
136        differences.push(format!(
137            "only in alternative {}: {}",
138            alternative,
139            format_pattern_binding_names(&unexpected),
140        ));
141    }
142    error.friendly_hint = Some(format!(
143        "make every `|` alternative bind the same names; {}",
144        differences.join("; "),
145    ));
146    error
147}
148
149// ─── AST ───────────────────────────────────────────────────────────────────
150
151#[derive(Debug, Clone)]
152pub struct Expr {
153    pub kind: ExprKind,
154    pub line: u32,
155    /// 1-indexed column where this expression starts in the
156    /// source. `None` on synthetic nodes that don't correspond
157    /// to a specific source position. Niche-packed into 4 bytes
158    /// so the column field costs nothing beyond a plain `u32`
159    /// — runtime error construction reads it out to render a
160    /// caret under the offending character.
161    pub column: Option<core::num::NonZeroU32>,
162}
163
164impl Expr {
165    /// Build an `Expr` from its kind and a 1-indexed source
166    /// line, leaving `column` unset. Convenience constructor
167    /// for call sites that don't have a token column handy
168    /// (synthetic / desugared nodes, for instance).
169    pub fn line(kind: ExprKind, line: u32) -> Self {
170        Self {
171            kind,
172            line,
173            column: None,
174        }
175    }
176
177    /// Build an `Expr` with a full source position. `column`
178    /// is typically `NonZeroU32::new(tok.column)`.
179    pub fn at(kind: ExprKind, line: u32, column: Option<core::num::NonZeroU32>) -> Self {
180        Self { kind, line, column }
181    }
182}
183
184/// The passing mode declared by a function parameter or written at a call
185/// site. `Ref` is explicit on both sides; engines use this metadata during
186/// call preflight before evaluating argument expressions.
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188pub enum ParamMode {
189    /// An ordinary positional argument passed with value semantics.
190    Value,
191    /// A transactional copy-in/copy-out argument marked with `ref`.
192    Ref,
193    /// The final declaration parameter collecting remaining value arguments.
194    /// This mode never appears on a call-site [`CallArg`].
195    Rest,
196}
197
198/// One declared function parameter, including its call-site passing mode.
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct Parameter {
201    /// The binding name visible inside the function body.
202    pub name: String,
203    /// Whether the parameter is value-only or must be called with `ref`.
204    pub mode: ParamMode,
205}
206
207/// One positional call argument. Keeping the marker beside the expression
208/// makes mode information survive aliases and dynamic callable dispatch.
209#[derive(Debug, Clone)]
210pub struct CallArg {
211    /// The source expression associated with this positional argument.
212    pub value: Expr,
213    /// Whether the call site wrote an explicit `ref` marker.
214    pub mode: ParamMode,
215}
216
217impl core::ops::Deref for CallArg {
218    type Target = Expr;
219
220    fn deref(&self) -> &Self::Target {
221        &self.value
222    }
223}
224
225#[derive(Debug, Clone)]
226pub enum ExprKind {
227    /// Integer literal (phase 6). Produced by integer tokens
228    /// like `42`; distinct from `Number` so each engine can
229    /// emit a `Value::Int(i64)` directly.
230    Int(i64),
231    Number(f64),
232    Str(String),
233    StringInterp(Vec<StringPart>),
234    Bool(bool),
235    None,
236    Ident(String),
237    BinaryOp {
238        left: Box<Expr>,
239        op: BinOp,
240        right: Box<Expr>,
241    },
242    UnaryOp {
243        op: UnaryOp,
244        expr: Box<Expr>,
245    },
246    Call {
247        callee: Box<Expr>,
248        args: Vec<CallArg>,
249    },
250    MethodCall {
251        object: Box<Expr>,
252        method: String,
253        args: Vec<CallArg>,
254    },
255    /// Bare field read: `obj.field` (no parens after the field
256    /// name). Distinct from `MethodCall`, which always has `(…)`.
257    FieldAccess {
258        object: Box<Expr>,
259        field: String,
260    },
261    /// Struct literal: `Point { x: 1, y: 2 }`. Only parsed in
262    /// contexts where struct literals are allowed — control-flow
263    /// conditions and `for-in` iterables disallow them so that
264    /// `if foo { body }` stays unambiguous.
265    StructConstruct {
266        /// `Some("m")` for `m.Entity { ... }` — a namespaced
267        /// struct literal through a module alias. `None` for
268        /// the unqualified `Entity { ... }` form. The walker /
269        /// VM / AOT resolve the (namespace, type_name) pair via
270        /// the current scope's type-alias table before
271        /// constructing the `Value::Struct`.
272        namespace: Option<String>,
273        type_name: String,
274        fields: Vec<(String, Expr)>,
275    },
276    /// Enum variant construction: `Shape::Circle(5)`,
277    /// `Shape::Rectangle { w: 4, h: 3 }`, `Shape::Empty`. The
278    /// payload shape is determined at parse time from the syntax
279    /// at the construction site.
280    EnumConstruct {
281        /// `Some("r")` for `r.Result::Ok(v)` — a namespaced
282        /// variant constructor through a module alias. `None`
283        /// for unqualified `Result::Ok(v)`.
284        namespace: Option<String>,
285        type_name: String,
286        variant: String,
287        payload: VariantPayload,
288    },
289    Index {
290        object: Box<Expr>,
291        index: Box<Expr>,
292    },
293    Array(Vec<Expr>),
294    Dict(Vec<(String, Expr)>),
295    IfExpr {
296        condition: Box<Expr>,
297        then_expr: Box<Expr>,
298        else_expr: Box<Expr>,
299    },
300    /// Anonymous function expression: `fn(params) { body }`.
301    /// Captures the referenced free variables from the enclosing
302    /// scope when evaluated; see the evaluator for capture rules.
303    Lambda {
304        params: Vec<Parameter>,
305        body: Vec<Stmt>,
306    },
307    /// `match scrutinee { pat => body, ... }` — checks each arm
308    /// top-to-bottom, evaluates the first matching arm's body,
309    /// and returns its value. Raises a runtime error if no arm
310    /// matches (exhaustiveness isn't checked statically in v1).
311    Match {
312        scrutinee: Box<Expr>,
313        arms: Vec<MatchArm>,
314    },
315
316    /// `try <expr>` — inspect a Result-shaped enum variant.
317    /// If `<expr>` evaluates to an `Ok(value)`-shaped variant,
318    /// unwrap to `value`. If it evaluates to an `Err(...)`-shaped
319    /// variant, short-circuit the enclosing function's return
320    /// with that value (same mechanism as a `return` statement).
321    /// At top-level scope (no enclosing fn) or on a non-Result
322    /// scrutinee, `try` raises a runtime error.
323    ///
324    /// Desugars roughly to the match:
325    /// ```text
326    /// match <expr> {
327    ///     Ok(v) => v,
328    ///     Err(_) => return <expr>,
329    /// }
330    /// ```
331    /// but is its own AST node so each engine can compile it
332    /// directly without paying the pattern-construction cost.
333    Try(Box<Expr>),
334}
335
336#[derive(Debug, Clone)]
337pub struct MatchArm {
338    pub pattern: Pattern,
339    /// Optional guard expression — evaluated after the pattern
340    /// matches. A `false` guard skips to the next arm.
341    pub guard: Option<Expr>,
342    pub body: Expr,
343    pub line: u32,
344}
345
346/// A pattern in a `match` arm. Structurally mirrors the runtime `Value` enum
347/// so each variant's matcher reads as "does this value fit here?".
348#[derive(Debug, Clone)]
349pub enum Pattern {
350    /// Matches a specific value verbatim: `1`, `"foo"`, `true`,
351    /// `false`, `none`.
352    Literal(LiteralPattern),
353    /// `_` — matches anything, binds nothing.
354    Wildcard,
355    /// Value-shaped bare identifier — matches anything, binds
356    /// the value to this name for the arm's body.
357    Binding(String),
358    /// `Type::Variant` / `Type::Variant(...)` / `Type::Variant { ... }`,
359    /// optionally namespaced via `ns.Type::Variant(...)`.
360    EnumVariant {
361        namespace: Option<String>,
362        type_name: String,
363        variant: String,
364        payload: VariantPatternPayload,
365    },
366    /// `Type { field: pat, field, .. }` destructures a struct,
367    /// optionally namespaced via `ns.Type { ... }`.
368    Struct {
369        namespace: Option<String>,
370        type_name: String,
371        fields: Vec<(String, Pattern)>,
372        rest: bool,
373    },
374    /// `[a, b, ..rest]` destructures an array.
375    Array {
376        elements: Vec<Pattern>,
377        rest: Option<ArrayRest>,
378    },
379    /// `p1 | p2 | p3` — match if any alternative matches. Every
380    /// alternative must introduce the same set of bindings.
381    Or(Vec<Pattern>),
382}
383
384impl Pattern {
385    /// Return every value binding introduced by this pattern in stable name
386    /// order. Duplicate occurrences collapse to one name; valid or-patterns
387    /// therefore expose the same set regardless of alternative order or shape.
388    pub fn binding_names(&self) -> BTreeSet<String> {
389        let mut names = BTreeSet::new();
390        self.collect_binding_names(&mut names);
391        names
392    }
393
394    /// Return every namespace identifier used by a namespaced type pattern,
395    /// including references nested inside tuple/struct/array/or patterns.
396    pub fn namespace_names(&self) -> BTreeSet<String> {
397        let mut names = BTreeSet::new();
398        self.collect_namespace_names(&mut names);
399        names
400    }
401
402    fn collect_namespace_names(&self, names: &mut BTreeSet<String>) {
403        match self {
404            Self::EnumVariant {
405                namespace, payload, ..
406            } => {
407                if let Some(namespace) = namespace {
408                    names.insert(namespace.clone());
409                }
410                match payload {
411                    VariantPatternPayload::Unit => {}
412                    VariantPatternPayload::Tuple(patterns) => {
413                        for pattern in patterns {
414                            pattern.collect_namespace_names(names);
415                        }
416                    }
417                    VariantPatternPayload::Struct { fields, .. } => {
418                        for (_, pattern) in fields {
419                            pattern.collect_namespace_names(names);
420                        }
421                    }
422                }
423            }
424            Self::Struct {
425                namespace, fields, ..
426            } => {
427                if let Some(namespace) = namespace {
428                    names.insert(namespace.clone());
429                }
430                for (_, pattern) in fields {
431                    pattern.collect_namespace_names(names);
432                }
433            }
434            Self::Array { elements, .. } | Self::Or(elements) => {
435                for pattern in elements {
436                    pattern.collect_namespace_names(names);
437                }
438            }
439            Self::Literal(_) | Self::Wildcard | Self::Binding(_) => {}
440        }
441    }
442
443    fn collect_binding_names(&self, names: &mut BTreeSet<String>) {
444        match self {
445            Self::Binding(name) => {
446                names.insert(name.clone());
447            }
448            Self::EnumVariant { payload, .. } => match payload {
449                VariantPatternPayload::Unit => {}
450                VariantPatternPayload::Tuple(patterns) => {
451                    for pattern in patterns {
452                        pattern.collect_binding_names(names);
453                    }
454                }
455                VariantPatternPayload::Struct { fields, .. } => {
456                    for (_, pattern) in fields {
457                        pattern.collect_binding_names(names);
458                    }
459                }
460            },
461            Self::Struct { fields, .. } => {
462                for (_, pattern) in fields {
463                    pattern.collect_binding_names(names);
464                }
465            }
466            Self::Array { elements, rest } => {
467                for pattern in elements {
468                    pattern.collect_binding_names(names);
469                }
470                if let Some(ArrayRest::Named(name)) = rest {
471                    names.insert(name.clone());
472                }
473            }
474            Self::Or(alternatives) => {
475                for pattern in alternatives {
476                    pattern.collect_binding_names(names);
477                }
478            }
479            Self::Literal(_) | Self::Wildcard => {}
480        }
481    }
482}
483
484#[derive(Debug, Clone)]
485pub enum LiteralPattern {
486    /// Integer literal pattern (e.g. `match x { 1 => ... }`).
487    /// Added in phase 6 alongside `Value::Int`.
488    Int(i64),
489    Number(f64),
490    Str(String),
491    Bool(bool),
492    None,
493}
494
495#[derive(Debug, Clone)]
496pub enum VariantPatternPayload {
497    Unit,
498    Tuple(Vec<Pattern>),
499    Struct {
500        fields: Vec<(String, Pattern)>,
501        rest: bool,
502    },
503}
504
505/// What `..rest` does at the tail of an array pattern.
506#[derive(Debug, Clone)]
507pub enum ArrayRest {
508    /// `..` — matches any remaining elements, binds nothing.
509    Ignored,
510    /// `..name` — captures remaining elements under a value-shaped name.
511    Named(String),
512}
513
514#[derive(Debug, Clone, Copy)]
515pub enum BinOp {
516    Add,
517    Sub,
518    Mul,
519    Div,
520    Mod,
521    Eq,
522    NotEq,
523    Lt,
524    Gt,
525    LtEq,
526    GtEq,
527    And,
528    Or,
529}
530
531#[derive(Debug, Clone, Copy)]
532pub enum UnaryOp {
533    Neg,
534    Not,
535}
536
537#[derive(Debug, Clone)]
538pub struct Stmt {
539    pub kind: StmtKind,
540    pub line: u32,
541    /// 1-indexed column where this statement starts. See
542    /// [`Expr::column`] — same niche-packed shape, same
543    /// purpose (caret rendering on runtime errors).
544    pub column: Option<core::num::NonZeroU32>,
545}
546
547impl Stmt {
548    /// Build a `Stmt` from its kind and a 1-indexed source
549    /// line, leaving `column` unset. See
550    /// [`Expr::line`].
551    pub fn line(kind: StmtKind, line: u32) -> Self {
552        Self {
553            kind,
554            line,
555            column: None,
556        }
557    }
558
559    /// Build a `Stmt` with a full source position.
560    pub fn at(kind: StmtKind, line: u32, column: Option<core::num::NonZeroU32>) -> Self {
561        Self { kind, line, column }
562    }
563}
564
565#[derive(Debug, Clone)]
566pub enum StmtKind {
567    /// `let NAME = expr` (value binding, mutable) and `const NAME
568    /// = expr` (constant binding, immutable). The `is_const` flag
569    /// flips enforcement at use/assign sites: reassigning a
570    /// constant is a compile-time error (the parser refuses any
571    /// assignment whose LHS is an all-uppercase identifier).
572    Let {
573        name: String,
574        value: Expr,
575        is_const: bool,
576    },
577    Assign {
578        target: AssignTarget,
579        op: AssignOp,
580        value: Expr,
581    },
582    If {
583        condition: Expr,
584        body: Vec<Stmt>,
585        else_ifs: Vec<(Expr, Vec<Stmt>)>,
586        else_body: Option<Vec<Stmt>>,
587    },
588    While {
589        condition: Expr,
590        body: Vec<Stmt>,
591    },
592    Repeat {
593        count: Expr,
594        body: Vec<Stmt>,
595    },
596    ForIn {
597        var: String,
598        iterable: Expr,
599        body: Vec<Stmt>,
600    },
601    FnDecl {
602        name: String,
603        params: Vec<Parameter>,
604        body: Vec<Stmt>,
605        visibility: Visibility,
606    },
607    /// `fn Type.method(self, ...) { body }` — declares a method
608    /// on a user-defined struct or enum. At call time
609    /// (`obj.method(...)`) the receiver is passed as the first
610    /// parameter (conventionally named `self`), followed by the
611    /// rest. A `ref` first parameter is an implicit mutable receiver
612    /// at the call site; an ordinary first parameter is read-only.
613    MethodDecl {
614        type_name: String,
615        method_name: String,
616        params: Vec<Parameter>,
617        body: Vec<Stmt>,
618    },
619    Return {
620        value: Option<Expr>,
621    },
622    Break,
623    Continue,
624    /// `use foo.bar.baz` — resolves the module named by the
625    /// dot-joined path through `NyblHost::resolve_module`,
626    /// evaluates its top-level statements in a fresh scope, and
627    /// injects its exports into the importer's scope. The shape
628    /// of the injection depends on the optional `items` / `alias`:
629    ///
630    /// - `use foo`                  — glob: all non-private
631    ///   top-level names land unqualified.
632    /// - `use foo.{a, b}`           — selective: only `a` and
633    ///   `b` land unqualified. `_`-prefixed names can be
634    ///   explicitly listed.
635    /// - `use foo as m`             — aliased: all exports
636    ///   (including `_`-prefixed) hang off a new `m` namespace
637    ///   value. Access via `m.a`, `m.Entity`, etc.
638    /// - `use foo.{a, b} as m`      — selective + aliased:
639    ///   `m` namespace contains only `a` and `b`.
640    ///
641    /// Glob imports skip `_`-prefixed top-level names (privacy
642    /// convention). Aliased and selective imports pass them
643    /// through when the user asks for them explicitly.
644    Use {
645        path: String,
646        /// `Some` iff the caller used the selective `.{a, b}`
647        /// form. The listed names are injected (whatever shape
648        /// they have); anything not listed is skipped.
649        items: Option<Vec<String>>,
650        /// `Some("m")` iff the caller used the `as m` form.
651        /// Exports are bound inside a `Value::Module` under this
652        /// name rather than in the caller's scope directly.
653        alias: Option<String>,
654    },
655    /// Explicit module export allow-list. Multiple statements are unioned.
656    /// At a directly executed root this statement is intentionally inert.
657    PublicSurface {
658        names: Vec<String>,
659    },
660    /// `struct Point { x, y }` — registers a user-defined struct
661    /// type with the listed field names. Field values get their
662    /// types from the construction site (`Point { x: 1, y: 2 }`).
663    StructDecl {
664        name: String,
665        fields: Vec<String>,
666    },
667    /// `enum Shape { Circle(radius), Rectangle { w, h }, Empty }`
668    /// — registers a user-defined sum type with named variants.
669    EnumDecl {
670        name: String,
671        variants: Vec<VariantDecl>,
672    },
673    ExprStmt(Expr),
674}
675
676/// Host-ABI visibility for a named function declaration.
677///
678/// `pub` deliberately affects only root instance entry points. It does not
679/// change Nybl's module export or in-language lookup rules.
680#[derive(Debug, Clone, Copy, PartialEq, Eq)]
681pub enum Visibility {
682    Private,
683    Public,
684}
685
686/// One variant of an `enum` declaration.
687#[derive(Debug, Clone, PartialEq)]
688pub struct VariantDecl {
689    pub name: String,
690    pub kind: VariantKind,
691}
692
693/// What shape a variant's payload takes.
694#[derive(Debug, Clone, PartialEq)]
695pub enum VariantKind {
696    /// No payload — `Empty`.
697    Unit,
698    /// Positional payload — `Circle(radius)`.
699    Tuple(Vec<String>),
700    /// Named payload — `Rectangle { width, height }`.
701    Struct(Vec<String>),
702}
703
704/// Runtime-side payload at a `T::Variant(...)` construction site.
705#[derive(Debug, Clone)]
706pub enum VariantPayload {
707    Unit,
708    Tuple(Vec<Expr>),
709    Struct(Vec<(String, Expr)>),
710}
711
712#[derive(Debug, Clone)]
713pub enum AssignTarget {
714    Variable(String),
715    Index {
716        object: Expr,
717        index: Expr,
718    },
719    /// Assignment to a struct field: `obj.field = v`. The object may itself
720    /// be a field/index chain so long as the complete place is rooted in a
721    /// mutable binding.
722    Field {
723        object: Expr,
724        field: String,
725    },
726}
727
728#[derive(Debug, Clone, Copy)]
729pub enum AssignOp {
730    Eq,
731    AddEq,
732    SubEq,
733    MulEq,
734    DivEq,
735    ModEq,
736}
737
738// ─── Parser ────────────────────────────────────────────────────────────────
739
740const MAX_PARSE_DEPTH: usize = 128;
741
742pub fn parse(tokens: Vec<SpannedToken>) -> Result<Vec<Stmt>, NyblError> {
743    let mut parser = Parser::new(tokens);
744    let program = parser.parse_program()?;
745    reject_value_receivers_calling_ref_methods(&program)?;
746    Ok(program)
747}
748
749#[derive(Default)]
750struct ParsedRefMethodCollector {
751    methods_by_type: BTreeMap<String, BTreeSet<String>>,
752}
753
754impl crate::ast_visit::DeclarationSiteVisitor for ParsedRefMethodCollector {
755    fn visit_struct(&mut self, _name: &str, _fields: &[String], _stmt: &Stmt) {}
756
757    fn visit_enum(&mut self, _name: &str, _variants: &[VariantDecl], _stmt: &Stmt) {}
758
759    fn visit_method(
760        &mut self,
761        type_name: &str,
762        method_name: &str,
763        params: &[Parameter],
764        _body: &[Stmt],
765        _stmt: &Stmt,
766    ) {
767        if params
768            .first()
769            .is_some_and(|param| param.mode == ParamMode::Ref)
770        {
771            self.methods_by_type
772                .entry(type_name.to_string())
773                .or_default()
774                .insert(method_name.to_string());
775        }
776    }
777}
778
779struct ParsedValueReceiverValidator<'methods> {
780    ref_methods_by_type: &'methods BTreeMap<String, BTreeSet<String>>,
781    error: Option<NyblError>,
782}
783
784impl crate::ast_visit::DeclarationSiteVisitor for ParsedValueReceiverValidator<'_> {
785    fn visit_struct(&mut self, _name: &str, _fields: &[String], _stmt: &Stmt) {}
786
787    fn visit_enum(&mut self, _name: &str, _variants: &[VariantDecl], _stmt: &Stmt) {}
788
789    fn visit_method(
790        &mut self,
791        type_name: &str,
792        _method_name: &str,
793        params: &[Parameter],
794        body: &[Stmt],
795        _stmt: &Stmt,
796    ) {
797        if self.error.is_some() {
798            return;
799        }
800        let Some(receiver) = params
801            .first()
802            .filter(|param| param.mode == ParamMode::Value)
803            .map(|param| param.name.as_str())
804        else {
805            return;
806        };
807        let Some(ref_methods) = self.ref_methods_by_type.get(type_name) else {
808            return;
809        };
810        if let Some(line) = value_receiver_mutation_line(body, receiver, false, ref_methods) {
811            self.error = Some(value_receiver_mutation_error(receiver, line));
812        }
813    }
814}
815
816fn reject_value_receivers_calling_ref_methods(program: &[Stmt]) -> Result<(), NyblError> {
817    let mut collector = ParsedRefMethodCollector::default();
818    crate::ast_visit::visit_declaration_sites(program, &mut collector);
819
820    let mut validator = ParsedValueReceiverValidator {
821        ref_methods_by_type: &collector.methods_by_type,
822        error: None,
823    };
824    crate::ast_visit::visit_declaration_sites(program, &mut validator);
825    if let Some(error) = validator.error {
826        return Err(error);
827    }
828    Ok(())
829}
830
831#[cfg(test)]
832mod ref_method_validation_tests {
833    use core::fmt::Write;
834
835    use super::*;
836
837    fn parse_source(source: &str) -> Result<Vec<Stmt>, NyblError> {
838        parse(crate::lexer::lex(source).expect("source should lex"))
839    }
840
841    #[test]
842    fn value_receiver_cannot_call_later_declared_ref_method() {
843        let error = parse_source(
844            r#"struct Counter { n }
845fn Counter.call_bump(self) { self.bump() }
846fn Counter.bump(ref self) { self.n = self.n + 1 }"#,
847        )
848        .expect_err("the value receiver should be rejected");
849
850        assert_eq!(error.message, "can't mutate value receiver `self`");
851        assert_eq!(error.line, Some(2));
852    }
853
854    #[test]
855    fn ref_method_names_are_scoped_to_their_declaring_type() {
856        parse_source(
857            r#"struct Counter { n }
858struct Other { n }
859fn Counter.call_bump(self) { self.bump() }
860fn Other.bump(ref self) { self.n = self.n + 1 }"#,
861        )
862        .expect("a ref method on another type must not taint this receiver");
863    }
864
865    #[test]
866    fn validates_thousands_of_method_declarations() {
867        const METHOD_PAIRS: usize = 2_048;
868
869        let mut source = String::from("struct Counter { n }\n");
870        for index in 0..METHOD_PAIRS {
871            writeln!(source, "fn Counter.value_{index}(self) {{ return self.n }}").unwrap();
872            writeln!(
873                source,
874                "fn Counter.ref_{index}(ref self) {{ self.n = self.n + 1 }}"
875            )
876            .unwrap();
877        }
878
879        parse_source(&source)
880            .expect("method-heavy source should validate without quadratic rescans");
881    }
882}
883
884struct Parser {
885    tokens: Vec<SpannedToken>,
886    pos: usize,
887    depth: usize,
888    /// When false, `Ident { ... }` at expression position is
889    /// *not* parsed as a struct literal — the `{` is left for the
890    /// enclosing control-flow construct (e.g. `if foo { body }`,
891    /// `for x in arr { body }`). Flipped off while parsing `if`
892    /// / `while` conditions and `for-in` iterables.
893    allow_struct_literal: bool,
894    block_depth: usize,
895}
896
897impl Parser {
898    fn new(tokens: Vec<SpannedToken>) -> Self {
899        Self {
900            tokens,
901            pos: 0,
902            depth: 0,
903            allow_struct_literal: true,
904            block_depth: 0,
905        }
906    }
907
908    fn enter(&mut self) -> Result<(), NyblError> {
909        if !self.try_enter() {
910            return Err(self.too_deep());
911        }
912        Ok(())
913    }
914
915    /// Charge one level of the parse-depth budget. Chain loops use this
916    /// directly so their frames don't hold an extra `Result` temporary:
917    /// they run once per precedence level of every nested expression.
918    fn try_enter(&mut self) -> bool {
919        if self.depth >= MAX_PARSE_DEPTH {
920            return false;
921        }
922        self.depth += 1;
923        true
924    }
925
926    #[cold]
927    #[inline(never)]
928    fn too_deep(&self) -> NyblError {
929        self.error(self.peek_line(), "Code is nested too deeply")
930    }
931
932    fn leave(&mut self) {
933        self.depth -= 1;
934    }
935
936    fn peek(&self) -> &Token {
937        self.tokens
938            .get(self.pos)
939            .map(|t| &t.token)
940            .unwrap_or(&Token::Eof)
941    }
942
943    fn peek_line(&self) -> u32 {
944        self.tokens.get(self.pos).map(|t| t.line).unwrap_or(0)
945    }
946
947    /// 1-indexed column of the current token's first character.
948    /// Used for parse-error reporting so the caret under the
949    /// offending line points at the right place.
950    fn peek_column(&self) -> u32 {
951        self.tokens.get(self.pos).map(|t| t.column).unwrap_or(0)
952    }
953
954    /// Grab both the line and the niche-packed column of the
955    /// current token in one shot. Shorthand used at the head
956    /// of parse fns that build an `Expr` / `Stmt` — rather than
957    /// calling `peek_line()` then having to re-fetch column
958    /// later, capture the source position once.
959    fn peek_pos(&self) -> (u32, Option<core::num::NonZeroU32>) {
960        let tok = self.tokens.get(self.pos);
961        let line = tok.map(|t| t.line).unwrap_or(0);
962        let column = tok.map(|t| t.column).and_then(core::num::NonZeroU32::new);
963        (line, column)
964    }
965
966    fn peek_at(&self, offset: usize) -> &Token {
967        self.tokens
968            .get(self.pos + offset)
969            .map(|t| &t.token)
970            .unwrap_or(&Token::Eof)
971    }
972
973    /// Run `f` with an explicit struct-literal policy, restoring the prior
974    /// value even when `f` returns an error. Restricted control-flow heads use
975    /// `false`; unambiguous delimiter interiors use `true`.
976    fn with_struct_literal<F, R>(&mut self, allowed: bool, f: F) -> R
977    where
978        F: FnOnce(&mut Self) -> R,
979    {
980        let saved = self.allow_struct_literal;
981        self.allow_struct_literal = allowed;
982        let result = f(self);
983        self.allow_struct_literal = saved;
984        result
985    }
986
987    /// Keep a control-flow body's opening brace from being consumed as a
988    /// struct literal belonging to the preceding condition or iterable.
989    fn without_struct_literal<F, R>(&mut self, f: F) -> R
990    where
991        F: FnOnce(&mut Self) -> R,
992    {
993        self.with_struct_literal(false, f)
994    }
995
996    fn advance(&mut self) -> &Token {
997        let tok = self
998            .tokens
999            .get(self.pos)
1000            .map(|t| &t.token)
1001            .unwrap_or(&Token::Eof);
1002        if self.pos < self.tokens.len() {
1003            self.pos += 1;
1004        }
1005        tok
1006    }
1007
1008    /// Consume and return the current token without cloning heap payloads.
1009    ///
1010    /// Callers first inspect [`Self::peek`] to decide whether the token is
1011    /// valid in context. That keeps error paths positioned on the offending
1012    /// token while successful paths can transfer owned strings and vectors
1013    /// directly into the AST.
1014    fn take(&mut self) -> Token {
1015        if self.pos >= self.tokens.len() {
1016            return Token::Eof;
1017        }
1018
1019        let token = core::mem::replace(&mut self.tokens[self.pos].token, Token::Eof);
1020        self.pos += 1;
1021        token
1022    }
1023
1024    fn is_at_end(&self) -> bool {
1025        matches!(self.peek(), Token::Eof)
1026    }
1027
1028    fn expect(&mut self, expected: &Token) -> Result<u32, NyblError> {
1029        let (line, _column) = self.peek_pos();
1030        if self.peek() == expected {
1031            self.advance();
1032            Ok(line)
1033        } else {
1034            Err(self.error(
1035                line,
1036                format!(
1037                    "Expected `{}` but found `{}`",
1038                    fmt_token(expected),
1039                    fmt_token(self.peek())
1040                ),
1041            ))
1042        }
1043    }
1044
1045    fn expect_ident(&mut self) -> Result<(String, u32), NyblError> {
1046        let (line, _column) = self.peek_pos();
1047        if matches!(self.peek(), Token::Ident(_)) {
1048            let Token::Ident(name) = self.take() else {
1049                unreachable!("identifier variant checked before taking token")
1050            };
1051            Ok((name, line))
1052        } else if let Some(keyword) = self.peek().keyword_name() {
1053            Err(NyblError::reserved_word(keyword, line, self.peek_column()))
1054        } else {
1055            Err(self.error(
1056                line,
1057                format!("Expected a name but found `{}`", fmt_token(self.peek())),
1058            ))
1059        }
1060    }
1061
1062    /// Parse a function-style parameter list and enforce the same identifier
1063    /// contract at every declaration form that owns one. Keeping this in one
1064    /// place prevents anonymous functions from drifting away from named
1065    /// functions and methods again.
1066    fn parse_parameters(&mut self, site: &str) -> Result<Vec<Parameter>, NyblError> {
1067        self.expect(&Token::LParen)?;
1068
1069        let mut params = Vec::new();
1070        if !matches!(self.peek(), Token::RParen) {
1071            loop {
1072                let mode = if matches!(self.peek(), Token::DotDot) {
1073                    self.advance();
1074                    ParamMode::Rest
1075                } else if matches!(self.peek(), Token::Ref) {
1076                    self.advance();
1077                    ParamMode::Ref
1078                } else {
1079                    ParamMode::Value
1080                };
1081                let (_, column) = self.peek_pos();
1082                let (param, line) = self.expect_ident()?;
1083                ensure_value_name_at(&param, site, line, column)?;
1084                if mode == ParamMode::Rest
1085                    && params
1086                        .iter()
1087                        .any(|existing: &Parameter| existing.name == param)
1088                {
1089                    return Err(self.error(
1090                        line,
1091                        format!("rest parameter `{param}` must have a distinct name"),
1092                    ));
1093                }
1094                params.push(Parameter { name: param, mode });
1095
1096                if !matches!(self.peek(), Token::Comma) {
1097                    break;
1098                }
1099                if mode == ParamMode::Rest {
1100                    return Err(self.error(line, "a rest parameter must be the final parameter"));
1101                }
1102                self.advance();
1103            }
1104        }
1105
1106        self.expect(&Token::RParen)?;
1107        Ok(params)
1108    }
1109
1110    fn skip_semicolons(&mut self) {
1111        while matches!(self.peek(), Token::Semicolon) {
1112            self.advance();
1113        }
1114    }
1115
1116    fn error(&self, line: u32, message: impl Into<String>) -> NyblError {
1117        // Use the current token's column; if we've already
1118        // advanced past the token that triggered the complaint,
1119        // column 0 (unknown) is the honest answer rather than
1120        // silently misreporting.
1121        let column = if self.tokens.get(self.pos).map(|t| t.line) == Some(line) {
1122            Some(self.peek_column())
1123        } else {
1124            None
1125        };
1126        NyblError {
1127            line: Some(line),
1128            column,
1129            message: message.into(),
1130            friendly_hint: None,
1131            source_context: None,
1132            is_fatal: false,
1133            is_try_return: false,
1134        }
1135    }
1136
1137    // ─── Program & Blocks ──────────────────────────────────────────────
1138
1139    fn parse_program(&mut self) -> Result<Vec<Stmt>, NyblError> {
1140        let mut stmts = Vec::new();
1141        let mut public_names = BTreeSet::new();
1142        self.skip_semicolons();
1143        while !self.is_at_end() {
1144            let stmt = self.parse_statement()?;
1145            if let StmtKind::PublicSurface { names } = &stmt.kind {
1146                for name in names {
1147                    if !public_names.insert(name.clone()) {
1148                        return Err(self.error(
1149                            stmt.line,
1150                            format!("duplicate public name `{name}` across `pub` lists"),
1151                        ));
1152                    }
1153                }
1154            }
1155            stmts.push(stmt);
1156            self.skip_semicolons();
1157        }
1158        Ok(stmts)
1159    }
1160
1161    fn parse_block(&mut self) -> Result<Vec<Stmt>, NyblError> {
1162        self.enter()?;
1163        self.expect(&Token::LBrace)?;
1164        self.block_depth += 1;
1165        let result = (|| {
1166            let mut stmts = Vec::new();
1167            self.skip_semicolons();
1168            while !matches!(self.peek(), Token::RBrace | Token::Eof) {
1169                stmts.push(self.with_struct_literal(true, |p| p.parse_statement())?);
1170                self.skip_semicolons();
1171            }
1172            self.expect(&Token::RBrace)?;
1173            Ok(stmts)
1174        })();
1175        self.block_depth -= 1;
1176        self.leave();
1177        result
1178    }
1179
1180    // ─── Statements ────────────────────────────────────────────────────
1181
1182    fn parse_statement(&mut self) -> Result<Stmt, NyblError> {
1183        let (line, column) = self.peek_pos();
1184        match self.peek() {
1185            Token::Let => self.parse_let(),
1186            Token::Const => self.parse_const(),
1187            Token::If => self.parse_if_stmt(),
1188            Token::While => self.parse_while(),
1189            Token::For => self.parse_for(),
1190            Token::Repeat => self.parse_repeat(),
1191            // `fn name(...)` is a declaration; `fn(...)` is a
1192            // lambda expression at statement position — delegate
1193            // to the expression parser so it becomes an `ExprStmt`.
1194            Token::Fn
1195                if matches!(self.peek_at(1), Token::Ident(_))
1196                    || self.peek_at(1).keyword_name().is_some() =>
1197            {
1198                self.parse_fn_decl(Visibility::Private)
1199            }
1200            Token::Pub if matches!(self.peek_at(1), Token::LBrace) => self.parse_public_surface(),
1201            Token::Pub => self.parse_public_fn_decl(),
1202            Token::Return => self.parse_return(),
1203            Token::Break => {
1204                self.advance();
1205                Ok(Stmt {
1206                    kind: StmtKind::Break,
1207                    line,
1208                    column,
1209                })
1210            }
1211            Token::Continue => {
1212                self.advance();
1213                Ok(Stmt {
1214                    kind: StmtKind::Continue,
1215                    line,
1216                    column,
1217                })
1218            }
1219            Token::Use => self.parse_use(),
1220            Token::Struct => self.parse_struct_decl(),
1221            Token::Enum => self.parse_enum_decl(),
1222            _ => self.parse_expr_or_assign(),
1223        }
1224    }
1225
1226    fn parse_struct_decl(&mut self) -> Result<Stmt, NyblError> {
1227        let (line, column) = self.peek_pos();
1228        self.advance(); // consume `struct`
1229        let (name, name_line) = self.expect_ident()?;
1230        ensure_type_name(&name, "`struct` declaration", name_line)?;
1231        self.expect(&Token::LBrace)?;
1232        let mut fields = Vec::new();
1233        if !matches!(self.peek(), Token::RBrace) {
1234            let (f, f_line) = self.expect_ident()?;
1235            ensure_value_name(&f, "struct field", f_line)?;
1236            fields.push(f);
1237            while matches!(self.peek(), Token::Comma) {
1238                self.advance();
1239                if matches!(self.peek(), Token::RBrace) {
1240                    break; // trailing comma
1241                }
1242                let (f, f_line) = self.expect_ident()?;
1243                ensure_value_name(&f, "struct field", f_line)?;
1244                fields.push(f);
1245            }
1246        }
1247        self.expect(&Token::RBrace)?;
1248        Ok(Stmt {
1249            kind: StmtKind::StructDecl { name, fields },
1250            line,
1251            column,
1252        })
1253    }
1254
1255    fn parse_enum_decl(&mut self) -> Result<Stmt, NyblError> {
1256        let (line, column) = self.peek_pos();
1257        self.advance(); // consume `enum`
1258        let (name, name_line) = self.expect_ident()?;
1259        ensure_type_name(&name, "`enum` declaration", name_line)?;
1260        self.expect(&Token::LBrace)?;
1261        let mut variants: Vec<VariantDecl> = Vec::new();
1262        if !matches!(self.peek(), Token::RBrace) {
1263            variants.push(self.parse_variant_decl()?);
1264            while matches!(self.peek(), Token::Comma) {
1265                self.advance();
1266                if matches!(self.peek(), Token::RBrace) {
1267                    break; // trailing comma
1268                }
1269                variants.push(self.parse_variant_decl()?);
1270            }
1271        }
1272        self.expect(&Token::RBrace)?;
1273        Ok(Stmt {
1274            kind: StmtKind::EnumDecl { name, variants },
1275            line,
1276            column,
1277        })
1278    }
1279
1280    fn parse_variant_decl(&mut self) -> Result<VariantDecl, NyblError> {
1281        let (name, name_line) = self.expect_ident()?;
1282        ensure_type_name(&name, "enum variant", name_line)?;
1283        let kind = match self.peek() {
1284            Token::LParen => {
1285                self.advance();
1286                let mut fields: Vec<String> = Vec::new();
1287                if !matches!(self.peek(), Token::RParen) {
1288                    let (f, f_line) = self.expect_ident()?;
1289                    ensure_value_name(&f, "variant payload field", f_line)?;
1290                    fields.push(f);
1291                    while matches!(self.peek(), Token::Comma) {
1292                        self.advance();
1293                        if matches!(self.peek(), Token::RParen) {
1294                            break;
1295                        }
1296                        let (f, f_line) = self.expect_ident()?;
1297                        ensure_value_name(&f, "variant payload field", f_line)?;
1298                        fields.push(f);
1299                    }
1300                }
1301                self.expect(&Token::RParen)?;
1302                VariantKind::Tuple(fields)
1303            }
1304            Token::LBrace => {
1305                self.advance();
1306                let mut fields: Vec<String> = Vec::new();
1307                if !matches!(self.peek(), Token::RBrace) {
1308                    let (f, f_line) = self.expect_ident()?;
1309                    ensure_value_name(&f, "variant payload field", f_line)?;
1310                    fields.push(f);
1311                    while matches!(self.peek(), Token::Comma) {
1312                        self.advance();
1313                        if matches!(self.peek(), Token::RBrace) {
1314                            break;
1315                        }
1316                        let (f, f_line) = self.expect_ident()?;
1317                        ensure_value_name(&f, "variant payload field", f_line)?;
1318                        fields.push(f);
1319                    }
1320                }
1321                self.expect(&Token::RBrace)?;
1322                VariantKind::Struct(fields)
1323            }
1324            _ => VariantKind::Unit,
1325        };
1326        Ok(VariantDecl { name, kind })
1327    }
1328
1329    fn parse_use(&mut self) -> Result<Stmt, NyblError> {
1330        let (line, column) = self.peek_pos();
1331        self.advance(); // consume `use`
1332        let (first, first_line) = self.expect_ident()?;
1333        ensure_value_name(&first, "module path segment", first_line)?;
1334        let mut path = first;
1335
1336        // Consume dotted path segments. Breaks early if we see a
1337        // `.{` — the selective-import opener.
1338        loop {
1339            if !matches!(self.peek(), Token::Dot) {
1340                break;
1341            }
1342            // Peek ahead one more token: `.{` opens selective
1343            // imports; `.ident` continues the path.
1344            if matches!(self.peek_at(1), Token::LBrace) {
1345                break;
1346            }
1347            self.advance(); // consume '.'
1348            let (seg, seg_line) = self.expect_ident()?;
1349            ensure_value_name(&seg, "module path segment", seg_line)?;
1350            path.push('.');
1351            path.push_str(&seg);
1352        }
1353
1354        // Selective import: `use foo.bar.{a, b, c}`.
1355        let items = if matches!(self.peek(), Token::Dot) {
1356            self.advance(); // '.'
1357            self.expect(&Token::LBrace)?;
1358            let mut list: Vec<String> = Vec::new();
1359            if !matches!(self.peek(), Token::RBrace) {
1360                let (name, _) = self.expect_ident()?;
1361                list.push(name);
1362                while matches!(self.peek(), Token::Comma) {
1363                    self.advance();
1364                    if matches!(self.peek(), Token::RBrace) {
1365                        break; // trailing comma
1366                    }
1367                    let (name, _) = self.expect_ident()?;
1368                    list.push(name);
1369                }
1370            }
1371            self.expect(&Token::RBrace)?;
1372            Some(list)
1373        } else {
1374            None
1375        };
1376
1377        // Optional `as alias`.
1378        let alias = if matches!(self.peek(), Token::As) {
1379            self.advance();
1380            let (name, name_line) = self.expect_ident()?;
1381            ensure_value_name(&name, "`use` alias", name_line)?;
1382            Some(name)
1383        } else {
1384            None
1385        };
1386
1387        Ok(Stmt {
1388            kind: StmtKind::Use { path, items, alias },
1389            line,
1390            column,
1391        })
1392    }
1393
1394    fn parse_public_surface(&mut self) -> Result<Stmt, NyblError> {
1395        let (line, column) = self.peek_pos();
1396        self.advance(); // consume `pub`
1397        if self.block_depth != 0 {
1398            return Err(self.error(line, "`pub { ... }` is only valid at the module root"));
1399        }
1400        self.expect(&Token::LBrace)?;
1401        let mut names = Vec::new();
1402        if !matches!(self.peek(), Token::RBrace) {
1403            loop {
1404                let (name, _) = self.expect_ident()?;
1405                if names.iter().any(|existing| existing == &name) {
1406                    return Err(self.error(line, format!("duplicate public name `{name}`")));
1407                }
1408                names.push(name);
1409                if !matches!(self.peek(), Token::Comma) {
1410                    break;
1411                }
1412                self.advance();
1413                if matches!(self.peek(), Token::RBrace) {
1414                    break;
1415                }
1416            }
1417        }
1418        self.expect(&Token::RBrace)?;
1419        Ok(Stmt {
1420            kind: StmtKind::PublicSurface { names },
1421            line,
1422            column,
1423        })
1424    }
1425
1426    fn parse_let(&mut self) -> Result<Stmt, NyblError> {
1427        let (line, column) = self.peek_pos();
1428        self.advance(); // consume 'let'
1429        let (name, _) = self.expect_ident()?;
1430        ensure_value_name(&name, "`let` binding", line)?;
1431        self.expect(&Token::Eq)?;
1432        let value = self.parse_expr()?;
1433        Ok(Stmt {
1434            kind: StmtKind::Let {
1435                name,
1436                value,
1437                is_const: false,
1438            },
1439            line,
1440            column,
1441        })
1442    }
1443
1444    /// `const NAME = expr` — immutable binding, SCREAMING_SNAKE_CASE
1445    /// name enforced. Shares the `StmtKind::Let` variant with a
1446    /// `is_const: true` flag — the runtime treats constants as
1447    /// let bindings that were parsed in a way that makes
1448    /// reassignment impossible (the parser rejects any `=` whose
1449    /// LHS is an all-uppercase identifier).
1450    fn parse_const(&mut self) -> Result<Stmt, NyblError> {
1451        let (line, column) = self.peek_pos();
1452        self.advance(); // consume 'const'
1453        let (name, _) = self.expect_ident()?;
1454        ensure_constant_name(&name, "`const` declaration", line)?;
1455        self.expect(&Token::Eq)?;
1456        let value = self.parse_expr()?;
1457        Ok(Stmt {
1458            kind: StmtKind::Let {
1459                name,
1460                value,
1461                is_const: true,
1462            },
1463            line,
1464            column,
1465        })
1466    }
1467
1468    fn parse_if_stmt(&mut self) -> Result<Stmt, NyblError> {
1469        let (line, column) = self.peek_pos();
1470        self.advance(); // consume 'if'
1471        let condition = self.without_struct_literal(|p| p.parse_expr())?;
1472        let body = self.parse_block()?;
1473
1474        let mut else_ifs = Vec::new();
1475        let mut else_body = None;
1476
1477        while matches!(self.peek(), Token::Else) {
1478            self.advance(); // consume 'else'
1479            if matches!(self.peek(), Token::If) {
1480                self.advance(); // consume 'if'
1481                let cond = self.without_struct_literal(|p| p.parse_expr())?;
1482                let block = self.parse_block()?;
1483                else_ifs.push((cond, block));
1484            } else {
1485                else_body = Some(self.parse_block()?);
1486                break;
1487            }
1488        }
1489
1490        Ok(Stmt {
1491            kind: StmtKind::If {
1492                condition,
1493                body,
1494                else_ifs,
1495                else_body,
1496            },
1497            line,
1498            column,
1499        })
1500    }
1501
1502    fn parse_while(&mut self) -> Result<Stmt, NyblError> {
1503        let (line, column) = self.peek_pos();
1504        self.advance(); // consume 'while'
1505        let condition = self.without_struct_literal(|p| p.parse_expr())?;
1506        let body = self.parse_block()?;
1507        Ok(Stmt {
1508            kind: StmtKind::While { condition, body },
1509            line,
1510            column,
1511        })
1512    }
1513
1514    fn parse_for(&mut self) -> Result<Stmt, NyblError> {
1515        let (line, column) = self.peek_pos();
1516        self.advance(); // consume 'for'
1517        let (var, var_line) = self.expect_ident()?;
1518        ensure_value_name(&var, "`for` loop variable", var_line)?;
1519        self.expect(&Token::In)?;
1520        let iterable = self.without_struct_literal(|p| p.parse_expr())?;
1521        let body = self.parse_block()?;
1522        Ok(Stmt {
1523            kind: StmtKind::ForIn {
1524                var,
1525                iterable,
1526                body,
1527            },
1528            line,
1529            column,
1530        })
1531    }
1532
1533    fn parse_repeat(&mut self) -> Result<Stmt, NyblError> {
1534        let (line, column) = self.peek_pos();
1535        self.advance(); // consume 'repeat'
1536        let count = self.without_struct_literal(|p| p.parse_expr())?;
1537        let body = self.parse_block()?;
1538        Ok(Stmt {
1539            kind: StmtKind::Repeat { count, body },
1540            line,
1541            column,
1542        })
1543    }
1544
1545    fn parse_public_fn_decl(&mut self) -> Result<Stmt, NyblError> {
1546        let (line, column) = self.peek_pos();
1547        self.advance();
1548        if self.block_depth != 0 {
1549            return Err(self.error(line, "`pub fn` is only meaningful at the program root"));
1550        }
1551        if !matches!(self.peek(), Token::Fn) {
1552            return Err(self.error(line, "`pub` must be followed by `fn`"));
1553        }
1554        if !matches!(self.peek_at(1), Token::Ident(_)) && self.peek_at(1).keyword_name().is_none() {
1555            return Err(self.error(line, "`pub` can only mark a named function"));
1556        }
1557        let mut stmt = self.parse_fn_decl(Visibility::Public)?;
1558        stmt.line = line;
1559        stmt.column = column;
1560        Ok(stmt)
1561    }
1562
1563    fn parse_fn_decl(&mut self, visibility: Visibility) -> Result<Stmt, NyblError> {
1564        let (line, column) = self.peek_pos();
1565        self.advance(); // consume 'fn'
1566        let (name, name_line) = self.expect_ident()?;
1567
1568        // Method declaration: `fn Type.method(...)`. The leading
1569        // ident is the receiver's type; the post-dot ident is the
1570        // method's name. Everything else matches a regular fn
1571        // decl.
1572        if matches!(self.peek(), Token::Dot) {
1573            if visibility == Visibility::Public {
1574                return Err(self.error(
1575                    line,
1576                    "`pub` can only mark a root named function, not a method",
1577                ));
1578            }
1579            ensure_type_name(&name, "method receiver", name_line)?;
1580            self.advance();
1581            let (method_name, method_line) = self.expect_ident()?;
1582            ensure_value_name(&method_name, "method name", method_line)?;
1583            let params = self.parse_parameters("method parameter")?;
1584            if params
1585                .first()
1586                .is_some_and(|param| param.mode == ParamMode::Rest)
1587            {
1588                return Err(self.error(line, "a method receiver cannot be a rest parameter"));
1589            }
1590            let body = self.parse_block()?;
1591            if let Some(receiver) = params
1592                .first()
1593                .filter(|param| param.mode == ParamMode::Value)
1594                .map(|param| param.name.as_str())
1595            {
1596                reject_value_receiver_mutation(&body, receiver)?;
1597            }
1598            return Ok(Stmt {
1599                kind: StmtKind::MethodDecl {
1600                    type_name: name,
1601                    method_name,
1602                    params,
1603                    body,
1604                },
1605                line,
1606                column,
1607            });
1608        }
1609
1610        ensure_value_name(&name, "`fn` declaration", name_line)?;
1611        let params = self.parse_parameters("function parameter")?;
1612        let body = self.parse_block()?;
1613        Ok(Stmt {
1614            kind: StmtKind::FnDecl {
1615                name,
1616                params,
1617                body,
1618                visibility,
1619            },
1620            line,
1621            column,
1622        })
1623    }
1624
1625    fn parse_return(&mut self) -> Result<Stmt, NyblError> {
1626        let (line, column) = self.peek_pos();
1627        self.advance(); // consume 'return'
1628        let value = if matches!(self.peek(), Token::Semicolon | Token::RBrace | Token::Eof) {
1629            None
1630        } else {
1631            Some(self.parse_expr()?)
1632        };
1633        Ok(Stmt {
1634            kind: StmtKind::Return { value },
1635            line,
1636            column,
1637        })
1638    }
1639
1640    fn parse_expr_or_assign(&mut self) -> Result<Stmt, NyblError> {
1641        let (line, column) = self.peek_pos();
1642        let expr = self.parse_expr()?;
1643
1644        let op = match self.peek() {
1645            Token::Eq => Some(AssignOp::Eq),
1646            Token::PlusEq => Some(AssignOp::AddEq),
1647            Token::MinusEq => Some(AssignOp::SubEq),
1648            Token::StarEq => Some(AssignOp::MulEq),
1649            Token::SlashEq => Some(AssignOp::DivEq),
1650            Token::PercentEq => Some(AssignOp::ModEq),
1651            _ => None,
1652        };
1653
1654        if let Some(op) = op {
1655            self.advance(); // consume assignment operator
1656            let target = expr_to_assign_target(expr, line)?;
1657            let value = self.parse_expr()?;
1658            Ok(Stmt {
1659                kind: StmtKind::Assign { target, op, value },
1660                line,
1661                column,
1662            })
1663        } else {
1664            Ok(Stmt {
1665                kind: StmtKind::ExprStmt(expr),
1666                line,
1667                column,
1668            })
1669        }
1670    }
1671
1672    // ─── Expressions ───────────────────────────────────────────────────
1673
1674    fn parse_expr(&mut self) -> Result<Expr, NyblError> {
1675        let expression = self.parse_or()?;
1676        if matches!(self.peek(), Token::DotDot) {
1677            let (line, column) = self.peek_pos();
1678            let mut error = NyblError::runtime_at(
1679                "`..` range syntax is not supported in expressions",
1680                line,
1681                column,
1682            );
1683            error.friendly_hint =
1684                Some("use `range(start, end)` instead, for example `range(0, 3)`.".to_string());
1685            return Err(error);
1686        }
1687        Ok(expression)
1688    }
1689
1690    fn parse_or(&mut self) -> Result<Expr, NyblError> {
1691        // Each chain link nests the AST one level deeper without recursing,
1692        // so it charges the parse-depth budget; all links are released when
1693        // the chain ends.
1694        let chain_base = self.depth;
1695        let mut left = self.parse_and()?;
1696        while matches!(self.peek(), Token::PipePipe) {
1697            let (line, column) = self.peek_pos();
1698            self.advance();
1699            if !self.try_enter() {
1700                return Err(self.too_deep());
1701            }
1702            let right = self.parse_and()?;
1703            left = Expr {
1704                kind: ExprKind::BinaryOp {
1705                    left: Box::new(left),
1706                    op: BinOp::Or,
1707                    right: Box::new(right),
1708                },
1709                line,
1710                column,
1711            };
1712        }
1713        self.depth = chain_base;
1714        Ok(left)
1715    }
1716
1717    fn parse_and(&mut self) -> Result<Expr, NyblError> {
1718        // Each chain link nests the AST one level deeper without recursing,
1719        // so it charges the parse-depth budget; all links are released when
1720        // the chain ends.
1721        let chain_base = self.depth;
1722        let mut left = self.parse_equality()?;
1723        while matches!(self.peek(), Token::AmpAmp) {
1724            let (line, column) = self.peek_pos();
1725            self.advance();
1726            if !self.try_enter() {
1727                return Err(self.too_deep());
1728            }
1729            let right = self.parse_equality()?;
1730            left = Expr {
1731                kind: ExprKind::BinaryOp {
1732                    left: Box::new(left),
1733                    op: BinOp::And,
1734                    right: Box::new(right),
1735                },
1736                line,
1737                column,
1738            };
1739        }
1740        self.depth = chain_base;
1741        Ok(left)
1742    }
1743
1744    fn parse_equality(&mut self) -> Result<Expr, NyblError> {
1745        // Each chain link nests the AST one level deeper without recursing,
1746        // so it charges the parse-depth budget; all links are released when
1747        // the chain ends.
1748        let chain_base = self.depth;
1749        let mut left = self.parse_comparison()?;
1750        while matches!(self.peek(), Token::EqEq | Token::BangEq) {
1751            let (line, column) = self.peek_pos();
1752            let op = if matches!(self.peek(), Token::EqEq) {
1753                BinOp::Eq
1754            } else {
1755                BinOp::NotEq
1756            };
1757            self.advance();
1758            if !self.try_enter() {
1759                return Err(self.too_deep());
1760            }
1761            let right = self.parse_comparison()?;
1762            left = Expr {
1763                kind: ExprKind::BinaryOp {
1764                    left: Box::new(left),
1765                    op,
1766                    right: Box::new(right),
1767                },
1768                line,
1769                column,
1770            };
1771        }
1772        self.depth = chain_base;
1773        Ok(left)
1774    }
1775
1776    fn parse_comparison(&mut self) -> Result<Expr, NyblError> {
1777        // Each chain link nests the AST one level deeper without recursing,
1778        // so it charges the parse-depth budget; all links are released when
1779        // the chain ends.
1780        let chain_base = self.depth;
1781        let mut left = self.parse_addition()?;
1782        while matches!(
1783            self.peek(),
1784            Token::Lt | Token::Gt | Token::LtEq | Token::GtEq
1785        ) {
1786            let (line, column) = self.peek_pos();
1787            let op = match self.peek() {
1788                Token::Lt => BinOp::Lt,
1789                Token::Gt => BinOp::Gt,
1790                Token::LtEq => BinOp::LtEq,
1791                _ => BinOp::GtEq,
1792            };
1793            self.advance();
1794            if !self.try_enter() {
1795                return Err(self.too_deep());
1796            }
1797            let right = self.parse_addition()?;
1798            left = Expr {
1799                kind: ExprKind::BinaryOp {
1800                    left: Box::new(left),
1801                    op,
1802                    right: Box::new(right),
1803                },
1804                line,
1805                column,
1806            };
1807        }
1808        self.depth = chain_base;
1809        Ok(left)
1810    }
1811
1812    fn parse_addition(&mut self) -> Result<Expr, NyblError> {
1813        // Each chain link nests the AST one level deeper without recursing,
1814        // so it charges the parse-depth budget; all links are released when
1815        // the chain ends.
1816        let chain_base = self.depth;
1817        let mut left = self.parse_multiply()?;
1818        while matches!(self.peek(), Token::Plus | Token::Minus) {
1819            let (line, column) = self.peek_pos();
1820            let op = if matches!(self.peek(), Token::Plus) {
1821                BinOp::Add
1822            } else {
1823                BinOp::Sub
1824            };
1825            self.advance();
1826            if !self.try_enter() {
1827                return Err(self.too_deep());
1828            }
1829            let right = self.parse_multiply()?;
1830            left = Expr {
1831                kind: ExprKind::BinaryOp {
1832                    left: Box::new(left),
1833                    op,
1834                    right: Box::new(right),
1835                },
1836                line,
1837                column,
1838            };
1839        }
1840        self.depth = chain_base;
1841        Ok(left)
1842    }
1843
1844    fn parse_multiply(&mut self) -> Result<Expr, NyblError> {
1845        // Each chain link nests the AST one level deeper without recursing,
1846        // so it charges the parse-depth budget; all links are released when
1847        // the chain ends.
1848        let chain_base = self.depth;
1849        let mut left = self.parse_unary()?;
1850        while matches!(self.peek(), Token::Star | Token::Slash | Token::Percent) {
1851            let (line, column) = self.peek_pos();
1852            let op = match self.peek() {
1853                Token::Star => BinOp::Mul,
1854                Token::Slash => BinOp::Div,
1855                _ => BinOp::Mod,
1856            };
1857            self.advance();
1858            if !self.try_enter() {
1859                return Err(self.too_deep());
1860            }
1861            let right = self.parse_unary()?;
1862            left = Expr {
1863                kind: ExprKind::BinaryOp {
1864                    left: Box::new(left),
1865                    op,
1866                    right: Box::new(right),
1867                },
1868                line,
1869                column,
1870            };
1871        }
1872        self.depth = chain_base;
1873        Ok(left)
1874    }
1875
1876    fn parse_unary(&mut self) -> Result<Expr, NyblError> {
1877        self.enter()?;
1878        let (line, column) = self.peek_pos();
1879        let result = match self.peek() {
1880            Token::Bang => {
1881                self.advance();
1882                let expr = self.parse_unary()?;
1883                Ok(Expr {
1884                    kind: ExprKind::UnaryOp {
1885                        op: UnaryOp::Not,
1886                        expr: Box::new(expr),
1887                    },
1888                    line,
1889                    column,
1890                })
1891            }
1892            Token::Minus => {
1893                self.advance();
1894                if matches!(self.peek(), Token::IntMinMagnitude) {
1895                    self.advance();
1896                    Ok(Expr {
1897                        kind: ExprKind::Int(i64::MIN),
1898                        line,
1899                        column,
1900                    })
1901                } else {
1902                    let expr = self.parse_unary()?;
1903                    Ok(Expr {
1904                        kind: ExprKind::UnaryOp {
1905                            op: UnaryOp::Neg,
1906                            expr: Box::new(expr),
1907                        },
1908                        line,
1909                        column,
1910                    })
1911                }
1912            }
1913            Token::Try => {
1914                // `try <expr>` binds tighter than binary ops but
1915                // looser than postfix (calls, methods, indexing),
1916                // mirroring Rust's `?`. Recursing into
1917                // `parse_unary` lets `try try foo()` parse as
1918                // `try (try foo())` without a special case.
1919                self.advance();
1920                let expr = self.parse_unary()?;
1921                Ok(Expr {
1922                    kind: ExprKind::Try(Box::new(expr)),
1923                    line,
1924                    column,
1925                })
1926            }
1927            _ => self.parse_postfix(),
1928        };
1929        self.leave();
1930        result
1931    }
1932
1933    fn parse_postfix(&mut self) -> Result<Expr, NyblError> {
1934        // Each chain link nests the AST one level deeper without recursing,
1935        // so it charges the parse-depth budget; all links are released when
1936        // the chain ends.
1937        let chain_base = self.depth;
1938        let mut expr = self.parse_primary()?;
1939
1940        loop {
1941            match self.peek() {
1942                Token::LParen => {
1943                    if !self.try_enter() {
1944                        return Err(self.too_deep());
1945                    }
1946                    let (line, column) = self.peek_pos();
1947                    self.advance();
1948                    let args = self.parse_args()?;
1949                    self.expect(&Token::RParen)?;
1950                    expr = Expr {
1951                        kind: ExprKind::Call {
1952                            callee: Box::new(expr),
1953                            args,
1954                        },
1955                        line,
1956                        column,
1957                    };
1958                }
1959                Token::LBracket => {
1960                    if !self.try_enter() {
1961                        return Err(self.too_deep());
1962                    }
1963                    let (line, column) = self.peek_pos();
1964                    self.advance();
1965                    let index = self.with_struct_literal(true, |p| p.parse_expr())?;
1966                    self.expect(&Token::RBracket)?;
1967                    expr = Expr {
1968                        kind: ExprKind::Index {
1969                            object: Box::new(expr),
1970                            index: Box::new(index),
1971                        },
1972                        line,
1973                        column,
1974                    };
1975                }
1976                Token::Dot => {
1977                    if !self.try_enter() {
1978                        return Err(self.too_deep());
1979                    }
1980                    let (line, column) = self.peek_pos();
1981                    self.advance();
1982                    let (name, _) = self.expect_ident()?;
1983
1984                    // `a.B::V(...)` / `a.B { ... }` — namespaced
1985                    // type access through a module alias. We only
1986                    // take this path when the receiver is a bare
1987                    // `Ident` (the alias) and the field is a
1988                    // type-shape name. Anything else (method
1989                    // call, plain field read) falls through.
1990                    if let ExprKind::Ident(ns) = &expr.kind
1991                        && naming::is_type_name(&name)
1992                    {
1993                        match self.peek() {
1994                            Token::ColonColon => {
1995                                let ns_owned = ns.clone();
1996                                expr = self.parse_enum_variant_tail(
1997                                    name,
1998                                    Some(ns_owned),
1999                                    line,
2000                                    expr.column,
2001                                )?;
2002                                continue;
2003                            }
2004                            Token::LBrace if self.allow_struct_literal => {
2005                                let ns_owned = ns.clone();
2006                                expr = self.parse_struct_literal(
2007                                    name,
2008                                    Some(ns_owned),
2009                                    line,
2010                                    expr.column,
2011                                )?;
2012                                continue;
2013                            }
2014                            _ => {}
2015                        }
2016                    }
2017
2018                    if matches!(self.peek(), Token::LParen) {
2019                        // Method call: `.name(args)`.
2020                        self.advance();
2021                        let args = self.parse_args()?;
2022                        self.expect(&Token::RParen)?;
2023                        expr = Expr {
2024                            kind: ExprKind::MethodCall {
2025                                object: Box::new(expr),
2026                                method: name,
2027                                args,
2028                            },
2029                            line,
2030                            column,
2031                        };
2032                    } else {
2033                        // Bare field read: `.name`.
2034                        expr = Expr {
2035                            kind: ExprKind::FieldAccess {
2036                                object: Box::new(expr),
2037                                field: name,
2038                            },
2039                            line,
2040                            column,
2041                        };
2042                    }
2043                }
2044                _ => break,
2045            }
2046        }
2047
2048        self.depth = chain_base;
2049        Ok(expr)
2050    }
2051
2052    fn parse_args(&mut self) -> Result<Vec<CallArg>, NyblError> {
2053        let mut args = Vec::new();
2054        if !matches!(self.peek(), Token::RParen) {
2055            args.push(self.parse_call_arg()?);
2056            while matches!(self.peek(), Token::Comma) {
2057                self.advance();
2058                args.push(self.parse_call_arg()?);
2059            }
2060        }
2061        Ok(args)
2062    }
2063
2064    fn parse_call_arg(&mut self) -> Result<CallArg, NyblError> {
2065        let mode = if matches!(self.peek(), Token::Ref) {
2066            self.advance();
2067            ParamMode::Ref
2068        } else {
2069            ParamMode::Value
2070        };
2071        let value = self.with_struct_literal(true, |p| p.parse_expr())?;
2072        Ok(CallArg { value, mode })
2073    }
2074
2075    fn parse_primary(&mut self) -> Result<Expr, NyblError> {
2076        let (line, column) = self.peek_pos();
2077
2078        match self.peek() {
2079            Token::Int(n) => {
2080                let n = *n;
2081                self.advance();
2082                Ok(Expr {
2083                    kind: ExprKind::Int(n),
2084                    line,
2085                    column,
2086                })
2087            }
2088            Token::IntMinMagnitude => {
2089                Err(self.error(line, integer_literal_out_of_range(I64_MIN_MAGNITUDE_TEXT)))
2090            }
2091            Token::Number(n) => {
2092                let n = *n;
2093                self.advance();
2094                Ok(Expr {
2095                    kind: ExprKind::Number(n),
2096                    line,
2097                    column,
2098                })
2099            }
2100            Token::Str(_) => {
2101                let Token::Str(s) = self.take() else {
2102                    unreachable!("string variant checked before taking token")
2103                };
2104                Ok(Expr {
2105                    kind: ExprKind::Str(s),
2106                    line,
2107                    column,
2108                })
2109            }
2110            Token::StringInterp(_) => {
2111                let Token::StringInterp(parts) = self.take() else {
2112                    unreachable!("interpolation variant checked before taking token")
2113                };
2114                Ok(Expr {
2115                    kind: ExprKind::StringInterp(parts),
2116                    line,
2117                    column,
2118                })
2119            }
2120            Token::True => {
2121                self.advance();
2122                Ok(Expr {
2123                    kind: ExprKind::Bool(true),
2124                    line,
2125                    column,
2126                })
2127            }
2128            Token::False => {
2129                self.advance();
2130                Ok(Expr {
2131                    kind: ExprKind::Bool(false),
2132                    line,
2133                    column,
2134                })
2135            }
2136            Token::None => {
2137                self.advance();
2138                Ok(Expr {
2139                    kind: ExprKind::None,
2140                    line,
2141                    column,
2142                })
2143            }
2144            Token::Ident(_) => {
2145                let Token::Ident(name) = self.take() else {
2146                    unreachable!("identifier variant checked before taking token")
2147                };
2148                // Sugar: bare `Ok(args)` / `Err(args)` desugars
2149                // to the built-in `Result::Ok(args)` /
2150                // `Result::Err(args)`. Nybl's case rules already
2151                // reserve uppercase idents for type / variant
2152                // names, so `Ok` and `Err` can't collide with a
2153                // user fn or variable. Users who want the `Ok` /
2154                // `Err` variants of a *different* enum have to
2155                // name it explicitly (`MyEnum::Ok(...)`).
2156                if (name == "Ok" || name == "Err") && matches!(self.peek(), Token::LParen) {
2157                    return self.parse_result_shorthand(name, line, column);
2158                }
2159                // Enum variant construction: `Type::Variant…`.
2160                // Always parse (the `::` is unambiguous); the
2161                // payload shape is determined by what follows
2162                // the variant name.
2163                if matches!(self.peek(), Token::ColonColon) {
2164                    return self.parse_enum_variant_tail(name, None, line, column);
2165                }
2166                // Struct literal: `Name { field: value, ... }`.
2167                // Parsed only when struct literals are allowed in
2168                // the current context (see
2169                // `without_struct_literal`). This keeps `if foo {
2170                // body }` / `for x in arr { body }` parseable.
2171                if self.allow_struct_literal && matches!(self.peek(), Token::LBrace) {
2172                    return self.parse_struct_literal(name, None, line, column);
2173                }
2174                Ok(Expr {
2175                    kind: ExprKind::Ident(name),
2176                    line,
2177                    column,
2178                })
2179            }
2180            Token::LParen => {
2181                self.enter()?;
2182                self.advance();
2183                let expr = self.with_struct_literal(true, |p| p.parse_expr())?;
2184                self.expect(&Token::RParen)?;
2185                self.leave();
2186                Ok(expr)
2187            }
2188            Token::LBracket => self.parse_array_literal(),
2189            Token::LBrace => self.parse_dict_literal(),
2190            Token::If => self.parse_if_expr(),
2191            Token::Fn => self.parse_lambda(),
2192            Token::Match => self.parse_match_expr(),
2193            _ => Err(self.error(
2194                line,
2195                format!("I didn't expect `{}` here", fmt_token(self.peek())),
2196            )),
2197        }
2198    }
2199
2200    fn parse_enum_variant_tail(
2201        &mut self,
2202        type_name: String,
2203        namespace: Option<String>,
2204        line: u32,
2205        column: Option<core::num::NonZeroU32>,
2206    ) -> Result<Expr, NyblError> {
2207        self.advance(); // consume `::`
2208        let (variant, _) = self.expect_ident()?;
2209        let payload = match self.peek() {
2210            Token::LParen => {
2211                self.enter()?;
2212                self.advance();
2213                let mut args: Vec<Expr> = Vec::new();
2214                if !matches!(self.peek(), Token::RParen) {
2215                    args.push(self.with_struct_literal(true, |p| p.parse_expr())?);
2216                    while matches!(self.peek(), Token::Comma) {
2217                        self.advance();
2218                        if matches!(self.peek(), Token::RParen) {
2219                            break;
2220                        }
2221                        args.push(self.with_struct_literal(true, |p| p.parse_expr())?);
2222                    }
2223                }
2224                self.expect(&Token::RParen)?;
2225                self.leave();
2226                VariantPayload::Tuple(args)
2227            }
2228            Token::LBrace if self.allow_struct_literal => {
2229                self.enter()?;
2230                self.advance();
2231                let mut fields: Vec<(String, Expr)> = Vec::new();
2232                if !matches!(self.peek(), Token::RBrace) {
2233                    let (fname, _) = self.expect_ident()?;
2234                    self.expect(&Token::Colon)?;
2235                    let fvalue = self.parse_expr()?;
2236                    fields.push((fname, fvalue));
2237                    while matches!(self.peek(), Token::Comma) {
2238                        self.advance();
2239                        if matches!(self.peek(), Token::RBrace) {
2240                            break;
2241                        }
2242                        let (fname, _) = self.expect_ident()?;
2243                        self.expect(&Token::Colon)?;
2244                        let fvalue = self.parse_expr()?;
2245                        fields.push((fname, fvalue));
2246                    }
2247                }
2248                self.expect(&Token::RBrace)?;
2249                self.leave();
2250                VariantPayload::Struct(fields)
2251            }
2252            _ => VariantPayload::Unit,
2253        };
2254        Ok(Expr {
2255            kind: ExprKind::EnumConstruct {
2256                namespace,
2257                type_name,
2258                variant,
2259                payload,
2260            },
2261            line,
2262            column,
2263        })
2264    }
2265
2266    /// `Ok(args)` / `Err(args)` — parser-level sugar for the
2267    /// built-in `Result::Ok(args)` / `Result::Err(args)` so user
2268    /// code can skip the `Result::` prefix for the two variants
2269    /// used overwhelmingly often. The caller already advanced
2270    /// past the identifier and verified the lookahead is
2271    /// `LParen`; `variant` must be `"Ok"` or `"Err"`.
2272    fn parse_result_shorthand(
2273        &mut self,
2274        variant: String,
2275        line: u32,
2276        column: Option<core::num::NonZeroU32>,
2277    ) -> Result<Expr, NyblError> {
2278        debug_assert!(variant == "Ok" || variant == "Err");
2279        self.enter()?;
2280        self.expect(&Token::LParen)?;
2281        let mut args: Vec<Expr> = Vec::new();
2282        if !matches!(self.peek(), Token::RParen) {
2283            args.push(self.with_struct_literal(true, |p| p.parse_expr())?);
2284            while matches!(self.peek(), Token::Comma) {
2285                self.advance();
2286                if matches!(self.peek(), Token::RParen) {
2287                    break;
2288                }
2289                args.push(self.with_struct_literal(true, |p| p.parse_expr())?);
2290            }
2291        }
2292        self.expect(&Token::RParen)?;
2293        self.leave();
2294        Ok(Expr {
2295            kind: ExprKind::EnumConstruct {
2296                namespace: None,
2297                type_name: String::from("Result"),
2298                variant,
2299                payload: VariantPayload::Tuple(args),
2300            },
2301            line,
2302            column,
2303        })
2304    }
2305
2306    fn parse_struct_literal(
2307        &mut self,
2308        type_name: String,
2309        namespace: Option<String>,
2310        line: u32,
2311        column: Option<core::num::NonZeroU32>,
2312    ) -> Result<Expr, NyblError> {
2313        self.enter()?;
2314        self.expect(&Token::LBrace)?;
2315        let mut fields: Vec<(String, Expr)> = Vec::new();
2316        if !matches!(self.peek(), Token::RBrace) {
2317            let (fname, _) = self.expect_ident()?;
2318            self.expect(&Token::Colon)?;
2319            let fvalue = self.parse_expr()?;
2320            fields.push((fname, fvalue));
2321            while matches!(self.peek(), Token::Comma) {
2322                self.advance();
2323                if matches!(self.peek(), Token::RBrace) {
2324                    break; // trailing comma
2325                }
2326                let (fname, _) = self.expect_ident()?;
2327                self.expect(&Token::Colon)?;
2328                let fvalue = self.parse_expr()?;
2329                fields.push((fname, fvalue));
2330            }
2331        }
2332        self.expect(&Token::RBrace)?;
2333        self.leave();
2334        Ok(Expr {
2335            kind: ExprKind::StructConstruct {
2336                namespace,
2337                type_name,
2338                fields,
2339            },
2340            line,
2341            column,
2342        })
2343    }
2344
2345    fn parse_array_literal(&mut self) -> Result<Expr, NyblError> {
2346        let (line, column) = self.peek_pos();
2347        self.advance(); // consume [
2348        let mut elements = Vec::new();
2349        if !matches!(self.peek(), Token::RBracket) {
2350            elements.push(self.with_struct_literal(true, |p| p.parse_expr())?);
2351            while matches!(self.peek(), Token::Comma) {
2352                self.advance();
2353                if matches!(self.peek(), Token::RBracket) {
2354                    break; // trailing comma
2355                }
2356                elements.push(self.with_struct_literal(true, |p| p.parse_expr())?);
2357            }
2358        }
2359        self.expect(&Token::RBracket)?;
2360        Ok(Expr {
2361            kind: ExprKind::Array(elements),
2362            line,
2363            column,
2364        })
2365    }
2366
2367    fn parse_dict_literal(&mut self) -> Result<Expr, NyblError> {
2368        let (line, column) = self.peek_pos();
2369        self.advance(); // consume {
2370        let mut entries = Vec::new();
2371        if !matches!(self.peek(), Token::RBrace) {
2372            let key = self.expect_string_key()?;
2373            self.expect(&Token::Colon)?;
2374            let value = self.with_struct_literal(true, |p| p.parse_expr())?;
2375            entries.push((key, value));
2376            while matches!(self.peek(), Token::Comma) {
2377                self.advance();
2378                if matches!(self.peek(), Token::RBrace) {
2379                    break; // trailing comma
2380                }
2381                let key = self.expect_string_key()?;
2382                self.expect(&Token::Colon)?;
2383                let value = self.with_struct_literal(true, |p| p.parse_expr())?;
2384                entries.push((key, value));
2385            }
2386        }
2387        self.expect(&Token::RBrace)?;
2388        Ok(Expr {
2389            kind: ExprKind::Dict(entries),
2390            line,
2391            column,
2392        })
2393    }
2394
2395    fn expect_string_key(&mut self) -> Result<String, NyblError> {
2396        let (line, _column) = self.peek_pos();
2397        match self.peek() {
2398            Token::Str(_) => {
2399                let Token::Str(s) = self.take() else {
2400                    unreachable!("string variant checked before taking token")
2401                };
2402                Ok(s)
2403            }
2404            _ => Err(self.error(line, "Dict keys must be strings (in quotes)")),
2405        }
2406    }
2407
2408    fn parse_match_expr(&mut self) -> Result<Expr, NyblError> {
2409        let (line, column) = self.peek_pos();
2410        self.advance(); // consume 'match'
2411        // Scrutinee reads without struct-literal parsing — same
2412        // rule as `if` / `while` / `for`, so `match foo { ... }`
2413        // stays parseable.
2414        let scrutinee = self.without_struct_literal(|p| p.parse_expr())?;
2415        self.expect(&Token::LBrace)?;
2416        let mut arms: Vec<MatchArm> = Vec::new();
2417        self.skip_semicolons();
2418        while !matches!(self.peek(), Token::RBrace | Token::Eof) {
2419            arms.push(self.parse_match_arm()?);
2420            // Arms separate by `,` (common) or `;` (auto-semi from
2421            // newline). Accept and continue; also accept trailing
2422            // separators before the closing brace.
2423            while matches!(self.peek(), Token::Comma | Token::Semicolon) {
2424                self.advance();
2425            }
2426        }
2427        self.expect(&Token::RBrace)?;
2428        Ok(Expr {
2429            kind: ExprKind::Match {
2430                scrutinee: Box::new(scrutinee),
2431                arms,
2432            },
2433            line,
2434            column,
2435        })
2436    }
2437
2438    fn parse_match_arm(&mut self) -> Result<MatchArm, NyblError> {
2439        let (line, _column) = self.peek_pos();
2440        let pattern = self.parse_pattern()?;
2441        let guard = if matches!(self.peek(), Token::If) {
2442            self.advance();
2443            Some(self.with_struct_literal(true, |p| p.parse_expr())?)
2444        } else {
2445            None
2446        };
2447        self.expect(&Token::FatArrow)?;
2448        // Braces in expression position introduce a dictionary, not a
2449        // statement block. Preserve valid dictionary-valued arms while giving
2450        // the common `pattern => { do_work() }` mistake a diagnostic that
2451        // points at the construct the user needs to change. Comments are
2452        // absent from the token stream, so the next token is the first item in
2453        // the braces even when the body starts on a later line.
2454        let starts_dictionary = matches!(self.peek_at(1), Token::RBrace)
2455            || (matches!(self.peek_at(1), Token::Str(_))
2456                && matches!(self.peek_at(2), Token::Colon));
2457        if matches!(self.peek(), Token::LBrace) && !starts_dictionary {
2458            let (body_line, body_column) = self.peek_pos();
2459            let mut error = NyblError::runtime_at(
2460                "`{ ... }` after `=>` is a dictionary expression, not a match-arm block",
2461                body_line,
2462                body_column,
2463            );
2464            error.friendly_hint = Some(
2465                "`match` arm bodies must be a single expression; put it directly after `=>`, or quote dictionary keys if you meant to return a dictionary."
2466                    .to_string(),
2467            );
2468            return Err(error);
2469        }
2470        let body = self.with_struct_literal(true, |p| p.parse_expr())?;
2471        Ok(MatchArm {
2472            pattern,
2473            guard,
2474            body,
2475            line,
2476        })
2477    }
2478
2479    fn parse_pattern(&mut self) -> Result<Pattern, NyblError> {
2480        let first = self.parse_pattern_single()?;
2481        // Or-pattern: `p1 | p2 | p3`. Keep the left-associative
2482        // tree flat in a single `Or` variant for ergonomic
2483        // matching later.
2484        if matches!(self.peek(), Token::Pipe) {
2485            let expected_bindings = first.binding_names();
2486            let mut alts = vec![first];
2487            while matches!(self.peek(), Token::Pipe) {
2488                self.advance();
2489                let (alternative_line, alternative_column) = self.peek_pos();
2490                let alternative = self.parse_pattern_single()?;
2491                let actual_bindings = alternative.binding_names();
2492                if actual_bindings != expected_bindings {
2493                    return Err(inconsistent_or_pattern_bindings_error(
2494                        &expected_bindings,
2495                        &actual_bindings,
2496                        alts.len() + 1,
2497                        alternative_line,
2498                        alternative_column,
2499                    ));
2500                }
2501                alts.push(alternative);
2502            }
2503            Ok(Pattern::Or(alts))
2504        } else {
2505            Ok(first)
2506        }
2507    }
2508
2509    fn parse_pattern_single(&mut self) -> Result<Pattern, NyblError> {
2510        self.enter()?;
2511        let result = self.parse_pattern_single_inner();
2512        self.leave();
2513        result
2514    }
2515
2516    /// Parse one pattern after its nesting-budget entry has been acquired.
2517    /// Keeping the budget owner outside the parsing body ensures every `?`
2518    /// and early `return` below is balanced by [`Self::leave`].
2519    fn parse_pattern_single_inner(&mut self) -> Result<Pattern, NyblError> {
2520        let (line, column) = self.peek_pos();
2521        match self.peek() {
2522            Token::Int(n) => {
2523                let n = *n;
2524                self.advance();
2525                Ok(Pattern::Literal(LiteralPattern::Int(n)))
2526            }
2527            Token::IntMinMagnitude => {
2528                Err(self.error(line, integer_literal_out_of_range(I64_MIN_MAGNITUDE_TEXT)))
2529            }
2530            Token::Number(n) => {
2531                let n = *n;
2532                self.advance();
2533                Ok(Pattern::Literal(LiteralPattern::Number(n)))
2534            }
2535            Token::Str(_) => {
2536                let Token::Str(s) = self.take() else {
2537                    unreachable!("string variant checked before taking token")
2538                };
2539                Ok(Pattern::Literal(LiteralPattern::Str(s)))
2540            }
2541            Token::True => {
2542                self.advance();
2543                Ok(Pattern::Literal(LiteralPattern::Bool(true)))
2544            }
2545            Token::False => {
2546                self.advance();
2547                Ok(Pattern::Literal(LiteralPattern::Bool(false)))
2548            }
2549            Token::None => {
2550                self.advance();
2551                Ok(Pattern::Literal(LiteralPattern::None))
2552            }
2553            Token::Minus => {
2554                // Negative number literal: `-1`, `-3.14`.
2555                self.advance();
2556                match self.peek() {
2557                    Token::IntMinMagnitude => {
2558                        self.advance();
2559                        Ok(Pattern::Literal(LiteralPattern::Int(i64::MIN)))
2560                    }
2561                    Token::Int(n) => {
2562                        let n = *n;
2563                        self.advance();
2564                        // `i64::MIN` has no positive counterpart
2565                        // — negating it overflows. Raise a clear
2566                        // parse error rather than silently
2567                        // wrapping.
2568                        match n.checked_neg() {
2569                            Some(neg) => Ok(Pattern::Literal(LiteralPattern::Int(neg))),
2570                            None => Err(self.error(
2571                                line,
2572                                format!("Integer literal `-{n}` is out of range for i64"),
2573                            )),
2574                        }
2575                    }
2576                    Token::Number(n) => {
2577                        let n = *n;
2578                        self.advance();
2579                        Ok(Pattern::Literal(LiteralPattern::Number(-n)))
2580                    }
2581                    other => Err(self.error(
2582                        line,
2583                        format!(
2584                            "Expected a number after `-` in pattern, got `{}`",
2585                            fmt_token(other)
2586                        ),
2587                    )),
2588                }
2589            }
2590            Token::LBracket => self.parse_pattern_array(),
2591            Token::Ident(name) if name == "_" => {
2592                self.advance();
2593                Ok(Pattern::Wildcard)
2594            }
2595            Token::Ident(_) => {
2596                let Token::Ident(name) = self.take() else {
2597                    unreachable!("identifier variant checked before taking token")
2598                };
2599                // Sugar: `Ok(p)` / `Err(p)` as patterns — mirror
2600                // the expression-side shortcut. Reduces the
2601                // `match r { Result::Ok(v) => ..., Result::Err(e)
2602                // => ... }` boilerplate to plain `Ok(v)` / `Err(e)`.
2603                if (name == "Ok" || name == "Err") && matches!(self.peek(), Token::LParen) {
2604                    return self.parse_result_shorthand_pattern(name);
2605                }
2606                // `Type::Variant[...]` path pattern.
2607                if matches!(self.peek(), Token::ColonColon) {
2608                    self.parse_pattern_variant_tail(name, None)
2609                } else if matches!(self.peek(), Token::LBrace) {
2610                    // `Type { ... }` struct pattern — only when
2611                    // the `LBrace` is syntactically plausible as
2612                    // a struct pattern. Inside a match arm pattern
2613                    // it always is.
2614                    self.parse_pattern_struct(name, None)
2615                } else if matches!(self.peek(), Token::Dot) && naming::is_value_name(&name) {
2616                    // `ns.Type...` — namespaced variant / struct
2617                    // pattern through a module alias. Only fires
2618                    // when the first segment is value-shaped
2619                    // (an alias), to keep bare `Type.field` from
2620                    // being misread as a pattern.
2621                    self.advance(); // consume '.'
2622                    let (type_name, type_line) = self.expect_ident()?;
2623                    if !naming::is_type_name(&type_name) {
2624                        return Err(self.error(
2625                            type_line,
2626                            format!(
2627                                "Expected a type name after `{name}.` in pattern, got `{type_name}`"
2628                            ),
2629                        ));
2630                    }
2631                    if matches!(self.peek(), Token::ColonColon) {
2632                        self.parse_pattern_variant_tail(type_name, Some(name))
2633                    } else if matches!(self.peek(), Token::LBrace) {
2634                        self.parse_pattern_struct(type_name, Some(name))
2635                    } else {
2636                        Err(self.error(
2637                            type_line,
2638                            format!(
2639                                "Expected `::Variant(...)` or `{{...}}` after `{name}.{type_name}` in pattern"
2640                            ),
2641                        ))
2642                    }
2643                } else {
2644                    // Bare identifier = binding. `_` is handled
2645                    // above as wildcard.
2646                    ensure_value_name_at(&name, "`match` pattern binding", line, column)?;
2647                    Ok(Pattern::Binding(name))
2648                }
2649            }
2650            other => {
2651                if let Some(keyword) = other.keyword_name() {
2652                    Err(NyblError::reserved_word(keyword, line, self.peek_column()))
2653                } else {
2654                    Err(self.error(
2655                        line,
2656                        format!("Expected a pattern, got `{}`", fmt_token(other)),
2657                    ))
2658                }
2659            }
2660        }
2661    }
2662
2663    fn parse_pattern_array(&mut self) -> Result<Pattern, NyblError> {
2664        self.advance(); // consume `[`
2665        let mut elements: Vec<Pattern> = Vec::new();
2666        let mut rest: Option<ArrayRest> = None;
2667        if !matches!(self.peek(), Token::RBracket) {
2668            loop {
2669                if matches!(self.peek(), Token::DotDot) {
2670                    self.advance();
2671                    // Optional name binding after `..`.
2672                    let captured = match self.peek() {
2673                        Token::Ident(n) if n != "_" => {
2674                            let (line, column) = self.peek_pos();
2675                            let Token::Ident(n) = self.take() else {
2676                                unreachable!("identifier variant checked before taking token")
2677                            };
2678                            ensure_value_name_at(&n, "`match` pattern rest binding", line, column)?;
2679                            ArrayRest::Named(n)
2680                        }
2681                        other => {
2682                            if let Some(keyword) = other.keyword_name() {
2683                                let (line, _column) = self.peek_pos();
2684                                return Err(NyblError::reserved_word(
2685                                    keyword,
2686                                    line,
2687                                    self.peek_column(),
2688                                ));
2689                            }
2690                            ArrayRest::Ignored
2691                        }
2692                    };
2693                    rest = Some(captured);
2694                    // `..` must be the last element in the array
2695                    // pattern; the parser enforces this by
2696                    // stopping here.
2697                    break;
2698                }
2699                elements.push(self.parse_pattern()?);
2700                if matches!(self.peek(), Token::Comma) {
2701                    self.advance();
2702                    if matches!(self.peek(), Token::RBracket) {
2703                        break; // trailing comma
2704                    }
2705                } else {
2706                    break;
2707                }
2708            }
2709        }
2710        self.expect(&Token::RBracket)?;
2711        Ok(Pattern::Array { elements, rest })
2712    }
2713
2714    fn parse_pattern_variant_tail(
2715        &mut self,
2716        type_name: String,
2717        namespace: Option<String>,
2718    ) -> Result<Pattern, NyblError> {
2719        self.advance(); // consume `::`
2720        let (variant, _) = self.expect_ident()?;
2721        let payload = match self.peek() {
2722            Token::LParen => {
2723                self.advance();
2724                let mut items: Vec<Pattern> = Vec::new();
2725                if !matches!(self.peek(), Token::RParen) {
2726                    items.push(self.parse_pattern()?);
2727                    while matches!(self.peek(), Token::Comma) {
2728                        self.advance();
2729                        if matches!(self.peek(), Token::RParen) {
2730                            break;
2731                        }
2732                        items.push(self.parse_pattern()?);
2733                    }
2734                }
2735                self.expect(&Token::RParen)?;
2736                VariantPatternPayload::Tuple(items)
2737            }
2738            Token::LBrace => {
2739                let (fields, rest) = self.parse_pattern_field_list()?;
2740                VariantPatternPayload::Struct { fields, rest }
2741            }
2742            _ => VariantPatternPayload::Unit,
2743        };
2744        Ok(Pattern::EnumVariant {
2745            namespace,
2746            type_name,
2747            variant,
2748            payload,
2749        })
2750    }
2751
2752    /// Pattern-side mirror of [`Self::parse_result_shorthand`]:
2753    /// `Ok(p)` / `Err(p)` in a pattern desugar to the built-in
2754    /// `Result::Ok(p)` / `Result::Err(p)`. Caller has already
2755    /// advanced past the ident and verified `LParen` follows;
2756    /// `variant` must be `"Ok"` or `"Err"`.
2757    fn parse_result_shorthand_pattern(&mut self, variant: String) -> Result<Pattern, NyblError> {
2758        debug_assert!(variant == "Ok" || variant == "Err");
2759        self.expect(&Token::LParen)?;
2760        let mut items: Vec<Pattern> = Vec::new();
2761        if !matches!(self.peek(), Token::RParen) {
2762            items.push(self.parse_pattern()?);
2763            while matches!(self.peek(), Token::Comma) {
2764                self.advance();
2765                if matches!(self.peek(), Token::RParen) {
2766                    break;
2767                }
2768                items.push(self.parse_pattern()?);
2769            }
2770        }
2771        self.expect(&Token::RParen)?;
2772        Ok(Pattern::EnumVariant {
2773            namespace: None,
2774            type_name: String::from("Result"),
2775            variant,
2776            payload: VariantPatternPayload::Tuple(items),
2777        })
2778    }
2779
2780    fn parse_pattern_struct(
2781        &mut self,
2782        type_name: String,
2783        namespace: Option<String>,
2784    ) -> Result<Pattern, NyblError> {
2785        let (fields, rest) = self.parse_pattern_field_list()?;
2786        Ok(Pattern::Struct {
2787            namespace,
2788            type_name,
2789            fields,
2790            rest,
2791        })
2792    }
2793
2794    fn parse_pattern_field_list(&mut self) -> Result<(Vec<(String, Pattern)>, bool), NyblError> {
2795        self.expect(&Token::LBrace)?;
2796        let mut fields: Vec<(String, Pattern)> = Vec::new();
2797        let mut rest = false;
2798        if !matches!(self.peek(), Token::RBrace) {
2799            loop {
2800                if matches!(self.peek(), Token::DotDot) {
2801                    self.advance();
2802                    rest = true;
2803                    break;
2804                }
2805                let (field_line, field_column) = self.peek_pos();
2806                let (fname, _) = self.expect_ident()?;
2807                // Shorthand `{ field }` binds the field value to
2808                // a local named `field`. Full form `{ field: pat }`
2809                // lets the user nest or wildcard.
2810                let sub = if matches!(self.peek(), Token::Colon) {
2811                    self.advance();
2812                    self.parse_pattern()?
2813                } else {
2814                    ensure_value_name_at(
2815                        &fname,
2816                        "`match` pattern shorthand binding",
2817                        field_line,
2818                        field_column,
2819                    )?;
2820                    Pattern::Binding(fname.clone())
2821                };
2822                fields.push((fname, sub));
2823                if matches!(self.peek(), Token::Comma) {
2824                    self.advance();
2825                    if matches!(self.peek(), Token::RBrace) {
2826                        break;
2827                    }
2828                } else {
2829                    break;
2830                }
2831            }
2832        }
2833        self.expect(&Token::RBrace)?;
2834        Ok((fields, rest))
2835    }
2836
2837    fn parse_lambda(&mut self) -> Result<Expr, NyblError> {
2838        let (line, column) = self.peek_pos();
2839        self.advance(); // consume 'fn'
2840        let params = self.parse_parameters("function parameter")?;
2841        let body = self.parse_block()?;
2842        Ok(Expr {
2843            kind: ExprKind::Lambda { params, body },
2844            line,
2845            column,
2846        })
2847    }
2848
2849    fn parse_if_expr(&mut self) -> Result<Expr, NyblError> {
2850        let (line, column) = self.peek_pos();
2851        self.advance(); // consume 'if'
2852        let condition = self.without_struct_literal(|p| p.parse_expr())?;
2853        let then_expr = self.parse_if_expr_branch()?;
2854        self.expect(&Token::Else)?;
2855        let else_expr = self.parse_if_expr_branch()?;
2856        Ok(Expr {
2857            kind: ExprKind::IfExpr {
2858                condition: Box::new(condition),
2859                then_expr: Box::new(then_expr),
2860                else_expr: Box::new(else_expr),
2861            },
2862            line,
2863            column,
2864        })
2865    }
2866
2867    /// Parse one expression between an if-expression branch's braces.
2868    ///
2869    /// Braces remain normal statement-capable delimiters rather than the soft
2870    /// delimiters used by parentheses and brackets. Consume semicolon tokens
2871    /// only after the branch expression, where they are a trailing terminator;
2872    /// requiring `}` immediately afterward keeps a second expression or
2873    /// statement invalid. Leading semicolons stay invalid because they cannot
2874    /// be produced by layout after `{`.
2875    fn parse_if_expr_branch(&mut self) -> Result<Expr, NyblError> {
2876        self.expect(&Token::LBrace)?;
2877        let branch_expr = self.with_struct_literal(true, |p| p.parse_expr())?;
2878        self.skip_semicolons();
2879        self.expect(&Token::RBrace)?;
2880        Ok(branch_expr)
2881    }
2882}
2883
2884// ─── Instruction counting ───────────────────────────────────────────────────
2885
2886/// Count instructions in a list of statements (AST-based, format-independent).
2887///
2888/// Every `Stmt` counts as 1 instruction. Compound statements (if/while/repeat/for)
2889/// recurse into their body. `FnDecl` counts as 1 but does NOT recurse into the
2890/// function body — this rewards defining reusable functions.
2891pub fn count_instructions(stmts: &[Stmt]) -> u32 {
2892    let mut count = 0u32;
2893    for stmt in stmts {
2894        count += 1; // the statement itself
2895        match &stmt.kind {
2896            StmtKind::If {
2897                body,
2898                else_ifs,
2899                else_body,
2900                ..
2901            } => {
2902                count += count_instructions(body);
2903                for (_, branch_body) in else_ifs {
2904                    count += count_instructions(branch_body);
2905                }
2906                if let Some(eb) = else_body {
2907                    count += count_instructions(eb);
2908                }
2909            }
2910            StmtKind::While { body, .. }
2911            | StmtKind::Repeat { body, .. }
2912            | StmtKind::ForIn { body, .. } => {
2913                count += count_instructions(body);
2914            }
2915            StmtKind::FnDecl { .. } => {
2916                // Don't recurse into function body — reward reuse
2917            }
2918            _ => {}
2919        }
2920    }
2921    count
2922}
2923
2924// ─── Helpers ───────────────────────────────────────────────────────────────
2925
2926fn expr_to_assign_target(expr: Expr, line: u32) -> Result<AssignTarget, NyblError> {
2927    // Assignment mutates the binding at the root of a place, not
2928    // merely the final index or field. Parentheses do not need a
2929    // separate case because the parser deliberately erases them.
2930    // Check the complete place before lowering it so every engine
2931    // receives an AST in which const mutation is unrepresentable.
2932    if let Some(name) = assignable_root_name(&expr)
2933        && naming::is_constant_name(name)
2934    {
2935        return Err(crate::error_messages::constant_mutation_error(name, line));
2936    }
2937
2938    match expr.kind {
2939        ExprKind::Ident(name) => Ok(AssignTarget::Variable(name)),
2940        ExprKind::Index { object, index } => Ok(AssignTarget::Index {
2941            object: *object,
2942            index: *index,
2943        }),
2944        ExprKind::FieldAccess { object, field } => Ok(AssignTarget::Field {
2945            object: *object,
2946            field,
2947        }),
2948        _ => Err(NyblError {
2949            line: Some(line),
2950            column: None,
2951            message:
2952                "You can only assign to a variable, an index (`arr[0]`), or a struct field (`point.x`)"
2953                    .to_string(),
2954            friendly_hint: None,
2955            source_context: None,
2956            is_fatal: false,
2957            is_try_return: false,
2958        }),
2959    }
2960}
2961
2962/// Return the binding at the root of an assignable place.
2963///
2964/// Only the receiver/object side participates: an all-caps name
2965/// used as an index is a read (`items[INDEX] = value`), not the
2966/// binding being mutated. Calls and other expressions have no
2967/// assignable root and retain their existing invalid-target error.
2968fn assignable_root_name(expr: &Expr) -> Option<&str> {
2969    match &expr.kind {
2970        ExprKind::Ident(name) => Some(name),
2971        ExprKind::Index { object, .. } | ExprKind::FieldAccess { object, .. } => {
2972            assignable_root_name(object)
2973        }
2974        _ => None,
2975    }
2976}
2977
2978fn assign_target_root_name(target: &AssignTarget) -> Option<&str> {
2979    match target {
2980        AssignTarget::Variable(name) => Some(name),
2981        AssignTarget::Index { object, .. } | AssignTarget::Field { object, .. } => {
2982            assignable_root_name(object)
2983        }
2984    }
2985}
2986
2987/// A value receiver is a read-only snapshot. Reject writes while parsing so a
2988/// method cannot appear to mutate its caller while only changing a discarded
2989/// local copy. `ref self` opts into the transactional mutable-receiver path.
2990fn reject_value_receiver_mutation(body: &[Stmt], receiver: &str) -> Result<(), NyblError> {
2991    if let Some(line) = value_receiver_mutation_line(body, receiver, false, &BTreeSet::new()) {
2992        return Err(value_receiver_mutation_error(receiver, line));
2993    }
2994    Ok(())
2995}
2996
2997fn value_receiver_mutation_error(receiver: &str, line: u32) -> NyblError {
2998    let mut error = NyblError::runtime(format!("can't mutate value receiver `{receiver}`"), line);
2999    error.friendly_hint = Some(format!(
3000        "Declare the receiver as `ref {receiver}` to mutate it, or return a new value."
3001    ));
3002    error
3003}
3004
3005fn value_receiver_mutation_line(
3006    body: &[Stmt],
3007    receiver: &str,
3008    initially_shadowed: bool,
3009    ref_methods: &BTreeSet<String>,
3010) -> Option<u32> {
3011    let mut shadowed = initially_shadowed;
3012    for stmt in body {
3013        let expression_mutation = |expr: &Expr| {
3014            (!shadowed && expr_mutates_binding(expr, receiver, ref_methods)).then_some(expr.line)
3015        };
3016        match &stmt.kind {
3017            StmtKind::Let { name, value, .. } => {
3018                if let Some(line) = expression_mutation(value) {
3019                    return Some(line);
3020                }
3021                if name == receiver {
3022                    shadowed = true;
3023                }
3024            }
3025            StmtKind::Assign { target, value, .. } => {
3026                if !shadowed && assign_target_root_name(target) == Some(receiver) {
3027                    return Some(stmt.line);
3028                }
3029                if let Some(line) = expression_mutation(value) {
3030                    return Some(line);
3031                }
3032            }
3033            StmtKind::If {
3034                condition,
3035                body,
3036                else_ifs,
3037                else_body,
3038            } => {
3039                if let Some(line) = expression_mutation(condition) {
3040                    return Some(line);
3041                }
3042                if let Some(line) =
3043                    value_receiver_mutation_line(body, receiver, shadowed, ref_methods)
3044                {
3045                    return Some(line);
3046                }
3047                for (condition, body) in else_ifs {
3048                    if let Some(line) = expression_mutation(condition).or_else(|| {
3049                        value_receiver_mutation_line(body, receiver, shadowed, ref_methods)
3050                    }) {
3051                        return Some(line);
3052                    }
3053                }
3054                if let Some(line) = else_body.as_deref().and_then(|body| {
3055                    value_receiver_mutation_line(body, receiver, shadowed, ref_methods)
3056                }) {
3057                    return Some(line);
3058                }
3059            }
3060            StmtKind::While { condition, body } => {
3061                if let Some(line) = expression_mutation(condition)
3062                    .or_else(|| value_receiver_mutation_line(body, receiver, shadowed, ref_methods))
3063                {
3064                    return Some(line);
3065                }
3066            }
3067            StmtKind::Repeat { count, body } => {
3068                if let Some(line) = expression_mutation(count)
3069                    .or_else(|| value_receiver_mutation_line(body, receiver, shadowed, ref_methods))
3070                {
3071                    return Some(line);
3072                }
3073            }
3074            StmtKind::ForIn {
3075                var,
3076                iterable,
3077                body,
3078            } => {
3079                if let Some(line) = expression_mutation(iterable).or_else(|| {
3080                    value_receiver_mutation_line(
3081                        body,
3082                        receiver,
3083                        shadowed || var == receiver,
3084                        ref_methods,
3085                    )
3086                }) {
3087                    return Some(line);
3088                }
3089            }
3090            StmtKind::Return { value: Some(value) } | StmtKind::ExprStmt(value) => {
3091                if let Some(line) = expression_mutation(value) {
3092                    return Some(line);
3093                }
3094            }
3095            // Callable bodies get their own parameter/capture bindings; they
3096            // cannot write the receiver binding owned by this method call.
3097            StmtKind::FnDecl { .. }
3098            | StmtKind::MethodDecl { .. }
3099            | StmtKind::Return { value: None }
3100            | StmtKind::Break
3101            | StmtKind::Continue
3102            | StmtKind::Use { .. }
3103            | StmtKind::PublicSurface { .. }
3104            | StmtKind::StructDecl { .. }
3105            | StmtKind::EnumDecl { .. } => {}
3106        }
3107    }
3108    None
3109}
3110
3111fn expr_mutates_binding(expr: &Expr, binding: &str, ref_methods: &BTreeSet<String>) -> bool {
3112    let call_args_mutate = |args: &[CallArg]| {
3113        args.iter().any(|arg| {
3114            (arg.mode == ParamMode::Ref && assignable_root_name(&arg.value) == Some(binding))
3115                || expr_mutates_binding(&arg.value, binding, ref_methods)
3116        })
3117    };
3118    match &expr.kind {
3119        ExprKind::BinaryOp { left, right, .. } => {
3120            expr_mutates_binding(left, binding, ref_methods)
3121                || expr_mutates_binding(right, binding, ref_methods)
3122        }
3123        ExprKind::UnaryOp { expr, .. } | ExprKind::Try(expr) => {
3124            expr_mutates_binding(expr, binding, ref_methods)
3125        }
3126        ExprKind::Call { callee, args } => {
3127            expr_mutates_binding(callee, binding, ref_methods) || call_args_mutate(args)
3128        }
3129        ExprKind::MethodCall {
3130            object,
3131            method,
3132            args,
3133        } => {
3134            (matches!(&object.kind, ExprKind::Ident(name) if name == binding)
3135                && ref_methods.contains(method))
3136                || expr_mutates_binding(object, binding, ref_methods)
3137                || call_args_mutate(args)
3138        }
3139        ExprKind::FieldAccess { object, .. } => expr_mutates_binding(object, binding, ref_methods),
3140        ExprKind::StructConstruct { fields, .. } | ExprKind::Dict(fields) => fields
3141            .iter()
3142            .any(|(_, value)| expr_mutates_binding(value, binding, ref_methods)),
3143        ExprKind::EnumConstruct { payload, .. } => match payload {
3144            VariantPayload::Unit => false,
3145            VariantPayload::Tuple(values) => values
3146                .iter()
3147                .any(|value| expr_mutates_binding(value, binding, ref_methods)),
3148            VariantPayload::Struct(fields) => fields
3149                .iter()
3150                .any(|(_, value)| expr_mutates_binding(value, binding, ref_methods)),
3151        },
3152        ExprKind::Index { object, index } => {
3153            expr_mutates_binding(object, binding, ref_methods)
3154                || expr_mutates_binding(index, binding, ref_methods)
3155        }
3156        ExprKind::Array(values) => values
3157            .iter()
3158            .any(|value| expr_mutates_binding(value, binding, ref_methods)),
3159        ExprKind::IfExpr {
3160            condition,
3161            then_expr,
3162            else_expr,
3163        } => {
3164            expr_mutates_binding(condition, binding, ref_methods)
3165                || expr_mutates_binding(then_expr, binding, ref_methods)
3166                || expr_mutates_binding(else_expr, binding, ref_methods)
3167        }
3168        // Lambda bodies mutate their own captured snapshot, never the outer
3169        // receiver binding.
3170        ExprKind::Lambda { .. } => false,
3171        ExprKind::Match { scrutinee, arms } => {
3172            expr_mutates_binding(scrutinee, binding, ref_methods)
3173                || arms.iter().any(|arm| {
3174                    let shadowed = arm.pattern.binding_names().contains(binding);
3175                    !shadowed
3176                        && (arm
3177                            .guard
3178                            .as_ref()
3179                            .is_some_and(|guard| expr_mutates_binding(guard, binding, ref_methods))
3180                            || expr_mutates_binding(&arm.body, binding, ref_methods))
3181                })
3182        }
3183        ExprKind::Int(_)
3184        | ExprKind::Number(_)
3185        | ExprKind::Str(_)
3186        | ExprKind::StringInterp(_)
3187        | ExprKind::Bool(_)
3188        | ExprKind::None
3189        | ExprKind::Ident(_) => false,
3190    }
3191}
3192
3193pub fn fmt_token(token: &Token) -> &'static str {
3194    if let Some(keyword) = token.keyword_name() {
3195        return keyword;
3196    }
3197
3198    match token {
3199        Token::Int(_) => "an integer",
3200        Token::IntMinMagnitude => "an integer",
3201        Token::Number(_) => "a number",
3202        Token::Str(_) | Token::StringInterp(_) => "a string",
3203        Token::Ident(_) => "a name",
3204        Token::ColonColon => "::",
3205        Token::DotDot => "..",
3206        Token::FatArrow => "=>",
3207        Token::Pipe => "|",
3208        Token::Plus => "+",
3209        Token::Minus => "-",
3210        Token::Star => "*",
3211        Token::Slash => "/",
3212        Token::Percent => "%",
3213        Token::EqEq => "==",
3214        Token::BangEq => "!=",
3215        Token::Lt => "<",
3216        Token::Gt => ">",
3217        Token::LtEq => "<=",
3218        Token::GtEq => ">=",
3219        Token::AmpAmp => "&&",
3220        Token::PipePipe => "||",
3221        Token::Bang => "!",
3222        Token::Eq => "=",
3223        Token::PlusEq => "+=",
3224        Token::MinusEq => "-=",
3225        Token::StarEq => "*=",
3226        Token::SlashEq => "/=",
3227        Token::PercentEq => "%=",
3228        Token::LParen => "(",
3229        Token::RParen => ")",
3230        Token::LBracket => "[",
3231        Token::RBracket => "]",
3232        Token::LBrace => "{",
3233        Token::RBrace => "}",
3234        Token::Comma => ",",
3235        Token::Colon => ":",
3236        Token::Dot => ".",
3237        Token::Semicolon => ";",
3238        Token::Newline => "newline",
3239        Token::Eof => "end of code",
3240        Token::Let
3241        | Token::Const
3242        | Token::Fn
3243        | Token::Return
3244        | Token::If
3245        | Token::Else
3246        | Token::While
3247        | Token::For
3248        | Token::In
3249        | Token::Repeat
3250        | Token::Break
3251        | Token::Continue
3252        | Token::Use
3253        | Token::As
3254        | Token::Struct
3255        | Token::Enum
3256        | Token::Match
3257        | Token::Try
3258        | Token::Ref
3259        | Token::True
3260        | Token::False
3261        | Token::Pub
3262        | Token::None => unreachable!("keyword tokens return before punctuation formatting"),
3263    }
3264}
3265
3266#[cfg(test)]
3267mod depth_tests {
3268    use super::*;
3269
3270    fn pattern_parser(source: &str) -> Parser {
3271        Parser::new(crate::lexer::lex(source).expect("test pattern should lex"))
3272    }
3273
3274    fn nested_result_pattern(wrappers: usize) -> String {
3275        let mut source = String::new();
3276        for index in 0..wrappers {
3277            source.push_str(if index % 2 == 0 { "Ok(" } else { "Err(" });
3278        }
3279        source.push('_');
3280        for _ in 0..wrappers {
3281            source.push(')');
3282        }
3283        source
3284    }
3285
3286    #[test]
3287    fn pattern_depth_limit_accepts_boundary_and_rejects_next_level() {
3288        // The leaf pattern also owns one depth level, so 127 wrappers plus
3289        // `_` exactly reaches MAX_PARSE_DEPTH.
3290        let mut at_limit = pattern_parser(&nested_result_pattern(MAX_PARSE_DEPTH - 1));
3291        at_limit
3292            .parse_pattern()
3293            .expect("pattern at the nesting limit should parse");
3294        assert_eq!(at_limit.depth, 0);
3295
3296        let mut over_limit = pattern_parser(&nested_result_pattern(MAX_PARSE_DEPTH));
3297        let error = over_limit
3298            .parse_pattern()
3299            .expect_err("one level beyond the nesting limit should fail");
3300        assert_eq!(error.message, "Code is nested too deeply");
3301        assert_eq!(over_limit.depth, 0);
3302    }
3303
3304    fn chain_depth_error(source: &str) -> Option<String> {
3305        crate::parse(source)
3306            .err()
3307            .map(|error| error.message)
3308            .filter(|message| message == "Code is nested too deeply")
3309    }
3310
3311    #[test]
3312    fn long_operator_and_postfix_chains_count_toward_the_depth_cap() {
3313        // Every link nests the AST one level deeper, so a chain longer than
3314        // the cap is rejected even though the parser loops rather than
3315        // recursing over it.
3316        for (link, open) in [
3317            (" + 1", "let x = 1"),
3318            (" * 1", "let x = 1"),
3319            (" == 1", "let x = 1"),
3320            (" < 1", "let x = 1"),
3321            (" && true", "let x = true"),
3322            (" || true", "let x = true"),
3323            ("[0]", "let x = y"),
3324            (".to_str()", "let x = y"),
3325            (".field", "let x = y"),
3326            ("(1)", "let x = f"),
3327        ] {
3328            let long = format!("{open}{}", link.repeat(MAX_PARSE_DEPTH + 1));
3329            assert!(chain_depth_error(&long).is_some(), "{long:.40}");
3330            let short = format!("{open}{}", link.repeat(MAX_PARSE_DEPTH / 2));
3331            assert!(crate::parse(&short).is_ok(), "{short:.40}");
3332        }
3333    }
3334
3335    #[test]
3336    fn chain_links_are_released_when_the_chain_ends() {
3337        // Many sibling chains, each well inside the cap, never accumulate.
3338        let statements = vec!["let x = 1 + 1 + 1 + 1 + 1"; MAX_PARSE_DEPTH * 2].join("\n");
3339        crate::parse(&statements).expect("independent chains parse");
3340        let arguments = vec!["1 + 1 + 1"; MAX_PARSE_DEPTH * 2].join(", ");
3341        crate::parse(&format!("f({arguments})")).expect("sibling arguments parse");
3342    }
3343
3344    #[test]
3345    fn malformed_result_shorthand_restores_pattern_depth() {
3346        let mut parser = pattern_parser("Ok(");
3347        parser
3348            .parse_pattern()
3349            .expect_err("incomplete shorthand should fail");
3350        assert_eq!(parser.depth, 0);
3351    }
3352
3353    #[test]
3354    fn namespaced_pattern_error_restores_pattern_depth() {
3355        // This path contains both a fallible identifier parse and an explicit
3356        // validation return; keep both covered alongside the reported Ok/Err
3357        // shorthand path.
3358        for source in ["module.", "module.lowercase"] {
3359            let mut parser = pattern_parser(source);
3360            parser
3361                .parse_pattern()
3362                .expect_err("the namespaced pattern should be malformed");
3363            assert_eq!(parser.depth, 0, "source: {source}");
3364        }
3365    }
3366}
3367
3368#[cfg(test)]
3369mod integer_boundary_tests {
3370    use super::*;
3371
3372    fn expression(source: &str) -> Result<Expr, NyblError> {
3373        let mut parser = Parser::new(crate::lexer::lex(source)?);
3374        let expression = parser.parse_expr()?;
3375        assert!(matches!(parser.peek(), Token::Eof), "source: {source}");
3376        Ok(expression)
3377    }
3378
3379    fn pattern(source: &str) -> Result<Pattern, NyblError> {
3380        let mut parser = Parser::new(crate::lexer::lex(source)?);
3381        let pattern = parser.parse_pattern()?;
3382        assert!(matches!(parser.peek(), Token::Eof), "source: {source}");
3383        Ok(pattern)
3384    }
3385
3386    #[test]
3387    fn immediate_unary_minus_folds_the_minimum_integer() {
3388        for source in [
3389            "-9223372036854775808",
3390            "- 9223372036854775808",
3391            "- // continue the operand\n  9223372036854775808",
3392            "(-9223372036854775808)",
3393        ] {
3394            let expression = expression(source).expect("minimum integer should parse");
3395            assert!(
3396                matches!(expression.kind, ExprKind::Int(i64::MIN)),
3397                "source: {source}; expression: {expression:?}"
3398            );
3399        }
3400    }
3401
3402    #[test]
3403    fn minimum_integer_fold_preserves_outer_unary_precedence() {
3404        let expression = expression("--9223372036854775808").expect("double negation parses");
3405        assert!(matches!(
3406            expression.kind,
3407            ExprKind::UnaryOp {
3408                op: UnaryOp::Neg,
3409                expr,
3410            } if matches!(expr.kind, ExprKind::Int(i64::MIN))
3411        ));
3412    }
3413
3414    #[test]
3415    fn unnegated_or_non_immediate_minimum_magnitude_is_rejected() {
3416        let cases = [
3417            ("  9223372036854775808", 3),
3418            ("0 - 9223372036854775808", 5),
3419            ("-(9223372036854775808)", 3),
3420        ];
3421        for (source, column) in cases {
3422            let error = expression(source).expect_err("positive magnitude must be rejected");
3423            assert_eq!(error.line, Some(1), "source: {source}");
3424            assert_eq!(error.column, Some(column), "source: {source}");
3425            assert_eq!(
3426                error.message, "Integer literal out of range for i64: 9223372036854775808",
3427                "source: {source}"
3428            );
3429        }
3430    }
3431
3432    #[test]
3433    fn minimum_integer_pattern_is_exact_and_positive_pattern_is_rejected() {
3434        for source in [
3435            "-9223372036854775808",
3436            "- 9223372036854775808",
3437            "- // continue the pattern\n  9223372036854775808",
3438        ] {
3439            assert!(
3440                matches!(
3441                    pattern(source).expect("negative boundary pattern should parse"),
3442                    Pattern::Literal(LiteralPattern::Int(i64::MIN))
3443                ),
3444                "source: {source}"
3445            );
3446        }
3447
3448        let error =
3449            pattern("9223372036854775808").expect_err("positive boundary pattern must be rejected");
3450        assert_eq!(error.line, Some(1));
3451        assert_eq!(error.column, Some(1));
3452        assert_eq!(
3453            error.message,
3454            "Integer literal out of range for i64: 9223372036854775808"
3455        );
3456    }
3457}
3458
3459#[cfg(test)]
3460mod token_ownership_tests {
3461    use super::*;
3462
3463    fn ident_ptr(tokens: &[SpannedToken], expected: &str, occurrence: usize) -> *const u8 {
3464        tokens
3465            .iter()
3466            .filter_map(|spanned| match &spanned.token {
3467                Token::Ident(name) if name == expected => Some(name.as_ptr()),
3468                _ => None,
3469            })
3470            .nth(occurrence)
3471            .expect("expected identifier token")
3472    }
3473
3474    fn string_ptr(tokens: &[SpannedToken], expected: &str) -> *const u8 {
3475        tokens
3476            .iter()
3477            .find_map(|spanned| match &spanned.token {
3478                Token::Str(value) if value == expected => Some(value.as_ptr()),
3479                _ => None,
3480            })
3481            .expect("expected string token")
3482    }
3483
3484    #[test]
3485    fn declaration_and_primary_payloads_move_from_tokens_into_the_ast() {
3486        let tokens =
3487            crate::lexer::lex(r#"let owned_name = "owned_literal""#).expect("source should lex");
3488        let name_ptr = ident_ptr(&tokens, "owned_name", 0);
3489        let literal_ptr = string_ptr(&tokens, "owned_literal");
3490
3491        let statements = parse(tokens).expect("source should parse");
3492        let StmtKind::Let { name, value, .. } = &statements[0].kind else {
3493            panic!("expected let statement")
3494        };
3495        let ExprKind::Str(literal) = &value.kind else {
3496            panic!("expected string value")
3497        };
3498
3499        assert_eq!(name.as_ptr(), name_ptr);
3500        assert_eq!(literal.as_ptr(), literal_ptr);
3501    }
3502
3503    #[test]
3504    fn interpolation_and_dict_key_buffers_move_into_the_ast() {
3505        let interpolation_tokens =
3506            crate::lexer::lex(r#""left {owned_var} right""#).expect("interpolation should lex");
3507        let (parts_ptr, variable_ptr) = interpolation_tokens
3508            .iter()
3509            .find_map(|spanned| match &spanned.token {
3510                Token::StringInterp(parts) => Some((
3511                    parts.as_ptr(),
3512                    parts.iter().find_map(|part| match part {
3513                        StringPart::Variable(name) => Some(name.as_ptr()),
3514                        StringPart::Literal(_) => None,
3515                    })?,
3516                )),
3517                _ => None,
3518            })
3519            .expect("expected interpolation token");
3520
3521        let statements = parse(interpolation_tokens).expect("interpolation should parse");
3522        let StmtKind::ExprStmt(Expr {
3523            kind: ExprKind::StringInterp(parts),
3524            ..
3525        }) = &statements[0].kind
3526        else {
3527            panic!("expected interpolation expression")
3528        };
3529        let ast_variable_ptr = parts
3530            .iter()
3531            .find_map(|part| match part {
3532                StringPart::Variable(name) => Some(name.as_ptr()),
3533                StringPart::Literal(_) => None,
3534            })
3535            .expect("expected interpolation variable");
3536        assert_eq!(parts.as_ptr(), parts_ptr);
3537        assert_eq!(ast_variable_ptr, variable_ptr);
3538
3539        let dict_tokens = crate::lexer::lex(r#"{"owned_key": 1}"#).expect("dictionary should lex");
3540        let key_ptr = string_ptr(&dict_tokens, "owned_key");
3541        let statements = parse(dict_tokens).expect("dictionary should parse");
3542        let StmtKind::ExprStmt(Expr {
3543            kind: ExprKind::Dict(entries),
3544            ..
3545        }) = &statements[0].kind
3546        else {
3547            panic!("expected dictionary expression")
3548        };
3549        assert_eq!(entries[0].0.as_ptr(), key_ptr);
3550    }
3551
3552    #[test]
3553    fn pattern_payloads_move_from_tokens_into_the_ast() {
3554        let tokens = crate::lexer::lex(
3555            r#"match subject { ["owned_pattern", owned_binding, ..owned_rest] => owned_binding }"#,
3556        )
3557        .expect("pattern should lex");
3558        let literal_ptr = string_ptr(&tokens, "owned_pattern");
3559        let binding_ptr = ident_ptr(&tokens, "owned_binding", 0);
3560        let rest_ptr = ident_ptr(&tokens, "owned_rest", 0);
3561
3562        let statements = parse(tokens).expect("pattern should parse");
3563        let StmtKind::ExprStmt(Expr {
3564            kind: ExprKind::Match { arms, .. },
3565            ..
3566        }) = &statements[0].kind
3567        else {
3568            panic!("expected match expression")
3569        };
3570        let Pattern::Array { elements, rest } = &arms[0].pattern else {
3571            panic!("expected array pattern")
3572        };
3573        let Pattern::Literal(LiteralPattern::Str(literal)) = &elements[0] else {
3574            panic!("expected string pattern")
3575        };
3576        let Pattern::Binding(binding) = &elements[1] else {
3577            panic!("expected binding pattern")
3578        };
3579        let Some(ArrayRest::Named(rest)) = rest else {
3580            panic!("expected named rest pattern")
3581        };
3582
3583        assert_eq!(literal.as_ptr(), literal_ptr);
3584        assert_eq!(binding.as_ptr(), binding_ptr);
3585        assert_eq!(rest.as_ptr(), rest_ptr);
3586    }
3587}
3588
3589#[cfg(test)]
3590mod struct_literal_context_tests {
3591    use super::*;
3592
3593    fn expression_parser(source: &str) -> Parser {
3594        Parser::new(crate::lexer::lex(source).expect("test expression should lex"))
3595    }
3596
3597    #[test]
3598    fn delimiter_errors_restore_restricted_struct_literal_context() {
3599        let cases = [
3600            "(Point { x: 1 }",
3601            "get_x(Point { x: 1 }",
3602            "items[Point { x: 1 }.x",
3603            "[Point { x: 1 }",
3604            r#"{"point": Point { x: 1 }"#,
3605            "Ok(Point { x: 1 }",
3606            "Result::Ok(Point { x: 1 }",
3607            "match 1 { _ => Point { x: 1 }",
3608            "fn() { return Point { x: 1 }",
3609        ];
3610
3611        for source in cases {
3612            let mut parser = expression_parser(source);
3613            parser.allow_struct_literal = false;
3614            parser
3615                .parse_expr()
3616                .expect_err("the deliberately unclosed delimiter should fail");
3617            assert!(!parser.allow_struct_literal, "source: {source}");
3618        }
3619    }
3620}
3621
3622#[cfg(test)]
3623mod targeted_diagnostic_tests {
3624    use super::*;
3625
3626    fn parse_source(source: &str) -> Result<Vec<Stmt>, NyblError> {
3627        parse(crate::lexer::lex(source)?)
3628    }
3629
3630    #[test]
3631    fn block_shaped_match_arm_points_at_the_opening_brace() {
3632        for source in [
3633            "let label = match 1 {\n  1 => { print(\"one\") },\n  _ => \"other\",\n}",
3634            "let label = match 1 {\n  1 => { \"one\"; print(\"done\") },\n  _ => \"other\",\n}",
3635        ] {
3636            let error = parse_source(source).expect_err("block-shaped arm must be rejected");
3637
3638            assert_eq!(error.line, Some(2), "source: {source}");
3639            assert_eq!(error.column, Some(8), "source: {source}");
3640            assert_eq!(
3641                error.message,
3642                "`{ ... }` after `=>` is a dictionary expression, not a match-arm block",
3643                "source: {source}"
3644            );
3645            assert_eq!(
3646                error.friendly_hint.as_deref(),
3647                Some(
3648                    "`match` arm bodies must be a single expression; put it directly after `=>`, or quote dictionary keys if you meant to return a dictionary."
3649                ),
3650                "source: {source}"
3651            );
3652        }
3653    }
3654
3655    #[test]
3656    fn dotdot_in_expression_points_at_the_operator_and_suggests_range() {
3657        for (source, line, column) in [
3658            ("for i in 0..3 {}", 1, 11),
3659            ("let values = 4..9", 1, 15),
3660            ("let values = (\n  4..9\n)", 2, 4),
3661        ] {
3662            let error = parse_source(source).expect_err("expression range must be rejected");
3663            assert_eq!(error.line, Some(line), "source: {source}");
3664            assert_eq!(error.column, Some(column), "source: {source}");
3665            assert_eq!(
3666                error.message, "`..` range syntax is not supported in expressions",
3667                "source: {source}"
3668            );
3669            assert_eq!(
3670                error.friendly_hint.as_deref(),
3671                Some("use `range(start, end)` instead, for example `range(0, 3)`."),
3672                "source: {source}"
3673            );
3674        }
3675    }
3676
3677    #[test]
3678    fn dictionary_arms_and_rest_patterns_keep_their_existing_grammar() {
3679        parse_source(
3680            r#"struct Pair { left, right }
3681let value = match [1, 2, 3] {
3682  [head, ..tail] => {"head": head, "tail": tail},
3683  _ => {},
3684}
3685let pair = Pair { left: 1, right: 2 }
3686let right = match pair {
3687  Pair { left, .. } => left,
3688}"#,
3689        )
3690        .expect("valid dictionary arms and rest patterns must still parse");
3691    }
3692}
3693
3694#[cfg(test)]
3695mod pattern_binding_name_tests {
3696    use super::*;
3697
3698    fn parse_source(source: &str) -> Result<Vec<Stmt>, NyblError> {
3699        parse(crate::lexer::lex(source)?)
3700    }
3701
3702    fn assert_pattern_binding_error(
3703        source: &str,
3704        site: &str,
3705        name: &str,
3706        kind: &str,
3707        line: u32,
3708        column: u32,
3709    ) {
3710        let error = parse_source(source)
3711            .expect_err("constant- and type-shaped pattern bindings must be rejected");
3712        assert_eq!(
3713            error.message,
3714            format!("{site} `{name}` looks like a {kind}, but a value name is required here"),
3715            "source: {source}"
3716        );
3717        assert_eq!(error.line, Some(line), "source: {source}");
3718        assert_eq!(error.column, Some(column), "source: {source}");
3719        assert_eq!(
3720            error.friendly_hint.as_deref(),
3721            Some(naming::pattern_binding_hint(name).as_str()),
3722            "source: {source}"
3723        );
3724    }
3725
3726    #[test]
3727    fn constant_shaped_bare_pattern_cannot_shadow_constant() {
3728        assert_pattern_binding_error(
3729            "const Y = 2\nmatch 3 { Y => 0 }",
3730            "`match` pattern binding",
3731            "Y",
3732            "constant",
3733            2,
3734            11,
3735        );
3736    }
3737
3738    #[test]
3739    fn nested_and_specialized_pattern_bindings_apply_value_name_rules() {
3740        let cases = [
3741            (
3742                "match value {\n  [head, TypeName] => 0,\n}",
3743                "`match` pattern binding",
3744                "TypeName",
3745                "type",
3746                2,
3747                10,
3748            ),
3749            (
3750                "match value {\n  Maybe::Some(CONSTANT) => 0,\n}",
3751                "`match` pattern binding",
3752                "CONSTANT",
3753                "constant",
3754                2,
3755                15,
3756            ),
3757            (
3758                "match value {\n  Point { x: TypeName } => 0,\n}",
3759                "`match` pattern binding",
3760                "TypeName",
3761                "type",
3762                2,
3763                14,
3764            ),
3765            (
3766                "match value {\n  [head, ..TAIL] => 0,\n}",
3767                "`match` pattern rest binding",
3768                "TAIL",
3769                "constant",
3770                2,
3771                12,
3772            ),
3773            (
3774                "match value {\n  Point { Field } => 0,\n}",
3775                "`match` pattern shorthand binding",
3776                "Field",
3777                "type",
3778                2,
3779                11,
3780            ),
3781            (
3782                "match value {\n  Maybe::Named { FIELD } => 0,\n}",
3783                "`match` pattern shorthand binding",
3784                "FIELD",
3785                "constant",
3786                2,
3787                18,
3788            ),
3789        ];
3790
3791        for (source, site, name, kind, line, column) in cases {
3792            assert_pattern_binding_error(source, site, name, kind, line, column);
3793        }
3794    }
3795
3796    #[test]
3797    fn constant_shaped_or_alternative_reports_the_naming_error_first() {
3798        assert_pattern_binding_error(
3799            "match 1 {\n  1 | Y => 0,\n}",
3800            "`match` pattern binding",
3801            "Y",
3802            "constant",
3803            2,
3804            7,
3805        );
3806    }
3807
3808    #[test]
3809    fn uppercase_type_variant_syntax_and_wildcards_remain_valid() {
3810        parse_source(
3811            r#"enum HTTP { OK(value), EMPTY }
3812fn classify(value) {
3813  return match value {
3814    HTTP::OK(inner) => inner,
3815    HTTP::EMPTY => 0,
3816    _ => 0,
3817  }
3818}
3819fn classify_imported(value) {
3820  return match value {
3821    network.HTTP::OK(inner) => inner,
3822    _ => 0,
3823  }
3824}
3825match [1, 2] {
3826  [head, ..] => head,
3827  _ => 0,
3828}"#,
3829        )
3830        .expect("type/variant names and wildcard patterns must retain their grammar");
3831    }
3832}
3833
3834#[cfg(test)]
3835mod or_pattern_binding_tests {
3836    use super::*;
3837
3838    fn pattern(source: &str) -> Result<Pattern, NyblError> {
3839        let mut parser = Parser::new(crate::lexer::lex(source).expect("test pattern should lex"));
3840        let pattern = parser.parse_pattern()?;
3841        assert!(matches!(parser.peek(), Token::Eof), "source: {source}");
3842        Ok(pattern)
3843    }
3844
3845    #[test]
3846    fn inconsistent_or_pattern_reports_offending_alternative_location_and_hint() {
3847        let source = "match 1 {\n    1 | y => y,\n}";
3848        let error = parse(crate::lexer::lex(source).expect("source should lex"))
3849            .expect_err("inconsistent alternatives must fail during parsing");
3850
3851        assert_eq!(error.line, Some(2));
3852        assert_eq!(error.column, Some(9));
3853        assert_eq!(
3854            error.message,
3855            "`or`-pattern alternative 2 binds `y`, but alternative 1 binds no names"
3856        );
3857        assert_eq!(
3858            error.friendly_hint.as_deref(),
3859            Some("make every `|` alternative bind the same names; only in alternative 2: `y`")
3860        );
3861    }
3862
3863    #[test]
3864    fn inconsistent_nested_pattern_bindings_are_deterministic() {
3865        let cases = [
3866            (
3867                "[x, y] | [x, z]",
3868                "missing from alternative 2: `y`; only in alternative 2: `z`",
3869            ),
3870            (
3871                "Node { left: x, right: y, .. } | Node { left: x, .. }",
3872                "missing from alternative 2: `y`",
3873            ),
3874            (
3875                "Maybe::Some([x, ..tail]) | Maybe::Some([x, ..])",
3876                "missing from alternative 2: `tail`",
3877            ),
3878        ];
3879
3880        for (source, expected_hint_tail) in cases {
3881            let error = pattern(source).expect_err("binding sets should differ");
3882            assert!(
3883                error
3884                    .friendly_hint
3885                    .as_deref()
3886                    .is_some_and(|hint| hint.ends_with(expected_hint_tail)),
3887                "source: {source}; error: {error:?}"
3888            );
3889        }
3890    }
3891
3892    #[test]
3893    fn reordered_relocated_and_duplicate_bindings_are_valid() {
3894        let cases = [
3895            (
3896                "[left, right, ..tail] | [right, left, ..tail]",
3897                &["left", "right", "tail"][..],
3898            ),
3899            (
3900                "Pair::Both(left, right) | Pair::Both(right, left)",
3901                &["left", "right"],
3902            ),
3903            (
3904                "Node { left, right, .. } | Node { left: right, right: left, .. }",
3905                &["left", "right"],
3906            ),
3907            (
3908                "Maybe::Some { first: left, second: [right, ..tail], .. } | Maybe::Some { first: right, second: [left, ..tail], .. }",
3909                &["left", "right", "tail"],
3910            ),
3911            ("[x, x] | [_, x]", &["x"]),
3912        ];
3913
3914        for (source, expected) in cases {
3915            let parsed = pattern(source).expect("matching binding sets should parse");
3916            let binding_names = parsed.binding_names();
3917            let names: Vec<&str> = binding_names.iter().map(String::as_str).collect();
3918            assert_eq!(names, expected, "source: {source}");
3919        }
3920    }
3921}