Skip to main content

oxdock_parser/
parser.rs

1//! Script parser: [`Tok`] stream to [`Step`].
2//!
3//! The single parser for string scripts and braced-macro token
4//! streams. The string entry points at the bottom of this module lex
5//! with `lex_str` and lower here; the braced-macro frontend fuses
6//! span-adjacent literals, runs the same scanner, and lowers here.
7//!
8//! Statement boundaries resolve here from grammar state, never in the
9//! lexers: groups arrive structurally atomic, so at each nesting level
10//! a `Newline`/`Semicolon` ends the statement. Continuation exceptions
11//! (trailing `=`, `IN`, trailing `ASYNC`, bare wrapper heads) land with
12//! their structural slices; the decision point is
13//! `boundary_ends_statement`.
14//!
15//! Coverage: generic commands (head word plus gap-split args with
16//! quote-accurate joins), guards (leading `[..]` groups; in-body
17//! brackets splice to raw text), `LET`/reassignment (`$var = <expr>`)/`RETURN`
18//! with the full expression tiers, static calls and RUN-exec with instruction
19//! exactness, single-command wrappers (`WITH_IO`/`TIMEOUT`/`ISOLATED`/
20//! `ASYNC`), io-blocks, `AWAIT`/`CANCEL`, multi-element statements,
21//! block statements (`IF`/`FOR`/`WHILE`/`FUNC`/`REMOTE`/`TYPE`/
22//! `IMPORT`/`EXPORT`), guard blocks, and a whole-script post-pass
23//! (prelude order, COPY placement, EXPORT membership). Comments ride
24//! as `TokKind::Comment` markers plus mid-line `//`/`#`/`/*` gap
25//! rules.
26//!
27//! Design record: shared lowering cores with parser-native token
28//! classification. Each item below states what is shared and what is
29//! parser-native (verified by the lexer-agreement oracle and the fuzz
30//! harness).
31//! - Argument assembly matches single-quoted-string `quoted=true` and
32//!   multi-fragment space-or-empty joins by the `joint` flag.
33//! - `key_char`/`bare_run`/`value_run` implement the guard key/value
34//!   charsets (everything but `: = ! , | ( ) ] $`, whitespace, and
35//!   comment opens; `eq` values cross gaps like the atomic span).
36//! - `ns_guard` validates namespaces with shared messages.
37//! - Guard validation strings (`any(...)/all(...)/eq(...)` shapes)
38//!   carry shared messages.
39//! - `parse_guard_groups` folds stacked brackets with `All` (the
40//!   statement-guard stash semantics).
41//! - The expression tiers implement or/and/compare/ordering/add/mul/
42//!   unary/atom precedence over [`Tok`]; lowering runs through the
43//!   shared constructors (`make_arith`, `make_compare`,
44//!   `apply_unary_neg`, `reject_boundary`, `classify_numeric_text`,
45//!   `canonicalize_spelling`, `lower_block_string`).
46//! - Static call resolution is truly shared (`resolve_call_name`,
47//!   `check_func_ident` in `resolve.rs`).
48//! - Instruction tokens are truly shared (`InsToken`,
49//!   `lower_env_tokens`, `lower_expand_tokens`,
50//!   `canonical_assignment_arg` in `commands.rs`); only the
51//!   token-level classifiers (key runs, boundaries, call shapes,
52//!   expression extension) are parser-native.
53//! - Numeric `_`-separator shape gating, bare-word charsets, and
54//!   `-`-prefix dispatch match the lexical rules (durations, paths,
55//!   and versions lex as bare words; `-f` stays literal).
56//! - Wrapper validators are truly shared (`check_tty_wrapping`,
57//!   `reject_async_in_capture`, `reject_pipe_stdout_in_capture`,
58//!   `rewrite_isolated_inherit`, `contains_inherit_env`,
59//!   `reject_nested_inherit_env`, `merge_bindings`, `IoBindingSet`,
60//!   `and_guard_exprs`, `reject_with_io_in_async` in `commands.rs`;
61//!   in `commands.rs`); only the token-level shape classifiers
62//!   (duration gate, binding splitter, await/cancel shapes,
63//!   block-vs-template, inherit keys) are parser-native.
64//! - The element loop lowers consecutive elements to end of run:
65//!   structural pairs end mid-line and trailing elements form
66//!   following steps (guards attach to the first only); the `WITH_IO`
67//!   pending wait holds bare brackets across separators.
68//! - Block headers: `IF`/`FOR`/`WHILE` conditions miss to generic
69//!   on unclassified expression failure (classified callee failures
70//!   and inline-block failures propagate); `FUNC` paren-group params parse with `gap_nl`
71//!   discipline (shared helper, like call args); `REMOTE` targets/blocks/bindings; `TYPE` maximal
72//!   shape match; `IMPORT`/`EXPORT` lists. Shared
73//!   validators are truly shared (`validate_remote_copy_placement`,
74//!   `contains_remote_block`, `collect_remote_body_symbols`,
75//!   `validate_exports` in `commands.rs`).
76//! - Scope marking: top-level guard nesting
77//!   bumps each level (stateful `pending_scope_enters`); wrapper and
78//!   guard-block bodies pin 0/0 (`parse_body_steps` without marking).
79//! - Comment handling: statement-position
80//!   comments vanish (releasing `ELSE` holds), gap positions skip,
81//!   arg positions type or glue literally; `/*` depth protects
82//!   separators in the splitter, and group scanning copies comments
83//!   through for the recursive re-lex.
84
85use crate::ast::{
86    Arg, ArithOp, CompareOp, Expr, Guard, GuardExpr, IoBinding, IoStream, LogicalOp, ModuleTable,
87    Ns, Step, StepKind, Value,
88};
89use crate::command::ArgType;
90use crate::commands::{
91    BindRhs, InsToken, apply_unary_neg, canonical_assignment_arg, check_tty_wrapping,
92    classify_numeric_text, is_known_command, lower_env_tokens, lower_expand_tokens, make_arith,
93    make_compare, reject_boundary,
94};
95use crate::constants::{
96    INJECT_PREFIX, INJECT_SUFFIX, KEYWORD_AS, KEYWORD_ASYNC, KEYWORD_AWAIT, KEYWORD_BREAK,
97    KEYWORD_CANCEL, KEYWORD_CASE, KEYWORD_CONST, KEYWORD_CONTINUE, KEYWORD_DEFAULT, KEYWORD_ELSE,
98    KEYWORD_ENV, KEYWORD_EXPAND, KEYWORD_EXPORT, KEYWORD_FAIL, KEYWORD_FOR, KEYWORD_FROM,
99    KEYWORD_FUNC, KEYWORD_IF, KEYWORD_IMPORT, KEYWORD_IN, KEYWORD_INHERIT_ENV, KEYWORD_INSPECT,
100    KEYWORD_ISOLATED, KEYWORD_LET, KEYWORD_REMOTE, KEYWORD_RETURN, KEYWORD_RUN, KEYWORD_SWITCH,
101    KEYWORD_TIMEOUT, KEYWORD_TYPE, KEYWORD_WHILE, KEYWORD_WITH_IO, MODULE_SEPARATOR,
102    VAR_SIGIL_CHAR, qualify, sigil_qualified, sigil_var,
103};
104use crate::error::{ParseError, ParseErrorKind, ParseResult, SpanContext};
105
106use crate::resolve::resolve_call_name;
107use crate::tok::{GroupDelim, LexError, Tok, TokKind, lex_str};
108use std::cell::RefCell;
109use std::collections::HashSet;
110use std::fmt;
111
112/// Backend error. Carries the statement index and message; the string
113/// entry points below map it to [`crate::ParseError`]. Lowering
114/// failures from the shared `lower` dispatcher stringify through here
115/// so success paths compare exactly.
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub struct TokenError {
118    pub stmt: usize,
119    /// 1-based source line, `0` when unknown (the split loops stamp the
120    /// enclosing statement's line on the way out, so only genuinely
121    /// position-less errors stay `0`).
122    pub line: usize,
123    /// 1-based start column of the enclosing statement, `0` when
124    /// unknown (stamped alongside `line`).
125    pub col: usize,
126    pub msg: String,
127    /// Lowering failures preserve the dispatcher's classification
128    /// (`UnknownCommand`, `InvalidSyntax`, `Validation`); `None` means
129    /// a parser-native structural failure.
130    pub kind: Option<ParseErrorKind>,
131}
132
133impl fmt::Display for TokenError {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        write!(
136            f,
137            "parse error in statement {}: {}",
138            self.stmt + 1,
139            self.msg
140        )
141    }
142}
143
144impl std::error::Error for TokenError {}
145
146/// Lift a dispatcher/resolver [`ParseError`] into a [`TokenError`],
147/// preserving its machine-readable classification (the entry points
148/// convert it back verbatim, so `UnknownCommand`/`InvalidSyntax`/
149/// `Validation` survive the round trip). The message is the
150/// dispatcher's own display text; the split loops stamp the line.
151fn lower_err(stmt: usize, e: ParseError) -> TokenError {
152    TokenError {
153        stmt,
154        line: 0,
155        col: 0,
156        msg: e.to_string(),
157        kind: Some(e.kind().clone()),
158    }
159}
160
161/// One split statement: leading bracket groups (guard region) plus
162/// the body tokens. `brace_detached` records a
163/// `Newline`/`Semicolon` between the guard region and a brace-headed
164/// body: in-body such statements are hard errors (a bare `{` is
165/// illegal inside blocks), while top level merges or parses guard
166/// blocks regardless.
167#[derive(Debug, Clone)]
168struct Stmt {
169    guard: Vec<Tok>,
170    body: Vec<Tok>,
171    brace_detached: bool,
172    /// 1-based source line where the body starts (guards ride on
173    /// earlier lines; errors report this).
174    line: usize,
175    /// 1-based column where the body starts (`0` when the head token
176    /// carries no coordinates: synthetic streams). Read off the first
177    /// body token, which always has the statement's own start.
178    col: usize,
179}
180
181impl PartialEq for Stmt {
182    fn eq(&self, other: &Self) -> bool {
183        // Coordinates are provenance (never rendered, never compared),
184        // like `Step`/`Tok`: two splits of one text compare equal.
185        self.guard == other.guard
186            && self.body == other.body
187            && self.brace_detached == other.brace_detached
188    }
189}
190
191impl Eq for Stmt {}
192
193/// True when a newline continues the statement for a multi-line
194/// generic: the body opens a type-carrying statement (TYPE/LET/CONST/FOR)
195/// and holds an unclosed `<...>` shape. Only a joint `<` after an
196/// uppercase word opens (never `<=`, never `$VAR<`), so spaced
197/// comparisons keep ending the statement as before. FUNC needs no
198/// gate: parameter types ride inside the atomic paren group, and the
199/// grammar defines no return-type position after the group.
200fn type_continuation_rides(body: &[Tok], next: Option<&Tok>) -> bool {
201    if !matches!(
202        body.first().map(|t| &t.kind),
203        Some(TokKind::Word(w)) if w == KEYWORD_TYPE || w == KEYWORD_LET || w == KEYWORD_CONST || w == KEYWORD_FOR
204    ) {
205        return false;
206    }
207    open_generic_depth(body, next) > 0
208}
209
210/// Unclosed `<...>` depth over a statement body: a joint `<` after
211/// an uppercase word opens (generic instantiation), `>` closes.
212fn open_generic_depth(body: &[Tok], next: Option<&Tok>) -> usize {
213    let mut depth = 0usize;
214    for (idx, tok) in body.iter().enumerate() {
215        if !matches!(&tok.kind, TokKind::Punct('<')) {
216            if matches!(&tok.kind, TokKind::Punct('>')) && depth > 0 {
217                depth -= 1;
218            }
219            continue;
220        }
221        if !tok.joint {
222            continue;
223        }
224        if idx == 0 {
225            continue;
226        }
227        if !matches!(
228            body.get(idx - 1).map(|t| &t.kind),
229            Some(TokKind::Word(w)) if is_upper_ident(w)
230        ) {
231            continue;
232        }
233        // `$VAR<` is a comparison, never a generic.
234        if idx >= 2
235            && body.get(idx - 1).is_some_and(|t| t.joint)
236            && matches!(
237                body.get(idx - 2).map(|t| &t.kind),
238                Some(TokKind::Punct(VAR_SIGIL_CHAR))
239            )
240        {
241            continue;
242        }
243        // `<=` is a comparison lead, never a generic open.
244        let followed_by_eq = matches!(
245            body.get(idx + 1).map(|t| &t.kind),
246            Some(TokKind::Punct('='))
247        ) || (idx + 1 == body.len()
248            && matches!(next.map(|t| &t.kind), Some(TokKind::Punct('='))));
249        if !followed_by_eq {
250            depth += 1;
251        }
252    }
253    depth
254}
255
256/// Grammar-state boundary decision: does this `Newline`/`Semicolon`
257/// end the statement? Groups are atomic, so every statement fits one
258/// logical token line; every keyword-headed statement (commands,
259/// wrappers, `LET`/`AWAIT`, block statements, directives) ends here.
260/// Only non-word heads fail, exactly like the grammar's element
261/// mismatch.
262fn boundary_ends_statement(body: &[Tok]) -> Result<bool, String> {
263    let head = match body.first() {
264        None => return Ok(true),
265        Some(t) => t,
266    };
267    match &head.kind {
268        TokKind::Word(_) | TokKind::Punct(VAR_SIGIL_CHAR) => Ok(true),
269        // A lone leading `{...}` ends here too: the splitter merges
270        // it into pending waits (`WITH_IO`, `IF`/`ELSE` chains) or
271        // emits it for block-statement lowering, never splitting
272        // inside.
273        TokKind::Group {
274            delim: GroupDelim::Brace,
275            ..
276        } => Ok(true),
277        _ => Err("statement must open with a command word".to_string()),
278    }
279}
280
281/// Bare `WITH_IO [..]` with no inner command: holds the line for a
282/// following `{...}` block (bare-bracket hold), which merges into one
283/// io-block statement. Anything else (or EOF) fails exactly like the
284/// grammar's `must be followed by '{'`.
285fn is_bare_with_io(body: &[Tok]) -> bool {
286    matches!(body.first().map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_WITH_IO)
287        && matches!(
288            body.get(1).map(|t| (&t.kind, t.joint)),
289            Some((
290                TokKind::Group {
291                    delim: GroupDelim::Bracket,
292                    ..
293                },
294                false
295            ))
296        )
297        && body.len() == 2
298}
299
300/// An if-tailed statement body: head `IF`, ends with a non-template
301/// brace (the then/else-if block), ignoring trailing gap comments.
302/// Trailing `//`/`#` runs and balanced `/* */` strip backward (the
303/// grammar's `gap` eats them before the `ELSE` chain, joint state
304/// irrelevant after a complete pair); anything else trailing (text,
305/// groups, strings) breaks the tail. Over-holding is safe: a merged
306/// non-`ELSE` follower releases, and a merged `ELSE` parses exactly
307/// where the grammar would.
308fn is_if_tail(body: &[Tok]) -> bool {
309    if !matches!(body.first().map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_IF) {
310        return false;
311    }
312    let mut end = body.len();
313    loop {
314        // Lexer comment markers.
315        while end > 0 && matches!(&body[end - 1].kind, TokKind::Comment(_)) {
316            end -= 1;
317        }
318        // Earliest comment opener (`//`-pair, `#`, `/*`-pair) starts
319        // trailing comment territory.
320        let mut cut = None;
321        let mut k = 0;
322        while k < end {
323            match &body[k].kind {
324                TokKind::Punct('#') => {
325                    cut = Some(k);
326                    break;
327                }
328                TokKind::Punct('/') if is_comment_open(&body[..end], k) => {
329                    cut = Some(k);
330                    break;
331                }
332                _ => k += 1,
333            }
334        }
335        match cut {
336            Some(k) => {
337                // A balanced `/* */` may be followed by more gap
338                // comments; anything else ends the strip for the
339                // brace check below.
340                if matches!(&body[k].kind, TokKind::Punct('/'))
341                    && !matches!(body.get(k + 1).map(|t| &t.kind), Some(TokKind::Punct('/')))
342                {
343                    match skip_inline_comment(&body[..end], k) {
344                        Some(past) if past < end => {
345                            end = past;
346                            continue;
347                        }
348                        _ => {}
349                    }
350                }
351                end = k;
352                continue;
353            }
354            None => break,
355        }
356    }
357    matches!(
358        body[..end].last().map(|t| &t.kind),
359        Some(TokKind::Group {
360            delim: GroupDelim::Brace,
361            ..
362        })
363    ) && body[..end].last().is_some_and(|t| !is_template_brace(t))
364}
365
366/// True when a body opens with a brace group (guard-block position
367/// or bare block).
368fn starts_brace(body: &[Tok]) -> bool {
369    matches!(
370        body.first().map(|t| &t.kind),
371        Some(TokKind::Group {
372            delim: GroupDelim::Brace,
373            ..
374        })
375    )
376}
377
378/// Source lines spanned by one token (for the splitter's line
379/// counter): newlines, `/* */` comment interiors, and nested group
380/// contents. Everything else occupies its own line.
381fn tok_newlines(tok: &Tok) -> usize {
382    match &tok.kind {
383        TokKind::Newline => 1,
384        TokKind::Comment(text) => text.matches('\n').count(),
385        TokKind::Group { inner, .. } => inner.iter().map(tok_newlines).sum(),
386        _ => 0,
387    }
388}
389
390/// Stamp an error with the innermost statement's position when it
391/// has none yet (deeper frames stamp first, so outer frames never
392/// overwrite real positions). Each component fills independently.
393fn stamp_pos(err: TokenError, line: usize, col: usize) -> TokenError {
394    TokenError {
395        line: if err.line == 0 { line } else { err.line },
396        col: if err.col == 0 { col } else { err.col },
397        ..err
398    }
399}
400
401/// Split top-level tokens into statements. Leading `[..]` groups attach
402/// to the following statement as its guard region; `Newline`/`Semicolon`
403/// end statements per [`boundary_ends_statement`]. Empty statements
404/// (blank lines, stray `;`) drop, matching the blank/semicolon
405/// grammar elements. Comment markers drop silently everywhere except
406/// pending `ELSE` waits, which a comment line breaks exactly like the
407/// grammar. Mid-line `//` runs and `#`/`/*` opens with an empty body
408/// skip as comments (statement position, like the grammar's silent
409/// elements); anywhere else they stay payload text for the arg engine.
410fn split_statements(toks: &[Tok], base: usize) -> Result<Vec<Stmt>, TokenError> {
411    let mut stmts = Vec::new();
412    let mut guard = Vec::new();
413    let mut body: Vec<Tok> = Vec::new();
414    let mut stmt_idx = 0;
415    // 1-based source line tracker: `base` is the line `toks[0]` starts
416    // on (1 at top level, the enclosing statement's line inside
417    // groups, where headers are single-line so the brace shares it).
418    // Groups and block comments advance past their inner newlines;
419    // every pushed statement records its body's start line for errors.
420    let mut line = base;
421    let mut start_line = base;
422    let mut start_col = 0;
423    // Bare `WITH_IO [..]` awaiting its `{...}` block (see
424    // `is_bare_with_io`): the guard and body hold across any
425    // separator until the brace arrives or the wait fails.
426    // Pending holds carry their body's start line with them.
427    let mut pending_io: Option<(Vec<Tok>, Vec<Tok>, usize, usize)> = None;
428    // If-tailed statement awaiting an `ELSE` continuation across
429    // newlines only (a `;` breaks the chain like the grammar).
430    let mut pending_if: Option<(Vec<Tok>, Vec<Tok>, usize, usize)> = None;
431    // Separator crossed between the guard region and the body start:
432    // only observed for brace-headed bodies (`brace_detached`).
433    let mut detached = false;
434    // Flush a statement, resolving pending waits first. `via_newline`
435    // records the separator kind: only newlines hold/merge `ELSE`
436    // chains; `;` and EOF release them. `line` is the current tracker
437    // for wait-failure errors; `start_line` is this body's start.
438    let flush_or_hold = |stmts: &mut Vec<Stmt>,
439                         guard: &mut Vec<Tok>,
440                         body: &mut Vec<Tok>,
441                         detached: &mut bool,
442                         stmt_idx: &mut usize,
443                         pending_io: &mut Option<(Vec<Tok>, Vec<Tok>, usize, usize)>,
444                         pending_if: &mut Option<(Vec<Tok>, Vec<Tok>, usize, usize)>,
445                         via_newline: bool,
446                         start_line: usize,
447                         start_col: usize,
448                         line: usize|
449     -> Result<(), TokenError> {
450        if body.is_empty() {
451            guard.clear();
452            *detached = false;
453            return Ok(());
454        }
455        // Pending `WITH_IO` wait takes precedence (the holds are
456        // mutually exclusive: setting either returns first).
457        if let Some((pending_guard, mut pending_body, pending_line, pending_col)) =
458            pending_io.take()
459        {
460            // Only a lone guard-less `{...}` group satisfies the wait;
461            // anything else (commands, guarded braces) fails like the
462            // grammar's `must be followed by '{'`.
463            let lone_brace = guard.is_empty()
464                && body.len() == 1
465                && matches!(
466                    body.first().map(|t| &t.kind),
467                    Some(TokKind::Group {
468                        delim: GroupDelim::Brace,
469                        ..
470                    })
471                );
472            if !lone_brace {
473                return Err(TokenError {
474                    stmt: *stmt_idx,
475                    msg: "WITH_IO block must be followed by '{'".to_string(),
476                    line: pending_line,
477                    col: pending_col,
478                    kind: None,
479                });
480            }
481            pending_body.extend(std::mem::take(body));
482            guard.clear();
483            *detached = false;
484            stmts.push(Stmt {
485                guard: pending_guard,
486                body: pending_body,
487                brace_detached: false,
488                line: pending_line,
489                col: pending_col,
490            });
491            *stmt_idx += 1;
492            return Ok(());
493        }
494        // Pending `ELSE` wait: merge guard-less `ELSE`-led statements.
495        // The wait was set across a newline (only newlines hold), so
496        // the separator kind of *this* flush is irrelevant — `;` and
497        // EOF merge too; anything else releases the held IF.
498        if let Some((held_guard, mut held_body, held_line, held_col)) = pending_if.take() {
499            let else_start = guard.is_empty()
500                && matches!(
501                    body.first().map(|t| &t.kind),
502                    Some(TokKind::Word(w)) if w == KEYWORD_ELSE
503                );
504            if !else_start {
505                stmts.push(Stmt {
506                    guard: held_guard,
507                    body: held_body,
508                    brace_detached: false,
509                    line: held_line,
510                    col: held_col,
511                });
512                *stmt_idx += 1;
513            } else {
514                // The merged chain may hold again for a further
515                // `ELSE`, newlines only, like the grammar. A newline
516                // marker joins the parts: `#` comments end at it
517                // (their extent is unrecoverable post-merge), while
518                // `//`/`/*` carry their own extents.
519                held_body.push(Tok::fresh(TokKind::Newline, false));
520                held_body.extend(std::mem::take(body));
521                guard.clear();
522                *detached = false;
523                if via_newline && is_if_tail(&held_body) {
524                    *pending_if = Some((held_guard, held_body, held_line, held_col));
525                    return Ok(());
526                }
527                stmts.push(Stmt {
528                    guard: held_guard,
529                    body: held_body,
530                    brace_detached: false,
531                    line: held_line,
532                    col: held_col,
533                });
534                *stmt_idx += 1;
535                return Ok(());
536            }
537        }
538        if is_bare_with_io(body) {
539            if pending_io.is_some() {
540                return Err(TokenError {
541                    stmt: *stmt_idx,
542                    msg: "previous WITH_IO block is still waiting for '{'".to_string(),
543                    line,
544                    col: start_col,
545                    kind: None,
546                });
547            }
548            *pending_io = Some((
549                std::mem::take(guard),
550                std::mem::take(body),
551                start_line,
552                start_col,
553            ));
554            *detached = false;
555            return Ok(());
556        }
557        // Ordinary statement: emit it, holding if-tailed bodies for
558        // an `ELSE` continuation across newlines only.
559        if via_newline && is_if_tail(body) {
560            *pending_if = Some((
561                std::mem::take(guard),
562                std::mem::take(body),
563                start_line,
564                start_col,
565            ));
566            *detached = false;
567            return Ok(());
568        }
569        let brace_detached = *detached && !guard.is_empty() && starts_brace(body);
570        stmts.push(Stmt {
571            guard: std::mem::take(guard),
572            body: std::mem::take(body),
573            brace_detached,
574            line: start_line,
575            col: start_col,
576        });
577        *detached = false;
578        *stmt_idx += 1;
579        Ok(())
580    };
581    // Release a pending `ELSE` wait by emitting the held IF as-is.
582    // (Inlined at use sites: a closure would collide with
583    // `flush_or_hold`'s borrow of the statement buffer.)
584    let mut i = 0;
585    // Open text-`/*` depth (line-start comments arrive as `Comment`
586    // toks; `//` never spans separators): newlines and semicolons
587    // inside never split, and `[` never guards (the closer, an
588    // error, or downstream rules resolve everything, exactly like
589    // the grammar).
590    let mut comment_depth = 0usize;
591    // True when `toks[i]` opens a text block comment (`/` plus a
592    // joint `*`; `//` is line-comment territory, handled elsewhere).
593    let block_open_at = |toks: &[Tok], i: usize| {
594        matches!(toks.get(i).map(|t| &t.kind), Some(TokKind::Punct('/')))
595            && matches!(
596                toks.get(i + 1).map(|t| (&t.kind, t.joint)),
597                Some((TokKind::Punct('*'), true))
598            )
599    };
600    // True when `toks[i]` closes one (`*` plus a joint `/`).
601    let block_close_at = |toks: &[Tok], i: usize| {
602        matches!(toks.get(i).map(|t| &t.kind), Some(TokKind::Punct('*')))
603            && matches!(
604                toks.get(i + 1).map(|t| (&t.kind, t.joint)),
605                Some((TokKind::Punct('/'), true))
606            )
607    };
608    while i < toks.len() {
609        let tok = &toks[i];
610        // Statement-start `/*` (silent gap position): skip balanced,
611        // failing unclosed like the grammar; mid-body opens only
612        // deepen the tracker below and ride into args as payload.
613        if body.is_empty() && comment_depth == 0 && block_open_at(toks, i) {
614            match skip_inline_comment(toks, i) {
615                Some(past) => {
616                    // The skipped span may cross lines (`/*a\nb*/`).
617                    line += toks[i..past].iter().map(tok_newlines).sum::<usize>();
618                    i = past;
619                    continue;
620                }
621                None => {
622                    return Err(TokenError {
623                        stmt: stmt_idx,
624                        msg: "unclosed block comment".to_string(),
625                        line,
626                        col: tok.col,
627                        kind: None,
628                    });
629                }
630            }
631        }
632        // Nesting transitions on text pairs (mid-body opens deepen;
633        // closers pop when nested).
634        if block_open_at(toks, i) && (comment_depth > 0 || !body.is_empty()) {
635            comment_depth += 1;
636        } else if block_close_at(toks, i) && comment_depth > 0 {
637            comment_depth -= 1;
638        }
639        // Inside a block comment everything rides into the current
640        // body (never splits, never guards, never releases waits,
641        // never skips): gap positions swallow it downstream, arg
642        // positions fail or math over it, exactly like the grammar.
643        if comment_depth > 0 {
644            if body.is_empty() {
645                // Head-token coordinates are authoritative: the line
646                // tracker lags content stripped before lexing (comments
647                // vanish on the token path, leaving no newline behind).
648                // Zero coordinates (synthetic streams) keep the tracker.
649                if tok.line > 0 {
650                    start_line = tok.line;
651                } else {
652                    start_line = line;
653                }
654                if tok.col > 0 {
655                    start_col = tok.col;
656                }
657            }
658            line += tok_newlines(tok);
659            body.push(tok.clone());
660            detached = false;
661            i += 1;
662            continue;
663        }
664        match &tok.kind {
665            TokKind::Newline => {
666                if body.is_empty() {
667                    // A separator between the guard region and a
668                    // following brace matters (see `brace_detached`).
669                    detached = true;
670                    line += 1;
671                    i += 1;
672                    continue;
673                }
674                // Multi-line generics: a newline inside an unclosed
675                // `<...>` rides into the body, so `MAP<...>` shapes may
676                // span lines. Anything else ends here as before.
677                if type_continuation_rides(&body, toks.get(i + 1)) {
678                    line += 1;
679                    body.push(tok.clone());
680                    detached = false;
681                    i += 1;
682                    continue;
683                }
684                match boundary_ends_statement(&body) {
685                    Ok(true) => flush_or_hold(
686                        &mut stmts,
687                        &mut guard,
688                        &mut body,
689                        &mut detached,
690                        &mut stmt_idx,
691                        &mut pending_io,
692                        &mut pending_if,
693                        true,
694                        start_line,
695                        start_col,
696                        line,
697                    )?,
698                    Ok(false) => {}
699                    Err(msg) => {
700                        return Err(TokenError {
701                            stmt: stmt_idx,
702                            msg,
703                            line: start_line,
704                            col: start_col,
705                            kind: None,
706                        });
707                    }
708                }
709                line += 1;
710                i += 1;
711            }
712            TokKind::Semicolon => {
713                if body.is_empty() {
714                    // A `;` breaks `ELSE` chains (release the hold)
715                    // but not `WITH_IO` waits (probed `;` merge).
716                    if let Some((held_guard, held_body, held_line, held_col)) = pending_if.take() {
717                        stmts.push(Stmt {
718                            guard: held_guard,
719                            body: held_body,
720                            brace_detached: false,
721                            line: held_line,
722                            col: held_col,
723                        });
724                        stmt_idx += 1;
725                    }
726                    detached = true;
727                    i += 1;
728                    continue;
729                }
730                match boundary_ends_statement(&body) {
731                    Ok(true) => flush_or_hold(
732                        &mut stmts,
733                        &mut guard,
734                        &mut body,
735                        &mut detached,
736                        &mut stmt_idx,
737                        &mut pending_io,
738                        &mut pending_if,
739                        false,
740                        start_line,
741                        start_col,
742                        line,
743                    )?,
744                    Ok(false) => {}
745                    Err(msg) => {
746                        return Err(TokenError {
747                            stmt: stmt_idx,
748                            msg,
749                            line: start_line,
750                            col: start_col,
751                            kind: None,
752                        });
753                    }
754                }
755                i += 1;
756            }
757            // Lexer comment markers drop silently, but release a
758            // pending `ELSE` wait (a comment line breaks the chain
759            // like the grammar); `WITH_IO` waits survive comments.
760            TokKind::Comment(text) => {
761                if let Some((held_guard, held_body, held_line, held_col)) = pending_if.take() {
762                    stmts.push(Stmt {
763                        guard: held_guard,
764                        body: held_body,
765                        brace_detached: false,
766                        line: held_line,
767                        col: held_col,
768                    });
769                    stmt_idx += 1;
770                }
771                // A joint marker (`a//b`) is payload, not trivia: it
772                // rides into the body so arg assembly glues it
773                // literally, exactly like the grammar. Gapped and
774                // line-start markers drop.
775                if tok.joint && !body.is_empty() {
776                    line += text.matches('\n').count();
777                    body.push(tok.clone());
778                    detached = false;
779                    i += 1;
780                    continue;
781                }
782                // Block markers may span lines (`/*a\nb*/`).
783                line += text.matches('\n').count();
784                i += 1;
785            }
786            // A `//` run with an empty body (mid-line, e.g. after
787            // `;`) is a comment to the line end; with a non-empty
788            // body the slash-run rule owns it as payload text.
789            TokKind::Punct('/') if body.is_empty() && is_comment_open(toks, i) => {
790                if matches!(toks.get(i + 1).map(|t| &t.kind), Some(TokKind::Punct('/'))) {
791                    while i < toks.len() && !matches!(&toks[i].kind, TokKind::Newline) {
792                        i += 1;
793                    }
794                } else {
795                    match skip_inline_comment(toks, i) {
796                        Some(past) => i = past,
797                        None => {
798                            return Err(TokenError {
799                                stmt: stmt_idx,
800                                msg: "unclosed block comment".to_string(),
801                                line,
802                                col: tok.col,
803                                kind: None,
804                            });
805                        }
806                    }
807                }
808            }
809            // `#` with an empty body (e.g. after `;`) is a comment
810            // to the line end; mid-body it stays arg text.
811            TokKind::Punct('#') if body.is_empty() => {
812                while i < toks.len() && !matches!(&toks[i].kind, TokKind::Newline) {
813                    i += 1;
814                }
815            }
816            TokKind::Group { delim, .. } if body.is_empty() && *delim == GroupDelim::Bracket => {
817                // Guard groups may span lines; the body starts after.
818                line += tok_newlines(tok);
819                guard.push(tok.clone());
820                detached = false;
821                i += 1;
822            }
823            _ => {
824                if body.is_empty() {
825                    // Head-token coordinates are authoritative (see
826                    // above); the tracker is the fallback.
827                    if tok.line > 0 {
828                        start_line = tok.line;
829                    } else {
830                        start_line = line;
831                    }
832                    if tok.col > 0 {
833                        start_col = tok.col;
834                    }
835                }
836                line += tok_newlines(tok);
837                body.push(tok.clone());
838                i += 1;
839            }
840        }
841    }
842    if !body.is_empty() {
843        match boundary_ends_statement(&body) {
844            Ok(_) => flush_or_hold(
845                &mut stmts,
846                &mut guard,
847                &mut body,
848                &mut detached,
849                &mut stmt_idx,
850                &mut pending_io,
851                &mut pending_if,
852                false,
853                start_line,
854                start_col,
855                line,
856            )?,
857            Err(msg) => {
858                return Err(TokenError {
859                    stmt: stmt_idx,
860                    msg,
861                    line: start_line,
862                    col: start_col,
863                    kind: None,
864                });
865            }
866        }
867    } else if !guard.is_empty() {
868        // Trailing guards with no following command error (probed: a
869        // lone `[env:X]` is an error), never drop silently.
870        return Err(TokenError {
871            stmt: stmt_idx,
872            msg: "guard declared without a following command".to_string(),
873            line,
874            col: 0,
875            kind: None,
876        });
877    }
878    // Release a trailing `ELSE` wait; a trailing `WITH_IO` wait fails.
879    if let Some((held_guard, held_body, held_line, held_col)) = pending_if.take() {
880        stmts.push(Stmt {
881            guard: held_guard,
882            body: held_body,
883            brace_detached: false,
884            line: held_line,
885            col: held_col,
886        });
887    }
888    if let Some((_, _, pending_line, pending_col)) = pending_io.take() {
889        return Err(TokenError {
890            stmt: stmt_idx,
891            msg: "WITH_IO block must be followed by '{'".to_string(),
892            line: pending_line,
893            col: pending_col,
894            kind: None,
895        });
896    }
897    Ok(stmts)
898}
899
900/// Splice in-body bracket/paren groups to flat raw text: arg-position
901/// brackets read as ordinary characters split purely on whitespace
902/// (`ECHO [a, b]` is args `"[a,"` + `"b]"`), so the parser expands
903/// each group to open-punct + inner + close-punct and lets the normal
904/// gap-split/render reproduce the bytes exactly (probed parity).
905/// Recursion handles nesting; edge joints ride along untouched. Brace
906/// groups stay put (blocks, never args). Newlines/semicolons spliced
907/// from multi-line groups fail loudly in assembly.
908fn splice_arg_groups(body: &[Tok], stmt: usize) -> Result<Vec<Tok>, TokenError> {
909    let _ = stmt;
910    let mut out = Vec::new();
911    for tok in body.iter() {
912        match &tok.kind {
913            TokKind::Group {
914                delim: GroupDelim::Brace,
915                ..
916            } => out.push(tok.clone()),
917            // Call parens stay structural: exploding them to puncts
918            // would strand full-region calls (`MAKE()` in arg position)
919            // as raw text, disagreeing with assignment values and
920            // RUN-exec items, which both parse calls. Brackets keep
921            // the raw-text splicing below (whitespace splits inside
922            // them, strings de-quote to words).
923            TokKind::Group {
924                delim: GroupDelim::Paren,
925                ..
926            } => out.push(tok.clone()),
927            TokKind::Group {
928                delim: GroupDelim::Bracket,
929                inner,
930                close_joint,
931                ..
932            } => {
933                out.push(Tok::fresh(TokKind::Punct('['), tok.joint));
934                // Inside brackets raw-text rules apply: quotes are
935                // characters, blocks never dedent, and whitespace splits
936                // runs (`['a b']` is args `"['a"` + `"b']"`). Convert
937                // spliced strings back to word text (splitting it like
938                // raw text); top-level strings stay structural.
939                for t in splice_arg_groups(inner, stmt)? {
940                    match &t.kind {
941                        TokKind::Str { text, quote } => {
942                            out.extend(split_word_text(&format!("{quote}{text}{quote}"), t.joint));
943                        }
944                        TokKind::BlockStr(full) => {
945                            out.extend(split_word_text(full, t.joint));
946                        }
947                        _ => out.push(t),
948                    }
949                }
950                out.push(Tok::fresh(TokKind::Punct(']'), *close_joint));
951            }
952            _ => out.push(tok.clone()),
953        }
954    }
955    Ok(out)
956}
957
958/// Split re-quoted raw text on whitespace runs. The first piece keeps the source joint flag; the rest break
959/// (whitespace separates args). Multi-space gaps normalize to one
960/// (documented edge, same class as group rendering).
961fn split_word_text(text: &str, joint: bool) -> Vec<Tok> {
962    let mut out = Vec::new();
963    let mut first = true;
964    for piece in text.split_whitespace() {
965        out.push(Tok::fresh(
966            TokKind::Word(piece.to_string()),
967            if first { joint } else { false },
968        ));
969        first = false;
970    }
971    if out.is_empty() {
972        out.push(Tok::fresh(TokKind::Word(text.to_string()), joint));
973    }
974    out
975}
976
977/// Assignment key charset, minus the `=` the
978/// classifier handles separately. Words are pre-filtered by the same
979/// set; `$`, quotes, and groups never start a key.
980fn is_assign_key_char(c: char) -> bool {
981    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':')
982}
983
984/// Match an assignment key run at an argument start: joint
985/// word/punct run in the key charset, non-empty, not `--`-led
986/// (flags keep their literal reading). Returns the key and end index.
987fn match_assign_key(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
988    let mut out = String::new();
989    let mut p = pos;
990    loop {
991        let t = toks.get(p)?;
992        if !out.is_empty() && !t.joint {
993            break;
994        }
995        match &t.kind {
996            TokKind::Word(w) => out.push_str(w),
997            TokKind::Punct(c) if is_assign_key_char(*c) => out.push(*c),
998            _ => break,
999        }
1000        p += 1;
1001    }
1002    if out.is_empty() || out.starts_with("--") {
1003        return None;
1004    }
1005    if !out
1006        .chars()
1007        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':'))
1008    {
1009        return None;
1010    }
1011    Some((out, p))
1012}
1013
1014/// Assignment boundary ahead (for value scanning): an argument start
1015/// holding `KEY=` (key run plus `=` at any gap).
1016/// Groups and strings are opaque: a `=` inside them never counts.
1017fn at_assign_boundary(toks: &[Tok], pos: usize) -> bool {
1018    match match_assign_key(toks, pos) {
1019        Some((_, end)) => matches!(toks.get(end).map(|t| &t.kind), Some(TokKind::Punct('='))),
1020        None => false,
1021    }
1022}
1023
1024/// Line breaks nested in a raw paren run fail like flat ones did
1025/// before parens stayed structural: splicing used to surface every
1026/// `;`/newline to `render_raw_text`'s reject arm. Brace contents are
1027/// skipped (templates and blocks render whole, then and now);
1028/// brackets nested in parens were spliced before, so their breaks
1029/// fail here too. Single owner for the rule; both raw fallbacks
1030/// (positional args, assignment values) ride `render_raw_text`.
1031fn reject_paren_line_breaks(inner: &[Tok], stmt: usize) -> Result<(), TokenError> {
1032    for tok in inner {
1033        match &tok.kind {
1034            TokKind::Newline | TokKind::Semicolon => {
1035                return Err(TokenError {
1036                    stmt,
1037                    msg: "unexpected line break in argument".to_string(),
1038                    line: tok.line,
1039                    col: tok.col,
1040                    kind: None,
1041                });
1042            }
1043            TokKind::Group {
1044                delim: GroupDelim::Brace,
1045                ..
1046            } => {}
1047            TokKind::Group { inner, .. } => reject_paren_line_breaks(inner, stmt)?,
1048            _ => {}
1049        }
1050    }
1051    Ok(())
1052}
1053
1054/// Raw-text render of one gap-run (or value span): words/puncts
1055/// literally (`$`+word literally, `$` elsewhere errors), strings by
1056/// their inner bytes, blocks lowered, groups spliced. Gaps collapse
1057/// to one space like `collapse_ws`; newlines/semicolons fail (the
1058/// grammar's raw span excludes them).
1059fn render_raw_text(toks: &[Tok], stmt: usize) -> Result<String, TokenError> {
1060    let mut out = String::new();
1061    let mut i = 0;
1062    while i < toks.len() {
1063        let tok = &toks[i];
1064        if !tok.joint && !out.is_empty() {
1065            out.push(' ');
1066        }
1067        match &tok.kind {
1068            TokKind::Word(w) => out.push_str(w),
1069            TokKind::Punct(c) => {
1070                if *c == VAR_SIGIL_CHAR {
1071                    // Lone-`$` runs never reach here (expression
1072                    // extension claims them first and fails loudly).
1073                    // Elsewhere `$` renders literally (probed `a$(x)`
1074                    // reads raw) except before a brace group, where
1075                    // the grammar strands it (probed `K=${x}` fails).
1076                    let next = toks.get(i + 1);
1077                    let brace_next = next.is_some_and(|t| {
1078                        matches!(
1079                            &t.kind,
1080                            TokKind::Group {
1081                                delim: GroupDelim::Brace,
1082                                ..
1083                            }
1084                        )
1085                    });
1086                    if brace_next {
1087                        return Err(TokenError {
1088                            stmt,
1089                            msg: "unexpected `$` in argument".to_string(),
1090                            line: 0,
1091                            col: 0,
1092                            kind: None,
1093                        });
1094                    }
1095                    out.push(VAR_SIGIL_CHAR);
1096                } else {
1097                    out.push(*c);
1098                }
1099            }
1100            // Standalone quotes strip (the caller handles single-tok
1101            // runs); glued quotes keep their marks, like the grammar's
1102            // mixed fragments (`>"a"` stays quoted, `"a"` strips).
1103            TokKind::Str { text: s, quote } => {
1104                let glued = tok.joint || toks.get(i + 1).is_some_and(|t| t.joint);
1105                if toks.len() > 1 && glued {
1106                    out.push(*quote);
1107                    out.push_str(s);
1108                    out.push(*quote);
1109                } else {
1110                    out.push_str(s);
1111                }
1112            }
1113            // Comments reproduce verbatim (templates keep comment
1114            // text like the atomic grammar span); gaps collapse
1115            // around them like other fragments per the documented
1116            // single-space normalization.
1117            TokKind::Comment(text) => out.push_str(text),
1118            TokKind::BlockStr(full) => {
1119                // Glued blocks keep their delimiters, like quotes.
1120                let glued = tok.joint || toks.get(i + 1).is_some_and(|t| t.joint);
1121                if toks.len() > 1 && glued {
1122                    out.push_str(full);
1123                } else {
1124                    out.push_str(&crate::command::lower_block_string(full));
1125                }
1126            }
1127            TokKind::Group {
1128                delim: GroupDelim::Brace,
1129                inner,
1130                open_joint,
1131                close_joint,
1132                ..
1133            } => out.push_str(&render_brace_run_text(inner, *open_joint, *close_joint)),
1134            TokKind::Group {
1135                delim: GroupDelim::Bracket,
1136                inner,
1137                open_joint,
1138                close_joint,
1139                ..
1140            } => out.push_str(&render_group('[', ']', inner, *open_joint, *close_joint)),
1141            TokKind::Group {
1142                delim: GroupDelim::Paren,
1143                inner,
1144                open_joint,
1145                close_joint,
1146                ..
1147            } => {
1148                // Parens stayed structural (call shapes need them), so
1149                // surface the breaks splicing used to expose: a `;` or
1150                // newline anywhere inside fails exactly like a flat one
1151                // did. Brace contents keep the verbatim whole-render
1152                // below; brackets nested in parens were spliced before,
1153                // so their breaks fail here too.
1154                reject_paren_line_breaks(inner, stmt)?;
1155                out.push_str(&render_group('(', ')', inner, *open_joint, *close_joint))
1156            }
1157            TokKind::Newline | TokKind::Semicolon => {
1158                return Err(TokenError {
1159                    stmt,
1160                    msg: "unexpected line break in argument".to_string(),
1161                    line: 0,
1162                    col: 0,
1163                    kind: None,
1164                });
1165            }
1166        }
1167        i += 1;
1168    }
1169    Ok(out)
1170}
1171
1172/// Build an assignment value `Arg` over a region that runs to the next
1173/// boundary or end. Single quoted/block strings keep `quoted=true`; a
1174/// region that is exactly one lone `$var`/keypath/`env:`/call shape
1175/// stays typed (calls resolve through the shared resolver, matching
1176/// `assign_expr`); everything else renders raw. A quoted unit followed
1177/// by joint content errors (probed: `K="a"b` fails), like the grammar.
1178/// Lone-shape failures stash into `deferred` and render raw: the
1179/// command's own lowering error (if any) takes precedence, and the
1180/// stashed call error surfaces only when lowering succeeds.
1181fn build_value_arg(
1182    region: &[Tok],
1183    stmt: usize,
1184    ctx: &ParseCtx,
1185    lone_ok: bool,
1186    deferred: &mut Option<TokenError>,
1187) -> Result<Arg, TokenError> {
1188    if region.is_empty() {
1189        return Ok(Arg::String(String::new(), false));
1190    }
1191    if region.len() == 1 {
1192        match &region[0].kind {
1193            TokKind::Str { text: s, .. } => return Ok(Arg::String(s.clone(), true)),
1194            TokKind::BlockStr(full) => {
1195                return Ok(Arg::String(crate::command::lower_block_string(full), true));
1196            }
1197            _ => {}
1198        }
1199    }
1200    if region.len() > 1
1201        && matches!(&region[0].kind, TokKind::Str { .. } | TokKind::BlockStr(_))
1202        && region[1].joint
1203    {
1204        return Err(TokenError {
1205            stmt,
1206            msg: "unexpected text after quoted value".to_string(),
1207            line: 0,
1208            col: 0,
1209            kind: None,
1210        });
1211    }
1212    // Single-quoted values mid-line (`K='a b'`): the string lexer only
1213    // opens `'` gapped, so these arrive as fragments; the grammar's
1214    // `quoted_string` admits them anywhere. Reassemble a region that
1215    // opens with `'` and closes at its end, stripping exactly like a
1216    // structural string (escapes intact for runtime, like `Str`).
1217    if matches!(&region[0].kind, TokKind::Punct('\''))
1218        && let Some(text) = try_squote_value(region)
1219    {
1220        return Ok(Arg::String(text, true));
1221    }
1222    // Lone typed values apply only at a true end/boundary, never
1223    // past a comment (the grammar's `!assign_expr_cont` guard).
1224    // Failures stash (see above) so command syntax owns precedence.
1225    if lone_ok {
1226        match try_lone_value_expr(region, stmt, ctx) {
1227            Ok(Some(expr)) => return Ok(expr),
1228            Ok(None) => {}
1229            Err(err) => {
1230                deferred.get_or_insert(err);
1231            }
1232        }
1233    }
1234    Ok(Arg::String(render_raw_text(region, stmt)?, false))
1235}
1236
1237/// Reassemble a single-quoted assignment value (`K='a b'`) from its
1238/// lexer fragments: the opener must close at the region end (a
1239/// trailing fragment falls back to raw text, which fails downstream
1240/// like the grammar). Inner gaps join with one space and nested
1241/// double quotes re-quote (the atomic span keeps them); `\'` escapes
1242/// pass through intact for runtime, like structural strings. `None`
1243/// on shape miss.
1244fn try_squote_value(region: &[Tok]) -> Option<String> {
1245    // Closing `'`: first unescaped quote past the opener.
1246    let mut close = None;
1247    let mut i = 1;
1248    while i < region.len() {
1249        match &region[i].kind {
1250            TokKind::Punct('\\') => i += 2,
1251            TokKind::Punct('\'') => {
1252                close = Some(i);
1253                break;
1254            }
1255            _ => i += 1,
1256        }
1257    }
1258    if close != Some(region.len() - 1) {
1259        return None;
1260    }
1261    let mut out = String::new();
1262    for tok in &region[1..region.len() - 1] {
1263        if !tok.joint && !out.is_empty() {
1264            out.push(' ');
1265        }
1266        match &tok.kind {
1267            TokKind::Word(w) => out.push_str(w),
1268            TokKind::Punct(c) => out.push(*c),
1269            TokKind::Semicolon => out.push(';'),
1270            // Nested double quotes keep their marks (the atomic span
1271            // never strips them); triple quotes pass through whole.
1272            TokKind::Str { text, quote } => {
1273                out.push(*quote);
1274                out.push_str(text);
1275                out.push(*quote);
1276            }
1277            TokKind::BlockStr(full) => out.push_str(full),
1278            // Groups and newlines never occur in value regions (the
1279            // splitter owns them); anything else breaks the shape.
1280            _ => return None,
1281        }
1282    }
1283    Some(out)
1284}
1285
1286/// Lone assignable shapes (`assign_expr` without continuation): `$var`,
1287/// key paths, `env:KEY`, `$`-sigiled `CONST` reads (`$NAME`,
1288/// `$ALIAS::NAME`), and full-region calls
1289/// (resolved). Anything longer renders raw; the caller decides
1290/// strictness.
1291fn try_lone_value_expr(
1292    region: &[Tok],
1293    stmt: usize,
1294    ctx: &ParseCtx,
1295) -> Result<Option<Arg>, TokenError> {
1296    // `$` shapes: exactly Punct+Word or dotted runs, all joint past
1297    // the first (the region starts at an argument start by construction).
1298    if matches!(
1299        region.first().map(|t| &t.kind),
1300        Some(TokKind::Punct(VAR_SIGIL_CHAR))
1301    ) {
1302        let mut cur = Cursor::expr(region, stmt);
1303        cur.pos += 1;
1304        let base = match cur.next() {
1305            Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
1306                match &t.kind {
1307                    TokKind::Word(w) => w.clone(),
1308                    _ => unreachable!(),
1309                }
1310            }
1311            _ => return Ok(None),
1312        };
1313        // Qualified immutable read (`$ALIAS::NAME`). Key paths
1314        // never ride qualified names: copy to a local first.
1315        if let Some(name) = match_joint_qualified(cur.toks, cur.pos) {
1316            if cur.toks.get(cur.pos + 3).is_some() {
1317                if matches!(
1318                    cur.toks.get(cur.pos + 3).map(|t| &t.kind),
1319                    Some(TokKind::Punct('.'))
1320                ) && cur.toks.get(cur.pos + 3).is_some_and(|t| t.joint)
1321                {
1322                    return Err(TokenError {
1323                        stmt,
1324                        msg: crate::template::qualified_keypath_error(),
1325                        line: 0,
1326                        col: 0,
1327                        kind: None,
1328                    });
1329                }
1330                return Err(TokenError {
1331                    stmt,
1332                    msg: format!("unexpected text after {}", sigil_qualified(&base, &name)),
1333                    line: 0,
1334                    col: 0,
1335                    kind: None,
1336                });
1337            }
1338            return Ok(Some(Arg::Expr(Expr::ConstRef { alias: base, name })));
1339        }
1340        let mut keys = Vec::new();
1341        loop {
1342            let dot = matches!(
1343                cur.toks.get(cur.pos).map(|t| &t.kind),
1344                Some(TokKind::Punct('.'))
1345            ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
1346            let seg = cur.toks.get(cur.pos + 1);
1347            let seg_ok = dot
1348                && matches!(seg.map(|t| &t.kind), Some(TokKind::Word(w)) if is_key_segment(w))
1349                && seg.is_some_and(|t| t.joint);
1350            if !seg_ok {
1351                break;
1352            }
1353            if let Some(TokKind::Word(w)) = seg.map(|t| &t.kind) {
1354                keys.push(w.clone());
1355            }
1356            cur.pos += 2;
1357        }
1358        if cur.pos != region.len() {
1359            return Ok(None);
1360        }
1361        return Ok(Some(Arg::Expr(if keys.is_empty() {
1362            Expr::Var { name: base }
1363        } else {
1364            Expr::KeyPath { base, keys }
1365        })));
1366    }
1367    // `env:KEY` read, gapless and exact.
1368    if region.len() == 3
1369        && matches!(&region[0].kind, TokKind::Word(w) if w == "env")
1370        && matches!(&region[1].kind, TokKind::Punct(':'))
1371        && region[1].joint
1372        && let TokKind::Word(k) = &region[2].kind
1373        && is_env_key(k)
1374        && region[2].joint
1375    {
1376        return Ok(Some(Arg::Expr(Expr::Env(k.clone()))));
1377    }
1378    // Full-region call: resolve and keep typed (canonical rendering
1379    // happens per command: verbatim for ENV/EXPAND, `K=`-joined text
1380    // elsewhere, all from the same `Arg::Expr`). Single owner for the
1381    // call tail; positional args share it (see `build_arg_tokens`).
1382    if let Some(arg) = try_lone_call_expr(region, stmt, ctx)? {
1383        return Ok(Some(arg));
1384    }
1385    Ok(None)
1386}
1387
1388/// Full-region call shape (`NAME(...)`, `MOD::NAME(...)`) over one
1389/// argument run: parse args through the shared call owner and resolve
1390/// through the shared resolver, so assignment values, RUN-exec items,
1391/// and generic positional args can never disagree on what a call is.
1392/// `None` on shape miss (caller renders raw); errors propagate, so a
1393/// misspelled callee fails loud instead of going literal.
1394fn try_lone_call_expr(
1395    region: &[Tok],
1396    stmt: usize,
1397    ctx: &ParseCtx,
1398) -> Result<Option<Arg>, TokenError> {
1399    if let Some((name, paren)) = call_shape_at(region, 0, false)
1400        && paren + 1 == region.len()
1401        && let TokKind::Group { inner, .. } = &region[paren].kind
1402    {
1403        let inner = inner.clone();
1404        let args = parse_call_args(&inner, stmt, ctx)?;
1405        if name == KEYWORD_INSPECT {
1406            let [arg] = args.as_slice() else {
1407                return Err(TokenError {
1408                    stmt,
1409                    msg: "INSPECT requires exactly one argument: INSPECT($var)".to_string(),
1410                    line: 0,
1411                    col: 0,
1412                    kind: None,
1413                });
1414            };
1415            if let Expr::Var { name } = arg {
1416                return Ok(Some(Arg::Expr(Expr::Inspect { name: name.clone() })));
1417            }
1418            return Err(TokenError {
1419                stmt,
1420                msg: format!("INSPECT requires a $variable argument, found {arg:?}"),
1421                line: 0,
1422                col: 0,
1423                kind: None,
1424            });
1425        }
1426        let qualified = resolve_name(ctx, stmt, &name)?;
1427        return Ok(Some(Arg::Expr(Expr::Call {
1428            name: qualified,
1429            args,
1430        })));
1431    }
1432    Ok(None)
1433}
1434
1435/// Expression extension for `$`/`env:`-led argument starts: parse a
1436/// full expression (operators reach across gaps exactly like the
1437/// grammar's inner `gap`s). Ending at a gap/end yields a typed single
1438/// group; ending mid-run falls back to raw text of the run (`$x=K`);
1439/// parse failure is fatal (every fragment alternative failed).
1440/// Returns the arg and tokens consumed.
1441fn try_expr_arg(
1442    toks: &[Tok],
1443    pos: usize,
1444    stmt: usize,
1445    ctx: &ParseCtx,
1446) -> Result<Option<(Arg, usize)>, TokenError> {
1447    let extend = matches!(
1448        toks.get(pos).map(|t| &t.kind),
1449        Some(TokKind::Punct(VAR_SIGIL_CHAR))
1450    ) || matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == "env");
1451    if !extend {
1452        return Ok(None);
1453    }
1454    // A bare `env` head only extends into a real `env:KEY` read (joint
1455    // `:`); dotted bare words (`env.txt`) stay raw strings like the
1456    // grammar's `unquoted_arg`, which precedes `expr`.
1457    if matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == "env")
1458        && !matches!(
1459            (
1460                toks.get(pos + 1).map(|t| &t.kind),
1461                toks.get(pos + 1).map(|t| t.joint)
1462            ),
1463            (Some(TokKind::Punct(':')), Some(true))
1464        )
1465    {
1466        return Ok(None);
1467    }
1468    let mut cur = Cursor::expr(&toks[pos..], stmt);
1469    let expr = parse_expr_or(&mut cur, ctx)?;
1470    let end = pos + cur.pos;
1471    // Mid-run stop (joint follower): the whole run renders raw
1472    // (`$x=K`, `$a$b`); the run always ends the fallback span here
1473    // because extension starts groups.
1474    if toks.get(end).is_some_and(|t| t.joint) {
1475        let mut run_end = end;
1476        while toks.get(run_end).is_some_and(|t| t.joint) {
1477            run_end += 1;
1478        }
1479        let text = render_raw_text(&toks[pos..run_end], stmt)?;
1480        return Ok(Some((Arg::String(text, false), run_end - pos)));
1481    }
1482    Ok(Some((Arg::Expr(expr), end - pos)))
1483}
1484
1485/// Render a brace group inside raw text (`{{..}}` templates and
1486/// mid-run `{..}` shapes): verbatim bytes, single-space-normalized
1487/// gaps. Run-start non-template braces never reach here (they parse
1488/// as maps/blocks in `build_arg_tokens`).
1489fn render_brace_run_text(inner: &[Tok], open_joint: bool, close_joint: bool) -> String {
1490    render_group('{', '}', inner, open_joint, close_joint)
1491}
1492
1493/// Inner bytes of a fully-quoted word (`"hi"`, `'a'`): the re-quoted
1494/// standalone strings spliced from groups strip exactly like
1495/// structural ones. Triple-quote pieces never qualify (block lowering
1496/// owns them); glued quotes (`['a`) never reach here as sole runs.
1497fn quoted_word_inner(w: &str) -> Option<String> {
1498    if w.len() >= 2 && !w.starts_with("\"\"\"") {
1499        let q = w.as_bytes()[0] as char;
1500        if (q == '"' || q == '\'') && w.ends_with(q) {
1501            return Some(w[1..w.len() - 1].to_string());
1502        }
1503    }
1504    None
1505}
1506
1507/// Build instruction tokens over generic args, mirroring
1508/// `assignment | argument` order at every argument start: assignments
1509/// merge across gaps to the next boundary, `$`/`env:`-led runs extend
1510/// as expressions, brace-led runs try templates then maps/blocks, and
1511/// everything else renders raw. Single quoted strings keep their flag.
1512fn build_arg_tokens(
1513    toks: &[Tok],
1514    stmt: usize,
1515    ctx: &ParseCtx,
1516) -> Result<(Vec<InsToken>, Option<TokenError>), TokenError> {
1517    // Splice bracket groups first: they read as ordinary
1518    // characters (whitespace splits inside them), with strings
1519    // re-quoted back to word text. Paren groups stay structural (see
1520    // `splice_arg_groups`); brace groups stay structural
1521    // (templates render whole; blocks parse as expressions).
1522    let flat = splice_arg_groups(toks, stmt)?;
1523    let mut deferred: Option<TokenError> = None;
1524    let mut out = Vec::new();
1525    let mut pos = 0;
1526    while pos < flat.len() {
1527        // 1. Assignment: key run plus `=` at any gap.
1528        if let Some((key, key_end)) = match_assign_key(&flat, pos)
1529            && let Some(tok) = flat.get(key_end)
1530            && matches!(&tok.kind, TokKind::Punct('='))
1531        {
1532            // Value runs to the next boundary, but raw text also
1533            // stops at `//` / `/*` (raw-text rule):
1534            // a line comment swallows the rest silently, a block
1535            // comment must be followed by nothing or a boundary
1536            // (anything else strands text and fails the line, like
1537            // the grammar). Lone typed values (`$x`, calls) apply
1538            // only at a true end/boundary, never past a comment
1539            // (the grammar's `!assign_expr_cont` guard).
1540            let mut vend = key_end + 1;
1541            let mut lone_ok = true;
1542            let mut failed: Option<String> = None;
1543            'scan: while vend < flat.len() {
1544                if !flat[vend].joint && at_assign_boundary(&flat, vend) {
1545                    break;
1546                }
1547                // Lexer comment markers end the raw span like `//`
1548                // (they run to end of line by construction).
1549                if matches!(&flat[vend].kind, TokKind::Comment(_)) {
1550                    lone_ok = false;
1551                    vend = flat.len();
1552                    break;
1553                }
1554                if matches!(&flat[vend].kind, TokKind::Punct('/')) && is_comment_open(&flat, vend) {
1555                    // Comments end the raw span: line comments eat
1556                    // the rest silently, block comments must be
1557                    // followed by nothing, a boundary, or more
1558                    // comments (stranded text fails the line, like
1559                    // the grammar).
1560                    lone_ok = false;
1561                    loop {
1562                        if vend >= flat.len()
1563                            || (!flat[vend].joint && at_assign_boundary(&flat, vend))
1564                        {
1565                            break 'scan;
1566                        }
1567                        if !matches!(&flat[vend].kind, TokKind::Punct('/'))
1568                            || !is_comment_open(&flat, vend)
1569                        {
1570                            failed = Some("unexpected text after assignment value".to_string());
1571                            break 'scan;
1572                        }
1573                        if matches!(
1574                            flat.get(vend + 1).map(|t| &t.kind),
1575                            Some(TokKind::Punct('/'))
1576                        ) {
1577                            vend = flat.len();
1578                            break 'scan;
1579                        }
1580                        match skip_inline_comment(&flat, vend) {
1581                            None => {
1582                                failed = Some("unclosed block comment".to_string());
1583                                break 'scan;
1584                            }
1585                            Some(past) => vend = past,
1586                        }
1587                    }
1588                }
1589                vend += 1;
1590            }
1591            if let Some(msg) = failed {
1592                return Err(TokenError {
1593                    stmt,
1594                    msg,
1595                    line: 0,
1596                    col: 0,
1597                    kind: None,
1598                });
1599            }
1600            let value =
1601                build_value_arg(&flat[key_end + 1..vend], stmt, ctx, lone_ok, &mut deferred)?;
1602            out.push(InsToken::Assign(key, value));
1603            pos = vend;
1604            continue;
1605        }
1606        // 2. Brace-led run: template text, else map/block expression.
1607        if matches!(
1608            flat.get(pos).map(|t| &t.kind),
1609            Some(TokKind::Group {
1610                delim: GroupDelim::Brace,
1611                ..
1612            })
1613        ) {
1614            let mut run_end = pos + 1;
1615            while flat.get(run_end).is_some_and(|t| t.joint) {
1616                run_end += 1;
1617            }
1618            let run = &flat[pos..run_end];
1619            let is_template = is_template_brace(&run[0]);
1620            if is_template {
1621                out.push(InsToken::Pos(Arg::String(
1622                    render_raw_text(run, stmt)?,
1623                    false,
1624                )));
1625            } else {
1626                let inner = match &run[0].kind {
1627                    TokKind::Group { inner, .. } => inner.clone(),
1628                    _ => unreachable!(),
1629                };
1630                // Map success alone stays typed; map success with a
1631                // joint tail renders raw (`{k:1}x`, like the grammar's
1632                // mixed fragments); map failure defers/errors exactly
1633                // like the expression path.
1634                match parse_map_or_block(&inner, stmt, ctx) {
1635                    Ok(expr) if run.len() == 1 => {
1636                        out.push(InsToken::Pos(Arg::Expr(expr)));
1637                    }
1638                    Ok(_) => out.push(InsToken::Pos(Arg::String(
1639                        render_raw_text(run, stmt)?,
1640                        false,
1641                    ))),
1642                    Err(e) => return Err(e),
1643                }
1644            }
1645            pos = run_end;
1646            continue;
1647        }
1648        // 3. `$`/`env:`-led expression extension.
1649        if let Some((arg, used)) = try_expr_arg(&flat, pos, stmt, ctx)? {
1650            // A lone expression group stays typed; the fallback
1651            // already rendered text above.
1652            out.push(InsToken::Pos(arg));
1653            pos += used;
1654            continue;
1655        }
1656        // 4. Raw text run to the next gap.
1657        let mut run_end = pos + 1;
1658        while flat.get(run_end).is_some_and(|t| t.joint) {
1659            run_end += 1;
1660        }
1661        let run = &flat[pos..run_end];
1662        // Slash-pair-led runs (`/*c*/`; `//` arrives as `Comment`
1663        // toks) parse as expression fragments (typed when single,
1664        // glued verbatim otherwise).
1665        if is_slash_run(run) {
1666            out.push(InsToken::Pos(parse_slash_run(run, stmt, ctx)?));
1667            pos = run_end;
1668            continue;
1669        }
1670        // Trailing `Comment` (`//` to end of line) glues as a
1671        // literal fragment (typed when alone, verbatim otherwise),
1672        // exactly like the grammar's expression fragments.
1673        if let Some(TokKind::Comment(text)) = run.last().map(|t| &t.kind) {
1674            if run.len() == 1 {
1675                out.push(InsToken::Pos(Arg::Expr(Expr::Literal(Value::string(
1676                    text.clone(),
1677                )))));
1678            } else {
1679                let mut bytes = render_raw_text(&run[..run.len() - 1], stmt)?;
1680                bytes.push_str(text);
1681                out.push(InsToken::Pos(Arg::String(bytes, false)));
1682            }
1683            pos = run_end;
1684            continue;
1685        }
1686        if run.len() == 1 {
1687            match &run[0].kind {
1688                TokKind::Str { text: s, .. } => {
1689                    out.push(InsToken::Pos(Arg::String(s.clone(), true)));
1690                    pos = run_end;
1691                    continue;
1692                }
1693                TokKind::BlockStr(full) => {
1694                    out.push(InsToken::Pos(Arg::String(
1695                        crate::command::lower_block_string(full),
1696                        true,
1697                    )));
1698                    pos = run_end;
1699                    continue;
1700                }
1701                // Re-quoted standalone strings (spliced from groups)
1702                // strip exactly like structural ones (`["hi"]` gives
1703                // `hi`); glued quotes stay literal (`['a` keeps its
1704                // mark). Triple-quote pieces never qualify.
1705                TokKind::Word(w) if quoted_word_inner(w).is_some() => {
1706                    out.push(InsToken::Pos(Arg::String(
1707                        quoted_word_inner(w).unwrap(),
1708                        true,
1709                    )));
1710                    pos = run_end;
1711                    continue;
1712                }
1713                _ => {}
1714            }
1715        }
1716        // Bare full-region calls stay typed like assignment values and
1717        // RUN-exec items (same owner, `try_lone_call_expr`), so every
1718        // argument position evaluates them instead of one silently
1719        // appending the source text. Failures stash: the command's own
1720        // lowering error (if any) takes precedence, and the stashed
1721        // call error surfaces only when lowering succeeds.
1722        match try_lone_call_expr(run, stmt, ctx) {
1723            Ok(Some(arg)) => {
1724                out.push(InsToken::Pos(arg));
1725                pos = run_end;
1726                continue;
1727            }
1728            Ok(None) => {}
1729            Err(err) => {
1730                deferred.get_or_insert(err);
1731            }
1732        }
1733        out.push(InsToken::Pos(Arg::String(
1734            render_raw_text(run, stmt)?,
1735            false,
1736        )));
1737        pos = run_end;
1738    }
1739    Ok((out, deferred))
1740}
1741
1742/// A raw run starting with `//` or `/*` (a slash-pair: `/` plus a
1743/// joint `/` or `*`) parses as expression fragments: both route to
1744/// `expr` there (so `//c` types as a literal and `/*c*/` as math). A single
1745/// fully-consuming expression stays typed; anything longer glues to
1746/// verbatim text exactly like the grammar's mixed fragments (byte
1747/// for byte, since joint runs admit no span gaps). An unparseable
1748/// unterminated block open (`/*` with no `*/` in the run) reads
1749/// literally like the old backend (`ECHO /*`, `[a /* c]`); a
1750/// terminated span keeps the loud failure.
1751fn parse_slash_run(run: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Arg, TokenError> {
1752    let mut cur = Cursor::expr(run, stmt);
1753    match parse_expr_checked(&mut cur, ctx) {
1754        Ok(expr) if cur.done() => Ok(Arg::Expr(expr)),
1755        Ok(_) => Ok(Arg::String(render_raw_text(run, stmt)?, false)),
1756        Err(_) if !run_has_block_close(run) => Ok(Arg::String(render_raw_text(run, stmt)?, false)),
1757        Err(e) => Err(e),
1758    }
1759}
1760
1761/// True when the run holds a `*/` close pair (`*` plus a joint `/`),
1762/// mirroring [`skip_inline_comment`]'s terminator: only unterminated
1763/// block opens read literally.
1764fn run_has_block_close(run: &[Tok]) -> bool {
1765    run.windows(2).any(|w| {
1766        matches!(&w[0].kind, TokKind::Punct('*'))
1767            && matches!(&w[1].kind, TokKind::Punct('/'))
1768            && w[1].joint
1769    })
1770}
1771
1772/// True when a raw run opens with a slash-pair (`/` plus a joint
1773/// `/` or `*`), routing it to expression fragments (see
1774/// [`parse_slash_run`]). A lone `/` (`/a`, `/`) stays raw text.
1775fn is_slash_run(run: &[Tok]) -> bool {
1776    matches!(run.first().map(|t| &t.kind), Some(TokKind::Punct('/')))
1777        && matches!(
1778            run.get(1).map(|t| (&t.kind, t.joint)),
1779            Some((TokKind::Punct('/'), true)) | Some((TokKind::Punct('*'), true))
1780        )
1781}
1782
1783/// Lower generic args through the shared cores: `ENV`/`EXPAND` bypass
1784/// the injected dispatcher; everything else
1785/// canonicalizes assignments and calls it.
1786fn lower_generic_args(
1787    name: &str,
1788    tokens: Vec<InsToken>,
1789    stmt: usize,
1790    ctx: &ParseCtx,
1791) -> Result<StepKind, TokenError> {
1792    if name == KEYWORD_ENV {
1793        return lower_env_tokens(&lowering_ctx(stmt), tokens).map_err(|e| TokenError {
1794            stmt,
1795            msg: e.to_string(),
1796            line: 0,
1797            col: 0,
1798            kind: None,
1799        });
1800    }
1801    if name == KEYWORD_EXPAND {
1802        return lower_expand_tokens(&lowering_ctx(stmt), tokens).map_err(|e| TokenError {
1803            stmt,
1804            msg: e.to_string(),
1805            line: 0,
1806            col: 0,
1807            kind: None,
1808        });
1809    }
1810    let args = tokens
1811        .into_iter()
1812        .map(|token| match token {
1813            InsToken::Pos(arg) => arg,
1814            InsToken::Assign(key, value) => canonical_assignment_arg(&key, &value),
1815        })
1816        .collect();
1817    (ctx.lower)(name, args).map_err(|e| lower_err(stmt, e))
1818}
1819
1820/// Render a bracket/paren/brace group back to source text for raw-text
1821/// positions (in-body groups are args, template braces render whole).
1822/// Fragments join with a space on gaps and glue on `joint`, so both
1823/// lexers render the same source identically; quote styles round-trip
1824/// exactly. Known normalization (documented, not silent): multi-space
1825/// gaps collapse to one.
1826fn render_group(
1827    open: char,
1828    close: char,
1829    inner: &[Tok],
1830    open_joint: bool,
1831    close_joint: bool,
1832) -> String {
1833    let mut out = String::from(open);
1834    if !open_joint && !inner.is_empty() {
1835        out.push(' ');
1836    }
1837    let mut first = true;
1838    for tok in inner {
1839        match &tok.kind {
1840            TokKind::Newline => out.push('\n'),
1841            TokKind::Semicolon => out.push(';'),
1842            // Comments reproduce verbatim (templates keep comment
1843            // text like the atomic grammar span); like newlines they
1844            // carry their own separation, never a synthetic space.
1845            TokKind::Comment(text) => out.push_str(text),
1846            _ => {
1847                if !first && !tok.joint {
1848                    out.push(' ');
1849                }
1850                match &tok.kind {
1851                    TokKind::Word(w) => out.push_str(w),
1852                    TokKind::Punct(c) => out.push(*c),
1853                    TokKind::Str { text, quote } => {
1854                        out.push(*quote);
1855                        out.push_str(text);
1856                        out.push(*quote);
1857                    }
1858                    TokKind::BlockStr(full) => out.push_str(full),
1859                    TokKind::Group {
1860                        delim: GroupDelim::Bracket,
1861                        inner,
1862                        open_joint,
1863                        close_joint,
1864                        ..
1865                    } => out.push_str(&render_group('[', ']', inner, *open_joint, *close_joint)),
1866                    TokKind::Group {
1867                        delim: GroupDelim::Paren,
1868                        inner,
1869                        open_joint,
1870                        close_joint,
1871                        ..
1872                    } => out.push_str(&render_group('(', ')', inner, *open_joint, *close_joint)),
1873                    TokKind::Group {
1874                        delim: GroupDelim::Brace,
1875                        inner,
1876                        open_joint,
1877                        close_joint,
1878                        ..
1879                    } => out.push_str(&render_group('{', '}', inner, *open_joint, *close_joint)),
1880                    // Comments reproduce verbatim (nested groups keep
1881                    // comment text like the atomic grammar span).
1882                    TokKind::Comment(text) => out.push_str(text),
1883                    TokKind::Newline | TokKind::Semicolon => unreachable!(),
1884                }
1885            }
1886        }
1887        first = false;
1888    }
1889    if !close_joint && !inner.is_empty() {
1890        out.push(' ');
1891    }
1892    out.push(close);
1893    out
1894}
1895
1896/// Positional cursor over guard/group token slices. Newlines skip
1897/// freely between tokens (`ws` admits linebreaks in the grammar);
1898/// bare key/value runs never cross them (the grammar excludes
1899/// linebreaks there), so runs read raw.
1900///
1901/// Expression parsing reuses this cursor with `nl_skip = false`:
1902/// expressions are single-line (`gap`, never `gap_nl`, between
1903/// operands), so a newline terminates instead of vanishing. Newlines
1904/// inside group inners (call args, lists, maps) skip via explicit
1905/// `skip_newlines` calls at the grammar's `gap_nl` junctures.
1906struct Cursor<'t> {
1907    toks: &'t [Tok],
1908    pos: usize,
1909    stmt: usize,
1910    nl_skip: bool,
1911}
1912
1913impl<'t> Cursor<'t> {
1914    fn new(toks: &'t [Tok], stmt: usize) -> Self {
1915        Self {
1916            toks,
1917            pos: 0,
1918            stmt,
1919            nl_skip: true,
1920        }
1921    }
1922
1923    /// Expression-mode cursor: newlines stop, never skip.
1924    fn expr(toks: &'t [Tok], stmt: usize) -> Self {
1925        Self {
1926            toks,
1927            pos: 0,
1928            stmt,
1929            nl_skip: false,
1930        }
1931    }
1932
1933    fn err(&self, msg: impl Into<String>) -> TokenError {
1934        TokenError {
1935            stmt: self.stmt,
1936            line: 0,
1937            col: 0,
1938            msg: msg.into(),
1939            kind: None,
1940        }
1941    }
1942
1943    fn skip_newlines(&mut self) {
1944        while matches!(
1945            self.toks.get(self.pos).map(|t| &t.kind),
1946            Some(TokKind::Newline)
1947        ) {
1948            self.pos += 1;
1949        }
1950    }
1951
1952    fn peek(&mut self) -> Option<&'t Tok> {
1953        if self.nl_skip {
1954            self.skip_newlines();
1955        }
1956        self.toks.get(self.pos)
1957    }
1958
1959    fn next(&mut self) -> Option<&'t Tok> {
1960        if self.nl_skip {
1961            self.skip_newlines();
1962        }
1963        let t = self.toks.get(self.pos)?;
1964        self.pos += 1;
1965        Some(t)
1966    }
1967
1968    fn done(&mut self) -> bool {
1969        if self.nl_skip {
1970            self.skip_newlines();
1971        }
1972        self.pos >= self.toks.len()
1973    }
1974
1975    fn eat_punct(&mut self, c: char) -> bool {
1976        if self.nl_skip {
1977            self.skip_newlines();
1978        }
1979        match self.peek() {
1980            Some(t) if matches!(&t.kind, TokKind::Punct(p) if *p == c) => {
1981                self.pos += 1;
1982                true
1983            }
1984            _ => false,
1985        }
1986    }
1987
1988    /// Skip one gap's worth of comments (`gap`: `//`-to-newline,
1989    /// balanced `/* */` even across newlines, `#`-to-newline —
1990    /// never a standalone newline, which ends single-line
1991    /// expressions. Greedy gap before operators and operands; whitespace itself is
1992    /// already invisible in the token stream.
1993    fn skip_gap(&mut self) {
1994        loop {
1995            match self.toks.get(self.pos).map(|t| &t.kind) {
1996                Some(TokKind::Comment(_)) => {
1997                    self.pos += 1;
1998                }
1999                Some(TokKind::Punct('/')) if is_comment_open(self.toks, self.pos) => {
2000                    match skip_inline_comment(self.toks, self.pos) {
2001                        Some(next) => self.pos = next,
2002                        // Unclosed block comments fail the gap (and
2003                        // the enclosing rule) like the grammar.
2004                        None => break,
2005                    }
2006                }
2007                Some(TokKind::Punct('#')) => {
2008                    while self.pos < self.toks.len()
2009                        && !matches!(&self.toks[self.pos].kind, TokKind::Newline)
2010                    {
2011                        self.pos += 1;
2012                    }
2013                }
2014                _ => break,
2015            }
2016        }
2017    }
2018
2019    /// Skip gap comments plus standalone newlines (`gap_nl`: call
2020    /// args, list items, maps, parenthesized expressions).
2021    fn skip_gap_nl(&mut self) {
2022        loop {
2023            match self.toks.get(self.pos).map(|t| &t.kind) {
2024                Some(TokKind::Newline) => {
2025                    self.pos += 1;
2026                }
2027                _ => {
2028                    let before = self.pos;
2029                    self.skip_gap();
2030                    if self.pos == before {
2031                        break;
2032                    }
2033                }
2034            }
2035        }
2036    }
2037
2038    /// Consume the parenthesized group following a call word (`not`,
2039    /// `any`, `all`, `eq`, `ne`), ignoring gap width exactly like the
2040    /// grammar's implicit whitespace.
2041    fn eat_paren_group(&mut self) -> Option<Vec<Tok>> {
2042        match self.peek() {
2043            Some(t) => match &t.kind {
2044                TokKind::Group {
2045                    delim: GroupDelim::Paren,
2046                    inner,
2047                    ..
2048                } => {
2049                    let inner = inner.clone();
2050                    self.pos += 1;
2051                    Some(inner)
2052                }
2053                _ => None,
2054            },
2055            None => None,
2056        }
2057    }
2058}
2059
2060/// Split a flat token slice on top-level commas (nesting lives inside
2061/// atomic groups, so a flat scan is exact).
2062fn split_top_commas(toks: &[Tok]) -> Vec<&[Tok]> {
2063    let mut parts = Vec::new();
2064    let mut start = 0;
2065    for (i, t) in toks.iter().enumerate() {
2066        if matches!(&t.kind, TokKind::Punct(',')) {
2067            parts.push(&toks[start..i]);
2068            start = i + 1;
2069        }
2070    }
2071    parts.push(&toks[start..]);
2072    parts
2073}
2074
2075/// Punctuation admissible inside bare guard key runs: everything but
2076/// the terminators the parser enforces separately. `;` arrives as its
2077/// own token kind; the key charset admits it, so runs accept it literally.
2078fn key_char(c: char) -> bool {
2079    !matches!(
2080        c,
2081        ':' | '=' | '!' | ',' | '|' | '(' | ')' | ']' | VAR_SIGIL_CHAR
2082    )
2083}
2084
2085/// Consume a joint run of words/punctuation as one bare key or value.
2086/// Gaps end the run; terminators and groups end or fail it per `extra`.
2087fn bare_run(cur: &mut Cursor, extra: fn(char) -> bool, what: &str) -> Result<String, TokenError> {
2088    let mut out = String::new();
2089    loop {
2090        let tok = match cur.toks.get(cur.pos) {
2091            Some(t) if matches!(&t.kind, TokKind::Newline) => break,
2092            Some(t) => t,
2093            None => break,
2094        };
2095        // First element may follow a gap; continuations must be gapless.
2096        if !out.is_empty() && !tok.joint {
2097            break;
2098        }
2099        match &tok.kind {
2100            TokKind::Word(w) => out.push_str(w),
2101            TokKind::Punct(c) if key_char(*c) && extra(*c) => out.push(*c),
2102            TokKind::Semicolon if extra(';') => out.push(';'),
2103            _ => break,
2104        }
2105        cur.pos += 1;
2106    }
2107    if out.is_empty() {
2108        return Err(cur.err(format!("missing {what}")));
2109    }
2110    Ok(out)
2111}
2112
2113/// The `guard_term` negative lookahead: a complete term followed by
2114/// `(`, `:`, `=`, or `!` is malformed, never a longer form.
2115fn check_term_end(cur: &mut Cursor) -> Result<(), TokenError> {
2116    cur.skip_newlines();
2117    match cur.toks.get(cur.pos) {
2118        Some(t) => match &t.kind {
2119            TokKind::Group {
2120                delim: GroupDelim::Paren,
2121                ..
2122            } => Err(cur.err("unexpected `(` after guard term")),
2123            TokKind::Punct(c) if matches!(c, ':' | '=' | '!') => {
2124                Err(cur.err(format!("unexpected `{c}` after guard term")))
2125            }
2126            _ => Ok(()),
2127        },
2128        None => Ok(()),
2129    }
2130}
2131
2132fn os_guard(value: &str) -> GuardExpr {
2133    GuardExpr::Predicate(Guard::Attr {
2134        ns: Ns::Os,
2135        key: None,
2136        val: Some(value.to_string()),
2137    })
2138}
2139
2140/// Namespace validation for guard predicates with closed domains
2141/// (`family`, `os`, `arch`); open namespaces pass through.
2142fn ns_guard(ns: &str, val: &str, cur: &Cursor) -> Result<GuardExpr, TokenError> {
2143    match ns {
2144        "family" => match val {
2145            "unix" => Ok(GuardExpr::or(vec![os_guard("macos"), os_guard("linux")])),
2146            "windows" => Ok(os_guard("windows")),
2147            _ => Err(cur.err(format!(
2148                "unknown family '{val}'; known values: unix, windows"
2149            ))),
2150        },
2151        "os" => match val {
2152            "macos" | "linux" | "windows" => Ok(os_guard(val)),
2153            _ => Err(cur.err(format!(
2154                "unknown os '{val}'; known values: macos, linux, windows"
2155            ))),
2156        },
2157        "arch" => {
2158            if crate::ARCH_VALUES.contains(&val) {
2159                Ok(GuardExpr::Predicate(Guard::Attr {
2160                    ns: Ns::Arch,
2161                    key: None,
2162                    val: Some(val.to_string()),
2163                }))
2164            } else {
2165                Err(cur.err(format!(
2166                    "unknown arch '{val}'; known values: {}",
2167                    crate::ARCH_VALUES.join(", ")
2168                )))
2169            }
2170        }
2171        _ => Err(cur.err(format!(
2172            "unknown guard namespace '{ns}'; known namespaces: family, os, arch, env, bool"
2173        ))),
2174    }
2175}
2176
2177fn parse_guard_term(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2178    let tok = cur
2179        .next()
2180        .ok_or_else(|| cur.err("missing guard predicate"))?;
2181    // A `!` prefix is never negation in guards (only `not(...)` negates).
2182    if matches!(&tok.kind, TokKind::Punct('!')) {
2183        return Err(cur.err("unexpected `!` in guard; negation uses `not(...)`"));
2184    }
2185    let word = match &tok.kind {
2186        TokKind::Word(w) => w.clone(),
2187        _ => return Err(cur.err("missing guard predicate")),
2188    };
2189    // `__OXDOCK_INJECT_N__` interpolation placeholder: env-key shape.
2190    if let Some(rest) = word.strip_prefix(INJECT_PREFIX) {
2191        if !rest.is_empty()
2192            && rest
2193                .strip_suffix(INJECT_SUFFIX)
2194                .is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()))
2195        {
2196            return Ok(GuardExpr::Predicate(Guard::Attr {
2197                ns: Ns::Env,
2198                key: Some(word),
2199                val: None,
2200            }));
2201        }
2202        return Err(cur.err("missing guard predicate"));
2203    }
2204    match word.as_str() {
2205        "eq" | "ne" => {
2206            let inner = cur
2207                .eat_paren_group()
2208                .ok_or_else(|| cur.err(format!("`{word}` requires `(env:KEY, value)`")))?;
2209            let mut arg = Cursor::new(&inner, cur.stmt);
2210            if arg.next().map(|t| &t.kind) != Some(&TokKind::Word("env".to_string())) {
2211                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2212            }
2213            if !arg.eat_punct(':') {
2214                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2215            }
2216            let key = bare_run(&mut arg, |_| true, "guard key")?;
2217            if !arg.eat_punct(',') {
2218                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2219            }
2220            arg.skip_newlines();
2221            let value = match arg.next() {
2222                Some(t) => match &t.kind {
2223                    TokKind::Str { text, .. } => text.clone(),
2224                    TokKind::BlockStr(full) => crate::command::lower_block_string(full),
2225                    _ => {
2226                        // Bare value: runs to the region end (commas and
2227                        // groups terminate it with an error, matching the
2228                        // bare-value exclusions).
2229                        arg.pos -= 1;
2230                        value_run(&mut arg)?
2231                    }
2232                },
2233                None => return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`"))),
2234            };
2235            if !arg.done() {
2236                return Err(arg.err(format!("unexpected text after `{word}` value")));
2237            }
2238            let pred = GuardExpr::Predicate(Guard::Attr {
2239                ns: Ns::Env,
2240                key: Some(key),
2241                val: Some(value),
2242            });
2243            if word == "ne" {
2244                Ok(GuardExpr::Not(Box::new(pred)))
2245            } else {
2246                Ok(pred)
2247            }
2248        }
2249        "bool" => {
2250            if !cur.eat_punct(':') {
2251                return Err(cur.err("`bool` requires `:value`"));
2252            }
2253            let val = bare_run(cur, |_| true, "bool value")?;
2254            check_term_end(cur)?;
2255            Ok(GuardExpr::Predicate(Guard::Attr {
2256                ns: Ns::Bool,
2257                key: None,
2258                val: Some(val),
2259            }))
2260        }
2261        "env" => {
2262            if !cur.eat_punct(':') {
2263                return Err(cur.err("`env` requires `:KEY`"));
2264            }
2265            let key = bare_run(cur, |_| true, "guard key")?;
2266            check_term_end(cur)?;
2267            Ok(GuardExpr::Predicate(Guard::Attr {
2268                ns: Ns::Env,
2269                key: Some(key),
2270                val: None,
2271            }))
2272        }
2273        _ => {
2274            if !cur.eat_punct(':') {
2275                return Err(cur.err("missing guard predicate"));
2276            }
2277            let val = bare_run(cur, |_| true, "guard value")?;
2278            check_term_end(cur)?;
2279            ns_guard(&word, &val, cur)
2280        }
2281    }
2282}
2283
2284/// Bare `eq`/`ne` value run: key charset plus `:`/`=`/`!` (the grammar
2285/// admits them in values, never in keys), with nested groups rendered
2286/// for the pathological `(`-in-value shape. `$`, `|`, `,` terminate
2287/// with an error downstream.
2288/// Bare `eq`/`ne` value with atomic bare-value semantics:
2289/// everything except `, | ) ] $`, linebreaks, and comment opens —
2290/// gaps included (joined with one space; the token stream cannot
2291/// preserve gap width). Quotes ride literally mid-run (the atomic
2292/// span keeps them); a *leading* quote never reaches here (the
2293/// caller strips it as the `quoted_string` alternative, which then
2294/// requires end-of-region like the grammar's committed choice).
2295fn value_run(arg: &mut Cursor) -> Result<String, TokenError> {
2296    let mut out = String::new();
2297    while let Some(tok) = arg.toks.get(arg.pos) {
2298        // Terminators: the grammar's negative-lookahead set.
2299        match &tok.kind {
2300            TokKind::Newline | TokKind::Comment(_) => break,
2301            TokKind::Punct(',')
2302            | TokKind::Punct('|')
2303            | TokKind::Punct(']')
2304            | TokKind::Punct(')') => break,
2305            TokKind::Punct(VAR_SIGIL_CHAR) => break,
2306            TokKind::Punct('/') if is_comment_open(arg.toks, arg.pos) => break,
2307            TokKind::Group { .. } => break,
2308            _ => {}
2309        }
2310        if !out.is_empty() && !tok.joint {
2311            out.push(' ');
2312        }
2313        match &tok.kind {
2314            TokKind::Word(w) => out.push_str(w),
2315            TokKind::Punct(c) => out.push(*c),
2316            TokKind::Semicolon => out.push(';'),
2317            // Mid-run quotes keep their marks, like the atomic span.
2318            TokKind::Str { text, quote } => {
2319                out.push(*quote);
2320                out.push_str(text);
2321                out.push(*quote);
2322            }
2323            TokKind::BlockStr(full) => out.push_str(full),
2324            _ => break,
2325        }
2326        arg.pos += 1;
2327    }
2328    if out.is_empty() {
2329        return Err(arg.err("missing guard value"));
2330    }
2331    Ok(out)
2332}
2333
2334/// True when the cursor sits on `name` followed (over newlines,
2335/// like the grammar's implicit whitespace) by a paren group.
2336fn at_call(cur: &Cursor, name: &str) -> bool {
2337    let mut pos = cur.pos;
2338    // Leading newlines skip (the grammar's implicit whitespace gaps
2339    // multi-line guards, e.g. `[\nnot(env:K)\n]`).
2340    while matches!(cur.toks.get(pos).map(|t| &t.kind), Some(TokKind::Newline)) {
2341        pos += 1;
2342    }
2343    match cur.toks.get(pos) {
2344        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == name) => pos += 1,
2345        _ => return false,
2346    }
2347    while matches!(cur.toks.get(pos).map(|t| &t.kind), Some(TokKind::Newline)) {
2348        pos += 1;
2349    }
2350    matches!(
2351        cur.toks.get(pos).map(|t| &t.kind),
2352        Some(TokKind::Group {
2353            delim: GroupDelim::Paren,
2354            ..
2355        })
2356    )
2357}
2358
2359fn parse_guard_primary(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2360    // Call shapes dispatch on word + paren group regardless of gap
2361    // width (the grammar's implicit whitespace); anything else is a term.
2362    for name in ["not", "any", "all"] {
2363        if at_call(cur, name) {
2364            cur.next();
2365            let inner = cur
2366                .eat_paren_group()
2367                .ok_or_else(|| cur.err("unreachable"))?;
2368            let parts = split_top_commas(&inner);
2369            match name {
2370                "not" => {
2371                    if parts.len() != 1 {
2372                        return Err(cur.err("`not` takes exactly one guard expression"));
2373                    }
2374                    let mut sub = Cursor::new(parts[0], cur.stmt);
2375                    let expr = parse_guard_seq(&mut sub)?;
2376                    if !sub.done() {
2377                        return Err(sub.err("unexpected text in `not`"));
2378                    }
2379                    return Ok(GuardExpr::Not(Box::new(expr)));
2380                }
2381                "any" => {
2382                    if parts.len() < 2 {
2383                        return Err(cur.err("any(...) requires at least two guard expressions"));
2384                    }
2385                    let mut exprs = Vec::new();
2386                    for part in parts {
2387                        let mut sub = Cursor::new(part, cur.stmt);
2388                        exprs.push(parse_guard_seq(&mut sub)?);
2389                        if !sub.done() {
2390                            return Err(sub.err("unexpected text in `any`"));
2391                        }
2392                    }
2393                    return Ok(GuardExpr::or(exprs));
2394                }
2395                _ => {
2396                    if parts.is_empty() {
2397                        return Err(cur.err("all(...) requires at least one guard expression"));
2398                    }
2399                    let mut exprs = Vec::new();
2400                    for part in parts {
2401                        if part.iter().all(|t| matches!(&t.kind, TokKind::Newline)) {
2402                            return Err(cur.err("all(...) requires at least one guard expression"));
2403                        }
2404                        let mut sub = Cursor::new(part, cur.stmt);
2405                        exprs.push(parse_guard_seq(&mut sub)?);
2406                        if !sub.done() {
2407                            return Err(sub.err("unexpected text in `all`"));
2408                        }
2409                    }
2410                    return Ok(GuardExpr::all(exprs));
2411                }
2412            }
2413        }
2414    }
2415    match cur.peek() {
2416        Some(t) => match &t.kind {
2417            TokKind::Group {
2418                delim: GroupDelim::Paren,
2419                inner,
2420                ..
2421            } => {
2422                let inner = inner.clone();
2423                cur.next();
2424                let mut sub = Cursor::new(&inner, cur.stmt);
2425                let expr = parse_guard_seq(&mut sub)?;
2426                if !sub.done() {
2427                    return Err(sub.err("unexpected text in guard group"));
2428                }
2429                Ok(expr)
2430            }
2431            _ => parse_guard_term(cur),
2432        },
2433        None => Err(cur.err("missing guard expression")),
2434    }
2435}
2436
2437fn parse_guard_seq(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2438    let first = parse_guard_primary(cur)?;
2439    let mut rest = vec![first];
2440    while cur.eat_punct(',') {
2441        rest.push(parse_guard_primary(cur)?);
2442    }
2443    if rest.len() == 1 {
2444        Ok(rest.pop().unwrap())
2445    } else {
2446        Ok(GuardExpr::all(rest))
2447    }
2448}
2449
2450/// Parse one bracket group's contents as a guard expression.
2451fn parse_guard_inner(inner: &[Tok], stmt: usize) -> Result<GuardExpr, TokenError> {
2452    let mut cur = Cursor::new(inner, stmt);
2453    let expr = parse_guard_seq(&mut cur)?;
2454    if !cur.done() {
2455        return Err(cur.err("unexpected text in guard"));
2456    }
2457    Ok(expr)
2458}
2459
2460/// Parse one standalone guard expression from lexed tokens (the
2461/// `parse_guard_expr_str` entry point): a bare `guard_seq` with full
2462/// consumption.
2463pub(crate) fn parse_single_guard(toks: &[Tok], stmt: usize) -> Result<GuardExpr, TokenError> {
2464    let mut cur = Cursor::new(toks, stmt);
2465    if cur.done() {
2466        return Err(cur.err("empty guard"));
2467    }
2468    let expr = parse_guard_seq(&mut cur)?;
2469    if !cur.done() {
2470        return Err(cur.err("unexpected text in guard"));
2471    }
2472    Ok(expr)
2473}
2474
2475/// Combine a statement's leading guard groups: stacked brackets `All`
2476/// together, a single bracket stands alone.
2477fn parse_guard_groups(guard: &[Tok], stmt: usize) -> Result<Option<GuardExpr>, TokenError> {
2478    let mut acc: Option<GuardExpr> = None;
2479    for tok in guard {
2480        let inner = match &tok.kind {
2481            TokKind::Group {
2482                delim: GroupDelim::Bracket,
2483                inner,
2484                ..
2485            } => inner.clone(),
2486            _ => {
2487                return Err(TokenError {
2488                    stmt,
2489                    msg: "unsupported non-bracket guard".to_string(),
2490                    line: 0,
2491                    col: 0,
2492                    kind: None,
2493                });
2494            }
2495        };
2496        let expr = parse_guard_inner(&inner, stmt)?;
2497        acc = Some(match acc {
2498            None => expr,
2499            Some(prev) => GuardExpr::all(vec![prev, expr]),
2500        });
2501    }
2502    Ok(acc)
2503}
2504
2505// ---- Calls, RUN-exec, instruction exactness ----
2506// Static call resolution runs through the shared `resolve_call_name`
2507// (same module table, same messages); only the token-level call-shape
2508// detector is v2-native. Generic arguments classify like the
2509// `assignment | argument` grammar order (assignments merge across
2510// gaps, `$`/`env:`-led runs extend as expressions, everything else
2511// renders raw), and `ENV`/`EXPAND` lower through the shared direct
2512// cores instead of the injected dispatcher.
2513
2514/// Parse context: shared lowering dispatcher plus module table for
2515/// static call resolution, with `FUNC`/import frames per braced body.
2516pub struct ParseCtx<'a> {
2517    pub lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
2518    pub modules: &'a ModuleTable,
2519    /// Host-registered function names for the `FUNC` shadow check
2520    /// (empty when hosts are unknown).
2521    pub reserved: &'a HashSet<String>,
2522    /// `FUNC` scopes (innermost last) and import frames, pushed per
2523    /// braced body; short borrows only,
2524    /// never held across recursive parses.
2525    pub funcs: RefCell<Vec<HashSet<String>>>,
2526    pub imports: RefCell<Vec<Vec<(String, bool)>>>,
2527    /// Single-file `EXPORT` metadata in source order, validated at end
2528    /// of parse (forward references allowed). One struct for all three
2529    /// kinds so holders never thread parallel lists.
2530    pub exports: RefCell<Exports>,
2531    /// Top-level `FUNC` names pre-declared before lowering, so forward
2532    /// references resolve regardless of order. Separate from `funcs`
2533    /// frames so duplicate detection in `declare_func` stays intact;
2534    /// `visible_snapshot` unions this set.
2535    pub forward: RefCell<Vec<HashSet<String>>>,
2536    /// 1-based source line of the statement currently lowering (the
2537    /// innermost split statement; updated per statement by the body
2538    /// loops, read as the base for nested splits). Lets every error
2539    /// carry its statement's line without threading it through every
2540    /// header function by hand.
2541    pub current_line: RefCell<usize>,
2542}
2543
2544impl<'a> ParseCtx<'a> {
2545    /// Context with empty tables.
2546    pub fn empty(
2547        lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
2548        modules: &'a ModuleTable,
2549        reserved: &'a HashSet<String>,
2550    ) -> Self {
2551        Self {
2552            lower,
2553            modules,
2554            reserved,
2555            funcs: RefCell::new(vec![HashSet::new()]),
2556            imports: RefCell::new(vec![Vec::new()]),
2557            exports: RefCell::new(Exports::default()),
2558            forward: RefCell::new(vec![HashSet::new()]),
2559            current_line: RefCell::new(0),
2560        }
2561    }
2562
2563    /// Snapshot of everything visible at this point: `FUNC` names
2564    /// unioned across frames plus imports flattened outer-to-inner
2565    /// (unions `FUNC` names across frames, flattens imports outer-to-inner,
2566    /// dropping guardedness: call resolution only needs names).
2567    fn visible_snapshot(&self) -> (HashSet<String>, Vec<String>) {
2568        let mut funcs = HashSet::new();
2569        for scope in self.funcs.borrow().iter() {
2570            funcs.extend(scope.iter().cloned());
2571        }
2572        funcs.extend(
2573            self.forward
2574                .borrow()
2575                .iter()
2576                .flat_map(|frame| frame.iter().cloned()),
2577        );
2578        let mut imports = Vec::new();
2579        for frame in self.imports.borrow().iter() {
2580            for (module, _) in frame {
2581                if !imports.contains(module) {
2582                    imports.push(module.clone());
2583                }
2584            }
2585        }
2586        (funcs, imports)
2587    }
2588
2589    /// Record a `FUNC` name in the innermost scope. Returns false when
2590    /// already defined in that same scope (nested shadowing stays
2591    /// allowed (nested shadowing stays permitted).
2592    fn declare_func(&self, name: &str) -> bool {
2593        match self.funcs.borrow_mut().last_mut() {
2594            Some(current) => current.insert(name.to_string()),
2595            None => true,
2596        }
2597    }
2598
2599    /// Record `IMPORT`ed modules in the innermost frame (deduped,
2600    /// (deduped; the unknown-module table check lives at the import site),
2601    /// which lives at the import site. `guarded` marks guard-gated
2602    /// imports so the same-frame duplicate gate can tell a probable
2603    /// typo (unguarded, always collides) from a platform branch
2604    /// (guarded, disjointness decided by the static pass).
2605    fn import_into_frame(&self, modules: &[String], guarded: bool) {
2606        match self.imports.borrow_mut().last_mut() {
2607            Some(frame) => {
2608                for module in modules {
2609                    if !frame.iter().any(|(known, _)| known == module) {
2610                        frame.push((module.clone(), guarded));
2611                    }
2612                }
2613            }
2614            None => {
2615                self.imports
2616                    .borrow_mut()
2617                    .push(modules.iter().map(|m| (m.clone(), guarded)).collect());
2618            }
2619        }
2620    }
2621
2622    /// Guardedness of every visible entry for `alias`, outer to inner.
2623    /// Single owner for the duplicate-gate input, so the gate never
2624    /// restates the frame walk.
2625    fn import_guard_flags(&self, alias: &str) -> Vec<bool> {
2626        let mut out = Vec::new();
2627        for frame in self.imports.borrow().iter() {
2628            for (known, guarded) in frame {
2629                if known == alias {
2630                    out.push(*guarded);
2631                }
2632            }
2633        }
2634        out
2635    }
2636}
2637
2638fn resolve_name(ctx: &ParseCtx, stmt: usize, name: &str) -> Result<String, TokenError> {
2639    let (funcs, imports) = ctx.visible_snapshot();
2640    resolve_call_name(ctx.modules, &funcs, &imports, &lowering_ctx(stmt), name)
2641        .map_err(|e| lower_err(stmt, e))
2642}
2643
2644/// Pre-declare `FUNC` names before lowering, so forward references
2645/// resolve regardless of order. Only valid non-reserved headers hoist:
2646/// the head (`FUNC NAME`, `ASYNC FUNC NAME`), a parameter Paren group,
2647/// a `:` return-type shape (via the shared `parse_type_shape` owner),
2648/// and a trailing non-template Brace body. Malformed headers
2649/// (`FUNC FOO() ECHO hi`) and reserved names (`FUNC LEN`) stay silent
2650/// here so the main pass owns their diagnostics. Runs per scope: the
2651/// caller pre-declares each statement list into its own frame, so
2652/// nested blocks resolve forward without leaking outward.
2653fn predeclare_forward_funcs(stmts: &[Stmt], ctx: &ParseCtx) {
2654    // Guarded definitions hoist like unguarded ones: `parse_func_at`
2655    // registers the name in `ctx.funcs` unconditionally, so the
2656    // forward set must see the same statement regardless of its
2657    // guard, or forward calls to `[os:macos] FUNC FOO` would fail
2658    // while backward calls resolve.
2659    for stmt in stmts {
2660        let body = &stmt.body;
2661        // `ASYNC FUNC` carries the prefix; the shared header owner
2662        // takes `pos` at `FUNC` in both cases.
2663        let pos = match body.first().map(|t| &t.kind) {
2664            Some(TokKind::Word(w)) if w == KEYWORD_FUNC => 0,
2665            Some(TokKind::Word(w)) if w == KEYWORD_ASYNC => match body.get(1).map(|t| &t.kind) {
2666                Some(TokKind::Word(next)) if next == KEYWORD_FUNC => 1,
2667                _ => continue,
2668            },
2669            _ => continue,
2670        };
2671        // Header grammar lives in the single owner: parameter lists,
2672        // return types, and trailing tokens validate exactly like the
2673        // real path, so malformed headers never hoist. Diagnostics
2674        // drop here (silent skip); the main pass owns the error.
2675        let Ok(Some((header, _))) = parse_func_header(body, pos, 0, KEYWORD_FUNC) else {
2676            continue;
2677        };
2678        if ctx.reserved.contains(&header.name)
2679            || ctx.modules.reserved_base_names().contains(&header.name)
2680        {
2681            continue;
2682        }
2683        // Trailing tokens after the body block are malformed (the real
2684        // path consumes the header exactly, leaving them to fail as the
2685        // next element), so such headers never hoist into `forward`:
2686        // only gap trivia may follow.
2687        if body.len() != header.block + 1
2688            && !body[header.block + 1..]
2689                .iter()
2690                .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
2691        {
2692            continue;
2693        }
2694        if let Some(frame) = ctx.forward.borrow_mut().last_mut() {
2695            frame.insert(header.name.clone());
2696        }
2697    }
2698}
2699
2700/// Qualify bare placeholder calls in template text through the
2701/// shared static resolver, so `{{ NAME(args) }}` obeys exactly the
2702/// same scope rule as statement-position calls: `IMPORT [MOD]`
2703/// brings the names into scope, unimported names fail naming the
2704/// fix, ambiguity fails closed. Qualified (`MOD::FUNC`), variable
2705/// (`$x`, `bare_key`), env (`env:K`), and non-call keys pass
2706/// through untouched for the runtime to handle exactly as before;
2707/// only keys that are entirely one bare call shape are rewritten,
2708/// and only the head identifier's bytes change: surrounding
2709/// spacing and neighboring placeholders stay byte-identical, so
2710/// string payloads never lose formatting. Returns `None` when
2711/// nothing qualified, leaving the text completely untouched.
2712/// Shape detection is the shared `template::parse_placeholder_call`
2713/// grammar (also behind runtime dispatch), so parse and runtime
2714/// can never disagree on what counts as one call.
2715fn qualify_template_calls(
2716    text: &str,
2717    ctx: &ParseCtx,
2718    stmt: usize,
2719) -> Result<Option<String>, TokenError> {
2720    use crate::template::{TemplateSegment, TemplateSegments, parse_placeholder_call};
2721    let mut out = String::with_capacity(text.len());
2722    let mut changed = false;
2723    for segment in TemplateSegments::new(text) {
2724        match segment {
2725            TemplateSegment::Text(raw) => out.push_str(raw),
2726            TemplateSegment::Placeholder { key, raw } => {
2727                let call = match parse_placeholder_call(key) {
2728                    Some(call) if call.module.is_none() => call,
2729                    _ => {
2730                        out.push_str(raw);
2731                        continue;
2732                    }
2733                };
2734                let head = call.name;
2735                let resolved = resolve_name(ctx, stmt, head)?;
2736                if !resolved.contains(MODULE_SEPARATOR) {
2737                    // Unqualified resolutions (`INSPECT`) keep today's
2738                    // runtime handling untouched.
2739                    out.push_str(raw);
2740                    continue;
2741                }
2742                changed = true;
2743                // Splice only the head span: `name_span` is the byte
2744                // range of the head inside `key`, and `key` is the
2745                // trimmed interior of `raw`, so the raw offset is the
2746                // interior start plus the span start.
2747                let key_off = raw.find(key).expect("key is trimmed interior");
2748                let off = key_off + call.name_span.start;
2749                out.push_str(&raw[..off]);
2750                out.push_str(&resolved);
2751                out.push_str(&raw[off + head.len()..]);
2752            }
2753        }
2754    }
2755    if changed { Ok(Some(out)) } else { Ok(None) }
2756}
2757
2758/// Call shape at `pos`: UPPERCASE head plus joint `::` segments and a
2759/// paren group (joint iff required: statements forbid the gap;
2760/// expressions allow it).
2761/// Peek-only; anything else falls through (not a call shape).
2762/// Returns the dotted name and paren index.
2763fn call_shape_at(toks: &[Tok], pos: usize, joint_paren: bool) -> Option<(String, usize)> {
2764    let head = match toks.get(pos).map(|t| &t.kind) {
2765        Some(TokKind::Word(w))
2766            if !w.is_empty()
2767                && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
2768                && w.chars()
2769                    .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') =>
2770        {
2771            w.clone()
2772        }
2773        _ => return None,
2774    };
2775    let mut name = head;
2776    let mut p = pos + 1;
2777    loop {
2778        let colons = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')))
2779            && toks.get(p).is_some_and(|t| t.joint)
2780            && matches!(toks.get(p + 1).map(|t| &t.kind), Some(TokKind::Punct(':')))
2781            && toks.get(p + 1).is_some_and(|t| t.joint)
2782            && matches!(toks.get(p + 2).map(|t| &t.kind), Some(TokKind::Word(_)))
2783            && toks.get(p + 2).is_some_and(|t| t.joint);
2784        if !colons {
2785            break;
2786        }
2787        if let Some(TokKind::Word(seg)) = toks.get(p + 2).map(|t| &t.kind) {
2788            name.push_str(MODULE_SEPARATOR);
2789            name.push_str(seg);
2790        }
2791        p += 3;
2792    }
2793    match toks.get(p).map(|t| &t.kind) {
2794        Some(TokKind::Group {
2795            delim: GroupDelim::Paren,
2796            ..
2797        }) => {
2798            if joint_paren && !toks[p].joint {
2799                return None;
2800            }
2801            Some((name, p))
2802        }
2803        _ => None,
2804    }
2805}
2806
2807/// Call arguments over a paren group's contents: comma-separated full
2808/// expressions with `gap_nl` newlines at the edges (each arg rejects
2809/// a stray boundary).
2810fn parse_call_args(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Vec<Expr>, TokenError> {
2811    let mut cur = Cursor::expr(inner, stmt);
2812    cur.skip_gap_nl();
2813    if cur.done() {
2814        return Ok(vec![]);
2815    }
2816    let mut args = Vec::new();
2817    loop {
2818        let arg = parse_expr_or(&mut cur, ctx)?;
2819        reject_boundary(&lowering_ctx(stmt), &arg).map_err(|e| cur.err(e.to_string()))?;
2820        args.push(arg);
2821        cur.skip_gap_nl();
2822        if cur.eat_punct(',') {
2823            cur.skip_gap_nl();
2824            continue;
2825        }
2826        break;
2827    }
2828    if !cur.done() {
2829        return Err(trailing_items_error(
2830            &cur,
2831            ctx,
2832            stmt,
2833            "call arguments",
2834            "unexpected text in call",
2835        ));
2836    }
2837    Ok(args)
2838}
2839
2840/// Lower a call-shape to `Expr`: `INSPECT` keeps its variable
2841/// unevaluated (`INSPECT($var)` for `LET` and `$`-sigiled `CONST`
2842/// reads); everything else resolves statically through the shared
2843/// resolver.
2844fn parse_expr_call(
2845    name: String,
2846    inner: &[Tok],
2847    stmt: usize,
2848    ctx: &ParseCtx,
2849) -> Result<Expr, TokenError> {
2850    let args = parse_call_args(inner, stmt, ctx)?;
2851    if name == KEYWORD_INSPECT {
2852        let [arg] = args.as_slice() else {
2853            return Err(TokenError {
2854                stmt,
2855                msg: "INSPECT requires exactly one argument: INSPECT($var)".to_string(),
2856                line: 0,
2857                col: 0,
2858                kind: None,
2859            });
2860        };
2861        if let Expr::Var { name } = arg {
2862            return Ok(Expr::Inspect { name: name.clone() });
2863        }
2864        return Err(TokenError {
2865            stmt,
2866            msg: format!("INSPECT requires a $variable argument, found {arg:?}"),
2867            line: 0,
2868            col: 0,
2869            kind: None,
2870        });
2871    }
2872    let qualified = resolve_name(ctx, stmt, &name)?;
2873    Ok(Expr::Call {
2874        name: qualified,
2875        args,
2876    })
2877}
2878
2879/// Item rule selecting which `[...]` position the shared list core
2880/// parses for. The loop, comma rule, empty rule, trailing-content rule,
2881/// and newline tolerance are identical for every position (see
2882/// [`parse_bracket_list`]); only items and miss handling differ.
2883#[derive(Clone, Copy)]
2884enum BracketItems {
2885    /// Full checked expressions; a miss fails loudly.
2886    Expr,
2887    /// RUN-exec restricted atoms (brace groups try maps only, so blocks
2888    /// miss); a miss is shell fallthrough (`None`), never an error, so
2889    /// POSIX `[ -f ... ]` and malformed shapes stay shell.
2890    Exec,
2891}
2892
2893/// Trailing-content error for comma-separated positions (list
2894/// items, call arguments): stamps the offending token's position so
2895/// the caret names the line that actually fails instead of the
2896/// statement head, and names the likely missing comma when the
2897/// remainder parses as another item. Genuine trailing garbage keeps
2898/// the previous message verbatim. Error-path only, so the probe
2899/// parse costs nothing on success.
2900fn trailing_items_error(
2901    cur: &Cursor,
2902    ctx: &ParseCtx,
2903    stmt: usize,
2904    missing_what: &str,
2905    fallback: &str,
2906) -> TokenError {
2907    let (line, col) = cur
2908        .toks
2909        .get(cur.pos)
2910        .map(|t| (t.line, t.col))
2911        .unwrap_or((0, 0));
2912    let mut probe = Cursor::expr(&cur.toks[cur.pos.min(cur.toks.len())..], stmt);
2913    let msg = if parse_expr_checked(&mut probe, ctx).is_ok() {
2914        format!("missing comma between {missing_what}")
2915    } else {
2916        fallback.to_string()
2917    };
2918    TokenError {
2919        stmt,
2920        line,
2921        col,
2922        msg,
2923        kind: None,
2924    }
2925}
2926
2927/// Shared comma-separated `[...]` core behind every bracket position.
2928/// There is exactly one list loop: one empty rule, one comma rule, one
2929/// trailing-content rule, newlines riding every gap. A bracket group
2930/// already lexes across lines, so rejecting newlines here only strands
2931/// the statement in raw-text rendering.
2932fn parse_bracket_list(
2933    inner: &[Tok],
2934    stmt: usize,
2935    ctx: &ParseCtx,
2936    items: BracketItems,
2937) -> Result<Option<Expr>, TokenError> {
2938    let mut cur = Cursor::expr(inner, stmt);
2939    cur.skip_gap_nl();
2940    if cur.done() {
2941        return Ok(Some(Expr::List(vec![])));
2942    }
2943    let mut list = Vec::new();
2944    loop {
2945        let item = match items {
2946            BracketItems::Expr => parse_expr_checked(&mut cur, ctx),
2947            BracketItems::Exec => match parse_run_exec_atom(&mut cur, ctx) {
2948                Ok(Some(atom)) => Ok(atom),
2949                // Not an exec shape at all: shell fallthrough.
2950                Ok(None) | Err(_) => return Ok(None),
2951            },
2952        };
2953        // Only expression positions can fail here: exec misses
2954        // return `None` above.
2955        let item = item?;
2956        match reject_boundary(&lowering_ctx(stmt), &item) {
2957            Ok(()) => {}
2958            Err(e) if matches!(items, BracketItems::Expr) => {
2959                return Err(cur.err(e.to_string()));
2960            }
2961            Err(_) => return Ok(None),
2962        }
2963        list.push(item);
2964        cur.skip_gap_nl();
2965        if cur.eat_punct(',') {
2966            cur.skip_gap_nl();
2967            continue;
2968        }
2969        break;
2970    }
2971    if !cur.done() {
2972        return match items {
2973            BracketItems::Expr => Err(trailing_items_error(
2974                &cur,
2975                ctx,
2976                stmt,
2977                "list items",
2978                "unexpected text in list",
2979            )),
2980            BracketItems::Exec => Ok(None),
2981        };
2982    }
2983    Ok(Some(Expr::List(list)))
2984}
2985
2986/// RUN exec-form list: the shared bracket core in `Exec` mode (atoms
2987/// only, except parenthesized/calls/lists/maps which recurse fully).
2988/// Anything that is not a clean comma-separated list misses the whole
2989/// exec shape (`None`): the grammar falls through to the shell path,
2990/// which reads the bracket literally and lets the shared lowering
2991/// decide (POSIX `[ -f ... ]` stays shell; non-map blocks and malformed
2992/// shapes behave exactly like the grammar's fallthrough).
2993/// (`instruction`), which reads the bracket literally and lets the
2994/// shared lowering decide (POSIX `[ -f ... ]` stays shell, malformed
2995/// shapes fail there exactly like the grammar). Only the
2996/// joint-bracket gate stays a hard error (it precedes this function).
2997fn parse_run_exec_list(
2998    inner: &[Tok],
2999    stmt: usize,
3000    ctx: &ParseCtx,
3001) -> Result<Option<Expr>, TokenError> {
3002    parse_bracket_list(inner, stmt, ctx, BracketItems::Exec)
3003}
3004
3005/// One RUN-exec item: brace groups try maps only (blocks miss);
3006/// everything else parses as a full atom (nested lists and map
3007/// values still admit blocks, like the grammar).
3008fn parse_run_exec_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Option<Expr>, TokenError> {
3009    if matches!(
3010        cur.toks.get(cur.pos).map(|t| &t.kind),
3011        Some(TokKind::Group {
3012            delim: GroupDelim::Brace,
3013            ..
3014        })
3015    ) {
3016        let inner = match &cur.toks[cur.pos].kind {
3017            TokKind::Group { inner, .. } => inner.clone(),
3018            _ => unreachable!(),
3019        };
3020        return match parse_map_literal(&inner, cur.stmt, ctx) {
3021            Ok(map) => {
3022                cur.pos += 1;
3023                Ok(Some(map))
3024            }
3025            Err(_) => Ok(None),
3026        };
3027    }
3028    parse_expr_atom(cur, ctx).map(Some)
3029}
3030
3031// ---- Single-command wrappers + AWAIT/CANCEL ----
3032// Wrappers parse through the shared validators (`check_tty_wrapping`,
3033// capture rejects, isolated rewrite, nesting reject, binding merge,
3034// guard `and`) promoted verbatim to `commands.rs`; only the
3035// token-level shape classifiers (duration gate, binding splitter,
3036// await/cancel shapes, block-vs-template) are v2-native. Statements
3037// lower to step VECTORS: structural pairs (calls, RUN-exec,
3038// await/cancel, wrapper blocks) end mid-line and trailing elements
3039// form following steps, exactly like the grammar's `element*`.
3040//
3041// Deferred: block STATEMENTS (slice 5: top-level `IF`/`FOR`/`WHILE`
3042// bodies, guard blocks, `REMOTE`, directives).
3043
3044/// Static duration shape mirror (`timeout_literal`, atomic): ASCII
3045/// digits plus one optional unit, full-match only. Anything else
3046/// (`10ss`, `banana`, `-5s`) misses the wrapper shape and falls back
3047/// to the generic instruction path, which fails in lowering exactly
3048/// like the grammar's committed `instruction`.
3049fn is_timeout_literal(text: &str) -> bool {
3050    let digits = text.len() - text.trim_start_matches(|c: char| c.is_ascii_digit()).len();
3051    if digits == 0 {
3052        return false;
3053    }
3054    matches!(&text[digits..], "" | "ms" | "s" | "m" | "h")
3055}
3056
3057/// Template-brace test: a brace group whose first inner token opens
3058/// another brace (`{{...}}`); anything else braced is a block body.
3059/// Same shape the arg engine uses; single source from here.
3060fn is_template_brace(tok: &Tok) -> bool {
3061    matches!(
3062        &tok.kind,
3063        TokKind::Group {
3064            delim: GroupDelim::Brace,
3065            inner,
3066            ..
3067        } if matches!(
3068            inner.first().map(|t| &t.kind),
3069            Some(TokKind::Group {
3070                delim: GroupDelim::Brace,
3071                ..
3072            })
3073        )
3074    )
3075}
3076
3077/// Parse one TIMEOUT duration unit at `pos` (the token after the
3078/// head, gapped like the grammar's `sep`). Returns the arg and
3079/// tokens consumed, or `None` on shape miss (caller falls back to
3080/// generic, which fails in lowering). Static
3081/// literals validate now through the shared Duration check
3082/// (`TIMEOUT 0s` fails here, probed); dynamics defer to runtime.
3083fn parse_timeout_duration_at(
3084    toks: &[Tok],
3085    pos: usize,
3086    stmt: usize,
3087) -> Result<Option<(Arg, usize)>, TokenError> {
3088    let Some(head) = toks.get(pos) else {
3089        return Ok(None);
3090    };
3091    if head.joint {
3092        return Ok(None);
3093    }
3094    let arg = match &head.kind {
3095        TokKind::Word(w) if is_timeout_literal(w) => Arg::String(w.clone(), false),
3096        TokKind::Punct(VAR_SIGIL_CHAR) => match toks.get(pos + 1) {
3097            Some(var) if var.joint && matches!(&var.kind, TokKind::Word(w) if is_ident_word(w)) => {
3098                match &var.kind {
3099                    TokKind::Word(w) => Arg::Expr(Expr::Var { name: w.clone() }),
3100                    _ => unreachable!(),
3101                }
3102            }
3103            _ => return Ok(None),
3104        },
3105        TokKind::Str { text, .. } => Arg::String(text.clone(), true),
3106        TokKind::BlockStr(full) => Arg::String(crate::command::lower_block_string(full), true),
3107        TokKind::Group {
3108            delim: GroupDelim::Brace,
3109            inner,
3110            open_joint,
3111            close_joint,
3112        } if is_template_brace(&toks[pos]) => Arg::String(
3113            render_group('{', '}', inner, *open_joint, *close_joint),
3114            false,
3115        ),
3116        _ => return Ok(None),
3117    };
3118    let used = match &head.kind {
3119        TokKind::Punct(VAR_SIGIL_CHAR) => 2,
3120        _ => 1,
3121    };
3122    ArgType::Duration.check_arg(&arg).map_err(|e| TokenError {
3123        stmt,
3124        msg: e.to_string(),
3125        line: 0,
3126        col: 0,
3127        kind: None,
3128    })?;
3129    Ok(Some((arg, used)))
3130}
3131
3132/// Parse `WITH_IO [...]` bindings over a bracket group's inner
3133/// tokens: comma-separated `stream[=$var]` / `rows|cols=int`
3134/// bindings, newlines skipping freely like `ws`. Returns `None` on
3135/// shape miss (empty flags, bad stream words, missing commas or
3136/// values: the caller falls back to generic, which fails in lowering).
3137/// Grammar-matched but invalid bindings (tty
3138/// values, out-of-range geometry) fail loudly, mirroring
3139/// `parse_io_binding`'s messages one by one.
3140fn parse_io_bindings(
3141    inner: &[Tok],
3142    stmt: usize,
3143    ctx: &ParseCtx,
3144) -> Result<Option<Vec<IoBinding>>, TokenError> {
3145    let mut parts: Vec<&[Tok]> = Vec::new();
3146    let mut start = 0;
3147    for (i, tok) in inner.iter().enumerate() {
3148        // Newlines skip freely like `ws` (filtered per part below);
3149        // commas split bindings; everything else is content.
3150        if matches!(&tok.kind, TokKind::Punct(',')) {
3151            parts.push(&inner[start..i]);
3152            start = i + 1;
3153        }
3154    }
3155    parts.push(&inner[start..]);
3156    // An empty flag list (`[]`, `[,]`) misses the shape.
3157    if parts.len() == 1 && parts[0].iter().all(|t| matches!(&t.kind, TokKind::Newline)) {
3158        return Ok(None);
3159    }
3160    let mut out = Vec::new();
3161    for part in parts {
3162        let part: Vec<&Tok> = part
3163            .iter()
3164            .filter(|t| !matches!(&t.kind, TokKind::Newline))
3165            .collect();
3166        match parse_io_binding_part(&part, stmt, ctx)? {
3167            Some(binding) => out.push(binding),
3168            None => return Ok(None),
3169        }
3170    }
3171    if out.is_empty() {
3172        return Ok(None);
3173    }
3174    Ok(Some(out))
3175}
3176
3177/// One `stream[=$var]` / `rows|cols=int` binding.
3178/// Gaps ride free around `=`/`,`/names like `ws?`; only `$`+name
3179/// stays gapless (atomic `dollar_ident`), covering `LET` and
3180/// `$`-sigiled `CONST` pipes alike. Streams and size names outside the grammar's words
3181/// miss the shape; a valued `tty` and out-of-range geometry fail
3182/// loudly with exact messages.
3183fn parse_io_binding_part(
3184    part: &[&Tok],
3185    stmt: usize,
3186    _ctx: &ParseCtx,
3187) -> Result<Option<IoBinding>, TokenError> {
3188    let fail = |msg: String| TokenError {
3189        stmt,
3190        msg,
3191        line: 0,
3192        col: 0,
3193        kind: None,
3194    };
3195    let Some(first) = part.first() else {
3196        return Ok(None);
3197    };
3198    let TokKind::Word(stream) = &first.kind else {
3199        return Ok(None);
3200    };
3201    let is_stream = matches!(stream.as_str(), "stdin" | "stdout" | "stderr" | "tty");
3202    let is_size = matches!(stream.as_str(), "rows" | "cols");
3203    if !is_stream && !is_size {
3204        return Ok(None);
3205    }
3206    let rest = &part[1..];
3207    if rest.is_empty() {
3208        if is_size {
3209            // Bare `rows` misses `io_size` (`=` + digits required).
3210            return Ok(None);
3211        }
3212        return Ok(Some(IoBinding {
3213            stream: io_stream_of(stream),
3214            pipe: None,
3215        }));
3216    }
3217    // `= value` at any gap.
3218    if !matches!(rest.first().map(|t| &t.kind), Some(TokKind::Punct('='))) {
3219        return Ok(None);
3220    }
3221    let value = &rest[1..];
3222    if is_size {
3223        // Geometry: one all-digit word, 1-65535 (mirrors `parse_io_size`).
3224        if value.len() != 1 {
3225            return Ok(None);
3226        }
3227        let TokKind::Word(digits) = &value[0].kind else {
3228            return Ok(None);
3229        };
3230        if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
3231            return Ok(None);
3232        }
3233        let dim = digits
3234            .parse::<u64>()
3235            .ok()
3236            .filter(|v| (1..=u64::from(u16::MAX)).contains(v))
3237            .ok_or_else(|| {
3238                fail(
3239                    "WITH_IO terminal geometry needs a positive integer 1-65535 (e.g. `rows=40`)"
3240                        .to_string(),
3241                )
3242            })?;
3243        let dim = dim as u16;
3244        return Ok(Some(IoBinding {
3245            stream: if stream == "rows" {
3246                IoStream::Rows(dim)
3247            } else {
3248                IoStream::Cols(dim)
3249            },
3250            pipe: None,
3251        }));
3252    }
3253    // Stream pipe: `= $var` with a gapless name.
3254    if value.len() == 2
3255        && matches!(&value[0].kind, TokKind::Punct(VAR_SIGIL_CHAR))
3256        && let TokKind::Word(var) = &value[1].kind
3257        && value[1].joint
3258        && is_ident_word(var)
3259    {
3260        if stream == "tty" {
3261            return Err(fail(
3262                "WITH_IO [tty] takes no value: use bare `tty`, with `rows = <int>` / `cols = <int>` for geometry (e.g. `[tty, rows=40, cols=100]`)"
3263                    .to_string(),
3264            ));
3265        }
3266        return Ok(Some(IoBinding {
3267            stream: io_stream_of(stream),
3268            pipe: Some(crate::ast::PipeTarget::Var { name: var.clone() }),
3269        }));
3270    }
3271    Ok(None)
3272}
3273
3274/// Stream word to [`IoStream`]: only grammar words reach here, so
3275/// the mapping is total (mirrors `parse_io_stream`).
3276fn io_stream_of(name: &str) -> IoStream {
3277    match name {
3278        "stdin" => IoStream::Stdin,
3279        "stdout" => IoStream::Stdout,
3280        "stderr" => IoStream::Stderr,
3281        _ => IoStream::Tty,
3282    }
3283}
3284
3285/// `AWAIT`/`CANCEL $var` shape at `pos` (`$`-sigiled, covering `LET`
3286/// and `CONST` handles alike). A head without `$` misses
3287/// (`None`: generic fails it in lowering); once `$` commits, the
3288/// name must follow and parse errors stay loud. `var_joint`
3289/// enforces atomic adjacency inside compound parents.
3290fn parse_await_cancel_at(
3291    toks: &[Tok],
3292    pos: usize,
3293    stmt: usize,
3294    var_joint: bool,
3295    _ctx: &ParseCtx,
3296) -> Result<Option<(StepKind, usize)>, TokenError> {
3297    let head = match toks.get(pos).map(|t| &t.kind) {
3298        Some(TokKind::Word(w)) if w == KEYWORD_AWAIT || w == KEYWORD_CANCEL => w.clone(),
3299        _ => return Ok(None),
3300    };
3301    if matches!(
3302        toks.get(pos + 1).map(|t| &t.kind),
3303        Some(TokKind::Punct(VAR_SIGIL_CHAR))
3304    ) {
3305        let var = match toks.get(pos + 2) {
3306            Some(t)
3307                if matches!(&t.kind, TokKind::Word(w) if is_ident_word(w))
3308                    && (!var_joint || t.joint) =>
3309            {
3310                match &t.kind {
3311                    TokKind::Word(w) => w.clone(),
3312                    _ => unreachable!(),
3313                }
3314            }
3315            _ => {
3316                return Err(TokenError {
3317                    stmt,
3318                    msg: format!("{head} requires a variable"),
3319                    line: 0,
3320                    col: 0,
3321                    kind: None,
3322                });
3323            }
3324        };
3325        return Ok(Some((
3326            if head == KEYWORD_AWAIT {
3327                StepKind::Await { var }
3328            } else {
3329                StepKind::Cancel { var }
3330            },
3331            3,
3332        )));
3333    }
3334    Ok(None)
3335}
3336
3337/// Wrapper strictness for one single-command inner: `AWAIT` parses
3338/// dedicated in `TIMEOUT`/`ISOLATED` inners but falls to generic in
3339/// `WITH_IO`/`ASYNC` inners (where lowering fails it, probed), and
3340/// `WITH_IO` recurses everywhere but directly under `ASYNC` (where
3341/// lowering fails it, probed). Shared predicates, never restated.
3342#[derive(Clone, Copy)]
3343struct InnerRules {
3344    allow_await: bool,
3345    allow_with_io: bool,
3346}
3347
3348/// Parse one single (non-block) inner command, returning the kind
3349/// and tokens consumed: dedicated await/cancel, while/remote, calls,
3350/// RUN-exec, nested wrappers, strict `INHERIT_ENV` (the caller
3351/// rejects the nesting or rewrites it), or the generic instruction
3352/// path (which consumes everything and fails unknown heads in
3353/// lowering, exactly like the grammar's committed `instruction`).
3354fn parse_single_inner(
3355    toks: &[Tok],
3356    pos: usize,
3357    stmt: usize,
3358    ctx: &ParseCtx,
3359    rules: InnerRules,
3360) -> Result<(StepKind, usize), TokenError> {
3361    let head_word = match toks.get(pos).map(|t| &t.kind) {
3362        Some(TokKind::Word(w)) => Some(w.clone()),
3363        _ => None,
3364    };
3365    // Nested `WHILE`/`REMOTE` recurse structurally (both ride every
3366    // inner-command set in the grammar); misses fall through to
3367    // generic below.
3368    if head_word.as_deref() == Some(KEYWORD_WHILE) {
3369        match parse_while_single(toks, pos, stmt, ctx) {
3370            Ok(Some((kind, used))) => return Ok((kind, used)),
3371            Ok(None) => {}
3372            Err(e) => return Err(e),
3373        }
3374    }
3375    if head_word.as_deref() == Some(KEYWORD_REMOTE) {
3376        match parse_remote_single(toks, pos, stmt, ctx) {
3377            Ok(Some((kind, used))) => return Ok((kind, used)),
3378            Ok(None) => {}
3379            Err(e) => return Err(e),
3380        }
3381    }
3382    // File `IMPORT "path" AS ALIAS` (#115) rides every single-inner
3383    // set (TIMEOUT/ISOLATED/WITH_IO/ASYNC, LET ASYNC): exactly one file
3384    // entry and no modules, else a hard error; shape misses fall through
3385    // to generic below, which fails them in lowering.
3386    if head_word.as_deref() == Some(KEYWORD_IMPORT)
3387        && let Some((path, alias, used)) = parse_single_file_import(toks, pos, stmt, ctx)?
3388    {
3389        return Ok((StepKind::ImportFile { path, alias }, used));
3390    }
3391    // Dedicated await/cancel first (await gated by parent); anything
3392    // they decline falls through to generic below.
3393    if head_word.as_deref() == Some(KEYWORD_AWAIT)
3394        && rules.allow_await
3395        && let Some(found) = parse_await_cancel_at(toks, pos, stmt, true, ctx)?
3396    {
3397        return Ok(found);
3398    }
3399    if head_word.as_deref() == Some(KEYWORD_CANCEL)
3400        && let Some(found) = parse_await_cancel_at(toks, pos, stmt, true, ctx)?
3401    {
3402        return Ok(found);
3403    }
3404    // Calls and RUN-exec end mid-run; the caller continues past them.
3405    if let Some((call_name, paren)) = call_shape_at(toks, pos, true) {
3406        let inner = match &toks[paren].kind {
3407            TokKind::Group { inner, .. } => inner.clone(),
3408            _ => unreachable!(),
3409        };
3410        let args = parse_call_args(&inner, stmt, ctx)?;
3411        if !call_name.contains(MODULE_SEPARATOR) {
3412            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
3413                .map_err(|e| lower_err(stmt, e))?;
3414        }
3415        let qualified = resolve_name(ctx, stmt, &call_name)?;
3416        return Ok((
3417            StepKind::Call {
3418                name: qualified,
3419                args,
3420            },
3421            paren + 1 - pos,
3422        ));
3423    }
3424    if head_word.as_deref() == Some(KEYWORD_RUN)
3425        && matches!(
3426            toks.get(pos + 1).map(|t| &t.kind),
3427            Some(TokKind::Group {
3428                delim: GroupDelim::Bracket,
3429                ..
3430            })
3431        )
3432    {
3433        // Gapped like the grammar's `sep`; a joint bracket is a
3434        // hard error, never a spliced arg (probed `RUN["a"]`).
3435        if toks[pos + 1].joint {
3436            return Err(TokenError {
3437                stmt,
3438                msg: "RUN [...] requires a gap after RUN".to_string(),
3439                line: 0,
3440                col: 0,
3441                kind: None,
3442            });
3443        }
3444        let inner = match &toks[pos + 1].kind {
3445            TokKind::Group { inner, .. } => inner.clone(),
3446            _ => unreachable!(),
3447        };
3448        let exec_list = parse_run_exec_list(&inner, stmt, ctx)?;
3449        // Non-map blocks miss the exec shape (the grammar has no
3450        // `block` alternative here); fall through to generic below,
3451        // which reads the shell path literally.
3452        if let Some(list) = exec_list {
3453            let kind =
3454                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
3455            return Ok((kind, 2));
3456        }
3457    }
3458    // Nested wrappers recurse structurally; a `WITH_IO` directly
3459    // under `ASYNC` goes generic instead (lowering fails it, probed).
3460    match head_word.as_deref() {
3461        Some(KEYWORD_WITH_IO) if rules.allow_with_io => {
3462            match parse_with_io_single(toks, pos, stmt, ctx) {
3463                Ok(Some((kind, used))) => return Ok((kind, used)),
3464                Ok(None) => {}
3465                Err(e) => return Err(e),
3466            }
3467        }
3468        Some(KEYWORD_TIMEOUT) => match parse_timeout_single(toks, pos, stmt, ctx) {
3469            Ok(Some((kind, used))) => return Ok((kind, used)),
3470            Ok(None) => {}
3471            Err(e) => return Err(e),
3472        },
3473        Some(KEYWORD_ISOLATED) => match parse_isolated_single(toks, pos, stmt, ctx) {
3474            Ok(Some((kind, used))) => return Ok((kind, used)),
3475            Ok(None) => {}
3476            Err(e) => return Err(e),
3477        },
3478        Some(KEYWORD_ASYNC) => match parse_async_single(toks, pos, stmt, ctx) {
3479            Ok(Some((kind, used))) => return Ok((kind, used)),
3480            Ok(None) => {}
3481            Err(e) => return Err(e),
3482        },
3483        // `INHERIT_ENV [...]` parses strictly here (shared with
3484        // element level); the caller either rejects the nesting or
3485        // rewrites it, same as the shared validator. Trailing
3486        // elements loop on outside (a bad follower fails there, like
3487        // the grammar's line end).
3488        Some(KEYWORD_INHERIT_ENV) => {
3489            if let Some(found) = parse_inherit_env_at(toks, pos, stmt)? {
3490                return Ok(found);
3491            }
3492        }
3493        _ => {}
3494    }
3495    // Generic instruction: consumes the whole run; unknown heads
3496    // (LET/RETURN/FUNC/IF/...) fail in lowering.
3497    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
3498    Ok((kind, used))
3499}
3500
3501/// Parse an `INHERIT_ENV [...]` key list over a bracket group's
3502/// inner tokens, mirroring `inherit_list` strictly: comma-separated
3503/// keys, gaps/newlines only around keys and commas (never inside:
3504/// keys are atomic), each key a joint run validated against the
3505/// `guard_key_char` exclusions (`: = ! , | ( ) ] $`, plus the `//`
3506/// and `/*` comment opens). Groups and strings render raw (they read
3507/// as ordinary characters here); anything else misses
3508/// the shape (`None`: generic fails it in lowering).
3509/// Statement-level `INHERIT_ENV` stays generic (slice 5 directives);
3510/// this serves wrapper inners, where the nesting check (or the
3511/// isolated rewrite) consumes the result.
3512fn parse_inherit_keys(inner: &[Tok], stmt: usize) -> Result<Option<Vec<String>>, TokenError> {
3513    let mut parts: Vec<&[Tok]> = Vec::new();
3514    let mut start = 0;
3515    for (i, tok) in inner.iter().enumerate() {
3516        if matches!(&tok.kind, TokKind::Punct(',')) {
3517            parts.push(&inner[start..i]);
3518            start = i + 1;
3519        }
3520    }
3521    parts.push(&inner[start..]);
3522    let mut out = Vec::new();
3523    for part in parts {
3524        // Newlines skip at the edges only, like `ws?`.
3525        let mut part = part;
3526        while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
3527            part = &part[1..];
3528        }
3529        while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
3530            part = &part[..part.len() - 1];
3531        }
3532        let Some(key) = render_inherit_key(part, stmt)? else {
3533            return Ok(None);
3534        };
3535        out.push(key);
3536    }
3537    if out.is_empty() {
3538        return Ok(None);
3539    }
3540    Ok(Some(out))
3541}
3542
3543/// True when a `/` opens an inline comment: joint `//` or `/*`
3544/// (mirroring the grammar's comment literals, which need adjacency;
3545/// a gapped second char is payload text, like `a/ /b`). Used
3546/// everywhere `gap`/`gap_nl` admit comments.
3547fn is_comment_open(toks: &[Tok], pos: usize) -> bool {
3548    matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('/')))
3549        && matches!(
3550            toks.get(pos + 1).map(|t| (&t.kind, t.joint)),
3551            Some((TokKind::Punct('/'), true)) | Some((TokKind::Punct('*'), true))
3552        )
3553}
3554
3555/// Skip one inline comment starting at `pos` (which holds the `/`;
3556/// see [`is_comment_open`): `//` runs to a newline or the end,
3557/// `/* */` balances (nesting like the grammar) across newlines.
3558/// Returns the first position past the comment, or `None` when the
3559/// block never closes (the grammar fails unclosed comments too).
3560fn skip_inline_comment(toks: &[Tok], pos: usize) -> Option<usize> {
3561    let second = match toks.get(pos + 1).map(|t| &t.kind) {
3562        Some(TokKind::Punct('/')) => '/',
3563        Some(TokKind::Punct('*')) => '*',
3564        _ => return None,
3565    };
3566    if second == '/' {
3567        let mut p = pos + 2;
3568        while p < toks.len() && !matches!(&toks[p].kind, TokKind::Newline) {
3569            p += 1;
3570        }
3571        return Some(p);
3572    }
3573    let mut depth = 1usize;
3574    let mut p = pos + 2;
3575    while p < toks.len() {
3576        let is_open = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('/')))
3577            && matches!(
3578                toks.get(p + 1).map(|t| (&t.kind, t.joint)),
3579                Some((TokKind::Punct('*'), true))
3580            );
3581        let is_close = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('*')))
3582            && matches!(
3583                toks.get(p + 1).map(|t| (&t.kind, t.joint)),
3584                Some((TokKind::Punct('/'), true))
3585            );
3586        if is_open {
3587            depth += 1;
3588            p += 2;
3589        } else if is_close {
3590            depth -= 1;
3591            p += 2;
3592            if depth == 0 {
3593                return Some(p);
3594            }
3595        } else {
3596            p += 1;
3597        }
3598    }
3599    None
3600}
3601
3602/// Parse one inherit key: a maximal key-char run, then only
3603/// trailing gap content (`gap_nl`: newlines, comments, `#`). Key
3604/// chars exclude `: = ! , | ( ) ] $`, whitespace, and the `//` / `/*`
3605/// comment opens; a joint `#`
3606/// stays literal, a gapped one opens a trailing comment. Groups and
3607/// strings render raw for the exclusion check (they read as
3608/// ordinary characters here). `None` on shape miss.
3609fn render_inherit_key(part: &[Tok], stmt: usize) -> Result<Option<String>, TokenError> {
3610    let mut out = String::new();
3611    let mut i = 0;
3612    // Key run: words, puncts (except comment opens), groups and
3613    // strings rendered raw; ends at any gap, newline, comment, or
3614    // `//` / `/*` open.
3615    while i < part.len() {
3616        let tok = &part[i];
3617        if i > 0 && !tok.joint {
3618            break;
3619        }
3620        match &tok.kind {
3621            TokKind::Word(w) => {
3622                out.push_str(w);
3623                i += 1;
3624            }
3625            TokKind::Punct('/') if is_comment_open(part, i) => break,
3626            // `#` stays literal at key start (`#c`) or joint
3627            // (`a#b`); gapped mid-key it opens a trailing
3628            // comment like the grammar's `gap_nl`.
3629            TokKind::Punct('#') if tok.joint || out.is_empty() => {
3630                // `#` stays literal at key start (`#c`) or joint
3631                // (`a#b`).
3632                out.push('#');
3633                i += 1;
3634            }
3635            // Gapped mid-key `#` opens a trailing comment (handled
3636            // by the trailer check below, like `gap_nl`).
3637            TokKind::Punct('#') => break,
3638            TokKind::Punct(c) => {
3639                out.push(*c);
3640                i += 1;
3641            }
3642            TokKind::Semicolon => {
3643                out.push(';');
3644                i += 1;
3645            }
3646            TokKind::Str { text, quote } => {
3647                out.push(*quote);
3648                out.push_str(text);
3649                out.push(*quote);
3650                i += 1;
3651            }
3652            TokKind::BlockStr(full) => {
3653                out.push_str(full);
3654                i += 1;
3655            }
3656            TokKind::Group {
3657                delim,
3658                inner,
3659                open_joint,
3660                close_joint,
3661            } => {
3662                let (open, close) = match delim {
3663                    GroupDelim::Bracket => ('[', ']'),
3664                    GroupDelim::Paren => ('(', ')'),
3665                    GroupDelim::Brace => ('{', '}'),
3666                };
3667                out.push_str(&render_group(open, close, inner, *open_joint, *close_joint));
3668                i += 1;
3669            }
3670            // Newlines and comment markers end the key; the trailer
3671            // check below admits them.
3672            TokKind::Newline | TokKind::Comment(_) => break,
3673        }
3674    }
3675    if out.is_empty() {
3676        return Ok(None);
3677    }
3678    // Trailer: only gap content (`gap_nl`) may follow the key.
3679    let mut j = i;
3680    while j < part.len() {
3681        let tok = &part[j];
3682        match &tok.kind {
3683            TokKind::Newline | TokKind::Comment(_) => {
3684                j += 1;
3685            }
3686            TokKind::Punct('/') if is_comment_open(part, j) => {
3687                j = skip_inline_comment(part, j).ok_or(TokenError {
3688                    stmt,
3689                    msg: "unclosed block comment".to_string(),
3690                    line: 0,
3691                    col: 0,
3692                    kind: None,
3693                })?;
3694            }
3695            TokKind::Punct('#') => {
3696                // `#` comment runs to a newline or the part end.
3697                while j < part.len() && !matches!(&part[j].kind, TokKind::Newline) {
3698                    j += 1;
3699                }
3700            }
3701            _ => return Ok(None),
3702        }
3703    }
3704    // `guard_key_char` exclusions: the single-char set plus the
3705    // comment opens (`//`, `/*`); lone `/` stays legal.
3706    if out.contains("//") || out.contains("/*") {
3707        return Ok(None);
3708    }
3709    if out.chars().any(|c| {
3710        matches!(
3711            c,
3712            ':' | '=' | '!' | ',' | '|' | '(' | ')' | ']' | VAR_SIGIL_CHAR
3713        )
3714    }) {
3715        return Ok(None);
3716    }
3717    Ok(Some(out))
3718}
3719
3720/// Strict `INHERIT_ENV [...]` at an element or single-inner
3721/// position: bracket riding gapped with valid keys yields the
3722/// directive (trailing elements loop on outside); anything else
3723/// misses (`None`) and generic fails it in lowering.
3724/// Serves both levels so keys stay exact everywhere; slice 5 adds
3725/// only the prelude-order validation.
3726fn parse_inherit_env_at(
3727    toks: &[Tok],
3728    pos: usize,
3729    stmt: usize,
3730) -> Result<Option<(StepKind, usize)>, TokenError> {
3731    // The bracket rides gapped (`sep`); anything else misses and
3732    // generic fails it in lowering.
3733    let bracket = match toks.get(pos + 1) {
3734        Some(t)
3735            if !t.joint
3736                && matches!(
3737                    &t.kind,
3738                    TokKind::Group {
3739                        delim: GroupDelim::Bracket,
3740                        ..
3741                    }
3742                ) =>
3743        {
3744            Some(t)
3745        }
3746        _ => None,
3747    };
3748    let Some(bracket) = bracket else {
3749        return Ok(None);
3750    };
3751    let inner = match &bracket.kind {
3752        TokKind::Group { inner, .. } => inner,
3753        _ => unreachable!(),
3754    };
3755    match parse_inherit_keys(inner, stmt)? {
3756        Some(keys) => Ok(Some((StepKind::InheritEnv { keys }, 2))),
3757        None => Ok(None),
3758    }
3759}
3760
3761/// Parse a brace block body into steps: statements split and lower
3762/// recursively, each keeping its own guard. `mark` selects scope
3763/// marking: top-level guard-block bodies mark (each nesting level
3764/// bumps first/last); wrapper bodies
3765/// (`IF`/`FOR`/`WHILE`/`FUNC`/`REMOTE`/wrappers/io-blocks) never mark
3766/// (block-element lowering pins 0/0).
3767fn parse_body_steps(
3768    inner: &[Tok],
3769    stmt: usize,
3770    ctx: &ParseCtx,
3771    mark: bool,
3772) -> Result<Vec<Step>, TokenError> {
3773    // One function/import scope per braced body (mirroring the
3774    // runtime push/pop boundary): same-block
3775    // `FUNC` redefinition errors, nested shadowing stays allowed.
3776    // Errors abort the whole parse (frames discarded with it), so no
3777    // exit runs on failure.
3778    ctx.funcs.borrow_mut().push(HashSet::new());
3779    ctx.imports.borrow_mut().push(Vec::new());
3780    ctx.forward.borrow_mut().push(HashSet::new());
3781    // Nested splits count lines from the enclosing statement's line
3782    // (headers are single-line, so the brace shares it). Save and
3783    // restore the discipline around the loop: sibling bodies after
3784    // this one must see the enclosing line, not the last inner one.
3785    // (On error the parse aborts and the context is discarded.)
3786    let saved = *ctx.current_line.borrow();
3787    let mut out = Vec::new();
3788    let stmts = split_statements(inner, saved)?;
3789    predeclare_forward_funcs(&stmts, ctx);
3790
3791    for s in &stmts {
3792        // The innermost statement owns error positions: record it for
3793        // nested splits and stamp failures that have none yet (deeper
3794        // frames stamp first, so this never overwrites real positions).
3795        *ctx.current_line.borrow_mut() = s.line;
3796        out.extend(
3797            lower_stmt_steps(s, stmt, ctx, true, mark).map_err(|e| stamp_pos(e, s.line, s.col))?,
3798        );
3799    }
3800    *ctx.current_line.borrow_mut() = saved;
3801    ctx.funcs.borrow_mut().pop();
3802    ctx.imports.borrow_mut().pop();
3803    ctx.forward.borrow_mut().pop();
3804    Ok(out)
3805}
3806
3807/// Single (non-block) `WITH_IO`: bindings plus an optional inner
3808/// command. `None` on shape miss (no/gapped bracket: generic fails
3809/// it in lowering). A brace in single-inner position is
3810/// the grammar's pending-guard error, never an io-block; a bare
3811/// bracket leaks the transient `WithIoBlock` into the body (probed).
3812fn parse_with_io_single(
3813    toks: &[Tok],
3814    pos: usize,
3815    stmt: usize,
3816    ctx: &ParseCtx,
3817) -> Result<Option<(StepKind, usize)>, TokenError> {
3818    let bracket = match toks.get(pos + 1) {
3819        // The bracket rides gapped (`sep`); anything else misses the
3820        // shape and generic fails it in lowering.
3821        Some(t)
3822            if !t.joint
3823                && matches!(
3824                    &t.kind,
3825                    TokKind::Group {
3826                        delim: GroupDelim::Bracket,
3827                        ..
3828                    }
3829                ) =>
3830        {
3831            t
3832        }
3833        _ => return Ok(None),
3834    };
3835    let inner = match &bracket.kind {
3836        TokKind::Group { inner, .. } => inner.clone(),
3837        _ => unreachable!(),
3838    };
3839    let bindings = match parse_io_bindings(&inner, stmt, ctx)? {
3840        Some(bindings) => bindings,
3841        None => return Ok(None),
3842    };
3843    let rest = pos + 2;
3844    // A brace directly after the bracket is the pending-guard error
3845    // in single-inner position (probed); templates fall to generic.
3846    if let Some(next) = toks.get(rest)
3847        && matches!(
3848            &next.kind,
3849            TokKind::Group {
3850                delim: GroupDelim::Brace,
3851                ..
3852            }
3853        )
3854        && !is_template_brace(next)
3855    {
3856        return Err(TokenError {
3857            stmt,
3858            msg: "'{' without a pending guard".to_string(),
3859            line: 0,
3860            col: 0,
3861            kind: None,
3862        });
3863    }
3864    if rest >= toks.len() {
3865        // Bare bracket: the transient block node leaks into wrapper
3866        // bodies (statement level never reaches
3867        // here; the splitter holds it for `{`).
3868        return Ok(Some((StepKind::WithIoBlock { bindings }, 2)));
3869    }
3870    // A joint follower misses the inner `sep`: the bracket stands
3871    // bare (probed `TIMEOUT 10s WITH_IO [..]ECHO hi` yields the
3872    // transient node) and trailing elements loop on outside.
3873    if toks[rest].joint {
3874        return Ok(Some((StepKind::WithIoBlock { bindings }, 2)));
3875    }
3876    let (cmd, used) = parse_single_inner(
3877        toks,
3878        rest,
3879        stmt,
3880        ctx,
3881        InnerRules {
3882            allow_await: false,
3883            allow_with_io: true,
3884        },
3885    )?;
3886    let span = lowering_ctx(stmt);
3887    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| TokenError {
3888        stmt,
3889        msg: e.to_string(),
3890        line: 0,
3891        col: 0,
3892        kind: None,
3893    })?;
3894    let kind = StepKind::WithIo {
3895        bindings,
3896        cmd: Box::new(cmd),
3897    };
3898    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
3899        stmt,
3900        msg: e.to_string(),
3901        line: 0,
3902        col: 0,
3903        kind: None,
3904    })?;
3905    Ok(Some((kind, 2 + used)))
3906}
3907
3908/// Single (non-block) `TIMEOUT`: duration plus one inner command.
3909/// `None` on shape miss (bad duration, missing/joint inner: generic
3910/// fails it in lowering). Blocks parse inline; the body
3911/// holds one step for single inners.
3912fn parse_timeout_single(
3913    toks: &[Tok],
3914    pos: usize,
3915    stmt: usize,
3916    ctx: &ParseCtx,
3917) -> Result<Option<(StepKind, usize)>, TokenError> {
3918    let Some((duration, dused)) = parse_timeout_duration_at(toks, pos + 1, stmt)? else {
3919        return Ok(None);
3920    };
3921    let rest = pos + 1 + dused;
3922    let Some(next) = toks.get(rest) else {
3923        // `TIMEOUT 10s` alone is a generic instruction (lowering
3924        // fails it, probed), never a bare wrapper.
3925        return Ok(None);
3926    };
3927    if next.joint {
3928        return Ok(None);
3929    }
3930    let body = if matches!(
3931        &next.kind,
3932        TokKind::Group {
3933            delim: GroupDelim::Brace,
3934            ..
3935        }
3936    ) && !is_template_brace(next)
3937    {
3938        let inner = match &next.kind {
3939            TokKind::Group { inner, .. } => inner.clone(),
3940            _ => unreachable!(),
3941        };
3942        let steps = parse_body_steps(&inner, stmt, ctx, false)?;
3943        (steps, 1)
3944    } else {
3945        let (cmd, used) = parse_single_inner(
3946            toks,
3947            rest,
3948            stmt,
3949            ctx,
3950            InnerRules {
3951                allow_await: true,
3952                allow_with_io: true,
3953            },
3954        )?;
3955        (
3956            vec![Step {
3957                guard: None,
3958                kind: cmd,
3959                scope_enter: 0,
3960                scope_exit: 0,
3961                line: 0,
3962                col: 0,
3963            }],
3964            used,
3965        )
3966    };
3967    let kind = StepKind::Timeout {
3968        duration,
3969        body: body.0,
3970    };
3971    let span = lowering_ctx(stmt);
3972    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
3973        stmt,
3974        msg: e.to_string(),
3975        line: 0,
3976        col: 0,
3977        kind: None,
3978    })?;
3979    Ok(Some((kind, 1 + dused + body.1)))
3980}
3981
3982/// Single (non-block) `ISOLATED`: one inner command or block; the
3983/// body rewrites nested `INHERIT_ENV` through the shared pass.
3984/// `None` on shape miss (missing/joint inner: generic fails it).
3985fn parse_isolated_single(
3986    toks: &[Tok],
3987    pos: usize,
3988    stmt: usize,
3989    ctx: &ParseCtx,
3990) -> Result<Option<(StepKind, usize)>, TokenError> {
3991    let Some(next) = toks.get(pos + 1) else {
3992        return Ok(None);
3993    };
3994    if next.joint {
3995        return Ok(None);
3996    }
3997    let (mut body, used) = if matches!(
3998        &next.kind,
3999        TokKind::Group {
4000            delim: GroupDelim::Brace,
4001            ..
4002        }
4003    ) && !is_template_brace(next)
4004    {
4005        let inner = match &next.kind {
4006            TokKind::Group { inner, .. } => inner.clone(),
4007            _ => unreachable!(),
4008        };
4009        (parse_body_steps(&inner, stmt, ctx, false)?, 1)
4010    } else {
4011        let (cmd, used) = parse_single_inner(
4012            toks,
4013            pos + 1,
4014            stmt,
4015            ctx,
4016            InnerRules {
4017                allow_await: true,
4018                allow_with_io: true,
4019            },
4020        )?;
4021        (
4022            vec![Step {
4023                guard: None,
4024                kind: cmd,
4025                scope_enter: 0,
4026                scope_exit: 0,
4027                line: 0,
4028                col: 0,
4029            }],
4030            used,
4031        )
4032    };
4033    crate::commands::rewrite_isolated_inherit(&mut body);
4034    Ok(Some((StepKind::Isolated { body }, 1 + used)))
4035}
4036
4037/// `FAIL [<code>] [<message>] [{ <block> }]`: message and/or block
4038/// required, code optional. The trailing brace (when present and not
4039/// a `{{ }}` template) parses as a child-scope body that reads
4040/// caller locals; the remaining tokens lower as 0-2 plain args (no `KEY=VAL`). One arg
4041/// is the message unless it is a bare int literal, which is the
4042/// code (`FAIL 2` exits silently, `FAIL "2"` prints); two args are
4043/// code plus message with the code statically int-checked like
4044/// `EXIT`. `None` on shape miss (joint head, `KEY=VAL`, >2 args fall
4045/// to generic, which fails with the `FAIL` hint).
4046fn parse_fail_single(
4047    toks: &[Tok],
4048    pos: usize,
4049    stmt: usize,
4050    ctx: &ParseCtx,
4051) -> Result<Option<(StepKind, usize)>, TokenError> {
4052    let head_ok =
4053        matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FAIL);
4054    if !head_ok {
4055        return Ok(None);
4056    }
4057    let next_joint = toks.get(pos + 1).is_some_and(|t| t.joint);
4058    if next_joint {
4059        return Ok(None);
4060    }
4061    let end = toks.len();
4062    let mut arg_end = end;
4063    let mut body: Vec<Step> = Vec::new();
4064    // Brace presence is tracked apart from body length: `FAIL {}`
4065    // is a valid empty block, while a missing block leaves no
4066    // braces at all.
4067    let mut has_block = false;
4068    if let Some(last) = toks.last()
4069        && matches!(
4070            &last.kind,
4071            TokKind::Group {
4072                delim: GroupDelim::Brace,
4073                ..
4074            }
4075        )
4076        && !is_template_brace(last)
4077        && end > pos + 1
4078    {
4079        let inner = match &last.kind {
4080            TokKind::Group { inner, .. } => inner.clone(),
4081            _ => unreachable!(),
4082        };
4083        body = parse_body_steps(&inner, stmt, ctx, false)?;
4084        arg_end = end - 1;
4085        has_block = true;
4086    }
4087    let arg_toks = if arg_end > pos + 1 {
4088        &toks[pos + 1..arg_end]
4089    } else {
4090        &[]
4091    };
4092    if !arg_toks.is_empty() && arg_toks.first().is_some_and(|t| t.joint) {
4093        return Ok(None);
4094    }
4095    let (tokens, deferred) = build_arg_tokens(arg_toks, stmt, ctx)?;
4096    let mut args: Vec<Arg> = Vec::with_capacity(tokens.len());
4097    for token in tokens {
4098        match token {
4099            InsToken::Pos(arg) => args.push(arg),
4100            InsToken::Assign(..) => return Ok(None),
4101        }
4102    }
4103    if args.len() > 2 {
4104        return Ok(None);
4105    }
4106    if args.is_empty() && !has_block {
4107        return Ok(None);
4108    }
4109    if let Some(err) = deferred {
4110        return Err(err);
4111    }
4112    let (code, message) = match args.len() {
4113        0 => (None, None),
4114        1 => {
4115            let mut it = args.into_iter();
4116            let only = it.next();
4117            // A lone bare int is a silent code (`FAIL 2`); anything
4118            // else (quoted text, `$var`, templates) is the message.
4119            // Quoting decides: `FAIL "2"` prints `2` and exits 1.
4120            match &only {
4121                Some(Arg::String(s, false))
4122                    if crate::command::strip_digit_separators(s)
4123                        .parse::<i64>()
4124                        .is_ok() =>
4125                {
4126                    (only, None)
4127                }
4128                _ => (None, only),
4129            }
4130        }
4131        _ => {
4132            let mut it = args.into_iter();
4133            let code = it.next();
4134            let message = it.next();
4135            // The code position is statically int-checked like
4136            // `EXIT`: a non-int literal fails here, while `$var`
4137            // and templates defer to runtime resolution.
4138            if let Some(arg) = &code {
4139                crate::command::ArgType::Int
4140                    .check_arg(arg)
4141                    .map_err(|e| TokenError {
4142                        stmt,
4143                        msg: e.to_string(),
4144                        line: 0,
4145                        col: 0,
4146                        kind: Some(ParseErrorKind::Validation {
4147                            command: KEYWORD_FAIL.to_string(),
4148                        }),
4149                    })?;
4150            }
4151            (code, message)
4152        }
4153    };
4154    crate::commands::rewrite_isolated_inherit(&mut body);
4155    let kind = StepKind::Fail {
4156        code,
4157        message,
4158        body,
4159    };
4160    let span = lowering_ctx(stmt);
4161    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
4162        stmt,
4163        msg: e.to_string(),
4164        line: 0,
4165        col: 0,
4166        kind: None,
4167    })?;
4168    Ok(Some((kind, end - pos)))
4169}
4170
4171/// Single (non-block) `ASYNC`: one inner command or block (blocks
4172/// admit a joint brace, like `async_statement_block`'s `sep?`).
4173/// Top-level `WITH_IO` steps fail through the shared reject; the
4174/// `LET` path never scans (probed: it accepts). `None` on shape
4175/// miss (missing/joint-single inner: generic fails it).
4176fn parse_async_single(
4177    toks: &[Tok],
4178    pos: usize,
4179    stmt: usize,
4180    ctx: &ParseCtx,
4181) -> Result<Option<(StepKind, usize)>, TokenError> {
4182    let Some(next) = toks.get(pos + 1) else {
4183        return Ok(None);
4184    };
4185    // Block form admits a joint brace (`ASYNC{...}`, probed); the
4186    // single form needs its `sep`.
4187    if matches!(
4188        &next.kind,
4189        TokKind::Group {
4190            delim: GroupDelim::Brace,
4191            ..
4192        }
4193    ) && !is_template_brace(next)
4194    {
4195        let inner = match &next.kind {
4196            TokKind::Group { inner, .. } => inner.clone(),
4197            _ => unreachable!(),
4198        };
4199        let body = parse_body_steps(&inner, stmt, ctx, false)?;
4200        let span = lowering_ctx(stmt);
4201        crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| TokenError {
4202            stmt,
4203            msg: e.to_string(),
4204            line: 0,
4205            col: 0,
4206            kind: None,
4207        })?;
4208        let kind = StepKind::AsyncBlock { body };
4209        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
4210            stmt,
4211            msg: e.to_string(),
4212            line: 0,
4213            col: 0,
4214            kind: None,
4215        })?;
4216        return Ok(Some((kind, 2)));
4217    }
4218    if next.joint {
4219        return Ok(None);
4220    }
4221    let (cmd, used) = parse_single_inner(
4222        toks,
4223        pos + 1,
4224        stmt,
4225        ctx,
4226        InnerRules {
4227            allow_await: false,
4228            allow_with_io: false,
4229        },
4230    )?;
4231    let body = vec![Step {
4232        guard: None,
4233        kind: cmd,
4234        scope_enter: 0,
4235        scope_exit: 0,
4236        line: 0,
4237        col: 0,
4238    }];
4239    let span = lowering_ctx(stmt);
4240    crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| TokenError {
4241        stmt,
4242        msg: e.to_string(),
4243        line: 0,
4244        col: 0,
4245        kind: None,
4246    })?;
4247    let kind = StepKind::AsyncBlock { body };
4248    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
4249        stmt,
4250        msg: e.to_string(),
4251        line: 0,
4252        col: 0,
4253        kind: None,
4254    })?;
4255    Ok(Some((kind, 1 + used)))
4256}
4257
4258// ---- Block statements, directives, REMOTE ----
4259// `IF`/`FOR`/`WHILE`/`FUNC` parse their headers token-natively with
4260// miss-to-generic fallback (the grammar's committed `instruction`
4261// path); bodies lower recursively with pushed scopes. `TYPE` builds
4262// aliases through a maximal type-shape match; `IMPORT`/`EXPORT` are
4263// zero-step frame/table directives; `REMOTE` validates targets,
4264// bindings, bodies, and outer-call containment through the shared
4265// validators. Guard blocks fold guards with scope markers at top
4266// level and mirror the nested quirk formula in bodies. A whole-script
4267// post-pass runs the shared validations (prelude order, COPY
4268// placement, EXPORT membership).
4269
4270/// Uppercase identifier mirror (`func_ident`, `type_name`,
4271/// `import_module`): ASCII upper start, upper/digit/`_` rest.
4272fn is_upper_ident(w: &str) -> bool {
4273    !w.is_empty()
4274        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
4275        && w.chars()
4276            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
4277}
4278
4279/// Lowercase identifier mirror (`field_name`): ASCII lower start,
4280/// lower/digit/`_` rest.
4281fn is_lower_ident(w: &str) -> bool {
4282    !w.is_empty()
4283        && w.chars().next().is_some_and(|c| c.is_ascii_lowercase())
4284        && w.chars()
4285            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
4286}
4287
4288/// `$name` with gapless adjacency (atomic `dollar_ident`); `None` on
4289/// shape miss (the caller falls back to generic, which fails in
4290/// lowering like the grammar's committed `instruction`).
4291fn peek_dollar_var(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
4292    match (toks.get(pos), toks.get(pos + 1)) {
4293        (Some(dollar), Some(name))
4294            if matches!(&dollar.kind, TokKind::Punct(VAR_SIGIL_CHAR))
4295                && name.joint
4296                && matches!(&name.kind, TokKind::Word(w) if is_ident_word(w)) =>
4297        {
4298            match &name.kind {
4299                TokKind::Word(w) => Some((w.clone(), 2)),
4300                _ => unreachable!(),
4301            }
4302        }
4303        _ => None,
4304    }
4305}
4306
4307/// Skip statement-level newlines (multi-line `<...>` shapes ride
4308/// them into the body) before the next type token. Narrower than
4309/// `gap_nl` on purpose: comments keep failing here exactly like
4310/// single-line shapes, so only the separator moves.
4311fn skip_type_nl(toks: &[Tok], mut p: usize) -> usize {
4312    while matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Newline)) {
4313        p += 1;
4314    }
4315    p
4316}
4317
4318/// Maximal `type_tag` match over toks (non-atomic: gaps free
4319/// everywhere): atoms with `<>` args, `|` unions, `name?:` fields,
4320/// and one `= literal` default tail per field.
4321/// Returns the exclusive end index, or `None` on shape miss.
4322fn parse_type_shape(toks: &[Tok], pos: usize) -> Option<usize> {
4323    let mut p = parse_type_atom(toks, skip_type_nl(toks, pos))?;
4324    loop {
4325        let q = skip_type_nl(toks, p);
4326        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('|'))) {
4327            return Some(p);
4328        }
4329        p = parse_type_atom(toks, skip_type_nl(toks, q + 1))?;
4330    }
4331}
4332
4333fn parse_type_atom(toks: &[Tok], pos: usize) -> Option<usize> {
4334    let pos = skip_type_nl(toks, pos);
4335    match toks.get(pos).map(|t| &t.kind) {
4336        Some(TokKind::Word(w)) if is_upper_ident(w) => {}
4337        _ => return None,
4338    }
4339    let mut p = skip_type_nl(toks, pos + 1);
4340    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('<'))) {
4341        p = parse_type_args(toks, skip_type_nl(toks, p + 1))?;
4342        p = skip_type_nl(toks, p);
4343        if !matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('>'))) {
4344            return None;
4345        }
4346        p += 1;
4347    }
4348    Some(p)
4349}
4350
4351fn parse_type_args(toks: &[Tok], pos: usize) -> Option<usize> {
4352    let mut p = parse_type_field(toks, skip_type_nl(toks, pos))?;
4353    loop {
4354        let q = skip_type_nl(toks, p);
4355        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(','))) {
4356            return Some(p);
4357        }
4358        p = parse_type_field(toks, skip_type_nl(toks, q + 1))?;
4359    }
4360}
4361
4362fn parse_type_field(toks: &[Tok], pos: usize) -> Option<usize> {
4363    let mut p = skip_type_nl(toks, pos);
4364    // Optional `name?:` prefix (lowercase names only, like the
4365    // grammar's `field_name`).
4366    if let Some(TokKind::Word(w)) = toks.get(p).map(|t| &t.kind)
4367        && is_lower_ident(w)
4368    {
4369        let mut q = skip_type_nl(toks, p + 1);
4370        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('?'))) {
4371            q = skip_type_nl(toks, q + 1);
4372        }
4373        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4374            p = skip_type_nl(toks, q + 1);
4375        }
4376    }
4377    let mut p = parse_type_shape(toks, p)?;
4378    // Optional `ALIAS name` clause (#310.5): one alternate CLI spelling
4379    // for `TYPE FLAGS` fields. Skipped as a unit here so the shape
4380    // matcher covers it; the spelling parser owns validation, and the
4381    // renderer carries the raw tokens through. Order is fixed:
4382    // `TYPE [ALIAS alias] [= default]`. The alias word itself rides
4383    // along regardless of case so a miscapitalized alias still reaches
4384    // the spelling diagnostic instead of missing to unknown-command.
4385    let q = skip_type_nl(toks, p);
4386    if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Word(w)) if w == crate::tag::ALIAS_KEYWORD)
4387    {
4388        p = skip_type_nl(toks, q + 1);
4389        if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Word(_))) {
4390            p = skip_type_nl(toks, p + 1);
4391        }
4392    }
4393    // Optional `= ...` default tail: consume to the next field
4394    // delimiter (`,`, `>`, `|` at angle depth zero), tracking `<>`
4395    // so nested shapes ride along. Any spacing, any tokens:
4396    // literals, `$vars`, `env:` reads, calls. The spelling parser
4397    // owns literal validation, so non-literals fail there naming
4398    // the alias instead of missing here as unknown-command noise.
4399    let q = skip_type_nl(toks, p);
4400    if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('=')))
4401        && !matches!(toks.get(q + 1).map(|t| &t.kind), Some(TokKind::Punct('=')))
4402    {
4403        let mut r = skip_type_nl(toks, q + 1);
4404        let mut depth = 0usize;
4405        loop {
4406            match toks.get(r).map(|t| &t.kind) {
4407                Some(TokKind::Punct('<')) => {
4408                    depth += 1;
4409                    r = skip_type_nl(toks, r + 1);
4410                }
4411                Some(TokKind::Punct('>')) => {
4412                    if depth == 0 {
4413                        break;
4414                    }
4415                    depth -= 1;
4416                    r = skip_type_nl(toks, r + 1);
4417                }
4418                Some(TokKind::Punct(',' | '|')) if depth == 0 => break,
4419                Some(_) => {
4420                    r += 1;
4421                }
4422                None => break,
4423            }
4424        }
4425        p = r;
4426    }
4427    Some(p)
4428}
4429
4430/// Single (non-block) `IF`: condition plus then-block with an
4431/// opportunistic `ELSE` chain (a malformed `ELSE` stays for the
4432/// element loop, which fails it in lowering exactly like the
4433/// grammar). `None` on shape miss (missing/joint-agnostic block or
4434/// unclassified bad condition: generic fails it); classified
4435/// expression failures (unknown/ambiguous callees) and inline-block
4436/// failures propagate (blocks lower here, so their errors surface
4437/// directly).
4438fn parse_if_at(
4439    toks: &[Tok],
4440    pos: usize,
4441    stmt: usize,
4442    ctx: &ParseCtx,
4443) -> Result<Option<(StepKind, usize)>, TokenError> {
4444    // Condition entry skips leading gap comments (`IF` uses `gap`).
4445    let mut lead = Cursor::expr(&toks[pos + 1..], stmt);
4446    lead.skip_gap();
4447    let mut cur = Cursor::expr(&toks[pos + 1 + lead.pos..], stmt);
4448    let cond = match parse_expr_checked(&mut cur, ctx) {
4449        Ok(expr) => expr,
4450        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4451        // Classified failures (unknown/ambiguous callees) name the
4452        // culprit instead of missing to the generic IF hint: the head
4453        // is unambiguously `IF`, so there is no alternative parse.
4454        Err(e) if e.kind.is_some() => return Err(e),
4455        Err(_) => return Ok(None),
4456    };
4457    let cond_end = pos + 1 + lead.pos + cur.pos;
4458    // Then-block: any gap (`gap` zero-width), never a template.
4459    let then_brace = match toks.get(cond_end) {
4460        Some(t)
4461            if matches!(
4462                &t.kind,
4463                TokKind::Group {
4464                    delim: GroupDelim::Brace,
4465                    ..
4466                }
4467            ) && !is_template_brace(t) =>
4468        {
4469            t
4470        }
4471        _ => return Ok(None),
4472    };
4473    let then_inner = match &then_brace.kind {
4474        TokKind::Group { inner, .. } => inner.clone(),
4475        _ => unreachable!(),
4476    };
4477    let then_body = parse_body_steps(&then_inner, stmt, ctx, false)?;
4478    let mut p = cond_end + 1;
4479    // Gap comments between the blocks and `ELSE` vanish (merge
4480    // junctions contribute newlines, crossed like `blank*`).
4481    {
4482        let mut gcur = Cursor::expr(&toks[p..], stmt);
4483        gcur.skip_gap_nl();
4484        p += gcur.pos;
4485    }
4486    let mut else_ifs = Vec::new();
4487    let mut else_body = None;
4488    loop {
4489        // `ELSE IF cond block`: any gaps (non-atomic chain).
4490        let is_else_if = matches!(
4491            toks.get(p).map(|t| &t.kind),
4492            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4493        ) && matches!(
4494            toks.get(p + 1).map(|t| &t.kind),
4495            Some(TokKind::Word(w)) if w == KEYWORD_IF
4496        );
4497        if is_else_if {
4498            let mut ecur = Cursor::expr(&toks[p + 2..], stmt);
4499            ecur.skip_gap();
4500            let econd = match parse_expr_checked(&mut ecur, ctx) {
4501                Ok(expr) => expr,
4502                Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4503                // Same classified-error rule as the `IF` head above:
4504                // an `ELSE IF` with a resolvable-but-unknown callee
4505                // names it instead of silently dropping the branch.
4506                Err(e) if e.kind.is_some() => return Err(e),
4507                Err(_) => break,
4508            };
4509            let ebrace = p + 2 + ecur.pos;
4510            let eblock_ok = matches!(
4511                toks.get(ebrace).map(|t| &t.kind),
4512                Some(TokKind::Group {
4513                    delim: GroupDelim::Brace,
4514                    ..
4515                })
4516            ) && toks.get(ebrace).is_some_and(|t| !is_template_brace(t));
4517            if !eblock_ok {
4518                break;
4519            }
4520            let einner = match &toks[ebrace].kind {
4521                TokKind::Group { inner, .. } => inner.clone(),
4522                _ => unreachable!(),
4523            };
4524            let ebody = parse_body_steps(&einner, stmt, ctx, false)?;
4525            else_ifs.push((Box::new(econd), ebody));
4526            p = ebrace + 1;
4527            // Gap comments before a further `ELSE` vanish too
4528            // (merge junctions contribute newlines).
4529            {
4530                let mut gcur = Cursor::expr(&toks[p..], stmt);
4531                gcur.skip_gap_nl();
4532                p += gcur.pos;
4533            }
4534            continue;
4535        }
4536        // `ELSE block`: same opportunism (a bare `ELSE` stays for
4537        // the loop, failing in lowering like the grammar).
4538        let is_else = matches!(
4539            toks.get(p).map(|t| &t.kind),
4540            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4541        ) && matches!(
4542            toks.get(p + 1).map(|t| &t.kind),
4543            Some(TokKind::Group {
4544                delim: GroupDelim::Brace,
4545                ..
4546            })
4547        ) && toks.get(p + 1).is_some_and(|t| !is_template_brace(t));
4548        if !is_else {
4549            break;
4550        }
4551        let einner = match &toks[p + 1].kind {
4552            TokKind::Group { inner, .. } => inner.clone(),
4553            _ => unreachable!(),
4554        };
4555        else_body = Some(parse_body_steps(&einner, stmt, ctx, false)?);
4556        p += 2;
4557        break;
4558    }
4559    let kind = StepKind::If {
4560        cond: Box::new(cond),
4561        then_body,
4562        else_ifs,
4563        else_body,
4564    };
4565    Ok(Some((kind, p - pos)))
4566}
4567
4568/// Parse one `CASE` value list: comma-separated expressions up to (not
4569/// including) the arm body brace. Groups are atomic tokens, so commas
4570/// inside calls, lists, and maps never split. Returns the values plus
4571/// the token count consumed past the `CASE` word.
4572fn parse_case_values(
4573    toks: &[Tok],
4574    stmt: usize,
4575    ctx: &ParseCtx,
4576) -> Result<(Vec<Expr>, usize), TokenError> {
4577    let mut values = Vec::new();
4578    let mut p = 0;
4579    loop {
4580        let mut gcur = Cursor::expr(&toks[p..], stmt);
4581        gcur.skip_gap_nl();
4582        let start = p + gcur.pos;
4583        let mut vcur = Cursor::expr(&toks[start..], stmt);
4584        let value = match parse_expr_checked(&mut vcur, ctx) {
4585            Ok(expr) => expr,
4586            Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4587            Err(e) => return Err(e),
4588        };
4589        // A `{ ... }` block is never a case value: without this, a
4590        // missing `CASE` value consumes the arm body as a block
4591        // expression and fails downstream instead of naming the miss.
4592        if matches!(value, Expr::Block(_)) {
4593            return Err(TokenError {
4594                stmt,
4595                line: 0,
4596                col: 0,
4597                msg: "SWITCH CASE requires a value or condition before '{'".to_string(),
4598                kind: None,
4599            });
4600        }
4601        values.push(value);
4602        p = start + vcur.pos;
4603        let mut gcur = Cursor::expr(&toks[p..], stmt);
4604        gcur.skip_gap_nl();
4605        p += gcur.pos;
4606        if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(','))) {
4607            p += 1;
4608            continue;
4609        }
4610        break;
4611    }
4612    Ok((values, p))
4613}
4614
4615/// Parsed `SWITCH` arms: one value list plus body per `CASE`, with
4616/// an optional trailing `DEFAULT` body.
4617type SwitchArms = (Vec<(Vec<Expr>, Vec<Step>)>, Option<Vec<Step>>);
4618
4619/// Parse the arms inside a `SWITCH` body brace: `CASE <values> { ... }`
4620/// arms plus an optional trailing `DEFAULT { ... }`. Hard errors once
4621/// committed (the `SWITCH` head is unambiguous): unknown words, empty
4622/// bodies, missing blocks, duplicate or non-trailing `DEFAULT`.
4623fn parse_switch_body(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<SwitchArms, TokenError> {
4624    let err = |msg: String| TokenError {
4625        stmt,
4626        line: 0,
4627        col: 0,
4628        msg,
4629        kind: None,
4630    };
4631    let mut cases: Vec<(Vec<Expr>, Vec<Step>)> = Vec::new();
4632    let mut default_body: Option<Vec<Step>> = None;
4633    let mut p = 0;
4634    loop {
4635        let mut gcur = Cursor::expr(&inner[p..], stmt);
4636        gcur.skip_gap_nl();
4637        p += gcur.pos;
4638        if p >= inner.len() {
4639            break;
4640        }
4641        let word = match &inner[p].kind {
4642            TokKind::Word(w) => w.clone(),
4643            _ => {
4644                return Err(err(
4645                    "SWITCH body must hold CASE or DEFAULT arms, e.g. `SWITCH $cmd { CASE \"a\" { ECHO yes } DEFAULT { ECHO no } }`".to_string(),
4646                ));
4647            }
4648        };
4649        if word == KEYWORD_CASE {
4650            if default_body.is_some() {
4651                return Err(err(
4652                    "SWITCH DEFAULT must be the last arm; no CASE may follow it".to_string(),
4653                ));
4654            }
4655            let (values, used) = parse_case_values(&inner[p + 1..], stmt, ctx)?;
4656            p += 1 + used;
4657            let mut bcur = Cursor::expr(&inner[p..], stmt);
4658            bcur.skip_gap_nl();
4659            p += bcur.pos;
4660            let arm_ok = matches!(
4661                inner.get(p).map(|t| &t.kind),
4662                Some(TokKind::Group {
4663                    delim: GroupDelim::Brace,
4664                    ..
4665                })
4666            ) && inner.get(p).is_some_and(|t| !is_template_brace(t));
4667            if !arm_ok {
4668                return Err(err(
4669                    "SWITCH CASE needs a braced block, e.g. `CASE \"a\", \"b\" { ECHO yes }`"
4670                        .to_string(),
4671                ));
4672            }
4673            let arm_inner = match &inner[p].kind {
4674                TokKind::Group { inner, .. } => inner.clone(),
4675                _ => unreachable!(),
4676            };
4677            let body = parse_body_steps(&arm_inner, stmt, ctx, false)?;
4678            cases.push((values, body));
4679            p += 1;
4680        } else if word == KEYWORD_DEFAULT {
4681            if default_body.is_some() {
4682                return Err(err("SWITCH allows only one DEFAULT arm".to_string()));
4683            }
4684            p += 1;
4685            let mut bcur = Cursor::expr(&inner[p..], stmt);
4686            bcur.skip_gap_nl();
4687            p += bcur.pos;
4688            let arm_ok = matches!(
4689                inner.get(p).map(|t| &t.kind),
4690                Some(TokKind::Group {
4691                    delim: GroupDelim::Brace,
4692                    ..
4693                })
4694            ) && inner.get(p).is_some_and(|t| !is_template_brace(t));
4695            if !arm_ok {
4696                return Err(err(
4697                    "SWITCH DEFAULT needs a braced block, e.g. `DEFAULT { ECHO fallback }`"
4698                        .to_string(),
4699                ));
4700            }
4701            let arm_inner = match &inner[p].kind {
4702                TokKind::Group { inner, .. } => inner.clone(),
4703                _ => unreachable!(),
4704            };
4705            default_body = Some(parse_body_steps(&arm_inner, stmt, ctx, false)?);
4706            p += 1;
4707        } else {
4708            return Err(err(
4709                "SWITCH body must hold CASE or DEFAULT arms, e.g. `SWITCH $cmd { CASE \"a\" { ECHO yes } DEFAULT { ECHO no } }`".to_string(),
4710            ));
4711        }
4712    }
4713    if cases.is_empty() && default_body.is_none() {
4714        return Err(err(
4715            "SWITCH needs at least one CASE or DEFAULT arm".to_string()
4716        ));
4717    }
4718    Ok((cases, default_body))
4719}
4720
4721/// `SWITCH [disc] { CASE v, ... { ... } ... [DEFAULT { ... }] }` or
4722/// bare `SWITCH { CASE <bool> { ... } ... }`. `None` on shape miss (no
4723/// outer brace: falls to generic, which fails it with the SWITCH hint);
4724/// classified expression failures propagate like `IF`, and arm errors
4725/// are hard (the head commits the shape).
4726fn parse_switch_at(
4727    toks: &[Tok],
4728    pos: usize,
4729    stmt: usize,
4730    ctx: &ParseCtx,
4731) -> Result<Option<(StepKind, usize)>, TokenError> {
4732    // Bare head: gaps skipped like the discriminant entry below; the
4733    // token then opens the body brace, so no discriminant is parsed
4734    // (every `CASE` carries its own condition).
4735    let mut gap = Cursor::expr(&toks[pos + 1..], stmt);
4736    gap.skip_gap();
4737    let brace_pos = pos + 1 + gap.pos;
4738    let bare_head = matches!(
4739        toks.get(brace_pos).map(|t| &t.kind),
4740        Some(TokKind::Group {
4741            delim: GroupDelim::Brace,
4742            ..
4743        })
4744    ) && toks.get(brace_pos).is_some_and(|t| !is_template_brace(t));
4745    let p: usize;
4746    let discriminant = if bare_head {
4747        p = brace_pos;
4748        None
4749    } else {
4750        // Discriminant entry reuses the skipped gaps above (`IF` uses
4751        // the same gap rule).
4752        let mut cur = Cursor::expr(&toks[brace_pos..], stmt);
4753        let disc = match parse_expr_checked(&mut cur, ctx) {
4754            Ok(expr) => expr,
4755            Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4756            // Same classified-error rule as the `IF` head above: the
4757            // head is unambiguous, so resolvable-but-unknown callees
4758            // name the culprit instead of the generic hint.
4759            Err(e) if e.kind.is_some() => return Err(e),
4760            Err(_) => return Ok(None),
4761        };
4762        p = brace_pos + cur.pos;
4763        Some(Box::new(disc))
4764    };
4765    let body_ok = matches!(
4766        toks.get(p).map(|t| &t.kind),
4767        Some(TokKind::Group {
4768            delim: GroupDelim::Brace,
4769            ..
4770        })
4771    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4772    if !body_ok {
4773        return Ok(None);
4774    }
4775    let inner = match &toks[p].kind {
4776        TokKind::Group { inner, .. } => inner.clone(),
4777        _ => unreachable!(),
4778    };
4779    let (cases, default_body) = parse_switch_body(&inner, stmt, ctx)?;
4780    let kind = StepKind::Switch {
4781        discriminant,
4782        cases,
4783        default_body,
4784    };
4785    Ok(Some((kind, p + 1 - pos)))
4786}
4787
4788/// Single (non-block) `FOR`: `$var[: TYPE] (, $var[: TYPE])? IN
4789/// expr` plus block. Header shapes miss to generic (a third variable,
4790/// a missing block, a bad name all fail in lowering like the
4791/// grammar); completed headers validate counts and key types loudly.
4792/// Expression failures from inline blocks propagate (blocks lower
4793/// here); other expression failures miss (generic fails them like a
4794/// committed `instruction` would).
4795fn parse_for_at(
4796    toks: &[Tok],
4797    pos: usize,
4798    stmt: usize,
4799    ctx: &ParseCtx,
4800) -> Result<Option<(StepKind, usize)>, TokenError> {
4801    let mut p = pos + 1;
4802    let mut idents = Vec::new();
4803    let mut types = Vec::new();
4804    // First `$var[: TYPE]` (gapless `$var`; gaps free elsewhere).
4805    let Some((var1, _)) = peek_dollar_var(toks, p) else {
4806        return Ok(None);
4807    };
4808    idents.push(var1);
4809    p += 2;
4810    let mut cur = Cursor::expr(&toks[p..], stmt);
4811    cur.skip_gap();
4812    p += cur.pos;
4813    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4814        p += 1;
4815        let mut tcur = Cursor::expr(&toks[p..], stmt);
4816        tcur.skip_gap();
4817        let tstart = p + tcur.pos;
4818        let Some(tend) = parse_type_shape(toks, tstart) else {
4819            return Ok(None);
4820        };
4821        // `render_type_region` canonicalizes (shared spelling).
4822        types.push(render_type_region(&toks[tstart..tend], stmt)?);
4823        p = tend;
4824    }
4825    // Optional `, $var2[: TYPE2]`.
4826    {
4827        let mut ccur = Cursor::expr(&toks[p..], stmt);
4828        ccur.skip_gap();
4829        if matches!(
4830            ccur.toks.get(ccur.pos).map(|t| &t.kind),
4831            Some(TokKind::Punct(','))
4832        ) {
4833            ccur.pos += 1;
4834            ccur.skip_gap();
4835            let base = p + ccur.pos;
4836            let Some((var2, _)) = peek_dollar_var(toks, base) else {
4837                return Ok(None);
4838            };
4839            idents.push(var2);
4840            let mut q = base + 2;
4841            let mut qcur = Cursor::expr(&toks[q..], stmt);
4842            qcur.skip_gap();
4843            q += qcur.pos;
4844            if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4845                q += 1;
4846                let mut tcur = Cursor::expr(&toks[q..], stmt);
4847                tcur.skip_gap();
4848                let tstart = q + tcur.pos;
4849                let Some(tend) = parse_type_shape(toks, tstart) else {
4850                    return Ok(None);
4851                };
4852                types.push(render_type_region(&toks[tstart..tend], stmt)?);
4853                q = tend;
4854            }
4855            p = q;
4856        }
4857    }
4858    // `IN expr block`.
4859    {
4860        let mut icur = Cursor::expr(&toks[p..], stmt);
4861        icur.skip_gap();
4862        if !matches!(
4863            icur.toks.get(icur.pos).map(|t| &t.kind),
4864            Some(TokKind::Word(w)) if w == KEYWORD_IN
4865        ) {
4866            return Ok(None);
4867        }
4868        icur.pos += 1;
4869        p += icur.pos;
4870    }
4871    let mut ecur = Cursor::expr(&toks[p..], stmt);
4872    ecur.skip_gap();
4873    let in_expr = match parse_expr_checked(&mut ecur, ctx) {
4874        Ok(expr) => expr,
4875        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4876        // Classified failures name the callee: `FOR ... IN` is
4877        // committed once the header matched this far.
4878        Err(e) if e.kind.is_some() => return Err(e),
4879        Err(_) => return Ok(None),
4880    };
4881    p += ecur.pos;
4882    let block_ok = matches!(
4883        toks.get(p).map(|t| &t.kind),
4884        Some(TokKind::Group {
4885            delim: GroupDelim::Brace,
4886            ..
4887        })
4888    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4889    if !block_ok {
4890        return Ok(None);
4891    }
4892    let inner = match &toks[p].kind {
4893        TokKind::Group { inner, .. } => inner.clone(),
4894        _ => unreachable!(),
4895    };
4896    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4897    p += 1;
4898    if idents.len() != types.len() {
4899        return Err(TokenError {
4900            stmt,
4901            msg: format!(
4902                "FOR requires explicit types: FOR $item: TYPE IN <expr> (got {} vars, {} types)",
4903                idents.len(),
4904                types.len()
4905            ),
4906            line: 0,
4907            col: 0,
4908            kind: Some(ParseErrorKind::Validation {
4909                command: KEYWORD_FOR.to_string(),
4910            }),
4911        });
4912    }
4913    let (key_var, key_type, var, var_type) = match idents.len() {
4914        1 => (
4915            None,
4916            None,
4917            idents.into_iter().next().unwrap_or_default(),
4918            types.into_iter().next().unwrap_or_default(),
4919        ),
4920        2 => {
4921            let mut iv = idents.into_iter();
4922            let mut tv = types.into_iter();
4923            (
4924                Some(iv.next().unwrap_or_default()),
4925                Some(tv.next().unwrap_or_default()),
4926                iv.next().unwrap_or_default(),
4927                tv.next().unwrap_or_default(),
4928            )
4929        }
4930        _ => {
4931            return Err(TokenError {
4932                stmt,
4933                msg: "FOR requires one or two variables".to_string(),
4934                line: 0,
4935                col: 0,
4936                kind: Some(ParseErrorKind::Validation {
4937                    command: KEYWORD_FOR.to_string(),
4938                }),
4939            });
4940        }
4941    };
4942    if let Some(kt) = &key_type
4943        && kt != crate::TypeTag::String.name()
4944        && kt != crate::TypeTag::Int.name()
4945    {
4946        return Err(TokenError {
4947            stmt,
4948            msg: format!("FOR key variable must be INT or STRING, got {kt}"),
4949            line: 0,
4950            col: 0,
4951            kind: Some(ParseErrorKind::Validation {
4952                command: KEYWORD_FOR.to_string(),
4953            }),
4954        });
4955    }
4956    let kind = StepKind::For {
4957        key_var,
4958        key_type,
4959        var,
4960        var_type,
4961        in_expr,
4962        body,
4963    };
4964    Ok(Some((kind, p - pos)))
4965}
4966
4967/// Single (non-block) `WHILE`: condition plus block. `None` on
4968/// shape miss (missing block: generic fails it); classified
4969/// expression failures and inline-block failures propagate, other
4970/// expression failures miss (generic fails them like a committed
4971/// `instruction` would).
4972/// No leading gap-skip: `WHILE` takes `sep`, so a joint follower
4973/// never reaches here with a valid shape... (misses fall through
4974/// the same way regardless).
4975fn parse_while_single(
4976    toks: &[Tok],
4977    pos: usize,
4978    stmt: usize,
4979    ctx: &ParseCtx,
4980) -> Result<Option<(StepKind, usize)>, TokenError> {
4981    let mut cur = Cursor::expr(&toks[pos + 1..], stmt);
4982    let cond = match parse_expr_checked(&mut cur, ctx) {
4983        Ok(expr) => expr,
4984        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4985        // Same rule as `IF`: the head is unambiguous, so classified
4986        // failures name the culprit instead of the generic hint.
4987        Err(e) if e.kind.is_some() => return Err(e),
4988        Err(_) => return Ok(None),
4989    };
4990    let brace = pos + 1 + cur.pos;
4991    let block_ok = matches!(
4992        toks.get(brace).map(|t| &t.kind),
4993        Some(TokKind::Group {
4994            delim: GroupDelim::Brace,
4995            ..
4996        })
4997    ) && toks.get(brace).is_some_and(|t| !is_template_brace(t));
4998    if !block_ok {
4999        return Ok(None);
5000    }
5001    let inner = match &toks[brace].kind {
5002        TokKind::Group { inner, .. } => inner.clone(),
5003        _ => unreachable!(),
5004    };
5005    let body = parse_body_steps(&inner, stmt, ctx, false)?;
5006    let kind = StepKind::While {
5007        cond: Box::new(cond),
5008        body,
5009    };
5010    Ok(Some((kind, brace + 1 - pos)))
5011}
5012
5013/// Validated `FUNC` header shape: name, parameter list, return type,
5014/// and body block. Single owner for the header grammar, shared by
5015/// `parse_func_at` and `predeclare_forward_funcs` so the hoist set can
5016/// never admit what the real path rejects (or reject what it admits).
5017/// Returns the header plus tokens consumed; `None` on shape miss
5018/// (lowercase names, missing paren/colon/block all miss to generic,
5019/// probed). Content failures (bad params, missing return type, bad
5020/// trailing tokens) carry the bare diagnostic: `parse_func_at`
5021/// adorns it, pre-declaration drops it (silent skip, letting the main
5022/// pass own the error).
5023struct FuncHeader {
5024    name: String,
5025    params: Vec<(String, String, bool)>,
5026    return_type: String,
5027    block: usize,
5028}
5029
5030#[allow(clippy::too_many_lines)]
5031fn parse_func_header(
5032    toks: &[Tok],
5033    pos: usize,
5034    stmt: usize,
5035    keyword: &str,
5036) -> Result<Option<(FuncHeader, usize)>, String> {
5037    // Head word: `FUNC` (callers normalize `ASYNC FUNC` to `pos`
5038    // first, so the header shape stays prefix-free).
5039    if !matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC) {
5040        return Ok(None);
5041    }
5042    // Name: UPPERCASE ident (lowercase misses to generic, probed).
5043    let def_name = match toks.get(pos + 1).map(|t| &t.kind) {
5044        Some(TokKind::Word(w))
5045            if crate::resolve::check_func_ident(&lowering_ctx(stmt), w).is_ok() =>
5046        {
5047            w.clone()
5048        }
5049        _ => return Ok(None),
5050    };
5051    // Paren group at any gap (`gap` zero-width): params live inside
5052    // its inner tokens, parsed with `gap_nl` discipline (newlines ride
5053    // free like call args and generics, via the shared helper).
5054    let mut p = pos + 2;
5055    let paren_inner = match toks.get(p).map(|t| &t.kind) {
5056        Some(TokKind::Group {
5057            delim: GroupDelim::Paren,
5058            inner,
5059            ..
5060        }) => inner.clone(),
5061        _ => return Ok(None),
5062    };
5063    p += 1;
5064    let mut params = Vec::new();
5065    let mut seen_optional = false;
5066    {
5067        let mut pcur = Cursor::expr(&paren_inner, stmt);
5068        pcur.skip_gap_nl();
5069        if !pcur.done() {
5070            loop {
5071                let base = pcur.pos;
5072                let Some((pname, _)) = peek_dollar_var(&paren_inner, base) else {
5073                    return Err(format!(
5074                        "FUNC {def_name} params must be `$name: TYPE` separated by commas"
5075                    ));
5076                };
5077                pcur.pos = base + 2;
5078                pcur.skip_gap_nl();
5079                // Optional params carry `?` before the colon
5080                // (`$flag?: BOOL`); all params are otherwise required.
5081                let optional = pcur.eat_punct('?');
5082                pcur.skip_gap_nl();
5083                if !pcur.eat_punct(':') {
5084                    return Err(format!(
5085                        "FUNC {def_name} param `${pname}` needs `: TYPE` after the name"
5086                    ));
5087                }
5088                pcur.skip_gap_nl();
5089                let tstart = pcur.pos;
5090                let Some(tend) = parse_type_shape(&paren_inner, tstart) else {
5091                    let got = match paren_inner.get(tstart).map(|tok| &tok.kind) {
5092                        Some(TokKind::Word(word)) => format!("; got `{word}`"),
5093                        _ => String::new(),
5094                    };
5095                    return Err(format!(
5096                        "FUNC {def_name} param `${pname}` needs an uppercase type after `:` (e.g. STRING, INT, BOOL){got}"
5097                    ));
5098                };
5099                // Post-match the span holds words/puncts only, so the
5100                // shared renderer cannot fail; stay failed regardless.
5101                let ptype =
5102                    render_type_region(&paren_inner[tstart..tend], stmt).unwrap_or_default();
5103                if optional {
5104                    seen_optional = true;
5105                } else if seen_optional {
5106                    return Err(format!(
5107                        "FUNC {def_name} optional ? params must be trailing: `${pname}` follows an optional param"
5108                    ));
5109                }
5110                params.push((pname, ptype, optional));
5111                pcur.pos = tend;
5112                pcur.skip_gap_nl();
5113                if pcur.eat_punct(',') {
5114                    pcur.skip_gap_nl();
5115                    // Trailing comma misses (a param must follow).
5116                    if pcur.done() {
5117                        return Err(format!(
5118                            "FUNC {def_name} params must not end with a trailing comma"
5119                        ));
5120                    }
5121                    continue;
5122                }
5123                break;
5124            }
5125            // Trailing junk (including newlines) misses to generic.
5126            pcur.skip_gap_nl();
5127            if !pcur.done() {
5128                return Err(format!(
5129                    "FUNC {def_name} params must be `$name: TYPE` separated by commas"
5130                ));
5131            }
5132        }
5133    }
5134    // Mandatory return annotation: FUNC NAME(...): RET { ... }.
5135    // After paren group, require gap-optional colon then type shape.
5136    // Missing colon after matched name+parens is a hard parse error
5137    // (no legacy fallback). Non-block tails (neither colon nor brace)
5138    // miss to generic (probed FUNC FOO() ECHO hi).
5139    let is_colon = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')));
5140    if !is_colon {
5141        let is_brace = matches!(
5142            toks.get(p).map(|t| &t.kind),
5143            Some(TokKind::Group {
5144                delim: GroupDelim::Brace,
5145                ..
5146            })
5147        ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
5148        if is_brace {
5149            return Err(format!(
5150                "{keyword} {def_name} requires a return type : TYPE (e.g. : VOID, : STRING)"
5151            ));
5152        }
5153        return Ok(None);
5154    }
5155    let Some(ret_end) = parse_type_shape(toks, p + 1) else {
5156        return Err(format!(
5157            "{keyword} {def_name} requires a return type : TYPE after ':'"
5158        ));
5159    };
5160    let return_type = render_type_region(&toks[p + 1..ret_end], stmt)
5161        .map_err(|_| format!("{keyword} {def_name} requires a return type : TYPE after ':'"))?;
5162    let return_type = crate::canonicalize_spelling(&return_type);
5163    p = ret_end;
5164    // Block at any gap (never a template); missing blocks miss to
5165    // generic (probed FUNC FOO() ECHO hi).
5166    let block_ok = matches!(
5167        toks.get(p).map(|t| &t.kind),
5168        Some(TokKind::Group {
5169            delim: GroupDelim::Brace,
5170            ..
5171        })
5172    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
5173    if !block_ok {
5174        return Ok(None);
5175    }
5176    Ok(Some((
5177        FuncHeader {
5178            name: def_name,
5179            params,
5180            return_type,
5181            block: p,
5182        },
5183        p + 1 - pos,
5184    )))
5185}
5186
5187/// Single (non-block) `FUNC`: name, parenthesized params, block. The
5188/// shape parses purely first (misses fall to generic, declaring
5189/// nothing — the grammar only lowers matched pairs); then the name
5190/// declares in the enclosing scope before the body lowers (so
5191/// recursion resolves), and the body pushes a fresh scope.
5192/// Duplicates, reserved shadows, and parameter dupes fail loudly.
5193fn parse_func_at(
5194    toks: &[Tok],
5195    pos: usize,
5196    stmt: usize,
5197    ctx: &ParseCtx,
5198    is_async: bool,
5199) -> Result<Option<(StepKind, usize)>, TokenError> {
5200    let keyword = if is_async { "ASYNC FUNC" } else { KEYWORD_FUNC };
5201    let fail = |msg: String| TokenError {
5202        stmt,
5203        msg,
5204        line: 0,
5205        col: 0,
5206        kind: Some(ParseErrorKind::Validation {
5207            command: KEYWORD_FUNC.to_string(),
5208        }),
5209    };
5210    // Phase 1 (pure shape) through the single header owner:
5211    // adorn content errors with the `FUNC` / `ASYNC FUNC` keyword,
5212    // miss to generic on shape miss exactly as before.
5213    let Some((header, used)) = parse_func_header(toks, pos, stmt, keyword).map_err(fail)? else {
5214        return Ok(None);
5215    };
5216    let FuncHeader {
5217        name: def_name,
5218        params,
5219        return_type,
5220        block: p,
5221    } = header;
5222    // Phase 2 (effects): reserved shadows and same-scope duplicates
5223    // fail at the definition line, verbatim.
5224    if ctx.reserved.contains(&def_name) || ctx.modules.reserved_base_names().contains(&def_name) {
5225        return Err(fail(format!(
5226            "FUNC {def_name} cannot shadow reserved function `{def_name}`"
5227        )));
5228    }
5229    if !ctx.declare_func(&def_name) {
5230        return Err(fail(format!(
5231            "duplicate function `{def_name}` in same scope"
5232        )));
5233    }
5234    let mut seen = HashSet::new();
5235    for (pname, _, _) in &params {
5236        if !seen.insert(pname.clone()) {
5237            return Err(fail(format!(
5238                "FUNC {def_name} declares duplicate parameter ${pname}"
5239            )));
5240        }
5241    }
5242    let inner = match &toks[p].kind {
5243        TokKind::Group { inner, .. } => inner.clone(),
5244        _ => unreachable!(),
5245    };
5246    let body = parse_body_steps(&inner, stmt, ctx, false)?;
5247    let kind = StepKind::FuncDef {
5248        name: def_name,
5249        params,
5250        return_type,
5251        is_async,
5252        body,
5253        docs: None,
5254    };
5255    Ok(Some((kind, used)))
5256}
5257
5258/// `REMOTE` header bindings `[$var, env:KEY]` over a bracket
5259/// group's inner tokens: comma-separated, newlines and comments free
5260/// like `gap_nl`. `$`+name and `env`+`:`+key all ride gapless (the
5261/// enclosing rule is compound-atomic). Empty lists parse (probed);
5262/// anything else misses the shape (`None`: generic fails it like
5263/// the grammar's dropped optional).
5264#[allow(clippy::type_complexity)]
5265fn parse_remote_bindings(
5266    inner: &[Tok],
5267    stmt: usize,
5268    _ctx: &ParseCtx,
5269) -> Result<Option<(Vec<String>, Vec<String>)>, TokenError> {
5270    let _ = stmt;
5271    let mut parts: Vec<&[Tok]> = Vec::new();
5272    let mut start = 0;
5273    for (i, tok) in inner.iter().enumerate() {
5274        if matches!(&tok.kind, TokKind::Punct(',')) {
5275            parts.push(&inner[start..i]);
5276            start = i + 1;
5277        }
5278    }
5279    parts.push(&inner[start..]);
5280    // An empty list (`[]`, whitespace/comment-only) holds no bindings.
5281    if parts.len() == 1
5282        && parts[0]
5283            .iter()
5284            .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
5285    {
5286        return Ok(Some((Vec::new(), Vec::new())));
5287    }
5288    let mut vars = Vec::new();
5289    let mut env = Vec::new();
5290    for part in parts {
5291        // Edges admit gaps, newlines, and comments, like `gap_nl`.
5292        let mut part = part;
5293        while matches!(
5294            part.first().map(|t| &t.kind),
5295            Some(TokKind::Newline | TokKind::Comment(_))
5296        ) {
5297            part = &part[1..];
5298        }
5299        while matches!(
5300            part.last().map(|t| &t.kind),
5301            Some(TokKind::Newline | TokKind::Comment(_))
5302        ) {
5303            part = &part[..part.len() - 1];
5304        }
5305        // `$var` entries only: bare words are literal text, never
5306        // bindings.
5307        if matches!(
5308            part.first().map(|t| &t.kind),
5309            Some(TokKind::Punct(VAR_SIGIL_CHAR))
5310        ) && part.len() == 2
5311        {
5312            if part[1].joint
5313                && let TokKind::Word(w) = &part[1].kind
5314                && is_ident_word(w)
5315            {
5316                vars.push(w.clone());
5317                continue;
5318            }
5319            return Ok(None);
5320        }
5321        // `env:KEY`: gapless triple with an uppercase key.
5322        if part.len() == 3
5323            && matches!(&part[0].kind, TokKind::Word(w) if w == "env")
5324            && matches!(&part[1].kind, TokKind::Punct(':'))
5325            && part[1].joint
5326            && part[2].joint
5327        {
5328            if let TokKind::Word(k) = &part[2].kind
5329                && is_env_key(k)
5330            {
5331                env.push(k.clone());
5332                continue;
5333            }
5334            return Ok(None);
5335        }
5336        return Ok(None);
5337    }
5338    Ok(Some((vars, env)))
5339}
5340
5341/// `IMPORT` statement at `pos` (#115): module form (`IMPORT MOD`,
5342/// `IMPORT [A, B]`), file form (`IMPORT "p" AS A`,
5343/// `IMPORT ["p" AS A]`), mixed/multi forms
5344/// (`IMPORT [STD, "p" AS A, "q" AS B]`, multi-line included), and
5345/// selective harvests (`IMPORT [[F, G FROM "p" (AS A)?]]`).
5346/// Returns module names plus `ImportFile`/`ImportFuncs` steps in source
5347/// order, plus tokens consumed (relative to `pos`), or `None` on shape
5348/// miss (generic lowering fails it like the grammar). Validation is
5349/// hard: unknown modules, bad names, collisions, templates, and remote
5350/// URLs fail here, and validated entries register immediately
5351/// (modules, aliases, and bare harvest names share the innermost
5352/// frames).
5353type ImportEntries = (Vec<String>, Vec<StepKind>);
5354
5355fn parse_import_statement(
5356    toks: &[Tok],
5357    pos: usize,
5358    stmt: usize,
5359    ctx: &ParseCtx,
5360    guarded: bool,
5361) -> Result<Option<(ImportEntries, usize)>, TokenError> {
5362    let fail = |msg: String| TokenError {
5363        stmt,
5364        msg,
5365        line: 0,
5366        col: 0,
5367        kind: Some(ParseErrorKind::Validation {
5368            command: KEYWORD_IMPORT.to_string(),
5369        }),
5370    };
5371    let next = match toks.get(pos + 1) {
5372        // `sep` after `IMPORT`: joint followers miss.
5373        Some(t) if !t.joint => t,
5374        _ => return Ok(None),
5375    };
5376    // Parse entries first, validate in source order after.
5377    enum RawEntry {
5378        Module(String),
5379        File {
5380            path: String,
5381            alias: String,
5382        },
5383        From {
5384            func_names: Vec<String>,
5385            type_names: Vec<String>,
5386            path: String,
5387            alias: Option<String>,
5388        },
5389    }
5390    let mut raw: Vec<RawEntry> = Vec::new();
5391    let used;
5392    if matches!(
5393        &next.kind,
5394        TokKind::Group {
5395            delim: GroupDelim::Brace,
5396            ..
5397        }
5398    ) {
5399        return Ok(None);
5400    }
5401    if let TokKind::Group {
5402        delim: GroupDelim::Bracket,
5403        inner,
5404        ..
5405    } = &next.kind
5406    {
5407        // Comma-separated entries, `ws` gaps (newlines ok inside and
5408        // around entries, comments MISS — `ws` admits neither).
5409        // Single-file multi-name harvests skip the split: in
5410        // `[TYPE A, TYPE B FROM "f"]` the first comma-part (`[TYPE A]`)
5411        // carries no FROM and is invalid alone, so the whole bracket
5412        // is one harvest (see `whole_file_harvest`).
5413        // Bare-multi hint: `[FOO, BAR FROM "f"]` reads FOO as a
5414        // module for back-compat (bare words stay modules in single
5415        // brackets). If that word is not a known module but a harvest
5416        // follows, fail fast naming the two valid spellings instead
5417        // of the misleading unknown-module error.
5418        let whole = whole_file_harvest(inner);
5419        if whole.is_none()
5420            && let Some(word) = single_bare_first_part(inner)
5421            && !ctx.modules.modules.contains_key(word)
5422            && has_top_level_from_after_comma(inner)
5423        {
5424            return Err(fail(format!(
5425                "unknown module `{word}`; to harvest multiple names qualify each kind (`IMPORT [FUNC FOO, FUNC BAR FROM \"f\"]`)"
5426            )));
5427        }
5428        let mut parts: Vec<&[Tok]> = Vec::new();
5429        if whole.is_some() {
5430            parts.push(inner);
5431        } else {
5432            let mut start = 0;
5433            for (i, tok) in inner.iter().enumerate() {
5434                if matches!(&tok.kind, TokKind::Punct(',')) {
5435                    parts.push(&inner[start..i]);
5436                    start = i + 1;
5437                }
5438            }
5439            parts.push(&inner[start..]);
5440        }
5441        for part in parts {
5442            let dense: Vec<&Tok> = part
5443                .iter()
5444                .filter(|t| !matches!(&t.kind, TokKind::Newline))
5445                .collect();
5446            // `[[F, G FROM "path" (AS ALIAS)?]]`: selective function
5447            // harvest. Anything else bracketed here misses.
5448            if let [bracket] = dense.as_slice()
5449                && let TokKind::Group {
5450                    delim: GroupDelim::Bracket,
5451                    inner,
5452                    ..
5453                } = &bracket.kind
5454            {
5455                let Some(HarvestImport {
5456                    func_names,
5457                    type_names,
5458                    path,
5459                    alias,
5460                }) = parse_from_entry(inner)
5461                else {
5462                    return Ok(None);
5463                };
5464                raw.push(RawEntry::From {
5465                    func_names,
5466                    type_names,
5467                    path,
5468                    alias,
5469                });
5470                continue;
5471            }
5472            // `[F FROM "path" (AS ALIAS)?]`: single harvest without
5473            // inner brackets. The `FROM` keyword is the discriminant
5474            // (module and file parts never contain a top-level one);
5475            // multi-name harvests keep `[[F, G FROM ...]]` so the comma
5476            // stays grouped inside its own scope.
5477            if dense.len() >= 3 {
5478                let owned: Vec<Tok> = dense.iter().map(|t| (*t).clone()).collect();
5479                if let Some(HarvestImport {
5480                    func_names,
5481                    type_names,
5482                    path,
5483                    alias,
5484                }) = parse_from_entry(&owned)
5485                {
5486                    raw.push(RawEntry::From {
5487                        func_names,
5488                        type_names,
5489                        path,
5490                        alias,
5491                    });
5492                    continue;
5493                }
5494            }
5495            match dense.as_slice() {
5496                [tok] => match &tok.kind {
5497                    TokKind::Word(w) if is_upper_ident(w) => {
5498                        raw.push(RawEntry::Module(w.clone()));
5499                    }
5500                    _ => return Ok(None),
5501                },
5502                [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5503                    let (
5504                        TokKind::Str { text, .. },
5505                        TokKind::Word(as_word),
5506                        TokKind::Word(alias_word),
5507                    ) = (&path_tok.kind, &as_tok.kind, &alias_tok.kind)
5508                    else {
5509                        return Ok(None);
5510                    };
5511                    if as_word != KEYWORD_AS {
5512                        return Ok(None);
5513                    }
5514                    raw.push(RawEntry::File {
5515                        path: text.clone(),
5516                        alias: alias_word.clone(),
5517                    });
5518                }
5519                _ => return Ok(None),
5520            }
5521        }
5522        if raw.is_empty() {
5523            return Ok(None);
5524        }
5525        used = 2;
5526    } else if let TokKind::Word(w) = &next.kind {
5527        // Bare `IMPORT MOD` (single module, probed).
5528        if !is_upper_ident(w) {
5529            return Ok(None);
5530        }
5531        raw.push(RawEntry::Module(w.clone()));
5532        used = 2;
5533    } else if let TokKind::Str { text, .. } = &next.kind {
5534        // Bare `IMPORT "path" AS ALIAS`.
5535        let (Some(as_tok), Some(alias_tok)) = (toks.get(pos + 2), toks.get(pos + 3)) else {
5536            return Ok(None);
5537        };
5538        if as_tok.joint || alias_tok.joint {
5539            return Ok(None);
5540        }
5541        let (TokKind::Word(as_word), TokKind::Word(alias_word)) = (&as_tok.kind, &alias_tok.kind)
5542        else {
5543            return Ok(None);
5544        };
5545        if as_word != KEYWORD_AS {
5546            return Ok(None);
5547        }
5548        raw.push(RawEntry::File {
5549            path: text.clone(),
5550            alias: alias_word.clone(),
5551        });
5552        used = 4;
5553    } else {
5554        return Ok(None);
5555    }
5556    // Validate in source order: unknown modules fail with the exact
5557    // backend message (sorted known list); file and harvest entries
5558    // validate hard (bad names, collisions, templates, remote URLs).
5559    let mut modules = Vec::new();
5560    let mut steps = Vec::new();
5561    for entry in raw {
5562        match entry {
5563            RawEntry::Module(module) => {
5564                if !ctx.modules.modules.contains_key(&module) {
5565                    let mut known: Vec<String> = ctx.modules.modules.keys().cloned().collect();
5566                    known.sort();
5567                    return Err(fail(format!(
5568                        "unknown module `{module}`; known modules: {}",
5569                        known.join(", ")
5570                    )));
5571                }
5572                ctx.import_into_frame(std::slice::from_ref(&module), false);
5573                modules.push(module);
5574            }
5575            RawEntry::File { path, alias } => {
5576                let (path, alias) =
5577                    validate_file_import(&path, &alias, ctx, guarded).map_err(fail)?;
5578                steps.push(StepKind::ImportFile { path, alias });
5579            }
5580            RawEntry::From {
5581                func_names,
5582                type_names,
5583                path,
5584                alias,
5585            } => {
5586                let HarvestImport {
5587                    func_names,
5588                    type_names,
5589                    path,
5590                    alias,
5591                } = validate_from_import(
5592                    &func_names,
5593                    &type_names,
5594                    &path,
5595                    alias.as_deref(),
5596                    ctx,
5597                    guarded,
5598                )
5599                .map_err(fail)?;
5600                steps.push(StepKind::ImportFuncs {
5601                    path,
5602                    alias,
5603                    func_names,
5604                    type_names,
5605                });
5606            }
5607        }
5608    }
5609    Ok(Some(((modules, steps), used)))
5610}
5611
5612/// Single file import for value positions (#115): exactly one
5613/// `"path" AS ALIAS` entry and no modules. Anything else shaped like an
5614/// import is a hard error naming the restriction; shape misses return
5615/// `None` for the generic path.
5616fn parse_single_file_import(
5617    toks: &[Tok],
5618    pos: usize,
5619    stmt: usize,
5620    ctx: &ParseCtx,
5621) -> Result<Option<(String, String, usize)>, TokenError> {
5622    let Some(((modules, mut kinds), used)) = parse_import_statement(toks, pos, stmt, ctx, false)?
5623    else {
5624        return Ok(None);
5625    };
5626    if !modules.is_empty() || !matches!(kinds.as_slice(), [StepKind::ImportFile { .. }]) {
5627        return Err(TokenError {
5628            stmt,
5629            msg: if !modules.is_empty()
5630                || kinds
5631                    .iter()
5632                    .any(|k| matches!(k, StepKind::ImportFuncs { .. }))
5633            {
5634                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>]); modules and function harvests stay at statement level".to_string()
5635            } else {
5636                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>])"
5637                    .to_string()
5638            },
5639            line: 0,
5640            col: 0,
5641            kind: Some(ParseErrorKind::Validation {
5642                command: KEYWORD_IMPORT.to_string(),
5643            }),
5644        });
5645    }
5646    let Some(StepKind::ImportFile { path, alias }) = kinds.pop() else {
5647        unreachable!("length and variant checked above")
5648    };
5649    Ok(Some((path, alias, used)))
5650}
5651
5652/// One `EXPORT` name: an uppercase word with an optional joint
5653/// `::UPPER` tail. Returns the name and tokens consumed, `Ok(None)`
5654/// on shape miss, or `Err` when a recognizable identifier carries
5655/// the wrong sigil (`CONST` requires `$`, `FUNC`/`TYPE` forbid it).
5656fn parse_export_name(
5657    toks: &[Tok],
5658    pos: usize,
5659    require_sigil: bool,
5660    stmt: usize,
5661) -> Result<Option<(String, usize)>, TokenError> {
5662    // Sigil rule: `EXPORT CONST $N` and `EXPORT CONST $LIB::V` require
5663    // the `$`, exactly like every other `CONST` read; `EXPORT FOO`,
5664    // `EXPORT TYPE T`, and qualified func forwards never take one.
5665    // Stored without the sigil; downstream matching (top-level tables,
5666    // harvest maps) is unchanged. `$` must ride gapless onto the
5667    // name, like every `$` read.
5668    let fail = |msg: String| TokenError {
5669        stmt,
5670        line: 0,
5671        col: 0,
5672        kind: None,
5673        msg,
5674    };
5675    let offset = match toks.get(pos).map(|t| &t.kind) {
5676        Some(TokKind::Punct(VAR_SIGIL_CHAR)) if toks.get(pos + 1).is_some_and(|t| t.joint) => 1,
5677        Some(TokKind::Punct(VAR_SIGIL_CHAR)) => return Ok(None),
5678        _ => 0,
5679    };
5680    if require_sigil != (offset == 1) {
5681        let head = toks.get(pos + offset).map(|t| &t.kind);
5682        let recognizable = matches!(head, Some(TokKind::Word(w)) if is_upper_ident(w));
5683        if !recognizable {
5684            return Ok(None);
5685        }
5686        if require_sigil {
5687            return Err(fail(
5688                "EXPORT CONST requires `$`: write EXPORT CONST $NAME (never bare)".to_string(),
5689            ));
5690        } else {
5691            return Err(fail(
5692                "EXPORT FUNC and EXPORT TYPE names never take `$`: write EXPORT FOO".to_string(),
5693            ));
5694        }
5695    }
5696    let head = match toks.get(pos + offset).map(|t| &t.kind) {
5697        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
5698        _ => return Ok(None),
5699    };
5700    let mut name = head;
5701    let mut used = 1 + offset;
5702    // Greedy-prefix `::tail` (atomic, like the grammar): a valid
5703    // tail joins, an invalid one stays trailing (failing downstream
5704    // exactly like the grammar's committed prefix).
5705    if matches!(
5706        toks.get(pos + offset + 1).map(|t| &t.kind),
5707        Some(TokKind::Punct(':'))
5708    ) && toks.get(pos + offset + 1).is_some_and(|t| t.joint)
5709        && matches!(
5710            toks.get(pos + offset + 2).map(|t| &t.kind),
5711            Some(TokKind::Punct(':'))
5712        )
5713        && toks.get(pos + offset + 2).is_some_and(|t| t.joint)
5714        && let Some(TokKind::Word(tail)) = toks.get(pos + offset + 3).map(|t| &t.kind)
5715        && toks[pos + offset + 3].joint
5716        && is_upper_ident(tail)
5717    {
5718        name.push_str(MODULE_SEPARATOR);
5719        name.push_str(tail);
5720        used = 4 + offset;
5721    }
5722    Ok(Some((name, used)))
5723}
5724
5725/// One selective harvest (`[[F, G FROM "path" (AS ALIAS)?]]`): the
5726/// wanted function and type names plus the path and optional alias.
5727/// Bare names are functions; `TYPE`/`FUNC` prefixes select the kind
5728/// explicitly (`[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`).
5729struct HarvestImport {
5730    func_names: Vec<String>,
5731    type_names: Vec<String>,
5732    path: String,
5733    alias: Option<String>,
5734}
5735
5736/// One `[[F, G FROM "path" (AS ALIAS)?]]` entry: selective function
5737/// harvest with optional `TYPE`/`FUNC` qualifiers per name:
5738/// `[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`
5739/// (bare stays func for back-compat).
5740/// Returns the harvest, or `None` on shape miss (generic lowering fails
5741/// it). Name case is validated hard by the caller, like file aliases.
5742fn parse_from_entry(inner: &[Tok]) -> Option<HarvestImport> {
5743    let dense: Vec<&Tok> = inner
5744        .iter()
5745        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5746        .collect();
5747    let from = dense
5748        .iter()
5749        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5750    if from == 0 {
5751        return None;
5752    }
5753    // Names: comma-separated entries, each `NAME` (func) or
5754    // `TYPE NAME` / `FUNC NAME` (explicit kind for clarity).
5755    let mut func_names = Vec::new();
5756    let mut type_names = Vec::new();
5757    let mut start = 0;
5758    let head = &dense[..from];
5759    // Local helper: classify one comma-separated part.
5760    fn classify_part(part: &[&Tok]) -> Option<(bool, String)> {
5761        match part {
5762            [tok] => {
5763                let TokKind::Word(w) = &tok.kind else {
5764                    return None;
5765                };
5766                Some((false, w.clone()))
5767            }
5768            // `TYPE NAME` / `FUNC NAME`: the name must be `sep` (gapped
5769            // from the kind); the kind may be joint to a preceding `[`
5770            // or `,` (no space required there), so only the name's joint
5771            // flag matters.
5772            [kind_tok, name_tok] if !name_tok.joint => {
5773                let (TokKind::Word(kind), TokKind::Word(name)) = (&kind_tok.kind, &name_tok.kind)
5774                else {
5775                    return None;
5776                };
5777                if kind == KEYWORD_TYPE {
5778                    Some((true, name.clone()))
5779                } else if kind == KEYWORD_FUNC {
5780                    Some((false, name.clone()))
5781                } else {
5782                    None
5783                }
5784            }
5785            _ => None,
5786        }
5787    }
5788    for (i, tok) in head.iter().enumerate() {
5789        if matches!(&tok.kind, TokKind::Punct(',')) {
5790            let part = &head[start..i];
5791            let (is_type, name) = classify_part(part)?;
5792            if is_type {
5793                type_names.push(name);
5794            } else {
5795                func_names.push(name);
5796            }
5797            start = i + 1;
5798        }
5799    }
5800    let part = &head[start..];
5801    let (is_type, name) = classify_part(part)?;
5802    if is_type {
5803        type_names.push(name);
5804    } else {
5805        func_names.push(name);
5806    }
5807    // Tail: `"path"` or bare `MODULE` with an optional gapped `AS ALIAS`.
5808    // Quoted is a file path (module fallback only when no file matches);
5809    // bare is a host module (no file probe ambiguity).
5810    let tail = &dense[from + 1..];
5811    let path_text = |tok: &Tok| match &tok.kind {
5812        TokKind::Str { text, .. } => Some(text.clone()),
5813        TokKind::Word(w) if is_upper_ident(w) => Some(w.clone()),
5814        _ => None,
5815    };
5816    match tail {
5817        [path_tok] => {
5818            let text = path_text(path_tok)?;
5819            Some(HarvestImport {
5820                func_names,
5821                type_names,
5822                path: text,
5823                alias: None,
5824            })
5825        }
5826        [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5827            let text = path_text(path_tok)?;
5828            let (TokKind::Word(as_word), TokKind::Word(alias_word)) =
5829                (&as_tok.kind, &alias_tok.kind)
5830            else {
5831                return None;
5832            };
5833            if as_word != KEYWORD_AS {
5834                return None;
5835            }
5836            Some(HarvestImport {
5837                func_names,
5838                type_names,
5839                path: text,
5840                alias: Some(alias_word.clone()),
5841            })
5842        }
5843        _ => None,
5844    }
5845}
5846
5847/// First comma-part of a bracket when it is exactly one bare
5848/// uppercase word: the back-compat module reading. Anything else
5849/// (prefixed names, groups, multiple words) is not a bare module.
5850fn single_bare_first_part(inner: &[Tok]) -> Option<&str> {
5851    let end = inner
5852        .iter()
5853        .position(|t| matches!(&t.kind, TokKind::Punct(',')))
5854        .unwrap_or(inner.len());
5855    let mut words = inner[..end]
5856        .iter()
5857        .filter(|t| !matches!(&t.kind, TokKind::Newline));
5858    match (words.next(), words.next()) {
5859        (Some(tok), None) => match &tok.kind {
5860            TokKind::Word(w) if is_upper_ident(w) => Some(w.as_str()),
5861            _ => None,
5862        },
5863        _ => None,
5864    }
5865}
5866
5867/// Whether a top-level `FROM` follows the first top-level comma:
5868/// distinguishes a module-plus-harvest entry (`[STD, T FROM "f"]`)
5869/// from a bare word the author meant as a harvest name.
5870fn has_top_level_from_after_comma(inner: &[Tok]) -> bool {
5871    let mut seen_comma = false;
5872    for tok in inner {
5873        match &tok.kind {
5874            TokKind::Punct(',') => seen_comma = true,
5875            TokKind::Word(w) if seen_comma && w == KEYWORD_FROM => return true,
5876            _ => {}
5877        }
5878    }
5879    false
5880}
5881
5882/// Whole-bracket single-file harvest (`[TYPE A, TYPE B FROM "f"]`):
5883/// the comma-split would orphan `[TYPE A]` (no FROM, invalid alone),
5884/// so the entire bracket parses as one harvest. Only explicitly
5885/// prefixed names qualify: a bare word keeps its legacy module
5886/// reading, so `[STD, TYPE T FROM "f"]` still splits into a module
5887/// plus a harvest instead of harvesting STD as a function.
5888fn whole_file_harvest(inner: &[Tok]) -> Option<HarvestImport> {
5889    let owned: Vec<Tok> = inner.to_vec();
5890    let harvest = parse_from_entry(&owned)?;
5891    let dense: Vec<&Tok> = inner
5892        .iter()
5893        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5894        .collect();
5895    let from = dense
5896        .iter()
5897        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5898    let mut start = 0;
5899    for (i, tok) in dense[..from].iter().enumerate() {
5900        if matches!(&tok.kind, TokKind::Punct(',')) {
5901            if !is_prefixed_name(&dense[start..i]) {
5902                return None;
5903            }
5904            start = i + 1;
5905        }
5906    }
5907    if !is_prefixed_name(&dense[start..from]) {
5908        return None;
5909    }
5910    Some(harvest)
5911}
5912
5913/// One explicitly prefixed name (`TYPE NAME` / `FUNC NAME`): the name
5914/// stays gapped from its kind; the kind may joint to `[` or `,`.
5915fn is_prefixed_name(part: &[&Tok]) -> bool {
5916    match part {
5917        [kind_tok, name_tok] if !name_tok.joint => {
5918            matches!(
5919                (&kind_tok.kind, &name_tok.kind),
5920                (
5921                    TokKind::Word(kind),
5922                    TokKind::Word(_)
5923                ) if kind == KEYWORD_TYPE || kind == KEYWORD_FUNC
5924            )
5925        }
5926        _ => false,
5927    }
5928}
5929
5930/// Validate an `IMPORT` alias: hard errors (never shape misses) plus
5931/// registration into the innermost import frame. Same-frame duplicates
5932/// reject, unless the new import and every visible same-alias entry
5933/// are guard-gated: an unguarded duplicate always collides at runtime
5934/// (probable typo, fail fast), while guarded duplicates may be
5935/// platform branches whose disjointness the static pass decides.
5936fn validate_import_alias(alias: &str, ctx: &ParseCtx, guarded: bool) -> Result<String, String> {
5937    if !is_upper_ident(alias) {
5938        return Err(format!(
5939            "IMPORT alias must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{alias}`"
5940        ));
5941    }
5942    if ctx.modules.modules.contains_key(alias) {
5943        return Err(format!(
5944            "IMPORT alias `{alias}` collides with module `{alias}`"
5945        ));
5946    }
5947    let flags = ctx.import_guard_flags(alias);
5948    if !flags.is_empty() && (!guarded || flags.iter().any(|g| !g)) {
5949        return Err(format!("duplicate IMPORT alias `{alias}`"));
5950    }
5951    ctx.import_into_frame(std::slice::from_ref(&alias.to_string()), guarded);
5952    Ok(alias.to_string())
5953}
5954
5955/// Validate an `IMPORT` path: hard errors, never shape misses.
5956fn validate_import_path(path: &str) -> Result<String, String> {
5957    if path.is_empty() {
5958        return Err("IMPORT path must not be empty".to_string());
5959    }
5960    if path.contains("{{") {
5961        return Err("IMPORT path must be a literal string (no {{ }} templates)".to_string());
5962    }
5963    if path.contains("://") {
5964        return Err(
5965            "remote imports are deferred to #270 (net: Run scripts from a remote URL)".to_string(),
5966        );
5967    }
5968    Ok(path.to_string())
5969}
5970
5971/// Validate a file-import path/alias pair: hard errors (never shape
5972/// misses) plus alias registration into the innermost import frame.
5973/// `guarded` marks a guard-gated statement, relaxing the same-frame
5974/// duplicate gate for platform branches (see `validate_import_alias`).
5975fn validate_file_import(
5976    path: &str,
5977    alias: &str,
5978    ctx: &ParseCtx,
5979    guarded: bool,
5980) -> Result<(String, String), String> {
5981    let alias = validate_import_alias(alias, ctx, guarded)?;
5982    let path = validate_import_path(path)?;
5983    Ok((path, alias))
5984}
5985
5986/// Validate a `[[F, G FROM "path" (AS ALIAS)?]]` entry: hard errors
5987/// (never shape misses). Bare func names declare into the innermost
5988/// `FUNC` frame so calls resolve statically; the runtime defines them
5989/// (and fails unknown names there). Type names need no func-frame
5990/// declaration (types resolve through the global type directory);
5991/// the runtime validates them against the file's `EXPORT TYPE` list.
5992/// An alias registers like a file import.
5993fn validate_from_import(
5994    func_names: &[String],
5995    type_names: &[String],
5996    path: &str,
5997    alias: Option<&str>,
5998    ctx: &ParseCtx,
5999    guarded: bool,
6000) -> Result<HarvestImport, String> {
6001    let path = validate_import_path(path)?;
6002    let mut out_func_names = Vec::with_capacity(func_names.len());
6003    for name in func_names {
6004        if !is_upper_ident(name) {
6005            return Err(format!(
6006                "IMPORT function names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
6007            ));
6008        }
6009        if ctx.reserved.contains(name) {
6010            return Err(format!("cannot shadow reserved function `{name}`"));
6011        }
6012        out_func_names.push(name.clone());
6013    }
6014    let mut out_type_names = Vec::with_capacity(type_names.len());
6015    for name in type_names {
6016        if !is_upper_ident(name) {
6017            return Err(format!(
6018                "IMPORT type names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
6019            ));
6020        }
6021        out_type_names.push(name.clone());
6022    }
6023    if out_func_names.is_empty() && out_type_names.is_empty() {
6024        return Err("IMPORT harvest needs at least one function or type name".to_string());
6025    }
6026    if let Some(alias) = alias {
6027        let alias = validate_import_alias(alias, ctx, guarded)?;
6028        Ok(HarvestImport {
6029            func_names: out_func_names,
6030            type_names: out_type_names,
6031            path,
6032            alias: Some(alias),
6033        })
6034    } else {
6035        for name in &out_func_names {
6036            if !ctx.declare_func(name) {
6037                return Err(format!("duplicate function `{name}` in same scope"));
6038            }
6039        }
6040        // Type harvests without alias land bare in the global type
6041        // directory: duplicates across files fail at import time
6042        // (different targets), not at parse time (targets need IO).
6043        Ok(HarvestImport {
6044            func_names: out_func_names,
6045            type_names: out_type_names,
6046            path,
6047            alias: None,
6048        })
6049    }
6050}
6051
6052/// One `EXPORT ...` name list: function, type, and const names in
6053/// source order. Bare names are functions; explicit `TYPE`/`FUNC`/
6054/// `CONST` prefixes select the kind.
6055struct ExportNames {
6056    func_names: Vec<String>,
6057    type_names: Vec<String>,
6058    const_names: Vec<String>,
6059}
6060
6061/// `EXPORT ...` names at `pos`: bracket list (strict, `ws` gaps:
6062/// newlines ok, comments miss) or a bare greedy-prefix name.
6063/// Supports explicit `TYPE`/`FUNC`/`CONST` qualifiers for clarity:
6064/// `EXPORT TYPE FOO`, `EXPORT FUNC FOO`, `EXPORT CONST $FOO`,
6065/// plus mixed `EXPORT [TYPE A, FUNC B, CONST $C, D]` (bare stays func).
6066/// Returns the name lists plus tokens consumed, `Ok(None)` on shape
6067/// miss (generic fails it in lowering like the grammar), or `Err`
6068/// when a recognizable name carries the wrong sigil. Recording and
6069/// duplicate checks live with the caller (they need the guard and
6070/// level context).
6071fn parse_export_at(
6072    toks: &[Tok],
6073    pos: usize,
6074    stmt: usize,
6075) -> Result<Option<(ExportNames, usize)>, TokenError> {
6076    let next = match toks.get(pos + 1) {
6077        // `sep` after `EXPORT`: joint followers miss.
6078        Some(t) if !t.joint => t,
6079        _ => return Ok(None),
6080    };
6081    // Explicit `EXPORT TYPE ...`, `EXPORT FUNC ...`, or
6082    // `EXPORT CONST ...` prefix.
6083    if let TokKind::Word(w) = &next.kind
6084        && (w == KEYWORD_TYPE || w == KEYWORD_FUNC || w == KEYWORD_CONST)
6085    {
6086        let kind = w.as_str();
6087        let after = match toks.get(pos + 2) {
6088            Some(t) if !t.joint => t,
6089            _ => return Ok(None),
6090        };
6091        if let TokKind::Group {
6092            delim: GroupDelim::Bracket,
6093            inner,
6094            ..
6095        } = &after.kind
6096        {
6097            let mut func_names = Vec::new();
6098            let mut type_names = Vec::new();
6099            let mut const_names = Vec::new();
6100            for part in split_bracket_entries(inner) {
6101                let part = trim_export_part(part);
6102                // A trailing comma leaves an empty final entry; it
6103                // carries no name and must not fail the list.
6104                if part.is_empty() {
6105                    continue;
6106                }
6107                let require_sigil = kind == KEYWORD_CONST;
6108                let Some((name, used)) = parse_export_name(part, 0, require_sigil, stmt)? else {
6109                    return Ok(None);
6110                };
6111                if used != part.len() {
6112                    return Ok(None);
6113                }
6114                match kind {
6115                    k if k == KEYWORD_TYPE => type_names.push(name),
6116                    k if k == KEYWORD_CONST => const_names.push(name),
6117                    _ => func_names.push(name),
6118                }
6119            }
6120            if func_names.is_empty() && type_names.is_empty() && const_names.is_empty() {
6121                return Ok(None);
6122            }
6123            return Ok(Some((
6124                ExportNames {
6125                    func_names,
6126                    type_names,
6127                    const_names,
6128                },
6129                3,
6130            )));
6131        }
6132        if matches!(&after.kind, TokKind::Group { .. }) {
6133            return Ok(None);
6134        }
6135        let require_sigil = kind == KEYWORD_CONST;
6136        let Some((name, used)) = parse_export_name(toks, pos + 2, require_sigil, stmt)? else {
6137            return Ok(None);
6138        };
6139        // Bare name after TYPE/FUNC/CONST prefix must consume exactly
6140        // one name; trailing loops stay outside like the unprefixed
6141        // case. `used` counts from pos+2, so 1 name is valid.
6142        if used == 0 {
6143            return Ok(None);
6144        }
6145        return Ok(Some((
6146            match kind {
6147                k if k == KEYWORD_TYPE => ExportNames {
6148                    func_names: Vec::new(),
6149                    type_names: vec![name],
6150                    const_names: Vec::new(),
6151                },
6152                k if k == KEYWORD_CONST => ExportNames {
6153                    func_names: Vec::new(),
6154                    type_names: Vec::new(),
6155                    const_names: vec![name],
6156                },
6157                _ => ExportNames {
6158                    func_names: vec![name],
6159                    type_names: Vec::new(),
6160                    const_names: Vec::new(),
6161                },
6162            },
6163            2 + used,
6164        )));
6165    }
6166    if let TokKind::Group {
6167        delim: GroupDelim::Bracket,
6168        inner,
6169        ..
6170    } = &next.kind
6171    {
6172        let mut func_names = Vec::new();
6173        let mut type_names = Vec::new();
6174        let mut const_names = Vec::new();
6175        for part in split_bracket_entries(inner) {
6176            let part = trim_export_part(part);
6177            // A trailing comma leaves an empty final entry; it
6178            // carries no name and must not fail the list.
6179            if part.is_empty() {
6180                continue;
6181            }
6182            let (kind, rest) = split_export_prefix(part);
6183            let is_const = matches!(&kind, TokKind::Word(w) if w == KEYWORD_CONST);
6184            let is_type = matches!(&kind, TokKind::Word(w) if w == KEYWORD_TYPE);
6185            // Exactly one name per entry (entries never trail).
6186            let Some((name, used)) = parse_export_name(rest, 0, is_const, stmt)? else {
6187                return Ok(None);
6188            };
6189            if used != rest.len() {
6190                return Ok(None);
6191            }
6192            if is_const {
6193                const_names.push(name);
6194            } else if is_type {
6195                type_names.push(name);
6196            } else {
6197                func_names.push(name);
6198            }
6199        }
6200        if func_names.is_empty() && type_names.is_empty() && const_names.is_empty() {
6201            return Ok(None);
6202        }
6203        return Ok(Some((
6204            ExportNames {
6205                func_names,
6206                type_names,
6207                const_names,
6208            },
6209            2,
6210        )));
6211    }
6212    if matches!(&next.kind, TokKind::Group { .. }) {
6213        return Ok(None);
6214    }
6215    // Bare name (greedy `::` prefix; trailing loops outside). Bare
6216    // stays func for back-compat; `TYPE`/`FUNC` prefix selects above.
6217    // Func names never take `$`: `EXPORT $X` errors inside
6218    // `parse_export_name`, exactly like a `$`-less read elsewhere.
6219    match parse_export_name(toks, pos + 1, false, stmt)? {
6220        Some((name, used)) => Ok(Some((
6221            ExportNames {
6222                func_names: vec![name],
6223                type_names: Vec::new(),
6224                const_names: Vec::new(),
6225            },
6226            1 + used,
6227        ))),
6228        None => Ok(None),
6229    }
6230}
6231
6232/// Trim leading/trailing newlines around one `EXPORT` bracket entry.
6233/// Single owner so the explicit-prefix and mixed-list loops cannot
6234/// drift on trailing-comma handling.
6235fn trim_export_part(part: &[Tok]) -> &[Tok] {
6236    let mut part = part;
6237    while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
6238        part = &part[1..];
6239    }
6240    while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
6241        part = &part[..part.len() - 1];
6242    }
6243    part
6244}
6245
6246/// Split one mixed-list `EXPORT` entry into its kind prefix and name
6247/// slice. `TYPE`/`FUNC`/`CONST` plus a gapped name selects the kind;
6248/// anything else defaults to `FUNC`. Single owner so both bracket
6249/// loops agree on prefix parsing.
6250fn split_export_prefix(part: &[Tok]) -> (TokKind, &[Tok]) {
6251    // Optional per-entry `TYPE`/`FUNC`/`CONST` prefix for mixed
6252    // lists: `EXPORT [TYPE A, FUNC B, CONST $C, D]` (bare stays
6253    // func, `CONST` entries require `$`). The name must be `sep`
6254    // from the prefix; the prefix itself may be joint to a
6255    // preceding `[` or `,`, so only the name's joint flag matters.
6256    match part {
6257        [first, second, ..]
6258            if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_TYPE || w == KEYWORD_FUNC || w == KEYWORD_CONST)
6259                && !second.joint =>
6260        {
6261            (first.kind.clone(), &part[1..])
6262        }
6263        _ => (TokKind::Word(KEYWORD_FUNC.to_string()), part),
6264    }
6265}
6266
6267/// Split bracket inner tokens on top-level commas, preserving entries
6268/// for per-entry `TYPE`/`FUNC` handling. Newlines trim at the caller.
6269fn split_bracket_entries(inner: &[Tok]) -> Vec<&[Tok]> {
6270    let mut parts: Vec<&[Tok]> = Vec::new();
6271    let mut start = 0;
6272    for (i, tok) in inner.iter().enumerate() {
6273        if matches!(&tok.kind, TokKind::Punct(',')) {
6274            parts.push(&inner[start..i]);
6275            start = i + 1;
6276        }
6277    }
6278    parts.push(&inner[start..]);
6279    parts
6280}
6281
6282/// `TYPE NAME = SHAPE` at `pos`: uppercase name, single `=`, maximal
6283/// type-tag shape canonicalized through the shared spelling.
6284/// Returns the alias plus tokens consumed, or `None` on shape miss
6285/// (generic fails it in lowering like the grammar).
6286fn parse_type_stmt_at(
6287    toks: &[Tok],
6288    pos: usize,
6289    stmt: usize,
6290) -> Result<Option<(StepKind, usize)>, TokenError> {
6291    let name = match toks.get(pos + 1).map(|t| &t.kind) {
6292        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
6293        _ => return Ok(None),
6294    };
6295    // Single `=` at any gap (`gap` zero-width); `==` misses.
6296    if !matches!(
6297        toks.get(pos + 2).map(|t| &t.kind),
6298        Some(TokKind::Punct('='))
6299    ) {
6300        return Ok(None);
6301    }
6302    if matches!(
6303        toks.get(pos + 3).map(|t| &t.kind),
6304        Some(TokKind::Punct('='))
6305    ) {
6306        return Ok(None);
6307    }
6308    let Some(end) = parse_type_shape(toks, pos + 3) else {
6309        return Ok(None);
6310    };
6311    // Post-match the span holds words, puncts, and default literals
6312    // only, so the shared renderer cannot fail; stay failed regardless.
6313    let target = render_type_region(&toks[pos + 3..end], stmt).unwrap_or_default();
6314    Ok(Some((StepKind::TypeAlias { name, target }, end - pos)))
6315}
6316
6317/// Single (non-block) `REMOTE`: target, optional bindings, block.
6318/// The target reads a maximal joint run in the grammar's superset
6319/// charset (misses fall to generic); strict validity fails loudly
6320/// with the exact backend message. Bindings miss to generic;
6321/// empty/missing bodies and nesting violations fail loudly.
6322fn parse_remote_single(
6323    toks: &[Tok],
6324    pos: usize,
6325    stmt: usize,
6326    ctx: &ParseCtx,
6327) -> Result<Option<(StepKind, usize)>, TokenError> {
6328    let fail = |msg: String| TokenError {
6329        stmt,
6330        msg,
6331        line: 0,
6332        col: 0,
6333        kind: Some(ParseErrorKind::Validation {
6334            command: KEYWORD_REMOTE.to_string(),
6335        }),
6336    };
6337    // Target: joint run in the superset charset (alnum/`_`/`-`/`.`/`:`).
6338    // Anything else (joint or not) ends the run; an empty run misses
6339    // to generic. (`sep` needs no explicit check: a joint `(` is a
6340    // call routed before this ever runs, and anything unparseable
6341    // misses the same way.)
6342    let mut target = String::new();
6343    let mut p = pos + 1;
6344    while let Some(t) = toks.get(p) {
6345        if !t.joint && !target.is_empty() {
6346            break;
6347        }
6348        match &t.kind {
6349            TokKind::Word(w)
6350                if w.chars().all(|c| {
6351                    c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' || c == ':'
6352                }) =>
6353            {
6354                // Words arrive whole from the lexer; a bad word ends
6355                // the run (never partially appends), like the grammar.
6356                target.push_str(w);
6357                p += 1;
6358            }
6359            TokKind::Punct(c)
6360                if matches!(c, '_' | '-' | '.' | ':') && (target.is_empty() || t.joint) =>
6361            {
6362                target.push(*c);
6363                p += 1;
6364            }
6365            _ => break,
6366        }
6367    }
6368    if target.is_empty() {
6369        return Ok(None);
6370    }
6371    if !crate::commands::is_valid_remote_target(&target) {
6372        return Err(fail(format!(
6373            "invalid REMOTE target `{target}`: start alphanumeric, then alphanumeric, `_`, or `-`, max 64 chars, never SNAPSHOT, LOCAL, CACHE, SYSTEM, or REMOTE"
6374        )));
6375    }
6376    // Optional bindings `[$var, env:KEY]` at any gap (even joint,
6377    // probed); malformed bindings miss the whole shape to generic.
6378    let mut vars = Vec::new();
6379    let mut env = Vec::new();
6380    if let Some(bracket) = toks.get(p)
6381        && matches!(
6382            &bracket.kind,
6383            TokKind::Group {
6384                delim: GroupDelim::Bracket,
6385                ..
6386            }
6387        )
6388    {
6389        let inner = match &bracket.kind {
6390            TokKind::Group { inner, .. } => inner.clone(),
6391            _ => unreachable!(),
6392        };
6393        match parse_remote_bindings(&inner, stmt, ctx)? {
6394            Some((v, e)) => {
6395                vars = v;
6396                env = e;
6397            }
6398            None => return Ok(None),
6399        }
6400        p += 1;
6401    }
6402    // Block required (any gap, never a template); missing blocks
6403    // miss to generic.
6404    let block_ok = matches!(
6405        toks.get(p).map(|t| &t.kind),
6406        Some(TokKind::Group {
6407            delim: GroupDelim::Brace,
6408            ..
6409        })
6410    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
6411    if !block_ok {
6412        return Ok(None);
6413    }
6414    let inner = match &toks[p].kind {
6415        TokKind::Group { inner, .. } => inner.clone(),
6416        _ => unreachable!(),
6417    };
6418    let body = parse_body_steps(&inner, stmt, ctx, false)?;
6419    p += 1;
6420    if body.is_empty() {
6421        return Err(fail("REMOTE requires a non-empty braced block".to_string()));
6422    }
6423    if crate::commands::contains_remote_block(&body) {
6424        return Err(fail(format!(
6425            "REMOTE blocks cannot nest (target `{target}` contains another REMOTE block)"
6426        )));
6427    }
6428    if body
6429        .iter()
6430        .any(|s| crate::commands::contains_inherit_env(&s.kind))
6431    {
6432        return Err(fail(
6433            "INHERIT_ENV cannot appear inside a REMOTE block: the guest inherits its own process environment".to_string(),
6434        ));
6435    }
6436    // Outer-function containment (same rule as the shared remote
6437    // validators): body calls resolving to visible
6438    // outer `SCRIPT` defs (without same-body definitions) fail.
6439    {
6440        let mut inner_defs = HashSet::new();
6441        let mut calls = Vec::new();
6442        crate::commands::collect_remote_body_symbols(&body, &mut inner_defs, &mut calls);
6443        let outer_defs: HashSet<String> = ctx.funcs.borrow().iter().flatten().cloned().collect();
6444        for call in &calls {
6445            let bare = crate::constants::base_name(call);
6446            let is_script_call = match crate::constants::split_qualified(call) {
6447                Some((module, _)) => module == crate::constants::SCRIPT_MODULE_NAME,
6448                None => true,
6449            };
6450            if is_script_call && outer_defs.contains(bare) && !inner_defs.contains(bare) {
6451                return Err(fail(format!(
6452                    "REMOTE '{target}' calls outer function '{bare}' (functions must be defined inside the block)"
6453                )));
6454            }
6455        }
6456    }
6457    Ok(Some((
6458        StepKind::RemoteBlock {
6459            target,
6460            vars,
6461            env,
6462            body,
6463        },
6464        p - pos,
6465    )))
6466}
6467// ---- LET/SET/RETURN + expressions ----
6468// Expression tiers over [`Tok`] implement the precedence chain
6469// (or > and > comparison > ordering > add > mul > unary > atom);
6470// arithmetic/comparison lowering runs through the shared constructors
6471// (`make_arith`, `make_compare`, `apply_unary_neg`), so folding, RPN
6472// compilation, and overflow behavior are identical by construction,
6473// never re-derived.
6474
6475/// Eat a one- or two-char operator: single puncts match directly;
6476/// pairs (`==`, `!=`, `<=`, `>=`, `&&`, `||`, `::`) require a joint
6477/// second punct. Newlines never skip here (expression mode).
6478fn eat_op(cur: &mut Cursor, first: char, second: Option<char>) -> bool {
6479    // Gaps (comments included) are skipped before every operator.
6480    cur.skip_gap();
6481    let (a, b) = match (cur.toks.get(cur.pos), cur.toks.get(cur.pos + 1)) {
6482        (Some(a), b) => (a, b),
6483        _ => return false,
6484    };
6485    if !matches!(&a.kind, TokKind::Punct(c) if *c == first) {
6486        return false;
6487    }
6488    match second {
6489        None => {
6490            cur.pos += 1;
6491            true
6492        }
6493        Some(c2) => match b {
6494            Some(t) if t.joint && matches!(&t.kind, TokKind::Punct(c) if *c == c2) => {
6495                cur.pos += 2;
6496                true
6497            }
6498            _ => false,
6499        },
6500    }
6501}
6502
6503/// Dummy span for the shared lowering constructors: v2 owns no source
6504/// positions yet, so only success values (span-free) participate in
6505/// parity; failures surface through [`TokenError`] text.
6506fn lowering_ctx(stmt: usize) -> SpanContext<'static> {
6507    let _ = stmt;
6508    SpanContext::line_only(0)
6509}
6510
6511fn parse_expr_or(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6512    let mut left = parse_expr_and(cur, ctx)?;
6513    while eat_op(cur, '|', Some('|')) {
6514        cur.skip_gap();
6515        let right = parse_expr_and(cur, ctx)?;
6516        // No folding, no boundary checks: unfused literal runs stay
6517        // literal here.
6518        left = Expr::Logical {
6519            op: LogicalOp::Or,
6520            left: Box::new(left),
6521            right: Box::new(right),
6522        };
6523    }
6524    Ok(left)
6525}
6526
6527fn parse_expr_and(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6528    let mut left = parse_expr_cmp(cur, ctx)?;
6529    while eat_op(cur, '&', Some('&')) {
6530        cur.skip_gap();
6531        let right = parse_expr_cmp(cur, ctx)?;
6532        reject_boundary(&lowering_ctx(cur.stmt), &left).map_err(|e| cur.err(e.to_string()))?;
6533        reject_boundary(&lowering_ctx(cur.stmt), &right).map_err(|e| cur.err(e.to_string()))?;
6534        left = Expr::Logical {
6535            op: LogicalOp::And,
6536            left: Box::new(left),
6537            right: Box::new(right),
6538        };
6539    }
6540    Ok(left)
6541}
6542
6543fn parse_expr_cmp(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6544    let left = parse_expr_ord(cur, ctx)?;
6545    let op = if eat_op(cur, '=', Some('=')) {
6546        CompareOp::Eq
6547    } else if eat_op(cur, '!', Some('=')) {
6548        CompareOp::Ne
6549    } else {
6550        return Ok(left);
6551    };
6552    cur.skip_gap();
6553    let right = parse_expr_ord(cur, ctx)?;
6554    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
6555        .map_err(|e| cur.err(e.to_string()))?;
6556    reject_chained_compare(cur, false)?;
6557    Ok(expr)
6558}
6559
6560/// Reject a comparison operator trailing a complete comparison:
6561/// no grammar position continues with one, so the shape always fails —
6562/// loudly here instead of stranding text for a confusing downstream
6563/// error. The equality tier rejects all six (`$a == $b == $c`,
6564/// `$a == $b < $c < $d`); the ordering tier rejects ordering only
6565/// (`$a < $b < $c`), since `$a < $b == $c` is a legitimate equality
6566/// over an ordering result. Probes without consuming.
6567fn reject_chained_compare(cur: &mut Cursor, ordering_only: bool) -> Result<(), TokenError> {
6568    let mut probe = Cursor::expr(cur.toks, cur.stmt);
6569    probe.pos = cur.pos;
6570    probe.skip_gap();
6571    let chained = match probe.toks.get(probe.pos).map(|t| &t.kind) {
6572        Some(TokKind::Punct('<' | '>')) => true,
6573        Some(TokKind::Punct('=' | '!')) => !ordering_only,
6574        _ => false,
6575    };
6576    if chained {
6577        return Err(cur
6578            .err("chained comparison operators need explicit parentheses, e.g. `($a < $b) < $c`"));
6579    }
6580    Ok(())
6581}
6582
6583fn parse_expr_ord(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6584    let left = parse_expr_add(cur, ctx)?;
6585    let op = if eat_op(cur, '<', Some('=')) {
6586        CompareOp::Le
6587    } else if eat_op(cur, '>', Some('=')) {
6588        CompareOp::Ge
6589    } else if eat_op(cur, '<', None) {
6590        CompareOp::Lt
6591    } else if eat_op(cur, '>', None) {
6592        CompareOp::Gt
6593    } else {
6594        return Ok(left);
6595    };
6596    cur.skip_gap();
6597    let right = parse_expr_add(cur, ctx)?;
6598    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
6599        .map_err(|e| cur.err(e.to_string()))?;
6600    reject_chained_compare(cur, true)?;
6601    Ok(expr)
6602}
6603
6604fn parse_expr_add(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6605    let mut left = parse_expr_mul(cur, ctx)?;
6606    loop {
6607        let op = if eat_op(cur, '+', None) {
6608            ArithOp::Add
6609        } else if eat_op(cur, '-', None) {
6610            ArithOp::Sub
6611        } else {
6612            break;
6613        };
6614        cur.skip_gap();
6615        let right = parse_expr_mul(cur, ctx)?;
6616        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
6617            .map_err(|e| cur.err(e.to_string()))?;
6618    }
6619    Ok(left)
6620}
6621
6622fn parse_expr_mul(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6623    let mut left = parse_expr_unary(cur, ctx)?;
6624    loop {
6625        let op = if eat_op(cur, '*', None) {
6626            ArithOp::Mul
6627        } else if eat_op(cur, '/', None) {
6628            ArithOp::Div
6629        } else {
6630            break;
6631        };
6632        cur.skip_gap();
6633        let right = parse_expr_unary(cur, ctx)?;
6634        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
6635            .map_err(|e| cur.err(e.to_string()))?;
6636    }
6637    Ok(left)
6638}
6639
6640/// A `-` opens a bare word (never negation) when gaplessly followed by
6641/// a letter, `_`, or `/` — the `neg_op` lookahead, read off `joint`.
6642fn dash_is_bare(cur: &Cursor) -> bool {
6643    let next = cur.toks.get(cur.pos + 1);
6644    match next {
6645        Some(t) if t.joint => match &t.kind {
6646            TokKind::Word(w) => w
6647                .chars()
6648                .next()
6649                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_'),
6650            TokKind::Punct('/') => true,
6651            _ => false,
6652        },
6653        _ => false,
6654    }
6655}
6656
6657fn parse_expr_unary(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6658    let mut prefixes = Vec::new();
6659    loop {
6660        match cur.toks.get(cur.pos).map(|t| &t.kind) {
6661            Some(TokKind::Punct('!')) => {
6662                cur.pos += 1;
6663                // Each prefix is gap-separated.
6664                cur.skip_gap();
6665                prefixes.push(false);
6666            }
6667            Some(TokKind::Punct('-')) if !dash_is_bare(cur) => {
6668                cur.pos += 1;
6669                cur.skip_gap();
6670                prefixes.push(true);
6671            }
6672            _ => break,
6673        }
6674    }
6675    let mut expr = parse_expr_atom(cur, ctx)?;
6676    // Innermost prefix is closest to the atom: apply in reverse order.
6677    for is_neg in prefixes.into_iter().rev() {
6678        if is_neg {
6679            expr = apply_unary_neg(&lowering_ctx(cur.stmt), expr)
6680                .map_err(|e| cur.err(e.to_string()))?;
6681        } else {
6682            reject_boundary(&lowering_ctx(cur.stmt), &expr).map_err(|e| cur.err(e.to_string()))?;
6683            expr = Expr::Not(Box::new(expr));
6684        }
6685    }
6686    Ok(expr)
6687}
6688
6689/// Identifier charset for `$var` and `.segment` parts. Segments admit
6690/// digits-only too (`$a.0`); anything else ends the key path and errors
6691/// downstream, like the grammar's backtrack to `variable`.
6692fn is_ident_word(w: &str) -> bool {
6693    !w.is_empty() && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
6694}
6695
6696/// One joint `::NAME` tail at `pos` (the first `:`): both colons and
6697/// the name ride gapless, and the name matches [`is_ident_word`].
6698/// Single owner for qualified-`$ALIAS::NAME` matching, so `$` arms
6699/// and bare-word diagnostics cannot drift on jointness or charset.
6700fn match_joint_qualified(toks: &[Tok], pos: usize) -> Option<String> {
6701    let first = matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct(':')))
6702        && toks.get(pos).is_some_and(|t| t.joint);
6703    let second = matches!(
6704        toks.get(pos + 1).map(|t| &t.kind),
6705        Some(TokKind::Punct(':'))
6706    ) && toks.get(pos + 1).is_some_and(|t| t.joint);
6707    let name_tok = toks.get(pos + 2);
6708    let ok = first
6709        && second
6710        && matches!(name_tok.map(|t| &t.kind), Some(TokKind::Word(w)) if is_ident_word(w))
6711        && name_tok.is_some_and(|t| t.joint);
6712    if !ok {
6713        return None;
6714    }
6715    match &name_tok.expect("checked").kind {
6716        TokKind::Word(w) => Some(w.clone()),
6717        _ => unreachable!(),
6718    }
6719}
6720
6721fn is_key_segment(w: &str) -> bool {
6722    !w.is_empty()
6723        && (w.chars().all(|c| c.is_ascii_digit())
6724            || (w
6725                .chars()
6726                .next()
6727                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
6728                && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')))
6729}
6730
6731fn is_env_key(w: &str) -> bool {
6732    !w.is_empty()
6733        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
6734        && w.chars()
6735            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
6736}
6737
6738/// Maximal joint run of words and `-/.'/'` puncts: the bare-word
6739/// shape (which admits `/` anywhere, so `//c`, `/a`, `a/b`, and the
6740/// `/`-`c`-`/` operands of `/*c*/` math all read literally here).
6741/// Callers classify (`true`/`false`/string); the numeric path
6742/// runs first and falls back here on shape/follower mismatch.
6743/// Backslash escapes are arg-position syntax: the bare-word shape admits
6744/// no `\`, so expression runs containing one fail here (never drift
6745/// into a string the grammar rejects).
6746fn expr_bare_run(cur: &mut Cursor, leading_dash: bool) -> Result<String, TokenError> {
6747    let mut out = String::new();
6748    if leading_dash {
6749        match cur.next() {
6750            Some(t) if matches!(&t.kind, TokKind::Punct('-')) => out.push('-'),
6751            _ => return Err(cur.err("missing expression operand")),
6752        }
6753    }
6754    match cur.next() {
6755        Some(t) => match &t.kind {
6756            TokKind::Word(w) => out.push_str(w),
6757            // Leading `/` (operand position only; operators are
6758            // consumed by the tiers before operands parse).
6759            TokKind::Punct('/') => out.push('/'),
6760            _ => return Err(cur.err("missing expression operand")),
6761        },
6762        None => return Err(cur.err("missing expression operand")),
6763    }
6764    loop {
6765        let next = match cur.toks.get(cur.pos) {
6766            Some(t) if t.joint => t,
6767            _ => break,
6768        };
6769        match &next.kind {
6770            TokKind::Word(w) => {
6771                // Abutting words only continue through an operator gap
6772                // the tiers own (`a -b` never fuses); without a joint
6773                // punct between, stop. Since this token IS joint, the
6774                // previous token must have been a bare punct.
6775                out.push_str(w);
6776                cur.pos += 1;
6777            }
6778            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
6779                out.push(*c);
6780                cur.pos += 1;
6781            }
6782            _ => break,
6783        }
6784    }
6785    if out.contains('\\') {
6786        return Err(cur.err("unexpected escape in expression"));
6787    }
6788    Ok(out)
6789}
6790
6791/// Numeric literal head: digit-led word plus joint `.digits` tails.
6792/// Callers apply the separator-shape gate and the follower rule, then
6793/// the shared classifier.
6794fn number_head(cur: &mut Cursor) -> Option<String> {
6795    let first = match cur.toks.get(cur.pos).map(|t| &t.kind) {
6796        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => w.clone(),
6797        _ => return None,
6798    };
6799    let mut text = first;
6800    let mut pos = cur.pos + 1;
6801    loop {
6802        let dot = matches!(
6803            cur.toks.get(pos).map(|t| &t.kind),
6804            Some(TokKind::Punct('.'))
6805        ) && cur.toks.get(pos).is_some_and(|t| t.joint);
6806        let digits = cur.toks.get(pos + 1);
6807        let digits_ok = dot
6808            && matches!(digits.map(|t| &t.kind), Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_'))
6809            && digits.is_some_and(|t| t.joint);
6810        if !digits_ok {
6811            break;
6812        }
6813        text.push('.');
6814        if let Some(TokKind::Word(w)) = digits.map(|t| &t.kind) {
6815            text.push_str(w);
6816        }
6817        pos += 2;
6818    }
6819    Some(text)
6820}
6821
6822/// `_`-separator shape gate mirroring the `numeric_literal` rule:
6823/// digits with single-underscore separators, at most one fraction.
6824fn numeric_shape_ok(text: &str) -> bool {
6825    let mut parts = text.split('.');
6826    let int_part = parts.next().unwrap_or("");
6827    let frac_part = parts.next();
6828    if parts.next().is_some() {
6829        return false;
6830    }
6831    fn run_ok(s: &str) -> bool {
6832        !s.is_empty()
6833            && s.chars().all(|c| c.is_ascii_digit() || c == '_')
6834            && !s.starts_with('_')
6835            && !s.ends_with('_')
6836            && !s.contains("__")
6837    }
6838    run_ok(int_part) && frac_part.is_none_or(run_ok)
6839}
6840
6841/// Follower rule mirroring the `numeric_literal` trailing guard
6842/// (`!(ALNUM | "_" | "." | "/")`): a joint word, `.`, or `/` continues
6843/// into a bare word (`30s`, `1.`, `4/2`); `-`/`+`/operators let the
6844/// number stand for the tiers (`1-2` is `Sub`, like the grammar).
6845fn number_falls_to_bare(cur: &Cursor, consumed: usize) -> bool {
6846    match cur.toks.get(cur.pos + consumed) {
6847        Some(t) if t.joint => matches!(
6848            &t.kind,
6849            TokKind::Word(_) | TokKind::Punct('.') | TokKind::Punct('/')
6850        ),
6851        _ => false,
6852    }
6853}
6854
6855fn parse_expr_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6856    match cur.toks.get(cur.pos).map(|t| &t.kind) {
6857        Some(TokKind::Group {
6858            delim: GroupDelim::Paren,
6859            inner,
6860            ..
6861        }) => {
6862            let inner = inner.clone();
6863            cur.pos += 1;
6864            let mut sub = Cursor::expr(&inner, cur.stmt);
6865            sub.skip_gap_nl();
6866            let expr = parse_expr_or(&mut sub, ctx)?;
6867            sub.skip_gap_nl();
6868            if !sub.done() {
6869                return Err(sub.err("unexpected text in parentheses"));
6870            }
6871            Ok(expr)
6872        }
6873        Some(TokKind::Word(_)) if call_shape_at(cur.toks, cur.pos, false).is_some() => {
6874            let (name, paren) =
6875                call_shape_at(cur.toks, cur.pos, false).ok_or_else(|| cur.err("unreachable"))?;
6876            let inner = match &cur.toks[paren].kind {
6877                TokKind::Group { inner, .. } => inner.clone(),
6878                _ => unreachable!(),
6879            };
6880            cur.pos = paren + 1;
6881            parse_expr_call(name, &inner, cur.stmt, ctx)
6882        }
6883        Some(TokKind::Punct(VAR_SIGIL_CHAR)) => {
6884            cur.pos += 1;
6885            // Atomic `variable`: `$` and the name ride gapless (the
6886            // enclosing rules are compound-atomic).
6887            let base = match cur.next() {
6888                Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
6889                    match &t.kind {
6890                        TokKind::Word(w) => w.clone(),
6891                        _ => unreachable!(),
6892                    }
6893                }
6894                _ => return Err(cur.err("`$` requires a variable name")),
6895            };
6896            let mut keys = Vec::new();
6897            // Qualified immutable read (`$ALIAS::NAME`). Key paths
6898            // never ride qualified names: copy to a local first.
6899            if let Some(name) = match_joint_qualified(cur.toks, cur.pos) {
6900                cur.pos += 3;
6901                if matches!(
6902                    cur.toks.get(cur.pos).map(|t| &t.kind),
6903                    Some(TokKind::Punct('.'))
6904                ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint)
6905                {
6906                    return Err(cur.err(crate::template::qualified_keypath_error()));
6907                }
6908                return Ok(Expr::ConstRef { alias: base, name });
6909            }
6910            loop {
6911                // Key-path dots are gapless too (`~` without `gap`).
6912                let dot = matches!(
6913                    cur.toks.get(cur.pos).map(|t| &t.kind),
6914                    Some(TokKind::Punct('.'))
6915                ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
6916                let seg = cur.toks.get(cur.pos + 1);
6917                let seg_ok = dot
6918                    && matches!(seg.map(|t| &t.kind), Some(TokKind::Word(w)) if is_key_segment(w))
6919                    && seg.is_some_and(|t| t.joint);
6920                if !seg_ok {
6921                    break;
6922                }
6923                if let Some(TokKind::Word(w)) = seg.map(|t| &t.kind) {
6924                    keys.push(w.clone());
6925                }
6926                cur.pos += 2;
6927            }
6928            if keys.is_empty() {
6929                Ok(Expr::Var { name: base })
6930            } else {
6931                Ok(Expr::KeyPath { base, keys })
6932            }
6933        }
6934        Some(TokKind::Word(w)) if w == "env" => {
6935            // `env:KEY` read when the full shape matches gaplessly
6936            // (atomic `env_read`); otherwise a bare word (`env` alone,
6937            // `env:k` lowercase) for the error path, exactly like the
6938            // grammar's mismatch.
6939            let key_ok = matches!(
6940                cur.toks.get(cur.pos + 1).map(|t| &t.kind),
6941                Some(TokKind::Punct(':'))
6942            ) && cur.toks.get(cur.pos + 1).is_some_and(|t| t.joint)
6943                && matches!(
6944                    cur.toks.get(cur.pos + 2).map(|t| &t.kind),
6945                    Some(TokKind::Word(k)) if is_env_key(k)
6946                )
6947                && cur.toks.get(cur.pos + 2).is_some_and(|t| t.joint);
6948            if !key_ok {
6949                return parse_bare_atom(cur, ctx, false);
6950            }
6951            cur.pos += 1;
6952            cur.pos += 1;
6953            match cur.next() {
6954                Some(t) => match &t.kind {
6955                    TokKind::Word(k) => Ok(Expr::Env(k.clone())),
6956                    _ => Err(cur.err("unreachable")),
6957                },
6958                None => Err(cur.err("unreachable")),
6959            }
6960        }
6961        Some(TokKind::Group {
6962            delim: GroupDelim::Bracket,
6963            inner,
6964            ..
6965        }) => {
6966            let inner = inner.clone();
6967            cur.pos += 1;
6968            parse_list_literal(&inner, cur.stmt, ctx)
6969        }
6970        Some(TokKind::Group {
6971            delim: GroupDelim::Brace,
6972            inner,
6973            ..
6974        }) => {
6975            let inner = inner.clone();
6976            cur.pos += 1;
6977            parse_map_or_block(&inner, cur.stmt, ctx)
6978        }
6979        Some(TokKind::Str { text, .. }) => {
6980            let text = text.clone();
6981            cur.pos += 1;
6982            Ok(Expr::Literal(Value::string(text)))
6983        }
6984        Some(TokKind::BlockStr(full)) => {
6985            let full = full.clone();
6986            cur.pos += 1;
6987            Ok(Expr::Literal(Value::string(
6988                crate::command::lower_block_string(&full),
6989            )))
6990        }
6991        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => {
6992            parse_numeric_atom(cur, ctx)
6993        }
6994        Some(TokKind::Word(_)) => {
6995            // Bare `ALIAS::NAME` never reads: without the `$` sigil
6996            // there is no qualified shape, only a bare word followed
6997            // by stray punctuation. Name the `$` form instead of
6998            // stranding the reader on the colons.
6999            if let Some(TokKind::Word(base)) = cur.toks.get(cur.pos).map(|t| &t.kind)
7000                && is_ident_word(base)
7001                && let Some(name) = match_joint_qualified(cur.toks, cur.pos + 1)
7002            {
7003                let base = base.clone();
7004                return Err(cur.err(crate::template::bare_sigil_error(&qualify(&base, &name))));
7005            }
7006            parse_bare_atom(cur, ctx, false)
7007        }
7008        Some(TokKind::Punct('-')) => parse_bare_atom(cur, ctx, true),
7009        Some(TokKind::Punct('/')) => parse_bare_atom(cur, ctx, false),
7010        _ => Err(cur.err("missing expression operand")),
7011    }
7012}
7013
7014/// Bare-word atom with a `-` lead (the caller proved it is not
7015/// negation): consumes the joint `-/.'/'` run for the bare-word
7016/// shape.
7017fn parse_bare_atom(
7018    cur: &mut Cursor,
7019    _ctx: &ParseCtx,
7020    leading_dash: bool,
7021) -> Result<Expr, TokenError> {
7022    let text = expr_bare_run(cur, leading_dash)?;
7023    match text.as_str() {
7024        "true" => Ok(Expr::Literal(Value::bool(true))),
7025        "false" => Ok(Expr::Literal(Value::bool(false))),
7026        _ => Ok(Expr::Literal(Value::string(text))),
7027    }
7028}
7029
7030/// Numeric atom: rejoin dotted tails, apply the shape gate and the
7031/// follower rule, then the shared classifier. Anything failing the
7032/// gate or follower reparses as a bare word (durations, versions,
7033/// paths), exactly like the grammar's numeric-literal-or-bare-word
7034/// order.
7035fn parse_numeric_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7036    let start = cur.pos;
7037    let text = number_head(cur).ok_or_else(|| cur.err("missing expression operand"))?;
7038    let consumed = {
7039        let mut n = 1;
7040        let mut p = start + 1;
7041        while matches!(cur.toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('.')))
7042            && cur.toks.get(p).is_some_and(|t| t.joint)
7043            && matches!(
7044                cur.toks.get(p + 1).map(|t| &t.kind),
7045                Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_')
7046            )
7047            && cur.toks.get(p + 1).is_some_and(|t| t.joint)
7048        {
7049            n += 2;
7050            p += 2;
7051        }
7052        n
7053    };
7054    if !numeric_shape_ok(&text) || number_falls_to_bare(cur, consumed) {
7055        return parse_bare_atom(cur, ctx, false);
7056    }
7057    cur.pos += consumed;
7058    classify_numeric_text(&text).map_err(|msg| cur.err(msg))
7059}
7060
7061/// Full expression with the top-level boundary rejection (mirrors
7062/// `parse_expr`): a stray `UnsignedIntBoundary` that no unary `-`
7063/// consumed is an overflow error.
7064fn parse_expr_checked(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7065    let expr = parse_expr_or(cur, ctx)?;
7066    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
7067        return Err(cur.err("integer overflow: 9223372036854775808 exceeds i64::MAX"));
7068    }
7069    Ok(expr)
7070}
7071
7072/// List literal over a bracket group's contents: the shared bracket
7073/// core (see [`parse_bracket_list`]) in `Expr` mode. Expression
7074/// positions fail loudly instead of missing, so `None` is unreachable.
7075fn parse_list_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7076    parse_bracket_list(inner, stmt, ctx, BracketItems::Expr)
7077        .map(|list| list.expect("expression lists fail loudly, never miss"))
7078}
7079
7080/// Map literal attempt over a brace group's contents: comma-separated
7081/// `key: value` entries with `gap` (never newline) around the colon.
7082/// Any entry failing the shape is not a map: the caller reports the
7083/// deferred block slice (the grammar tries `block` next, which fails
7084/// the same inputs at this stage).
7085/// Marker message for a map entry run that ends without a comma
7086/// where another entry follows. Matched by exact equality in
7087/// [`parse_map_or_block`], never by prefix, so wording changes stay
7088/// local to this const and its one reader.
7089const MISSING_MAP_COMMA_MSG: &str = "missing comma between map entries";
7090
7091fn parse_map_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7092    let mut entries = Vec::new();
7093    // Empty (or blank/comment-only) braces are an empty map.
7094    if inner
7095        .iter()
7096        .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
7097    {
7098        return Ok(Expr::Map(vec![]));
7099    }
7100    for part in split_top_commas(inner) {
7101        let mut sub = Cursor::expr(part, stmt);
7102        sub.skip_gap_nl();
7103        let (key, val) = parse_map_entry(&mut sub, ctx, stmt)?;
7104        sub.skip_gap_nl();
7105        if !sub.done() {
7106            return Err(map_trailing_error(&sub, ctx, stmt));
7107        }
7108        entries.push((key, val));
7109    }
7110    Ok(Expr::Map(entries))
7111}
7112
7113/// One `key: value` map entry: string, block-string, or bare key,
7114/// a colon, then a full checked expression. Every failure reads
7115/// `not a map literal` exactly like the old inline loop, so only
7116/// the trailing rule changes the surface.
7117fn parse_map_entry(
7118    sub: &mut Cursor,
7119    ctx: &ParseCtx,
7120    stmt: usize,
7121) -> Result<(String, Expr), TokenError> {
7122    let key = match sub.toks.get(sub.pos).map(|t| &t.kind) {
7123        Some(TokKind::Str { text, .. }) => {
7124            let key = text.clone();
7125            sub.pos += 1;
7126            key
7127        }
7128        Some(TokKind::BlockStr(full)) => {
7129            let key = crate::command::lower_block_string(full);
7130            sub.pos += 1;
7131            key
7132        }
7133        Some(TokKind::Word(_)) | Some(TokKind::Punct('-')) | Some(TokKind::Punct('/')) => {
7134            map_bare_key(sub)?
7135        }
7136        _ => return Err(sub.err("not a map literal")),
7137    };
7138    sub.skip_gap();
7139    if !sub.eat_punct(':') {
7140        return Err(sub.err("not a map literal"));
7141    }
7142    let val = parse_expr_checked(sub, ctx)?;
7143    reject_boundary(&lowering_ctx(stmt), &val).map_err(|e| sub.err(e.to_string()))?;
7144    Ok((key, val))
7145}
7146
7147/// Trailing content after a complete map entry: stamps the
7148/// offending token and names the likely missing comma when the
7149/// remainder parses as another entry. Anything else keeps the old
7150/// `not a map literal` text. Error-path only.
7151fn map_trailing_error(sub: &Cursor, ctx: &ParseCtx, stmt: usize) -> TokenError {
7152    let (line, col) = sub
7153        .toks
7154        .get(sub.pos)
7155        .map(|t| (t.line, t.col))
7156        .unwrap_or((0, 0));
7157    let mut probe = Cursor::expr(&sub.toks[sub.pos.min(sub.toks.len())..], stmt);
7158    probe.skip_gap_nl();
7159    if parse_map_entry(&mut probe, ctx, stmt).is_ok() {
7160        return TokenError {
7161            stmt,
7162            line,
7163            col,
7164            msg: MISSING_MAP_COMMA_MSG.to_string(),
7165            kind: None,
7166        };
7167    }
7168    sub.err("not a map literal")
7169}
7170
7171/// Bare map key: joint `-/.'/'`-run, mirroring the bare-word charset
7172/// (no bool/numeric classification: keys are always strings).
7173fn map_bare_key(sub: &mut Cursor) -> Result<String, TokenError> {
7174    let mut out = String::new();
7175    if matches!(
7176        sub.toks.get(sub.pos).map(|t| &t.kind),
7177        Some(TokKind::Punct('-'))
7178    ) {
7179        out.push('-');
7180        sub.pos += 1;
7181    }
7182    // Leading `/` reads literally too (the bare-word shape admits `/`
7183    // anywhere: `{/a: 1}`, `{//c: 1}`); the joint loop below
7184    // continues the run.
7185    if matches!(
7186        sub.toks.get(sub.pos).map(|t| &t.kind),
7187        Some(TokKind::Punct('/'))
7188    ) {
7189        out.push('/');
7190        sub.pos += 1;
7191    }
7192    match sub.toks.get(sub.pos).map(|t| &t.kind) {
7193        Some(TokKind::Word(w)) => {
7194            out.push_str(w);
7195            sub.pos += 1;
7196        }
7197        // A leading `/` above already started the run; anything
7198        // else still needs a word head.
7199        _ if !out.is_empty() => {}
7200        _ => return Err(sub.err("not a map literal")),
7201    }
7202    while let Some(t) = sub.toks.get(sub.pos) {
7203        if !t.joint {
7204            break;
7205        }
7206        match &t.kind {
7207            TokKind::Word(w) => {
7208                out.push_str(w);
7209                sub.pos += 1;
7210            }
7211            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
7212                out.push(*c);
7213                sub.pos += 1;
7214            }
7215            _ => break,
7216        }
7217    }
7218    if out.contains('\\') {
7219        return Err(sub.err("unexpected escape in map key"));
7220    }
7221    Ok(out)
7222}
7223
7224/// Map-or-block over a brace group's contents: maps parse literally;
7225/// anything else is an inline block (`Expr::Block` over the body
7226/// steps, scopes unmarked like every braced body).
7227fn parse_map_or_block(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7228    match parse_map_literal(inner, stmt, ctx) {
7229        Ok(map) => Ok(map),
7230        // A detected missing comma is never a block: its `key:`
7231        // remainder cannot parse as a statement (a `name: "a"` line
7232        // fails as `unknown command`), so the block path can only
7233        // misreport it. Surface the map error instead; every other
7234        // map failure keeps the block fallback exactly as before.
7235        Err(e) if e.msg == MISSING_MAP_COMMA_MSG => Err(e),
7236        Err(_) => Ok(Expr::Block(parse_body_steps(inner, stmt, ctx, false)?)),
7237    }
7238}
7239
7240/// Parse one standalone expression from lexed tokens (the
7241/// `parse_expression_str` entry point): a full tier parse with
7242/// top-level boundary rejection and full consumption.
7243pub(crate) fn parse_single_expr(
7244    toks: &[Tok],
7245    stmt: usize,
7246    ctx: &ParseCtx,
7247) -> Result<Expr, TokenError> {
7248    let mut cur = Cursor::expr(toks, stmt);
7249    let expr = parse_expr_checked(&mut cur, ctx)?;
7250    if !cur.done() {
7251        return Err(cur.err("unexpected text in expression"));
7252    }
7253    Ok(expr)
7254}
7255
7256/// Assignment `=`: the first depth-zero `=` neither glued to a
7257/// following `=` (`==`) nor glued after `!`/`<`/`>`/`=` (`!=`, `<=`,
7258/// `>=`, second of `==`). `<>` shape brackets own any `=` inside
7259/// them (field defaults), so LET annotations with defaults find the
7260/// real assignment. Glued-ness reads off the `=`'s own `joint` (gap
7261/// before it) and the follower's (gap after it). Anything else leaves
7262/// the statement bare (`LET $p: PIPE`), exactly where the grammar's
7263/// `"="` match fails.
7264fn find_assign_eq(body: &[Tok]) -> Option<usize> {
7265    let mut depth = 0usize;
7266    for (i, tok) in body.iter().enumerate() {
7267        match &tok.kind {
7268            TokKind::Punct('<') => depth += 1,
7269            TokKind::Punct('>') if depth > 0 => depth -= 1,
7270            TokKind::Punct('=') if depth == 0 => {
7271                let next_eq = body
7272                    .get(i + 1)
7273                    .is_some_and(|t| t.joint && matches!(&t.kind, TokKind::Punct('=')));
7274                let prev_op = tok.joint
7275                    && i > 0
7276                    && matches!(&body[i - 1].kind, TokKind::Punct('!' | '<' | '>' | '='));
7277                if !next_eq && !prev_op {
7278                    return Some(i);
7279                }
7280            }
7281            _ => {}
7282        }
7283    }
7284    None
7285}
7286
7287/// Render a type region joint-aware (`LIST< MAP >` keeps its gaps for
7288/// the shared canonicalizer, exactly like `type_tag.as_str()`).
7289fn render_type_region(toks: &[Tok], stmt: usize) -> Result<String, TokenError> {
7290    let mut out = String::new();
7291    for tok in toks {
7292        // Ridden newlines from multi-line `<...>` shapes carry no
7293        // output, so the shape canonicalizes exactly like one line.
7294        if matches!(&tok.kind, TokKind::Newline) {
7295            continue;
7296        }
7297        if !tok.joint && !out.is_empty() {
7298            out.push(' ');
7299        }
7300        match &tok.kind {
7301            TokKind::Word(w) => out.push_str(w),
7302            TokKind::Punct(c) => out.push(*c),
7303            TokKind::Str { text, quote } => {
7304                out.push(*quote);
7305                out.push_str(text);
7306                out.push(*quote);
7307            }
7308            TokKind::BlockStr(full) => out.push_str(full),
7309            _ => {
7310                return Err(TokenError {
7311                    stmt,
7312                    msg: "malformed type in LET".to_string(),
7313                    line: 0,
7314                    col: 0,
7315                    kind: None,
7316                });
7317            }
7318        }
7319    }
7320    if out.is_empty() {
7321        return Err(TokenError {
7322            stmt,
7323            msg: "LET requires explicit type: LET $var: TYPE = <expr>".to_string(),
7324            line: 0,
7325            col: 0,
7326            kind: None,
7327        });
7328    }
7329    Ok(crate::canonicalize_spelling(&out))
7330}
7331
7332fn expect_dollar_var(cur: &mut Cursor, msg: &str) -> Result<String, TokenError> {
7333    // Atomic `dollar_ident`: no gap between `$` and the name (the
7334    // enclosing statements are compound-atomic, so implicit spacing is
7335    // off and only explicit `gap`s admit whitespace).
7336    match cur.next() {
7337        Some(t) if matches!(&t.kind, TokKind::Punct(VAR_SIGIL_CHAR)) => {}
7338        _ => return Err(cur.err(msg)),
7339    }
7340    match cur.next() {
7341        Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
7342            match &t.kind {
7343                TokKind::Word(w) => Ok(w.clone()),
7344                _ => unreachable!(),
7345            }
7346        }
7347        _ => Err(cur.err(msg)),
7348    }
7349}
7350
7351/// Reject a qualified `$ALIAS::NAME` where a declaration or mutation
7352/// target stands: bindings declare plain locals, and module `CONST`s
7353/// are immutable (reads use `$ALIAS::NAME` in expressions).
7354/// Single owner for the qualified-target gate, shared by the binding
7355/// (`LET`/`CONST`) and reassignment (`$var = <expr>`) heads so all fail
7356/// with one message shape.
7357fn reject_qualified_target(cur: &Cursor, base: &str) -> Result<(), TokenError> {
7358    let first = matches!(
7359        cur.toks.get(cur.pos).map(|t| &t.kind),
7360        Some(TokKind::Punct(':'))
7361    ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
7362    let second = matches!(
7363        cur.toks.get(cur.pos + 1).map(|t| &t.kind),
7364        Some(TokKind::Punct(':'))
7365    ) && cur.toks.get(cur.pos + 1).is_some_and(|t| t.joint);
7366    if first && second {
7367        return Err(cur.err(format!(
7368            "cannot declare or assign ${base}::...: module values read as $ALIAS::NAME in expressions and are never binding targets"
7369        )));
7370    }
7371    Ok(())
7372}
7373
7374/// `LET`/`CONST` body: the keyword is already matched. Returns `None`
7375/// (miss to generic, which fails in lowering like the grammar's
7376/// committed `instruction`) when the shape cannot match any binding
7377/// form: no gapless `$var`, or no `:` after it
7378/// (every form needs `: TYPE`). Past that the shape is committed and
7379/// malformed tails fail loudly. `kw` selects the produced StepKind
7380/// family (`LET` or `CONST`) and the diagnostic spellings.
7381fn parse_let_body(
7382    body: &[Tok],
7383    stmt: usize,
7384    ctx: &ParseCtx,
7385) -> Result<Option<(StepKind, usize)>, TokenError> {
7386    parse_binding_body(body, stmt, ctx, KEYWORD_LET)
7387}
7388
7389/// `CONST` body: same shapes as `LET`, producing the `Const` family.
7390/// Miss semantics mirror [`parse_let_body`].
7391fn parse_const_body(
7392    body: &[Tok],
7393    stmt: usize,
7394    ctx: &ParseCtx,
7395) -> Result<Option<(StepKind, usize)>, TokenError> {
7396    parse_binding_body(body, stmt, ctx, KEYWORD_CONST)
7397}
7398
7399/// Shared `LET`/`CONST` body: the head keyword is already matched.
7400/// `kw` must be `KEYWORD_LET` or `KEYWORD_CONST`. Both take a `$var`
7401/// head; `CONST` additionally requires an uppercase name.
7402/// Single owner for the binding header: the `is_const` flag rides
7403/// straight into [`StepKind::Bind`], so no post-pass flips per form.
7404fn parse_binding_body(
7405    body: &[Tok],
7406    stmt: usize,
7407    ctx: &ParseCtx,
7408    kw: &'static str,
7409) -> Result<Option<(StepKind, usize)>, TokenError> {
7410    use crate::commands::BindRhs;
7411    let is_const = kw == KEYWORD_CONST;
7412    let mut cur = Cursor::expr(body, stmt);
7413    match cur.next() {
7414        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == kw) => {}
7415        _ => return Err(cur.err("unreachable")),
7416    }
7417    // Head: `$var` for both `LET` and `CONST`. `CONST` additionally
7418    // requires an uppercase name (see `validate_const_name`). The
7419    // keyword already committed to a binding, so a malformed head
7420    // fails loudly; only a non-name head misses to generic.
7421    let var = if is_const {
7422        cur.skip_gap();
7423        match cur.toks.get(cur.pos).map(|t| &t.kind) {
7424            Some(TokKind::Punct(VAR_SIGIL_CHAR)) => {
7425                let var = expect_dollar_var(
7426                    &mut cur,
7427                    "CONST requires a `$NAME` head: CONST $NAME: TYPE = ...",
7428                )?;
7429                reject_qualified_target(&cur, &var)?;
7430                validate_const_name(ctx, &cur, &var)?;
7431                var
7432            }
7433            Some(TokKind::Word(_)) => {
7434                return Err(
7435                    cur.err("CONST requires `$`: write CONST $NAME: TYPE = ... (never bare)")
7436                );
7437            }
7438            _ => return Ok(None),
7439        }
7440    } else {
7441        // No `$var`: no binding form can match (miss, never a hard fail).
7442        let var = match expect_dollar_var(&mut cur, &format!("{kw} requires a variable")) {
7443            Ok(var) => var,
7444            Err(_) => return Ok(None),
7445        };
7446        reject_qualified_target(&cur, &var)?;
7447        var
7448    };
7449    // The header allows gaps (comments, never newlines).
7450    cur.skip_gap();
7451    // No `:`: untyped bindings are rejected outright. Every binding is
7452    // typed; the old miss-to-generic path only hid that behind a
7453    // rambling "invalid syntax" message. (FOR already does this.)
7454    let head_example = if is_const { "$NAME" } else { "$var" };
7455    if !cur.eat_punct(':') {
7456        return Err(TokenError {
7457            stmt,
7458            msg: format!("{kw} requires explicit types: {kw} {head_example}: TYPE = <expr>"),
7459            line: 0,
7460            col: 0,
7461            kind: Some(ParseErrorKind::InvalidSyntax {
7462                command: kw.to_string(),
7463            }),
7464        });
7465    }
7466    // Type region runs to the depth-zero assignment `=`; `<>`
7467    // shapes own any `=` inside them (field defaults).
7468    let type_start = cur.pos;
7469    let assign = find_assign_eq(&body[type_start..]).map(|i| i + type_start);
7470    let Some(eq) = assign else {
7471        // Bare `$p: PIPE` mints a fresh pipe and ends with the
7472        // type word (trailing elements loop on, probed); every other
7473        // bare type is a validation error, mirroring the grammar.
7474        if matches!(
7475            body.get(type_start).map(|t| &t.kind),
7476            Some(TokKind::Word(w)) if w == crate::TypeTag::Pipe.name()
7477        ) {
7478            let kind = StepKind::Bind {
7479                var: var.clone(),
7480                decl_type: crate::TypeTag::Pipe.name().to_string(),
7481                is_const,
7482                rhs: BindRhs::Expr(Expr::FreshPipe),
7483            };
7484            return Ok(Some((kind, type_start + 1)));
7485        }
7486        return Err(cur.err(format!(
7487            "{kw} requires an expression: {kw} {head_example}: TYPE = <expr> (only {kw} {head_example}: PIPE omits the initializer)"
7488        )));
7489    };
7490    let decl_type = render_type_region(&body[type_start..eq], stmt)?;
7491    let (kind, rhs_used) = parse_let_rhs(&body[eq + 1..], var, decl_type, stmt, ctx, is_const)?;
7492    Ok(Some((kind, eq + 1 + rhs_used)))
7493}
7494
7495/// Collision gate for `CONST` names: uppercase plus keywords,
7496/// commands, types, and workspace targets. `FUNC` names and host
7497/// functions live in separate namespaces and may share a spelling
7498/// with a private `CONST`.
7499/// Same-scope `LET`/`CONST` duplicates rely on the static gate so
7500/// guard-disjoint declarations stay legal.
7501fn validate_const_name(ctx: &ParseCtx, cur: &Cursor, name: &str) -> Result<(), TokenError> {
7502    let _ = ctx;
7503    // Single gate for the declaration spelling: uppercase plus
7504    // freedom from reserved words (see [`crate::constants`]).
7505    if !crate::constants::is_const_name(name) {
7506        return Err(cur.err(format!("CONST names must be UPPERCASE: got `{name}`")));
7507    }
7508    if crate::commands::is_reserved_const_name(name) {
7509        return Err(cur.err(format!(
7510            "CONST {name} collides with reserved keyword `{name}`"
7511        )));
7512    }
7513    Ok(())
7514}
7515
7516/// LET right-hand side dispatch, mirroring the grammar order
7517/// (`let_async`, then `let_capture`, then `let_statement`):
7518/// `WITH_IO`-led lines branch async/sync like
7519/// `parse_let_async_statement_from_pair`, `ASYNC`-led lines spawn
7520/// tasks, `TIMEOUT`-led lines capture through the wrapper,
7521/// `AWAIT $v` captures, RUN exec-form captures, known commands
7522/// capture through the generic parser (lowering failures fatal,
7523/// exactly like the committed grammar alternative), and anything
7524/// else parses as an expression (unknown leads included). Returns
7525/// the kind and RHS tokens consumed: captures ending in structural
7526/// pairs leave trailing elements for the caller.
7527fn parse_let_rhs(
7528    rhs: &[Tok],
7529    var: String,
7530    decl_type: String,
7531    stmt: usize,
7532    ctx: &ParseCtx,
7533    is_const: bool,
7534) -> Result<(StepKind, usize), TokenError> {
7535    // Leading gap comments vanish like the `=` gap (but a `//`/`#`
7536    // to end of input leaves no expression, failing).
7537    let mut lead = Cursor::expr(rhs, stmt);
7538    lead.skip_gap();
7539    let (rhs, skipped) = (&rhs[lead.pos..], lead.pos);
7540    let head_word = match rhs.first().map(|t| &t.kind) {
7541        Some(TokKind::Word(w)) => Some(w.clone()),
7542        _ => None,
7543    };
7544    // `WITH_IO`-led lines share `let_async_statement` with the
7545    // `ASYNC` forms (the grammar claims every WITH_IO-led LET
7546    // there); shape misses fall through to generic below.
7547    if head_word.as_deref() == Some(KEYWORD_WITH_IO)
7548        && let Some(found) =
7549            try_let_with_io_rhs(rhs, var.clone(), decl_type.clone(), stmt, ctx, is_const)?
7550    {
7551        let (kind, used) = found;
7552        return Ok((kind, skipped + used));
7553    }
7554    // `ASYNC`-led lines (with followers; alone they commit to the
7555    // generic path like the grammar, failing in lowering) spawn
7556    // background tasks. No `WITH_IO` scan here (probed: the LET
7557    // path accepts what statement `ASYNC` rejects).
7558    if head_word.as_deref() == Some(KEYWORD_ASYNC) && rhs.len() > 1 {
7559        let (kind, used) = parse_let_async_rhs(&rhs[1..], var, decl_type, stmt, ctx, is_const)?;
7560        return Ok((kind, skipped + 1 + used));
7561    }
7562    // `TIMEOUT`-led lines capture through the wrapper (shape misses
7563    // fall through to generic, which fails in lowering).
7564    if head_word.as_deref() == Some(KEYWORD_TIMEOUT)
7565        && let Some((kind, used)) = parse_timeout_single(rhs, 0, stmt, ctx)?
7566    {
7567        let span = lowering_ctx(stmt);
7568        crate::commands::reject_async_in_capture(&span, &kind).map_err(|e| TokenError {
7569            stmt,
7570            msg: e.to_string(),
7571            line: 0,
7572            col: 0,
7573            kind: None,
7574        })?;
7575        crate::commands::reject_pipe_stdout_in_capture(&span, &kind).map_err(|e| TokenError {
7576            stmt,
7577            msg: e.to_string(),
7578            line: 0,
7579            col: 0,
7580            kind: None,
7581        })?;
7582        return Ok((
7583            StepKind::Bind {
7584                var,
7585                decl_type,
7586                is_const,
7587                rhs: BindRhs::Capture(Box::new(kind)),
7588            },
7589            skipped + used,
7590        ));
7591    }
7592    // `AWAIT $v` captures the task output (`$`+name ride gapless in
7593    // this atomic position, like the grammar). Anything else
7594    // `AWAIT`-led goes generic below (lowering fails it, probed).
7595    if head_word.as_deref() == Some(KEYWORD_AWAIT)
7596        && rhs.len() == 3
7597        && let (Some(dollar), Some(task)) = (rhs.get(1), rhs.get(2))
7598        && matches!(&dollar.kind, TokKind::Punct(VAR_SIGIL_CHAR))
7599        && task.joint
7600        && let TokKind::Word(task_var) = &task.kind
7601        && is_ident_word(task_var)
7602    {
7603        return Ok((
7604            StepKind::Bind {
7605                var,
7606                decl_type,
7607                is_const,
7608                rhs: BindRhs::Await {
7609                    task_var: task_var.clone(),
7610                },
7611            },
7612            skipped + 3,
7613        ));
7614    }
7615    // RUN exec form captures the structured argv (gapped bracket;
7616    // a joint bracket falls through to generic, which fails it in
7617    // lowering).
7618    if head_word.as_deref() == Some(KEYWORD_RUN)
7619        && matches!(
7620            rhs.get(1).map(|t| (&t.kind, t.joint)),
7621            Some((
7622                TokKind::Group {
7623                    delim: GroupDelim::Bracket,
7624                    ..
7625                },
7626                false
7627            ))
7628        )
7629        && rhs.len() == 2
7630    {
7631        let inner = match &rhs[1].kind {
7632            TokKind::Group { inner, .. } => inner.clone(),
7633            _ => unreachable!(),
7634        };
7635        // Non-map blocks miss the exec shape; fall through below
7636        // (known-command capture, then expression), mirroring the
7637        // grammar's ordered alternatives.
7638        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
7639            let kind =
7640                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
7641            return Ok((
7642                StepKind::Bind {
7643                    var,
7644                    decl_type,
7645                    is_const,
7646                    rhs: BindRhs::Capture(Box::new(kind)),
7647                },
7648                skipped + 2,
7649            ));
7650        }
7651    }
7652    // File `IMPORT ["path" AS ALIAS]` (#115) captures the imported
7653    // pipeline's `RETURN` value like a call (`LET $r: STRING = IMPORT ...`
7654    // lowers to `AssignCapture`): exactly one file entry, no modules.
7655    // Anything else shaped like an import is a hard error; shape misses
7656    // fall through to generic below, which fails them in lowering.
7657    if head_word.as_deref() == Some(KEYWORD_IMPORT)
7658        && let Some((path, alias, used)) = parse_single_file_import(rhs, 0, stmt, ctx)?
7659    {
7660        return Ok((
7661            StepKind::Bind {
7662                var,
7663                decl_type,
7664                is_const,
7665                rhs: BindRhs::Capture(Box::new(StepKind::ImportFile { path, alias })),
7666            },
7667            skipped + used,
7668        ));
7669    }
7670    // Known-command leads capture through the generic parser
7671    // (lowering failures are fatal here, exactly like the committed
7672    // grammar alternative: probed wrapper-alone and `ISOLATED`-led
7673    // shapes error in lowering); unknown leads parse as expressions.
7674    match &head_word {
7675        Some(head) if is_known_command(head) => {
7676            let (cmd, used) = parse_inner_command(rhs, stmt, ctx)?;
7677            let span = lowering_ctx(stmt);
7678            crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| TokenError {
7679                stmt,
7680                msg: e.to_string(),
7681                line: 0,
7682                col: 0,
7683                kind: None,
7684            })?;
7685            crate::commands::reject_pipe_stdout_in_capture(&span, &cmd).map_err(|e| {
7686                TokenError {
7687                    stmt,
7688                    msg: e.to_string(),
7689                    line: 0,
7690                    col: 0,
7691                    kind: None,
7692                }
7693            })?;
7694            // `INHERIT_ENV`-led lines land here (generic): the
7695            // nesting check rejects them (probed).
7696            crate::commands::reject_nested_inherit_env(&span, &cmd).map_err(|e| TokenError {
7697                stmt,
7698                msg: e.to_string(),
7699                line: 0,
7700                col: 0,
7701                kind: None,
7702            })?;
7703            return Ok((
7704                StepKind::Bind {
7705                    var,
7706                    decl_type,
7707                    is_const,
7708                    rhs: BindRhs::Capture(Box::new(cmd)),
7709                },
7710                skipped + used,
7711            ));
7712        }
7713        _ => {}
7714    }
7715    let mut cur = Cursor::expr(rhs, stmt);
7716    let expr = parse_expr_checked(&mut cur, ctx)?;
7717    let used = skipped + cur.pos;
7718    Ok((
7719        StepKind::Bind {
7720            var,
7721            decl_type,
7722            is_const,
7723            rhs: BindRhs::Expr(expr),
7724        },
7725        used,
7726    ))
7727}
7728
7729/// `WITH_IO`-led LET right-hand side, mirroring
7730/// `parse_let_async_statement_from_pair`'s `with_io_command` branch:
7731/// wrapping `ASYNC` binds a pipe-wired background task (multi-step
7732/// blocks fail loudly), wrapping a sync command captures its stdout
7733/// (async bodies and `stdout` pipes fail loudly), and a bare
7734/// bracket fails validation. `None` on shape miss (bad bracket:
7735/// the caller goes generic, which fails in lowering).
7736fn try_let_with_io_rhs(
7737    rhs: &[Tok],
7738    var: String,
7739    decl_type: String,
7740    stmt: usize,
7741    ctx: &ParseCtx,
7742    is_const: bool,
7743) -> Result<Option<(StepKind, usize)>, TokenError> {
7744    let kw = if is_const { KEYWORD_CONST } else { KEYWORD_LET };
7745    let bracket = match rhs.get(1) {
7746        Some(t)
7747            if !t.joint
7748                && matches!(
7749                    &t.kind,
7750                    TokKind::Group {
7751                        delim: GroupDelim::Bracket,
7752                        ..
7753                    }
7754                ) =>
7755        {
7756            t
7757        }
7758        _ => return Ok(None),
7759    };
7760    let inner = match &bracket.kind {
7761        TokKind::Group { inner, .. } => inner.clone(),
7762        _ => unreachable!(),
7763    };
7764    let bindings = match parse_io_bindings(&inner, stmt, ctx)? {
7765        Some(bindings) => bindings,
7766        None => return Ok(None),
7767    };
7768    let fail = |msg: String| TokenError {
7769        stmt,
7770        msg,
7771        line: 0,
7772        col: 0,
7773        kind: None,
7774    };
7775    let rest = &rhs[2..];
7776    let Some(first) = rest.first() else {
7777        // Bare bracket: the grammar's committed validation error.
7778        return Err(fail(format!(
7779            "{kw} $var: TYPE = WITH_IO requires an ASYNC command (e.g. {kw} $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7780        )));
7781    };
7782    if first.joint {
7783        // The inner rides after a `sep`: joint followers miss the
7784        // shape and fail validation like the grammar's bare bracket.
7785        return Err(fail(format!(
7786            "{kw} $var: TYPE = WITH_IO requires an ASYNC command (e.g. {kw} $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7787        )));
7788    }
7789    if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_ASYNC) {
7790        // `WITH_IO [..] ASYNC <single|block>`: the bindings apply
7791        // inside the task thread (same shape as a one-step body
7792        // holding one `WITH_IO` step, which the runtime supports).
7793        // A bare `ASYNC` goes generic and fails in lowering
7794        // (`unknown command: ASYNC`, probed).
7795        let after = &rest[1..];
7796        if after.is_empty() {
7797            // Bare `ASYNC`: the grammar commits to `instruction`
7798            // and lowering fails it (`unknown command: ASYNC`,
7799            // probed); mirror by running generic, staying failed
7800            // even under a lenient dispatcher.
7801            match parse_inner_command(&rest[..1], stmt, ctx) {
7802                Err(e) => return Err(e),
7803                Ok(_) => {
7804                    return Err(fail(format!(
7805                        "{kw} $var: HANDLE<T> = ASYNC requires a body"
7806                    )));
7807                }
7808            }
7809        }
7810        if let Some(second) = after.first()
7811            && matches!(
7812                &second.kind,
7813                TokKind::Group {
7814                    delim: GroupDelim::Brace,
7815                    ..
7816                }
7817            )
7818            && !is_template_brace(second)
7819        {
7820            let brace_inner = match &second.kind {
7821                TokKind::Group { inner, .. } => inner.clone(),
7822                _ => unreachable!(),
7823            };
7824            let body = parse_body_steps(&brace_inner, stmt, ctx, false)?;
7825            if body.len() != 1 {
7826                return Err(fail(format!(
7827                    "{kw} $var: TYPE = WITH_IO [..] ASYNC accepts a single command; use {kw} $var: HANDLE<T> = ASYNC {{ ... }} with WITH_IO inside the block for multi-step tasks"
7828                )));
7829            }
7830            let wrapped = Step {
7831                guard: None,
7832                kind: StepKind::WithIo {
7833                    bindings,
7834                    cmd: Box::new(
7835                        body.into_iter()
7836                            .next()
7837                            .ok_or_else(|| {
7838                                fail("LET $var: HANDLE<T> = ASYNC requires a body".to_string())
7839                            })?
7840                            .kind,
7841                    ),
7842                },
7843                scope_enter: 0,
7844                scope_exit: 0,
7845                line: 0,
7846                col: 0,
7847            };
7848            return Ok(Some((
7849                StepKind::Bind {
7850                    var,
7851                    decl_type,
7852                    is_const,
7853                    rhs: BindRhs::Async(vec![wrapped]),
7854                },
7855                2 + 2,
7856            )));
7857        }
7858        if after.first().is_some_and(|t| t.joint) {
7859            // Joint followers miss the inner `sep`: same validation
7860            // error as the bare bracket.
7861            return Err(fail(
7862                "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7863                    .to_string(),
7864            ));
7865        }
7866        let (cmd, used) = parse_single_inner(
7867            rest,
7868            1,
7869            stmt,
7870            ctx,
7871            InnerRules {
7872                allow_await: false,
7873                allow_with_io: false,
7874            },
7875        )?;
7876        let wrapped = Step {
7877            guard: None,
7878            kind: StepKind::WithIo {
7879                bindings,
7880                cmd: Box::new(cmd),
7881            },
7882            scope_enter: 0,
7883            scope_exit: 0,
7884            line: 0,
7885            col: 0,
7886        };
7887        let kind = StepKind::Bind {
7888            var,
7889            decl_type,
7890            is_const,
7891            rhs: BindRhs::Async(vec![wrapped]),
7892        };
7893        let span = lowering_ctx(stmt);
7894        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7895            stmt,
7896            msg: e.to_string(),
7897            line: 0,
7898            col: 0,
7899            kind: None,
7900        })?;
7901        return Ok(Some((kind, 2 + 1 + used)));
7902    }
7903    if matches!(
7904        &first.kind,
7905        TokKind::Group {
7906            delim: GroupDelim::Brace,
7907            ..
7908        }
7909    ) {
7910        // A brace is no sync command: same validation error (probed).
7911        return Err(fail(format!(
7912            "{kw} $var: TYPE = WITH_IO requires an ASYNC command (e.g. {kw} $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7913        )));
7914    }
7915    // Sync inner: capture with the shared checks (the capture sink
7916    // owns stdout; async never runs inline).
7917    let (cmd, used) = parse_single_inner(
7918        rest,
7919        0,
7920        stmt,
7921        ctx,
7922        InnerRules {
7923            allow_await: false,
7924            allow_with_io: true,
7925        },
7926    )?;
7927    let span = lowering_ctx(stmt);
7928    if crate::commands::has_stdout_pipe(&bindings) {
7929        return Err(fail(format!(
7930            "{kw} capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
7931        )));
7932    }
7933    crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| TokenError {
7934        stmt,
7935        msg: e.to_string(),
7936        line: 0,
7937        col: 0,
7938        kind: None,
7939    })?;
7940    Ok(Some((
7941        StepKind::Bind {
7942            var,
7943            decl_type,
7944            is_const,
7945            rhs: BindRhs::Capture(Box::new(StepKind::WithIo {
7946                bindings,
7947                cmd: Box::new(cmd),
7948            })),
7949        },
7950        2 + used,
7951    )))
7952}
7953
7954/// `ASYNC`-led LET right-hand side (the tokens after `ASYNC`):
7955/// a block or single command becomes the task body. No `WITH_IO`
7956/// scan (probed: this path accepts what statement `ASYNC`
7957/// rejects); nesting still fails loudly through the shared check.
7958fn parse_let_async_rhs(
7959    rest: &[Tok],
7960    var: String,
7961    decl_type: String,
7962    stmt: usize,
7963    ctx: &ParseCtx,
7964    is_const: bool,
7965) -> Result<(StepKind, usize), TokenError> {
7966    let Some(first) = rest.first() else {
7967        return Err(TokenError {
7968            stmt,
7969            msg: "binding $var: HANDLE<T> = ASYNC requires a body".to_string(),
7970            line: 0,
7971            col: 0,
7972            kind: None,
7973        });
7974    };
7975    if matches!(
7976        &first.kind,
7977        TokKind::Group {
7978            delim: GroupDelim::Brace,
7979            ..
7980        }
7981    ) && !is_template_brace(first)
7982    {
7983        let inner = match &first.kind {
7984            TokKind::Group { inner, .. } => inner.clone(),
7985            _ => unreachable!(),
7986        };
7987        let body = parse_body_steps(&inner, stmt, ctx, false)?;
7988        let kind = StepKind::Bind {
7989            var,
7990            decl_type,
7991            is_const,
7992            rhs: BindRhs::Async(body),
7993        };
7994        let span = lowering_ctx(stmt);
7995        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7996            stmt,
7997            msg: e.to_string(),
7998            line: 0,
7999            col: 0,
8000            kind: None,
8001        })?;
8002        return Ok((kind, 1));
8003    }
8004    if first.joint {
8005        return Err(TokenError {
8006            stmt,
8007            msg: "binding $var: HANDLE<T> = ASYNC requires a body".to_string(),
8008            line: 0,
8009            col: 0,
8010            kind: None,
8011        });
8012    }
8013    let (cmd, used) = parse_single_inner(
8014        rest,
8015        0,
8016        stmt,
8017        ctx,
8018        InnerRules {
8019            allow_await: false,
8020            allow_with_io: false,
8021        },
8022    )?;
8023    let kind = StepKind::Bind {
8024        var,
8025        decl_type,
8026        is_const,
8027        rhs: BindRhs::Async(vec![Step {
8028            guard: None,
8029            kind: cmd,
8030            scope_enter: 0,
8031            scope_exit: 0,
8032            line: 0,
8033            col: 0,
8034        }]),
8035    };
8036    let span = lowering_ctx(stmt);
8037    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
8038        stmt,
8039        msg: e.to_string(),
8040        line: 0,
8041        col: 0,
8042        kind: None,
8043    })?;
8044    Ok((kind, used))
8045}
8046
8047fn parse_set_body(
8048    body: &[Tok],
8049    stmt: usize,
8050    ctx: &ParseCtx,
8051) -> Result<(StepKind, usize), TokenError> {
8052    let mut cur = Cursor::expr(body, stmt);
8053    if matches!(
8054        cur.toks.get(cur.pos).map(|t| &t.kind),
8055        Some(TokKind::Punct(VAR_SIGIL_CHAR))
8056    ) {
8057        let var = expect_dollar_var(&mut cur, "mutation requires a variable: $var = <expr>")?;
8058        reject_qualified_target(&cur, &var)?;
8059        // Key paths never serve as mutation targets: without this,
8060        // `$M.a = ...` would drop `.a` when the head jumps to `=`
8061        // below and silently rebind the whole `$M`. Reads use key
8062        // paths in expressions; writes rebind the variable
8063        // (e.g. `$M = MAP_SET($M, "a", 2)`).
8064        if matches!(
8065            cur.toks.get(cur.pos).map(|t| &t.kind),
8066            Some(TokKind::Punct('.'))
8067        ) {
8068            let mut target = sigil_var(&var);
8069            let mut p = cur.pos;
8070            loop {
8071                let dot = matches!(cur.toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('.')));
8072                let word = match cur.toks.get(p + 1).map(|t| &t.kind) {
8073                    Some(TokKind::Word(w)) if is_key_segment(w) => w.clone(),
8074                    _ => break,
8075                };
8076                if !dot {
8077                    break;
8078                }
8079                target.push('.');
8080                target.push_str(&word);
8081                p += 2;
8082            }
8083            return Err(cur.err(format!(
8084                "cannot assign to {target}: key paths read in expressions but are never mutation targets; rebind the variable instead (e.g. {example} = MAP_SET({example}, \"a\", 2))",
8085                example = sigil_var(&var),
8086            )));
8087        }
8088        let assign = find_assign_eq(&body[cur.pos..]).map(|i| i + cur.pos);
8089        let eq = match assign {
8090            Some(eq) => eq,
8091            None => {
8092                return Err(cur.err("mutation requires a variable: $var = <expr>"));
8093            }
8094        };
8095        cur.pos = eq + 1;
8096        cur.skip_gap();
8097        let expr = parse_expr_checked(&mut cur, ctx)?;
8098        return Ok((StepKind::Set { var, expr }, cur.pos));
8099    }
8100    // Bare words are literal text, never variable targets: only
8101    // `$var = <expr>` mutates.
8102    Err(cur.err("mutation requires a variable: $var = <expr>"))
8103}
8104
8105fn parse_return_body(
8106    body: &[Tok],
8107    stmt: usize,
8108    ctx: &ParseCtx,
8109) -> Result<(StepKind, usize), TokenError> {
8110    let mut cur = Cursor::expr(body, stmt);
8111    match cur.next() {
8112        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_RETURN) => {}
8113        _ => return Err(cur.err("unreachable")),
8114    }
8115    if cur.done() {
8116        return Ok((
8117            StepKind::Return {
8118                expr: Box::new(Expr::Literal(Value::string(String::new()))),
8119                is_bare: true,
8120            },
8121            cur.pos,
8122        ));
8123    }
8124    let expr = parse_expr_checked(&mut cur, ctx)?;
8125    Ok((
8126        StepKind::Return {
8127            expr: Box::new(expr),
8128            is_bare: false,
8129        },
8130        cur.pos,
8131    ))
8132}
8133
8134/// Lower one statement to steps through the element loop: the
8135/// statement guard attaches to the first element only (trailing
8136/// elements ride guardless, probed): the pending guard clears after
8137/// the first command token.
8138fn lower_stmt_steps(
8139    stmt: &Stmt,
8140    idx: usize,
8141    ctx: &ParseCtx,
8142    in_block: bool,
8143    mark: bool,
8144) -> Result<Vec<Step>, TokenError> {
8145    let guard = parse_guard_groups(&stmt.guard, idx)?;
8146    // Statement-head braces route here (mid-run braces fail inside
8147    // the element loop): templates and guardless/bare blocks fail
8148    // loudly; guarded braces open guard blocks (top level) or the
8149    // nested quirk (in bodies).
8150    let mut steps = if starts_brace(&stmt.body) {
8151        parse_brace_head(stmt, guard, idx, ctx, in_block, mark)?
8152    } else {
8153        parse_elements(&stmt.body, idx, ctx, guard, in_block)?
8154    };
8155    // Stamp the statement's source position on every directly
8156    // produced step still missing one. Nested body steps were stamped
8157    // by their own statements during recursion, so only direct
8158    // products are claimed here; inner statements keep their own
8159    // lines and columns.
8160    for step in &mut steps {
8161        if step.line == 0 {
8162            step.line = stmt.line;
8163        }
8164        if step.col == 0 {
8165            step.col = stmt.col;
8166        }
8167    }
8168    // Qualify bare placeholder calls (`{{ NAME(args) }}`) through
8169    // the shared static resolver, so templates obey exactly the
8170    // statement-position scope rule. Nested bodies were already
8171    // qualified by their own recursive statements with their own
8172    // frames, so only direct products are visited here. Both
8173    // `Arg::String` fragments (via `walk_raw_strings_mut`) and
8174    // `Expr::Literal` strings (LET/SET/RETURN/call args/list/map
8175    // literals/parenthesized args) are qualified: expression
8176    // positions expand through the same `expand_string` at runtime,
8177    // so they must see the same parse-time rewrite. `WithIo` and
8178    // `AssignCapture` box their inner command directly (no recursive
8179    // statement pass), so the helper descends into them; all other
8180    // bodies were already qualified with their own frames.
8181    // `Step.guards` carry no template text (`Guard::Attr` triples
8182    // evaluated via `guard_allows`, never expanded), so there is
8183    // nothing to qualify there.
8184    let mut failed: Option<TokenError> = None;
8185    for step in &mut steps {
8186        qualify_step_templates(step, ctx, idx, &mut failed);
8187        if failed.is_some() {
8188            break;
8189        }
8190    }
8191    if let Some(err) = failed {
8192        return Err(err);
8193    }
8194    Ok(steps)
8195}
8196
8197/// Qualify one direct statement product plus any boxed `WithIo` /
8198/// `AssignCapture` inner command (same scope frame, never a
8199/// recursive statement pass). Body vectors are skipped: their steps
8200/// were qualified by their own recursive statements.
8201fn qualify_step_templates(
8202    step: &mut Step,
8203    ctx: &ParseCtx,
8204    stmt: usize,
8205    failed: &mut Option<TokenError>,
8206) {
8207    qualify_kind_templates(&mut step.kind, ctx, stmt, failed);
8208}
8209
8210/// Qualify one `StepKind` plus boxed inner commands sharing the
8211/// same scope frame.
8212fn qualify_kind_templates(
8213    kind: &mut StepKind,
8214    ctx: &ParseCtx,
8215    stmt: usize,
8216    failed: &mut Option<TokenError>,
8217) {
8218    kind.walk_raw_strings_mut(&mut |text| {
8219        if failed.is_none() {
8220            match qualify_template_calls(text, ctx, stmt) {
8221                Ok(Some(rewritten)) => *text = rewritten,
8222                Ok(None) => {}
8223                Err(err) => *failed = Some(err),
8224            }
8225        }
8226    });
8227    if failed.is_some() {
8228        return;
8229    }
8230    kind.walk_exprs_mut(&mut |expr| {
8231        if failed.is_some() {
8232            return;
8233        }
8234        expr.walk_mut(&mut |node| {
8235            if failed.is_some() {
8236                return;
8237            }
8238            if let Expr::Literal(value) = node
8239                && let Some(text) = value.as_str()
8240            {
8241                match qualify_template_calls(text, ctx, stmt) {
8242                    Ok(Some(rewritten)) => {
8243                        *value = Value::string(rewritten);
8244                    }
8245                    Ok(None) => {}
8246                    Err(err) => *failed = Some(err),
8247                }
8248            }
8249        });
8250    });
8251    if failed.is_some() {
8252        return;
8253    }
8254    // Boxed single commands share the outer scope frame (no recursive
8255    // statement pass built them): qualify the inner kind directly.
8256    match kind {
8257        StepKind::WithIo { cmd, .. } => {
8258            qualify_kind_templates(cmd, ctx, stmt, failed);
8259        }
8260        StepKind::Bind {
8261            rhs: BindRhs::Capture(cmd),
8262            ..
8263        } => {
8264            qualify_kind_templates(cmd, ctx, stmt, failed);
8265        }
8266        _ => {}
8267    }
8268    if failed.is_some() {
8269        return;
8270    }
8271    // Single-command synthetic bodies share the outer frame: `TIMEOUT 5s
8272    // <cmd>`, `ISOLATED <cmd>`, `ASYNC <cmd>`, and `AssignAsync` wrappers
8273    // build their `body` inline via `parse_single_inner` with no recursive
8274    // `lower_stmt_steps` pass, so their one synthetic step needs this one.
8275    // Brace-delimited bodies are NEVER re-walked here: they were already
8276    // lowered via `parse_body_steps` with their own frames and statement
8277    // indices (mirroring `Expr::walk_mut` skipping `Expr::Block`), and
8278    // re-resolving under the outer frame would corrupt scope isolation
8279    // and error attribution. The match names only the synthetic carriers;
8280    // any other body (If/For/While/FuncDef/RemoteBlock/WithIoBlock) stays
8281    // exactly as its own recursive pass left it.
8282    match kind {
8283        StepKind::Timeout { body, .. }
8284        | StepKind::Isolated { body }
8285        | StepKind::AsyncBlock { body } => {
8286            for step in body.iter_mut() {
8287                if failed.is_some() {
8288                    return;
8289                }
8290                qualify_step_templates(step, ctx, stmt, failed);
8291            }
8292        }
8293        StepKind::Bind { rhs, .. } => match rhs {
8294            BindRhs::Async(body) => {
8295                for step in body.iter_mut() {
8296                    if failed.is_some() {
8297                        return;
8298                    }
8299                    qualify_step_templates(step, ctx, stmt, failed);
8300                }
8301            }
8302            BindRhs::Capture(_) | BindRhs::Expr(_) | BindRhs::Await { .. } => {}
8303        },
8304        _ => {}
8305    }
8306}
8307
8308/// Statement-head `{...}` dispatcher. Template braces fail (the
8309/// grammar strands them); guardless top-level braces fail; detached
8310/// or guardless in-body braces fail (no `block_start` in
8311/// `block_element`); guarded braces open a guard scope at top level
8312/// or mirror the nested quirk formula in bodies. Trailing elements
8313/// loop on guardless outside (like the grammar's continued line).
8314fn parse_brace_head(
8315    stmt: &Stmt,
8316    guard: Option<GuardExpr>,
8317    idx: usize,
8318    ctx: &ParseCtx,
8319    in_block: bool,
8320    mark: bool,
8321) -> Result<Vec<Step>, TokenError> {
8322    let brace = &stmt.body[0];
8323    if is_template_brace(brace) {
8324        return Err(TokenError {
8325            stmt: idx,
8326            msg: "'{' without a pending guard".to_string(),
8327            line: 0,
8328            col: 0,
8329            kind: None,
8330        });
8331    }
8332    let inner = match &brace.kind {
8333        TokKind::Group { inner, .. } => inner.clone(),
8334        _ => unreachable!(),
8335    };
8336    if in_block {
8337        // Attached guarded braces only: pending holds all groups but
8338        // the last (the block's own), mirroring the pair structure.
8339        if guard.is_none() || stmt.brace_detached || stmt.guard.is_empty() {
8340            return Err(TokenError {
8341                stmt: idx,
8342                msg: "unexpected '{' in block body".to_string(),
8343                line: 0,
8344                col: 0,
8345                kind: None,
8346            });
8347        }
8348        let n = stmt.guard.len();
8349        let mut pending = None;
8350        if n > 1 {
8351            pending = parse_guard_groups(&stmt.guard[..n - 1], idx)?;
8352        }
8353        let block_guard = parse_guard_groups(&stmt.guard[n - 1..n], idx)?.ok_or(TokenError {
8354            stmt: idx,
8355            msg: "unexpected '{' in block body".to_string(),
8356            line: 0,
8357            col: 0,
8358            kind: None,
8359        })?;
8360        let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
8361        // Guard-block bodies propagate the ambient marking context
8362        // (top-level nesting marks; wrapper bodies never mark).
8363        // Quirk formula verbatim (including the dropped block guard
8364        // with inner guards, probed).
8365        for s in &mut steps {
8366            let inner_guard = s.guard.take();
8367            s.guard = Some(match (pending.clone(), inner_guard) {
8368                (Some(p), Some(e)) => GuardExpr::all(vec![p, e]),
8369                (Some(p), None) => GuardExpr::all(vec![p, block_guard.clone()]),
8370                (None, Some(e)) => e,
8371                (None, None) => block_guard.clone(),
8372            });
8373        }
8374        // Marking contexts bump each nesting level (probed top-level
8375        // double-block 2/2); wrapper bodies stay 0/0.
8376        // Trailing elements ride outside, unmarked.
8377        if mark {
8378            if let Some(first) = steps.first_mut() {
8379                first.scope_enter += 1;
8380            }
8381            if let Some(last) = steps.last_mut() {
8382                last.scope_exit += 1;
8383            }
8384        }
8385        // Trailing elements loop on guardless outside.
8386        if stmt.body.len() > 1 {
8387            let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
8388            steps.append(&mut rest);
8389        }
8390        return Ok(steps);
8391    }
8392    // Top level: guardless braces fail; guarded braces open a guard
8393    // scope (each step folds outer-then-inner with markers).
8394    let Some(outer) = guard else {
8395        return Err(TokenError {
8396            stmt: idx,
8397            msg: "'{' without a pending guard".to_string(),
8398            line: 0,
8399            col: 0,
8400            kind: None,
8401        });
8402    };
8403    let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
8404    if steps.is_empty() {
8405        return Err(TokenError {
8406            stmt: idx,
8407            msg: "guard block must contain at least one command".to_string(),
8408            line: 0,
8409            col: 0,
8410            kind: None,
8411        });
8412    }
8413    for s in &mut steps {
8414        let inner_guard = s.guard.take();
8415        s.guard = Some(match inner_guard {
8416            Some(e) => GuardExpr::all(vec![outer.clone(), e]),
8417            None => outer.clone(),
8418        });
8419    }
8420    if let Some(first) = steps.first_mut() {
8421        first.scope_enter += 1;
8422    }
8423    if let Some(last) = steps.last_mut() {
8424        last.scope_exit += 1;
8425    }
8426    if stmt.body.len() > 1 {
8427        let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
8428        steps.append(&mut rest);
8429    }
8430    Ok(steps)
8431}
8432
8433/// Parse consecutive elements to end of run (the grammar's
8434/// `element*`): structural pairs (calls, RUN-exec, await/cancel,
8435/// wrapper blocks) end mid-run and trailing elements form following
8436/// steps; instructions and expressions consume greedily to the end.
8437fn parse_elements(
8438    toks: &[Tok],
8439    stmt: usize,
8440    ctx: &ParseCtx,
8441    guard: Option<GuardExpr>,
8442    in_block: bool,
8443) -> Result<Vec<Step>, TokenError> {
8444    let mut steps = Vec::new();
8445    let mut pos = 0;
8446    // Statement guard: consumed by the first element that yields a
8447    // step. `IMPORT` yields none, so the guard leaks to the next
8448    // element (probed).
8449    let mut pending_guard: Option<GuardExpr> = guard;
8450    while pos < toks.len() {
8451        // Trailing gap comments between elements (`} #c`, `F("a")
8452        // /*c*/ ECHO`, `LET $x: INT = 1 //c` — the pair ended, so the
8453        // comment is silent like the grammar, never payload):
8454        // `#` and lexer `Comment` markers run to the run end, `//`
8455        // likewise (line comments eat `;` too, and runs hold no
8456        // newlines), `/* */` balances. Mid-run `#`/`/*` stay payload
8457        // text inside the generic path, which consumes everything
8458        // and never loops back here.
8459        if matches!(&toks[pos].kind, TokKind::Punct('#'))
8460            || matches!(&toks[pos].kind, TokKind::Comment(_))
8461        {
8462            break;
8463        }
8464        if matches!(&toks[pos].kind, TokKind::Punct('/')) && is_comment_open(toks, pos) {
8465            if matches!(
8466                toks.get(pos + 1).map(|t| &t.kind),
8467                Some(TokKind::Punct('/'))
8468            ) {
8469                break;
8470            }
8471            match skip_inline_comment(toks, pos) {
8472                Some(past) => {
8473                    pos = past;
8474                    continue;
8475                }
8476                None => {
8477                    return Err(TokenError {
8478                        stmt,
8479                        msg: "unclosed block comment".to_string(),
8480                        line: 0,
8481                        col: 0,
8482                        kind: None,
8483                    });
8484                }
8485            }
8486        }
8487        // `IMPORT` statements update the import frames; module entries
8488        // emit no step (the guard leaks to the next element, probed,
8489        // unless this is top level, where a guarded module import
8490        // fails), while each file entry emits one `ImportFile` step
8491        // carrying the guard. Shape misses fall through to generic
8492        // (lowering fails them).
8493        if matches!(
8494            toks.get(pos).map(|t| &t.kind),
8495            Some(TokKind::Word(w)) if w == KEYWORD_IMPORT
8496        ) {
8497            // Unified statement form (#115): each entry validates hard
8498            // (unknown modules, bad aliases, templates, remote URLs);
8499            // module entries update the frame and emit no step, file
8500            // and harvest entries emit one step each, in source order.
8501            // A top-level guard on a statement with module entries fails
8502            // like the historical directive; file-only statements consume
8503            // the guard like any other element.
8504            if let Some(((modules, kinds), used)) =
8505                parse_import_statement(toks, pos, stmt, ctx, pending_guard.is_some())?
8506            {
8507                if !modules.is_empty() && !in_block && pending_guard.is_some() {
8508                    return Err(TokenError {
8509                        stmt,
8510                        msg: "IMPORT cannot be guarded".to_string(),
8511                        line: 0,
8512                        col: 0,
8513                        kind: None,
8514                    });
8515                }
8516                // Modules-only statements stay zero-step directives: the
8517                // guard leaks to the next element (probed). Anything with
8518                // file or harvest entries consumes it.
8519                let guard = if kinds.is_empty() {
8520                    None
8521                } else {
8522                    pending_guard.take()
8523                };
8524                for kind in kinds {
8525                    steps.push(Step {
8526                        guard: guard.clone(),
8527                        kind,
8528                        scope_enter: 0,
8529                        scope_exit: 0,
8530                        line: 0,
8531                        col: 0,
8532                    });
8533                }
8534                pos += used;
8535                continue;
8536            }
8537        }
8538        let guard = pending_guard.take();
8539        let (mut got, used) = parse_element_at(toks, pos, stmt, ctx, guard, in_block)?;
8540        if used == 0 {
8541            return Err(TokenError {
8542                stmt,
8543                msg: "element consumed no input".to_string(),
8544                line: 0,
8545                col: 0,
8546                kind: None,
8547            });
8548        }
8549        steps.append(&mut got);
8550        pos += used;
8551    }
8552    Ok(steps)
8553}
8554
8555/// Parse one element at `pos`, returning built steps (guard already
8556/// assigned: `first_guard` for the first, folded per io-block inner
8557/// step) and tokens consumed.
8558fn parse_element_at(
8559    toks: &[Tok],
8560    pos: usize,
8561    stmt: usize,
8562    ctx: &ParseCtx,
8563    first_guard: Option<GuardExpr>,
8564    in_block: bool,
8565) -> Result<(Vec<Step>, usize), TokenError> {
8566    let step = |kind: StepKind| Step {
8567        guard: first_guard.clone(),
8568        kind,
8569        scope_enter: 0,
8570        scope_exit: 0,
8571        line: 0,
8572        col: 0,
8573    };
8574    let head_word = match toks.get(pos).map(|t| &t.kind) {
8575        Some(TokKind::Word(w)) => Some(w.clone()),
8576        _ => None,
8577    };
8578    // Mid-run `{...}` (after a call, wrapper block, ...): the
8579    // grammar strands it (`block_start` needs a pending guard or
8580    // `WITH_IO` wait, both consumed), so fail loudly. Statement-head
8581    // braces route through `lower_stmt_steps`, never here.
8582    if starts_brace(&toks[pos..]) {
8583        return Err(TokenError {
8584            stmt,
8585            msg: "'{' without a pending guard".to_string(),
8586            line: 0,
8587            col: 0,
8588            kind: None,
8589        });
8590    }
8591    // LET/CONST/SET/RETURN heads parse with groups intact, then trailing
8592    // elements loop on (probed `LET $x: INT = 1 ECHO bye`). Binding shape
8593    // misses fall to generic (lowering fails them like a committed
8594    // `instruction` would, e.g. `LET foo`).
8595    if head_word.as_deref() == Some(KEYWORD_LET)
8596        && let Some((kind, used)) = parse_let_body(&toks[pos..], stmt, ctx)?
8597    {
8598        return Ok((vec![step(kind)], used));
8599    }
8600    if head_word.as_deref() == Some(KEYWORD_CONST)
8601        && let Some((kind, used)) = parse_const_body(&toks[pos..], stmt, ctx)?
8602    {
8603        return Ok((vec![step(kind)], used));
8604    }
8605    if matches!(
8606        toks.get(pos).map(|t| &t.kind),
8607        Some(TokKind::Punct(VAR_SIGIL_CHAR))
8608    ) {
8609        let (kind, used) = parse_set_body(&toks[pos..], stmt, ctx)?;
8610        return Ok((vec![step(kind)], used));
8611    }
8612    if head_word.as_deref() == Some(KEYWORD_RETURN) {
8613        let (kind, used) = parse_return_body(&toks[pos..], stmt, ctx)?;
8614        return Ok((vec![step(kind)], used));
8615    }
8616    // Calls route before heads (even known commands take the call
8617    // path with a joint paren, probed `ECHO("hi")`); the call ends
8618    // mid-run and trailing elements loop on (fixes the slice-4a
8619    // divergence, probed).
8620    if call_shape_at(toks, pos, true).is_some() {
8621        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8622        return Ok((vec![step(kind)], used));
8623    }
8624    if let Some(TokKind::Word(base)) = toks.get(pos).map(|t| &t.kind)
8625        && is_ident_word(base)
8626        && match_joint_qualified(toks, pos + 1).is_some()
8627    {
8628        // Qualified calls already returned above; anything else
8629        // starting `ALIAS::NAME` is a binding-target misuse.
8630        return Err(TokenError {
8631            stmt,
8632            msg: "cannot declare or assign ALIAS::NAME: module values read as $ALIAS::NAME in expressions and are never binding targets".to_string(),
8633            line: 0,
8634            col: 0,
8635            kind: None,
8636        });
8637    }
8638    // Block statements (shape misses fall to generic, which fails
8639    // them in lowering like the grammar's committed `instruction`).
8640    // `BREAK`/`CONTINUE` take no args (structural, like the grammar):
8641    // each consumes one token and trailing elements loop on (probed
8642    // `BREAK ECHO hi`); a lone trailing word fails downstream like
8643    // the grammar's committed mismatch.
8644    match head_word.as_deref() {
8645        Some(KEYWORD_BREAK) => {
8646            return Ok((vec![step(StepKind::Break)], 1));
8647        }
8648        Some(KEYWORD_CONTINUE) => {
8649            return Ok((vec![step(StepKind::Continue)], 1));
8650        }
8651        Some(KEYWORD_IF) => {
8652            if let Some((kind, used)) = parse_if_at(toks, pos, stmt, ctx)? {
8653                return Ok((vec![step(kind)], used));
8654            }
8655        }
8656        Some(KEYWORD_SWITCH) => {
8657            if let Some((kind, used)) = parse_switch_at(toks, pos, stmt, ctx)? {
8658                return Ok((vec![step(kind)], used));
8659            }
8660        }
8661        Some(KEYWORD_FOR) => {
8662            if let Some((kind, used)) = parse_for_at(toks, pos, stmt, ctx)? {
8663                return Ok((vec![step(kind)], used));
8664            }
8665        }
8666        Some(KEYWORD_WHILE) => {
8667            if let Some((kind, used)) = parse_while_single(toks, pos, stmt, ctx)? {
8668                return Ok((vec![step(kind)], used));
8669            }
8670        }
8671        Some(KEYWORD_FUNC) => {
8672            if let Some((kind, used)) = parse_func_at(toks, pos, stmt, ctx, false)? {
8673                return Ok((vec![step(kind)], used));
8674            }
8675        }
8676        Some(KEYWORD_REMOTE) => {
8677            if let Some((kind, used)) = parse_remote_single(toks, pos, stmt, ctx)? {
8678                return Ok((vec![step(kind)], used));
8679            }
8680        }
8681        _ => {}
8682    }
8683    // Wrappers (block or single); shape misses fall to generic.
8684    match head_word.as_deref() {
8685        Some(KEYWORD_WITH_IO) => {
8686            return parse_with_io_element(toks, pos, stmt, ctx, first_guard);
8687        }
8688        Some(KEYWORD_TIMEOUT) => {
8689            if let Some((kind, used)) = parse_timeout_single(toks, pos, stmt, ctx)? {
8690                return Ok((vec![step(kind)], used));
8691            }
8692        }
8693        Some(KEYWORD_ISOLATED) => {
8694            if let Some((kind, used)) = parse_isolated_single(toks, pos, stmt, ctx)? {
8695                return Ok((vec![step(kind)], used));
8696            }
8697        }
8698        Some(KEYWORD_FAIL) => {
8699            if let Some((kind, used)) = parse_fail_single(toks, pos, stmt, ctx)? {
8700                return Ok((vec![step(kind)], used));
8701            }
8702        }
8703        Some(KEYWORD_ASYNC) => {
8704            // ASYNC FUNC definition form: prefix, parser records is_async
8705            // with no type-constraint validation (checker owns HANDLE rule).
8706            if matches!(toks.get(pos + 1).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC)
8707                && let Some((kind, used)) = parse_func_at(toks, pos + 1, stmt, ctx, true)?
8708            {
8709                return Ok((vec![step(kind)], 1 + used));
8710            }
8711            if let Some((kind, used)) = parse_async_single(toks, pos, stmt, ctx)? {
8712                return Ok((vec![step(kind)], used));
8713            }
8714        }
8715        _ => {}
8716    }
8717    // AWAIT/CANCEL statements (element level admits the `$` gap,
8718    // probed); heads without `$` go generic (lowering fails the
8719    // rest).
8720    if matches!(
8721        head_word.as_deref(),
8722        Some(KEYWORD_AWAIT) | Some(KEYWORD_CANCEL)
8723    ) && let Some((kind, used)) = parse_await_cancel_at(toks, pos, stmt, false, ctx)?
8724    {
8725        return Ok((vec![step(kind)], used));
8726    }
8727    // `INHERIT_ENV [...]` parses strictly even at element level
8728    // (keys stay exact everywhere; slice 5 adds only the
8729    // prelude-order validation). Shape misses go generic.
8730    if head_word.as_deref() == Some(KEYWORD_INHERIT_ENV)
8731        && let Some((kind, used)) = parse_inherit_env_at(toks, pos, stmt)?
8732    {
8733        return Ok((vec![step(kind)], used));
8734    }
8735    // `EXPORT ...` records names (zero steps) or misses to generic;
8736    // level, guard, and sigil violations fail loudly like the backend.
8737    if head_word.as_deref() == Some(KEYWORD_EXPORT) {
8738        if in_block {
8739            return Err(TokenError {
8740                stmt,
8741                msg: "EXPORT is only allowed at the top level".to_string(),
8742                line: 0,
8743                col: 0,
8744                kind: None,
8745            });
8746        }
8747        if first_guard.is_some() {
8748            return Err(TokenError {
8749                stmt,
8750                msg: "EXPORT cannot be guarded".to_string(),
8751                line: 0,
8752                col: 0,
8753                kind: None,
8754            });
8755        }
8756        if let Some((
8757            ExportNames {
8758                func_names,
8759                type_names,
8760                const_names,
8761            },
8762            used,
8763        )) = parse_export_at(toks, pos, stmt)?
8764        {
8765            for name in &func_names {
8766                for part in name.split(MODULE_SEPARATOR) {
8767                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8768                        .map_err(|e| lower_err(stmt, e))?;
8769                }
8770                // Recording and the duplicate rule live in
8771                // `Exports::insert` (single owner); this loop only
8772                // validates identifier shapes.
8773                if let Err(msg) = ctx
8774                    .exports
8775                    .borrow_mut()
8776                    .insert(ExportKind::Func, name.clone())
8777                {
8778                    return Err(TokenError {
8779                        stmt,
8780                        msg,
8781                        line: 0,
8782                        col: 0,
8783                        kind: Some(ParseErrorKind::Validation {
8784                            command: KEYWORD_EXPORT.to_string(),
8785                        }),
8786                    });
8787                }
8788            }
8789            for name in &type_names {
8790                for part in name.split(MODULE_SEPARATOR) {
8791                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8792                        .map_err(|e| lower_err(stmt, e))?;
8793                }
8794                if let Err(msg) = ctx
8795                    .exports
8796                    .borrow_mut()
8797                    .insert(ExportKind::Type, name.clone())
8798                {
8799                    return Err(TokenError {
8800                        stmt,
8801                        msg,
8802                        line: 0,
8803                        col: 0,
8804                        kind: Some(ParseErrorKind::Validation {
8805                            command: KEYWORD_EXPORT.to_string(),
8806                        }),
8807                    });
8808                }
8809            }
8810            for name in &const_names {
8811                for part in name.split(MODULE_SEPARATOR) {
8812                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8813                        .map_err(|e| lower_err(stmt, e))?;
8814                }
8815                if let Err(msg) = ctx
8816                    .exports
8817                    .borrow_mut()
8818                    .insert(ExportKind::Const, name.clone())
8819                {
8820                    return Err(TokenError {
8821                        stmt,
8822                        msg,
8823                        line: 0,
8824                        col: 0,
8825                        kind: Some(ParseErrorKind::Validation {
8826                            command: KEYWORD_EXPORT.to_string(),
8827                        }),
8828                    });
8829                }
8830            }
8831            return Ok((Vec::new(), used));
8832        }
8833    }
8834    // `TYPE NAME = SHAPE` aliases (zero or one step); level and guard
8835    // violations fail loudly, shape misses fall to generic.
8836    if head_word.as_deref() == Some(KEYWORD_TYPE) {
8837        if in_block {
8838            return Err(TokenError {
8839                stmt,
8840                msg: "TYPE must appear at top level".to_string(),
8841                line: 0,
8842                col: 0,
8843                kind: None,
8844            });
8845        }
8846        if first_guard.is_some() {
8847            return Err(TokenError {
8848                stmt,
8849                msg: "TYPE cannot be guarded".to_string(),
8850                line: 0,
8851                col: 0,
8852                kind: None,
8853            });
8854        }
8855        if let Some((kind, used)) = parse_type_stmt_at(toks, pos, stmt)? {
8856            return Ok((vec![step(kind)], used));
8857        }
8858    }
8859    // Lowercase heads name their uppercase form (the grammar's
8860    // `command_name` mismatch): never a bare unknown-command.
8861    if let Some(head) = head_word.as_deref()
8862        && head.chars().all(|c| c.is_ascii_lowercase())
8863        && let upper = head.to_ascii_uppercase()
8864        && (is_known_command(&upper) || crate::STRUCTURAL_KEYWORDS.contains(&upper.as_str()))
8865    {
8866        return Err(TokenError {
8867            stmt,
8868            msg: format!("command must be uppercase: found `{head}`, expected `{upper}`"),
8869            line: 0,
8870            col: 0,
8871            kind: Some(ParseErrorKind::Syntax),
8872        });
8873    }
8874    // RUN-exec ends mid-run (trailing loops on, probed); generic
8875    // instructions consume everything.
8876    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8877    Ok((vec![step(kind)], used))
8878}
8879
8880/// Element-level `WITH_IO`: a same-run brace (any gap: `]{` works,
8881/// probed) opens the io-block form, wrapping every inner step with
8882/// scope markers; a joint non-brace follower is the pending-guard
8883/// error (the splitter only holds bare brackets); anything else is
8884/// the single form. Shape misses go generic.
8885fn parse_with_io_element(
8886    toks: &[Tok],
8887    pos: usize,
8888    stmt: usize,
8889    ctx: &ParseCtx,
8890    first_guard: Option<GuardExpr>,
8891) -> Result<(Vec<Step>, usize), TokenError> {
8892    // The bracket rides gapped (`sep`); anything else misses the
8893    // shape and generic fails it in lowering.
8894    let bracket = match toks.get(pos + 1) {
8895        Some(t)
8896            if !t.joint
8897                && matches!(
8898                    &t.kind,
8899                    TokKind::Group {
8900                        delim: GroupDelim::Bracket,
8901                        ..
8902                    }
8903                ) =>
8904        {
8905            Some(t)
8906        }
8907        _ => None,
8908    };
8909    let Some(bracket) = bracket else {
8910        // Shape miss: generic fails it in lowering.
8911        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8912        return Ok((
8913            vec![Step {
8914                guard: first_guard,
8915                kind,
8916                scope_enter: 0,
8917                scope_exit: 0,
8918                line: 0,
8919                col: 0,
8920            }],
8921            used,
8922        ));
8923    };
8924    let inner = match &bracket.kind {
8925        TokKind::Group { inner, .. } => inner.clone(),
8926        _ => unreachable!(),
8927    };
8928    let bindings = match parse_io_bindings(&inner, stmt, ctx)? {
8929        Some(bindings) => bindings,
8930        // Shape miss: generic fails it.
8931        None => {
8932            let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8933            return Ok((
8934                vec![Step {
8935                    guard: first_guard,
8936                    kind,
8937                    scope_enter: 0,
8938                    scope_exit: 0,
8939                    line: 0,
8940                    col: 0,
8941                }],
8942                used,
8943            ));
8944        }
8945    };
8946    let rest = pos + 2;
8947    // Same-run brace opens the io-block form (block-expanded
8948    // bindings skip the tty checks: the runtime repeats them).
8949    if let Some(next) = toks.get(rest)
8950        && matches!(
8951            &next.kind,
8952            TokKind::Group {
8953                delim: GroupDelim::Brace,
8954                ..
8955            }
8956        )
8957        && !is_template_brace(next)
8958    {
8959        let brace_inner = match &next.kind {
8960            TokKind::Group { inner, .. } => inner.clone(),
8961            _ => unreachable!(),
8962        };
8963        let mut steps = parse_body_steps(&brace_inner, stmt, ctx, false)?;
8964        if steps.is_empty() {
8965            return Err(TokenError {
8966                stmt,
8967                msg: "WITH_IO block must contain at least one command".to_string(),
8968                line: 0,
8969                col: 0,
8970                kind: None,
8971            });
8972        }
8973        // Every inner step wraps (merging when already wrapped,
8974        // like nested io scopes); the line guard folds into each
8975        // inner guard, inner-first (probed fold order).
8976        for s in &mut steps {
8977            let merged = match std::mem::replace(&mut s.kind, StepKind::Continue) {
8978                StepKind::WithIo {
8979                    bindings: inner_bindings,
8980                    cmd,
8981                } => StepKind::WithIo {
8982                    bindings: crate::commands::merge_bindings(&bindings, &inner_bindings),
8983                    cmd,
8984                },
8985                other => StepKind::WithIo {
8986                    bindings: bindings.clone(),
8987                    cmd: Box::new(other),
8988                },
8989            };
8990            s.kind = merged;
8991            s.guard = crate::commands::and_guard_exprs(s.guard.take(), first_guard.clone());
8992        }
8993        let span = lowering_ctx(stmt);
8994        for s in &steps {
8995            crate::commands::reject_nested_inherit_env(&span, &s.kind).map_err(|e| TokenError {
8996                stmt,
8997                msg: e.to_string(),
8998                line: 0,
8999                col: 0,
9000                kind: None,
9001            })?;
9002        }
9003        if let Some(first) = steps.first_mut() {
9004            first.scope_enter += 1;
9005        }
9006        if let Some(last) = steps.last_mut() {
9007            last.scope_exit += 1;
9008        }
9009        return Ok((steps, rest + 1 - pos));
9010    }
9011    if rest >= toks.len() {
9012        // Unreachable: the splitter holds bare brackets for `{`.
9013        // Kept for body-parsed runs, mirroring the transient node.
9014        return Ok((
9015            vec![Step {
9016                guard: first_guard,
9017                kind: StepKind::WithIoBlock { bindings },
9018                scope_enter: 0,
9019                scope_exit: 0,
9020                line: 0,
9021                col: 0,
9022            }],
9023            2,
9024        ));
9025    }
9026    // A joint follower misses the inner `sep`: the pending wait
9027    // fails exactly like the grammar.
9028    if toks[rest].joint {
9029        return Err(TokenError {
9030            stmt,
9031            msg: "WITH_IO block must be followed by '{'".to_string(),
9032            line: 0,
9033            col: 0,
9034            kind: None,
9035        });
9036    }
9037    // Single form, shared with single-inner (element guards the step).
9038    let (cmd, used) = parse_single_inner(
9039        toks,
9040        rest,
9041        stmt,
9042        ctx,
9043        InnerRules {
9044            allow_await: false,
9045            allow_with_io: true,
9046        },
9047    )?;
9048    let span = lowering_ctx(stmt);
9049    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| TokenError {
9050        stmt,
9051        msg: e.to_string(),
9052        line: 0,
9053        col: 0,
9054        kind: None,
9055    })?;
9056    let kind = StepKind::WithIo {
9057        bindings,
9058        cmd: Box::new(cmd),
9059    };
9060    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
9061        stmt,
9062        msg: e.to_string(),
9063        line: 0,
9064        col: 0,
9065        kind: None,
9066    })?;
9067    Ok((
9068        vec![Step {
9069            guard: first_guard,
9070            kind,
9071            scope_enter: 0,
9072            scope_exit: 0,
9073            line: 0,
9074            col: 0,
9075        }],
9076        2 + used,
9077    ))
9078}
9079
9080/// Shared inner-command parser: statement calls (joint paren, even on
9081/// known commands), RUN exec
9082/// form, and generic instructions. Returns the kind and tokens
9083/// consumed: calls and RUN-exec end mid-run (the caller continues
9084/// past them, like the grammar's `element*`); generic instructions
9085/// consume everything. Wrappers never route here (element and
9086/// single-inner dispatch own them); slice 4b reuses the call/RUN
9087/// arms for trailing elements.
9088fn parse_inner_command(
9089    body: &[Tok],
9090    stmt: usize,
9091    ctx: &ParseCtx,
9092) -> Result<(StepKind, usize), TokenError> {
9093    // Bare `NAME(...)` calls invoke functions with one syntax; the head
9094    // and `(` ride gapless or the shape stays an instruction (which
9095    // fails later as UnknownCommand), exactly like the grammar.
9096    if let Some((call_name, paren)) = call_shape_at(body, 0, true) {
9097        let inner = match &body[paren].kind {
9098            TokKind::Group { inner, .. } => inner.clone(),
9099            _ => unreachable!(),
9100        };
9101        let args = parse_call_args(&inner, stmt, ctx)?;
9102        // Statement-level `INSPECT(...)` resolves like any other call
9103        // (only expression position mints the node); unknown functions
9104        // fail in the shared resolver with identical messages.
9105        if !call_name.contains(MODULE_SEPARATOR) {
9106            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
9107                .map_err(|e| lower_err(stmt, e))?;
9108        }
9109        let qualified = resolve_name(ctx, stmt, &call_name)?;
9110        return Ok((
9111            StepKind::Call {
9112                name: qualified,
9113                args,
9114            },
9115            paren + 1,
9116        ));
9117    }
9118    let head = match body.first().map(|t| &t.kind) {
9119        Some(TokKind::Word(n)) => n.clone(),
9120        _ => {
9121            return Err(TokenError {
9122                stmt,
9123                msg: "statement must open with a command word".to_string(),
9124                line: 0,
9125                col: 0,
9126                kind: None,
9127            });
9128        }
9129    };
9130    // RUN exec form: the list routes structured through `lower` (the
9131    // mock wraps it in `Run`; production maps it to `RunExec`); the
9132    // caller continues past the list, like the grammar. The list
9133    // rides gapped (`sep`): a joint bracket is a hard error, never
9134    // a spliced arg (probed `RUN["a"]`).
9135    if head == KEYWORD_RUN
9136        && matches!(
9137            body.get(1).map(|t| &t.kind),
9138            Some(TokKind::Group {
9139                delim: GroupDelim::Bracket,
9140                ..
9141            })
9142        )
9143    {
9144        if body[1].joint {
9145            return Err(TokenError {
9146                stmt,
9147                msg: "RUN [...] requires a gap after RUN".to_string(),
9148                line: 0,
9149                col: 0,
9150                kind: None,
9151            });
9152        }
9153        let inner = match &body[1].kind {
9154            TokKind::Group { inner, .. } => inner.clone(),
9155            _ => unreachable!(),
9156        };
9157        // Non-map blocks miss the exec shape (the grammar has no
9158        // `block` alternative here); fall through to the shell path
9159        // below, which reads the bracket literally.
9160        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
9161            let kind =
9162                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
9163            return Ok((kind, 2));
9164        }
9165    }
9166    let (tokens, deferred) = build_arg_tokens(&body[1..], stmt, ctx)?;
9167    let lowered = lower_generic_args(&head, tokens, stmt, ctx);
9168    match lowered {
9169        Ok(kind) => {
9170            // Stashed call errors surface only for otherwise well-formed
9171            // statements: the command head owns its syntax, so a malformed
9172            // header keeps its tailored error instead of being masked by an
9173            // argument-position resolution failure.
9174            if let Some(err) = deferred {
9175                return Err(err);
9176            }
9177            Ok((kind, body.len()))
9178        }
9179        Err(lower_err) => {
9180            // Fallback raw strings (`NOPE()` rendered as text) can fail
9181            // argument-shape lowering with a misleading error. The
9182            // stashed unknown-callee error names the real culprit, so
9183            // it wins over every argument-level failure (`Validation`,
9184            // `Syntax`, `InvalidSyntax`, or the `None` classification
9185            // that `ENV`/`EXPAND` lowering uses). Heads owned by a
9186            // statement-header parser (`FUNC`, `LET`, `IF`, `FOR`,
9187            // `WHILE`, `TYPE`, `IMPORT`, `EXPORT`, `REMOTE`, `WITH_IO`)
9188            // keep their lowering `InvalidSyntax`: those parsers miss to
9189            // this path on shape miss (e.g. `FUNC FOO() ECHO hi` has no
9190            // body block), so the lowering error names the malformed
9191            // header while the stashed name is its definiendum, never an
9192            // argument-position call. Every other head is a plain
9193            // command, so a lowering `InvalidSyntax` there is an
9194            // argument-shape failure from the raw-text fallback, and
9195            // the stashed callee names the culprit. Only
9196            // head-identity errors (`UnknownCommand`, `Structural`)
9197            // keep their tailored diagnostic everywhere.
9198            let is_header_syntax = matches!(
9199                head.as_str(),
9200                KEYWORD_FUNC
9201                    | KEYWORD_LET
9202                    | KEYWORD_CONST
9203                    | KEYWORD_IF
9204                    | KEYWORD_SWITCH
9205                    | KEYWORD_FOR
9206                    | KEYWORD_WHILE
9207                    | KEYWORD_TYPE
9208                    | KEYWORD_IMPORT
9209                    | KEYWORD_EXPORT
9210                    | KEYWORD_REMOTE
9211                    | KEYWORD_WITH_IO
9212            ) && matches!(
9213                lower_err.kind,
9214                Some(crate::error::ParseErrorKind::InvalidSyntax { .. })
9215            );
9216            if let Some(deferred_err) = deferred
9217                && !is_header_syntax
9218                && matches!(
9219                    lower_err.kind,
9220                    Some(crate::error::ParseErrorKind::Validation { .. })
9221                        | Some(crate::error::ParseErrorKind::Syntax)
9222                        | Some(crate::error::ParseErrorKind::InvalidSyntax { .. })
9223                        | None
9224                )
9225            {
9226                return Err(deferred_err);
9227            }
9228            Err(lower_err)
9229        }
9230    }
9231}
9232
9233/// Parse a token stream (either lexer) into steps. Markers normalize to
9234/// 0/0 like the fuzz harness; scopes arrive with block slices.
9235pub fn parse_tokens(
9236    toks: &[Tok],
9237    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9238) -> Result<Vec<Step>, TokenError> {
9239    let modules = ModuleTable::default();
9240    let reserved = HashSet::new();
9241    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
9242    parse_tokens_with_ctx(toks, &ctx)
9243}
9244
9245/// Parse with an explicit context (module table for call resolution).
9246/// `parse_tokens` uses empty modules.
9247pub fn parse_tokens_with_ctx(toks: &[Tok], ctx: &ParseCtx) -> Result<Vec<Step>, TokenError> {
9248    let mut out = Vec::new();
9249    *ctx.current_line.borrow_mut() = 1;
9250    let stmts = split_statements(toks, 1)?;
9251    predeclare_forward_funcs(&stmts, ctx);
9252    for (i, s) in stmts.iter().enumerate() {
9253        *ctx.current_line.borrow_mut() = s.line;
9254        out.extend(
9255            lower_stmt_steps(s, i, ctx, false, true).map_err(|e| stamp_pos(e, s.line, s.col))?,
9256        );
9257    }
9258    // Whole-script validations through the shared validators.
9259    // `INHERIT_ENV` prelude order: only leading positions read.
9260    {
9261        let mut seen_non_prelude = false;
9262        for step in &out {
9263            match &step.kind {
9264                StepKind::InheritEnv { .. } => {
9265                    if seen_non_prelude {
9266                        return Err(TokenError {
9267                            stmt: out.len(),
9268                            msg: "INHERIT_ENV must appear before any other commands".to_string(),
9269                            line: 0,
9270                            col: 0,
9271                            kind: None,
9272                        });
9273                    }
9274                }
9275                kind => {
9276                    if crate::commands::contains_inherit_env(kind) {
9277                        return Err(TokenError {
9278                            stmt: out.len(),
9279                            msg: "INHERIT_ENV cannot be nested inside other commands".to_string(),
9280                            line: 0,
9281                            col: 0,
9282                            kind: None,
9283                        });
9284                    }
9285                    // Harvest imports stay prelude: they bind functions
9286                    // and types without executing module bodies, so they
9287                    // neither read nor disturb the inherited environment.
9288                    // File imports execute arbitrary top-level steps on
9289                    // import, so they end the prelude like any other
9290                    // side-effecting command. Host-only IMPORTs emit no
9291                    // step at all, which is why they never tripped this
9292                    // gate.
9293                    if !matches!(kind, StepKind::ImportFuncs { .. }) {
9294                        seen_non_prelude = true;
9295                    }
9296                }
9297            }
9298        }
9299    }
9300    crate::commands::validate_remote_copy_placement(&out, &lowering_ctx(out.len())).map_err(
9301        |e| TokenError {
9302            stmt: out.len(),
9303            msg: e.to_string(),
9304            line: 0,
9305            col: 0,
9306            kind: None,
9307        },
9308    )?;
9309    {
9310        let top: HashSet<String> = ctx.funcs.borrow().first().cloned().unwrap_or_default();
9311        let top_imports: Vec<String> = ctx
9312            .imports
9313            .borrow()
9314            .first()
9315            .cloned()
9316            .unwrap_or_default()
9317            .into_iter()
9318            .map(|(name, _)| name)
9319            .collect();
9320        let mut top_types = HashSet::new();
9321        let mut top_consts = HashSet::new();
9322        for step in &out {
9323            if let StepKind::TypeAlias { name, .. } = &step.kind {
9324                top_types.insert(name.clone());
9325            }
9326            match &step.kind {
9327                StepKind::Bind { var, is_const, .. } if *is_const => {
9328                    top_consts.insert(var.clone());
9329                }
9330                _ => {}
9331            }
9332        }
9333        crate::commands::validate_exports(
9334            &lowering_ctx(out.len()),
9335            &ctx.exports.borrow(),
9336            &top,
9337            &top_types,
9338            &top_consts,
9339            ctx.modules,
9340            &top_imports,
9341        )
9342        .map_err(|e| TokenError {
9343            stmt: out.len(),
9344            msg: e.to_string(),
9345            line: 0,
9346            col: 0,
9347            kind: None,
9348        })?;
9349    }
9350    Ok(out)
9351}
9352
9353// ---- String entry points: lex, lower, collect exports and docs ----
9354
9355/// Source text of a 1-based line. The line just past a trailing
9356/// newline (where unbalanced groups report) reads as empty text so
9357/// caret blocks still render.
9358fn source_line_of(input: &str, line: usize) -> Option<String> {
9359    let count = input.lines().count();
9360    let idx = line.checked_sub(1)?;
9361    if idx < count {
9362        input.lines().nth(idx).map(str::to_string)
9363    } else if idx == count {
9364        Some(String::new())
9365    } else {
9366        None
9367    }
9368}
9369
9370/// Last script line (end-of-script validations blame it).
9371fn last_line(input: &str) -> usize {
9372    input.lines().count().max(1)
9373}
9374
9375/// Convert a lexer failure: low-level syntax kind, exact lexer
9376/// position, and the source line for the caret block. Unclosed groups
9377/// name their opener (no grammar dumps); the closer expectation rides
9378/// along so `expected()` stays informative. A lexer-known kind (an
9379/// unclosed `WITH_IO` bracket) converts verbatim.
9380fn lex_error(input: &str, e: LexError) -> ParseError {
9381    let line = e.line.max(1);
9382    let ctx = match source_line_of(input, line) {
9383        Some(source_line) => SpanContext::full(line, e.col.max(1), e.col.max(1), source_line),
9384        None => SpanContext::line_only(line),
9385    };
9386    if let Some(ParseErrorKind::InvalidSyntax { command }) = e.kind {
9387        // Lexer-known command syntax (an unclosed `WITH_IO` bracket).
9388        return ParseError::invalid_syntax(
9389            &command,
9390            e.msg,
9391            None,
9392            vec!["`]`".to_string()],
9393            None,
9394            &ctx,
9395        );
9396    }
9397    let expected = if e.msg.starts_with("unclosed") {
9398        vec!["`}`".to_string()]
9399    } else {
9400        Vec::new()
9401    };
9402    ParseError::syntax(e.msg, expected, None, &ctx)
9403}
9404
9405/// Convert a backend failure, preserving the dispatcher's error kind
9406/// and completing line/source context the token stream knows. Spans
9407/// open at the statement's start column and cover its whole first line
9408/// (multi-line spans clamp to the start line), so caret blocks render
9409/// for every string-path error.
9410fn token_error(input: &str, e: TokenError) -> ParseError {
9411    let line = if e.line == 0 {
9412        last_line(input)
9413    } else {
9414        e.line
9415    };
9416    let start_col = e.col.max(1);
9417    let ctx = match source_line_of(input, line) {
9418        Some(source_line) => {
9419            let end = source_line.len().max(start_col);
9420            SpanContext::full(line, start_col, end, source_line)
9421        }
9422        None => SpanContext::line_only(line),
9423    };
9424    // Column spans are statement granularity (every error names its
9425    // statement's first column); the caret block still renders.
9426    match e.kind {
9427        Some(crate::error::ParseErrorKind::UnknownCommand { name }) => {
9428            ParseError::unknown_command(&name, e.msg, None, &ctx)
9429        }
9430        Some(crate::error::ParseErrorKind::InvalidSyntax { command }) => {
9431            ParseError::invalid_syntax(&command, e.msg, None, Vec::new(), None, &ctx)
9432        }
9433        Some(crate::error::ParseErrorKind::Validation { command }) => {
9434            ParseError::validation(&command, e.msg, &ctx)
9435        }
9436        Some(crate::error::ParseErrorKind::Syntax) => {
9437            ParseError::syntax(e.msg, Vec::new(), None, &ctx)
9438        }
9439        Some(crate::error::ParseErrorKind::Structural { rule }) => {
9440            ParseError::structural(&rule, e.msg, &ctx)
9441        }
9442        None => ParseError::structural("statement", e.msg, &ctx),
9443    }
9444}
9445
9446/// Shared parse driver: lex, lower with preseeded frames, and collect
9447/// `EXPORT` names (validated at end of parse, forward references
9448/// allowed).
9449fn parse_with_ctx(
9450    input: &str,
9451    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9452    reserved_names: HashSet<String>,
9453    modules: ModuleTable,
9454    preseed_funcs: HashSet<String>,
9455    preseed_imports: Vec<String>,
9456) -> ParseResult<ScriptWithExports> {
9457    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
9458    let ctx = ParseCtx::empty(&lower, &modules, &reserved_names);
9459    // Snippet re-parses seed their base frames so lookup behaves
9460    // identically; snippets never define, only read.
9461    ctx.funcs.borrow_mut()[0].extend(preseed_funcs);
9462    ctx.imports.borrow_mut()[0].extend(preseed_imports.into_iter().map(|name| (name, false)));
9463    let steps = parse_tokens_with_ctx(&toks, &ctx).map_err(|e| token_error(input, e))?;
9464    let mut steps = steps;
9465    stamp_func_docs(input, &mut steps);
9466    Ok(ScriptWithExports {
9467        steps,
9468        exports: ctx.exports.borrow().clone(),
9469    })
9470}
9471
9472/// Steps plus single-file `EXPORT` metadata, before `#` doc stamping.
9473/// Callers needing docs build a [`ParsedScript`] from this.
9474struct ScriptWithExports {
9475    steps: Vec<Step>,
9476    exports: Exports,
9477}
9478
9479/// Parse a script with an unknown host environment.
9480pub fn parse_script(
9481    input: &str,
9482    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9483) -> ParseResult<Vec<Step>> {
9484    Ok(parse_with_ctx(
9485        input,
9486        lower,
9487        HashSet::new(),
9488        ModuleTable::default(),
9489        HashSet::new(),
9490        Vec::new(),
9491    )?
9492    .steps)
9493}
9494
9495/// Parse a snippet with an enclosing parse's visible scope state, so
9496/// re-parsed inner commands (async bodies) resolve calls identically.
9497/// The snippet never defines, only reads: seeds affect lookup alone.
9498pub fn parse_script_with_preseed(
9499    input: &str,
9500    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9501    reserved_names: HashSet<String>,
9502    modules: ModuleTable,
9503    preseed_funcs: HashSet<String>,
9504    preseed_imports: Vec<String>,
9505) -> ParseResult<Vec<Step>> {
9506    Ok(parse_with_ctx(
9507        input,
9508        lower,
9509        reserved_names,
9510        modules,
9511        preseed_funcs,
9512        preseed_imports,
9513    )?
9514    .steps)
9515}
9516
9517/// Parse with a module provenance table so calls resolve statically:
9518/// qualified `MODULE::NAME` checks membership, bare `NAME` resolves through
9519/// `SCRIPT` definitions and `IMPORT`ed modules, and anything else fails at
9520/// parse time instead of at runtime.
9521pub fn parse_script_with_modules(
9522    input: &str,
9523    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9524    reserved_names: HashSet<String>,
9525    modules: ModuleTable,
9526) -> ParseResult<Vec<Step>> {
9527    Ok(parse_script_with_modules_and_exports(input, lower, reserved_names, modules)?.steps)
9528}
9529
9530/// Parse with modules plus single-file `EXPORT` metadata and `#` doc
9531/// comments for top-level `FUNC`s. Used by the MCP host; the linear
9532/// runner keeps using `parse_script_with_modules` and ignores exports.
9533pub fn parse_script_with_modules_and_exports(
9534    input: &str,
9535    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9536    reserved_names: HashSet<String>,
9537    modules: ModuleTable,
9538) -> ParseResult<ParsedScript> {
9539    let ScriptWithExports { steps, exports } = parse_with_ctx(
9540        input,
9541        lower,
9542        reserved_names,
9543        modules,
9544        HashSet::new(),
9545        Vec::new(),
9546    )?;
9547    Ok(ParsedScript {
9548        func_docs: collect_func_docs(input, &steps),
9549        steps,
9550        exports,
9551    })
9552}
9553
9554/// Parse without modules plus `EXPORT` metadata. Used by tests and
9555/// tooling that lower with the shared mock.
9556pub fn parse_script_with_exports(
9557    input: &str,
9558    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9559) -> ParseResult<ParsedScript> {
9560    let ScriptWithExports { steps, exports } = parse_with_ctx(
9561        input,
9562        lower,
9563        HashSet::new(),
9564        ModuleTable::default(),
9565        HashSet::new(),
9566        Vec::new(),
9567    )?;
9568    Ok(ParsedScript {
9569        func_docs: collect_func_docs(input, &steps),
9570        steps,
9571        exports,
9572    })
9573}
9574
9575/// Parse one expression from source text with an empty module scope, for
9576/// tooling that shows lowering without running (docs demos, explain output).
9577/// No imports exist here, so bare function calls fail and qualified calls
9578/// fail against the empty table; only `INSPECT` passes through untouched.
9579/// Arithmetic, comparison, variables, env reads, keypaths, and literals
9580/// lower normally, with literal only subtrees folded before flattening.
9581pub fn parse_expression_str(input: &str) -> ParseResult<Expr> {
9582    // Trailing whitespace lexes unconsumed, so lex the trimmed text:
9583    // otherwise padded but valid input fails the full consumption check.
9584    let trimmed = input.trim();
9585    let toks = lex_str(trimmed).map_err(|e| lex_error(trimmed, e))?;
9586    let modules = ModuleTable::default();
9587    let reserved = HashSet::new();
9588    let lower = crate::commands::lower_command as fn(&str, Vec<Arg>) -> ParseResult<StepKind>;
9589    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
9590    *ctx.current_line.borrow_mut() = 1;
9591    parse_single_expr(&toks, 0, &ctx).map_err(|e| token_error(trimmed, e))
9592}
9593
9594/// Parse one guard expression from source text (a bare `guard_seq`:
9595/// predicates, `not`/`any`/`all`, comma lists), for tooling and tests.
9596pub fn parse_guard_expr_str(input: &str) -> ParseResult<GuardExpr> {
9597    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
9598    parse_single_guard(&toks, 0).map_err(|e| token_error(input, e))
9599}
9600
9601/// Parsed script with single-file `EXPORT` metadata. `steps` is the
9602/// linear execution plan, `exports` the `EXPORT` names in source order
9603/// per kind, and `func_docs` maps top-level `FUNC` base names to
9604/// (summary, docs) collected from the immediately preceding `#`
9605/// comment block.
9606#[derive(Debug, Clone, Default)]
9607pub struct ParsedScript {
9608    pub steps: Vec<Step>,
9609    pub exports: Exports,
9610    pub func_docs: std::collections::HashMap<String, (String, String)>,
9611}
9612
9613/// One `EXPORT` list kind. Single owner for the func/type/const
9614/// distinction, so the duplicate rule and every holder never restate
9615/// the three-way split.
9616#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9617pub enum ExportKind {
9618    Func,
9619    Type,
9620    Const,
9621}
9622
9623/// Single-file `EXPORT` metadata: per-kind names in source order.
9624/// Separate lists (never one mixed vec) so the MCP server never
9625/// confuses a type for a tool, and reads stay kind-addressed.
9626#[derive(Debug, Clone, Default)]
9627pub struct Exports {
9628    pub funcs: Vec<String>,
9629    pub types: Vec<String>,
9630    pub consts: Vec<String>,
9631}
9632
9633impl Exports {
9634    /// Record one `EXPORT` name, enforcing the duplicate rule.
9635    /// Uniqueness is by exported base name for every kind: `EXPORT FOO`
9636    /// and `EXPORT LIB::FOO` name one servable tool, `EXPORT CONST $N`
9637    /// and `EXPORT CONST $A::N` name one read, so the second spelling
9638    /// shapes the same `duplicate EXPORT` instead of silently
9639    /// shadowing. One base name rides exactly one export kind.
9640    /// `Err` carries the `duplicate EXPORT` message unchanged.
9641    pub fn insert(&mut self, kind: ExportKind, name: String) -> Result<(), String> {
9642        let base = crate::base_name(&name);
9643        let clash = [&self.funcs, &self.types, &self.consts]
9644            .iter()
9645            .any(|list| list.iter().any(|e| crate::base_name(e) == base));
9646        if clash {
9647            return Err(format!("duplicate EXPORT `{name}`"));
9648        }
9649        match kind {
9650            ExportKind::Func => self.funcs.push(name),
9651            ExportKind::Type => self.types.push(name),
9652            ExportKind::Const => self.consts.push(name),
9653        }
9654        Ok(())
9655    }
9656}
9657
9658fn collect_func_docs(
9659    input: &str,
9660    steps: &[Step],
9661) -> std::collections::HashMap<String, (String, String)> {
9662    use std::collections::{HashMap, HashSet};
9663    let lines: Vec<&str> = input.lines().collect();
9664    // Top-level FUNC definition lines keyed by base name. Brace depth
9665    // tracks nesting so only depth-0 `FUNC` lines count; the first
9666    // occurrence wins because same-scope duplicates fail at lowering.
9667    let mut def_lines: HashMap<String, usize> = HashMap::new();
9668    let mut seen: HashSet<String> = HashSet::new();
9669    let mut depth: usize = 0;
9670    for (idx, line) in lines.iter().enumerate() {
9671        let trimmed = line.trim_start();
9672        let is_comment = trimmed.starts_with('#');
9673        let is_guard_only = trimmed.starts_with('[');
9674        if !is_comment
9675            && !is_guard_only
9676            && let Some(rest) = strip_func_head(trimmed)
9677            && depth == 0
9678            && !seen.contains(&rest)
9679        {
9680            seen.insert(rest.clone());
9681            def_lines.insert(rest, idx + 1);
9682        }
9683        if !is_comment {
9684            for ch in line.chars() {
9685                if ch == '{' {
9686                    depth = depth.saturating_add(1);
9687                } else if ch == '}' {
9688                    depth = depth.saturating_sub(1);
9689                }
9690            }
9691        }
9692    }
9693    let mut out: HashMap<String, (String, String)> = HashMap::new();
9694    for step in steps {
9695        if let StepKind::FuncDef { name, .. } = &step.kind
9696            && !out.contains_key(name)
9697            && let Some(&line_no) = def_lines.get(name)
9698            && let Some((summary, docs)) = docs_above(&lines, line_no)
9699        {
9700            out.insert(name.clone(), (summary, docs));
9701        }
9702    }
9703    out
9704}
9705
9706/// Stamp `#` doc blocks onto top-level `FUNC` steps, from the same map
9707/// that feeds `func_docs`, so step-carried docs and the sidecar can
9708/// never disagree. Only top-level definitions qualify (same rule as
9709/// collection); nested shadowing keeps `docs: None`.
9710fn stamp_func_docs(input: &str, steps: &mut [Step]) {
9711    let docs = collect_func_docs(input, steps);
9712    for step in steps {
9713        if let StepKind::FuncDef {
9714            name, docs: slot, ..
9715        } = &mut step.kind
9716            && slot.is_none()
9717            && let Some(pair) = docs.get(name)
9718        {
9719            *slot = Some(pair.clone());
9720        }
9721    }
9722}
9723
9724fn strip_func_head(trimmed: &str) -> Option<String> {
9725    let rest = trimmed.strip_prefix(KEYWORD_FUNC)?;
9726    let after = rest.strip_prefix([' ', '\t'])?;
9727    if after.is_empty() {
9728        return None;
9729    }
9730    let name: String = after
9731        .chars()
9732        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
9733        .collect();
9734    if name.is_empty()
9735        || !name
9736            .bytes()
9737            .all(|b| b.is_ascii_uppercase() || b == b'_' || b.is_ascii_digit())
9738    {
9739        return None;
9740    }
9741    if name.starts_with(|c: char| c.is_ascii_digit()) {
9742        return None;
9743    }
9744    Some(name)
9745}
9746
9747fn docs_above(lines: &[&str], line_no: usize) -> Option<(String, String)> {
9748    if line_no <= 1 {
9749        return None;
9750    }
9751    let mut block: Vec<String> = Vec::new();
9752    let mut idx = line_no - 1;
9753    while idx > 0 {
9754        idx -= 1;
9755        let trimmed = lines[idx].trim_start();
9756        if trimmed.is_empty() {
9757            break;
9758        }
9759        if let Some(body) = trimmed.strip_prefix('#') {
9760            let text = body.strip_prefix(' ').unwrap_or(body);
9761            block.push(text.to_string());
9762        } else {
9763            break;
9764        }
9765        if idx == 0 {
9766            break;
9767        }
9768    }
9769    if block.is_empty() {
9770        return None;
9771    }
9772    block.reverse();
9773    let summary = block.first().cloned().unwrap_or_default();
9774    let docs = block.join("\n");
9775    Some((summary, docs))
9776}
9777
9778#[cfg(test)]
9779mod tests {
9780    use super::*;
9781    use crate::test_lower_mock;
9782    use indoc::indoc;
9783
9784    fn lower(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9785        test_lower_mock::lower(name, args)
9786    }
9787
9788    /// Lexer-agreement oracle: both frontends must deliver identical
9789    /// steps through the single backend. `parse_script` is the string
9790    /// entry point; `parse_tokens` runs each lexer's output directly.
9791    fn assert_parity(text: &str) {
9792        let old = crate::parse_script(text, lower)
9793            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9794        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9795        let new = parse_tokens(&toks, lower)
9796            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9797        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9798        #[cfg(feature = "proc-macro-api")]
9799        {
9800            let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
9801            let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
9802            let new = parse_tokens(&toks, lower).expect("token path must parse token script");
9803            assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
9804        }
9805    }
9806
9807    /// String-path-only oracle for shapes `rustc` cannot carry at all
9808    /// (lifetime-like quotes). The backend must still agree there.
9809    fn assert_parity_string_only(text: &str) {
9810        let old = crate::parse_script(text, lower)
9811            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9812        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9813        let new = parse_tokens(&toks, lower)
9814            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9815        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9816    }
9817
9818    #[test]
9819    fn token_and_string_paths_agree_on_wrappers() {
9820        // Single-command wrappers, io-blocks, await/cancel,
9821        // LET wrapper forms — three-way agreement per script.
9822        for text in [
9823            "WITH_IO [stdout=$p] ECHO hi",
9824            "WITH_IO [stdin=$p] ECHO hi",
9825            "WITH_IO [stdin] ECHO hi",
9826            "WITH_IO [stdout] ECHO hi",
9827            "WITH_IO [stdin=$p, stdout=$q] ECHO hi",
9828            "WITH_IO [stdin=$p, stdin=$q] ECHO hi",
9829            "WITH_IO [tty] RUN echo hi",
9830            "WITH_IO [tty, rows=40, cols=100] RUN echo hi",
9831            "WITH_IO [rows=40, cols=100, tty] RUN echo hi",
9832            "WITH_IO [stdin =$p] ECHO hi",
9833            "WITH_IO [stdin= $p] ECHO hi",
9834            "WITH_IO [ stdin=$p ] ECHO hi",
9835            "WITH_IO [\nstdin=$p\n] ECHO hi",
9836            "WITH_IO [stdin=$p\n, stdout=$q] ECHO hi",
9837            "WITH_IO [stdout=$p] ASYNC ECHO hi",
9838            "WITH_IO [stdin=$p] WITH_IO [stderr=$e] ECHO hi",
9839            "WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
9840            "WITH_IO [stdin=$p] ISOLATED ECHO hi",
9841            "WITH_IO [stdin=$p] CANCEL $t",
9842            "WITH_IO [stdin=$p] CANCEL $t ECHO bye",
9843            "WITH_IO [stdin=$p] { ECHO hi }",
9844            "WITH_IO [stdin=$p]\n{ ECHO hi }",
9845            "WITH_IO [stdin=$p]; { ECHO hi }",
9846            "WITH_IO [stdin=$p]{ ECHO hi }",
9847            "WITH_IO [stdin=$p] { ECHO a\nECHO b }",
9848            "WITH_IO [stdin=$p] { ECHO hi } ECHO bye",
9849            "WITH_IO [rows=40] { ECHO hi }",
9850            "WITH_IO [tty] { ECHO hi }",
9851            "WITH_IO [stdin=$p] { WITH_IO [stderr=$e] ECHO hi }",
9852            "TIMEOUT 10s ECHO hi",
9853            "TIMEOUT 10 ECHO hi",
9854            "TIMEOUT 500ms ECHO hi",
9855            "TIMEOUT 5m ECHO hi",
9856            "TIMEOUT 2h ECHO hi",
9857            "TIMEOUT $d ECHO hi",
9858            "TIMEOUT \"10s\" ECHO hi",
9859            "TIMEOUT \"30 s\" ECHO hi",
9860            "TIMEOUT {{ $d }} ECHO hi",
9861            "TIMEOUT 10s AWAIT $t",
9862            "TIMEOUT 10s CANCEL $t",
9863            "TIMEOUT 10s AWAIT $t ECHO bye",
9864            "TIMEOUT 10s CANCEL $t ECHO bye",
9865            "TIMEOUT 10s { ECHO hi }",
9866            "TIMEOUT 10s {\nECHO hi\n}",
9867            "TIMEOUT 10s { ECHO hi } ECHO bye",
9868            "TIMEOUT 10s { ECHO hi } TIMEOUT 5s ECHO bye",
9869            "TIMEOUT 10s TIMEOUT 5s ECHO hi",
9870            "TIMEOUT 10s { ECHO a\nECHO b }",
9871            "TIMEOUT 10s ECHO hi extra",
9872            "ISOLATED ECHO hi",
9873            "ISOLATED { ECHO hi }",
9874            "ISOLATED { ECHO hi } ECHO bye",
9875            "ISOLATED AWAIT $t",
9876            "ISOLATED INHERIT_ENV [M]",
9877            "ISOLATED { INHERIT_ENV [M] }",
9878            "ISOLATED { INHERIT_ENV [MODE]\nECHO hi }",
9879            "ASYNC ECHO hi",
9880            "ASYNC { ECHO hi }",
9881            "ASYNC{ECHO hi}",
9882            "ASYNC { ECHO a\nECHO b }",
9883            "ASYNC { ECHO hi } ECHO bye",
9884            "ASYNC CANCEL $t",
9885            "ASYNC CANCEL $t ECHO bye",
9886            "AWAIT $t",
9887            "AWAIT$t",
9888            "AWAIT $ t",
9889            "AWAIT $T",
9890            "AWAIT $t2",
9891            "AWAIT $_t",
9892            "CANCEL $t",
9893            "CANCEL$t",
9894            "CANCEL $ t",
9895            "AWAIT $t ECHO bye",
9896            "CANCEL $t ECHO bye",
9897            "AWAIT $t AWAIT $u",
9898            "AWAIT $t\nECHO bye",
9899            "LET $t: HANDLE = ASYNC ECHO hi",
9900            "LET $t: HANDLE = ASYNC { ECHO hi }",
9901            "LET $t: HANDLE = ASYNC { ECHO hi } ECHO bye",
9902            "LET $a: STRING = ASYNC ECHO hi",
9903            "LET $t: HANDLE = ASYNC { WITH_IO [stdin=$p] ECHO hi }",
9904            "LET $w: STRING = WITH_IO [stdin=$p] ASYNC ECHO hi",
9905            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC ECHO hi",
9906            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi }",
9907            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi } ECHO bye",
9908            "LET $x: STRING = WITH_IO [stdin=$p] ECHO hi",
9909            "LET $x: STRING = WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
9910            "LET $x: STRING = TIMEOUT 10s ECHO hi",
9911            "LET $x: STRING = TIMEOUT 10s { ECHO hi }",
9912            "LET $x: STRING = TIMEOUT 10s ECHO hi ECHO bye",
9913            "LET $o: STRING = AWAIT $t",
9914            "LET $p: PIPE ECHO bye",
9915            "TIMEOUT 10s WITH_IO [stdin=$p]",
9916            "TIMEOUT 10s WITH_IO [stdin=$p]ECHO hi",
9917            "ISOLATED INHERIT_ENV [A, B]",
9918            "ISOLATED INHERIT_ENV [A-B]",
9919            "TIMEOUT 10s { [os:linux] ECHO hi }",
9920            "ASYNC { [os:linux] ECHO hi }",
9921            "ISOLATED { [os:linux] ECHO hi }",
9922            "[os:linux] WITH_IO [stdin=$p]\n{ ECHO hi }",
9923            "LET $x: INT = 1 ECHO bye",
9924            "CANCEL $t LET $x: INT = 1",
9925            "CANCEL $t $x = 1",
9926            "CANCEL $t RETURN \"hi\"",
9927            "TIMEOUT 10s { ECHO hi } LET $x: INT = 1",
9928            "RUN [\"a\"] ECHO bye",
9929            "[os:linux] AWAIT $t",
9930            "[os:linux] TIMEOUT 10s { ECHO hi } ECHO bye",
9931            "[os:linux] ASYNC CANCEL $t ECHO bye",
9932            "[os:linux] WITH_IO [stdin=$p] { [os:macos] ECHO hi }",
9933        ] {
9934            assert_parity(text);
9935        }
9936    }
9937
9938    #[test]
9939    fn token_and_string_paths_agree_on_blocks() {
9940        // Slice 5: `IF`/`FOR`/`WHILE`/`FUNC` with inline and
9941        // cross-newline `ELSE` chains, guard blocks (top-level and
9942        // nested quirk), and multi-element trailing — three-way
9943        // agreement per script.
9944        for text in [
9945            "IF true { ECHO hi }",
9946            "IF $x { ECHO hi } ELSE { ECHO bye }",
9947            "IF true { ECHO a } ELSE IF false { ECHO b } ELSE { ECHO c }",
9948            "IF true{ ECHO hi }",
9949            "IF true { ECHO hi } ECHO bye",
9950            "IF true { ECHO hi }\nELSE { ECHO bye }",
9951            "IF true { ECHO hi }\nELSE IF false { ECHO b }\nELSE { ECHO c }",
9952            "IF true { ECHO hi } //c\nELSE { ECHO bye }",
9953            "IF true { ECHO hi } #c\nELSE { ECHO bye }",
9954            "IF true { ECHO hi }//c\nELSE { ECHO bye }",
9955            "IF true { ECHO hi } /*c*/ ELSE { ECHO bye }",
9956            "IF true { ECHO hi } /*c1*/ /*c2*/\nELSE { ECHO bye }",
9957            "IF true { /*c*/ ECHO hi }",
9958            "IF true { [os:linux] ECHO hi }",
9959            "TIMEOUT 10s { IF true { ECHO hi } }",
9960            "TIMEOUT 10s { IF true { ECHO hi }\nELSE { ECHO bye } }",
9961            "FOR $x: INT IN [1] { ECHO hi }",
9962            "FOR $k: STRING, $v: INT IN $m { ECHO hi }",
9963            "FOR $k: INT IN [1] { ECHO hi }",
9964            "FOR $x: INT IN [1]{ ECHO hi }",
9965            "FOR $x: MAP<name: STRING> IN [1] { ECHO hi }",
9966            "FOR $x: INT IN [1] { ECHO hi } ECHO bye",
9967            "WHILE true { ECHO hi }",
9968            "WHILE $x { ECHO hi }",
9969            "WHILE true{ ECHO hi }",
9970            "TIMEOUT 10s WHILE true { ECHO hi }",
9971            "ASYNC WHILE true { ECHO hi }",
9972            "FUNC FOO(): INT { RETURN 1 }",
9973            "FUNC FOO(): INT { RETURN 1 }",
9974            "FUNC FOO($x: INT): INT { RETURN $x }",
9975            "FUNC FOO($x: INT, $y: STRING): INT { RETURN $x }",
9976            "FUNC FOO(): INT { FUNC FOO(): INT { RETURN 1 } }",
9977            "FUNC FOO(): INT { RETURN 1 }\nFUNC BAR(): VOID { FOO() }\nBAR()",
9978            "TYPE PERSON = MAP<name: STRING>",
9979            "TYPE A=B",
9980            "TYPE A = B | C",
9981            "TYPE A = B\nTYPE A = C",
9982            "INHERIT_ENV [A]\nECHO hi",
9983            "[os:linux] INHERIT_ENV [M]",
9984            "INHERIT_ENV [A]\nINHERIT_ENV [B]\nECHO hi",
9985            "ISOLATED INHERIT_ENV [M]",
9986            "ISOLATED { INHERIT_ENV [M] }",
9987            "ISOLATED INHERIT_ENV [A, B]",
9988            "ISOLATED INHERIT_ENV [A-B]",
9989            "REMOTE prod { ECHO hi }",
9990            "REMOTE prod [$v] { ECHO hi }",
9991            "REMOTE prod [$v, env:E] { ECHO hi }",
9992            "REMOTE prod [] { ECHO hi }",
9993            "REMOTE prod[$v] { ECHO hi }",
9994            "REMOTE prod [$v]{ ECHO hi }",
9995            "REMOTE prod{ ECHO hi }",
9996            "REMOTE  prod  { ECHO hi }",
9997            "REMOTE prod [$v, $v] { ECHO hi }",
9998            "REMOTE prod { ECHO hi } ECHO bye",
9999            "TIMEOUT 10s REMOTE prod { ECHO hi }",
10000            "ASYNC REMOTE prod [$v] { ECHO hi }",
10001            "[os:linux] { ECHO hi }",
10002            "[os:linux]\n{ ECHO hi }",
10003            "[os:linux] { [os:macos] ECHO hi }",
10004            "[os:linux] { [os:macos] ECHO hi\nECHO bye }",
10005            "[os:linux] { [os:macos] { ECHO hi } }",
10006            "TIMEOUT 10s { [os:linux] { [os:macos] ECHO hi } }",
10007            "TIMEOUT 10s { [os:linux] [os:windows] { ECHO hi } }",
10008            "TIMEOUT 10s { [os:linux] { ECHO hi } ECHO bye }",
10009            "LET $x: INT = 1 ECHO bye",
10010            KEYWORD_BREAK,
10011            KEYWORD_CONTINUE,
10012            "BREAK ECHO hi",
10013            "FOR $x: INT IN [1] { BREAK }",
10014            "LET $b: STRING = { RETURN \"hi\" }",
10015            "ECHO { RETURN \"hi\" }",
10016            "RUN [{ RETURN \"hi\" }]",
10017            "[not(env:FOO)] WRITE x",
10018            "[\nnot(env:FOO)\n] WRITE x",
10019            "WRITE env.txt \"{{ env:GREETING }}\"",
10020            "CANCEL $t LET $x: INT = 1",
10021            "RUN [\"a\"] ECHO bye",
10022        ] {
10023            assert_parity(text);
10024        }
10025    }
10026
10027    #[test]
10028    fn multi_line_generics_match_single_line_shape() {
10029        // Multi-line `<...>` shapes parse, and canonicalize exactly
10030        // like their single-line spelling.
10031        for (single, multi) in [
10032            (
10033                "TYPE R = MAP<name: STRING, value: INT>",
10034                "TYPE R = MAP<name: STRING,\nvalue: INT>",
10035            ),
10036            (
10037                "TYPE R = MAP<name: STRING, value: LIST<INT>>",
10038                "TYPE R = MAP<name: STRING,\nvalue: LIST<INT>>",
10039            ),
10040            (
10041                "TYPE R = MAP<name: STRING, value: INT>",
10042                "TYPE R = MAP<\nname: STRING,\nvalue: INT\n>",
10043            ),
10044            (
10045                "LET $m: MAP<name: STRING, value: INT> = {}",
10046                "LET $m: MAP<name: STRING,\nvalue: INT> = {}",
10047            ),
10048            (
10049                "FOR $x: LIST<INT> IN [1] { ECHO hi }",
10050                "FOR $x: LIST<\nINT> IN [1] { ECHO hi }",
10051            ),
10052            ("TYPE R = MAP<x: A | B>", "TYPE R = MAP<x: A |\nB>"),
10053        ] {
10054            assert_parity(multi);
10055            let want = crate::parse_script(single, lower)
10056                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
10057            let got = crate::parse_script(multi, lower)
10058                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
10059            assert_eq!(
10060                got, want,
10061                "multi-line must canonicalize like one line: {multi:?}"
10062            );
10063        }
10064    }
10065
10066    #[test]
10067    fn type_field_defaults_parse_to_canonical_targets() {
10068        // Token-level regression: `= literal` tails belong to the
10069        // field (floats lex as three tokens), and the statement
10070        // target canonicalizes exactly like the spelling parser.
10071        for (text, want) in [
10072            ("TYPE F = MAP<retries: INT = 2>", "MAP<retries: INT = 2>"),
10073            ("TYPE F = MAP<retries: INT=-2>", "MAP<retries: INT = -2>"),
10074            (
10075                "TYPE F = MAP<ratio: FLOAT = 2.5>",
10076                "MAP<ratio: FLOAT = 2.5>",
10077            ),
10078            ("TYPE F = MAP<on: BOOL = true>", "MAP<on: BOOL = true>"),
10079            (
10080                "TYPE F = MAP<model: STRING = \"gpt-4\">",
10081                "MAP<model: STRING = \"gpt-4\">",
10082            ),
10083            (
10084                "TYPE F = MAP<k: STRING = \"d\", n: INT = 3>",
10085                "MAP<k: STRING = \"d\", n: INT = 3>",
10086            ),
10087        ] {
10088            assert_parity(text);
10089            let steps = crate::parse_script(text, lower)
10090                .unwrap_or_else(|e| panic!("default spelling must parse {text:?}: {e}"));
10091            let target = steps
10092                .iter()
10093                .find_map(|s| match &s.kind {
10094                    StepKind::TypeAlias { target, .. } => Some(target.clone()),
10095                    _ => None,
10096                })
10097                .expect("TYPE alias step");
10098            assert_eq!(target, want, "canonical target for {text:?}");
10099        }
10100    }
10101
10102    #[test]
10103    fn multi_line_run_exec_matches_single_line_shape() {
10104        // `RUN [...]` rides the shared bracket core, so a wrapped exec
10105        // list parses exactly like its single-line spelling (and agrees
10106        // across lexer frontends).
10107        for (single, multi) in [
10108            ("RUN [\"echo\", \"hi\"]", "RUN [\"echo\",\n\"hi\"]"),
10109            ("RUN [\"echo\", \"hi\"]", "RUN [\n\"echo\",\n\"hi\"\n]"),
10110            (
10111                "LET $o: STRING = RUN [\"echo\", \"hi\"]",
10112                "LET $o: STRING = RUN [\"echo\",\n\"hi\"]",
10113            ),
10114        ] {
10115            assert_parity(multi);
10116            let want = crate::parse_script(single, lower)
10117                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
10118            let got = crate::parse_script(multi, lower)
10119                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
10120            assert_eq!(
10121                got, want,
10122                "multi-line must canonicalize like one line: {multi:?}"
10123            );
10124        }
10125    }
10126
10127    #[test]
10128    fn untyped_let_fails_in_every_rhs_shape() {
10129        // The everything-typed rule: a missing `:` is a hard error
10130        // carrying the explicit-types message, regardless of what
10131        // follows the `=`. Every binding shape is covered, so no
10132        // untyped position can slip back in unnoticed.
10133        for text in [
10134            "LET $x = 1\n",
10135            "LET $x = \"hi\"\n",
10136            "LET $x = $y\n",
10137            "LET $x = [\"a\", \"b\"]\n",
10138            "LET $x = [\"a\",\n\"b\"]\n",
10139            "LET $x = ECHO hi\n",
10140            "LET $x = AWAIT $t\n",
10141            "LET $x = ASYNC ECHO hi\n",
10142            "LET $x = {\nRETURN 1\n}\n",
10143            "LET $x = WITH_IO [stdin=$p] ASYNC ECHO hi\n",
10144        ] {
10145            let err = crate::parse_script(text, lower).expect_err("untyped LET must fail");
10146            assert!(
10147                err.to_string().contains("LET requires explicit types"),
10148                "wrong error for {text:?}: {err}"
10149            );
10150        }
10151        // Typed spellings of the same shapes keep parsing through
10152        // every lexer frontend.
10153        for text in [
10154            "LET $x: INT = 1\n",
10155            "LET $x: STRING = \"hi\"\n",
10156            "LET $x: LIST<STRING> = [\"a\", \"b\"]\n",
10157            "LET $x: LIST<STRING> = [\"a\",\n\"b\"]\n",
10158            "LET $x: STRING = ECHO hi\n",
10159            "LET $x: STRING = AWAIT $t\n",
10160            "LET $x: HANDLE<VOID> = ASYNC ECHO hi\n",
10161            "LET $x: INT = {\nRETURN 1\n}\n",
10162        ] {
10163            assert_parity(text);
10164        }
10165    }
10166
10167    #[test]
10168    fn missing_comma_points_at_the_item() {
10169        // A forgotten comma between items names the missing
10170        // comma and points at the item's line, not the statement
10171        // head. Lists and call arguments share the rule.
10172        let text = indoc! {r#"
10173            LET $x: LIST<STRING> = [
10174            "a"
10175            "b",
10176            "c"
10177            ]
10178        "#};
10179        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
10180        assert!(
10181            err.to_string().contains("missing comma between list items"),
10182            "wrong error: {err}"
10183        );
10184        assert_eq!(err.line(), 3, "caret names the item line: {err}");
10185        // Same shape on one line.
10186        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" \"b\"]\n", lower)
10187            .expect_err("missing comma must fail");
10188        assert!(
10189            err.to_string().contains("missing comma between list items"),
10190            "wrong error: {err}"
10191        );
10192        assert_eq!(err.line(), 1, "single-line points at line 1: {err}");
10193        // Call arguments share the rule.
10194        let err = crate::parse_script("LET $x: STRING = FOO(\"a\" \"b\")\n", lower)
10195            .expect_err("missing comma must fail");
10196        assert!(
10197            err.to_string()
10198                .contains("missing comma between call arguments"),
10199            "wrong error: {err}"
10200        );
10201        // Genuine trailing garbage keeps the old message but still
10202        // points at the garbage instead of the statement head.
10203        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" : \"b\"]\n", lower)
10204            .expect_err("garbage must fail");
10205        assert!(
10206            err.to_string().contains("unexpected text in list"),
10207            "wrong error: {err}"
10208        );
10209        // Maps share the rule: a forgotten comma between entries
10210        // names it at the entry's line instead of misreporting the
10211        // key as an unknown command.
10212        let text = indoc! {r#"
10213            LET $m: MAP<name: STRING> = {
10214            name: "a"
10215            value: "b"
10216            }
10217        "#};
10218        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
10219        assert!(
10220            err.to_string()
10221                .contains("missing comma between map entries"),
10222            "wrong error: {err}"
10223        );
10224        assert_eq!(err.line(), 3, "caret names the entry line: {err}");
10225        let err = crate::parse_script(
10226            "LET $m: MAP<name: STRING> = {name: \"a\" value: \"b\"}\n",
10227            lower,
10228        )
10229        .expect_err("missing comma must fail");
10230        assert!(
10231            err.to_string()
10232                .contains("missing comma between map entries"),
10233            "wrong error: {err}"
10234        );
10235    }
10236
10237    #[test]
10238    fn spaced_comparisons_still_end_the_statement() {
10239        // A spaced `<` is a comparison, never a generic open: the
10240        // newline still ends the statement.
10241        let steps = crate::parse_script("LET $b: BOOL = $a < $b\nECHO hi", lower)
10242            .expect("comparison plus follower must parse");
10243        assert_eq!(steps.len(), 2, "newline ends the comparison statement");
10244    }
10245
10246    #[test]
10247    fn token_and_string_paths_agree_on_flat_commands() {
10248        for text in [
10249            "ECHO hi",
10250            "ECHO hi\nWRITE x out",
10251            "WRITE x",
10252            "ECHO \"quoted\" unquoted",
10253            "ENV COVERAGE=covered",
10254            "ECHO a; ECHO b",
10255            "// comment\nECHO hi",
10256            "ECHO 1.0.0 --flag a/b",
10257            "ECHO $x",
10258            "\n\nECHO hi\n\n",
10259        ] {
10260            assert_parity(text);
10261        }
10262    }
10263
10264    #[cfg(feature = "proc-macro-api")]
10265    #[test]
10266    fn backslash_outside_strings_is_string_only() {
10267        // `rustc` rejects a bare `\`, so unquoted backslash escapes
10268        // cannot cross `TokenStream` (same exclusion class as raw-`"`
10269        // blocks): the string lexer keeps them, the token path fails to
10270        // tokenize before v2 is ever reached.
10271        let toks = crate::tok::lex_str("ECHO a\\nb").expect("string lex keeps escapes");
10272        let old = crate::parse_script("ECHO a\\nb", lower).expect("string path parses it");
10273        assert_eq!(
10274            parse_tokens(&toks, lower).expect("token path parses it"),
10275            old
10276        );
10277        assert!("ECHO a\\nb".parse::<proc_macro2::TokenStream>().is_err());
10278    }
10279
10280    #[test]
10281    fn escaped_backslash_pair_is_atomic() {
10282        // `"a\\"` parses (one escape pair plus the closer): the pair
10283        // scans atomically, like the block-string arm and `lex_word`.
10284        // The value stays raw (`\\` verbatim for runtime
10285        // `expand_string`), so this pins parsing, not unescaping.
10286        assert_parity("ECHO \"a\\\\\"");
10287        let steps = crate::parse_script("ECHO \"a\\\\\"", lower).expect("escaped pair must parse");
10288        match &steps[..] {
10289            [s] => assert!(
10290                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a\\\\"),
10291                "escaped pair must survive raw: {s:?}"
10292            ),
10293            _ => panic!("one step: {steps:?}"),
10294        }
10295    }
10296
10297    #[test]
10298    fn joint_double_slash_stays_literal() {
10299        // `rustc` strips `//` before the macro ever runs, so these are
10300        // string-path-only by construction: joint `a//b` is one literal
10301        // arg, and `[a //c]` closes its group (the in-group `//` copy
10302        // stops at the closer).
10303        for text in ["ECHO a//b", "ECHO [a //c]"] {
10304            assert_parity_string_only(text);
10305        }
10306        let steps = crate::parse_script("ECHO a//b", lower).expect("joint slashes parse");
10307        match &steps[..] {
10308            [s] => assert!(
10309                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a//b"),
10310                "joint `//` must glue literally: {s:?}"
10311            ),
10312            _ => panic!("one step: {steps:?}"),
10313        }
10314        let steps = crate::parse_script("ECHO [a //c]", lower).expect("group must close");
10315        assert_eq!(steps.len(), 1, "one step: {steps:?}");
10316        // Full content survives literally: the mock joins WRITE args
10317        // with spaces, so the round trip is byte-exact here.
10318        let steps = crate::parse_script("WRITE f [a //c]", lower).expect("group must close");
10319        match &steps[..] {
10320            [s] => assert!(
10321                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a //c]"),
10322                "group content must survive literally: {s:?}"
10323            ),
10324            _ => panic!("one step: {steps:?}"),
10325        }
10326    }
10327
10328    #[test]
10329    fn block_comment_in_group_closes_like_line_comment() {
10330        // `[a /* c]` reads literally on the old backend (first arg
10331        // `[a`, joined `[a /* c]`), so the in-group `/*` copy breaks
10332        // at the depth-zero closer exactly like `//` does. The bare
10333        // `/*` reads literally too.
10334        for text in ["ECHO [a /* c]", "WRITE f [a /* c]", "ECHO /*"] {
10335            assert_parity_string_only(text);
10336        }
10337        let steps = crate::parse_script("ECHO /*", lower).expect("bare block open parses");
10338        match &steps[..] {
10339            [s] => assert!(
10340                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "/*"),
10341                "bare `/*` must stay literal: {s:?}"
10342            ),
10343            _ => panic!("one step: {steps:?}"),
10344        }
10345        let steps = crate::parse_script("WRITE f [a /* c]", lower).expect("group must close");
10346        match &steps[..] {
10347            [s] => assert!(
10348                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c]"),
10349                "group content must survive literally: {s:?}"
10350            ),
10351            _ => panic!("one step: {steps:?}"),
10352        }
10353        // Terminated spans keep working through the same path: the
10354        // run carries its closer, so math still gets first refusal.
10355        let steps = crate::parse_script("WRITE f [a /* c */ d]", lower).expect("group must close");
10356        match &steps[..] {
10357            [s] => assert!(
10358                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c */ d]"),
10359                "terminated group content must survive: {s:?}"
10360            ),
10361            _ => panic!("one step: {steps:?}"),
10362        }
10363    }
10364
10365    #[test]
10366    fn single_quoted_multiline_keeps_line_tracking() {
10367        // The `'` arm counts embedded newlines like the `"` arm, so the
10368        // statement after a multiline single-quoted string keeps its
10369        // own lines (func-docs stamping keys off them).
10370        let text = "ECHO 'a\nb'\nECHO c";
10371        assert_parity_string_only(text);
10372        let steps = crate::parse_script(text, lower).expect("must parse");
10373        assert_eq!(steps.len(), 2, "two steps: {steps:?}");
10374        assert_eq!((steps[0].line, steps[0].col), (1, 1));
10375        assert_eq!((steps[1].line, steps[1].col), (3, 1), "{steps:?}");
10376    }
10377
10378    #[test]
10379    fn token_and_string_paths_agree_on_guarded_commands() {
10380        for text in [
10381            "[env:X] ECHO hi",
10382            "[env:A] [os:linux] ECHO hi",
10383            "[os:macos] WRITE x",
10384            "[not(os:windows)] WRITE f x",
10385            "[any(os:macos, os:linux)] ECHO hi",
10386            "[all(env:A, os:linux)] ECHO hi",
10387            "[eq(env:K, v)] ECHO hi",
10388            "[ne(env:K, v)] ECHO hi",
10389            "[bool:true] ECHO hi",
10390            "[arch:arm] ECHO hi",
10391            "[family:unix] ECHO hi",
10392            "[(os:linux)] ECHO hi",
10393            "[env:A, os:linux] ECHO hi",
10394            "WRITE x\n[env:X] ECHO hi",
10395            "[env:K] ECHO $x",
10396            "[__OXDOCK_INJECT_1__] ECHO hi",
10397            "[eq(env:K, \"a b\")] ECHO hi",
10398            "[\nenv:X\n] ECHO hi",
10399            // In-body brackets are raw text split on whitespace (probed
10400            // parity: `[a, b]` is args `"[a,"` + `"b]"`, quotes kept).
10401            "ECHO [a, b] hi",
10402            "WRITE f [env:X]",
10403            "ECHO [env:X] hi",
10404            "WRITE f [\"a b\"]",
10405            "ECHO foo[bar]baz",
10406            "ECHO [a ]",
10407            "ECHO [ a]",
10408            "WRITE out x [env:X]",
10409        ] {
10410            assert_parity(text);
10411        }
10412        // `rustc` lexes `'a` as a lifetime start and rejects the
10413        // space: string-path-only by construction.
10414        assert_parity_string_only("ECHO ['a b']");
10415    }
10416
10417    #[test]
10418    fn token_and_string_paths_agree_on_calls_and_exact_args() {
10419        use crate::ast::{ModuleFuncs, ModuleTable};
10420        use std::collections::{HashMap, HashSet};
10421        let std_table = || ModuleTable {
10422            modules: HashMap::from([(
10423                crate::constants::STD_MODULE_NAME.to_string(),
10424                Some(ModuleFuncs {
10425                    func_names: HashSet::from(["LEN".to_string()]),
10426                }),
10427            )]),
10428        };
10429        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10430            test_lower_mock::lower(name, args)
10431        }
10432        // One table for both pathways: STD exports LEN.
10433        // Rebuilt per case (parse-time only, keeps borrows local).
10434        for text in [
10435            "LET $n: INT = STD::LEN(\"hi\")",
10436            "STD::LEN(\"hi\")",
10437            "LET $n: INT = STD::LEN(\"a\", \"b\")",
10438            "LET $s: STRING = INSPECT($x)",
10439            "INSPECT($x)",
10440            "LET $x: STRING = ECHO hi",
10441            "LET $t: STRING = WRITE x",
10442            "LET $o: STRING = RUN echo hi",
10443            "RUN [\"echo\", \"hi\"]",
10444            "RUN echo [a]",
10445            "LET $r: STRING = RUN [\"echo\"]",
10446            "ECHO K=v",
10447            "ECHO K = v",
10448            "ECHO K=a b",
10449            "ECHO K=a, b",
10450            "ECHO K=\"a b\"",
10451            "ECHO K=$x",
10452            "ECHO K=",
10453            "ECHO a = = b",
10454            "WRITE f K=v",
10455            "ECHO $a + $b",
10456            "ECHO $a==$b",
10457            "ECHO a $x b",
10458            "ECHO 5 + 3",
10459            "WRITE f ( \"hi\" )",
10460            "ECHO [a, b] hi",
10461            "ECHO {{x}}",
10462            "ECHO {{ $x }}",
10463            "ECHO $x=K",
10464            "ECHO a$x",
10465            "ECHO a$(x)",
10466            "ECHO K=$x tail",
10467            "EXPAND K1=$x K2=$y",
10468            "EXPAND a",
10469            "ENV K = v",
10470            "COPY a b",
10471            "ECHO foo[bar]baz",
10472            "LET $x: STRING = FOOBAR",
10473            "STD::LEN(\"hi\") ECHO bye",
10474            "LET $n: INT = STD::LEN(\"a\") ECHO bye",
10475            "TIMEOUT 10s STD::LEN(\"hi\")",
10476            "TIMEOUT 10s STD::LEN(\"hi\") ECHO bye",
10477            "LET $n: INT = STD::LEN(\"a\")STD::LEN(\"b\")",
10478        ] {
10479            let table = std_table();
10480            let old =
10481                crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
10482                    .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
10483            let reserved = HashSet::new();
10484            let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
10485            let toks = crate::tok::lex_str(text).expect("string lex must succeed");
10486            let new = parse_tokens_with_ctx(&toks, &ctx)
10487                .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
10488            assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
10489            #[cfg(feature = "proc-macro-api")]
10490            {
10491                let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
10492                let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
10493                let new = parse_tokens_with_ctx(&toks, &ctx)
10494                    .unwrap_or_else(|e| panic!("token path must parse token {text:?}: {e}"));
10495                assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
10496            }
10497        }
10498    }
10499
10500    #[test]
10501    fn placeholder_bare_calls_resolve_like_statements() {
10502        // `{{ NAME(args) }}` obeys exactly the statement-position
10503        // scope rule: `IMPORT [MOD]` brings the names into scope,
10504        // unimported names fail naming the fix, ambiguity fails
10505        // closed. The rewrite below is byte-identical past the
10506        // qualified head, so expansion sees the same args.
10507        use crate::ast::{ModuleFuncs, ModuleTable};
10508        use std::collections::{HashMap, HashSet};
10509        let table = || ModuleTable {
10510            modules: HashMap::from([
10511                (
10512                    crate::constants::STD_MODULE_NAME.to_string(),
10513                    Some(ModuleFuncs {
10514                        func_names: HashSet::from(["LEN".to_string()]),
10515                    }),
10516                ),
10517                (
10518                    "OTHER".to_string(),
10519                    Some(ModuleFuncs {
10520                        func_names: HashSet::from(["LEN".to_string()]),
10521                    }),
10522                ),
10523            ]),
10524        };
10525        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10526            test_lower_mock::lower(name, args)
10527        }
10528        fn echo_text(steps: &[crate::Step]) -> String {
10529            match steps {
10530                [s] => match &s.kind {
10531                    StepKind::Echo(Arg::String(text, _)) => text.clone(),
10532                    other => panic!("expected ECHO string, got {other:?}"),
10533                },
10534                _ => panic!("expected one step, got {steps:?}"),
10535            }
10536        }
10537        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10538            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10539        }
10540        // Imported bare names qualify; everything else rides through
10541        // byte-identical for the runtime to handle as before.
10542        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }}\"\n";
10543        let out = echo_text(&parse(text, table()).expect("imported bare call parses"));
10544        assert_eq!(out, "n: {{ STD::LEN($x) }}", "bare call qualifies: {out}");
10545        let text = "IMPORT [STD]\nECHO \"n: {{ STD::LEN($x) }}\"\n";
10546        let out = echo_text(&parse(text, table()).expect("qualified parses"));
10547        assert_eq!(
10548            out, "n: {{ STD::LEN($x) }}",
10549            "qualified keys stay untouched: {out}"
10550        );
10551        let text = "IMPORT [STD]\nECHO \"hi {{ $x }} and {{ bare }} and {{ env:K }}\"\n";
10552        let out = echo_text(&parse(text, table()).expect("non-calls parse"));
10553        assert_eq!(
10554            out, "hi {{ $x }} and {{ bare }} and {{ env:K }}",
10555            "non-call keys stay untouched: {out}"
10556        );
10557        let text = "IMPORT [STD]\nECHO \"lit \\{{ LEN($x) }}\"\n";
10558        let out = echo_text(&parse(text, table()).expect("escaped parses"));
10559        assert_eq!(
10560            out, "lit \\{{ LEN($x) }}",
10561            "escaped openers stay literal: {out}"
10562        );
10563        // Nested bodies resolve against the enclosing imports, exactly
10564        // like statement-position calls in the same body.
10565        let text = indoc! {r#"
10566            IMPORT [STD]
10567            FUNC F(): VOID {
10568            ECHO "n: {{ LEN($x) }}"
10569            }
10570        "#};
10571        let steps = parse(text, table()).expect("nested bare call parses");
10572        let body = steps.iter().find_map(|s| match &s.kind {
10573            StepKind::FuncDef { body, .. } => Some(body),
10574            _ => None,
10575        });
10576        match body.map(Vec::as_slice) {
10577            Some([inner]) => match &inner.kind {
10578                StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10579                    echoed, "n: {{ STD::LEN($x) }}",
10580                    "nested body qualifies: {echoed}"
10581                ),
10582                other => panic!("expected nested ECHO, got {other:?}"),
10583            },
10584            _ => panic!("expected one FUNC with one body step, got {steps:?}"),
10585        };
10586        // Neighboring placeholders keep their exact bytes: only the
10587        // head span changes, so payloads never lose formatting.
10588        let text = "IMPORT [STD]\nECHO \"Call {{ LEN($x) }} and value {{ $y }}\"\n";
10589        let out = echo_text(&parse(text, table()).expect("mixed template parses"));
10590        assert_eq!(
10591            out, "Call {{ STD::LEN($x) }} and value {{ $y }}",
10592            "only the head span changes: {out}"
10593        );
10594        // Unimported bare names fail exactly like statement position:
10595        // qualify it or add the import.
10596        let err = parse("ECHO \"n: {{ LEN($x) }}\"\n", table()).expect_err("must fail");
10597        assert!(
10598            err.to_string().contains("unknown function `LEN`")
10599                && err.to_string().contains("or add `IMPORT"),
10600            "names the fix: {err}"
10601        );
10602        // Two exporters fail closed instead of picking one.
10603        let err = parse(
10604            "IMPORT [STD]\nIMPORT [OTHER]\nECHO \"n: {{ LEN($x) }}\"\n",
10605            table(),
10606        )
10607        .expect_err("must fail");
10608        assert!(
10609            err.to_string().contains("ambiguous function `LEN`"),
10610            "ambiguity fails closed: {err}"
10611        );
10612        // Both lexing pathways agree on rewritten templates.
10613        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }} and {{ $y }}\"\n";
10614        let table = table();
10615        let old = crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
10616            .expect("string path parses");
10617        let reserved = HashSet::new();
10618        let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
10619        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
10620        let new = parse_tokens_with_ctx(&toks, &ctx).expect("token path parses");
10621        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
10622    }
10623
10624    #[test]
10625    fn placeholder_bare_calls_qualify_in_expr_positions() {
10626        // Regression: `walk_raw_strings_mut` skips `Assign`/`Set`/
10627        // `Call`/`Return`/`If`/`For`/`While`, so `LET`/`RETURN`/call
10628        // args/list/map literals never qualified and failed at
10629        // runtime as undefined variables. Both carriers now qualify.
10630        use crate::ast::{ModuleFuncs, ModuleTable};
10631        use std::collections::{HashMap, HashSet};
10632        let table = || ModuleTable {
10633            modules: HashMap::from([(
10634                crate::constants::STD_MODULE_NAME.to_string(),
10635                Some(ModuleFuncs {
10636                    func_names: HashSet::from(["LEN".to_string()]),
10637                }),
10638            )]),
10639        };
10640        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10641            test_lower_mock::lower(name, args)
10642        }
10643        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10644            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10645        }
10646        // LET string literal qualifies.
10647        let steps = parse(
10648            "IMPORT [STD]\nLET $s: STRING = \"n: {{ LEN($x) }}\"\n",
10649            table(),
10650        )
10651        .expect("LET template parses");
10652        match &steps[0].kind {
10653            StepKind::Bind {
10654                rhs: BindRhs::Expr(expr),
10655                ..
10656            } => match expr {
10657                Expr::Literal(value) => assert_eq!(
10658                    value.as_str().unwrap_or_default(),
10659                    "n: {{ STD::LEN($x) }}",
10660                    "LET qualifies"
10661                ),
10662                other => panic!("expected literal, got {other:?}"),
10663            },
10664            other => panic!("expected Bind, got {other:?}"),
10665        }
10666        // RETURN string literal qualifies.
10667        let steps = parse(
10668            "IMPORT [STD]\nFUNC F(): STRING {\nRETURN \"n: {{ LEN($x) }}\"\n}\n",
10669            table(),
10670        )
10671        .expect("RETURN template parses");
10672        let body = steps.iter().find_map(|s| match &s.kind {
10673            StepKind::FuncDef { body, .. } => Some(body),
10674            _ => None,
10675        });
10676        match body.map(Vec::as_slice) {
10677            Some([inner]) => match &inner.kind {
10678                StepKind::Return { expr, .. } => match &**expr {
10679                    Expr::Literal(value) => assert_eq!(
10680                        value.as_str().unwrap_or_default(),
10681                        "n: {{ STD::LEN($x) }}",
10682                        "RETURN qualifies"
10683                    ),
10684                    other => panic!("expected literal, got {other:?}"),
10685                },
10686                other => panic!("expected RETURN, got {other:?}"),
10687            },
10688            _ => panic!("expected one FUNC, got {steps:?}"),
10689        }
10690        // Call args, list and map literals qualify.
10691        let steps = parse(
10692            "IMPORT [STD]\nLET $y: INT = LEN(\"b: {{ LEN($x) }}\")\n",
10693            table(),
10694        )
10695        .expect("call-arg template parses");
10696        let rendered = format!("{:?}", steps[0].kind);
10697        assert!(
10698            rendered.contains("STD::LEN"),
10699            "call arg qualifies: {rendered}"
10700        );
10701        let steps = parse(
10702            "IMPORT [STD]\nLET $l: LIST<STRING> = [\"{{ LEN($x) }}\"]\n",
10703            table(),
10704        )
10705        .expect("list template parses");
10706        let rendered = format!("{:?}", steps[0].kind);
10707        assert!(rendered.contains("STD::LEN"), "list qualifies: {rendered}");
10708        // Compound placeholders are not single calls: they pass
10709        // through untouched (no partial rewrite) for the runtime to
10710        // fail closed on the whole key.
10711        let text = "IMPORT [STD]\nECHO \"v: {{ LEN($a) + LEN($b) }}\"\n";
10712        let steps = parse(text, table()).expect("compound parses");
10713        match &steps[0].kind {
10714            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10715                echoed, "v: {{ LEN($a) + LEN($b) }}",
10716                "compound untouched: {echoed}"
10717            ),
10718            other => panic!("expected ECHO string, got {other:?}"),
10719        }
10720        // Quoted parens inside args do not end the call early.
10721        let text = "IMPORT [STD]\nECHO 'v: {{ LEN(\"a(b\") }}'\n";
10722        let steps = parse(text, table()).expect("quoted paren parses");
10723        match &steps[0].kind {
10724            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10725                echoed, "v: {{ STD::LEN(\"a(b\") }}",
10726                "quoted paren qualifies: {echoed}"
10727            ),
10728            other => panic!("expected ECHO string, got {other:?}"),
10729        }
10730        // Single-quoted args balance the same way.
10731        let text = "IMPORT [STD]\nECHO \"v: {{ LEN('a(b') }}\"\n";
10732        let steps = parse(text, table()).expect("single-quoted paren parses");
10733        match &steps[0].kind {
10734            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10735                echoed, "v: {{ STD::LEN('a(b') }}",
10736                "single-quoted paren qualifies: {echoed}"
10737            ),
10738            other => panic!("expected ECHO string, got {other:?}"),
10739        }
10740        // `WithIo` boxes its inner command directly (no recursive
10741        // statement pass), so the qualifier must descend into it.
10742        // `LET $p: PIPE` plus bindings keep the shape realistic.
10743        let text = "IMPORT [STD]\nLET $p: PIPE\nWITH_IO [stdout=$p] ECHO 'v: {{ LEN($x) }}'\n";
10744        let steps = parse(text, table()).expect("with-io template parses");
10745        match &steps[1].kind {
10746            StepKind::WithIo { cmd, .. } => {
10747                let rendered = format!("{cmd:?}");
10748                assert!(
10749                    rendered.contains("STD::LEN"),
10750                    "with-io inner qualifies: {rendered}"
10751                );
10752            }
10753            other => panic!("expected WithIo, got {other:?}"),
10754        }
10755        // Single-command wrappers build synthetic body steps without a
10756        // recursive pass: `TIMEOUT 5s <cmd>` and `ASYNC <cmd>` share
10757        // the outer frame, so the qualifier must descend into bodies.
10758        let text = "IMPORT [STD]\nTIMEOUT 5s ECHO 't: {{ LEN($x) }}'\n";
10759        let steps = parse(text, table()).expect("timeout template parses");
10760        let rendered = format!("{:?}", steps[0].kind);
10761        assert!(
10762            rendered.contains("STD::LEN"),
10763            "timeout single qualifies: {rendered}"
10764        );
10765        let text = "IMPORT [STD]\nLET $h: HANDLE<ANY> = ASYNC ECHO 'a: {{ LEN($x) }}'\n";
10766        let steps = parse(text, table()).expect("async template parses");
10767        let rendered = format!("{:?}", steps[0].kind);
10768        assert!(
10769            rendered.contains("STD::LEN"),
10770            "async single qualifies: {rendered}"
10771        );
10772        // Brace bodies keep their own frames: the outer qualifier must
10773        // never re-walk them. A valid nested body qualifies via its own
10774        // recursive pass, and an unknown callee inside one fails with
10775        // the inner position, never re-resolved against the outer frame.
10776        let text = "IMPORT [STD]\nIF true {\nECHO 'v: {{ LEN($x) }}'\n}\n";
10777        let steps = parse(text, table()).expect("nested body qualifies");
10778        let rendered = format!("{:?}", steps[0].kind);
10779        assert!(
10780            rendered.contains("STD::LEN"),
10781            "nested IF body qualifies via its own frame: {rendered}"
10782        );
10783        let err = parse(
10784            "IMPORT [STD]\nIF true {\nECHO 'v: {{ NOPE($x) }}'\n}\n",
10785            table(),
10786        )
10787        .expect_err("nested unknown must fail");
10788        assert!(
10789            err.to_string().contains("unknown function `NOPE`"),
10790            "nested unknown names culprit: {err}"
10791        );
10792    }
10793
10794    #[test]
10795    fn block_conditions_name_unknown_callees() {
10796        // Regression: an unknown callee in a block header condition
10797        // used to miss to the generic `IF needs a condition and a
10798        // block` hint. Classified resolution failures now propagate
10799        // and name the culprit on all four speculative headers.
10800        use crate::ast::{ModuleFuncs, ModuleTable};
10801        use std::collections::{HashMap, HashSet};
10802        let table = || ModuleTable {
10803            modules: HashMap::from([(
10804                crate::constants::STD_MODULE_NAME.to_string(),
10805                Some(ModuleFuncs {
10806                    func_names: HashSet::from(["LEN".to_string()]),
10807                }),
10808            )]),
10809        };
10810        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10811            test_lower_mock::lower(name, args)
10812        }
10813        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10814            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10815        }
10816        for text in [
10817            "IMPORT [STD]\nIF NOPE($x) == 0 {\nECHO hi\n}\n",
10818            "IMPORT [STD]\nIF LEN($x) == 0 {\nECHO hi\n} ELSE IF NOPE($x) == 1 {\nECHO yo\n}\n",
10819            "IMPORT [STD]\nWHILE NOPE($x) > 0 {\nECHO hi\n}\n",
10820            "IMPORT [STD]\nFOR $i: STRING IN NOPE($x) {\nECHO $i\n}\n",
10821        ] {
10822            let err = parse(text, table()).expect_err("unknown callee must fail");
10823            assert!(
10824                err.to_string().contains("unknown function `NOPE`"),
10825                "names the culprit: {err}"
10826            );
10827        }
10828        // Unclassified shape misses still miss (the exact generic
10829        // hint comes from the real dispatcher, which the mock lacks).
10830        parse("IF {\nECHO hi\n}\n", table()).expect_err("empty condition must still fail");
10831    }
10832
10833    #[test]
10834    fn token_and_string_paths_agree_on_let_set_return() {
10835        for text in [
10836            "LET $x: INT = 1",
10837            "LET $s: STRING = \"hi\"",
10838            "LET $b: BOOL = true",
10839            "LET $f: FLOAT = 1.5",
10840            "LET $p: PIPE",
10841            "LET $l: LIST<STRING> = [\"a\", \"b\"]",
10842            "LET $e: LIST<STRING> = []",
10843            "LET $m: MAP = {k: 1}",
10844            "LET $m2: MAP = {\"a b\": 2, k: [1, 2]}",
10845            "LET $n: INT = $a + $b",
10846            "LET $c: BOOL = ($a == 3) && ($b == 4)",
10847            "LET $g: BOOL = !$ok",
10848            "LET $nn: BOOL = true && false",
10849            "LET $e2: STRING = env:HOME",
10850            "LET $k: STRING = $a.b.c",
10851            "LET $u: INT = -5",
10852            "LET $v: INT = 9223372036854775807",
10853            "LET $min: INT = -9223372036854775808",
10854            "LET $w: INT = 1_000",
10855            "LET $z: STRING = a/b",
10856            "LET $d: STRING = -f",
10857            "LET $t: STRING = 30s",
10858            "LET $q: STRING = \"\"\"hi\"\"\"",
10859            "LET $f2: FLOAT = 2 * -3",
10860            "LET $o: BOOL = 2 + 3 > 4",
10861            "LET $l2: LIST< MAP > = []",
10862            "LET $a1: INT = 1 + 2",
10863            "LET $s1: INT = 10 - 4 - 3",
10864            "LET $m1: INT = 2 * 3 + 4",
10865            "LET $x1: BOOL = 1 < 2 == true",
10866            "LET $or: BOOL = $a || $b",
10867            "LET $dbl: BOOL = !!$x",
10868            "LET $ver: STRING = 1.0.0",
10869            "LET $dash: STRING = a-b",
10870            "LET $div: INT = 4 / 2",
10871            "LET $bad: INT = 1__0 + 0",
10872            "LET $strdiv: STRING = 4/2",
10873            "LET $sp: INT = $a - $b",
10874            "$x = 1",
10875            "$x = $a + 1",
10876            "RETURN 1",
10877            KEYWORD_RETURN,
10878            "RETURN $x",
10879            "[env:X] LET $x: INT = 1",
10880            "[os:linux] $x = 2",
10881        ] {
10882            assert_parity(text);
10883        }
10884    }
10885
10886    #[test]
10887    fn malformed_shapes_fail_on_both_paths() {
10888        // Malformed shapes fail on both lexers (messages may differ;
10889        // success/failure must agree). Unbalanced groups fail even
10890        // earlier, at lex time: both layers reject, which is what the
10891        // oracle pins.
10892        for text in [
10893            "[a] ECHO hi",
10894            "[os:atari] ECHO hi",
10895            "[foo:bar] ECHO hi",
10896            "[any(os:linux)] ECHO hi",
10897            "[all()] ECHO hi",
10898            "[env:] ECHO hi",
10899            "[eq(env:K)] ECHO hi",
10900            "[not] ECHO hi",
10901            "ECHO [a;b]",
10902            "ECHO (a;b)",
10903            "ECHO a;b",
10904            "LET $x = 1",
10905            "LET $s: STRING",
10906            "LET $x: INT = 1 2",
10907            "LET $x: INT = (1",
10908            "LET $x: INT = 9223372036854775808",
10909            "$x =",
10910            "RETURN (",
10911            "[env:X]",
10912            "LET $x: INT = $a == $b == $c",
10913            "LET $x: BOOL = $a < $b < $c",
10914            "LET $bs: STRING = a\\nb",
10915            "FOO(\"a\")",
10916            "FOO (\"a\")",
10917            "ECHO FOO(\"a\")",
10918            "ECHO(\"hi\")",
10919            "RUN [a] extra",
10920            "RUN[\"a\"]",
10921            "TIMEOUT 10s RUN[\"a\"]",
10922            "LET $r: STRING = RUN[\"a\"]",
10923            "LET $e: STRING = ECHO",
10924            "ENV A=1 B=2",
10925            "EXPAND \"a b\" c",
10926            "ECHO {a}",
10927            "ECHO K=${x}",
10928            "[!env:A==1] RUN echo no",
10929            "run echo hi",
10930            "LET $x: STRING = AWAIT",
10931            "LET $o: STRING = CANCEL $t",
10932            "LET $x: STRING = ASYNC",
10933            "LET $x: STRING = WITH_IO",
10934            "LET $x: STRING = TIMEOUT",
10935            "LET $x: STRING = ISOLATED",
10936            "LET $x: STRING = ISOLATED ECHO hi",
10937            "COPY A=1",
10938            "WITH_IO [rows=40] RUN echo hi",
10939            "WITH_IO [tty] ECHO hi",
10940            "WITH_IO [tty, stderr=$p] RUN echo hi",
10941            "WITH_IO [tty=$p] RUN echo hi",
10942            "WITH_IO [cols=0] RUN echo hi",
10943            "WITH_IO [cols=65536] RUN echo hi",
10944            "WITH_IO [] ECHO hi",
10945            "WITH_IO [stdin=$p,] ECHO hi",
10946            "WITH_IO stdin=$p ECHO hi",
10947            "WITH_IO [STDIN=$p] ECHO hi",
10948            "WITH_IO [rows] RUN echo hi",
10949            KEYWORD_WITH_IO,
10950            "WITH_IO [stdout=$p]",
10951            "WITH_IO [stdin=$p]\n[os:linux] { ECHO hi }",
10952            "WITH_IO [stdin=$p] { }",
10953            "WITH_IO[stdin=$p] ECHO hi",
10954            "WITH_IO [stdin=$p]ECHO hi",
10955            "WITH_IO [stdin=$p] {{ $x }}",
10956            "ASYNC WITH_IO [stdout=$p] ECHO hi",
10957            "WITH_IO [stdin=$p] AWAIT $t",
10958            "ASYNC AWAIT $t",
10959            "WITH_IO [stdin=$p] RETURN \"hi\"",
10960            "ASYNC RETURN \"hi\"",
10961            "TIMEOUT 10s RETURN \"hi\"",
10962            "TIMEOUT banana ECHO hi",
10963            "TIMEOUT 10ss ECHO hi",
10964            "TIMEOUT 10 s ECHO hi",
10965            "TIMEOUT -5s ECHO hi",
10966            "TIMEOUT 0s ECHO hi",
10967            KEYWORD_TIMEOUT,
10968            "TIMEOUT 10s",
10969            "TIMEOUT { ECHO hi }",
10970            "TIMEOUT \"10s\"",
10971            "TIMEOUT 10s{ECHO hi}",
10972            "TIMEOUT 10sECHO hi",
10973            "TIMEOUT 10s {{ $d }}",
10974            "TIMEOUT 10s { $d }",
10975            "TIMEOUT { $d } ECHO hi",
10976            KEYWORD_ASYNC,
10977            KEYWORD_ISOLATED,
10978            "ISOLATED{ECHO hi}",
10979            KEYWORD_AWAIT,
10980            KEYWORD_CANCEL,
10981            "AWAIT t",
10982            "AWAIT $",
10983            "AWAIT $t extra",
10984            "CANCEL $t extra",
10985            "TIMEOUT 5s INHERIT_ENV [M]",
10986            "TIMEOUT 5s { INHERIT_ENV [M] }",
10987            "ASYNC { INHERIT_ENV [M] }",
10988            "LET $x: STRING = INHERIT_ENV [M]",
10989            "TIMEOUT 10s WITH_IO [stdin=$p] { ECHO hi }",
10990            "ISOLATED WITH_IO [stdin=$p] { ECHO hi }",
10991            "TIMEOUT 10s AWAIT $ t",
10992            "LET $o: STRING = AWAIT $ t",
10993            "ISOLATED AWAIT $ t",
10994            "WITH_IO [stdin=$p] CANCEL $ t",
10995            "LET $ x: INT = 1",
10996            "LET $x: STRING = WITH_IO [stdin=$p] { ECHO hi }",
10997            "LET $x: STRING = WITH_IO [stdin=$p] ASYNC",
10998            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO a\nECHO b }",
10999            "LET $x: STRING = WITH_IO [stdout=$p] ECHO hi",
11000            "LET $x: STRING = TIMEOUT 10s AWAIT $t",
11001            "LET $x: STRING = CANCEL $t",
11002            "LET $x: STRING = ASYNC",
11003            "LET $x: STRING = WITH_IO",
11004            "TIMEOUT 10s LET $x: INT = 1",
11005            "LET $x: STRING = FOO bar",
11006            "LET(\"a\")",
11007            "AWAIT($t)",
11008            "CANCEL($t)",
11009            "TIMEOUT(\"10s\") ECHO hi",
11010            "RETURN ECHO bye",
11011        ] {
11012            match crate::tok::lex_str(text) {
11013                Err(_) => {
11014                    assert!(
11015                        crate::parse_script(text, lower).is_err(),
11016                        "backend must also reject lex-broken input: {text:?}"
11017                    );
11018                    continue;
11019                }
11020                Ok(toks) => {
11021                    assert!(
11022                        parse_tokens(&toks, lower).is_err(),
11023                        "v2 must explicitly reject (not silently drift): {text:?}"
11024                    );
11025                }
11026            }
11027            assert!(
11028                crate::parse_script(text, lower).is_err(),
11029                "backend must also reject (oracle agreement): {text:?}"
11030            );
11031        }
11032        // No deferred shapes remain: every statement-level block and
11033        // inline-block expression parses natively.
11034    }
11035
11036    #[test]
11037    fn deferred_unknown_callee_beats_validation_arg_error() {
11038        // Directive 5: `WORKSPACE NOPE()` stashes `unknown function
11039        // NOPE` while the fallback raw string fails `WORKSPACE`
11040        // validation. On a well-formed header the stashed callee error
11041        // names the culprit instead of the misleading arg-shape error.
11042        let err =
11043            crate::parse_script("WORKSPACE NOPE()", lower).expect_err("unknown callee must fail");
11044        assert!(
11045            err.to_string().contains("unknown function `NOPE`"),
11046            "deferred must beat validation, got: {err}"
11047        );
11048    }
11049
11050    #[test]
11051    fn paren_line_break_reports_token_position() {
11052        // Directive 5: multiline paren breaks carry the offending
11053        // token's line/col, not a stamped 0/0. The break sits on line 2
11054        // while the statement opens on line 1.
11055        let err = crate::parse_script("ECHO (a\nb)", lower).expect_err("break must fail");
11056        let rendered = err.to_string();
11057        assert!(
11058            rendered.contains("unexpected line break"),
11059            "break must report, got: {rendered}"
11060        );
11061    }
11062
11063    #[test]
11064    fn deferred_unknown_callee_beats_invalid_syntax_arg_error() {
11065        // Fallback raw strings can trigger `InvalidSyntax` lowering
11066        // (for example `COPY NOPE()`). The stashed unknown-callee error
11067        // still names the culprit on a recognized head.
11068        for text in ["COPY NOPE()", "WRITE NOPE()"] {
11069            let err = crate::parse_script(text, lower).expect_err("unknown callee must fail");
11070            assert!(
11071                err.to_string().contains("unknown function `NOPE`"),
11072                "deferred must beat InvalidSyntax for {text:?}, got: {err}"
11073            );
11074        }
11075    }
11076
11077    #[test]
11078    fn deferred_beats_lowering_invalid_syntax_on_plain_heads() {
11079        // Plain command heads own no header grammar, so a lowering
11080        // `InvalidSyntax` there is an argument-shape failure from the
11081        // raw-text fallback: the stashed unknown-callee names the
11082        // culprit on every such head (no per-command allowlist).
11083        let lower_invalid =
11084            |name: &str, _args: Vec<crate::Arg>| -> crate::ParseResult<crate::StepKind> {
11085                Err(crate::ParseError::invalid_syntax(
11086                    name,
11087                    format!("{name} header is malformed"),
11088                    None,
11089                    Vec::new(),
11090                    None,
11091                    &crate::error::SpanContext::line_only(0),
11092                ))
11093            };
11094        for text in [
11095            "ASSERT_EQ $a NOSUCHFUNC()",
11096            "SYMLINK $a NOSUCHFUNC()",
11097            "COPY $a NOSUCHFUNC()",
11098            "WRITE $a NOSUCHFUNC()",
11099        ] {
11100            let err = crate::parse_script(text, lower_invalid).expect_err("arg error must fail");
11101            assert!(
11102                err.to_string().contains("unknown function `NOSUCHFUNC`"),
11103                "deferred must beat lowering InvalidSyntax for {text:?}, got: {err}"
11104            );
11105        }
11106        // Header-owned heads keep their lowering `InvalidSyntax`: the
11107        // native parser missed to the generic path on shape miss, so
11108        // the lowering error names the malformed header while the
11109        // stashed name is its definiendum, never a call.
11110        let err = crate::parse_script("FUNC $a NOSUCHFUNC()", lower_invalid)
11111            .expect_err("header syntax must fail");
11112        assert!(
11113            err.to_string().contains("header is malformed"),
11114            "header InvalidSyntax must stand on FUNC, got: {err}"
11115        );
11116    }
11117
11118    #[test]
11119    fn trailing_tokens_after_func_block_never_hoist() {
11120        // A `FUNC` header with trailing tokens after the body block is
11121        // malformed (the real path rejects it), so pre-declaration
11122        // must not hoist the name: the forward call fails instead of
11123        // resolving.
11124        let err = crate::parse_script(
11125            "LET $x: STRING = FOO()\nFUNC FOO(): STRING { RETURN \"a\" } TRAILING\n",
11126            lower,
11127        )
11128        .expect_err("trailing tokens must fail");
11129        assert!(
11130            err.to_string().contains("unknown function `FOO`"),
11131            "unhoisted forward call must fail, got: {err}"
11132        );
11133    }
11134
11135    #[test]
11136    fn forward_reference_resolves_regardless_of_order() {
11137        // `CALLER` calls `CALLEE` defined later. Top-level
11138        // pre-declaration hoists names before lowering, so order
11139        // does not matter. Runtime still executes sequentially;
11140        // the call below runs after both definitions.
11141        let steps = crate::parse_script(
11142            "FUNC CALLER(): STRING { RETURN CALLEE() }\nFUNC CALLEE(): STRING { RETURN \"forward-ok\" }\n",
11143            lower,
11144        )
11145        .expect("forward ref must parse");
11146        assert!(
11147            matches!(&steps[0].kind, crate::StepKind::FuncDef { name, .. } if name == "CALLER"),
11148            "first def kept, got: {:?}",
11149            steps[0].kind
11150        );
11151    }
11152
11153    #[test]
11154    fn forward_reference_to_guarded_func_resolves() {
11155        // Guarded definitions hoist like unguarded ones: `parse_func_at`
11156        // registers `[os:macos] FUNC FOO` unconditionally, so a forward
11157        // call before the definition must resolve identically to a
11158        // backward call after it.
11159        let steps = crate::parse_script(
11160            "LET $x: STRING = FOO()\n[os:macos] FUNC FOO(): STRING { RETURN \"guarded\" }\n",
11161            lower,
11162        )
11163        .expect("forward guarded ref must parse");
11164        assert!(
11165            matches!(&steps[1].kind, crate::StepKind::FuncDef { name, .. } if name == "FOO"),
11166            "guarded def kept, got: {:?}",
11167            steps[1].kind
11168        );
11169    }
11170}