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`/`SET`/`RETURN` with the full
18//! 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    InsToken, apply_unary_neg, canonical_assignment_arg, check_tty_wrapping, classify_numeric_text,
92    is_known_command, lower_env_tokens, lower_expand_tokens, make_arith, make_compare,
93    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_CONTINUE, KEYWORD_DEFAULT, KEYWORD_ELSE, KEYWORD_ENV,
98    KEYWORD_EXPAND, KEYWORD_EXPORT, KEYWORD_FOR, KEYWORD_FROM, KEYWORD_FUNC, KEYWORD_IF,
99    KEYWORD_IMPORT, KEYWORD_IN, KEYWORD_INHERIT_ENV, KEYWORD_INSPECT, KEYWORD_ISOLATED,
100    KEYWORD_LET, KEYWORD_REMOTE, KEYWORD_RETURN, KEYWORD_RUN, KEYWORD_SWITCH, KEYWORD_TIMEOUT,
101    KEYWORD_TYPE, KEYWORD_WHILE, KEYWORD_WITH_IO, MODULE_SEPARATOR,
102};
103use crate::error::{ParseError, ParseErrorKind, ParseResult, SpanContext};
104
105use crate::resolve::resolve_call_name;
106use crate::tok::{GroupDelim, LexError, Tok, TokKind, lex_str};
107use std::cell::RefCell;
108use std::collections::HashSet;
109use std::fmt;
110
111/// Backend error. Carries the statement index and message; the string
112/// entry points below map it to [`crate::ParseError`]. Lowering
113/// failures from the shared `lower` dispatcher stringify through here
114/// so success paths compare exactly.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct TokenError {
117    pub stmt: usize,
118    /// 1-based source line, `0` when unknown (the split loops stamp the
119    /// enclosing statement's line on the way out, so only genuinely
120    /// position-less errors stay `0`).
121    pub line: usize,
122    /// 1-based start column of the enclosing statement, `0` when
123    /// unknown (stamped alongside `line`).
124    pub col: usize,
125    pub msg: String,
126    /// Lowering failures preserve the dispatcher's classification
127    /// (`UnknownCommand`, `InvalidSyntax`, `Validation`); `None` means
128    /// a parser-native structural failure.
129    pub kind: Option<ParseErrorKind>,
130}
131
132impl fmt::Display for TokenError {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        write!(
135            f,
136            "parse error in statement {}: {}",
137            self.stmt + 1,
138            self.msg
139        )
140    }
141}
142
143impl std::error::Error for TokenError {}
144
145/// Lift a dispatcher/resolver [`ParseError`] into a [`TokenError`],
146/// preserving its machine-readable classification (the entry points
147/// convert it back verbatim, so `UnknownCommand`/`InvalidSyntax`/
148/// `Validation` survive the round trip). The message is the
149/// dispatcher's own display text; the split loops stamp the line.
150fn lower_err(stmt: usize, e: ParseError) -> TokenError {
151    TokenError {
152        stmt,
153        line: 0,
154        col: 0,
155        msg: e.to_string(),
156        kind: Some(e.kind().clone()),
157    }
158}
159
160/// One split statement: leading bracket groups (guard region) plus
161/// the body tokens. `brace_detached` records a
162/// `Newline`/`Semicolon` between the guard region and a brace-headed
163/// body: in-body such statements are hard errors (a bare `{` is
164/// illegal inside blocks), while top level merges or parses guard
165/// blocks regardless.
166#[derive(Debug, Clone)]
167struct Stmt {
168    guard: Vec<Tok>,
169    body: Vec<Tok>,
170    brace_detached: bool,
171    /// 1-based source line where the body starts (guards ride on
172    /// earlier lines; errors report this).
173    line: usize,
174    /// 1-based column where the body starts (`0` when the head token
175    /// carries no coordinates: synthetic streams). Read off the first
176    /// body token, which always has the statement's own start.
177    col: usize,
178}
179
180impl PartialEq for Stmt {
181    fn eq(&self, other: &Self) -> bool {
182        // Coordinates are provenance (never rendered, never compared),
183        // like `Step`/`Tok`: two splits of one text compare equal.
184        self.guard == other.guard
185            && self.body == other.body
186            && self.brace_detached == other.brace_detached
187    }
188}
189
190impl Eq for Stmt {}
191
192/// True when a newline continues the statement for a multi-line
193/// generic: the body opens a type-carrying statement (TYPE/LET/FOR)
194/// and holds an unclosed `<...>` shape. Only a joint `<` after an
195/// uppercase word opens (never `<=`, never `$VAR<`), so spaced
196/// comparisons keep ending the statement as before. FUNC needs no
197/// gate: parameter types ride inside the atomic paren group, and the
198/// grammar defines no return-type position after the group.
199fn type_continuation_rides(body: &[Tok], next: Option<&Tok>) -> bool {
200    if !matches!(
201        body.first().map(|t| &t.kind),
202        Some(TokKind::Word(w)) if w == KEYWORD_TYPE || w == KEYWORD_LET || w == KEYWORD_FOR
203    ) {
204        return false;
205    }
206    open_generic_depth(body, next) > 0
207}
208
209/// Unclosed `<...>` depth over a statement body: a joint `<` after
210/// an uppercase word opens (generic instantiation), `>` closes.
211fn open_generic_depth(body: &[Tok], next: Option<&Tok>) -> usize {
212    let mut depth = 0usize;
213    for (idx, tok) in body.iter().enumerate() {
214        if !matches!(&tok.kind, TokKind::Punct('<')) {
215            if matches!(&tok.kind, TokKind::Punct('>')) && depth > 0 {
216                depth -= 1;
217            }
218            continue;
219        }
220        if !tok.joint {
221            continue;
222        }
223        if idx == 0 {
224            continue;
225        }
226        if !matches!(
227            body.get(idx - 1).map(|t| &t.kind),
228            Some(TokKind::Word(w)) if is_upper_ident(w)
229        ) {
230            continue;
231        }
232        // `$VAR<` is a comparison, never a generic.
233        if idx >= 2
234            && body.get(idx - 1).is_some_and(|t| t.joint)
235            && matches!(
236                body.get(idx - 2).map(|t| &t.kind),
237                Some(TokKind::Punct('$'))
238            )
239        {
240            continue;
241        }
242        // `<=` is a comparison lead, never a generic open.
243        let followed_by_eq = matches!(
244            body.get(idx + 1).map(|t| &t.kind),
245            Some(TokKind::Punct('='))
246        ) || (idx + 1 == body.len()
247            && matches!(next.map(|t| &t.kind), Some(TokKind::Punct('='))));
248        if !followed_by_eq {
249            depth += 1;
250        }
251    }
252    depth
253}
254
255/// Grammar-state boundary decision: does this `Newline`/`Semicolon`
256/// end the statement? Groups are atomic, so every statement fits one
257/// logical token line; every keyword-headed statement (commands,
258/// wrappers, `LET`/`AWAIT`, block statements, directives) ends here.
259/// Only non-word heads fail, exactly like the grammar's element
260/// mismatch.
261fn boundary_ends_statement(body: &[Tok]) -> Result<bool, String> {
262    let head = match body.first() {
263        None => return Ok(true),
264        Some(t) => t,
265    };
266    match &head.kind {
267        TokKind::Word(_) | TokKind::Punct('$') => Ok(true),
268        // A lone leading `{...}` ends here too: the splitter merges
269        // it into pending waits (`WITH_IO`, `IF`/`ELSE` chains) or
270        // emits it for block-statement lowering, never splitting
271        // inside.
272        TokKind::Group {
273            delim: GroupDelim::Brace,
274            ..
275        } => Ok(true),
276        _ => Err("statement must open with a command word".to_string()),
277    }
278}
279
280/// Bare `WITH_IO [..]` with no inner command: holds the line for a
281/// following `{...}` block (bare-bracket hold), which merges into one
282/// io-block statement. Anything else (or EOF) fails exactly like the
283/// grammar's `must be followed by '{'`.
284fn is_bare_with_io(body: &[Tok]) -> bool {
285    matches!(body.first().map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_WITH_IO)
286        && matches!(
287            body.get(1).map(|t| (&t.kind, t.joint)),
288            Some((
289                TokKind::Group {
290                    delim: GroupDelim::Bracket,
291                    ..
292                },
293                false
294            ))
295        )
296        && body.len() == 2
297}
298
299/// An if-tailed statement body: head `IF`, ends with a non-template
300/// brace (the then/else-if block), ignoring trailing gap comments.
301/// Trailing `//`/`#` runs and balanced `/* */` strip backward (the
302/// grammar's `gap` eats them before the `ELSE` chain, joint state
303/// irrelevant after a complete pair); anything else trailing (text,
304/// groups, strings) breaks the tail. Over-holding is safe: a merged
305/// non-`ELSE` follower releases, and a merged `ELSE` parses exactly
306/// where the grammar would.
307fn is_if_tail(body: &[Tok]) -> bool {
308    if !matches!(body.first().map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_IF) {
309        return false;
310    }
311    let mut end = body.len();
312    loop {
313        // Lexer comment markers.
314        while end > 0 && matches!(&body[end - 1].kind, TokKind::Comment(_)) {
315            end -= 1;
316        }
317        // Earliest comment opener (`//`-pair, `#`, `/*`-pair) starts
318        // trailing comment territory.
319        let mut cut = None;
320        let mut k = 0;
321        while k < end {
322            match &body[k].kind {
323                TokKind::Punct('#') => {
324                    cut = Some(k);
325                    break;
326                }
327                TokKind::Punct('/') if is_comment_open(&body[..end], k) => {
328                    cut = Some(k);
329                    break;
330                }
331                _ => k += 1,
332            }
333        }
334        match cut {
335            Some(k) => {
336                // A balanced `/* */` may be followed by more gap
337                // comments; anything else ends the strip for the
338                // brace check below.
339                if matches!(&body[k].kind, TokKind::Punct('/'))
340                    && !matches!(body.get(k + 1).map(|t| &t.kind), Some(TokKind::Punct('/')))
341                {
342                    match skip_inline_comment(&body[..end], k) {
343                        Some(past) if past < end => {
344                            end = past;
345                            continue;
346                        }
347                        _ => {}
348                    }
349                }
350                end = k;
351                continue;
352            }
353            None => break,
354        }
355    }
356    matches!(
357        body[..end].last().map(|t| &t.kind),
358        Some(TokKind::Group {
359            delim: GroupDelim::Brace,
360            ..
361        })
362    ) && body[..end].last().is_some_and(|t| !is_template_brace(t))
363}
364
365/// True when a body opens with a brace group (guard-block position
366/// or bare block).
367fn starts_brace(body: &[Tok]) -> bool {
368    matches!(
369        body.first().map(|t| &t.kind),
370        Some(TokKind::Group {
371            delim: GroupDelim::Brace,
372            ..
373        })
374    )
375}
376
377/// Source lines spanned by one token (for the splitter's line
378/// counter): newlines, `/* */` comment interiors, and nested group
379/// contents. Everything else occupies its own line.
380fn tok_newlines(tok: &Tok) -> usize {
381    match &tok.kind {
382        TokKind::Newline => 1,
383        TokKind::Comment(text) => text.matches('\n').count(),
384        TokKind::Group { inner, .. } => inner.iter().map(tok_newlines).sum(),
385        _ => 0,
386    }
387}
388
389/// Stamp an error with the innermost statement's position when it
390/// has none yet (deeper frames stamp first, so outer frames never
391/// overwrite real positions). Each component fills independently.
392fn stamp_pos(err: TokenError, line: usize, col: usize) -> TokenError {
393    TokenError {
394        line: if err.line == 0 { line } else { err.line },
395        col: if err.col == 0 { col } else { err.col },
396        ..err
397    }
398}
399
400/// Split top-level tokens into statements. Leading `[..]` groups attach
401/// to the following statement as its guard region; `Newline`/`Semicolon`
402/// end statements per [`boundary_ends_statement`]. Empty statements
403/// (blank lines, stray `;`) drop, matching the blank/semicolon
404/// grammar elements. Comment markers drop silently everywhere except
405/// pending `ELSE` waits, which a comment line breaks exactly like the
406/// grammar. Mid-line `//` runs and `#`/`/*` opens with an empty body
407/// skip as comments (statement position, like the grammar's silent
408/// elements); anywhere else they stay payload text for the arg engine.
409fn split_statements(toks: &[Tok], base: usize) -> Result<Vec<Stmt>, TokenError> {
410    let mut stmts = Vec::new();
411    let mut guard = Vec::new();
412    let mut body: Vec<Tok> = Vec::new();
413    let mut stmt_idx = 0;
414    // 1-based source line tracker: `base` is the line `toks[0]` starts
415    // on (1 at top level, the enclosing statement's line inside
416    // groups, where headers are single-line so the brace shares it).
417    // Groups and block comments advance past their inner newlines;
418    // every pushed statement records its body's start line for errors.
419    let mut line = base;
420    let mut start_line = base;
421    let mut start_col = 0;
422    // Bare `WITH_IO [..]` awaiting its `{...}` block (see
423    // `is_bare_with_io`): the guard and body hold across any
424    // separator until the brace arrives or the wait fails.
425    // Pending holds carry their body's start line with them.
426    let mut pending_io: Option<(Vec<Tok>, Vec<Tok>, usize, usize)> = None;
427    // If-tailed statement awaiting an `ELSE` continuation across
428    // newlines only (a `;` breaks the chain like the grammar).
429    let mut pending_if: Option<(Vec<Tok>, Vec<Tok>, usize, usize)> = None;
430    // Separator crossed between the guard region and the body start:
431    // only observed for brace-headed bodies (`brace_detached`).
432    let mut detached = false;
433    // Flush a statement, resolving pending waits first. `via_newline`
434    // records the separator kind: only newlines hold/merge `ELSE`
435    // chains; `;` and EOF release them. `line` is the current tracker
436    // for wait-failure errors; `start_line` is this body's start.
437    let flush_or_hold = |stmts: &mut Vec<Stmt>,
438                         guard: &mut Vec<Tok>,
439                         body: &mut Vec<Tok>,
440                         detached: &mut bool,
441                         stmt_idx: &mut usize,
442                         pending_io: &mut Option<(Vec<Tok>, Vec<Tok>, usize, usize)>,
443                         pending_if: &mut Option<(Vec<Tok>, Vec<Tok>, usize, usize)>,
444                         via_newline: bool,
445                         start_line: usize,
446                         start_col: usize,
447                         line: usize|
448     -> Result<(), TokenError> {
449        if body.is_empty() {
450            guard.clear();
451            *detached = false;
452            return Ok(());
453        }
454        // Pending `WITH_IO` wait takes precedence (the holds are
455        // mutually exclusive: setting either returns first).
456        if let Some((pending_guard, mut pending_body, pending_line, pending_col)) =
457            pending_io.take()
458        {
459            // Only a lone guard-less `{...}` group satisfies the wait;
460            // anything else (commands, guarded braces) fails like the
461            // grammar's `must be followed by '{'`.
462            let lone_brace = guard.is_empty()
463                && body.len() == 1
464                && matches!(
465                    body.first().map(|t| &t.kind),
466                    Some(TokKind::Group {
467                        delim: GroupDelim::Brace,
468                        ..
469                    })
470                );
471            if !lone_brace {
472                return Err(TokenError {
473                    stmt: *stmt_idx,
474                    msg: "WITH_IO block must be followed by '{'".to_string(),
475                    line: pending_line,
476                    col: pending_col,
477                    kind: None,
478                });
479            }
480            pending_body.extend(std::mem::take(body));
481            guard.clear();
482            *detached = false;
483            stmts.push(Stmt {
484                guard: pending_guard,
485                body: pending_body,
486                brace_detached: false,
487                line: pending_line,
488                col: pending_col,
489            });
490            *stmt_idx += 1;
491            return Ok(());
492        }
493        // Pending `ELSE` wait: merge guard-less `ELSE`-led statements.
494        // The wait was set across a newline (only newlines hold), so
495        // the separator kind of *this* flush is irrelevant — `;` and
496        // EOF merge too; anything else releases the held IF.
497        if let Some((held_guard, mut held_body, held_line, held_col)) = pending_if.take() {
498            let else_start = guard.is_empty()
499                && matches!(
500                    body.first().map(|t| &t.kind),
501                    Some(TokKind::Word(w)) if w == KEYWORD_ELSE
502                );
503            if !else_start {
504                stmts.push(Stmt {
505                    guard: held_guard,
506                    body: held_body,
507                    brace_detached: false,
508                    line: held_line,
509                    col: held_col,
510                });
511                *stmt_idx += 1;
512            } else {
513                // The merged chain may hold again for a further
514                // `ELSE`, newlines only, like the grammar. A newline
515                // marker joins the parts: `#` comments end at it
516                // (their extent is unrecoverable post-merge), while
517                // `//`/`/*` carry their own extents.
518                held_body.push(Tok::fresh(TokKind::Newline, false));
519                held_body.extend(std::mem::take(body));
520                guard.clear();
521                *detached = false;
522                if via_newline && is_if_tail(&held_body) {
523                    *pending_if = Some((held_guard, held_body, held_line, held_col));
524                    return Ok(());
525                }
526                stmts.push(Stmt {
527                    guard: held_guard,
528                    body: held_body,
529                    brace_detached: false,
530                    line: held_line,
531                    col: held_col,
532                });
533                *stmt_idx += 1;
534                return Ok(());
535            }
536        }
537        if is_bare_with_io(body) {
538            if pending_io.is_some() {
539                return Err(TokenError {
540                    stmt: *stmt_idx,
541                    msg: "previous WITH_IO block is still waiting for '{'".to_string(),
542                    line,
543                    col: start_col,
544                    kind: None,
545                });
546            }
547            *pending_io = Some((
548                std::mem::take(guard),
549                std::mem::take(body),
550                start_line,
551                start_col,
552            ));
553            *detached = false;
554            return Ok(());
555        }
556        // Ordinary statement: emit it, holding if-tailed bodies for
557        // an `ELSE` continuation across newlines only.
558        if via_newline && is_if_tail(body) {
559            *pending_if = Some((
560                std::mem::take(guard),
561                std::mem::take(body),
562                start_line,
563                start_col,
564            ));
565            *detached = false;
566            return Ok(());
567        }
568        let brace_detached = *detached && !guard.is_empty() && starts_brace(body);
569        stmts.push(Stmt {
570            guard: std::mem::take(guard),
571            body: std::mem::take(body),
572            brace_detached,
573            line: start_line,
574            col: start_col,
575        });
576        *detached = false;
577        *stmt_idx += 1;
578        Ok(())
579    };
580    // Release a pending `ELSE` wait by emitting the held IF as-is.
581    // (Inlined at use sites: a closure would collide with
582    // `flush_or_hold`'s borrow of the statement buffer.)
583    let mut i = 0;
584    // Open text-`/*` depth (line-start comments arrive as `Comment`
585    // toks; `//` never spans separators): newlines and semicolons
586    // inside never split, and `[` never guards (the closer, an
587    // error, or downstream rules resolve everything, exactly like
588    // the grammar).
589    let mut comment_depth = 0usize;
590    // True when `toks[i]` opens a text block comment (`/` plus a
591    // joint `*`; `//` is line-comment territory, handled elsewhere).
592    let block_open_at = |toks: &[Tok], i: usize| {
593        matches!(toks.get(i).map(|t| &t.kind), Some(TokKind::Punct('/')))
594            && matches!(
595                toks.get(i + 1).map(|t| (&t.kind, t.joint)),
596                Some((TokKind::Punct('*'), true))
597            )
598    };
599    // True when `toks[i]` closes one (`*` plus a joint `/`).
600    let block_close_at = |toks: &[Tok], i: usize| {
601        matches!(toks.get(i).map(|t| &t.kind), Some(TokKind::Punct('*')))
602            && matches!(
603                toks.get(i + 1).map(|t| (&t.kind, t.joint)),
604                Some((TokKind::Punct('/'), true))
605            )
606    };
607    while i < toks.len() {
608        let tok = &toks[i];
609        // Statement-start `/*` (silent gap position): skip balanced,
610        // failing unclosed like the grammar; mid-body opens only
611        // deepen the tracker below and ride into args as payload.
612        if body.is_empty() && comment_depth == 0 && block_open_at(toks, i) {
613            match skip_inline_comment(toks, i) {
614                Some(past) => {
615                    // The skipped span may cross lines (`/*a\nb*/`).
616                    line += toks[i..past].iter().map(tok_newlines).sum::<usize>();
617                    i = past;
618                    continue;
619                }
620                None => {
621                    return Err(TokenError {
622                        stmt: stmt_idx,
623                        msg: "unclosed block comment".to_string(),
624                        line,
625                        col: tok.col,
626                        kind: None,
627                    });
628                }
629            }
630        }
631        // Nesting transitions on text pairs (mid-body opens deepen;
632        // closers pop when nested).
633        if block_open_at(toks, i) && (comment_depth > 0 || !body.is_empty()) {
634            comment_depth += 1;
635        } else if block_close_at(toks, i) && comment_depth > 0 {
636            comment_depth -= 1;
637        }
638        // Inside a block comment everything rides into the current
639        // body (never splits, never guards, never releases waits,
640        // never skips): gap positions swallow it downstream, arg
641        // positions fail or math over it, exactly like the grammar.
642        if comment_depth > 0 {
643            if body.is_empty() {
644                // Head-token coordinates are authoritative: the line
645                // tracker lags content stripped before lexing (comments
646                // vanish on the token path, leaving no newline behind).
647                // Zero coordinates (synthetic streams) keep the tracker.
648                if tok.line > 0 {
649                    start_line = tok.line;
650                } else {
651                    start_line = line;
652                }
653                if tok.col > 0 {
654                    start_col = tok.col;
655                }
656            }
657            line += tok_newlines(tok);
658            body.push(tok.clone());
659            detached = false;
660            i += 1;
661            continue;
662        }
663        match &tok.kind {
664            TokKind::Newline => {
665                if body.is_empty() {
666                    // A separator between the guard region and a
667                    // following brace matters (see `brace_detached`).
668                    detached = true;
669                    line += 1;
670                    i += 1;
671                    continue;
672                }
673                // Multi-line generics: a newline inside an unclosed
674                // `<...>` rides into the body, so `MAP<...>` shapes may
675                // span lines. Anything else ends here as before.
676                if type_continuation_rides(&body, toks.get(i + 1)) {
677                    line += 1;
678                    body.push(tok.clone());
679                    detached = false;
680                    i += 1;
681                    continue;
682                }
683                match boundary_ends_statement(&body) {
684                    Ok(true) => flush_or_hold(
685                        &mut stmts,
686                        &mut guard,
687                        &mut body,
688                        &mut detached,
689                        &mut stmt_idx,
690                        &mut pending_io,
691                        &mut pending_if,
692                        true,
693                        start_line,
694                        start_col,
695                        line,
696                    )?,
697                    Ok(false) => {}
698                    Err(msg) => {
699                        return Err(TokenError {
700                            stmt: stmt_idx,
701                            msg,
702                            line: start_line,
703                            col: start_col,
704                            kind: None,
705                        });
706                    }
707                }
708                line += 1;
709                i += 1;
710            }
711            TokKind::Semicolon => {
712                if body.is_empty() {
713                    // A `;` breaks `ELSE` chains (release the hold)
714                    // but not `WITH_IO` waits (probed `;` merge).
715                    if let Some((held_guard, held_body, held_line, held_col)) = pending_if.take() {
716                        stmts.push(Stmt {
717                            guard: held_guard,
718                            body: held_body,
719                            brace_detached: false,
720                            line: held_line,
721                            col: held_col,
722                        });
723                        stmt_idx += 1;
724                    }
725                    detached = true;
726                    i += 1;
727                    continue;
728                }
729                match boundary_ends_statement(&body) {
730                    Ok(true) => flush_or_hold(
731                        &mut stmts,
732                        &mut guard,
733                        &mut body,
734                        &mut detached,
735                        &mut stmt_idx,
736                        &mut pending_io,
737                        &mut pending_if,
738                        false,
739                        start_line,
740                        start_col,
741                        line,
742                    )?,
743                    Ok(false) => {}
744                    Err(msg) => {
745                        return Err(TokenError {
746                            stmt: stmt_idx,
747                            msg,
748                            line: start_line,
749                            col: start_col,
750                            kind: None,
751                        });
752                    }
753                }
754                i += 1;
755            }
756            // Lexer comment markers drop silently, but release a
757            // pending `ELSE` wait (a comment line breaks the chain
758            // like the grammar); `WITH_IO` waits survive comments.
759            TokKind::Comment(text) => {
760                if let Some((held_guard, held_body, held_line, held_col)) = pending_if.take() {
761                    stmts.push(Stmt {
762                        guard: held_guard,
763                        body: held_body,
764                        brace_detached: false,
765                        line: held_line,
766                        col: held_col,
767                    });
768                    stmt_idx += 1;
769                }
770                // A joint marker (`a//b`) is payload, not trivia: it
771                // rides into the body so arg assembly glues it
772                // literally, exactly like the grammar. Gapped and
773                // line-start markers drop.
774                if tok.joint && !body.is_empty() {
775                    line += text.matches('\n').count();
776                    body.push(tok.clone());
777                    detached = false;
778                    i += 1;
779                    continue;
780                }
781                // Block markers may span lines (`/*a\nb*/`).
782                line += text.matches('\n').count();
783                i += 1;
784            }
785            // A `//` run with an empty body (mid-line, e.g. after
786            // `;`) is a comment to the line end; with a non-empty
787            // body the slash-run rule owns it as payload text.
788            TokKind::Punct('/') if body.is_empty() && is_comment_open(toks, i) => {
789                if matches!(toks.get(i + 1).map(|t| &t.kind), Some(TokKind::Punct('/'))) {
790                    while i < toks.len() && !matches!(&toks[i].kind, TokKind::Newline) {
791                        i += 1;
792                    }
793                } else {
794                    match skip_inline_comment(toks, i) {
795                        Some(past) => i = past,
796                        None => {
797                            return Err(TokenError {
798                                stmt: stmt_idx,
799                                msg: "unclosed block comment".to_string(),
800                                line,
801                                col: tok.col,
802                                kind: None,
803                            });
804                        }
805                    }
806                }
807            }
808            // `#` with an empty body (e.g. after `;`) is a comment
809            // to the line end; mid-body it stays arg text.
810            TokKind::Punct('#') if body.is_empty() => {
811                while i < toks.len() && !matches!(&toks[i].kind, TokKind::Newline) {
812                    i += 1;
813                }
814            }
815            TokKind::Group { delim, .. } if body.is_empty() && *delim == GroupDelim::Bracket => {
816                // Guard groups may span lines; the body starts after.
817                line += tok_newlines(tok);
818                guard.push(tok.clone());
819                detached = false;
820                i += 1;
821            }
822            _ => {
823                if body.is_empty() {
824                    // Head-token coordinates are authoritative (see
825                    // above); the tracker is the fallback.
826                    if tok.line > 0 {
827                        start_line = tok.line;
828                    } else {
829                        start_line = line;
830                    }
831                    if tok.col > 0 {
832                        start_col = tok.col;
833                    }
834                }
835                line += tok_newlines(tok);
836                body.push(tok.clone());
837                i += 1;
838            }
839        }
840    }
841    if !body.is_empty() {
842        match boundary_ends_statement(&body) {
843            Ok(_) => flush_or_hold(
844                &mut stmts,
845                &mut guard,
846                &mut body,
847                &mut detached,
848                &mut stmt_idx,
849                &mut pending_io,
850                &mut pending_if,
851                false,
852                start_line,
853                start_col,
854                line,
855            )?,
856            Err(msg) => {
857                return Err(TokenError {
858                    stmt: stmt_idx,
859                    msg,
860                    line: start_line,
861                    col: start_col,
862                    kind: None,
863                });
864            }
865        }
866    } else if !guard.is_empty() {
867        // Trailing guards with no following command error (probed: a
868        // lone `[env:X]` is an error), never drop silently.
869        return Err(TokenError {
870            stmt: stmt_idx,
871            msg: "guard declared without a following command".to_string(),
872            line,
873            col: 0,
874            kind: None,
875        });
876    }
877    // Release a trailing `ELSE` wait; a trailing `WITH_IO` wait fails.
878    if let Some((held_guard, held_body, held_line, held_col)) = pending_if.take() {
879        stmts.push(Stmt {
880            guard: held_guard,
881            body: held_body,
882            brace_detached: false,
883            line: held_line,
884            col: held_col,
885        });
886    }
887    if let Some((_, _, pending_line, pending_col)) = pending_io.take() {
888        return Err(TokenError {
889            stmt: stmt_idx,
890            msg: "WITH_IO block must be followed by '{'".to_string(),
891            line: pending_line,
892            col: pending_col,
893            kind: None,
894        });
895    }
896    Ok(stmts)
897}
898
899/// Splice in-body bracket/paren groups to flat raw text: arg-position
900/// brackets read as ordinary characters split purely on whitespace
901/// (`ECHO [a, b]` is args `"[a,"` + `"b]"`), so the parser expands
902/// each group to open-punct + inner + close-punct and lets the normal
903/// gap-split/render reproduce the bytes exactly (probed parity).
904/// Recursion handles nesting; edge joints ride along untouched. Brace
905/// groups stay put (blocks, never args). Newlines/semicolons spliced
906/// from multi-line groups fail loudly in assembly.
907fn splice_arg_groups(body: &[Tok], stmt: usize) -> Result<Vec<Tok>, TokenError> {
908    let _ = stmt;
909    let mut out = Vec::new();
910    for tok in body.iter() {
911        match &tok.kind {
912            TokKind::Group {
913                delim: GroupDelim::Brace,
914                ..
915            } => out.push(tok.clone()),
916            // Call parens stay structural: exploding them to puncts
917            // would strand full-region calls (`MAKE()` in arg position)
918            // as raw text, disagreeing with assignment values and
919            // RUN-exec items, which both parse calls. Brackets keep
920            // the raw-text splicing below (whitespace splits inside
921            // them, strings de-quote to words).
922            TokKind::Group {
923                delim: GroupDelim::Paren,
924                ..
925            } => out.push(tok.clone()),
926            TokKind::Group {
927                delim: GroupDelim::Bracket,
928                inner,
929                close_joint,
930                ..
931            } => {
932                out.push(Tok::fresh(TokKind::Punct('['), tok.joint));
933                // Inside brackets raw-text rules apply: quotes are
934                // characters, blocks never dedent, and whitespace splits
935                // runs (`['a b']` is args `"['a"` + `"b']"`). Convert
936                // spliced strings back to word text (splitting it like
937                // raw text); top-level strings stay structural.
938                for t in splice_arg_groups(inner, stmt)? {
939                    match &t.kind {
940                        TokKind::Str { text, quote } => {
941                            out.extend(split_word_text(&format!("{quote}{text}{quote}"), t.joint));
942                        }
943                        TokKind::BlockStr(full) => {
944                            out.extend(split_word_text(full, t.joint));
945                        }
946                        _ => out.push(t),
947                    }
948                }
949                out.push(Tok::fresh(TokKind::Punct(']'), *close_joint));
950            }
951            _ => out.push(tok.clone()),
952        }
953    }
954    Ok(out)
955}
956
957/// Split re-quoted raw text on whitespace runs. The first piece keeps the source joint flag; the rest break
958/// (whitespace separates args). Multi-space gaps normalize to one
959/// (documented edge, same class as group rendering).
960fn split_word_text(text: &str, joint: bool) -> Vec<Tok> {
961    let mut out = Vec::new();
962    let mut first = true;
963    for piece in text.split_whitespace() {
964        out.push(Tok::fresh(
965            TokKind::Word(piece.to_string()),
966            if first { joint } else { false },
967        ));
968        first = false;
969    }
970    if out.is_empty() {
971        out.push(Tok::fresh(TokKind::Word(text.to_string()), joint));
972    }
973    out
974}
975
976/// Assignment key charset, minus the `=` the
977/// classifier handles separately. Words are pre-filtered by the same
978/// set; `$`, quotes, and groups never start a key.
979fn is_assign_key_char(c: char) -> bool {
980    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':')
981}
982
983/// Match an assignment key run at an argument start: joint
984/// word/punct run in the key charset, non-empty, not `--`-led
985/// (flags keep their literal reading). Returns the key and end index.
986fn match_assign_key(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
987    let mut out = String::new();
988    let mut p = pos;
989    loop {
990        let t = toks.get(p)?;
991        if !out.is_empty() && !t.joint {
992            break;
993        }
994        match &t.kind {
995            TokKind::Word(w) => out.push_str(w),
996            TokKind::Punct(c) if is_assign_key_char(*c) => out.push(*c),
997            _ => break,
998        }
999        p += 1;
1000    }
1001    if out.is_empty() || out.starts_with("--") {
1002        return None;
1003    }
1004    if !out
1005        .chars()
1006        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':'))
1007    {
1008        return None;
1009    }
1010    Some((out, p))
1011}
1012
1013/// Assignment boundary ahead (for value scanning): an argument start
1014/// holding `KEY=` (key run plus `=` at any gap).
1015/// Groups and strings are opaque: a `=` inside them never counts.
1016fn at_assign_boundary(toks: &[Tok], pos: usize) -> bool {
1017    match match_assign_key(toks, pos) {
1018        Some((_, end)) => matches!(toks.get(end).map(|t| &t.kind), Some(TokKind::Punct('='))),
1019        None => false,
1020    }
1021}
1022
1023/// Line breaks nested in a raw paren run fail like flat ones did
1024/// before parens stayed structural: splicing used to surface every
1025/// `;`/newline to `render_raw_text`'s reject arm. Brace contents are
1026/// skipped (templates and blocks render whole, then and now);
1027/// brackets nested in parens were spliced before, so their breaks
1028/// fail here too. Single owner for the rule; both raw fallbacks
1029/// (positional args, assignment values) ride `render_raw_text`.
1030fn reject_paren_line_breaks(inner: &[Tok], stmt: usize) -> Result<(), TokenError> {
1031    for tok in inner {
1032        match &tok.kind {
1033            TokKind::Newline | TokKind::Semicolon => {
1034                return Err(TokenError {
1035                    stmt,
1036                    msg: "unexpected line break in argument".to_string(),
1037                    line: tok.line,
1038                    col: tok.col,
1039                    kind: None,
1040                });
1041            }
1042            TokKind::Group {
1043                delim: GroupDelim::Brace,
1044                ..
1045            } => {}
1046            TokKind::Group { inner, .. } => reject_paren_line_breaks(inner, stmt)?,
1047            _ => {}
1048        }
1049    }
1050    Ok(())
1051}
1052
1053/// Raw-text render of one gap-run (or value span): words/puncts
1054/// literally (`$`+word literally, `$` elsewhere errors), strings by
1055/// their inner bytes, blocks lowered, groups spliced. Gaps collapse
1056/// to one space like `collapse_ws`; newlines/semicolons fail (the
1057/// grammar's raw span excludes them).
1058fn render_raw_text(toks: &[Tok], stmt: usize) -> Result<String, TokenError> {
1059    let mut out = String::new();
1060    let mut i = 0;
1061    while i < toks.len() {
1062        let tok = &toks[i];
1063        if !tok.joint && !out.is_empty() {
1064            out.push(' ');
1065        }
1066        match &tok.kind {
1067            TokKind::Word(w) => out.push_str(w),
1068            TokKind::Punct(c) => {
1069                if *c == '$' {
1070                    // Lone-`$` runs never reach here (expression
1071                    // extension claims them first and fails loudly).
1072                    // Elsewhere `$` renders literally (probed `a$(x)`
1073                    // reads raw) except before a brace group, where
1074                    // the grammar strands it (probed `K=${x}` fails).
1075                    let next = toks.get(i + 1);
1076                    let brace_next = next.is_some_and(|t| {
1077                        matches!(
1078                            &t.kind,
1079                            TokKind::Group {
1080                                delim: GroupDelim::Brace,
1081                                ..
1082                            }
1083                        )
1084                    });
1085                    if brace_next {
1086                        return Err(TokenError {
1087                            stmt,
1088                            msg: "unexpected `$` in argument".to_string(),
1089                            line: 0,
1090                            col: 0,
1091                            kind: None,
1092                        });
1093                    }
1094                    out.push('$');
1095                } else {
1096                    out.push(*c);
1097                }
1098            }
1099            // Standalone quotes strip (the caller handles single-tok
1100            // runs); glued quotes keep their marks, like the grammar's
1101            // mixed fragments (`>"a"` stays quoted, `"a"` strips).
1102            TokKind::Str { text: s, quote } => {
1103                let glued = tok.joint || toks.get(i + 1).is_some_and(|t| t.joint);
1104                if toks.len() > 1 && glued {
1105                    out.push(*quote);
1106                    out.push_str(s);
1107                    out.push(*quote);
1108                } else {
1109                    out.push_str(s);
1110                }
1111            }
1112            // Comments reproduce verbatim (templates keep comment
1113            // text like the atomic grammar span); gaps collapse
1114            // around them like other fragments per the documented
1115            // single-space normalization.
1116            TokKind::Comment(text) => out.push_str(text),
1117            TokKind::BlockStr(full) => {
1118                // Glued blocks keep their delimiters, like quotes.
1119                let glued = tok.joint || toks.get(i + 1).is_some_and(|t| t.joint);
1120                if toks.len() > 1 && glued {
1121                    out.push_str(full);
1122                } else {
1123                    out.push_str(&crate::command::lower_block_string(full));
1124                }
1125            }
1126            TokKind::Group {
1127                delim: GroupDelim::Brace,
1128                inner,
1129                open_joint,
1130                close_joint,
1131                ..
1132            } => out.push_str(&render_brace_run_text(inner, *open_joint, *close_joint)),
1133            TokKind::Group {
1134                delim: GroupDelim::Bracket,
1135                inner,
1136                open_joint,
1137                close_joint,
1138                ..
1139            } => out.push_str(&render_group('[', ']', inner, *open_joint, *close_joint)),
1140            TokKind::Group {
1141                delim: GroupDelim::Paren,
1142                inner,
1143                open_joint,
1144                close_joint,
1145                ..
1146            } => {
1147                // Parens stayed structural (call shapes need them), so
1148                // surface the breaks splicing used to expose: a `;` or
1149                // newline anywhere inside fails exactly like a flat one
1150                // did. Brace contents keep the verbatim whole-render
1151                // below; brackets nested in parens were spliced before,
1152                // so their breaks fail here too.
1153                reject_paren_line_breaks(inner, stmt)?;
1154                out.push_str(&render_group('(', ')', inner, *open_joint, *close_joint))
1155            }
1156            TokKind::Newline | TokKind::Semicolon => {
1157                return Err(TokenError {
1158                    stmt,
1159                    msg: "unexpected line break in argument".to_string(),
1160                    line: 0,
1161                    col: 0,
1162                    kind: None,
1163                });
1164            }
1165        }
1166        i += 1;
1167    }
1168    Ok(out)
1169}
1170
1171/// Build an assignment value `Arg` over a region that runs to the next
1172/// boundary or end. Single quoted/block strings keep `quoted=true`; a
1173/// region that is exactly one lone `$var`/keypath/`env:`/call shape
1174/// stays typed (calls resolve through the shared resolver, matching
1175/// `assign_expr`); everything else renders raw. A quoted unit followed
1176/// by joint content errors (probed: `K="a"b` fails), like the grammar.
1177/// Lone-shape failures stash into `deferred` and render raw: the
1178/// command's own lowering error (if any) takes precedence, and the
1179/// stashed call error surfaces only when lowering succeeds.
1180fn build_value_arg(
1181    region: &[Tok],
1182    stmt: usize,
1183    ctx: &ParseCtx,
1184    lone_ok: bool,
1185    deferred: &mut Option<TokenError>,
1186) -> Result<Arg, TokenError> {
1187    if region.is_empty() {
1188        return Ok(Arg::String(String::new(), false));
1189    }
1190    if region.len() == 1 {
1191        match &region[0].kind {
1192            TokKind::Str { text: s, .. } => return Ok(Arg::String(s.clone(), true)),
1193            TokKind::BlockStr(full) => {
1194                return Ok(Arg::String(crate::command::lower_block_string(full), true));
1195            }
1196            _ => {}
1197        }
1198    }
1199    if region.len() > 1
1200        && matches!(&region[0].kind, TokKind::Str { .. } | TokKind::BlockStr(_))
1201        && region[1].joint
1202    {
1203        return Err(TokenError {
1204            stmt,
1205            msg: "unexpected text after quoted value".to_string(),
1206            line: 0,
1207            col: 0,
1208            kind: None,
1209        });
1210    }
1211    // Single-quoted values mid-line (`K='a b'`): the string lexer only
1212    // opens `'` gapped, so these arrive as fragments; the grammar's
1213    // `quoted_string` admits them anywhere. Reassemble a region that
1214    // opens with `'` and closes at its end, stripping exactly like a
1215    // structural string (escapes intact for runtime, like `Str`).
1216    if matches!(&region[0].kind, TokKind::Punct('\''))
1217        && let Some(text) = try_squote_value(region)
1218    {
1219        return Ok(Arg::String(text, true));
1220    }
1221    // Lone typed values apply only at a true end/boundary, never
1222    // past a comment (the grammar's `!assign_expr_cont` guard).
1223    // Failures stash (see above) so command syntax owns precedence.
1224    if lone_ok {
1225        match try_lone_value_expr(region, stmt, ctx) {
1226            Ok(Some(expr)) => return Ok(expr),
1227            Ok(None) => {}
1228            Err(err) => {
1229                deferred.get_or_insert(err);
1230            }
1231        }
1232    }
1233    Ok(Arg::String(render_raw_text(region, stmt)?, false))
1234}
1235
1236/// Reassemble a single-quoted assignment value (`K='a b'`) from its
1237/// lexer fragments: the opener must close at the region end (a
1238/// trailing fragment falls back to raw text, which fails downstream
1239/// like the grammar). Inner gaps join with one space and nested
1240/// double quotes re-quote (the atomic span keeps them); `\'` escapes
1241/// pass through intact for runtime, like structural strings. `None`
1242/// on shape miss.
1243fn try_squote_value(region: &[Tok]) -> Option<String> {
1244    // Closing `'`: first unescaped quote past the opener.
1245    let mut close = None;
1246    let mut i = 1;
1247    while i < region.len() {
1248        match &region[i].kind {
1249            TokKind::Punct('\\') => i += 2,
1250            TokKind::Punct('\'') => {
1251                close = Some(i);
1252                break;
1253            }
1254            _ => i += 1,
1255        }
1256    }
1257    if close != Some(region.len() - 1) {
1258        return None;
1259    }
1260    let mut out = String::new();
1261    for tok in &region[1..region.len() - 1] {
1262        if !tok.joint && !out.is_empty() {
1263            out.push(' ');
1264        }
1265        match &tok.kind {
1266            TokKind::Word(w) => out.push_str(w),
1267            TokKind::Punct(c) => out.push(*c),
1268            TokKind::Semicolon => out.push(';'),
1269            // Nested double quotes keep their marks (the atomic span
1270            // never strips them); triple quotes pass through whole.
1271            TokKind::Str { text, quote } => {
1272                out.push(*quote);
1273                out.push_str(text);
1274                out.push(*quote);
1275            }
1276            TokKind::BlockStr(full) => out.push_str(full),
1277            // Groups and newlines never occur in value regions (the
1278            // splitter owns them); anything else breaks the shape.
1279            _ => return None,
1280        }
1281    }
1282    Some(out)
1283}
1284
1285/// Lone assignable shapes (`assign_expr` without continuation): `$var`,
1286/// key paths, `env:KEY`, and full-region calls (resolved). Anything
1287/// longer renders raw; the caller decides strictness.
1288fn try_lone_value_expr(
1289    region: &[Tok],
1290    stmt: usize,
1291    ctx: &ParseCtx,
1292) -> Result<Option<Arg>, TokenError> {
1293    // `$` shapes: exactly Punct+Word or dotted runs, all joint past
1294    // the first (the region starts at an argument start by construction).
1295    if matches!(region.first().map(|t| &t.kind), Some(TokKind::Punct('$'))) {
1296        let mut cur = Cursor::expr(region, stmt);
1297        cur.pos += 1;
1298        let base = match cur.next() {
1299            Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
1300                match &t.kind {
1301                    TokKind::Word(w) => w.clone(),
1302                    _ => unreachable!(),
1303                }
1304            }
1305            _ => return Ok(None),
1306        };
1307        let mut keys = Vec::new();
1308        loop {
1309            let dot = matches!(
1310                cur.toks.get(cur.pos).map(|t| &t.kind),
1311                Some(TokKind::Punct('.'))
1312            ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
1313            let seg = cur.toks.get(cur.pos + 1);
1314            let seg_ok = dot
1315                && matches!(seg.map(|t| &t.kind), Some(TokKind::Word(w)) if is_key_segment(w))
1316                && seg.is_some_and(|t| t.joint);
1317            if !seg_ok {
1318                break;
1319            }
1320            if let Some(TokKind::Word(w)) = seg.map(|t| &t.kind) {
1321                keys.push(w.clone());
1322            }
1323            cur.pos += 2;
1324        }
1325        if cur.pos != region.len() {
1326            return Ok(None);
1327        }
1328        return Ok(Some(Arg::Expr(if keys.is_empty() {
1329            Expr::Var(base)
1330        } else {
1331            Expr::KeyPath { base, keys }
1332        })));
1333    }
1334    // `env:KEY` read, gapless and exact.
1335    if region.len() == 3
1336        && matches!(&region[0].kind, TokKind::Word(w) if w == "env")
1337        && matches!(&region[1].kind, TokKind::Punct(':'))
1338        && region[1].joint
1339        && let TokKind::Word(k) = &region[2].kind
1340        && is_env_key(k)
1341        && region[2].joint
1342    {
1343        return Ok(Some(Arg::Expr(Expr::Env(k.clone()))));
1344    }
1345    // Full-region call: resolve and keep typed (canonical rendering
1346    // happens per command: verbatim for ENV/EXPAND, `K=`-joined text
1347    // elsewhere, all from the same `Arg::Expr`). Single owner for the
1348    // call tail; positional args share it (see `build_arg_tokens`).
1349    if let Some(arg) = try_lone_call_expr(region, stmt, ctx)? {
1350        return Ok(Some(arg));
1351    }
1352    Ok(None)
1353}
1354
1355/// Full-region call shape (`NAME(...)`, `MOD::NAME(...)`) over one
1356/// argument run: parse args through the shared call owner and resolve
1357/// through the shared resolver, so assignment values, RUN-exec items,
1358/// and generic positional args can never disagree on what a call is.
1359/// `None` on shape miss (caller renders raw); errors propagate, so a
1360/// misspelled callee fails loud instead of going literal.
1361fn try_lone_call_expr(
1362    region: &[Tok],
1363    stmt: usize,
1364    ctx: &ParseCtx,
1365) -> Result<Option<Arg>, TokenError> {
1366    if let Some((name, paren)) = call_shape_at(region, 0, false)
1367        && paren + 1 == region.len()
1368        && let TokKind::Group { inner, .. } = &region[paren].kind
1369    {
1370        let inner = inner.clone();
1371        let args = parse_call_args(&inner, stmt, ctx)?;
1372        if name == KEYWORD_INSPECT {
1373            let [arg] = args.as_slice() else {
1374                return Err(TokenError {
1375                    stmt,
1376                    msg: "INSPECT requires exactly one argument: INSPECT($var)".to_string(),
1377                    line: 0,
1378                    col: 0,
1379                    kind: None,
1380                });
1381            };
1382            if let Expr::Var(var) = arg {
1383                return Ok(Some(Arg::Expr(Expr::Inspect(var.clone()))));
1384            }
1385            return Err(TokenError {
1386                stmt,
1387                msg: format!("INSPECT requires a $variable argument, found {arg:?}"),
1388                line: 0,
1389                col: 0,
1390                kind: None,
1391            });
1392        }
1393        let qualified = resolve_name(ctx, stmt, &name)?;
1394        return Ok(Some(Arg::Expr(Expr::Call {
1395            name: qualified,
1396            args,
1397        })));
1398    }
1399    Ok(None)
1400}
1401
1402/// Expression extension for `$`/`env:`-led argument starts: parse a
1403/// full expression (operators reach across gaps exactly like the
1404/// grammar's inner `gap`s). Ending at a gap/end yields a typed single
1405/// group; ending mid-run falls back to raw text of the run (`$x=K`);
1406/// parse failure is fatal (every fragment alternative failed).
1407/// Returns the arg and tokens consumed.
1408fn try_expr_arg(
1409    toks: &[Tok],
1410    pos: usize,
1411    stmt: usize,
1412    ctx: &ParseCtx,
1413) -> Result<Option<(Arg, usize)>, TokenError> {
1414    let extend = matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('$')))
1415        || matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == "env");
1416    if !extend {
1417        return Ok(None);
1418    }
1419    // A bare `env` head only extends into a real `env:KEY` read (joint
1420    // `:`); dotted bare words (`env.txt`) stay raw strings like the
1421    // grammar's `unquoted_arg`, which precedes `expr`.
1422    if matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == "env")
1423        && !matches!(
1424            (
1425                toks.get(pos + 1).map(|t| &t.kind),
1426                toks.get(pos + 1).map(|t| t.joint)
1427            ),
1428            (Some(TokKind::Punct(':')), Some(true))
1429        )
1430    {
1431        return Ok(None);
1432    }
1433    let mut cur = Cursor::expr(&toks[pos..], stmt);
1434    let expr = parse_expr_or(&mut cur, ctx)?;
1435    let end = pos + cur.pos;
1436    // Mid-run stop (joint follower): the whole run renders raw
1437    // (`$x=K`, `$a$b`); the run always ends the fallback span here
1438    // because extension starts groups.
1439    if toks.get(end).is_some_and(|t| t.joint) {
1440        let mut run_end = end;
1441        while toks.get(run_end).is_some_and(|t| t.joint) {
1442            run_end += 1;
1443        }
1444        let text = render_raw_text(&toks[pos..run_end], stmt)?;
1445        return Ok(Some((Arg::String(text, false), run_end - pos)));
1446    }
1447    Ok(Some((Arg::Expr(expr), end - pos)))
1448}
1449
1450/// Render a brace group inside raw text (`{{..}}` templates and
1451/// mid-run `{..}` shapes): verbatim bytes, single-space-normalized
1452/// gaps. Run-start non-template braces never reach here (they parse
1453/// as maps/blocks in `build_arg_tokens`).
1454fn render_brace_run_text(inner: &[Tok], open_joint: bool, close_joint: bool) -> String {
1455    render_group('{', '}', inner, open_joint, close_joint)
1456}
1457
1458/// Inner bytes of a fully-quoted word (`"hi"`, `'a'`): the re-quoted
1459/// standalone strings spliced from groups strip exactly like
1460/// structural ones. Triple-quote pieces never qualify (block lowering
1461/// owns them); glued quotes (`['a`) never reach here as sole runs.
1462fn quoted_word_inner(w: &str) -> Option<String> {
1463    if w.len() >= 2 && !w.starts_with("\"\"\"") {
1464        let q = w.as_bytes()[0] as char;
1465        if (q == '"' || q == '\'') && w.ends_with(q) {
1466            return Some(w[1..w.len() - 1].to_string());
1467        }
1468    }
1469    None
1470}
1471
1472/// Build instruction tokens over generic args, mirroring
1473/// `assignment | argument` order at every argument start: assignments
1474/// merge across gaps to the next boundary, `$`/`env:`-led runs extend
1475/// as expressions, brace-led runs try templates then maps/blocks, and
1476/// everything else renders raw. Single quoted strings keep their flag.
1477fn build_arg_tokens(
1478    toks: &[Tok],
1479    stmt: usize,
1480    ctx: &ParseCtx,
1481) -> Result<(Vec<InsToken>, Option<TokenError>), TokenError> {
1482    // Splice bracket groups first: they read as ordinary
1483    // characters (whitespace splits inside them), with strings
1484    // re-quoted back to word text. Paren groups stay structural (see
1485    // `splice_arg_groups`); brace groups stay structural
1486    // (templates render whole; blocks parse as expressions).
1487    let flat = splice_arg_groups(toks, stmt)?;
1488    let mut deferred: Option<TokenError> = None;
1489    let mut out = Vec::new();
1490    let mut pos = 0;
1491    while pos < flat.len() {
1492        // 1. Assignment: key run plus `=` at any gap.
1493        if let Some((key, key_end)) = match_assign_key(&flat, pos)
1494            && let Some(tok) = flat.get(key_end)
1495            && matches!(&tok.kind, TokKind::Punct('='))
1496        {
1497            // Value runs to the next boundary, but raw text also
1498            // stops at `//` / `/*` (raw-text rule):
1499            // a line comment swallows the rest silently, a block
1500            // comment must be followed by nothing or a boundary
1501            // (anything else strands text and fails the line, like
1502            // the grammar). Lone typed values (`$x`, calls) apply
1503            // only at a true end/boundary, never past a comment
1504            // (the grammar's `!assign_expr_cont` guard).
1505            let mut vend = key_end + 1;
1506            let mut lone_ok = true;
1507            let mut failed: Option<String> = None;
1508            'scan: while vend < flat.len() {
1509                if !flat[vend].joint && at_assign_boundary(&flat, vend) {
1510                    break;
1511                }
1512                // Lexer comment markers end the raw span like `//`
1513                // (they run to end of line by construction).
1514                if matches!(&flat[vend].kind, TokKind::Comment(_)) {
1515                    lone_ok = false;
1516                    vend = flat.len();
1517                    break;
1518                }
1519                if matches!(&flat[vend].kind, TokKind::Punct('/')) && is_comment_open(&flat, vend) {
1520                    // Comments end the raw span: line comments eat
1521                    // the rest silently, block comments must be
1522                    // followed by nothing, a boundary, or more
1523                    // comments (stranded text fails the line, like
1524                    // the grammar).
1525                    lone_ok = false;
1526                    loop {
1527                        if vend >= flat.len()
1528                            || (!flat[vend].joint && at_assign_boundary(&flat, vend))
1529                        {
1530                            break 'scan;
1531                        }
1532                        if !matches!(&flat[vend].kind, TokKind::Punct('/'))
1533                            || !is_comment_open(&flat, vend)
1534                        {
1535                            failed = Some("unexpected text after assignment value".to_string());
1536                            break 'scan;
1537                        }
1538                        if matches!(
1539                            flat.get(vend + 1).map(|t| &t.kind),
1540                            Some(TokKind::Punct('/'))
1541                        ) {
1542                            vend = flat.len();
1543                            break 'scan;
1544                        }
1545                        match skip_inline_comment(&flat, vend) {
1546                            None => {
1547                                failed = Some("unclosed block comment".to_string());
1548                                break 'scan;
1549                            }
1550                            Some(past) => vend = past,
1551                        }
1552                    }
1553                }
1554                vend += 1;
1555            }
1556            if let Some(msg) = failed {
1557                return Err(TokenError {
1558                    stmt,
1559                    msg,
1560                    line: 0,
1561                    col: 0,
1562                    kind: None,
1563                });
1564            }
1565            let value =
1566                build_value_arg(&flat[key_end + 1..vend], stmt, ctx, lone_ok, &mut deferred)?;
1567            out.push(InsToken::Assign(key, value));
1568            pos = vend;
1569            continue;
1570        }
1571        // 2. Brace-led run: template text, else map/block expression.
1572        if matches!(
1573            flat.get(pos).map(|t| &t.kind),
1574            Some(TokKind::Group {
1575                delim: GroupDelim::Brace,
1576                ..
1577            })
1578        ) {
1579            let mut run_end = pos + 1;
1580            while flat.get(run_end).is_some_and(|t| t.joint) {
1581                run_end += 1;
1582            }
1583            let run = &flat[pos..run_end];
1584            let is_template = is_template_brace(&run[0]);
1585            if is_template {
1586                out.push(InsToken::Pos(Arg::String(
1587                    render_raw_text(run, stmt)?,
1588                    false,
1589                )));
1590            } else {
1591                let inner = match &run[0].kind {
1592                    TokKind::Group { inner, .. } => inner.clone(),
1593                    _ => unreachable!(),
1594                };
1595                // Map success alone stays typed; map success with a
1596                // joint tail renders raw (`{k:1}x`, like the grammar's
1597                // mixed fragments); map failure defers/errors exactly
1598                // like the expression path.
1599                match parse_map_or_block(&inner, stmt, ctx) {
1600                    Ok(expr) if run.len() == 1 => {
1601                        out.push(InsToken::Pos(Arg::Expr(expr)));
1602                    }
1603                    Ok(_) => out.push(InsToken::Pos(Arg::String(
1604                        render_raw_text(run, stmt)?,
1605                        false,
1606                    ))),
1607                    Err(e) => return Err(e),
1608                }
1609            }
1610            pos = run_end;
1611            continue;
1612        }
1613        // 3. `$`/`env:`-led expression extension.
1614        if let Some((arg, used)) = try_expr_arg(&flat, pos, stmt, ctx)? {
1615            // A lone expression group stays typed; the fallback
1616            // already rendered text above.
1617            out.push(InsToken::Pos(arg));
1618            pos += used;
1619            continue;
1620        }
1621        // 4. Raw text run to the next gap.
1622        let mut run_end = pos + 1;
1623        while flat.get(run_end).is_some_and(|t| t.joint) {
1624            run_end += 1;
1625        }
1626        let run = &flat[pos..run_end];
1627        // Slash-pair-led runs (`/*c*/`; `//` arrives as `Comment`
1628        // toks) parse as expression fragments (typed when single,
1629        // glued verbatim otherwise).
1630        if is_slash_run(run) {
1631            out.push(InsToken::Pos(parse_slash_run(run, stmt, ctx)?));
1632            pos = run_end;
1633            continue;
1634        }
1635        // Trailing `Comment` (`//` to end of line) glues as a
1636        // literal fragment (typed when alone, verbatim otherwise),
1637        // exactly like the grammar's expression fragments.
1638        if let Some(TokKind::Comment(text)) = run.last().map(|t| &t.kind) {
1639            if run.len() == 1 {
1640                out.push(InsToken::Pos(Arg::Expr(Expr::Literal(Value::string(
1641                    text.clone(),
1642                )))));
1643            } else {
1644                let mut bytes = render_raw_text(&run[..run.len() - 1], stmt)?;
1645                bytes.push_str(text);
1646                out.push(InsToken::Pos(Arg::String(bytes, false)));
1647            }
1648            pos = run_end;
1649            continue;
1650        }
1651        if run.len() == 1 {
1652            match &run[0].kind {
1653                TokKind::Str { text: s, .. } => {
1654                    out.push(InsToken::Pos(Arg::String(s.clone(), true)));
1655                    pos = run_end;
1656                    continue;
1657                }
1658                TokKind::BlockStr(full) => {
1659                    out.push(InsToken::Pos(Arg::String(
1660                        crate::command::lower_block_string(full),
1661                        true,
1662                    )));
1663                    pos = run_end;
1664                    continue;
1665                }
1666                // Re-quoted standalone strings (spliced from groups)
1667                // strip exactly like structural ones (`["hi"]` gives
1668                // `hi`); glued quotes stay literal (`['a` keeps its
1669                // mark). Triple-quote pieces never qualify.
1670                TokKind::Word(w) if quoted_word_inner(w).is_some() => {
1671                    out.push(InsToken::Pos(Arg::String(
1672                        quoted_word_inner(w).unwrap(),
1673                        true,
1674                    )));
1675                    pos = run_end;
1676                    continue;
1677                }
1678                _ => {}
1679            }
1680        }
1681        // Bare full-region calls stay typed like assignment values and
1682        // RUN-exec items (same owner, `try_lone_call_expr`), so every
1683        // argument position evaluates them instead of one silently
1684        // appending the source text. Failures stash: the command's own
1685        // lowering error (if any) takes precedence, and the stashed
1686        // call error surfaces only when lowering succeeds.
1687        match try_lone_call_expr(run, stmt, ctx) {
1688            Ok(Some(arg)) => {
1689                out.push(InsToken::Pos(arg));
1690                pos = run_end;
1691                continue;
1692            }
1693            Ok(None) => {}
1694            Err(err) => {
1695                deferred.get_or_insert(err);
1696            }
1697        }
1698        out.push(InsToken::Pos(Arg::String(
1699            render_raw_text(run, stmt)?,
1700            false,
1701        )));
1702        pos = run_end;
1703    }
1704    Ok((out, deferred))
1705}
1706
1707/// A raw run starting with `//` or `/*` (a slash-pair: `/` plus a
1708/// joint `/` or `*`) parses as expression fragments: both route to
1709/// `expr` there (so `//c` types as a literal and `/*c*/` as math). A single
1710/// fully-consuming expression stays typed; anything longer glues to
1711/// verbatim text exactly like the grammar's mixed fragments (byte
1712/// for byte, since joint runs admit no span gaps). An unparseable
1713/// unterminated block open (`/*` with no `*/` in the run) reads
1714/// literally like the old backend (`ECHO /*`, `[a /* c]`); a
1715/// terminated span keeps the loud failure.
1716fn parse_slash_run(run: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Arg, TokenError> {
1717    let mut cur = Cursor::expr(run, stmt);
1718    match parse_expr_checked(&mut cur, ctx) {
1719        Ok(expr) if cur.done() => Ok(Arg::Expr(expr)),
1720        Ok(_) => Ok(Arg::String(render_raw_text(run, stmt)?, false)),
1721        Err(_) if !run_has_block_close(run) => Ok(Arg::String(render_raw_text(run, stmt)?, false)),
1722        Err(e) => Err(e),
1723    }
1724}
1725
1726/// True when the run holds a `*/` close pair (`*` plus a joint `/`),
1727/// mirroring [`skip_inline_comment`]'s terminator: only unterminated
1728/// block opens read literally.
1729fn run_has_block_close(run: &[Tok]) -> bool {
1730    run.windows(2).any(|w| {
1731        matches!(&w[0].kind, TokKind::Punct('*'))
1732            && matches!(&w[1].kind, TokKind::Punct('/'))
1733            && w[1].joint
1734    })
1735}
1736
1737/// True when a raw run opens with a slash-pair (`/` plus a joint
1738/// `/` or `*`), routing it to expression fragments (see
1739/// [`parse_slash_run`]). A lone `/` (`/a`, `/`) stays raw text.
1740fn is_slash_run(run: &[Tok]) -> bool {
1741    matches!(run.first().map(|t| &t.kind), Some(TokKind::Punct('/')))
1742        && matches!(
1743            run.get(1).map(|t| (&t.kind, t.joint)),
1744            Some((TokKind::Punct('/'), true)) | Some((TokKind::Punct('*'), true))
1745        )
1746}
1747
1748/// Lower generic args through the shared cores: `ENV`/`EXPAND` bypass
1749/// the injected dispatcher; everything else
1750/// canonicalizes assignments and calls it.
1751fn lower_generic_args(
1752    name: &str,
1753    tokens: Vec<InsToken>,
1754    stmt: usize,
1755    ctx: &ParseCtx,
1756) -> Result<StepKind, TokenError> {
1757    if name == KEYWORD_ENV {
1758        return lower_env_tokens(&lowering_ctx(stmt), tokens).map_err(|e| TokenError {
1759            stmt,
1760            msg: e.to_string(),
1761            line: 0,
1762            col: 0,
1763            kind: None,
1764        });
1765    }
1766    if name == KEYWORD_EXPAND {
1767        return lower_expand_tokens(&lowering_ctx(stmt), tokens).map_err(|e| TokenError {
1768            stmt,
1769            msg: e.to_string(),
1770            line: 0,
1771            col: 0,
1772            kind: None,
1773        });
1774    }
1775    let args = tokens
1776        .into_iter()
1777        .map(|token| match token {
1778            InsToken::Pos(arg) => arg,
1779            InsToken::Assign(key, value) => canonical_assignment_arg(&key, &value),
1780        })
1781        .collect();
1782    (ctx.lower)(name, args).map_err(|e| lower_err(stmt, e))
1783}
1784
1785/// Render a bracket/paren/brace group back to source text for raw-text
1786/// positions (in-body groups are args, template braces render whole).
1787/// Fragments join with a space on gaps and glue on `joint`, so both
1788/// lexers render the same source identically; quote styles round-trip
1789/// exactly. Known normalization (documented, not silent): multi-space
1790/// gaps collapse to one.
1791fn render_group(
1792    open: char,
1793    close: char,
1794    inner: &[Tok],
1795    open_joint: bool,
1796    close_joint: bool,
1797) -> String {
1798    let mut out = String::from(open);
1799    if !open_joint && !inner.is_empty() {
1800        out.push(' ');
1801    }
1802    let mut first = true;
1803    for tok in inner {
1804        match &tok.kind {
1805            TokKind::Newline => out.push('\n'),
1806            TokKind::Semicolon => out.push(';'),
1807            // Comments reproduce verbatim (templates keep comment
1808            // text like the atomic grammar span); like newlines they
1809            // carry their own separation, never a synthetic space.
1810            TokKind::Comment(text) => out.push_str(text),
1811            _ => {
1812                if !first && !tok.joint {
1813                    out.push(' ');
1814                }
1815                match &tok.kind {
1816                    TokKind::Word(w) => out.push_str(w),
1817                    TokKind::Punct(c) => out.push(*c),
1818                    TokKind::Str { text, quote } => {
1819                        out.push(*quote);
1820                        out.push_str(text);
1821                        out.push(*quote);
1822                    }
1823                    TokKind::BlockStr(full) => out.push_str(full),
1824                    TokKind::Group {
1825                        delim: GroupDelim::Bracket,
1826                        inner,
1827                        open_joint,
1828                        close_joint,
1829                        ..
1830                    } => out.push_str(&render_group('[', ']', inner, *open_joint, *close_joint)),
1831                    TokKind::Group {
1832                        delim: GroupDelim::Paren,
1833                        inner,
1834                        open_joint,
1835                        close_joint,
1836                        ..
1837                    } => out.push_str(&render_group('(', ')', inner, *open_joint, *close_joint)),
1838                    TokKind::Group {
1839                        delim: GroupDelim::Brace,
1840                        inner,
1841                        open_joint,
1842                        close_joint,
1843                        ..
1844                    } => out.push_str(&render_group('{', '}', inner, *open_joint, *close_joint)),
1845                    // Comments reproduce verbatim (nested groups keep
1846                    // comment text like the atomic grammar span).
1847                    TokKind::Comment(text) => out.push_str(text),
1848                    TokKind::Newline | TokKind::Semicolon => unreachable!(),
1849                }
1850            }
1851        }
1852        first = false;
1853    }
1854    if !close_joint && !inner.is_empty() {
1855        out.push(' ');
1856    }
1857    out.push(close);
1858    out
1859}
1860
1861/// Positional cursor over guard/group token slices. Newlines skip
1862/// freely between tokens (`ws` admits linebreaks in the grammar);
1863/// bare key/value runs never cross them (the grammar excludes
1864/// linebreaks there), so runs read raw.
1865///
1866/// Expression parsing reuses this cursor with `nl_skip = false`:
1867/// expressions are single-line (`gap`, never `gap_nl`, between
1868/// operands), so a newline terminates instead of vanishing. Newlines
1869/// inside group inners (call args, lists, maps) skip via explicit
1870/// `skip_newlines` calls at the grammar's `gap_nl` junctures.
1871struct Cursor<'t> {
1872    toks: &'t [Tok],
1873    pos: usize,
1874    stmt: usize,
1875    nl_skip: bool,
1876}
1877
1878impl<'t> Cursor<'t> {
1879    fn new(toks: &'t [Tok], stmt: usize) -> Self {
1880        Self {
1881            toks,
1882            pos: 0,
1883            stmt,
1884            nl_skip: true,
1885        }
1886    }
1887
1888    /// Expression-mode cursor: newlines stop, never skip.
1889    fn expr(toks: &'t [Tok], stmt: usize) -> Self {
1890        Self {
1891            toks,
1892            pos: 0,
1893            stmt,
1894            nl_skip: false,
1895        }
1896    }
1897
1898    fn err(&self, msg: impl Into<String>) -> TokenError {
1899        TokenError {
1900            stmt: self.stmt,
1901            line: 0,
1902            col: 0,
1903            msg: msg.into(),
1904            kind: None,
1905        }
1906    }
1907
1908    fn skip_newlines(&mut self) {
1909        while matches!(
1910            self.toks.get(self.pos).map(|t| &t.kind),
1911            Some(TokKind::Newline)
1912        ) {
1913            self.pos += 1;
1914        }
1915    }
1916
1917    fn peek(&mut self) -> Option<&'t Tok> {
1918        if self.nl_skip {
1919            self.skip_newlines();
1920        }
1921        self.toks.get(self.pos)
1922    }
1923
1924    fn next(&mut self) -> Option<&'t Tok> {
1925        if self.nl_skip {
1926            self.skip_newlines();
1927        }
1928        let t = self.toks.get(self.pos)?;
1929        self.pos += 1;
1930        Some(t)
1931    }
1932
1933    fn done(&mut self) -> bool {
1934        if self.nl_skip {
1935            self.skip_newlines();
1936        }
1937        self.pos >= self.toks.len()
1938    }
1939
1940    fn eat_punct(&mut self, c: char) -> bool {
1941        if self.nl_skip {
1942            self.skip_newlines();
1943        }
1944        match self.peek() {
1945            Some(t) if matches!(&t.kind, TokKind::Punct(p) if *p == c) => {
1946                self.pos += 1;
1947                true
1948            }
1949            _ => false,
1950        }
1951    }
1952
1953    /// Skip one gap's worth of comments (`gap`: `//`-to-newline,
1954    /// balanced `/* */` even across newlines, `#`-to-newline —
1955    /// never a standalone newline, which ends single-line
1956    /// expressions. Greedy gap before operators and operands; whitespace itself is
1957    /// already invisible in the token stream.
1958    fn skip_gap(&mut self) {
1959        loop {
1960            match self.toks.get(self.pos).map(|t| &t.kind) {
1961                Some(TokKind::Comment(_)) => {
1962                    self.pos += 1;
1963                }
1964                Some(TokKind::Punct('/')) if is_comment_open(self.toks, self.pos) => {
1965                    match skip_inline_comment(self.toks, self.pos) {
1966                        Some(next) => self.pos = next,
1967                        // Unclosed block comments fail the gap (and
1968                        // the enclosing rule) like the grammar.
1969                        None => break,
1970                    }
1971                }
1972                Some(TokKind::Punct('#')) => {
1973                    while self.pos < self.toks.len()
1974                        && !matches!(&self.toks[self.pos].kind, TokKind::Newline)
1975                    {
1976                        self.pos += 1;
1977                    }
1978                }
1979                _ => break,
1980            }
1981        }
1982    }
1983
1984    /// Skip gap comments plus standalone newlines (`gap_nl`: call
1985    /// args, list items, maps, parenthesized expressions).
1986    fn skip_gap_nl(&mut self) {
1987        loop {
1988            match self.toks.get(self.pos).map(|t| &t.kind) {
1989                Some(TokKind::Newline) => {
1990                    self.pos += 1;
1991                }
1992                _ => {
1993                    let before = self.pos;
1994                    self.skip_gap();
1995                    if self.pos == before {
1996                        break;
1997                    }
1998                }
1999            }
2000        }
2001    }
2002
2003    /// Consume the parenthesized group following a call word (`not`,
2004    /// `any`, `all`, `eq`, `ne`), ignoring gap width exactly like the
2005    /// grammar's implicit whitespace.
2006    fn eat_paren_group(&mut self) -> Option<Vec<Tok>> {
2007        match self.peek() {
2008            Some(t) => match &t.kind {
2009                TokKind::Group {
2010                    delim: GroupDelim::Paren,
2011                    inner,
2012                    ..
2013                } => {
2014                    let inner = inner.clone();
2015                    self.pos += 1;
2016                    Some(inner)
2017                }
2018                _ => None,
2019            },
2020            None => None,
2021        }
2022    }
2023}
2024
2025/// Split a flat token slice on top-level commas (nesting lives inside
2026/// atomic groups, so a flat scan is exact).
2027fn split_top_commas(toks: &[Tok]) -> Vec<&[Tok]> {
2028    let mut parts = Vec::new();
2029    let mut start = 0;
2030    for (i, t) in toks.iter().enumerate() {
2031        if matches!(&t.kind, TokKind::Punct(',')) {
2032            parts.push(&toks[start..i]);
2033            start = i + 1;
2034        }
2035    }
2036    parts.push(&toks[start..]);
2037    parts
2038}
2039
2040/// Punctuation admissible inside bare guard key runs: everything but
2041/// the terminators the parser enforces separately. `;` arrives as its
2042/// own token kind; the key charset admits it, so runs accept it literally.
2043fn key_char(c: char) -> bool {
2044    !matches!(c, ':' | '=' | '!' | ',' | '|' | '(' | ')' | ']' | '$')
2045}
2046
2047/// Consume a joint run of words/punctuation as one bare key or value.
2048/// Gaps end the run; terminators and groups end or fail it per `extra`.
2049fn bare_run(cur: &mut Cursor, extra: fn(char) -> bool, what: &str) -> Result<String, TokenError> {
2050    let mut out = String::new();
2051    loop {
2052        let tok = match cur.toks.get(cur.pos) {
2053            Some(t) if matches!(&t.kind, TokKind::Newline) => break,
2054            Some(t) => t,
2055            None => break,
2056        };
2057        // First element may follow a gap; continuations must be gapless.
2058        if !out.is_empty() && !tok.joint {
2059            break;
2060        }
2061        match &tok.kind {
2062            TokKind::Word(w) => out.push_str(w),
2063            TokKind::Punct(c) if key_char(*c) && extra(*c) => out.push(*c),
2064            TokKind::Semicolon if extra(';') => out.push(';'),
2065            _ => break,
2066        }
2067        cur.pos += 1;
2068    }
2069    if out.is_empty() {
2070        return Err(cur.err(format!("missing {what}")));
2071    }
2072    Ok(out)
2073}
2074
2075/// The `guard_term` negative lookahead: a complete term followed by
2076/// `(`, `:`, `=`, or `!` is malformed, never a longer form.
2077fn check_term_end(cur: &mut Cursor) -> Result<(), TokenError> {
2078    cur.skip_newlines();
2079    match cur.toks.get(cur.pos) {
2080        Some(t) => match &t.kind {
2081            TokKind::Group {
2082                delim: GroupDelim::Paren,
2083                ..
2084            } => Err(cur.err("unexpected `(` after guard term")),
2085            TokKind::Punct(c) if matches!(c, ':' | '=' | '!') => {
2086                Err(cur.err(format!("unexpected `{c}` after guard term")))
2087            }
2088            _ => Ok(()),
2089        },
2090        None => Ok(()),
2091    }
2092}
2093
2094fn os_guard(value: &str) -> GuardExpr {
2095    GuardExpr::Predicate(Guard::Attr {
2096        ns: Ns::Os,
2097        key: None,
2098        val: Some(value.to_string()),
2099    })
2100}
2101
2102/// Namespace validation for guard predicates with closed domains
2103/// (`family`, `os`, `arch`); open namespaces pass through.
2104fn ns_guard(ns: &str, val: &str, cur: &Cursor) -> Result<GuardExpr, TokenError> {
2105    match ns {
2106        "family" => match val {
2107            "unix" => Ok(GuardExpr::or(vec![os_guard("macos"), os_guard("linux")])),
2108            "windows" => Ok(os_guard("windows")),
2109            _ => Err(cur.err(format!(
2110                "unknown family '{val}'; known values: unix, windows"
2111            ))),
2112        },
2113        "os" => match val {
2114            "macos" | "linux" | "windows" => Ok(os_guard(val)),
2115            _ => Err(cur.err(format!(
2116                "unknown os '{val}'; known values: macos, linux, windows"
2117            ))),
2118        },
2119        "arch" => {
2120            if crate::ARCH_VALUES.contains(&val) {
2121                Ok(GuardExpr::Predicate(Guard::Attr {
2122                    ns: Ns::Arch,
2123                    key: None,
2124                    val: Some(val.to_string()),
2125                }))
2126            } else {
2127                Err(cur.err(format!(
2128                    "unknown arch '{val}'; known values: {}",
2129                    crate::ARCH_VALUES.join(", ")
2130                )))
2131            }
2132        }
2133        _ => Err(cur.err(format!(
2134            "unknown guard namespace '{ns}'; known namespaces: family, os, arch, env, bool"
2135        ))),
2136    }
2137}
2138
2139fn parse_guard_term(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2140    let tok = cur
2141        .next()
2142        .ok_or_else(|| cur.err("missing guard predicate"))?;
2143    // A `!` prefix is never negation in guards (only `not(...)` negates).
2144    if matches!(&tok.kind, TokKind::Punct('!')) {
2145        return Err(cur.err("unexpected `!` in guard; negation uses `not(...)`"));
2146    }
2147    let word = match &tok.kind {
2148        TokKind::Word(w) => w.clone(),
2149        _ => return Err(cur.err("missing guard predicate")),
2150    };
2151    // `__OXDOCK_INJECT_N__` interpolation placeholder: env-key shape.
2152    if let Some(rest) = word.strip_prefix(INJECT_PREFIX) {
2153        if !rest.is_empty()
2154            && rest
2155                .strip_suffix(INJECT_SUFFIX)
2156                .is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()))
2157        {
2158            return Ok(GuardExpr::Predicate(Guard::Attr {
2159                ns: Ns::Env,
2160                key: Some(word),
2161                val: None,
2162            }));
2163        }
2164        return Err(cur.err("missing guard predicate"));
2165    }
2166    match word.as_str() {
2167        "eq" | "ne" => {
2168            let inner = cur
2169                .eat_paren_group()
2170                .ok_or_else(|| cur.err(format!("`{word}` requires `(env:KEY, value)`")))?;
2171            let mut arg = Cursor::new(&inner, cur.stmt);
2172            if arg.next().map(|t| &t.kind) != Some(&TokKind::Word("env".to_string())) {
2173                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2174            }
2175            if !arg.eat_punct(':') {
2176                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2177            }
2178            let key = bare_run(&mut arg, |_| true, "guard key")?;
2179            if !arg.eat_punct(',') {
2180                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2181            }
2182            arg.skip_newlines();
2183            let value = match arg.next() {
2184                Some(t) => match &t.kind {
2185                    TokKind::Str { text, .. } => text.clone(),
2186                    TokKind::BlockStr(full) => crate::command::lower_block_string(full),
2187                    _ => {
2188                        // Bare value: runs to the region end (commas and
2189                        // groups terminate it with an error, matching the
2190                        // bare-value exclusions).
2191                        arg.pos -= 1;
2192                        value_run(&mut arg)?
2193                    }
2194                },
2195                None => return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`"))),
2196            };
2197            if !arg.done() {
2198                return Err(arg.err(format!("unexpected text after `{word}` value")));
2199            }
2200            let pred = GuardExpr::Predicate(Guard::Attr {
2201                ns: Ns::Env,
2202                key: Some(key),
2203                val: Some(value),
2204            });
2205            if word == "ne" {
2206                Ok(GuardExpr::Not(Box::new(pred)))
2207            } else {
2208                Ok(pred)
2209            }
2210        }
2211        "bool" => {
2212            if !cur.eat_punct(':') {
2213                return Err(cur.err("`bool` requires `:value`"));
2214            }
2215            let val = bare_run(cur, |_| true, "bool value")?;
2216            check_term_end(cur)?;
2217            Ok(GuardExpr::Predicate(Guard::Attr {
2218                ns: Ns::Bool,
2219                key: None,
2220                val: Some(val),
2221            }))
2222        }
2223        "env" => {
2224            if !cur.eat_punct(':') {
2225                return Err(cur.err("`env` requires `:KEY`"));
2226            }
2227            let key = bare_run(cur, |_| true, "guard key")?;
2228            check_term_end(cur)?;
2229            Ok(GuardExpr::Predicate(Guard::Attr {
2230                ns: Ns::Env,
2231                key: Some(key),
2232                val: None,
2233            }))
2234        }
2235        _ => {
2236            if !cur.eat_punct(':') {
2237                return Err(cur.err("missing guard predicate"));
2238            }
2239            let val = bare_run(cur, |_| true, "guard value")?;
2240            check_term_end(cur)?;
2241            ns_guard(&word, &val, cur)
2242        }
2243    }
2244}
2245
2246/// Bare `eq`/`ne` value run: key charset plus `:`/`=`/`!` (the grammar
2247/// admits them in values, never in keys), with nested groups rendered
2248/// for the pathological `(`-in-value shape. `$`, `|`, `,` terminate
2249/// with an error downstream.
2250/// Bare `eq`/`ne` value with atomic bare-value semantics:
2251/// everything except `, | ) ] $`, linebreaks, and comment opens —
2252/// gaps included (joined with one space; the token stream cannot
2253/// preserve gap width). Quotes ride literally mid-run (the atomic
2254/// span keeps them); a *leading* quote never reaches here (the
2255/// caller strips it as the `quoted_string` alternative, which then
2256/// requires end-of-region like the grammar's committed choice).
2257fn value_run(arg: &mut Cursor) -> Result<String, TokenError> {
2258    let mut out = String::new();
2259    while let Some(tok) = arg.toks.get(arg.pos) {
2260        // Terminators: the grammar's negative-lookahead set.
2261        match &tok.kind {
2262            TokKind::Newline | TokKind::Comment(_) => break,
2263            TokKind::Punct(',')
2264            | TokKind::Punct('|')
2265            | TokKind::Punct(']')
2266            | TokKind::Punct(')') => break,
2267            TokKind::Punct('$') => break,
2268            TokKind::Punct('/') if is_comment_open(arg.toks, arg.pos) => break,
2269            TokKind::Group { .. } => break,
2270            _ => {}
2271        }
2272        if !out.is_empty() && !tok.joint {
2273            out.push(' ');
2274        }
2275        match &tok.kind {
2276            TokKind::Word(w) => out.push_str(w),
2277            TokKind::Punct(c) => out.push(*c),
2278            TokKind::Semicolon => out.push(';'),
2279            // Mid-run quotes keep their marks, like the atomic span.
2280            TokKind::Str { text, quote } => {
2281                out.push(*quote);
2282                out.push_str(text);
2283                out.push(*quote);
2284            }
2285            TokKind::BlockStr(full) => out.push_str(full),
2286            _ => break,
2287        }
2288        arg.pos += 1;
2289    }
2290    if out.is_empty() {
2291        return Err(arg.err("missing guard value"));
2292    }
2293    Ok(out)
2294}
2295
2296/// True when the cursor sits on `name` followed (over newlines,
2297/// like the grammar's implicit whitespace) by a paren group.
2298fn at_call(cur: &Cursor, name: &str) -> bool {
2299    let mut pos = cur.pos;
2300    // Leading newlines skip (the grammar's implicit whitespace gaps
2301    // multi-line guards, e.g. `[\nnot(env:K)\n]`).
2302    while matches!(cur.toks.get(pos).map(|t| &t.kind), Some(TokKind::Newline)) {
2303        pos += 1;
2304    }
2305    match cur.toks.get(pos) {
2306        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == name) => pos += 1,
2307        _ => return false,
2308    }
2309    while matches!(cur.toks.get(pos).map(|t| &t.kind), Some(TokKind::Newline)) {
2310        pos += 1;
2311    }
2312    matches!(
2313        cur.toks.get(pos).map(|t| &t.kind),
2314        Some(TokKind::Group {
2315            delim: GroupDelim::Paren,
2316            ..
2317        })
2318    )
2319}
2320
2321fn parse_guard_primary(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2322    // Call shapes dispatch on word + paren group regardless of gap
2323    // width (the grammar's implicit whitespace); anything else is a term.
2324    for name in ["not", "any", "all"] {
2325        if at_call(cur, name) {
2326            cur.next();
2327            let inner = cur
2328                .eat_paren_group()
2329                .ok_or_else(|| cur.err("unreachable"))?;
2330            let parts = split_top_commas(&inner);
2331            match name {
2332                "not" => {
2333                    if parts.len() != 1 {
2334                        return Err(cur.err("`not` takes exactly one guard expression"));
2335                    }
2336                    let mut sub = Cursor::new(parts[0], cur.stmt);
2337                    let expr = parse_guard_seq(&mut sub)?;
2338                    if !sub.done() {
2339                        return Err(sub.err("unexpected text in `not`"));
2340                    }
2341                    return Ok(GuardExpr::Not(Box::new(expr)));
2342                }
2343                "any" => {
2344                    if parts.len() < 2 {
2345                        return Err(cur.err("any(...) requires at least two guard expressions"));
2346                    }
2347                    let mut exprs = Vec::new();
2348                    for part in parts {
2349                        let mut sub = Cursor::new(part, cur.stmt);
2350                        exprs.push(parse_guard_seq(&mut sub)?);
2351                        if !sub.done() {
2352                            return Err(sub.err("unexpected text in `any`"));
2353                        }
2354                    }
2355                    return Ok(GuardExpr::or(exprs));
2356                }
2357                _ => {
2358                    if parts.is_empty() {
2359                        return Err(cur.err("all(...) requires at least one guard expression"));
2360                    }
2361                    let mut exprs = Vec::new();
2362                    for part in parts {
2363                        if part.iter().all(|t| matches!(&t.kind, TokKind::Newline)) {
2364                            return Err(cur.err("all(...) requires at least one guard expression"));
2365                        }
2366                        let mut sub = Cursor::new(part, cur.stmt);
2367                        exprs.push(parse_guard_seq(&mut sub)?);
2368                        if !sub.done() {
2369                            return Err(sub.err("unexpected text in `all`"));
2370                        }
2371                    }
2372                    return Ok(GuardExpr::all(exprs));
2373                }
2374            }
2375        }
2376    }
2377    match cur.peek() {
2378        Some(t) => match &t.kind {
2379            TokKind::Group {
2380                delim: GroupDelim::Paren,
2381                inner,
2382                ..
2383            } => {
2384                let inner = inner.clone();
2385                cur.next();
2386                let mut sub = Cursor::new(&inner, cur.stmt);
2387                let expr = parse_guard_seq(&mut sub)?;
2388                if !sub.done() {
2389                    return Err(sub.err("unexpected text in guard group"));
2390                }
2391                Ok(expr)
2392            }
2393            _ => parse_guard_term(cur),
2394        },
2395        None => Err(cur.err("missing guard expression")),
2396    }
2397}
2398
2399fn parse_guard_seq(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2400    let first = parse_guard_primary(cur)?;
2401    let mut rest = vec![first];
2402    while cur.eat_punct(',') {
2403        rest.push(parse_guard_primary(cur)?);
2404    }
2405    if rest.len() == 1 {
2406        Ok(rest.pop().unwrap())
2407    } else {
2408        Ok(GuardExpr::all(rest))
2409    }
2410}
2411
2412/// Parse one bracket group's contents as a guard expression.
2413fn parse_guard_inner(inner: &[Tok], stmt: usize) -> Result<GuardExpr, TokenError> {
2414    let mut cur = Cursor::new(inner, stmt);
2415    let expr = parse_guard_seq(&mut cur)?;
2416    if !cur.done() {
2417        return Err(cur.err("unexpected text in guard"));
2418    }
2419    Ok(expr)
2420}
2421
2422/// Parse one standalone guard expression from lexed tokens (the
2423/// `parse_guard_expr_str` entry point): a bare `guard_seq` with full
2424/// consumption.
2425pub(crate) fn parse_single_guard(toks: &[Tok], stmt: usize) -> Result<GuardExpr, TokenError> {
2426    let mut cur = Cursor::new(toks, stmt);
2427    if cur.done() {
2428        return Err(cur.err("empty guard"));
2429    }
2430    let expr = parse_guard_seq(&mut cur)?;
2431    if !cur.done() {
2432        return Err(cur.err("unexpected text in guard"));
2433    }
2434    Ok(expr)
2435}
2436
2437/// Combine a statement's leading guard groups: stacked brackets `All`
2438/// together, a single bracket stands alone.
2439fn parse_guard_groups(guard: &[Tok], stmt: usize) -> Result<Option<GuardExpr>, TokenError> {
2440    let mut acc: Option<GuardExpr> = None;
2441    for tok in guard {
2442        let inner = match &tok.kind {
2443            TokKind::Group {
2444                delim: GroupDelim::Bracket,
2445                inner,
2446                ..
2447            } => inner.clone(),
2448            _ => {
2449                return Err(TokenError {
2450                    stmt,
2451                    msg: "unsupported non-bracket guard".to_string(),
2452                    line: 0,
2453                    col: 0,
2454                    kind: None,
2455                });
2456            }
2457        };
2458        let expr = parse_guard_inner(&inner, stmt)?;
2459        acc = Some(match acc {
2460            None => expr,
2461            Some(prev) => GuardExpr::all(vec![prev, expr]),
2462        });
2463    }
2464    Ok(acc)
2465}
2466
2467// ---- Calls, RUN-exec, instruction exactness ----
2468// Static call resolution runs through the shared `resolve_call_name`
2469// (same module table, same messages); only the token-level call-shape
2470// detector is v2-native. Generic arguments classify like the
2471// `assignment | argument` grammar order (assignments merge across
2472// gaps, `$`/`env:`-led runs extend as expressions, everything else
2473// renders raw), and `ENV`/`EXPAND` lower through the shared direct
2474// cores instead of the injected dispatcher.
2475
2476/// Parse context: shared lowering dispatcher plus module table for
2477/// static call resolution, with `FUNC`/import frames per braced body.
2478pub struct ParseCtx<'a> {
2479    pub lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
2480    pub modules: &'a ModuleTable,
2481    /// Host-registered function names for the `FUNC` shadow check
2482    /// (empty when hosts are unknown).
2483    pub reserved: &'a HashSet<String>,
2484    /// `FUNC` scopes (innermost last) and import frames, pushed per
2485    /// braced body; short borrows only,
2486    /// never held across recursive parses.
2487    pub funcs: RefCell<Vec<HashSet<String>>>,
2488    pub imports: RefCell<Vec<Vec<String>>>,
2489    /// `EXPORT` func names in source order, validated at end of parse
2490    /// (forward references allowed).
2491    pub func_exports: RefCell<Vec<String>>,
2492    /// `EXPORT TYPE` names in source order, validated at end of parse
2493    /// (forward references allowed). Separate from func exports so the
2494    /// MCP server never confuses a type for a tool.
2495    pub type_exports: RefCell<Vec<String>>,
2496    /// Top-level `FUNC` names pre-declared before lowering, so forward
2497    /// references resolve regardless of order. Separate from `funcs`
2498    /// frames so duplicate detection in `declare_func` stays intact;
2499    /// `visible_snapshot` unions this set.
2500    pub forward: RefCell<Vec<HashSet<String>>>,
2501    /// 1-based source line of the statement currently lowering (the
2502    /// innermost split statement; updated per statement by the body
2503    /// loops, read as the base for nested splits). Lets every error
2504    /// carry its statement's line without threading it through every
2505    /// header function by hand.
2506    pub current_line: RefCell<usize>,
2507}
2508
2509impl<'a> ParseCtx<'a> {
2510    /// Context with empty tables.
2511    pub fn empty(
2512        lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
2513        modules: &'a ModuleTable,
2514        reserved: &'a HashSet<String>,
2515    ) -> Self {
2516        Self {
2517            lower,
2518            modules,
2519            reserved,
2520            funcs: RefCell::new(vec![HashSet::new()]),
2521            imports: RefCell::new(vec![Vec::new()]),
2522            func_exports: RefCell::new(Vec::new()),
2523            type_exports: RefCell::new(Vec::new()),
2524            forward: RefCell::new(vec![HashSet::new()]),
2525            current_line: RefCell::new(0),
2526        }
2527    }
2528
2529    /// Snapshot of everything visible at this point: `FUNC` names
2530    /// unioned across frames plus imports flattened outer-to-inner
2531    /// (unions `FUNC` names across frames, flattens imports outer-to-inner).
2532    fn visible_snapshot(&self) -> (HashSet<String>, Vec<String>) {
2533        let mut funcs = HashSet::new();
2534        for scope in self.funcs.borrow().iter() {
2535            funcs.extend(scope.iter().cloned());
2536        }
2537        funcs.extend(
2538            self.forward
2539                .borrow()
2540                .iter()
2541                .flat_map(|frame| frame.iter().cloned()),
2542        );
2543        let mut imports = Vec::new();
2544        for frame in self.imports.borrow().iter() {
2545            for module in frame {
2546                if !imports.contains(module) {
2547                    imports.push(module.clone());
2548                }
2549            }
2550        }
2551        (funcs, imports)
2552    }
2553
2554    /// Record a `FUNC` name in the innermost scope. Returns false when
2555    /// already defined in that same scope (nested shadowing stays
2556    /// allowed (nested shadowing stays permitted).
2557    fn declare_func(&self, name: &str) -> bool {
2558        match self.funcs.borrow_mut().last_mut() {
2559            Some(current) => current.insert(name.to_string()),
2560            None => true,
2561        }
2562    }
2563
2564    /// Record `IMPORT`ed modules in the innermost frame (deduped,
2565    /// (deduped; the unknown-module table check lives at the import site),
2566    /// which lives at the import site).
2567    fn import_into_frame(&self, modules: &[String]) {
2568        match self.imports.borrow_mut().last_mut() {
2569            Some(frame) => {
2570                for module in modules {
2571                    if !frame.contains(module) {
2572                        frame.push(module.clone());
2573                    }
2574                }
2575            }
2576            None => {
2577                self.imports.borrow_mut().push(modules.to_vec());
2578            }
2579        }
2580    }
2581}
2582
2583fn resolve_name(ctx: &ParseCtx, stmt: usize, name: &str) -> Result<String, TokenError> {
2584    let (funcs, imports) = ctx.visible_snapshot();
2585    resolve_call_name(ctx.modules, &funcs, &imports, &lowering_ctx(stmt), name)
2586        .map_err(|e| lower_err(stmt, e))
2587}
2588
2589/// Pre-declare `FUNC` names before lowering, so forward references
2590/// resolve regardless of order. Only valid non-reserved headers hoist:
2591/// the head (`FUNC NAME`, `ASYNC FUNC NAME`), a parameter Paren group,
2592/// a `:` return-type shape (via the shared `parse_type_shape` owner),
2593/// and a trailing non-template Brace body. Malformed headers
2594/// (`FUNC FOO() ECHO hi`) and reserved names (`FUNC LEN`) stay silent
2595/// here so the main pass owns their diagnostics. Runs per scope: the
2596/// caller pre-declares each statement list into its own frame, so
2597/// nested blocks resolve forward without leaking outward.
2598fn predeclare_forward_funcs(stmts: &[Stmt], ctx: &ParseCtx) {
2599    // Guarded definitions hoist like unguarded ones: `parse_func_at`
2600    // registers the name in `ctx.funcs` unconditionally, so the
2601    // forward set must see the same statement regardless of its
2602    // guard, or forward calls to `[os:macos] FUNC FOO` would fail
2603    // while backward calls resolve.
2604    for stmt in stmts {
2605        let body = &stmt.body;
2606        // `ASYNC FUNC` carries the prefix; the shared header owner
2607        // takes `pos` at `FUNC` in both cases.
2608        let pos = match body.first().map(|t| &t.kind) {
2609            Some(TokKind::Word(w)) if w == KEYWORD_FUNC => 0,
2610            Some(TokKind::Word(w)) if w == KEYWORD_ASYNC => match body.get(1).map(|t| &t.kind) {
2611                Some(TokKind::Word(next)) if next == KEYWORD_FUNC => 1,
2612                _ => continue,
2613            },
2614            _ => continue,
2615        };
2616        // Header grammar lives in the single owner: parameter lists,
2617        // return types, and trailing tokens validate exactly like the
2618        // real path, so malformed headers never hoist. Diagnostics
2619        // drop here (silent skip); the main pass owns the error.
2620        let Ok(Some((header, _))) = parse_func_header(body, pos, 0, KEYWORD_FUNC) else {
2621            continue;
2622        };
2623        if ctx.reserved.contains(&header.name)
2624            || ctx.modules.reserved_base_names().contains(&header.name)
2625        {
2626            continue;
2627        }
2628        // Trailing tokens after the body block are malformed (the real
2629        // path consumes the header exactly, leaving them to fail as the
2630        // next element), so such headers never hoist into `forward`:
2631        // only gap trivia may follow.
2632        if body.len() != header.block + 1
2633            && !body[header.block + 1..]
2634                .iter()
2635                .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
2636        {
2637            continue;
2638        }
2639        if let Some(frame) = ctx.forward.borrow_mut().last_mut() {
2640            frame.insert(header.name.clone());
2641        }
2642    }
2643}
2644
2645/// Qualify bare placeholder calls in template text through the
2646/// shared static resolver, so `{{ NAME(args) }}` obeys exactly the
2647/// same scope rule as statement-position calls: `IMPORT [MOD]`
2648/// brings the names into scope, unimported names fail naming the
2649/// fix, ambiguity fails closed. Qualified (`MOD::FUNC`), variable
2650/// (`$x`, `bare_key`), env (`env:K`), and non-call keys pass
2651/// through untouched for the runtime to handle exactly as before;
2652/// only keys that are entirely one bare call shape are rewritten,
2653/// and only the head identifier's bytes change: surrounding
2654/// spacing and neighboring placeholders stay byte-identical, so
2655/// string payloads never lose formatting. Returns `None` when
2656/// nothing qualified, leaving the text completely untouched.
2657/// Shape detection is the shared `template::parse_placeholder_call`
2658/// grammar (also behind runtime dispatch), so parse and runtime
2659/// can never disagree on what counts as one call.
2660fn qualify_template_calls(
2661    text: &str,
2662    ctx: &ParseCtx,
2663    stmt: usize,
2664) -> Result<Option<String>, TokenError> {
2665    use crate::template::{TemplateSegment, TemplateSegments, parse_placeholder_call};
2666    let mut out = String::with_capacity(text.len());
2667    let mut changed = false;
2668    for segment in TemplateSegments::new(text) {
2669        match segment {
2670            TemplateSegment::Text(raw) => out.push_str(raw),
2671            TemplateSegment::Placeholder { key, raw } => {
2672                let call = match parse_placeholder_call(key) {
2673                    Some(call) if call.module.is_none() => call,
2674                    _ => {
2675                        out.push_str(raw);
2676                        continue;
2677                    }
2678                };
2679                let head = call.name;
2680                let resolved = resolve_name(ctx, stmt, head)?;
2681                if !resolved.contains(MODULE_SEPARATOR) {
2682                    // Unqualified resolutions (`INSPECT`) keep today's
2683                    // runtime handling untouched.
2684                    out.push_str(raw);
2685                    continue;
2686                }
2687                changed = true;
2688                // Splice only the head span: `name_span` is the byte
2689                // range of the head inside `key`, and `key` is the
2690                // trimmed interior of `raw`, so the raw offset is the
2691                // interior start plus the span start.
2692                let key_off = raw.find(key).expect("key is trimmed interior");
2693                let off = key_off + call.name_span.start;
2694                out.push_str(&raw[..off]);
2695                out.push_str(&resolved);
2696                out.push_str(&raw[off + head.len()..]);
2697            }
2698        }
2699    }
2700    if changed { Ok(Some(out)) } else { Ok(None) }
2701}
2702
2703/// Call shape at `pos`: UPPERCASE head plus joint `::` segments and a
2704/// paren group (joint iff required: statements forbid the gap;
2705/// expressions allow it).
2706/// Peek-only; anything else falls through (not a call shape).
2707/// Returns the dotted name and paren index.
2708fn call_shape_at(toks: &[Tok], pos: usize, joint_paren: bool) -> Option<(String, usize)> {
2709    let head = match toks.get(pos).map(|t| &t.kind) {
2710        Some(TokKind::Word(w))
2711            if !w.is_empty()
2712                && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
2713                && w.chars()
2714                    .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') =>
2715        {
2716            w.clone()
2717        }
2718        _ => return None,
2719    };
2720    let mut name = head;
2721    let mut p = pos + 1;
2722    loop {
2723        let colons = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')))
2724            && toks.get(p).is_some_and(|t| t.joint)
2725            && matches!(toks.get(p + 1).map(|t| &t.kind), Some(TokKind::Punct(':')))
2726            && toks.get(p + 1).is_some_and(|t| t.joint)
2727            && matches!(toks.get(p + 2).map(|t| &t.kind), Some(TokKind::Word(_)))
2728            && toks.get(p + 2).is_some_and(|t| t.joint);
2729        if !colons {
2730            break;
2731        }
2732        if let Some(TokKind::Word(seg)) = toks.get(p + 2).map(|t| &t.kind) {
2733            name.push_str(MODULE_SEPARATOR);
2734            name.push_str(seg);
2735        }
2736        p += 3;
2737    }
2738    match toks.get(p).map(|t| &t.kind) {
2739        Some(TokKind::Group {
2740            delim: GroupDelim::Paren,
2741            ..
2742        }) => {
2743            if joint_paren && !toks[p].joint {
2744                return None;
2745            }
2746            Some((name, p))
2747        }
2748        _ => None,
2749    }
2750}
2751
2752/// Call arguments over a paren group's contents: comma-separated full
2753/// expressions with `gap_nl` newlines at the edges (each arg rejects
2754/// a stray boundary).
2755fn parse_call_args(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Vec<Expr>, TokenError> {
2756    let mut cur = Cursor::expr(inner, stmt);
2757    cur.skip_gap_nl();
2758    if cur.done() {
2759        return Ok(vec![]);
2760    }
2761    let mut args = Vec::new();
2762    loop {
2763        let arg = parse_expr_or(&mut cur, ctx)?;
2764        reject_boundary(&lowering_ctx(stmt), &arg).map_err(|e| cur.err(e.to_string()))?;
2765        args.push(arg);
2766        cur.skip_gap_nl();
2767        if cur.eat_punct(',') {
2768            cur.skip_gap_nl();
2769            continue;
2770        }
2771        break;
2772    }
2773    if !cur.done() {
2774        return Err(trailing_items_error(
2775            &cur,
2776            ctx,
2777            stmt,
2778            "call arguments",
2779            "unexpected text in call",
2780        ));
2781    }
2782    Ok(args)
2783}
2784
2785/// Lower a call-shape to `Expr`: `INSPECT` keeps its variable
2786/// unevaluated; everything else
2787/// resolves statically through the shared resolver.
2788fn parse_expr_call(
2789    name: String,
2790    inner: &[Tok],
2791    stmt: usize,
2792    ctx: &ParseCtx,
2793) -> Result<Expr, TokenError> {
2794    let args = parse_call_args(inner, stmt, ctx)?;
2795    if name == KEYWORD_INSPECT {
2796        let [arg] = args.as_slice() else {
2797            return Err(TokenError {
2798                stmt,
2799                msg: "INSPECT requires exactly one argument: INSPECT($var)".to_string(),
2800                line: 0,
2801                col: 0,
2802                kind: None,
2803            });
2804        };
2805        if let Expr::Var(var) = arg {
2806            return Ok(Expr::Inspect(var.clone()));
2807        }
2808        return Err(TokenError {
2809            stmt,
2810            msg: format!("INSPECT requires a $variable argument, found {arg:?}"),
2811            line: 0,
2812            col: 0,
2813            kind: None,
2814        });
2815    }
2816    let qualified = resolve_name(ctx, stmt, &name)?;
2817    Ok(Expr::Call {
2818        name: qualified,
2819        args,
2820    })
2821}
2822
2823/// Item rule selecting which `[...]` position the shared list core
2824/// parses for. The loop, comma rule, empty rule, trailing-content rule,
2825/// and newline tolerance are identical for every position (see
2826/// [`parse_bracket_list`]); only items and miss handling differ.
2827#[derive(Clone, Copy)]
2828enum BracketItems {
2829    /// Full checked expressions; a miss fails loudly.
2830    Expr,
2831    /// RUN-exec restricted atoms (brace groups try maps only, so blocks
2832    /// miss); a miss is shell fallthrough (`None`), never an error, so
2833    /// POSIX `[ -f ... ]` and malformed shapes stay shell.
2834    Exec,
2835}
2836
2837/// Trailing-content error for comma-separated positions (list
2838/// items, call arguments): stamps the offending token's position so
2839/// the caret names the line that actually fails instead of the
2840/// statement head, and names the likely missing comma when the
2841/// remainder parses as another item. Genuine trailing garbage keeps
2842/// the previous message verbatim. Error-path only, so the probe
2843/// parse costs nothing on success.
2844fn trailing_items_error(
2845    cur: &Cursor,
2846    ctx: &ParseCtx,
2847    stmt: usize,
2848    missing_what: &str,
2849    fallback: &str,
2850) -> TokenError {
2851    let (line, col) = cur
2852        .toks
2853        .get(cur.pos)
2854        .map(|t| (t.line, t.col))
2855        .unwrap_or((0, 0));
2856    let mut probe = Cursor::expr(&cur.toks[cur.pos.min(cur.toks.len())..], stmt);
2857    let msg = if parse_expr_checked(&mut probe, ctx).is_ok() {
2858        format!("missing comma between {missing_what}")
2859    } else {
2860        fallback.to_string()
2861    };
2862    TokenError {
2863        stmt,
2864        line,
2865        col,
2866        msg,
2867        kind: None,
2868    }
2869}
2870
2871/// Shared comma-separated `[...]` core behind every bracket position.
2872/// There is exactly one list loop: one empty rule, one comma rule, one
2873/// trailing-content rule, newlines riding every gap. A bracket group
2874/// already lexes across lines, so rejecting newlines here only strands
2875/// the statement in raw-text rendering.
2876fn parse_bracket_list(
2877    inner: &[Tok],
2878    stmt: usize,
2879    ctx: &ParseCtx,
2880    items: BracketItems,
2881) -> Result<Option<Expr>, TokenError> {
2882    let mut cur = Cursor::expr(inner, stmt);
2883    cur.skip_gap_nl();
2884    if cur.done() {
2885        return Ok(Some(Expr::List(vec![])));
2886    }
2887    let mut list = Vec::new();
2888    loop {
2889        let item = match items {
2890            BracketItems::Expr => parse_expr_checked(&mut cur, ctx),
2891            BracketItems::Exec => match parse_run_exec_atom(&mut cur, ctx) {
2892                Ok(Some(atom)) => Ok(atom),
2893                // Not an exec shape at all: shell fallthrough.
2894                Ok(None) | Err(_) => return Ok(None),
2895            },
2896        };
2897        // Only expression positions can fail here: exec misses
2898        // return `None` above.
2899        let item = item?;
2900        match reject_boundary(&lowering_ctx(stmt), &item) {
2901            Ok(()) => {}
2902            Err(e) if matches!(items, BracketItems::Expr) => {
2903                return Err(cur.err(e.to_string()));
2904            }
2905            Err(_) => return Ok(None),
2906        }
2907        list.push(item);
2908        cur.skip_gap_nl();
2909        if cur.eat_punct(',') {
2910            cur.skip_gap_nl();
2911            continue;
2912        }
2913        break;
2914    }
2915    if !cur.done() {
2916        return match items {
2917            BracketItems::Expr => Err(trailing_items_error(
2918                &cur,
2919                ctx,
2920                stmt,
2921                "list items",
2922                "unexpected text in list",
2923            )),
2924            BracketItems::Exec => Ok(None),
2925        };
2926    }
2927    Ok(Some(Expr::List(list)))
2928}
2929
2930/// RUN exec-form list: the shared bracket core in `Exec` mode (atoms
2931/// only, except parenthesized/calls/lists/maps which recurse fully).
2932/// Anything that is not a clean comma-separated list misses the whole
2933/// exec shape (`None`): the grammar falls through to the shell path,
2934/// which reads the bracket literally and lets the shared lowering
2935/// decide (POSIX `[ -f ... ]` stays shell; non-map blocks and malformed
2936/// shapes behave exactly like the grammar's fallthrough).
2937/// (`instruction`), which reads the bracket literally and lets the
2938/// shared lowering decide (POSIX `[ -f ... ]` stays shell, malformed
2939/// shapes fail there exactly like the grammar). Only the
2940/// joint-bracket gate stays a hard error (it precedes this function).
2941fn parse_run_exec_list(
2942    inner: &[Tok],
2943    stmt: usize,
2944    ctx: &ParseCtx,
2945) -> Result<Option<Expr>, TokenError> {
2946    parse_bracket_list(inner, stmt, ctx, BracketItems::Exec)
2947}
2948
2949/// One RUN-exec item: brace groups try maps only (blocks miss);
2950/// everything else parses as a full atom (nested lists and map
2951/// values still admit blocks, like the grammar).
2952fn parse_run_exec_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Option<Expr>, TokenError> {
2953    if matches!(
2954        cur.toks.get(cur.pos).map(|t| &t.kind),
2955        Some(TokKind::Group {
2956            delim: GroupDelim::Brace,
2957            ..
2958        })
2959    ) {
2960        let inner = match &cur.toks[cur.pos].kind {
2961            TokKind::Group { inner, .. } => inner.clone(),
2962            _ => unreachable!(),
2963        };
2964        return match parse_map_literal(&inner, cur.stmt, ctx) {
2965            Ok(map) => {
2966                cur.pos += 1;
2967                Ok(Some(map))
2968            }
2969            Err(_) => Ok(None),
2970        };
2971    }
2972    parse_expr_atom(cur, ctx).map(Some)
2973}
2974
2975// ---- Single-command wrappers + AWAIT/CANCEL ----
2976// Wrappers parse through the shared validators (`check_tty_wrapping`,
2977// capture rejects, isolated rewrite, nesting reject, binding merge,
2978// guard `and`) promoted verbatim to `commands.rs`; only the
2979// token-level shape classifiers (duration gate, binding splitter,
2980// await/cancel shapes, block-vs-template) are v2-native. Statements
2981// lower to step VECTORS: structural pairs (calls, RUN-exec,
2982// await/cancel, wrapper blocks) end mid-line and trailing elements
2983// form following steps, exactly like the grammar's `element*`.
2984//
2985// Deferred: block STATEMENTS (slice 5: top-level `IF`/`FOR`/`WHILE`
2986// bodies, guard blocks, `REMOTE`, directives).
2987
2988/// Static duration shape mirror (`timeout_literal`, atomic): ASCII
2989/// digits plus one optional unit, full-match only. Anything else
2990/// (`10ss`, `banana`, `-5s`) misses the wrapper shape and falls back
2991/// to the generic instruction path, which fails in lowering exactly
2992/// like the grammar's committed `instruction`.
2993fn is_timeout_literal(text: &str) -> bool {
2994    let digits = text.len() - text.trim_start_matches(|c: char| c.is_ascii_digit()).len();
2995    if digits == 0 {
2996        return false;
2997    }
2998    matches!(&text[digits..], "" | "ms" | "s" | "m" | "h")
2999}
3000
3001/// Template-brace test: a brace group whose first inner token opens
3002/// another brace (`{{...}}`); anything else braced is a block body.
3003/// Same shape the arg engine uses; single source from here.
3004fn is_template_brace(tok: &Tok) -> bool {
3005    matches!(
3006        &tok.kind,
3007        TokKind::Group {
3008            delim: GroupDelim::Brace,
3009            inner,
3010            ..
3011        } if matches!(
3012            inner.first().map(|t| &t.kind),
3013            Some(TokKind::Group {
3014                delim: GroupDelim::Brace,
3015                ..
3016            })
3017        )
3018    )
3019}
3020
3021/// Parse one TIMEOUT duration unit at `pos` (the token after the
3022/// head, gapped like the grammar's `sep`). Returns the arg and
3023/// tokens consumed, or `None` on shape miss (caller falls back to
3024/// generic, which fails in lowering). Static
3025/// literals validate now through the shared Duration check
3026/// (`TIMEOUT 0s` fails here, probed); dynamics defer to runtime.
3027fn parse_timeout_duration_at(
3028    toks: &[Tok],
3029    pos: usize,
3030    stmt: usize,
3031) -> Result<Option<(Arg, usize)>, TokenError> {
3032    let Some(head) = toks.get(pos) else {
3033        return Ok(None);
3034    };
3035    if head.joint {
3036        return Ok(None);
3037    }
3038    let arg = match &head.kind {
3039        TokKind::Word(w) if is_timeout_literal(w) => Arg::String(w.clone(), false),
3040        TokKind::Punct('$') => match toks.get(pos + 1) {
3041            Some(var) if var.joint && matches!(&var.kind, TokKind::Word(w) if is_ident_word(w)) => {
3042                match &var.kind {
3043                    TokKind::Word(w) => Arg::Expr(Expr::Var(w.clone())),
3044                    _ => unreachable!(),
3045                }
3046            }
3047            _ => return Ok(None),
3048        },
3049        TokKind::Str { text, .. } => Arg::String(text.clone(), true),
3050        TokKind::BlockStr(full) => Arg::String(crate::command::lower_block_string(full), true),
3051        TokKind::Group {
3052            delim: GroupDelim::Brace,
3053            inner,
3054            open_joint,
3055            close_joint,
3056        } if is_template_brace(&toks[pos]) => Arg::String(
3057            render_group('{', '}', inner, *open_joint, *close_joint),
3058            false,
3059        ),
3060        _ => return Ok(None),
3061    };
3062    let used = match &head.kind {
3063        TokKind::Punct('$') => 2,
3064        _ => 1,
3065    };
3066    ArgType::Duration.check_arg(&arg).map_err(|e| TokenError {
3067        stmt,
3068        msg: e.to_string(),
3069        line: 0,
3070        col: 0,
3071        kind: None,
3072    })?;
3073    Ok(Some((arg, used)))
3074}
3075
3076/// Parse `WITH_IO [...]` bindings over a bracket group's inner
3077/// tokens: comma-separated `stream[=$var]` / `rows|cols=int`
3078/// bindings, newlines skipping freely like `ws`. Returns `None` on
3079/// shape miss (empty flags, bad stream words, missing commas or
3080/// values: the caller falls back to generic, which fails in lowering).
3081/// Grammar-matched but invalid bindings (tty
3082/// values, out-of-range geometry) fail loudly, mirroring
3083/// `parse_io_binding`'s messages one by one.
3084fn parse_io_bindings(inner: &[Tok], stmt: usize) -> Result<Option<Vec<IoBinding>>, TokenError> {
3085    let mut parts: Vec<&[Tok]> = Vec::new();
3086    let mut start = 0;
3087    for (i, tok) in inner.iter().enumerate() {
3088        // Newlines skip freely like `ws` (filtered per part below);
3089        // commas split bindings; everything else is content.
3090        if matches!(&tok.kind, TokKind::Punct(',')) {
3091            parts.push(&inner[start..i]);
3092            start = i + 1;
3093        }
3094    }
3095    parts.push(&inner[start..]);
3096    // An empty flag list (`[]`, `[,]`) misses the shape.
3097    if parts.len() == 1 && parts[0].iter().all(|t| matches!(&t.kind, TokKind::Newline)) {
3098        return Ok(None);
3099    }
3100    let mut out = Vec::new();
3101    for part in parts {
3102        let part: Vec<&Tok> = part
3103            .iter()
3104            .filter(|t| !matches!(&t.kind, TokKind::Newline))
3105            .collect();
3106        match parse_io_binding_part(&part, stmt)? {
3107            Some(binding) => out.push(binding),
3108            None => return Ok(None),
3109        }
3110    }
3111    if out.is_empty() {
3112        return Ok(None);
3113    }
3114    Ok(Some(out))
3115}
3116
3117/// One `stream[=$var]` / `rows|cols=int` binding. Gaps ride free
3118/// around `=`/`,`/names like `ws?`; only `$`+name stays gapless
3119/// (atomic `dollar_ident`). Streams and size names outside the
3120/// grammar's words miss the shape; a valued `tty` and out-of-range
3121/// geometry fail loudly with exact messages.
3122fn parse_io_binding_part(part: &[&Tok], stmt: usize) -> Result<Option<IoBinding>, TokenError> {
3123    let fail = |msg: String| TokenError {
3124        stmt,
3125        msg,
3126        line: 0,
3127        col: 0,
3128        kind: None,
3129    };
3130    let Some(first) = part.first() else {
3131        return Ok(None);
3132    };
3133    let TokKind::Word(stream) = &first.kind else {
3134        return Ok(None);
3135    };
3136    let is_stream = matches!(stream.as_str(), "stdin" | "stdout" | "stderr" | "tty");
3137    let is_size = matches!(stream.as_str(), "rows" | "cols");
3138    if !is_stream && !is_size {
3139        return Ok(None);
3140    }
3141    let rest = &part[1..];
3142    if rest.is_empty() {
3143        if is_size {
3144            // Bare `rows` misses `io_size` (`=` + digits required).
3145            return Ok(None);
3146        }
3147        return Ok(Some(IoBinding {
3148            stream: io_stream_of(stream),
3149            pipe: None,
3150        }));
3151    }
3152    // `= value` at any gap.
3153    if !matches!(rest.first().map(|t| &t.kind), Some(TokKind::Punct('='))) {
3154        return Ok(None);
3155    }
3156    let value = &rest[1..];
3157    if is_size {
3158        // Geometry: one all-digit word, 1-65535 (mirrors `parse_io_size`).
3159        if value.len() != 1 {
3160            return Ok(None);
3161        }
3162        let TokKind::Word(digits) = &value[0].kind else {
3163            return Ok(None);
3164        };
3165        if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
3166            return Ok(None);
3167        }
3168        let dim = digits
3169            .parse::<u64>()
3170            .ok()
3171            .filter(|v| (1..=u64::from(u16::MAX)).contains(v))
3172            .ok_or_else(|| {
3173                fail(
3174                    "WITH_IO terminal geometry needs a positive integer 1-65535 (e.g. `rows=40`)"
3175                        .to_string(),
3176                )
3177            })?;
3178        let dim = dim as u16;
3179        return Ok(Some(IoBinding {
3180            stream: if stream == "rows" {
3181                IoStream::Rows(dim)
3182            } else {
3183                IoStream::Cols(dim)
3184            },
3185            pipe: None,
3186        }));
3187    }
3188    // Stream pipe: `= $var` with a gapless name.
3189    if value.len() != 2 {
3190        return Ok(None);
3191    }
3192    if !matches!(&value[0].kind, TokKind::Punct('$')) {
3193        return Ok(None);
3194    }
3195    let TokKind::Word(var) = &value[1].kind else {
3196        return Ok(None);
3197    };
3198    if !value[1].joint || !is_ident_word(var) {
3199        return Ok(None);
3200    }
3201    if stream == "tty" {
3202        // `tty` is a bare flag (mirrors `parse_io_binding`).
3203        return Err(fail(
3204            "WITH_IO [tty] takes no value: use bare `tty`, with `rows = <int>` / `cols = <int>` for geometry (e.g. `[tty, rows=40, cols=100]`)"
3205                .to_string(),
3206        ));
3207    }
3208    Ok(Some(IoBinding {
3209        stream: io_stream_of(stream),
3210        pipe: Some(crate::ast::PipeTarget::Var(var.clone())),
3211    }))
3212}
3213
3214/// Stream word to [`IoStream`]: only grammar words reach here, so
3215/// the mapping is total (mirrors `parse_io_stream`).
3216fn io_stream_of(name: &str) -> IoStream {
3217    match name {
3218        "stdin" => IoStream::Stdin,
3219        "stdout" => IoStream::Stdout,
3220        "stderr" => IoStream::Stderr,
3221        _ => IoStream::Tty,
3222    }
3223}
3224
3225/// `AWAIT`/`CANCEL $var` shape at `pos`. A head without `$` misses
3226/// (`None`: generic fails it in lowering); once `$`
3227/// commits, the name must follow and parse errors stay loud, like
3228/// the grammar's committed `"$" ~ ident`. `var_joint` enforces the
3229/// atomic `$var` adjacency inside compound-atomic parents; element
3230/// level admits the gap (probed `AWAIT $ t`). The caller continues
3231/// its element loop past the shape.
3232fn parse_await_cancel_at(
3233    toks: &[Tok],
3234    pos: usize,
3235    stmt: usize,
3236    var_joint: bool,
3237) -> Result<Option<(StepKind, usize)>, TokenError> {
3238    let head = match toks.get(pos).map(|t| &t.kind) {
3239        Some(TokKind::Word(w)) if w == KEYWORD_AWAIT || w == KEYWORD_CANCEL => w.clone(),
3240        _ => return Ok(None),
3241    };
3242    if !matches!(
3243        toks.get(pos + 1).map(|t| &t.kind),
3244        Some(TokKind::Punct('$'))
3245    ) {
3246        return Ok(None);
3247    }
3248    let var = match toks.get(pos + 2) {
3249        Some(t)
3250            if matches!(&t.kind, TokKind::Word(w) if is_ident_word(w))
3251                && (!var_joint || t.joint) =>
3252        {
3253            match &t.kind {
3254                TokKind::Word(w) => w.clone(),
3255                _ => unreachable!(),
3256            }
3257        }
3258        _ => {
3259            return Err(TokenError {
3260                stmt,
3261                msg: format!("{head} requires a variable"),
3262                line: 0,
3263                col: 0,
3264                kind: None,
3265            });
3266        }
3267    };
3268    Ok(Some((
3269        if head == KEYWORD_AWAIT {
3270            StepKind::Await { var }
3271        } else {
3272            StepKind::Cancel { var }
3273        },
3274        3,
3275    )))
3276}
3277
3278/// Wrapper strictness for one single-command inner: `AWAIT` parses
3279/// dedicated in `TIMEOUT`/`ISOLATED` inners but falls to generic in
3280/// `WITH_IO`/`ASYNC` inners (where lowering fails it, probed), and
3281/// `WITH_IO` recurses everywhere but directly under `ASYNC` (where
3282/// lowering fails it, probed). Shared predicates, never restated.
3283#[derive(Clone, Copy)]
3284struct InnerRules {
3285    allow_await: bool,
3286    allow_with_io: bool,
3287}
3288
3289/// Parse one single (non-block) inner command, returning the kind
3290/// and tokens consumed: dedicated await/cancel, while/remote, calls,
3291/// RUN-exec, nested wrappers, strict `INHERIT_ENV` (the caller
3292/// rejects the nesting or rewrites it), or the generic instruction
3293/// path (which consumes everything and fails unknown heads in
3294/// lowering, exactly like the grammar's committed `instruction`).
3295fn parse_single_inner(
3296    toks: &[Tok],
3297    pos: usize,
3298    stmt: usize,
3299    ctx: &ParseCtx,
3300    rules: InnerRules,
3301) -> Result<(StepKind, usize), TokenError> {
3302    let head_word = match toks.get(pos).map(|t| &t.kind) {
3303        Some(TokKind::Word(w)) => Some(w.clone()),
3304        _ => None,
3305    };
3306    // Nested `WHILE`/`REMOTE` recurse structurally (both ride every
3307    // inner-command set in the grammar); misses fall through to
3308    // generic below.
3309    if head_word.as_deref() == Some(KEYWORD_WHILE) {
3310        match parse_while_single(toks, pos, stmt, ctx) {
3311            Ok(Some((kind, used))) => return Ok((kind, used)),
3312            Ok(None) => {}
3313            Err(e) => return Err(e),
3314        }
3315    }
3316    if head_word.as_deref() == Some(KEYWORD_REMOTE) {
3317        match parse_remote_single(toks, pos, stmt, ctx) {
3318            Ok(Some((kind, used))) => return Ok((kind, used)),
3319            Ok(None) => {}
3320            Err(e) => return Err(e),
3321        }
3322    }
3323    // File `IMPORT "path" AS ALIAS` (#115) rides every single-inner
3324    // set (TIMEOUT/ISOLATED/WITH_IO/ASYNC, LET ASYNC): exactly one file
3325    // entry and no modules, else a hard error; shape misses fall through
3326    // to generic below, which fails them in lowering.
3327    if head_word.as_deref() == Some(KEYWORD_IMPORT)
3328        && let Some((path, alias, used)) = parse_single_file_import(toks, pos, stmt, ctx)?
3329    {
3330        return Ok((StepKind::ImportFile { path, alias }, used));
3331    }
3332    // Dedicated await/cancel first (await gated by parent); anything
3333    // they decline falls through to generic below.
3334    if head_word.as_deref() == Some(KEYWORD_AWAIT)
3335        && rules.allow_await
3336        && let Some(found) = parse_await_cancel_at(toks, pos, stmt, true)?
3337    {
3338        return Ok(found);
3339    }
3340    if head_word.as_deref() == Some(KEYWORD_CANCEL)
3341        && let Some(found) = parse_await_cancel_at(toks, pos, stmt, true)?
3342    {
3343        return Ok(found);
3344    }
3345    // Calls and RUN-exec end mid-run; the caller continues past them.
3346    if let Some((call_name, paren)) = call_shape_at(toks, pos, true) {
3347        let inner = match &toks[paren].kind {
3348            TokKind::Group { inner, .. } => inner.clone(),
3349            _ => unreachable!(),
3350        };
3351        let args = parse_call_args(&inner, stmt, ctx)?;
3352        if !call_name.contains(MODULE_SEPARATOR) {
3353            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
3354                .map_err(|e| lower_err(stmt, e))?;
3355        }
3356        let qualified = resolve_name(ctx, stmt, &call_name)?;
3357        return Ok((
3358            StepKind::Call {
3359                name: qualified,
3360                args,
3361            },
3362            paren + 1 - pos,
3363        ));
3364    }
3365    if head_word.as_deref() == Some(KEYWORD_RUN)
3366        && matches!(
3367            toks.get(pos + 1).map(|t| &t.kind),
3368            Some(TokKind::Group {
3369                delim: GroupDelim::Bracket,
3370                ..
3371            })
3372        )
3373    {
3374        // Gapped like the grammar's `sep`; a joint bracket is a
3375        // hard error, never a spliced arg (probed `RUN["a"]`).
3376        if toks[pos + 1].joint {
3377            return Err(TokenError {
3378                stmt,
3379                msg: "RUN [...] requires a gap after RUN".to_string(),
3380                line: 0,
3381                col: 0,
3382                kind: None,
3383            });
3384        }
3385        let inner = match &toks[pos + 1].kind {
3386            TokKind::Group { inner, .. } => inner.clone(),
3387            _ => unreachable!(),
3388        };
3389        let exec_list = parse_run_exec_list(&inner, stmt, ctx)?;
3390        // Non-map blocks miss the exec shape (the grammar has no
3391        // `block` alternative here); fall through to generic below,
3392        // which reads the shell path literally.
3393        if let Some(list) = exec_list {
3394            let kind =
3395                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
3396            return Ok((kind, 2));
3397        }
3398    }
3399    // Nested wrappers recurse structurally; a `WITH_IO` directly
3400    // under `ASYNC` goes generic instead (lowering fails it, probed).
3401    match head_word.as_deref() {
3402        Some(KEYWORD_WITH_IO) if rules.allow_with_io => {
3403            match parse_with_io_single(toks, pos, stmt, ctx) {
3404                Ok(Some((kind, used))) => return Ok((kind, used)),
3405                Ok(None) => {}
3406                Err(e) => return Err(e),
3407            }
3408        }
3409        Some(KEYWORD_TIMEOUT) => match parse_timeout_single(toks, pos, stmt, ctx) {
3410            Ok(Some((kind, used))) => return Ok((kind, used)),
3411            Ok(None) => {}
3412            Err(e) => return Err(e),
3413        },
3414        Some(KEYWORD_ISOLATED) => match parse_isolated_single(toks, pos, stmt, ctx) {
3415            Ok(Some((kind, used))) => return Ok((kind, used)),
3416            Ok(None) => {}
3417            Err(e) => return Err(e),
3418        },
3419        Some(KEYWORD_ASYNC) => match parse_async_single(toks, pos, stmt, ctx) {
3420            Ok(Some((kind, used))) => return Ok((kind, used)),
3421            Ok(None) => {}
3422            Err(e) => return Err(e),
3423        },
3424        // `INHERIT_ENV [...]` parses strictly here (shared with
3425        // element level); the caller either rejects the nesting or
3426        // rewrites it, same as the shared validator. Trailing
3427        // elements loop on outside (a bad follower fails there, like
3428        // the grammar's line end).
3429        Some(KEYWORD_INHERIT_ENV) => {
3430            if let Some(found) = parse_inherit_env_at(toks, pos, stmt)? {
3431                return Ok(found);
3432            }
3433        }
3434        _ => {}
3435    }
3436    // Generic instruction: consumes the whole run; unknown heads
3437    // (LET/RETURN/FUNC/IF/...) fail in lowering.
3438    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
3439    Ok((kind, used))
3440}
3441
3442/// Parse an `INHERIT_ENV [...]` key list over a bracket group's
3443/// inner tokens, mirroring `inherit_list` strictly: comma-separated
3444/// keys, gaps/newlines only around keys and commas (never inside:
3445/// keys are atomic), each key a joint run validated against the
3446/// `guard_key_char` exclusions (`: = ! , | ( ) ] $`, plus the `//`
3447/// and `/*` comment opens). Groups and strings render raw (they read
3448/// as ordinary characters here); anything else misses
3449/// the shape (`None`: generic fails it in lowering).
3450/// Statement-level `INHERIT_ENV` stays generic (slice 5 directives);
3451/// this serves wrapper inners, where the nesting check (or the
3452/// isolated rewrite) consumes the result.
3453fn parse_inherit_keys(inner: &[Tok], stmt: usize) -> Result<Option<Vec<String>>, TokenError> {
3454    let mut parts: Vec<&[Tok]> = Vec::new();
3455    let mut start = 0;
3456    for (i, tok) in inner.iter().enumerate() {
3457        if matches!(&tok.kind, TokKind::Punct(',')) {
3458            parts.push(&inner[start..i]);
3459            start = i + 1;
3460        }
3461    }
3462    parts.push(&inner[start..]);
3463    let mut out = Vec::new();
3464    for part in parts {
3465        // Newlines skip at the edges only, like `ws?`.
3466        let mut part = part;
3467        while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
3468            part = &part[1..];
3469        }
3470        while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
3471            part = &part[..part.len() - 1];
3472        }
3473        let Some(key) = render_inherit_key(part, stmt)? else {
3474            return Ok(None);
3475        };
3476        out.push(key);
3477    }
3478    if out.is_empty() {
3479        return Ok(None);
3480    }
3481    Ok(Some(out))
3482}
3483
3484/// True when a `/` opens an inline comment: joint `//` or `/*`
3485/// (mirroring the grammar's comment literals, which need adjacency;
3486/// a gapped second char is payload text, like `a/ /b`). Used
3487/// everywhere `gap`/`gap_nl` admit comments.
3488fn is_comment_open(toks: &[Tok], pos: usize) -> bool {
3489    matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('/')))
3490        && matches!(
3491            toks.get(pos + 1).map(|t| (&t.kind, t.joint)),
3492            Some((TokKind::Punct('/'), true)) | Some((TokKind::Punct('*'), true))
3493        )
3494}
3495
3496/// Skip one inline comment starting at `pos` (which holds the `/`;
3497/// see [`is_comment_open`): `//` runs to a newline or the end,
3498/// `/* */` balances (nesting like the grammar) across newlines.
3499/// Returns the first position past the comment, or `None` when the
3500/// block never closes (the grammar fails unclosed comments too).
3501fn skip_inline_comment(toks: &[Tok], pos: usize) -> Option<usize> {
3502    let second = match toks.get(pos + 1).map(|t| &t.kind) {
3503        Some(TokKind::Punct('/')) => '/',
3504        Some(TokKind::Punct('*')) => '*',
3505        _ => return None,
3506    };
3507    if second == '/' {
3508        let mut p = pos + 2;
3509        while p < toks.len() && !matches!(&toks[p].kind, TokKind::Newline) {
3510            p += 1;
3511        }
3512        return Some(p);
3513    }
3514    let mut depth = 1usize;
3515    let mut p = pos + 2;
3516    while p < toks.len() {
3517        let is_open = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('/')))
3518            && matches!(
3519                toks.get(p + 1).map(|t| (&t.kind, t.joint)),
3520                Some((TokKind::Punct('*'), true))
3521            );
3522        let is_close = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('*')))
3523            && matches!(
3524                toks.get(p + 1).map(|t| (&t.kind, t.joint)),
3525                Some((TokKind::Punct('/'), true))
3526            );
3527        if is_open {
3528            depth += 1;
3529            p += 2;
3530        } else if is_close {
3531            depth -= 1;
3532            p += 2;
3533            if depth == 0 {
3534                return Some(p);
3535            }
3536        } else {
3537            p += 1;
3538        }
3539    }
3540    None
3541}
3542
3543/// Parse one inherit key: a maximal key-char run, then only
3544/// trailing gap content (`gap_nl`: newlines, comments, `#`). Key
3545/// chars exclude `: = ! , | ( ) ] $`, whitespace, and the `//` / `/*`
3546/// comment opens; a joint `#`
3547/// stays literal, a gapped one opens a trailing comment. Groups and
3548/// strings render raw for the exclusion check (they read as
3549/// ordinary characters here). `None` on shape miss.
3550fn render_inherit_key(part: &[Tok], stmt: usize) -> Result<Option<String>, TokenError> {
3551    let mut out = String::new();
3552    let mut i = 0;
3553    // Key run: words, puncts (except comment opens), groups and
3554    // strings rendered raw; ends at any gap, newline, comment, or
3555    // `//` / `/*` open.
3556    while i < part.len() {
3557        let tok = &part[i];
3558        if i > 0 && !tok.joint {
3559            break;
3560        }
3561        match &tok.kind {
3562            TokKind::Word(w) => {
3563                out.push_str(w);
3564                i += 1;
3565            }
3566            TokKind::Punct('/') if is_comment_open(part, i) => break,
3567            // `#` stays literal at key start (`#c`) or joint
3568            // (`a#b`); gapped mid-key it opens a trailing
3569            // comment like the grammar's `gap_nl`.
3570            TokKind::Punct('#') if tok.joint || out.is_empty() => {
3571                // `#` stays literal at key start (`#c`) or joint
3572                // (`a#b`).
3573                out.push('#');
3574                i += 1;
3575            }
3576            // Gapped mid-key `#` opens a trailing comment (handled
3577            // by the trailer check below, like `gap_nl`).
3578            TokKind::Punct('#') => break,
3579            TokKind::Punct(c) => {
3580                out.push(*c);
3581                i += 1;
3582            }
3583            TokKind::Semicolon => {
3584                out.push(';');
3585                i += 1;
3586            }
3587            TokKind::Str { text, quote } => {
3588                out.push(*quote);
3589                out.push_str(text);
3590                out.push(*quote);
3591                i += 1;
3592            }
3593            TokKind::BlockStr(full) => {
3594                out.push_str(full);
3595                i += 1;
3596            }
3597            TokKind::Group {
3598                delim,
3599                inner,
3600                open_joint,
3601                close_joint,
3602            } => {
3603                let (open, close) = match delim {
3604                    GroupDelim::Bracket => ('[', ']'),
3605                    GroupDelim::Paren => ('(', ')'),
3606                    GroupDelim::Brace => ('{', '}'),
3607                };
3608                out.push_str(&render_group(open, close, inner, *open_joint, *close_joint));
3609                i += 1;
3610            }
3611            // Newlines and comment markers end the key; the trailer
3612            // check below admits them.
3613            TokKind::Newline | TokKind::Comment(_) => break,
3614        }
3615    }
3616    if out.is_empty() {
3617        return Ok(None);
3618    }
3619    // Trailer: only gap content (`gap_nl`) may follow the key.
3620    let mut j = i;
3621    while j < part.len() {
3622        let tok = &part[j];
3623        match &tok.kind {
3624            TokKind::Newline | TokKind::Comment(_) => {
3625                j += 1;
3626            }
3627            TokKind::Punct('/') if is_comment_open(part, j) => {
3628                j = skip_inline_comment(part, j).ok_or(TokenError {
3629                    stmt,
3630                    msg: "unclosed block comment".to_string(),
3631                    line: 0,
3632                    col: 0,
3633                    kind: None,
3634                })?;
3635            }
3636            TokKind::Punct('#') => {
3637                // `#` comment runs to a newline or the part end.
3638                while j < part.len() && !matches!(&part[j].kind, TokKind::Newline) {
3639                    j += 1;
3640                }
3641            }
3642            _ => return Ok(None),
3643        }
3644    }
3645    // `guard_key_char` exclusions: the single-char set plus the
3646    // comment opens (`//`, `/*`); lone `/` stays legal.
3647    if out.contains("//") || out.contains("/*") {
3648        return Ok(None);
3649    }
3650    if out
3651        .chars()
3652        .any(|c| matches!(c, ':' | '=' | '!' | ',' | '|' | '(' | ')' | ']' | '$'))
3653    {
3654        return Ok(None);
3655    }
3656    Ok(Some(out))
3657}
3658
3659/// Strict `INHERIT_ENV [...]` at an element or single-inner
3660/// position: bracket riding gapped with valid keys yields the
3661/// directive (trailing elements loop on outside); anything else
3662/// misses (`None`) and generic fails it in lowering.
3663/// Serves both levels so keys stay exact everywhere; slice 5 adds
3664/// only the prelude-order validation.
3665fn parse_inherit_env_at(
3666    toks: &[Tok],
3667    pos: usize,
3668    stmt: usize,
3669) -> Result<Option<(StepKind, usize)>, TokenError> {
3670    // The bracket rides gapped (`sep`); anything else misses and
3671    // generic fails it in lowering.
3672    let bracket = match toks.get(pos + 1) {
3673        Some(t)
3674            if !t.joint
3675                && matches!(
3676                    &t.kind,
3677                    TokKind::Group {
3678                        delim: GroupDelim::Bracket,
3679                        ..
3680                    }
3681                ) =>
3682        {
3683            Some(t)
3684        }
3685        _ => None,
3686    };
3687    let Some(bracket) = bracket else {
3688        return Ok(None);
3689    };
3690    let inner = match &bracket.kind {
3691        TokKind::Group { inner, .. } => inner,
3692        _ => unreachable!(),
3693    };
3694    match parse_inherit_keys(inner, stmt)? {
3695        Some(keys) => Ok(Some((StepKind::InheritEnv { keys }, 2))),
3696        None => Ok(None),
3697    }
3698}
3699
3700/// Parse a brace block body into steps: statements split and lower
3701/// recursively, each keeping its own guard. `mark` selects scope
3702/// marking: top-level guard-block bodies mark (each nesting level
3703/// bumps first/last); wrapper bodies
3704/// (`IF`/`FOR`/`WHILE`/`FUNC`/`REMOTE`/wrappers/io-blocks) never mark
3705/// (block-element lowering pins 0/0).
3706fn parse_body_steps(
3707    inner: &[Tok],
3708    stmt: usize,
3709    ctx: &ParseCtx,
3710    mark: bool,
3711) -> Result<Vec<Step>, TokenError> {
3712    // One function/import scope per braced body (mirroring the
3713    // runtime push/pop boundary): same-block
3714    // `FUNC` redefinition errors, nested shadowing stays allowed.
3715    // Errors abort the whole parse (frames discarded with it), so no
3716    // exit runs on failure.
3717    ctx.funcs.borrow_mut().push(HashSet::new());
3718    ctx.imports.borrow_mut().push(Vec::new());
3719    ctx.forward.borrow_mut().push(HashSet::new());
3720    // Nested splits count lines from the enclosing statement's line
3721    // (headers are single-line, so the brace shares it). Save and
3722    // restore the discipline around the loop: sibling bodies after
3723    // this one must see the enclosing line, not the last inner one.
3724    // (On error the parse aborts and the context is discarded.)
3725    let saved = *ctx.current_line.borrow();
3726    let mut out = Vec::new();
3727    let stmts = split_statements(inner, saved)?;
3728    predeclare_forward_funcs(&stmts, ctx);
3729    for s in &stmts {
3730        // The innermost statement owns error positions: record it for
3731        // nested splits and stamp failures that have none yet (deeper
3732        // frames stamp first, so this never overwrites real positions).
3733        *ctx.current_line.borrow_mut() = s.line;
3734        out.extend(
3735            lower_stmt_steps(s, stmt, ctx, true, mark).map_err(|e| stamp_pos(e, s.line, s.col))?,
3736        );
3737    }
3738    *ctx.current_line.borrow_mut() = saved;
3739    ctx.funcs.borrow_mut().pop();
3740    ctx.imports.borrow_mut().pop();
3741    ctx.forward.borrow_mut().pop();
3742    Ok(out)
3743}
3744
3745/// Single (non-block) `WITH_IO`: bindings plus an optional inner
3746/// command. `None` on shape miss (no/gapped bracket: generic fails
3747/// it in lowering). A brace in single-inner position is
3748/// the grammar's pending-guard error, never an io-block; a bare
3749/// bracket leaks the transient `WithIoBlock` into the body (probed).
3750fn parse_with_io_single(
3751    toks: &[Tok],
3752    pos: usize,
3753    stmt: usize,
3754    ctx: &ParseCtx,
3755) -> Result<Option<(StepKind, usize)>, TokenError> {
3756    let bracket = match toks.get(pos + 1) {
3757        // The bracket rides gapped (`sep`); anything else misses the
3758        // shape and generic fails it in lowering.
3759        Some(t)
3760            if !t.joint
3761                && matches!(
3762                    &t.kind,
3763                    TokKind::Group {
3764                        delim: GroupDelim::Bracket,
3765                        ..
3766                    }
3767                ) =>
3768        {
3769            t
3770        }
3771        _ => return Ok(None),
3772    };
3773    let inner = match &bracket.kind {
3774        TokKind::Group { inner, .. } => inner.clone(),
3775        _ => unreachable!(),
3776    };
3777    let bindings = match parse_io_bindings(&inner, stmt)? {
3778        Some(bindings) => bindings,
3779        None => return Ok(None),
3780    };
3781    let rest = pos + 2;
3782    // A brace directly after the bracket is the pending-guard error
3783    // in single-inner position (probed); templates fall to generic.
3784    if let Some(next) = toks.get(rest)
3785        && matches!(
3786            &next.kind,
3787            TokKind::Group {
3788                delim: GroupDelim::Brace,
3789                ..
3790            }
3791        )
3792        && !is_template_brace(next)
3793    {
3794        return Err(TokenError {
3795            stmt,
3796            msg: "'{' without a pending guard".to_string(),
3797            line: 0,
3798            col: 0,
3799            kind: None,
3800        });
3801    }
3802    if rest >= toks.len() {
3803        // Bare bracket: the transient block node leaks into wrapper
3804        // bodies (statement level never reaches
3805        // here; the splitter holds it for `{`).
3806        return Ok(Some((StepKind::WithIoBlock { bindings }, 2)));
3807    }
3808    // A joint follower misses the inner `sep`: the bracket stands
3809    // bare (probed `TIMEOUT 10s WITH_IO [..]ECHO hi` yields the
3810    // transient node) and trailing elements loop on outside.
3811    if toks[rest].joint {
3812        return Ok(Some((StepKind::WithIoBlock { bindings }, 2)));
3813    }
3814    let (cmd, used) = parse_single_inner(
3815        toks,
3816        rest,
3817        stmt,
3818        ctx,
3819        InnerRules {
3820            allow_await: false,
3821            allow_with_io: true,
3822        },
3823    )?;
3824    let span = lowering_ctx(stmt);
3825    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| TokenError {
3826        stmt,
3827        msg: e.to_string(),
3828        line: 0,
3829        col: 0,
3830        kind: None,
3831    })?;
3832    let kind = StepKind::WithIo {
3833        bindings,
3834        cmd: Box::new(cmd),
3835    };
3836    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
3837        stmt,
3838        msg: e.to_string(),
3839        line: 0,
3840        col: 0,
3841        kind: None,
3842    })?;
3843    Ok(Some((kind, 2 + used)))
3844}
3845
3846/// Single (non-block) `TIMEOUT`: duration plus one inner command.
3847/// `None` on shape miss (bad duration, missing/joint inner: generic
3848/// fails it in lowering). Blocks parse inline; the body
3849/// holds one step for single inners.
3850fn parse_timeout_single(
3851    toks: &[Tok],
3852    pos: usize,
3853    stmt: usize,
3854    ctx: &ParseCtx,
3855) -> Result<Option<(StepKind, usize)>, TokenError> {
3856    let Some((duration, dused)) = parse_timeout_duration_at(toks, pos + 1, stmt)? else {
3857        return Ok(None);
3858    };
3859    let rest = pos + 1 + dused;
3860    let Some(next) = toks.get(rest) else {
3861        // `TIMEOUT 10s` alone is a generic instruction (lowering
3862        // fails it, probed), never a bare wrapper.
3863        return Ok(None);
3864    };
3865    if next.joint {
3866        return Ok(None);
3867    }
3868    let body = if matches!(
3869        &next.kind,
3870        TokKind::Group {
3871            delim: GroupDelim::Brace,
3872            ..
3873        }
3874    ) && !is_template_brace(next)
3875    {
3876        let inner = match &next.kind {
3877            TokKind::Group { inner, .. } => inner.clone(),
3878            _ => unreachable!(),
3879        };
3880        let steps = parse_body_steps(&inner, stmt, ctx, false)?;
3881        (steps, 1)
3882    } else {
3883        let (cmd, used) = parse_single_inner(
3884            toks,
3885            rest,
3886            stmt,
3887            ctx,
3888            InnerRules {
3889                allow_await: true,
3890                allow_with_io: true,
3891            },
3892        )?;
3893        (
3894            vec![Step {
3895                guard: None,
3896                kind: cmd,
3897                scope_enter: 0,
3898                scope_exit: 0,
3899                line: 0,
3900                col: 0,
3901            }],
3902            used,
3903        )
3904    };
3905    let kind = StepKind::Timeout {
3906        duration,
3907        body: body.0,
3908    };
3909    let span = lowering_ctx(stmt);
3910    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
3911        stmt,
3912        msg: e.to_string(),
3913        line: 0,
3914        col: 0,
3915        kind: None,
3916    })?;
3917    Ok(Some((kind, 1 + dused + body.1)))
3918}
3919
3920/// Single (non-block) `ISOLATED`: one inner command or block; the
3921/// body rewrites nested `INHERIT_ENV` through the shared pass.
3922/// `None` on shape miss (missing/joint inner: generic fails it).
3923fn parse_isolated_single(
3924    toks: &[Tok],
3925    pos: usize,
3926    stmt: usize,
3927    ctx: &ParseCtx,
3928) -> Result<Option<(StepKind, usize)>, TokenError> {
3929    let Some(next) = toks.get(pos + 1) else {
3930        return Ok(None);
3931    };
3932    if next.joint {
3933        return Ok(None);
3934    }
3935    let (mut body, used) = if matches!(
3936        &next.kind,
3937        TokKind::Group {
3938            delim: GroupDelim::Brace,
3939            ..
3940        }
3941    ) && !is_template_brace(next)
3942    {
3943        let inner = match &next.kind {
3944            TokKind::Group { inner, .. } => inner.clone(),
3945            _ => unreachable!(),
3946        };
3947        (parse_body_steps(&inner, stmt, ctx, false)?, 1)
3948    } else {
3949        let (cmd, used) = parse_single_inner(
3950            toks,
3951            pos + 1,
3952            stmt,
3953            ctx,
3954            InnerRules {
3955                allow_await: true,
3956                allow_with_io: true,
3957            },
3958        )?;
3959        (
3960            vec![Step {
3961                guard: None,
3962                kind: cmd,
3963                scope_enter: 0,
3964                scope_exit: 0,
3965                line: 0,
3966                col: 0,
3967            }],
3968            used,
3969        )
3970    };
3971    crate::commands::rewrite_isolated_inherit(&mut body);
3972    Ok(Some((StepKind::Isolated { body }, 1 + used)))
3973}
3974
3975/// Single (non-block) `ASYNC`: one inner command or block (blocks
3976/// admit a joint brace, like `async_statement_block`'s `sep?`).
3977/// Top-level `WITH_IO` steps fail through the shared reject; the
3978/// `LET` path never scans (probed: it accepts). `None` on shape
3979/// miss (missing/joint-single inner: generic fails it).
3980fn parse_async_single(
3981    toks: &[Tok],
3982    pos: usize,
3983    stmt: usize,
3984    ctx: &ParseCtx,
3985) -> Result<Option<(StepKind, usize)>, TokenError> {
3986    let Some(next) = toks.get(pos + 1) else {
3987        return Ok(None);
3988    };
3989    // Block form admits a joint brace (`ASYNC{...}`, probed); the
3990    // single form needs its `sep`.
3991    if matches!(
3992        &next.kind,
3993        TokKind::Group {
3994            delim: GroupDelim::Brace,
3995            ..
3996        }
3997    ) && !is_template_brace(next)
3998    {
3999        let inner = match &next.kind {
4000            TokKind::Group { inner, .. } => inner.clone(),
4001            _ => unreachable!(),
4002        };
4003        let body = parse_body_steps(&inner, stmt, ctx, false)?;
4004        let span = lowering_ctx(stmt);
4005        crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| TokenError {
4006            stmt,
4007            msg: e.to_string(),
4008            line: 0,
4009            col: 0,
4010            kind: None,
4011        })?;
4012        let kind = StepKind::AsyncBlock { body };
4013        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
4014            stmt,
4015            msg: e.to_string(),
4016            line: 0,
4017            col: 0,
4018            kind: None,
4019        })?;
4020        return Ok(Some((kind, 2)));
4021    }
4022    if next.joint {
4023        return Ok(None);
4024    }
4025    let (cmd, used) = parse_single_inner(
4026        toks,
4027        pos + 1,
4028        stmt,
4029        ctx,
4030        InnerRules {
4031            allow_await: false,
4032            allow_with_io: false,
4033        },
4034    )?;
4035    let body = vec![Step {
4036        guard: None,
4037        kind: cmd,
4038        scope_enter: 0,
4039        scope_exit: 0,
4040        line: 0,
4041        col: 0,
4042    }];
4043    let span = lowering_ctx(stmt);
4044    crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| TokenError {
4045        stmt,
4046        msg: e.to_string(),
4047        line: 0,
4048        col: 0,
4049        kind: None,
4050    })?;
4051    let kind = StepKind::AsyncBlock { body };
4052    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
4053        stmt,
4054        msg: e.to_string(),
4055        line: 0,
4056        col: 0,
4057        kind: None,
4058    })?;
4059    Ok(Some((kind, 1 + used)))
4060}
4061
4062// ---- Block statements, directives, REMOTE ----
4063// `IF`/`FOR`/`WHILE`/`FUNC` parse their headers token-natively with
4064// miss-to-generic fallback (the grammar's committed `instruction`
4065// path); bodies lower recursively with pushed scopes. `TYPE` builds
4066// aliases through a maximal type-shape match; `IMPORT`/`EXPORT` are
4067// zero-step frame/table directives; `REMOTE` validates targets,
4068// bindings, bodies, and outer-call containment through the shared
4069// validators. Guard blocks fold guards with scope markers at top
4070// level and mirror the nested quirk formula in bodies. A whole-script
4071// post-pass runs the shared validations (prelude order, COPY
4072// placement, EXPORT membership).
4073
4074/// Uppercase identifier mirror (`func_ident`, `type_name`,
4075/// `import_module`): ASCII upper start, upper/digit/`_` rest.
4076fn is_upper_ident(w: &str) -> bool {
4077    !w.is_empty()
4078        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
4079        && w.chars()
4080            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
4081}
4082
4083/// Lowercase identifier mirror (`field_name`): ASCII lower start,
4084/// lower/digit/`_` rest.
4085fn is_lower_ident(w: &str) -> bool {
4086    !w.is_empty()
4087        && w.chars().next().is_some_and(|c| c.is_ascii_lowercase())
4088        && w.chars()
4089            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
4090}
4091
4092/// `$name` with gapless adjacency (atomic `dollar_ident`); `None` on
4093/// shape miss (the caller falls back to generic, which fails in
4094/// lowering like the grammar's committed `instruction`).
4095fn peek_dollar_var(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
4096    match (toks.get(pos), toks.get(pos + 1)) {
4097        (Some(dollar), Some(name))
4098            if matches!(&dollar.kind, TokKind::Punct('$'))
4099                && name.joint
4100                && matches!(&name.kind, TokKind::Word(w) if is_ident_word(w)) =>
4101        {
4102            match &name.kind {
4103                TokKind::Word(w) => Some((w.clone(), 2)),
4104                _ => unreachable!(),
4105            }
4106        }
4107        _ => None,
4108    }
4109}
4110
4111/// Skip statement-level newlines (multi-line `<...>` shapes ride
4112/// them into the body) before the next type token. Narrower than
4113/// `gap_nl` on purpose: comments keep failing here exactly like
4114/// single-line shapes, so only the separator moves.
4115fn skip_type_nl(toks: &[Tok], mut p: usize) -> usize {
4116    while matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Newline)) {
4117        p += 1;
4118    }
4119    p
4120}
4121
4122/// Maximal `type_tag` match over toks (non-atomic: gaps free
4123/// everywhere): atoms with `<>` args, `|` unions, `name?:` fields,
4124/// and one `= literal` default tail per field.
4125/// Returns the exclusive end index, or `None` on shape miss.
4126fn parse_type_shape(toks: &[Tok], pos: usize) -> Option<usize> {
4127    let mut p = parse_type_atom(toks, skip_type_nl(toks, pos))?;
4128    loop {
4129        let q = skip_type_nl(toks, p);
4130        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('|'))) {
4131            return Some(p);
4132        }
4133        p = parse_type_atom(toks, skip_type_nl(toks, q + 1))?;
4134    }
4135}
4136
4137fn parse_type_atom(toks: &[Tok], pos: usize) -> Option<usize> {
4138    let pos = skip_type_nl(toks, pos);
4139    match toks.get(pos).map(|t| &t.kind) {
4140        Some(TokKind::Word(w)) if is_upper_ident(w) => {}
4141        _ => return None,
4142    }
4143    let mut p = skip_type_nl(toks, pos + 1);
4144    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('<'))) {
4145        p = parse_type_args(toks, skip_type_nl(toks, p + 1))?;
4146        p = skip_type_nl(toks, p);
4147        if !matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('>'))) {
4148            return None;
4149        }
4150        p += 1;
4151    }
4152    Some(p)
4153}
4154
4155fn parse_type_args(toks: &[Tok], pos: usize) -> Option<usize> {
4156    let mut p = parse_type_field(toks, skip_type_nl(toks, pos))?;
4157    loop {
4158        let q = skip_type_nl(toks, p);
4159        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(','))) {
4160            return Some(p);
4161        }
4162        p = parse_type_field(toks, skip_type_nl(toks, q + 1))?;
4163    }
4164}
4165
4166fn parse_type_field(toks: &[Tok], pos: usize) -> Option<usize> {
4167    let mut p = skip_type_nl(toks, pos);
4168    // Optional `name?:` prefix (lowercase names only, like the
4169    // grammar's `field_name`).
4170    if let Some(TokKind::Word(w)) = toks.get(p).map(|t| &t.kind)
4171        && is_lower_ident(w)
4172    {
4173        let mut q = skip_type_nl(toks, p + 1);
4174        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('?'))) {
4175            q = skip_type_nl(toks, q + 1);
4176        }
4177        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4178            p = skip_type_nl(toks, q + 1);
4179        }
4180    }
4181    let mut p = parse_type_shape(toks, p)?;
4182    // Optional `= ...` default tail: consume to the next field
4183    // delimiter (`,`, `>`, `|` at angle depth zero), tracking `<>`
4184    // so nested shapes ride along. Any spacing, any tokens:
4185    // literals, `$vars`, `env:` reads, calls. The spelling parser
4186    // owns literal validation, so non-literals fail there naming
4187    // the alias instead of missing here as unknown-command noise.
4188    let q = skip_type_nl(toks, p);
4189    if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('=')))
4190        && !matches!(toks.get(q + 1).map(|t| &t.kind), Some(TokKind::Punct('=')))
4191    {
4192        let mut r = skip_type_nl(toks, q + 1);
4193        let mut depth = 0usize;
4194        loop {
4195            match toks.get(r).map(|t| &t.kind) {
4196                Some(TokKind::Punct('<')) => {
4197                    depth += 1;
4198                    r = skip_type_nl(toks, r + 1);
4199                }
4200                Some(TokKind::Punct('>')) => {
4201                    if depth == 0 {
4202                        break;
4203                    }
4204                    depth -= 1;
4205                    r = skip_type_nl(toks, r + 1);
4206                }
4207                Some(TokKind::Punct(',' | '|')) if depth == 0 => break,
4208                Some(_) => {
4209                    r += 1;
4210                }
4211                None => break,
4212            }
4213        }
4214        p = r;
4215    }
4216    Some(p)
4217}
4218
4219/// Single (non-block) `IF`: condition plus then-block with an
4220/// opportunistic `ELSE` chain (a malformed `ELSE` stays for the
4221/// element loop, which fails it in lowering exactly like the
4222/// grammar). `None` on shape miss (missing/joint-agnostic block or
4223/// unclassified bad condition: generic fails it); classified
4224/// expression failures (unknown/ambiguous callees) and inline-block
4225/// failures propagate (blocks lower here, so their errors surface
4226/// directly).
4227fn parse_if_at(
4228    toks: &[Tok],
4229    pos: usize,
4230    stmt: usize,
4231    ctx: &ParseCtx,
4232) -> Result<Option<(StepKind, usize)>, TokenError> {
4233    // Condition entry skips leading gap comments (`IF` uses `gap`).
4234    let mut lead = Cursor::expr(&toks[pos + 1..], stmt);
4235    lead.skip_gap();
4236    let mut cur = Cursor::expr(&toks[pos + 1 + lead.pos..], stmt);
4237    let cond = match parse_expr_checked(&mut cur, ctx) {
4238        Ok(expr) => expr,
4239        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4240        // Classified failures (unknown/ambiguous callees) name the
4241        // culprit instead of missing to the generic IF hint: the head
4242        // is unambiguously `IF`, so there is no alternative parse.
4243        Err(e) if e.kind.is_some() => return Err(e),
4244        Err(_) => return Ok(None),
4245    };
4246    let cond_end = pos + 1 + lead.pos + cur.pos;
4247    // Then-block: any gap (`gap` zero-width), never a template.
4248    let then_brace = match toks.get(cond_end) {
4249        Some(t)
4250            if matches!(
4251                &t.kind,
4252                TokKind::Group {
4253                    delim: GroupDelim::Brace,
4254                    ..
4255                }
4256            ) && !is_template_brace(t) =>
4257        {
4258            t
4259        }
4260        _ => return Ok(None),
4261    };
4262    let then_inner = match &then_brace.kind {
4263        TokKind::Group { inner, .. } => inner.clone(),
4264        _ => unreachable!(),
4265    };
4266    let then_body = parse_body_steps(&then_inner, stmt, ctx, false)?;
4267    let mut p = cond_end + 1;
4268    // Gap comments between the blocks and `ELSE` vanish (merge
4269    // junctions contribute newlines, crossed like `blank*`).
4270    {
4271        let mut gcur = Cursor::expr(&toks[p..], stmt);
4272        gcur.skip_gap_nl();
4273        p += gcur.pos;
4274    }
4275    let mut else_ifs = Vec::new();
4276    let mut else_body = None;
4277    loop {
4278        // `ELSE IF cond block`: any gaps (non-atomic chain).
4279        let is_else_if = matches!(
4280            toks.get(p).map(|t| &t.kind),
4281            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4282        ) && matches!(
4283            toks.get(p + 1).map(|t| &t.kind),
4284            Some(TokKind::Word(w)) if w == KEYWORD_IF
4285        );
4286        if is_else_if {
4287            let mut ecur = Cursor::expr(&toks[p + 2..], stmt);
4288            ecur.skip_gap();
4289            let econd = match parse_expr_checked(&mut ecur, ctx) {
4290                Ok(expr) => expr,
4291                Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4292                // Same classified-error rule as the `IF` head above:
4293                // an `ELSE IF` with a resolvable-but-unknown callee
4294                // names it instead of silently dropping the branch.
4295                Err(e) if e.kind.is_some() => return Err(e),
4296                Err(_) => break,
4297            };
4298            let ebrace = p + 2 + ecur.pos;
4299            let eblock_ok = matches!(
4300                toks.get(ebrace).map(|t| &t.kind),
4301                Some(TokKind::Group {
4302                    delim: GroupDelim::Brace,
4303                    ..
4304                })
4305            ) && toks.get(ebrace).is_some_and(|t| !is_template_brace(t));
4306            if !eblock_ok {
4307                break;
4308            }
4309            let einner = match &toks[ebrace].kind {
4310                TokKind::Group { inner, .. } => inner.clone(),
4311                _ => unreachable!(),
4312            };
4313            let ebody = parse_body_steps(&einner, stmt, ctx, false)?;
4314            else_ifs.push((Box::new(econd), ebody));
4315            p = ebrace + 1;
4316            // Gap comments before a further `ELSE` vanish too
4317            // (merge junctions contribute newlines).
4318            {
4319                let mut gcur = Cursor::expr(&toks[p..], stmt);
4320                gcur.skip_gap_nl();
4321                p += gcur.pos;
4322            }
4323            continue;
4324        }
4325        // `ELSE block`: same opportunism (a bare `ELSE` stays for
4326        // the loop, failing in lowering like the grammar).
4327        let is_else = matches!(
4328            toks.get(p).map(|t| &t.kind),
4329            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4330        ) && matches!(
4331            toks.get(p + 1).map(|t| &t.kind),
4332            Some(TokKind::Group {
4333                delim: GroupDelim::Brace,
4334                ..
4335            })
4336        ) && toks.get(p + 1).is_some_and(|t| !is_template_brace(t));
4337        if !is_else {
4338            break;
4339        }
4340        let einner = match &toks[p + 1].kind {
4341            TokKind::Group { inner, .. } => inner.clone(),
4342            _ => unreachable!(),
4343        };
4344        else_body = Some(parse_body_steps(&einner, stmt, ctx, false)?);
4345        p += 2;
4346        break;
4347    }
4348    let kind = StepKind::If {
4349        cond: Box::new(cond),
4350        then_body,
4351        else_ifs,
4352        else_body,
4353    };
4354    Ok(Some((kind, p - pos)))
4355}
4356
4357/// Parse one `CASE` value list: comma-separated expressions up to (not
4358/// including) the arm body brace. Groups are atomic tokens, so commas
4359/// inside calls, lists, and maps never split. Returns the values plus
4360/// the token count consumed past the `CASE` word.
4361fn parse_case_values(
4362    toks: &[Tok],
4363    stmt: usize,
4364    ctx: &ParseCtx,
4365) -> Result<(Vec<Expr>, usize), TokenError> {
4366    let mut values = Vec::new();
4367    let mut p = 0;
4368    loop {
4369        let mut gcur = Cursor::expr(&toks[p..], stmt);
4370        gcur.skip_gap_nl();
4371        let start = p + gcur.pos;
4372        let mut vcur = Cursor::expr(&toks[start..], stmt);
4373        let value = match parse_expr_checked(&mut vcur, ctx) {
4374            Ok(expr) => expr,
4375            Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4376            Err(e) => return Err(e),
4377        };
4378        values.push(value);
4379        p = start + vcur.pos;
4380        let mut gcur = Cursor::expr(&toks[p..], stmt);
4381        gcur.skip_gap_nl();
4382        p += gcur.pos;
4383        if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(','))) {
4384            p += 1;
4385            continue;
4386        }
4387        break;
4388    }
4389    Ok((values, p))
4390}
4391
4392/// Parsed `SWITCH` arms: one value list plus body per `CASE`, with
4393/// an optional trailing `DEFAULT` body.
4394type SwitchArms = (Vec<(Vec<Expr>, Vec<Step>)>, Option<Vec<Step>>);
4395
4396/// Parse the arms inside a `SWITCH` body brace: `CASE <values> { ... }`
4397/// arms plus an optional trailing `DEFAULT { ... }`. Hard errors once
4398/// committed (the `SWITCH` head is unambiguous): unknown words, empty
4399/// bodies, missing blocks, duplicate or non-trailing `DEFAULT`.
4400fn parse_switch_body(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<SwitchArms, TokenError> {
4401    let err = |msg: String| TokenError {
4402        stmt,
4403        line: 0,
4404        col: 0,
4405        msg,
4406        kind: None,
4407    };
4408    let mut cases: Vec<(Vec<Expr>, Vec<Step>)> = Vec::new();
4409    let mut default_body: Option<Vec<Step>> = None;
4410    let mut p = 0;
4411    loop {
4412        let mut gcur = Cursor::expr(&inner[p..], stmt);
4413        gcur.skip_gap_nl();
4414        p += gcur.pos;
4415        if p >= inner.len() {
4416            break;
4417        }
4418        let word = match &inner[p].kind {
4419            TokKind::Word(w) => w.clone(),
4420            _ => {
4421                return Err(err(
4422                    "SWITCH body must hold CASE or DEFAULT arms, e.g. `SWITCH $cmd { CASE \"a\" { ECHO yes } DEFAULT { ECHO no } }`".to_string(),
4423                ));
4424            }
4425        };
4426        if word == KEYWORD_CASE {
4427            if default_body.is_some() {
4428                return Err(err(
4429                    "SWITCH DEFAULT must be the last arm; no CASE may follow it".to_string(),
4430                ));
4431            }
4432            let (values, used) = parse_case_values(&inner[p + 1..], stmt, ctx)?;
4433            p += 1 + used;
4434            let mut bcur = Cursor::expr(&inner[p..], stmt);
4435            bcur.skip_gap_nl();
4436            p += bcur.pos;
4437            let arm_ok = matches!(
4438                inner.get(p).map(|t| &t.kind),
4439                Some(TokKind::Group {
4440                    delim: GroupDelim::Brace,
4441                    ..
4442                })
4443            ) && inner.get(p).is_some_and(|t| !is_template_brace(t));
4444            if !arm_ok {
4445                return Err(err(
4446                    "SWITCH CASE needs a braced block, e.g. `CASE \"a\", \"b\" { ECHO yes }`"
4447                        .to_string(),
4448                ));
4449            }
4450            let arm_inner = match &inner[p].kind {
4451                TokKind::Group { inner, .. } => inner.clone(),
4452                _ => unreachable!(),
4453            };
4454            let body = parse_body_steps(&arm_inner, stmt, ctx, false)?;
4455            cases.push((values, body));
4456            p += 1;
4457        } else if word == KEYWORD_DEFAULT {
4458            if default_body.is_some() {
4459                return Err(err("SWITCH allows only one DEFAULT arm".to_string()));
4460            }
4461            p += 1;
4462            let mut bcur = Cursor::expr(&inner[p..], stmt);
4463            bcur.skip_gap_nl();
4464            p += bcur.pos;
4465            let arm_ok = matches!(
4466                inner.get(p).map(|t| &t.kind),
4467                Some(TokKind::Group {
4468                    delim: GroupDelim::Brace,
4469                    ..
4470                })
4471            ) && inner.get(p).is_some_and(|t| !is_template_brace(t));
4472            if !arm_ok {
4473                return Err(err(
4474                    "SWITCH DEFAULT needs a braced block, e.g. `DEFAULT { ECHO fallback }`"
4475                        .to_string(),
4476                ));
4477            }
4478            let arm_inner = match &inner[p].kind {
4479                TokKind::Group { inner, .. } => inner.clone(),
4480                _ => unreachable!(),
4481            };
4482            default_body = Some(parse_body_steps(&arm_inner, stmt, ctx, false)?);
4483            p += 1;
4484        } else {
4485            return Err(err(
4486                "SWITCH body must hold CASE or DEFAULT arms, e.g. `SWITCH $cmd { CASE \"a\" { ECHO yes } DEFAULT { ECHO no } }`".to_string(),
4487            ));
4488        }
4489    }
4490    if cases.is_empty() && default_body.is_none() {
4491        return Err(err(
4492            "SWITCH needs at least one CASE or DEFAULT arm".to_string()
4493        ));
4494    }
4495    Ok((cases, default_body))
4496}
4497
4498/// `SWITCH [disc] { CASE v, ... { ... } ... [DEFAULT { ... }] }` or
4499/// bare `SWITCH { CASE <bool> { ... } ... }`. `None` on shape miss (no
4500/// outer brace: falls to generic, which fails it with the SWITCH hint);
4501/// classified expression failures propagate like `IF`, and arm errors
4502/// are hard (the head commits the shape).
4503fn parse_switch_at(
4504    toks: &[Tok],
4505    pos: usize,
4506    stmt: usize,
4507    ctx: &ParseCtx,
4508) -> Result<Option<(StepKind, usize)>, TokenError> {
4509    // Bare head: gaps skipped like the discriminant entry below; the
4510    // token then opens the body brace, so no discriminant is parsed
4511    // (every `CASE` carries its own condition).
4512    let mut gap = Cursor::expr(&toks[pos + 1..], stmt);
4513    gap.skip_gap();
4514    let brace_pos = pos + 1 + gap.pos;
4515    let bare_head = matches!(
4516        toks.get(brace_pos).map(|t| &t.kind),
4517        Some(TokKind::Group {
4518            delim: GroupDelim::Brace,
4519            ..
4520        })
4521    ) && toks.get(brace_pos).is_some_and(|t| !is_template_brace(t));
4522    let p: usize;
4523    let discriminant = if bare_head {
4524        p = brace_pos;
4525        None
4526    } else {
4527        // Discriminant entry reuses the skipped gaps above (`IF` uses
4528        // the same gap rule).
4529        let mut cur = Cursor::expr(&toks[brace_pos..], stmt);
4530        let disc = match parse_expr_checked(&mut cur, ctx) {
4531            Ok(expr) => expr,
4532            Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4533            // Same classified-error rule as the `IF` head above: the
4534            // head is unambiguous, so resolvable-but-unknown callees
4535            // name the culprit instead of the generic hint.
4536            Err(e) if e.kind.is_some() => return Err(e),
4537            Err(_) => return Ok(None),
4538        };
4539        p = brace_pos + cur.pos;
4540        Some(Box::new(disc))
4541    };
4542    let body_ok = matches!(
4543        toks.get(p).map(|t| &t.kind),
4544        Some(TokKind::Group {
4545            delim: GroupDelim::Brace,
4546            ..
4547        })
4548    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4549    if !body_ok {
4550        return Ok(None);
4551    }
4552    let inner = match &toks[p].kind {
4553        TokKind::Group { inner, .. } => inner.clone(),
4554        _ => unreachable!(),
4555    };
4556    let (cases, default_body) = parse_switch_body(&inner, stmt, ctx)?;
4557    let kind = StepKind::Switch {
4558        discriminant,
4559        cases,
4560        default_body,
4561    };
4562    Ok(Some((kind, p + 1 - pos)))
4563}
4564
4565/// Single (non-block) `FOR`: `$var[: TYPE] (, $var[: TYPE])? IN
4566/// expr` plus block. Header shapes miss to generic (a third variable,
4567/// a missing block, a bad name all fail in lowering like the
4568/// grammar); completed headers validate counts and key types loudly.
4569/// Expression failures from inline blocks propagate (blocks lower
4570/// here); other expression failures miss (generic fails them like a
4571/// committed `instruction` would).
4572fn parse_for_at(
4573    toks: &[Tok],
4574    pos: usize,
4575    stmt: usize,
4576    ctx: &ParseCtx,
4577) -> Result<Option<(StepKind, usize)>, TokenError> {
4578    let mut p = pos + 1;
4579    let mut idents = Vec::new();
4580    let mut types = Vec::new();
4581    // First `$var[: TYPE]` (gapless `$var`; gaps free elsewhere).
4582    let Some((var1, _)) = peek_dollar_var(toks, p) else {
4583        return Ok(None);
4584    };
4585    idents.push(var1);
4586    p += 2;
4587    let mut cur = Cursor::expr(&toks[p..], stmt);
4588    cur.skip_gap();
4589    p += cur.pos;
4590    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4591        p += 1;
4592        let mut tcur = Cursor::expr(&toks[p..], stmt);
4593        tcur.skip_gap();
4594        let tstart = p + tcur.pos;
4595        let Some(tend) = parse_type_shape(toks, tstart) else {
4596            return Ok(None);
4597        };
4598        // `render_type_region` canonicalizes (shared spelling).
4599        types.push(render_type_region(&toks[tstart..tend], stmt)?);
4600        p = tend;
4601    }
4602    // Optional `, $var2[: TYPE2]`.
4603    {
4604        let mut ccur = Cursor::expr(&toks[p..], stmt);
4605        ccur.skip_gap();
4606        if matches!(
4607            ccur.toks.get(ccur.pos).map(|t| &t.kind),
4608            Some(TokKind::Punct(','))
4609        ) {
4610            ccur.pos += 1;
4611            ccur.skip_gap();
4612            let base = p + ccur.pos;
4613            let Some((var2, _)) = peek_dollar_var(toks, base) else {
4614                return Ok(None);
4615            };
4616            idents.push(var2);
4617            let mut q = base + 2;
4618            let mut qcur = Cursor::expr(&toks[q..], stmt);
4619            qcur.skip_gap();
4620            q += qcur.pos;
4621            if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4622                q += 1;
4623                let mut tcur = Cursor::expr(&toks[q..], stmt);
4624                tcur.skip_gap();
4625                let tstart = q + tcur.pos;
4626                let Some(tend) = parse_type_shape(toks, tstart) else {
4627                    return Ok(None);
4628                };
4629                types.push(render_type_region(&toks[tstart..tend], stmt)?);
4630                q = tend;
4631            }
4632            p = q;
4633        }
4634    }
4635    // `IN expr block`.
4636    {
4637        let mut icur = Cursor::expr(&toks[p..], stmt);
4638        icur.skip_gap();
4639        if !matches!(
4640            icur.toks.get(icur.pos).map(|t| &t.kind),
4641            Some(TokKind::Word(w)) if w == KEYWORD_IN
4642        ) {
4643            return Ok(None);
4644        }
4645        icur.pos += 1;
4646        p += icur.pos;
4647    }
4648    let mut ecur = Cursor::expr(&toks[p..], stmt);
4649    ecur.skip_gap();
4650    let in_expr = match parse_expr_checked(&mut ecur, ctx) {
4651        Ok(expr) => expr,
4652        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4653        // Classified failures name the callee: `FOR ... IN` is
4654        // committed once the header matched this far.
4655        Err(e) if e.kind.is_some() => return Err(e),
4656        Err(_) => return Ok(None),
4657    };
4658    p += ecur.pos;
4659    let block_ok = matches!(
4660        toks.get(p).map(|t| &t.kind),
4661        Some(TokKind::Group {
4662            delim: GroupDelim::Brace,
4663            ..
4664        })
4665    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4666    if !block_ok {
4667        return Ok(None);
4668    }
4669    let inner = match &toks[p].kind {
4670        TokKind::Group { inner, .. } => inner.clone(),
4671        _ => unreachable!(),
4672    };
4673    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4674    p += 1;
4675    if idents.len() != types.len() {
4676        return Err(TokenError {
4677            stmt,
4678            msg: format!(
4679                "FOR requires explicit types: FOR $item: TYPE IN <expr> (got {} vars, {} types)",
4680                idents.len(),
4681                types.len()
4682            ),
4683            line: 0,
4684            col: 0,
4685            kind: Some(ParseErrorKind::Validation {
4686                command: KEYWORD_FOR.to_string(),
4687            }),
4688        });
4689    }
4690    let (key_var, key_type, var, var_type) = match idents.len() {
4691        1 => (
4692            None,
4693            None,
4694            idents.into_iter().next().unwrap_or_default(),
4695            types.into_iter().next().unwrap_or_default(),
4696        ),
4697        2 => {
4698            let mut iv = idents.into_iter();
4699            let mut tv = types.into_iter();
4700            (
4701                Some(iv.next().unwrap_or_default()),
4702                Some(tv.next().unwrap_or_default()),
4703                iv.next().unwrap_or_default(),
4704                tv.next().unwrap_or_default(),
4705            )
4706        }
4707        _ => {
4708            return Err(TokenError {
4709                stmt,
4710                msg: "FOR requires one or two variables".to_string(),
4711                line: 0,
4712                col: 0,
4713                kind: Some(ParseErrorKind::Validation {
4714                    command: KEYWORD_FOR.to_string(),
4715                }),
4716            });
4717        }
4718    };
4719    if let Some(kt) = &key_type
4720        && kt != crate::TypeTag::String.name()
4721        && kt != crate::TypeTag::Int.name()
4722    {
4723        return Err(TokenError {
4724            stmt,
4725            msg: format!("FOR key variable must be INT or STRING, got {kt}"),
4726            line: 0,
4727            col: 0,
4728            kind: Some(ParseErrorKind::Validation {
4729                command: KEYWORD_FOR.to_string(),
4730            }),
4731        });
4732    }
4733    let kind = StepKind::For {
4734        key_var,
4735        key_type,
4736        var,
4737        var_type,
4738        in_expr,
4739        body,
4740    };
4741    Ok(Some((kind, p - pos)))
4742}
4743
4744/// Single (non-block) `WHILE`: condition plus block. `None` on
4745/// shape miss (missing block: generic fails it); classified
4746/// expression failures and inline-block failures propagate, other
4747/// expression failures miss (generic fails them like a committed
4748/// `instruction` would).
4749/// No leading gap-skip: `WHILE` takes `sep`, so a joint follower
4750/// never reaches here with a valid shape... (misses fall through
4751/// the same way regardless).
4752fn parse_while_single(
4753    toks: &[Tok],
4754    pos: usize,
4755    stmt: usize,
4756    ctx: &ParseCtx,
4757) -> Result<Option<(StepKind, usize)>, TokenError> {
4758    let mut cur = Cursor::expr(&toks[pos + 1..], stmt);
4759    let cond = match parse_expr_checked(&mut cur, ctx) {
4760        Ok(expr) => expr,
4761        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4762        // Same rule as `IF`: the head is unambiguous, so classified
4763        // failures name the culprit instead of the generic hint.
4764        Err(e) if e.kind.is_some() => return Err(e),
4765        Err(_) => return Ok(None),
4766    };
4767    let brace = pos + 1 + cur.pos;
4768    let block_ok = matches!(
4769        toks.get(brace).map(|t| &t.kind),
4770        Some(TokKind::Group {
4771            delim: GroupDelim::Brace,
4772            ..
4773        })
4774    ) && toks.get(brace).is_some_and(|t| !is_template_brace(t));
4775    if !block_ok {
4776        return Ok(None);
4777    }
4778    let inner = match &toks[brace].kind {
4779        TokKind::Group { inner, .. } => inner.clone(),
4780        _ => unreachable!(),
4781    };
4782    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4783    let kind = StepKind::While {
4784        cond: Box::new(cond),
4785        body,
4786    };
4787    Ok(Some((kind, brace + 1 - pos)))
4788}
4789
4790/// Validated `FUNC` header shape: name, parameter list, return type,
4791/// and body block. Single owner for the header grammar, shared by
4792/// `parse_func_at` and `predeclare_forward_funcs` so the hoist set can
4793/// never admit what the real path rejects (or reject what it admits).
4794/// Returns the header plus tokens consumed; `None` on shape miss
4795/// (lowercase names, missing paren/colon/block all miss to generic,
4796/// probed). Content failures (bad params, missing return type, bad
4797/// trailing tokens) carry the bare diagnostic: `parse_func_at`
4798/// adorns it, pre-declaration drops it (silent skip, letting the main
4799/// pass own the error).
4800struct FuncHeader {
4801    name: String,
4802    params: Vec<(String, String, bool)>,
4803    return_type: String,
4804    block: usize,
4805}
4806
4807#[allow(clippy::too_many_lines)]
4808fn parse_func_header(
4809    toks: &[Tok],
4810    pos: usize,
4811    stmt: usize,
4812    keyword: &str,
4813) -> Result<Option<(FuncHeader, usize)>, String> {
4814    // Head word: `FUNC` (callers normalize `ASYNC FUNC` to `pos`
4815    // first, so the header shape stays prefix-free).
4816    if !matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC) {
4817        return Ok(None);
4818    }
4819    // Name: UPPERCASE ident (lowercase misses to generic, probed).
4820    let def_name = match toks.get(pos + 1).map(|t| &t.kind) {
4821        Some(TokKind::Word(w))
4822            if crate::resolve::check_func_ident(&lowering_ctx(stmt), w).is_ok() =>
4823        {
4824            w.clone()
4825        }
4826        _ => return Ok(None),
4827    };
4828    // Paren group at any gap (`gap` zero-width): params live inside
4829    // its inner tokens, parsed with `gap_nl` discipline (newlines ride
4830    // free like call args and generics, via the shared helper).
4831    let mut p = pos + 2;
4832    let paren_inner = match toks.get(p).map(|t| &t.kind) {
4833        Some(TokKind::Group {
4834            delim: GroupDelim::Paren,
4835            inner,
4836            ..
4837        }) => inner.clone(),
4838        _ => return Ok(None),
4839    };
4840    p += 1;
4841    let mut params = Vec::new();
4842    let mut seen_optional = false;
4843    {
4844        let mut pcur = Cursor::expr(&paren_inner, stmt);
4845        pcur.skip_gap_nl();
4846        if !pcur.done() {
4847            loop {
4848                let base = pcur.pos;
4849                let Some((pname, _)) = peek_dollar_var(&paren_inner, base) else {
4850                    return Err(format!(
4851                        "FUNC {def_name} params must be `$name: TYPE` separated by commas"
4852                    ));
4853                };
4854                pcur.pos = base + 2;
4855                pcur.skip_gap_nl();
4856                // Optional params carry `?` before the colon
4857                // (`$flag?: BOOL`); all params are otherwise required.
4858                let optional = pcur.eat_punct('?');
4859                pcur.skip_gap_nl();
4860                if !pcur.eat_punct(':') {
4861                    return Err(format!(
4862                        "FUNC {def_name} param `${pname}` needs `: TYPE` after the name"
4863                    ));
4864                }
4865                pcur.skip_gap_nl();
4866                let tstart = pcur.pos;
4867                let Some(tend) = parse_type_shape(&paren_inner, tstart) else {
4868                    let got = match paren_inner.get(tstart).map(|tok| &tok.kind) {
4869                        Some(TokKind::Word(word)) => format!("; got `{word}`"),
4870                        _ => String::new(),
4871                    };
4872                    return Err(format!(
4873                        "FUNC {def_name} param `${pname}` needs an uppercase type after `:` (e.g. STRING, INT, BOOL){got}"
4874                    ));
4875                };
4876                // Post-match the span holds words/puncts only, so the
4877                // shared renderer cannot fail; stay failed regardless.
4878                let ptype =
4879                    render_type_region(&paren_inner[tstart..tend], stmt).unwrap_or_default();
4880                if optional {
4881                    seen_optional = true;
4882                } else if seen_optional {
4883                    return Err(format!(
4884                        "FUNC {def_name} optional ? params must be trailing: `${pname}` follows an optional param"
4885                    ));
4886                }
4887                params.push((pname, ptype, optional));
4888                pcur.pos = tend;
4889                pcur.skip_gap_nl();
4890                if pcur.eat_punct(',') {
4891                    pcur.skip_gap_nl();
4892                    // Trailing comma misses (a param must follow).
4893                    if pcur.done() {
4894                        return Err(format!(
4895                            "FUNC {def_name} params must not end with a trailing comma"
4896                        ));
4897                    }
4898                    continue;
4899                }
4900                break;
4901            }
4902            // Trailing junk (including newlines) misses to generic.
4903            pcur.skip_gap_nl();
4904            if !pcur.done() {
4905                return Err(format!(
4906                    "FUNC {def_name} params must be `$name: TYPE` separated by commas"
4907                ));
4908            }
4909        }
4910    }
4911    // Mandatory return annotation: FUNC NAME(...): RET { ... }.
4912    // After paren group, require gap-optional colon then type shape.
4913    // Missing colon after matched name+parens is a hard parse error
4914    // (no legacy fallback). Non-block tails (neither colon nor brace)
4915    // miss to generic (probed FUNC FOO() ECHO hi).
4916    let is_colon = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')));
4917    if !is_colon {
4918        let is_brace = matches!(
4919            toks.get(p).map(|t| &t.kind),
4920            Some(TokKind::Group {
4921                delim: GroupDelim::Brace,
4922                ..
4923            })
4924        ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4925        if is_brace {
4926            return Err(format!(
4927                "{keyword} {def_name} requires a return type : TYPE (e.g. : VOID, : STRING)"
4928            ));
4929        }
4930        return Ok(None);
4931    }
4932    let Some(ret_end) = parse_type_shape(toks, p + 1) else {
4933        return Err(format!(
4934            "{keyword} {def_name} requires a return type : TYPE after ':'"
4935        ));
4936    };
4937    let return_type = render_type_region(&toks[p + 1..ret_end], stmt)
4938        .map_err(|_| format!("{keyword} {def_name} requires a return type : TYPE after ':'"))?;
4939    let return_type = crate::canonicalize_spelling(&return_type);
4940    p = ret_end;
4941    // Block at any gap (never a template); missing blocks miss to
4942    // generic (probed FUNC FOO() ECHO hi).
4943    let block_ok = matches!(
4944        toks.get(p).map(|t| &t.kind),
4945        Some(TokKind::Group {
4946            delim: GroupDelim::Brace,
4947            ..
4948        })
4949    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4950    if !block_ok {
4951        return Ok(None);
4952    }
4953    Ok(Some((
4954        FuncHeader {
4955            name: def_name,
4956            params,
4957            return_type,
4958            block: p,
4959        },
4960        p + 1 - pos,
4961    )))
4962}
4963
4964/// Single (non-block) `FUNC`: name, parenthesized params, block. The
4965/// shape parses purely first (misses fall to generic, declaring
4966/// nothing — the grammar only lowers matched pairs); then the name
4967/// declares in the enclosing scope before the body lowers (so
4968/// recursion resolves), and the body pushes a fresh scope.
4969/// Duplicates, reserved shadows, and parameter dupes fail loudly.
4970fn parse_func_at(
4971    toks: &[Tok],
4972    pos: usize,
4973    stmt: usize,
4974    ctx: &ParseCtx,
4975    is_async: bool,
4976) -> Result<Option<(StepKind, usize)>, TokenError> {
4977    let keyword = if is_async { "ASYNC FUNC" } else { KEYWORD_FUNC };
4978    let fail = |msg: String| TokenError {
4979        stmt,
4980        msg,
4981        line: 0,
4982        col: 0,
4983        kind: Some(ParseErrorKind::Validation {
4984            command: KEYWORD_FUNC.to_string(),
4985        }),
4986    };
4987    // Phase 1 (pure shape) through the single header owner:
4988    // adorn content errors with the `FUNC` / `ASYNC FUNC` keyword,
4989    // miss to generic on shape miss exactly as before.
4990    let Some((header, used)) = parse_func_header(toks, pos, stmt, keyword).map_err(fail)? else {
4991        return Ok(None);
4992    };
4993    let FuncHeader {
4994        name: def_name,
4995        params,
4996        return_type,
4997        block: p,
4998    } = header;
4999    // Phase 2 (effects): reserved shadows and same-scope duplicates
5000    // fail at the definition line, verbatim.
5001    if ctx.reserved.contains(&def_name) || ctx.modules.reserved_base_names().contains(&def_name) {
5002        return Err(fail(format!(
5003            "FUNC {def_name} cannot shadow reserved function `{def_name}`"
5004        )));
5005    }
5006    if !ctx.declare_func(&def_name) {
5007        return Err(fail(format!(
5008            "duplicate function `{def_name}` in same scope"
5009        )));
5010    }
5011    let mut seen = HashSet::new();
5012    for (pname, _, _) in &params {
5013        if !seen.insert(pname.clone()) {
5014            return Err(fail(format!(
5015                "FUNC {def_name} declares duplicate parameter ${pname}"
5016            )));
5017        }
5018    }
5019    let inner = match &toks[p].kind {
5020        TokKind::Group { inner, .. } => inner.clone(),
5021        _ => unreachable!(),
5022    };
5023    let body = parse_body_steps(&inner, stmt, ctx, false)?;
5024    let kind = StepKind::FuncDef {
5025        name: def_name,
5026        params,
5027        return_type,
5028        is_async,
5029        body,
5030        docs: None,
5031    };
5032    Ok(Some((kind, used)))
5033}
5034
5035/// `REMOTE` header bindings `[$var, env:KEY]` over a bracket
5036/// group's inner tokens: comma-separated, newlines and comments free
5037/// like `gap_nl`. `$`+name and `env`+`:`+key all ride gapless (the
5038/// enclosing rule is compound-atomic). Empty lists parse (probed);
5039/// anything else misses the shape (`None`: generic fails it like
5040/// the grammar's dropped optional).
5041#[allow(clippy::type_complexity)]
5042fn parse_remote_bindings(
5043    inner: &[Tok],
5044    stmt: usize,
5045) -> Result<Option<(Vec<String>, Vec<String>)>, TokenError> {
5046    let _ = stmt;
5047    let mut parts: Vec<&[Tok]> = Vec::new();
5048    let mut start = 0;
5049    for (i, tok) in inner.iter().enumerate() {
5050        if matches!(&tok.kind, TokKind::Punct(',')) {
5051            parts.push(&inner[start..i]);
5052            start = i + 1;
5053        }
5054    }
5055    parts.push(&inner[start..]);
5056    // An empty list (`[]`, whitespace/comment-only) holds no bindings.
5057    if parts.len() == 1
5058        && parts[0]
5059            .iter()
5060            .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
5061    {
5062        return Ok(Some((Vec::new(), Vec::new())));
5063    }
5064    let mut vars = Vec::new();
5065    let mut env = Vec::new();
5066    for part in parts {
5067        // Edges admit gaps, newlines, and comments, like `gap_nl`.
5068        let mut part = part;
5069        while matches!(
5070            part.first().map(|t| &t.kind),
5071            Some(TokKind::Newline | TokKind::Comment(_))
5072        ) {
5073            part = &part[1..];
5074        }
5075        while matches!(
5076            part.last().map(|t| &t.kind),
5077            Some(TokKind::Newline | TokKind::Comment(_))
5078        ) {
5079            part = &part[..part.len() - 1];
5080        }
5081        // `$var`: gapless `$` + ident.
5082        if matches!(part.first().map(|t| &t.kind), Some(TokKind::Punct('$'))) && part.len() == 2 {
5083            if part[1].joint
5084                && let TokKind::Word(w) = &part[1].kind
5085                && is_ident_word(w)
5086            {
5087                vars.push(w.clone());
5088                continue;
5089            }
5090            return Ok(None);
5091        }
5092        // `env:KEY`: gapless triple with an uppercase key.
5093        if part.len() == 3
5094            && matches!(&part[0].kind, TokKind::Word(w) if w == "env")
5095            && matches!(&part[1].kind, TokKind::Punct(':'))
5096            && part[1].joint
5097            && part[2].joint
5098        {
5099            if let TokKind::Word(k) = &part[2].kind
5100                && is_env_key(k)
5101            {
5102                env.push(k.clone());
5103                continue;
5104            }
5105            return Ok(None);
5106        }
5107        return Ok(None);
5108    }
5109    Ok(Some((vars, env)))
5110}
5111
5112/// `IMPORT` statement at `pos` (#115): module form (`IMPORT MOD`,
5113/// `IMPORT [A, B]`), file form (`IMPORT "p" AS A`,
5114/// `IMPORT ["p" AS A]`), mixed/multi forms
5115/// (`IMPORT [STD, "p" AS A, "q" AS B]`, multi-line included), and
5116/// selective harvests (`IMPORT [[F, G FROM "p" (AS A)?]]`).
5117/// Returns module names plus `ImportFile`/`ImportFuncs` steps in source
5118/// order, plus tokens consumed (relative to `pos`), or `None` on shape
5119/// miss (generic lowering fails it like the grammar). Validation is
5120/// hard: unknown modules, bad names, collisions, templates, and remote
5121/// URLs fail here, and validated entries register immediately
5122/// (modules, aliases, and bare harvest names share the innermost
5123/// frames).
5124type ImportEntries = (Vec<String>, Vec<StepKind>);
5125
5126fn parse_import_statement(
5127    toks: &[Tok],
5128    pos: usize,
5129    stmt: usize,
5130    ctx: &ParseCtx,
5131) -> Result<Option<(ImportEntries, usize)>, TokenError> {
5132    let fail = |msg: String| TokenError {
5133        stmt,
5134        msg,
5135        line: 0,
5136        col: 0,
5137        kind: Some(ParseErrorKind::Validation {
5138            command: KEYWORD_IMPORT.to_string(),
5139        }),
5140    };
5141    let next = match toks.get(pos + 1) {
5142        // `sep` after `IMPORT`: joint followers miss.
5143        Some(t) if !t.joint => t,
5144        _ => return Ok(None),
5145    };
5146    // Parse entries first, validate in source order after.
5147    enum RawEntry {
5148        Module(String),
5149        File {
5150            path: String,
5151            alias: String,
5152        },
5153        From {
5154            func_names: Vec<String>,
5155            type_names: Vec<String>,
5156            path: String,
5157            alias: Option<String>,
5158        },
5159    }
5160    let mut raw: Vec<RawEntry> = Vec::new();
5161    let used;
5162    if matches!(
5163        &next.kind,
5164        TokKind::Group {
5165            delim: GroupDelim::Brace,
5166            ..
5167        }
5168    ) {
5169        return Ok(None);
5170    }
5171    if let TokKind::Group {
5172        delim: GroupDelim::Bracket,
5173        inner,
5174        ..
5175    } = &next.kind
5176    {
5177        // Comma-separated entries, `ws` gaps (newlines ok inside and
5178        // around entries, comments MISS — `ws` admits neither).
5179        // Single-file multi-name harvests skip the split: in
5180        // `[TYPE A, TYPE B FROM "f"]` the first comma-part (`[TYPE A]`)
5181        // carries no FROM and is invalid alone, so the whole bracket
5182        // is one harvest (see `whole_file_harvest`).
5183        // Bare-multi hint: `[FOO, BAR FROM "f"]` reads FOO as a
5184        // module for back-compat (bare words stay modules in single
5185        // brackets). If that word is not a known module but a harvest
5186        // follows, fail fast naming the two valid spellings instead
5187        // of the misleading unknown-module error.
5188        let whole = whole_file_harvest(inner);
5189        if whole.is_none()
5190            && let Some(word) = single_bare_first_part(inner)
5191            && !ctx.modules.modules.contains_key(word)
5192            && has_top_level_from_after_comma(inner)
5193        {
5194            return Err(fail(format!(
5195                "unknown module `{word}`; to harvest multiple names qualify each kind (`IMPORT [FUNC FOO, FUNC BAR FROM \"f\"]`)"
5196            )));
5197        }
5198        let mut parts: Vec<&[Tok]> = Vec::new();
5199        if whole.is_some() {
5200            parts.push(inner);
5201        } else {
5202            let mut start = 0;
5203            for (i, tok) in inner.iter().enumerate() {
5204                if matches!(&tok.kind, TokKind::Punct(',')) {
5205                    parts.push(&inner[start..i]);
5206                    start = i + 1;
5207                }
5208            }
5209            parts.push(&inner[start..]);
5210        }
5211        for part in parts {
5212            let dense: Vec<&Tok> = part
5213                .iter()
5214                .filter(|t| !matches!(&t.kind, TokKind::Newline))
5215                .collect();
5216            // `[[F, G FROM "path" (AS ALIAS)?]]`: selective function
5217            // harvest. Anything else bracketed here misses.
5218            if let [bracket] = dense.as_slice()
5219                && let TokKind::Group {
5220                    delim: GroupDelim::Bracket,
5221                    inner,
5222                    ..
5223                } = &bracket.kind
5224            {
5225                let Some(HarvestImport {
5226                    func_names,
5227                    type_names,
5228                    path,
5229                    alias,
5230                }) = parse_from_entry(inner)
5231                else {
5232                    return Ok(None);
5233                };
5234                raw.push(RawEntry::From {
5235                    func_names,
5236                    type_names,
5237                    path,
5238                    alias,
5239                });
5240                continue;
5241            }
5242            // `[F FROM "path" (AS ALIAS)?]`: single harvest without
5243            // inner brackets. The `FROM` keyword is the discriminant
5244            // (module and file parts never contain a top-level one);
5245            // multi-name harvests keep `[[F, G FROM ...]]` so the comma
5246            // stays grouped inside its own scope.
5247            if dense.len() >= 3 {
5248                let owned: Vec<Tok> = dense.iter().map(|t| (*t).clone()).collect();
5249                if let Some(HarvestImport {
5250                    func_names,
5251                    type_names,
5252                    path,
5253                    alias,
5254                }) = parse_from_entry(&owned)
5255                {
5256                    raw.push(RawEntry::From {
5257                        func_names,
5258                        type_names,
5259                        path,
5260                        alias,
5261                    });
5262                    continue;
5263                }
5264            }
5265            match dense.as_slice() {
5266                [tok] => match &tok.kind {
5267                    TokKind::Word(w) if is_upper_ident(w) => {
5268                        raw.push(RawEntry::Module(w.clone()));
5269                    }
5270                    _ => return Ok(None),
5271                },
5272                [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5273                    let (
5274                        TokKind::Str { text, .. },
5275                        TokKind::Word(as_word),
5276                        TokKind::Word(alias_word),
5277                    ) = (&path_tok.kind, &as_tok.kind, &alias_tok.kind)
5278                    else {
5279                        return Ok(None);
5280                    };
5281                    if as_word != KEYWORD_AS {
5282                        return Ok(None);
5283                    }
5284                    raw.push(RawEntry::File {
5285                        path: text.clone(),
5286                        alias: alias_word.clone(),
5287                    });
5288                }
5289                _ => return Ok(None),
5290            }
5291        }
5292        if raw.is_empty() {
5293            return Ok(None);
5294        }
5295        used = 2;
5296    } else if let TokKind::Word(w) = &next.kind {
5297        // Bare `IMPORT MOD` (single module, probed).
5298        if !is_upper_ident(w) {
5299            return Ok(None);
5300        }
5301        raw.push(RawEntry::Module(w.clone()));
5302        used = 2;
5303    } else if let TokKind::Str { text, .. } = &next.kind {
5304        // Bare `IMPORT "path" AS ALIAS`.
5305        let (Some(as_tok), Some(alias_tok)) = (toks.get(pos + 2), toks.get(pos + 3)) else {
5306            return Ok(None);
5307        };
5308        if as_tok.joint || alias_tok.joint {
5309            return Ok(None);
5310        }
5311        let (TokKind::Word(as_word), TokKind::Word(alias_word)) = (&as_tok.kind, &alias_tok.kind)
5312        else {
5313            return Ok(None);
5314        };
5315        if as_word != KEYWORD_AS {
5316            return Ok(None);
5317        }
5318        raw.push(RawEntry::File {
5319            path: text.clone(),
5320            alias: alias_word.clone(),
5321        });
5322        used = 4;
5323    } else {
5324        return Ok(None);
5325    }
5326    // Validate in source order: unknown modules fail with the exact
5327    // backend message (sorted known list); file and harvest entries
5328    // validate hard (bad names, collisions, templates, remote URLs).
5329    let mut modules = Vec::new();
5330    let mut steps = Vec::new();
5331    for entry in raw {
5332        match entry {
5333            RawEntry::Module(module) => {
5334                if !ctx.modules.modules.contains_key(&module) {
5335                    let mut known: Vec<String> = ctx.modules.modules.keys().cloned().collect();
5336                    known.sort();
5337                    return Err(fail(format!(
5338                        "unknown module `{module}`; known modules: {}",
5339                        known.join(", ")
5340                    )));
5341                }
5342                ctx.import_into_frame(std::slice::from_ref(&module));
5343                modules.push(module);
5344            }
5345            RawEntry::File { path, alias } => {
5346                let (path, alias) = validate_file_import(&path, &alias, ctx).map_err(fail)?;
5347                steps.push(StepKind::ImportFile { path, alias });
5348            }
5349            RawEntry::From {
5350                func_names,
5351                type_names,
5352                path,
5353                alias,
5354            } => {
5355                let HarvestImport {
5356                    func_names,
5357                    type_names,
5358                    path,
5359                    alias,
5360                } = validate_from_import(&func_names, &type_names, &path, alias.as_deref(), ctx)
5361                    .map_err(fail)?;
5362                steps.push(StepKind::ImportFuncs {
5363                    path,
5364                    alias,
5365                    func_names,
5366                    type_names,
5367                });
5368            }
5369        }
5370    }
5371    Ok(Some(((modules, steps), used)))
5372}
5373
5374/// Single file import for value positions (#115): exactly one
5375/// `"path" AS ALIAS` entry and no modules. Anything else shaped like an
5376/// import is a hard error naming the restriction; shape misses return
5377/// `None` for the generic path.
5378fn parse_single_file_import(
5379    toks: &[Tok],
5380    pos: usize,
5381    stmt: usize,
5382    ctx: &ParseCtx,
5383) -> Result<Option<(String, String, usize)>, TokenError> {
5384    let Some(((modules, mut kinds), used)) = parse_import_statement(toks, pos, stmt, ctx)? else {
5385        return Ok(None);
5386    };
5387    if !modules.is_empty() || !matches!(kinds.as_slice(), [StepKind::ImportFile { .. }]) {
5388        return Err(TokenError {
5389            stmt,
5390            msg: if !modules.is_empty()
5391                || kinds
5392                    .iter()
5393                    .any(|k| matches!(k, StepKind::ImportFuncs { .. }))
5394            {
5395                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>]); modules and function harvests stay at statement level".to_string()
5396            } else {
5397                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>])"
5398                    .to_string()
5399            },
5400            line: 0,
5401            col: 0,
5402            kind: Some(ParseErrorKind::Validation {
5403                command: KEYWORD_IMPORT.to_string(),
5404            }),
5405        });
5406    }
5407    let Some(StepKind::ImportFile { path, alias }) = kinds.pop() else {
5408        unreachable!("length and variant checked above")
5409    };
5410    Ok(Some((path, alias, used)))
5411}
5412
5413/// One `EXPORT` name: an uppercase word with an optional joint
5414/// `::UPPER` tail. Returns the name and tokens consumed, or `None`
5415/// on shape miss.
5416fn parse_export_name(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
5417    let head = match toks.get(pos).map(|t| &t.kind) {
5418        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
5419        _ => return None,
5420    };
5421    let mut name = head;
5422    let mut used = 1;
5423    // Greedy-prefix `::tail` (atomic, like the grammar): a valid
5424    // tail joins, an invalid one stays trailing (failing downstream
5425    // exactly like the grammar's committed prefix).
5426    if matches!(
5427        toks.get(pos + 1).map(|t| &t.kind),
5428        Some(TokKind::Punct(':'))
5429    ) && toks.get(pos + 1).is_some_and(|t| t.joint)
5430        && matches!(
5431            toks.get(pos + 2).map(|t| &t.kind),
5432            Some(TokKind::Punct(':'))
5433        )
5434        && toks.get(pos + 2).is_some_and(|t| t.joint)
5435        && let Some(TokKind::Word(tail)) = toks.get(pos + 3).map(|t| &t.kind)
5436        && toks[pos + 3].joint
5437        && is_upper_ident(tail)
5438    {
5439        name.push_str(MODULE_SEPARATOR);
5440        name.push_str(tail);
5441        used = 4;
5442    }
5443    Some((name, used))
5444}
5445
5446/// One selective harvest (`[[F, G FROM "path" (AS ALIAS)?]]`): the
5447/// wanted function and type names plus the path and optional alias.
5448/// Bare names are functions; `TYPE`/`FUNC` prefixes select the kind
5449/// explicitly (`[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`).
5450struct HarvestImport {
5451    func_names: Vec<String>,
5452    type_names: Vec<String>,
5453    path: String,
5454    alias: Option<String>,
5455}
5456
5457/// One `[[F, G FROM "path" (AS ALIAS)?]]` entry: selective function
5458/// harvest with optional `TYPE`/`FUNC` qualifiers per name:
5459/// `[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`
5460/// (bare stays func for back-compat).
5461/// Returns the harvest, or `None` on shape miss (generic lowering fails
5462/// it). Name case is validated hard by the caller, like file aliases.
5463fn parse_from_entry(inner: &[Tok]) -> Option<HarvestImport> {
5464    let dense: Vec<&Tok> = inner
5465        .iter()
5466        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5467        .collect();
5468    let from = dense
5469        .iter()
5470        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5471    if from == 0 {
5472        return None;
5473    }
5474    // Names: comma-separated entries, each `NAME` (func) or
5475    // `TYPE NAME` / `FUNC NAME` (explicit kind for clarity).
5476    let mut func_names = Vec::new();
5477    let mut type_names = Vec::new();
5478    let mut start = 0;
5479    let head = &dense[..from];
5480    // Local helper: classify one comma-separated part.
5481    fn classify_part(part: &[&Tok]) -> Option<(bool, String)> {
5482        match part {
5483            [tok] => {
5484                let TokKind::Word(w) = &tok.kind else {
5485                    return None;
5486                };
5487                Some((false, w.clone()))
5488            }
5489            // `TYPE NAME` / `FUNC NAME`: the name must be `sep` (gapped
5490            // from the kind); the kind may be joint to a preceding `[`
5491            // or `,` (no space required there), so only the name's joint
5492            // flag matters.
5493            [kind_tok, name_tok] if !name_tok.joint => {
5494                let (TokKind::Word(kind), TokKind::Word(name)) = (&kind_tok.kind, &name_tok.kind)
5495                else {
5496                    return None;
5497                };
5498                if kind == KEYWORD_TYPE {
5499                    Some((true, name.clone()))
5500                } else if kind == KEYWORD_FUNC {
5501                    Some((false, name.clone()))
5502                } else {
5503                    None
5504                }
5505            }
5506            _ => None,
5507        }
5508    }
5509    for (i, tok) in head.iter().enumerate() {
5510        if matches!(&tok.kind, TokKind::Punct(',')) {
5511            let part = &head[start..i];
5512            let (is_type, name) = classify_part(part)?;
5513            if is_type {
5514                type_names.push(name);
5515            } else {
5516                func_names.push(name);
5517            }
5518            start = i + 1;
5519        }
5520    }
5521    let part = &head[start..];
5522    let (is_type, name) = classify_part(part)?;
5523    if is_type {
5524        type_names.push(name);
5525    } else {
5526        func_names.push(name);
5527    }
5528    // Tail: `"path"` or bare `MODULE` with an optional gapped `AS ALIAS`.
5529    // Quoted is a file path (module fallback only when no file matches);
5530    // bare is a host module (no file probe ambiguity).
5531    let tail = &dense[from + 1..];
5532    let path_text = |tok: &Tok| match &tok.kind {
5533        TokKind::Str { text, .. } => Some(text.clone()),
5534        TokKind::Word(w) if is_upper_ident(w) => Some(w.clone()),
5535        _ => None,
5536    };
5537    match tail {
5538        [path_tok] => {
5539            let text = path_text(path_tok)?;
5540            Some(HarvestImport {
5541                func_names,
5542                type_names,
5543                path: text,
5544                alias: None,
5545            })
5546        }
5547        [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5548            let text = path_text(path_tok)?;
5549            let (TokKind::Word(as_word), TokKind::Word(alias_word)) =
5550                (&as_tok.kind, &alias_tok.kind)
5551            else {
5552                return None;
5553            };
5554            if as_word != KEYWORD_AS {
5555                return None;
5556            }
5557            Some(HarvestImport {
5558                func_names,
5559                type_names,
5560                path: text,
5561                alias: Some(alias_word.clone()),
5562            })
5563        }
5564        _ => None,
5565    }
5566}
5567
5568/// First comma-part of a bracket when it is exactly one bare
5569/// uppercase word: the back-compat module reading. Anything else
5570/// (prefixed names, groups, multiple words) is not a bare module.
5571fn single_bare_first_part(inner: &[Tok]) -> Option<&str> {
5572    let end = inner
5573        .iter()
5574        .position(|t| matches!(&t.kind, TokKind::Punct(',')))
5575        .unwrap_or(inner.len());
5576    let mut words = inner[..end]
5577        .iter()
5578        .filter(|t| !matches!(&t.kind, TokKind::Newline));
5579    match (words.next(), words.next()) {
5580        (Some(tok), None) => match &tok.kind {
5581            TokKind::Word(w) if is_upper_ident(w) => Some(w.as_str()),
5582            _ => None,
5583        },
5584        _ => None,
5585    }
5586}
5587
5588/// Whether a top-level `FROM` follows the first top-level comma:
5589/// distinguishes a module-plus-harvest entry (`[STD, T FROM "f"]`)
5590/// from a bare word the author meant as a harvest name.
5591fn has_top_level_from_after_comma(inner: &[Tok]) -> bool {
5592    let mut seen_comma = false;
5593    for tok in inner {
5594        match &tok.kind {
5595            TokKind::Punct(',') => seen_comma = true,
5596            TokKind::Word(w) if seen_comma && w == KEYWORD_FROM => return true,
5597            _ => {}
5598        }
5599    }
5600    false
5601}
5602
5603/// Whole-bracket single-file harvest (`[TYPE A, TYPE B FROM "f"]`):
5604/// the comma-split would orphan `[TYPE A]` (no FROM, invalid alone),
5605/// so the entire bracket parses as one harvest. Only explicitly
5606/// prefixed names qualify: a bare word keeps its legacy module
5607/// reading, so `[STD, TYPE T FROM "f"]` still splits into a module
5608/// plus a harvest instead of harvesting STD as a function.
5609fn whole_file_harvest(inner: &[Tok]) -> Option<HarvestImport> {
5610    let owned: Vec<Tok> = inner.to_vec();
5611    let harvest = parse_from_entry(&owned)?;
5612    let dense: Vec<&Tok> = inner
5613        .iter()
5614        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5615        .collect();
5616    let from = dense
5617        .iter()
5618        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5619    let mut start = 0;
5620    for (i, tok) in dense[..from].iter().enumerate() {
5621        if matches!(&tok.kind, TokKind::Punct(',')) {
5622            if !is_prefixed_name(&dense[start..i]) {
5623                return None;
5624            }
5625            start = i + 1;
5626        }
5627    }
5628    if !is_prefixed_name(&dense[start..from]) {
5629        return None;
5630    }
5631    Some(harvest)
5632}
5633
5634/// One explicitly prefixed name (`TYPE NAME` / `FUNC NAME`): the name
5635/// stays gapped from its kind; the kind may joint to `[` or `,`.
5636fn is_prefixed_name(part: &[&Tok]) -> bool {
5637    match part {
5638        [kind_tok, name_tok] if !name_tok.joint => {
5639            matches!(
5640                (&kind_tok.kind, &name_tok.kind),
5641                (
5642                    TokKind::Word(kind),
5643                    TokKind::Word(_)
5644                ) if kind == KEYWORD_TYPE || kind == KEYWORD_FUNC
5645            )
5646        }
5647        _ => false,
5648    }
5649}
5650
5651/// Validate an `IMPORT` alias: hard errors (never shape misses) plus
5652/// registration into the innermost import frame.
5653fn validate_import_alias(alias: &str, ctx: &ParseCtx) -> Result<String, String> {
5654    if !is_upper_ident(alias) {
5655        return Err(format!(
5656            "IMPORT alias must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{alias}`"
5657        ));
5658    }
5659    if ctx.modules.modules.contains_key(alias) {
5660        return Err(format!(
5661            "IMPORT alias `{alias}` collides with module `{alias}`"
5662        ));
5663    }
5664    let (_, imports) = ctx.visible_snapshot();
5665    if imports.iter().any(|i| i == alias) {
5666        return Err(format!("duplicate IMPORT alias `{alias}`"));
5667    }
5668    ctx.import_into_frame(std::slice::from_ref(&alias.to_string()));
5669    Ok(alias.to_string())
5670}
5671
5672/// Validate an `IMPORT` path: hard errors, never shape misses.
5673fn validate_import_path(path: &str) -> Result<String, String> {
5674    if path.is_empty() {
5675        return Err("IMPORT path must not be empty".to_string());
5676    }
5677    if path.contains("{{") {
5678        return Err("IMPORT path must be a literal string (no {{ }} templates)".to_string());
5679    }
5680    if path.contains("://") {
5681        return Err(
5682            "remote imports are deferred to #270 (net: Run scripts from a remote URL)".to_string(),
5683        );
5684    }
5685    Ok(path.to_string())
5686}
5687
5688/// Validate a file-import path/alias pair: hard errors (never shape
5689/// misses) plus alias registration into the innermost import frame.
5690fn validate_file_import(
5691    path: &str,
5692    alias: &str,
5693    ctx: &ParseCtx,
5694) -> Result<(String, String), String> {
5695    let alias = validate_import_alias(alias, ctx)?;
5696    let path = validate_import_path(path)?;
5697    Ok((path, alias))
5698}
5699
5700/// Validate a `[[F, G FROM "path" (AS ALIAS)?]]` entry: hard errors
5701/// (never shape misses). Bare func names declare into the innermost
5702/// `FUNC` frame so calls resolve statically; the runtime defines them
5703/// (and fails unknown names there). Type names need no func-frame
5704/// declaration (types resolve through the global type directory);
5705/// the runtime validates them against the file's `EXPORT TYPE` list.
5706/// An alias registers like a file import.
5707fn validate_from_import(
5708    func_names: &[String],
5709    type_names: &[String],
5710    path: &str,
5711    alias: Option<&str>,
5712    ctx: &ParseCtx,
5713) -> Result<HarvestImport, String> {
5714    let path = validate_import_path(path)?;
5715    let mut out_func_names = Vec::with_capacity(func_names.len());
5716    for name in func_names {
5717        if !is_upper_ident(name) {
5718            return Err(format!(
5719                "IMPORT function names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
5720            ));
5721        }
5722        if ctx.reserved.contains(name) {
5723            return Err(format!("cannot shadow reserved function `{name}`"));
5724        }
5725        out_func_names.push(name.clone());
5726    }
5727    let mut out_type_names = Vec::with_capacity(type_names.len());
5728    for name in type_names {
5729        if !is_upper_ident(name) {
5730            return Err(format!(
5731                "IMPORT type names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
5732            ));
5733        }
5734        out_type_names.push(name.clone());
5735    }
5736    if out_func_names.is_empty() && out_type_names.is_empty() {
5737        return Err("IMPORT harvest needs at least one function or type name".to_string());
5738    }
5739    if let Some(alias) = alias {
5740        let alias = validate_import_alias(alias, ctx)?;
5741        Ok(HarvestImport {
5742            func_names: out_func_names,
5743            type_names: out_type_names,
5744            path,
5745            alias: Some(alias),
5746        })
5747    } else {
5748        for name in &out_func_names {
5749            if !ctx.declare_func(name) {
5750                return Err(format!("duplicate function `{name}` in same scope"));
5751            }
5752        }
5753        // Type harvests without alias land bare in the global type
5754        // directory: duplicates across files fail at import time
5755        // (different targets), not at parse time (targets need IO).
5756        Ok(HarvestImport {
5757            func_names: out_func_names,
5758            type_names: out_type_names,
5759            path,
5760            alias: None,
5761        })
5762    }
5763}
5764
5765/// One `EXPORT ...` name list: function names plus type names in
5766/// source order. Bare names are functions; explicit `TYPE`/`FUNC`
5767/// prefixes select the kind.
5768struct ExportNames {
5769    func_names: Vec<String>,
5770    type_names: Vec<String>,
5771}
5772
5773/// `EXPORT ...` names at `pos`: bracket list (strict, `ws` gaps:
5774/// newlines ok, comments miss) or a bare greedy-prefix name.
5775/// Supports explicit `TYPE`/`FUNC` qualifiers for clarity:
5776/// `EXPORT TYPE FOO`, `EXPORT TYPE [A, B]`, `EXPORT FUNC FOO`,
5777/// plus mixed `EXPORT [TYPE A, FUNC B, C]` (bare stays func).
5778/// Returns the name lists plus tokens consumed, or `None` on shape
5779/// miss (generic fails it in lowering like the grammar). Recording and
5780/// duplicate checks live with the caller (they need the guard and
5781/// level context).
5782fn parse_export_at(toks: &[Tok], pos: usize) -> Option<(ExportNames, usize)> {
5783    let next = match toks.get(pos + 1) {
5784        // `sep` after `EXPORT`: joint followers miss.
5785        Some(t) if !t.joint => t,
5786        _ => return None,
5787    };
5788    // Explicit `EXPORT TYPE ...` or `EXPORT FUNC ...` prefix.
5789    if let TokKind::Word(w) = &next.kind
5790        && (w == KEYWORD_TYPE || w == KEYWORD_FUNC)
5791    {
5792        let is_type = w == KEYWORD_TYPE;
5793        let after = match toks.get(pos + 2) {
5794            Some(t) if !t.joint => t,
5795            _ => return None,
5796        };
5797        if let TokKind::Group {
5798            delim: GroupDelim::Bracket,
5799            inner,
5800            ..
5801        } = &after.kind
5802        {
5803            let mut func_names = Vec::new();
5804            let mut type_names = Vec::new();
5805            for part in split_bracket_entries(inner) {
5806                let mut part = part;
5807                while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
5808                    part = &part[1..];
5809                }
5810                while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
5811                    part = &part[..part.len() - 1];
5812                }
5813                // A trailing comma leaves an empty final entry; it
5814                // carries no name and must not fail the list.
5815                if part.is_empty() {
5816                    continue;
5817                }
5818                let (name, used) = parse_export_name(part, 0)?;
5819                if used != part.len() {
5820                    return None;
5821                }
5822                if is_type {
5823                    type_names.push(name);
5824                } else {
5825                    func_names.push(name);
5826                }
5827            }
5828            if func_names.is_empty() && type_names.is_empty() {
5829                return None;
5830            }
5831            return Some((
5832                ExportNames {
5833                    func_names,
5834                    type_names,
5835                },
5836                3,
5837            ));
5838        }
5839        if matches!(&after.kind, TokKind::Group { .. }) {
5840            return None;
5841        }
5842        let (name, used) = parse_export_name(toks, pos + 2)?;
5843        // Bare name after TYPE/FUNC prefix must consume exactly one
5844        // name; trailing loops stay outside like the unprefixed case.
5845        // `used` counts from pos+2, so 1 name is valid.
5846        if used == 0 {
5847            return None;
5848        }
5849        if is_type {
5850            return Some((
5851                ExportNames {
5852                    func_names: Vec::new(),
5853                    type_names: vec![name],
5854                },
5855                2 + used,
5856            ));
5857        } else {
5858            return Some((
5859                ExportNames {
5860                    func_names: vec![name],
5861                    type_names: Vec::new(),
5862                },
5863                2 + used,
5864            ));
5865        }
5866    }
5867    if let TokKind::Group {
5868        delim: GroupDelim::Bracket,
5869        inner,
5870        ..
5871    } = &next.kind
5872    {
5873        let mut func_names = Vec::new();
5874        let mut type_names = Vec::new();
5875        for part in split_bracket_entries(inner) {
5876            let mut part = part;
5877            while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
5878                part = &part[1..];
5879            }
5880            while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
5881                part = &part[..part.len() - 1];
5882            }
5883            // A trailing comma leaves an empty final entry; it
5884            // carries no name and must not fail the list.
5885            if part.is_empty() {
5886                continue;
5887            }
5888            // Optional per-entry `TYPE`/`FUNC` prefix for mixed lists:
5889            // `EXPORT [TYPE A, FUNC B, C]` (bare stays func). The name
5890            // must be `sep` from the prefix; the prefix itself may be
5891            // joint to a preceding `[` or `,`, so only the name's joint
5892            // flag matters.
5893            let (is_type, rest) = match part {
5894                [first, second, ..]
5895                    if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_TYPE || w == KEYWORD_FUNC)
5896                        && !second.joint =>
5897                {
5898                    let is_t = matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_TYPE);
5899                    (is_t, &part[1..])
5900                }
5901                _ => (false, part),
5902            };
5903            // Exactly one name per entry (entries never trail).
5904            let (name, used) = parse_export_name(rest, 0)?;
5905            if used != rest.len() {
5906                return None;
5907            }
5908            if is_type {
5909                type_names.push(name);
5910            } else {
5911                func_names.push(name);
5912            }
5913        }
5914        if func_names.is_empty() && type_names.is_empty() {
5915            return None;
5916        }
5917        return Some((
5918            ExportNames {
5919                func_names,
5920                type_names,
5921            },
5922            2,
5923        ));
5924    }
5925    if matches!(&next.kind, TokKind::Group { .. }) {
5926        return None;
5927    }
5928    // Bare name (greedy `::` prefix; trailing loops outside). Bare
5929    // stays func for back-compat; `TYPE`/`FUNC` prefix selects above.
5930    parse_export_name(toks, pos + 1).map(|(name, used)| {
5931        (
5932            ExportNames {
5933                func_names: vec![name],
5934                type_names: Vec::new(),
5935            },
5936            1 + used,
5937        )
5938    })
5939}
5940
5941/// Split bracket inner tokens on top-level commas, preserving entries
5942/// for per-entry `TYPE`/`FUNC` handling. Newlines trim at the caller.
5943fn split_bracket_entries(inner: &[Tok]) -> Vec<&[Tok]> {
5944    let mut parts: Vec<&[Tok]> = Vec::new();
5945    let mut start = 0;
5946    for (i, tok) in inner.iter().enumerate() {
5947        if matches!(&tok.kind, TokKind::Punct(',')) {
5948            parts.push(&inner[start..i]);
5949            start = i + 1;
5950        }
5951    }
5952    parts.push(&inner[start..]);
5953    parts
5954}
5955
5956/// `TYPE NAME = SHAPE` at `pos`: uppercase name, single `=`, maximal
5957/// type-tag shape canonicalized through the shared spelling.
5958/// Returns the alias plus tokens consumed, or `None` on shape miss
5959/// (generic fails it in lowering like the grammar).
5960fn parse_type_stmt_at(
5961    toks: &[Tok],
5962    pos: usize,
5963    stmt: usize,
5964) -> Result<Option<(StepKind, usize)>, TokenError> {
5965    let name = match toks.get(pos + 1).map(|t| &t.kind) {
5966        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
5967        _ => return Ok(None),
5968    };
5969    // Single `=` at any gap (`gap` zero-width); `==` misses.
5970    if !matches!(
5971        toks.get(pos + 2).map(|t| &t.kind),
5972        Some(TokKind::Punct('='))
5973    ) {
5974        return Ok(None);
5975    }
5976    if matches!(
5977        toks.get(pos + 3).map(|t| &t.kind),
5978        Some(TokKind::Punct('='))
5979    ) {
5980        return Ok(None);
5981    }
5982    let Some(end) = parse_type_shape(toks, pos + 3) else {
5983        return Ok(None);
5984    };
5985    // Post-match the span holds words, puncts, and default literals
5986    // only, so the shared renderer cannot fail; stay failed regardless.
5987    let target = render_type_region(&toks[pos + 3..end], stmt).unwrap_or_default();
5988    Ok(Some((StepKind::TypeAlias { name, target }, end - pos)))
5989}
5990
5991/// Single (non-block) `REMOTE`: target, optional bindings, block.
5992/// The target reads a maximal joint run in the grammar's superset
5993/// charset (misses fall to generic); strict validity fails loudly
5994/// with the exact backend message. Bindings miss to generic;
5995/// empty/missing bodies and nesting violations fail loudly.
5996fn parse_remote_single(
5997    toks: &[Tok],
5998    pos: usize,
5999    stmt: usize,
6000    ctx: &ParseCtx,
6001) -> Result<Option<(StepKind, usize)>, TokenError> {
6002    let fail = |msg: String| TokenError {
6003        stmt,
6004        msg,
6005        line: 0,
6006        col: 0,
6007        kind: Some(ParseErrorKind::Validation {
6008            command: KEYWORD_REMOTE.to_string(),
6009        }),
6010    };
6011    // Target: joint run in the superset charset (alnum/`_`/`-`/`.`/`:`).
6012    // Anything else (joint or not) ends the run; an empty run misses
6013    // to generic. (`sep` needs no explicit check: a joint `(` is a
6014    // call routed before this ever runs, and anything unparseable
6015    // misses the same way.)
6016    let mut target = String::new();
6017    let mut p = pos + 1;
6018    while let Some(t) = toks.get(p) {
6019        if !t.joint && !target.is_empty() {
6020            break;
6021        }
6022        match &t.kind {
6023            TokKind::Word(w)
6024                if w.chars().all(|c| {
6025                    c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' || c == ':'
6026                }) =>
6027            {
6028                // Words arrive whole from the lexer; a bad word ends
6029                // the run (never partially appends), like the grammar.
6030                target.push_str(w);
6031                p += 1;
6032            }
6033            TokKind::Punct(c)
6034                if matches!(c, '_' | '-' | '.' | ':') && (target.is_empty() || t.joint) =>
6035            {
6036                target.push(*c);
6037                p += 1;
6038            }
6039            _ => break,
6040        }
6041    }
6042    if target.is_empty() {
6043        return Ok(None);
6044    }
6045    if !crate::commands::is_valid_remote_target(&target) {
6046        return Err(fail(format!(
6047            "invalid REMOTE target `{target}`: start alphanumeric, then alphanumeric, `_`, or `-`, max 64 chars, never SNAPSHOT, LOCAL, CACHE, SYSTEM, or REMOTE"
6048        )));
6049    }
6050    // Optional bindings `[$var, env:KEY]` at any gap (even joint,
6051    // probed); malformed bindings miss the whole shape to generic.
6052    let mut vars = Vec::new();
6053    let mut env = Vec::new();
6054    if let Some(bracket) = toks.get(p)
6055        && matches!(
6056            &bracket.kind,
6057            TokKind::Group {
6058                delim: GroupDelim::Bracket,
6059                ..
6060            }
6061        )
6062    {
6063        let inner = match &bracket.kind {
6064            TokKind::Group { inner, .. } => inner.clone(),
6065            _ => unreachable!(),
6066        };
6067        match parse_remote_bindings(&inner, stmt)? {
6068            Some((v, e)) => {
6069                vars = v;
6070                env = e;
6071            }
6072            None => return Ok(None),
6073        }
6074        p += 1;
6075    }
6076    // Block required (any gap, never a template); missing blocks
6077    // miss to generic.
6078    let block_ok = matches!(
6079        toks.get(p).map(|t| &t.kind),
6080        Some(TokKind::Group {
6081            delim: GroupDelim::Brace,
6082            ..
6083        })
6084    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
6085    if !block_ok {
6086        return Ok(None);
6087    }
6088    let inner = match &toks[p].kind {
6089        TokKind::Group { inner, .. } => inner.clone(),
6090        _ => unreachable!(),
6091    };
6092    let body = parse_body_steps(&inner, stmt, ctx, false)?;
6093    p += 1;
6094    if body.is_empty() {
6095        return Err(fail("REMOTE requires a non-empty braced block".to_string()));
6096    }
6097    if crate::commands::contains_remote_block(&body) {
6098        return Err(fail(format!(
6099            "REMOTE blocks cannot nest (target `{target}` contains another REMOTE block)"
6100        )));
6101    }
6102    if body
6103        .iter()
6104        .any(|s| crate::commands::contains_inherit_env(&s.kind))
6105    {
6106        return Err(fail(
6107            "INHERIT_ENV cannot appear inside a REMOTE block: the guest inherits its own process environment".to_string(),
6108        ));
6109    }
6110    // Outer-function containment (same rule as the shared remote
6111    // validators): body calls resolving to visible
6112    // outer `SCRIPT` defs (without same-body definitions) fail.
6113    {
6114        let mut inner_defs = HashSet::new();
6115        let mut calls = Vec::new();
6116        crate::commands::collect_remote_body_symbols(&body, &mut inner_defs, &mut calls);
6117        let outer_defs: HashSet<String> = ctx.funcs.borrow().iter().flatten().cloned().collect();
6118        for call in &calls {
6119            let bare = crate::constants::base_name(call);
6120            let is_script_call = match crate::constants::split_qualified(call) {
6121                Some((module, _)) => module == crate::constants::SCRIPT_MODULE_NAME,
6122                None => true,
6123            };
6124            if is_script_call && outer_defs.contains(bare) && !inner_defs.contains(bare) {
6125                return Err(fail(format!(
6126                    "REMOTE '{target}' calls outer function '{bare}' (functions must be defined inside the block)"
6127                )));
6128            }
6129        }
6130    }
6131    Ok(Some((
6132        StepKind::RemoteBlock {
6133            target,
6134            vars,
6135            env,
6136            body,
6137        },
6138        p - pos,
6139    )))
6140}
6141// ---- LET/SET/RETURN + expressions ----
6142// Expression tiers over [`Tok`] implement the precedence chain
6143// (or > and > comparison > ordering > add > mul > unary > atom);
6144// arithmetic/comparison lowering runs through the shared constructors
6145// (`make_arith`, `make_compare`, `apply_unary_neg`), so folding, RPN
6146// compilation, and overflow behavior are identical by construction,
6147// never re-derived.
6148
6149/// Eat a one- or two-char operator: single puncts match directly;
6150/// pairs (`==`, `!=`, `<=`, `>=`, `&&`, `||`, `::`) require a joint
6151/// second punct. Newlines never skip here (expression mode).
6152fn eat_op(cur: &mut Cursor, first: char, second: Option<char>) -> bool {
6153    // Gaps (comments included) are skipped before every operator.
6154    cur.skip_gap();
6155    let (a, b) = match (cur.toks.get(cur.pos), cur.toks.get(cur.pos + 1)) {
6156        (Some(a), b) => (a, b),
6157        _ => return false,
6158    };
6159    if !matches!(&a.kind, TokKind::Punct(c) if *c == first) {
6160        return false;
6161    }
6162    match second {
6163        None => {
6164            cur.pos += 1;
6165            true
6166        }
6167        Some(c2) => match b {
6168            Some(t) if t.joint && matches!(&t.kind, TokKind::Punct(c) if *c == c2) => {
6169                cur.pos += 2;
6170                true
6171            }
6172            _ => false,
6173        },
6174    }
6175}
6176
6177/// Dummy span for the shared lowering constructors: v2 owns no source
6178/// positions yet, so only success values (span-free) participate in
6179/// parity; failures surface through [`TokenError`] text.
6180fn lowering_ctx(stmt: usize) -> SpanContext<'static> {
6181    let _ = stmt;
6182    SpanContext::line_only(0)
6183}
6184
6185fn parse_expr_or(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6186    let mut left = parse_expr_and(cur, ctx)?;
6187    while eat_op(cur, '|', Some('|')) {
6188        cur.skip_gap();
6189        let right = parse_expr_and(cur, ctx)?;
6190        // No folding, no boundary checks: unfused literal runs stay
6191        // literal here.
6192        left = Expr::Logical {
6193            op: LogicalOp::Or,
6194            left: Box::new(left),
6195            right: Box::new(right),
6196        };
6197    }
6198    Ok(left)
6199}
6200
6201fn parse_expr_and(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6202    let mut left = parse_expr_cmp(cur, ctx)?;
6203    while eat_op(cur, '&', Some('&')) {
6204        cur.skip_gap();
6205        let right = parse_expr_cmp(cur, ctx)?;
6206        reject_boundary(&lowering_ctx(cur.stmt), &left).map_err(|e| cur.err(e.to_string()))?;
6207        reject_boundary(&lowering_ctx(cur.stmt), &right).map_err(|e| cur.err(e.to_string()))?;
6208        left = Expr::Logical {
6209            op: LogicalOp::And,
6210            left: Box::new(left),
6211            right: Box::new(right),
6212        };
6213    }
6214    Ok(left)
6215}
6216
6217fn parse_expr_cmp(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6218    let left = parse_expr_ord(cur, ctx)?;
6219    let op = if eat_op(cur, '=', Some('=')) {
6220        CompareOp::Eq
6221    } else if eat_op(cur, '!', Some('=')) {
6222        CompareOp::Ne
6223    } else {
6224        return Ok(left);
6225    };
6226    cur.skip_gap();
6227    let right = parse_expr_ord(cur, ctx)?;
6228    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
6229        .map_err(|e| cur.err(e.to_string()))?;
6230    reject_chained_compare(cur, false)?;
6231    Ok(expr)
6232}
6233
6234/// Reject a comparison operator trailing a complete comparison:
6235/// no grammar position continues with one, so the shape always fails —
6236/// loudly here instead of stranding text for a confusing downstream
6237/// error. The equality tier rejects all six (`$a == $b == $c`,
6238/// `$a == $b < $c < $d`); the ordering tier rejects ordering only
6239/// (`$a < $b < $c`), since `$a < $b == $c` is a legitimate equality
6240/// over an ordering result. Probes without consuming.
6241fn reject_chained_compare(cur: &mut Cursor, ordering_only: bool) -> Result<(), TokenError> {
6242    let mut probe = Cursor::expr(cur.toks, cur.stmt);
6243    probe.pos = cur.pos;
6244    probe.skip_gap();
6245    let chained = match probe.toks.get(probe.pos).map(|t| &t.kind) {
6246        Some(TokKind::Punct('<' | '>')) => true,
6247        Some(TokKind::Punct('=' | '!')) => !ordering_only,
6248        _ => false,
6249    };
6250    if chained {
6251        return Err(cur
6252            .err("chained comparison operators need explicit parentheses, e.g. `($a < $b) < $c`"));
6253    }
6254    Ok(())
6255}
6256
6257fn parse_expr_ord(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6258    let left = parse_expr_add(cur, ctx)?;
6259    let op = if eat_op(cur, '<', Some('=')) {
6260        CompareOp::Le
6261    } else if eat_op(cur, '>', Some('=')) {
6262        CompareOp::Ge
6263    } else if eat_op(cur, '<', None) {
6264        CompareOp::Lt
6265    } else if eat_op(cur, '>', None) {
6266        CompareOp::Gt
6267    } else {
6268        return Ok(left);
6269    };
6270    cur.skip_gap();
6271    let right = parse_expr_add(cur, ctx)?;
6272    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
6273        .map_err(|e| cur.err(e.to_string()))?;
6274    reject_chained_compare(cur, true)?;
6275    Ok(expr)
6276}
6277
6278fn parse_expr_add(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6279    let mut left = parse_expr_mul(cur, ctx)?;
6280    loop {
6281        let op = if eat_op(cur, '+', None) {
6282            ArithOp::Add
6283        } else if eat_op(cur, '-', None) {
6284            ArithOp::Sub
6285        } else {
6286            break;
6287        };
6288        cur.skip_gap();
6289        let right = parse_expr_mul(cur, ctx)?;
6290        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
6291            .map_err(|e| cur.err(e.to_string()))?;
6292    }
6293    Ok(left)
6294}
6295
6296fn parse_expr_mul(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6297    let mut left = parse_expr_unary(cur, ctx)?;
6298    loop {
6299        let op = if eat_op(cur, '*', None) {
6300            ArithOp::Mul
6301        } else if eat_op(cur, '/', None) {
6302            ArithOp::Div
6303        } else {
6304            break;
6305        };
6306        cur.skip_gap();
6307        let right = parse_expr_unary(cur, ctx)?;
6308        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
6309            .map_err(|e| cur.err(e.to_string()))?;
6310    }
6311    Ok(left)
6312}
6313
6314/// A `-` opens a bare word (never negation) when gaplessly followed by
6315/// a letter, `_`, or `/` — the `neg_op` lookahead, read off `joint`.
6316fn dash_is_bare(cur: &Cursor) -> bool {
6317    let next = cur.toks.get(cur.pos + 1);
6318    match next {
6319        Some(t) if t.joint => match &t.kind {
6320            TokKind::Word(w) => w
6321                .chars()
6322                .next()
6323                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_'),
6324            TokKind::Punct('/') => true,
6325            _ => false,
6326        },
6327        _ => false,
6328    }
6329}
6330
6331fn parse_expr_unary(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6332    let mut prefixes = Vec::new();
6333    loop {
6334        match cur.toks.get(cur.pos).map(|t| &t.kind) {
6335            Some(TokKind::Punct('!')) => {
6336                cur.pos += 1;
6337                // Each prefix is gap-separated.
6338                cur.skip_gap();
6339                prefixes.push(false);
6340            }
6341            Some(TokKind::Punct('-')) if !dash_is_bare(cur) => {
6342                cur.pos += 1;
6343                cur.skip_gap();
6344                prefixes.push(true);
6345            }
6346            _ => break,
6347        }
6348    }
6349    let mut expr = parse_expr_atom(cur, ctx)?;
6350    // Innermost prefix is closest to the atom: apply in reverse order.
6351    for is_neg in prefixes.into_iter().rev() {
6352        if is_neg {
6353            expr = apply_unary_neg(&lowering_ctx(cur.stmt), expr)
6354                .map_err(|e| cur.err(e.to_string()))?;
6355        } else {
6356            reject_boundary(&lowering_ctx(cur.stmt), &expr).map_err(|e| cur.err(e.to_string()))?;
6357            expr = Expr::Not(Box::new(expr));
6358        }
6359    }
6360    Ok(expr)
6361}
6362
6363/// Identifier charset for `$var` and `.segment` parts. Segments admit
6364/// digits-only too (`$a.0`); anything else ends the key path and errors
6365/// downstream, like the grammar's backtrack to `variable`.
6366fn is_ident_word(w: &str) -> bool {
6367    !w.is_empty() && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
6368}
6369
6370fn is_key_segment(w: &str) -> bool {
6371    !w.is_empty()
6372        && (w.chars().all(|c| c.is_ascii_digit())
6373            || (w
6374                .chars()
6375                .next()
6376                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
6377                && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')))
6378}
6379
6380fn is_env_key(w: &str) -> bool {
6381    !w.is_empty()
6382        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
6383        && w.chars()
6384            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
6385}
6386
6387/// Maximal joint run of words and `-/.'/'` puncts: the bare-word
6388/// shape (which admits `/` anywhere, so `//c`, `/a`, `a/b`, and the
6389/// `/`-`c`-`/` operands of `/*c*/` math all read literally here).
6390/// Callers classify (`true`/`false`/string); the numeric path
6391/// runs first and falls back here on shape/follower mismatch.
6392/// Backslash escapes are arg-position syntax: the bare-word shape admits
6393/// no `\`, so expression runs containing one fail here (never drift
6394/// into a string the grammar rejects).
6395fn expr_bare_run(cur: &mut Cursor, leading_dash: bool) -> Result<String, TokenError> {
6396    let mut out = String::new();
6397    if leading_dash {
6398        match cur.next() {
6399            Some(t) if matches!(&t.kind, TokKind::Punct('-')) => out.push('-'),
6400            _ => return Err(cur.err("missing expression operand")),
6401        }
6402    }
6403    match cur.next() {
6404        Some(t) => match &t.kind {
6405            TokKind::Word(w) => out.push_str(w),
6406            // Leading `/` (operand position only; operators are
6407            // consumed by the tiers before operands parse).
6408            TokKind::Punct('/') => out.push('/'),
6409            _ => return Err(cur.err("missing expression operand")),
6410        },
6411        None => return Err(cur.err("missing expression operand")),
6412    }
6413    loop {
6414        let next = match cur.toks.get(cur.pos) {
6415            Some(t) if t.joint => t,
6416            _ => break,
6417        };
6418        match &next.kind {
6419            TokKind::Word(w) => {
6420                // Abutting words only continue through an operator gap
6421                // the tiers own (`a -b` never fuses); without a joint
6422                // punct between, stop. Since this token IS joint, the
6423                // previous token must have been a bare punct.
6424                out.push_str(w);
6425                cur.pos += 1;
6426            }
6427            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
6428                out.push(*c);
6429                cur.pos += 1;
6430            }
6431            _ => break,
6432        }
6433    }
6434    if out.contains('\\') {
6435        return Err(cur.err("unexpected escape in expression"));
6436    }
6437    Ok(out)
6438}
6439
6440/// Numeric literal head: digit-led word plus joint `.digits` tails.
6441/// Callers apply the separator-shape gate and the follower rule, then
6442/// the shared classifier.
6443fn number_head(cur: &mut Cursor) -> Option<String> {
6444    let first = match cur.toks.get(cur.pos).map(|t| &t.kind) {
6445        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => w.clone(),
6446        _ => return None,
6447    };
6448    let mut text = first;
6449    let mut pos = cur.pos + 1;
6450    loop {
6451        let dot = matches!(
6452            cur.toks.get(pos).map(|t| &t.kind),
6453            Some(TokKind::Punct('.'))
6454        ) && cur.toks.get(pos).is_some_and(|t| t.joint);
6455        let digits = cur.toks.get(pos + 1);
6456        let digits_ok = dot
6457            && matches!(digits.map(|t| &t.kind), Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_'))
6458            && digits.is_some_and(|t| t.joint);
6459        if !digits_ok {
6460            break;
6461        }
6462        text.push('.');
6463        if let Some(TokKind::Word(w)) = digits.map(|t| &t.kind) {
6464            text.push_str(w);
6465        }
6466        pos += 2;
6467    }
6468    Some(text)
6469}
6470
6471/// `_`-separator shape gate mirroring the `numeric_literal` rule:
6472/// digits with single-underscore separators, at most one fraction.
6473fn numeric_shape_ok(text: &str) -> bool {
6474    let mut parts = text.split('.');
6475    let int_part = parts.next().unwrap_or("");
6476    let frac_part = parts.next();
6477    if parts.next().is_some() {
6478        return false;
6479    }
6480    fn run_ok(s: &str) -> bool {
6481        !s.is_empty()
6482            && s.chars().all(|c| c.is_ascii_digit() || c == '_')
6483            && !s.starts_with('_')
6484            && !s.ends_with('_')
6485            && !s.contains("__")
6486    }
6487    run_ok(int_part) && frac_part.is_none_or(run_ok)
6488}
6489
6490/// Follower rule mirroring the `numeric_literal` trailing guard
6491/// (`!(ALNUM | "_" | "." | "/")`): a joint word, `.`, or `/` continues
6492/// into a bare word (`30s`, `1.`, `4/2`); `-`/`+`/operators let the
6493/// number stand for the tiers (`1-2` is `Sub`, like the grammar).
6494fn number_falls_to_bare(cur: &Cursor, consumed: usize) -> bool {
6495    match cur.toks.get(cur.pos + consumed) {
6496        Some(t) if t.joint => matches!(
6497            &t.kind,
6498            TokKind::Word(_) | TokKind::Punct('.') | TokKind::Punct('/')
6499        ),
6500        _ => false,
6501    }
6502}
6503
6504fn parse_expr_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6505    match cur.toks.get(cur.pos).map(|t| &t.kind) {
6506        Some(TokKind::Group {
6507            delim: GroupDelim::Paren,
6508            inner,
6509            ..
6510        }) => {
6511            let inner = inner.clone();
6512            cur.pos += 1;
6513            let mut sub = Cursor::expr(&inner, cur.stmt);
6514            sub.skip_gap_nl();
6515            let expr = parse_expr_or(&mut sub, ctx)?;
6516            sub.skip_gap_nl();
6517            if !sub.done() {
6518                return Err(sub.err("unexpected text in parentheses"));
6519            }
6520            Ok(expr)
6521        }
6522        Some(TokKind::Word(_)) if call_shape_at(cur.toks, cur.pos, false).is_some() => {
6523            let (name, paren) =
6524                call_shape_at(cur.toks, cur.pos, false).ok_or_else(|| cur.err("unreachable"))?;
6525            let inner = match &cur.toks[paren].kind {
6526                TokKind::Group { inner, .. } => inner.clone(),
6527                _ => unreachable!(),
6528            };
6529            cur.pos = paren + 1;
6530            parse_expr_call(name, &inner, cur.stmt, ctx)
6531        }
6532        Some(TokKind::Punct('$')) => {
6533            cur.pos += 1;
6534            // Atomic `variable`: `$` and the name ride gapless (the
6535            // enclosing rules are compound-atomic).
6536            let base = match cur.next() {
6537                Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
6538                    match &t.kind {
6539                        TokKind::Word(w) => w.clone(),
6540                        _ => unreachable!(),
6541                    }
6542                }
6543                _ => return Err(cur.err("`$` requires a variable name")),
6544            };
6545            let mut keys = Vec::new();
6546            loop {
6547                // Key-path dots are gapless too (`~` without `gap`).
6548                let dot = matches!(
6549                    cur.toks.get(cur.pos).map(|t| &t.kind),
6550                    Some(TokKind::Punct('.'))
6551                ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
6552                let seg = cur.toks.get(cur.pos + 1);
6553                let seg_ok = dot
6554                    && matches!(seg.map(|t| &t.kind), Some(TokKind::Word(w)) if is_key_segment(w))
6555                    && seg.is_some_and(|t| t.joint);
6556                if !seg_ok {
6557                    break;
6558                }
6559                if let Some(TokKind::Word(w)) = seg.map(|t| &t.kind) {
6560                    keys.push(w.clone());
6561                }
6562                cur.pos += 2;
6563            }
6564            if keys.is_empty() {
6565                Ok(Expr::Var(base))
6566            } else {
6567                Ok(Expr::KeyPath { base, keys })
6568            }
6569        }
6570        Some(TokKind::Word(w)) if w == "env" => {
6571            // `env:KEY` read when the full shape matches gaplessly
6572            // (atomic `env_read`); otherwise a bare word (`env` alone,
6573            // `env:k` lowercase) for the error path, exactly like the
6574            // grammar's mismatch.
6575            let key_ok = matches!(
6576                cur.toks.get(cur.pos + 1).map(|t| &t.kind),
6577                Some(TokKind::Punct(':'))
6578            ) && cur.toks.get(cur.pos + 1).is_some_and(|t| t.joint)
6579                && matches!(
6580                    cur.toks.get(cur.pos + 2).map(|t| &t.kind),
6581                    Some(TokKind::Word(k)) if is_env_key(k)
6582                )
6583                && cur.toks.get(cur.pos + 2).is_some_and(|t| t.joint);
6584            if !key_ok {
6585                return parse_bare_atom(cur, ctx, false);
6586            }
6587            cur.pos += 1;
6588            cur.pos += 1;
6589            match cur.next() {
6590                Some(t) => match &t.kind {
6591                    TokKind::Word(k) => Ok(Expr::Env(k.clone())),
6592                    _ => Err(cur.err("unreachable")),
6593                },
6594                None => Err(cur.err("unreachable")),
6595            }
6596        }
6597        Some(TokKind::Group {
6598            delim: GroupDelim::Bracket,
6599            inner,
6600            ..
6601        }) => {
6602            let inner = inner.clone();
6603            cur.pos += 1;
6604            parse_list_literal(&inner, cur.stmt, ctx)
6605        }
6606        Some(TokKind::Group {
6607            delim: GroupDelim::Brace,
6608            inner,
6609            ..
6610        }) => {
6611            let inner = inner.clone();
6612            cur.pos += 1;
6613            parse_map_or_block(&inner, cur.stmt, ctx)
6614        }
6615        Some(TokKind::Str { text, .. }) => {
6616            let text = text.clone();
6617            cur.pos += 1;
6618            Ok(Expr::Literal(Value::string(text)))
6619        }
6620        Some(TokKind::BlockStr(full)) => {
6621            let full = full.clone();
6622            cur.pos += 1;
6623            Ok(Expr::Literal(Value::string(
6624                crate::command::lower_block_string(&full),
6625            )))
6626        }
6627        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => {
6628            parse_numeric_atom(cur, ctx)
6629        }
6630        Some(TokKind::Word(_)) => parse_bare_atom(cur, ctx, false),
6631        Some(TokKind::Punct('-')) => parse_bare_atom(cur, ctx, true),
6632        Some(TokKind::Punct('/')) => parse_bare_atom(cur, ctx, false),
6633        _ => Err(cur.err("missing expression operand")),
6634    }
6635}
6636
6637/// Bare-word atom with a `-` lead (the caller proved it is not
6638/// negation): consumes the joint `-/.'/'` run for the bare-word
6639/// shape.
6640fn parse_bare_atom(
6641    cur: &mut Cursor,
6642    _ctx: &ParseCtx,
6643    leading_dash: bool,
6644) -> Result<Expr, TokenError> {
6645    let text = expr_bare_run(cur, leading_dash)?;
6646    match text.as_str() {
6647        "true" => Ok(Expr::Literal(Value::bool(true))),
6648        "false" => Ok(Expr::Literal(Value::bool(false))),
6649        _ => Ok(Expr::Literal(Value::string(text))),
6650    }
6651}
6652
6653/// Numeric atom: rejoin dotted tails, apply the shape gate and the
6654/// follower rule, then the shared classifier. Anything failing the
6655/// gate or follower reparses as a bare word (durations, versions,
6656/// paths), exactly like the grammar's numeric-literal-or-bare-word
6657/// order.
6658fn parse_numeric_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6659    let start = cur.pos;
6660    let text = number_head(cur).ok_or_else(|| cur.err("missing expression operand"))?;
6661    let consumed = {
6662        let mut n = 1;
6663        let mut p = start + 1;
6664        while matches!(cur.toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('.')))
6665            && cur.toks.get(p).is_some_and(|t| t.joint)
6666            && matches!(
6667                cur.toks.get(p + 1).map(|t| &t.kind),
6668                Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_')
6669            )
6670            && cur.toks.get(p + 1).is_some_and(|t| t.joint)
6671        {
6672            n += 2;
6673            p += 2;
6674        }
6675        n
6676    };
6677    if !numeric_shape_ok(&text) || number_falls_to_bare(cur, consumed) {
6678        return parse_bare_atom(cur, ctx, false);
6679    }
6680    cur.pos += consumed;
6681    classify_numeric_text(&text).map_err(|msg| cur.err(msg))
6682}
6683
6684/// Full expression with the top-level boundary rejection (mirrors
6685/// `parse_expr`): a stray `UnsignedIntBoundary` that no unary `-`
6686/// consumed is an overflow error.
6687fn parse_expr_checked(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6688    let expr = parse_expr_or(cur, ctx)?;
6689    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
6690        return Err(cur.err("integer overflow: 9223372036854775808 exceeds i64::MAX"));
6691    }
6692    Ok(expr)
6693}
6694
6695/// List literal over a bracket group's contents: the shared bracket
6696/// core (see [`parse_bracket_list`]) in `Expr` mode. Expression
6697/// positions fail loudly instead of missing, so `None` is unreachable.
6698fn parse_list_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6699    parse_bracket_list(inner, stmt, ctx, BracketItems::Expr)
6700        .map(|list| list.expect("expression lists fail loudly, never miss"))
6701}
6702
6703/// Map literal attempt over a brace group's contents: comma-separated
6704/// `key: value` entries with `gap` (never newline) around the colon.
6705/// Any entry failing the shape is not a map: the caller reports the
6706/// deferred block slice (the grammar tries `block` next, which fails
6707/// the same inputs at this stage).
6708/// Marker message for a map entry run that ends without a comma
6709/// where another entry follows. Matched by exact equality in
6710/// [`parse_map_or_block`], never by prefix, so wording changes stay
6711/// local to this const and its one reader.
6712const MISSING_MAP_COMMA_MSG: &str = "missing comma between map entries";
6713
6714fn parse_map_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6715    let mut entries = Vec::new();
6716    // Empty (or blank/comment-only) braces are an empty map.
6717    if inner
6718        .iter()
6719        .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
6720    {
6721        return Ok(Expr::Map(vec![]));
6722    }
6723    for part in split_top_commas(inner) {
6724        let mut sub = Cursor::expr(part, stmt);
6725        sub.skip_gap_nl();
6726        let (key, val) = parse_map_entry(&mut sub, ctx, stmt)?;
6727        sub.skip_gap_nl();
6728        if !sub.done() {
6729            return Err(map_trailing_error(&sub, ctx, stmt));
6730        }
6731        entries.push((key, val));
6732    }
6733    Ok(Expr::Map(entries))
6734}
6735
6736/// One `key: value` map entry: string, block-string, or bare key,
6737/// a colon, then a full checked expression. Every failure reads
6738/// `not a map literal` exactly like the old inline loop, so only
6739/// the trailing rule changes the surface.
6740fn parse_map_entry(
6741    sub: &mut Cursor,
6742    ctx: &ParseCtx,
6743    stmt: usize,
6744) -> Result<(String, Expr), TokenError> {
6745    let key = match sub.toks.get(sub.pos).map(|t| &t.kind) {
6746        Some(TokKind::Str { text, .. }) => {
6747            let key = text.clone();
6748            sub.pos += 1;
6749            key
6750        }
6751        Some(TokKind::BlockStr(full)) => {
6752            let key = crate::command::lower_block_string(full);
6753            sub.pos += 1;
6754            key
6755        }
6756        Some(TokKind::Word(_)) | Some(TokKind::Punct('-')) | Some(TokKind::Punct('/')) => {
6757            map_bare_key(sub)?
6758        }
6759        _ => return Err(sub.err("not a map literal")),
6760    };
6761    sub.skip_gap();
6762    if !sub.eat_punct(':') {
6763        return Err(sub.err("not a map literal"));
6764    }
6765    let val = parse_expr_checked(sub, ctx)?;
6766    reject_boundary(&lowering_ctx(stmt), &val).map_err(|e| sub.err(e.to_string()))?;
6767    Ok((key, val))
6768}
6769
6770/// Trailing content after a complete map entry: stamps the
6771/// offending token and names the likely missing comma when the
6772/// remainder parses as another entry. Anything else keeps the old
6773/// `not a map literal` text. Error-path only.
6774fn map_trailing_error(sub: &Cursor, ctx: &ParseCtx, stmt: usize) -> TokenError {
6775    let (line, col) = sub
6776        .toks
6777        .get(sub.pos)
6778        .map(|t| (t.line, t.col))
6779        .unwrap_or((0, 0));
6780    let mut probe = Cursor::expr(&sub.toks[sub.pos.min(sub.toks.len())..], stmt);
6781    probe.skip_gap_nl();
6782    if parse_map_entry(&mut probe, ctx, stmt).is_ok() {
6783        return TokenError {
6784            stmt,
6785            line,
6786            col,
6787            msg: MISSING_MAP_COMMA_MSG.to_string(),
6788            kind: None,
6789        };
6790    }
6791    sub.err("not a map literal")
6792}
6793
6794/// Bare map key: joint `-/.'/'`-run, mirroring the bare-word charset
6795/// (no bool/numeric classification: keys are always strings).
6796fn map_bare_key(sub: &mut Cursor) -> Result<String, TokenError> {
6797    let mut out = String::new();
6798    if matches!(
6799        sub.toks.get(sub.pos).map(|t| &t.kind),
6800        Some(TokKind::Punct('-'))
6801    ) {
6802        out.push('-');
6803        sub.pos += 1;
6804    }
6805    // Leading `/` reads literally too (the bare-word shape admits `/`
6806    // anywhere: `{/a: 1}`, `{//c: 1}`); the joint loop below
6807    // continues the run.
6808    if matches!(
6809        sub.toks.get(sub.pos).map(|t| &t.kind),
6810        Some(TokKind::Punct('/'))
6811    ) {
6812        out.push('/');
6813        sub.pos += 1;
6814    }
6815    match sub.toks.get(sub.pos).map(|t| &t.kind) {
6816        Some(TokKind::Word(w)) => {
6817            out.push_str(w);
6818            sub.pos += 1;
6819        }
6820        // A leading `/` above already started the run; anything
6821        // else still needs a word head.
6822        _ if !out.is_empty() => {}
6823        _ => return Err(sub.err("not a map literal")),
6824    }
6825    while let Some(t) = sub.toks.get(sub.pos) {
6826        if !t.joint {
6827            break;
6828        }
6829        match &t.kind {
6830            TokKind::Word(w) => {
6831                out.push_str(w);
6832                sub.pos += 1;
6833            }
6834            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
6835                out.push(*c);
6836                sub.pos += 1;
6837            }
6838            _ => break,
6839        }
6840    }
6841    if out.contains('\\') {
6842        return Err(sub.err("unexpected escape in map key"));
6843    }
6844    Ok(out)
6845}
6846
6847/// Map-or-block over a brace group's contents: maps parse literally;
6848/// anything else is an inline block (`Expr::Block` over the body
6849/// steps, scopes unmarked like every braced body).
6850fn parse_map_or_block(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6851    match parse_map_literal(inner, stmt, ctx) {
6852        Ok(map) => Ok(map),
6853        // A detected missing comma is never a block: its `key:`
6854        // remainder cannot parse as a statement (a `name: "a"` line
6855        // fails as `unknown command`), so the block path can only
6856        // misreport it. Surface the map error instead; every other
6857        // map failure keeps the block fallback exactly as before.
6858        Err(e) if e.msg == MISSING_MAP_COMMA_MSG => Err(e),
6859        Err(_) => Ok(Expr::Block(parse_body_steps(inner, stmt, ctx, false)?)),
6860    }
6861}
6862
6863/// Parse one standalone expression from lexed tokens (the
6864/// `parse_expression_str` entry point): a full tier parse with
6865/// top-level boundary rejection and full consumption.
6866pub(crate) fn parse_single_expr(
6867    toks: &[Tok],
6868    stmt: usize,
6869    ctx: &ParseCtx,
6870) -> Result<Expr, TokenError> {
6871    let mut cur = Cursor::expr(toks, stmt);
6872    let expr = parse_expr_checked(&mut cur, ctx)?;
6873    if !cur.done() {
6874        return Err(cur.err("unexpected text in expression"));
6875    }
6876    Ok(expr)
6877}
6878
6879/// Assignment `=`: the first depth-zero `=` neither glued to a
6880/// following `=` (`==`) nor glued after `!`/`<`/`>`/`=` (`!=`, `<=`,
6881/// `>=`, second of `==`). `<>` shape brackets own any `=` inside
6882/// them (field defaults), so LET annotations with defaults find the
6883/// real assignment. Glued-ness reads off the `=`'s own `joint` (gap
6884/// before it) and the follower's (gap after it). Anything else leaves
6885/// the statement bare (`LET $p: PIPE`), exactly where the grammar's
6886/// `"="` match fails.
6887fn find_assign_eq(body: &[Tok]) -> Option<usize> {
6888    let mut depth = 0usize;
6889    for (i, tok) in body.iter().enumerate() {
6890        match &tok.kind {
6891            TokKind::Punct('<') => depth += 1,
6892            TokKind::Punct('>') if depth > 0 => depth -= 1,
6893            TokKind::Punct('=') if depth == 0 => {
6894                let next_eq = body
6895                    .get(i + 1)
6896                    .is_some_and(|t| t.joint && matches!(&t.kind, TokKind::Punct('=')));
6897                let prev_op = tok.joint
6898                    && i > 0
6899                    && matches!(&body[i - 1].kind, TokKind::Punct('!' | '<' | '>' | '='));
6900                if !next_eq && !prev_op {
6901                    return Some(i);
6902                }
6903            }
6904            _ => {}
6905        }
6906    }
6907    None
6908}
6909
6910/// Render a type region joint-aware (`LIST< MAP >` keeps its gaps for
6911/// the shared canonicalizer, exactly like `type_tag.as_str()`).
6912fn render_type_region(toks: &[Tok], stmt: usize) -> Result<String, TokenError> {
6913    let mut out = String::new();
6914    for tok in toks {
6915        // Ridden newlines from multi-line `<...>` shapes carry no
6916        // output, so the shape canonicalizes exactly like one line.
6917        if matches!(&tok.kind, TokKind::Newline) {
6918            continue;
6919        }
6920        if !tok.joint && !out.is_empty() {
6921            out.push(' ');
6922        }
6923        match &tok.kind {
6924            TokKind::Word(w) => out.push_str(w),
6925            TokKind::Punct(c) => out.push(*c),
6926            TokKind::Str { text, quote } => {
6927                out.push(*quote);
6928                out.push_str(text);
6929                out.push(*quote);
6930            }
6931            TokKind::BlockStr(full) => out.push_str(full),
6932            _ => {
6933                return Err(TokenError {
6934                    stmt,
6935                    msg: "malformed type in LET".to_string(),
6936                    line: 0,
6937                    col: 0,
6938                    kind: None,
6939                });
6940            }
6941        }
6942    }
6943    if out.is_empty() {
6944        return Err(TokenError {
6945            stmt,
6946            msg: "LET requires explicit type: LET $var: TYPE = <expr>".to_string(),
6947            line: 0,
6948            col: 0,
6949            kind: None,
6950        });
6951    }
6952    Ok(crate::canonicalize_spelling(&out))
6953}
6954
6955fn expect_dollar_var(cur: &mut Cursor, msg: &str) -> Result<String, TokenError> {
6956    // Atomic `dollar_ident`: no gap between `$` and the name (the
6957    // enclosing statements are compound-atomic, so implicit spacing is
6958    // off and only explicit `gap`s admit whitespace).
6959    match cur.next() {
6960        Some(t) if matches!(&t.kind, TokKind::Punct('$')) => {}
6961        _ => return Err(cur.err(msg)),
6962    }
6963    match cur.next() {
6964        Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
6965            match &t.kind {
6966                TokKind::Word(w) => Ok(w.clone()),
6967                _ => unreachable!(),
6968            }
6969        }
6970        _ => Err(cur.err(msg)),
6971    }
6972}
6973
6974/// `LET` body: `LET` is already matched. Returns `None` (miss to
6975/// generic, which fails in lowering like the grammar's committed
6976/// `instruction`) when the shape cannot match any `LET` form: no
6977/// gapless `$var`, or no `:` after it
6978/// (every form needs `: TYPE`). Past that the shape is committed and
6979/// malformed tails fail loudly.
6980fn parse_let_body(
6981    body: &[Tok],
6982    stmt: usize,
6983    ctx: &ParseCtx,
6984) -> Result<Option<(StepKind, usize)>, TokenError> {
6985    let mut cur = Cursor::expr(body, stmt);
6986    match cur.next() {
6987        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_LET) => {}
6988        _ => return Err(cur.err("unreachable")),
6989    }
6990    // No `$var`: no `LET` form can match (miss, never a hard fail).
6991    let var = match expect_dollar_var(&mut cur, "LET requires a variable") {
6992        Ok(var) => var,
6993        Err(_) => return Ok(None),
6994    };
6995    // The header allows gaps (comments, never newlines).
6996    cur.skip_gap();
6997    // No `:`: untyped LET is rejected outright. Every binding is
6998    // typed; the old miss-to-generic path only hid that behind a
6999    // rambling "invalid syntax" message. (FOR already does this.)
7000    if !cur.eat_punct(':') {
7001        return Err(TokenError {
7002            stmt,
7003            msg: "LET requires explicit types: LET $var: TYPE = <expr>".to_string(),
7004            line: 0,
7005            col: 0,
7006            kind: Some(ParseErrorKind::InvalidSyntax {
7007                command: KEYWORD_LET.to_string(),
7008            }),
7009        });
7010    }
7011    // Type region runs to the depth-zero assignment `=`; `<>`
7012    // shapes own any `=` inside them (field defaults).
7013    let type_start = cur.pos;
7014    let assign = find_assign_eq(&body[type_start..]).map(|i| i + type_start);
7015    let Some(eq) = assign else {
7016        // Bare `LET $p: PIPE` mints a fresh pipe and ends with the
7017        // type word (trailing elements loop on, probed); every other
7018        // bare type is a validation error, mirroring the grammar.
7019        if matches!(
7020            body.get(type_start).map(|t| &t.kind),
7021            Some(TokKind::Word(w)) if w == crate::TypeTag::Pipe.name()
7022        ) {
7023            return Ok(Some((
7024                StepKind::Assign {
7025                    var,
7026                    decl_type: crate::TypeTag::Pipe.name().to_string(),
7027                    expr: Expr::FreshPipe,
7028                },
7029                type_start + 1,
7030            )));
7031        }
7032        return Err(cur.err(
7033            "LET requires an expression: LET $var: TYPE = <expr> (only LET $p: PIPE omits the initializer)",
7034        ));
7035    };
7036    let decl_type = render_type_region(&body[type_start..eq], stmt)?;
7037    let (kind, rhs_used) = parse_let_rhs(&body[eq + 1..], var, decl_type, stmt, ctx)?;
7038    Ok(Some((kind, eq + 1 + rhs_used)))
7039}
7040
7041/// LET right-hand side dispatch, mirroring the grammar order
7042/// (`let_async`, then `let_capture`, then `let_statement`):
7043/// `WITH_IO`-led lines branch async/sync like
7044/// `parse_let_async_statement_from_pair`, `ASYNC`-led lines spawn
7045/// tasks, `TIMEOUT`-led lines capture through the wrapper,
7046/// `AWAIT $v` captures, RUN exec-form captures, known commands
7047/// capture through the generic parser (lowering failures fatal,
7048/// exactly like the committed grammar alternative), and anything
7049/// else parses as an expression (unknown leads included). Returns
7050/// the kind and RHS tokens consumed: captures ending in structural
7051/// pairs leave trailing elements for the caller.
7052fn parse_let_rhs(
7053    rhs: &[Tok],
7054    var: String,
7055    decl_type: String,
7056    stmt: usize,
7057    ctx: &ParseCtx,
7058) -> Result<(StepKind, usize), TokenError> {
7059    // Leading gap comments vanish like the `=` gap (but a `//`/`#`
7060    // to end of input leaves no expression, failing).
7061    let mut lead = Cursor::expr(rhs, stmt);
7062    lead.skip_gap();
7063    let (rhs, skipped) = (&rhs[lead.pos..], lead.pos);
7064    let head_word = match rhs.first().map(|t| &t.kind) {
7065        Some(TokKind::Word(w)) => Some(w.clone()),
7066        _ => None,
7067    };
7068    // `WITH_IO`-led lines share `let_async_statement` with the
7069    // `ASYNC` forms (the grammar claims every WITH_IO-led LET
7070    // there); shape misses fall through to generic below.
7071    if head_word.as_deref() == Some(KEYWORD_WITH_IO)
7072        && let Some(found) = try_let_with_io_rhs(rhs, var.clone(), decl_type.clone(), stmt, ctx)?
7073    {
7074        let (kind, used) = found;
7075        return Ok((kind, skipped + used));
7076    }
7077    // `ASYNC`-led lines (with followers; alone they commit to the
7078    // generic path like the grammar, failing in lowering) spawn
7079    // background tasks. No `WITH_IO` scan here (probed: the LET
7080    // path accepts what statement `ASYNC` rejects).
7081    if head_word.as_deref() == Some(KEYWORD_ASYNC) && rhs.len() > 1 {
7082        let (kind, used) = parse_let_async_rhs(&rhs[1..], var, decl_type, stmt, ctx)?;
7083        return Ok((kind, skipped + 1 + used));
7084    }
7085    // `TIMEOUT`-led lines capture through the wrapper (shape misses
7086    // fall through to generic, which fails in lowering).
7087    if head_word.as_deref() == Some(KEYWORD_TIMEOUT)
7088        && let Some((kind, used)) = parse_timeout_single(rhs, 0, stmt, ctx)?
7089    {
7090        let span = lowering_ctx(stmt);
7091        crate::commands::reject_async_in_capture(&span, &kind).map_err(|e| TokenError {
7092            stmt,
7093            msg: e.to_string(),
7094            line: 0,
7095            col: 0,
7096            kind: None,
7097        })?;
7098        crate::commands::reject_pipe_stdout_in_capture(&span, &kind).map_err(|e| TokenError {
7099            stmt,
7100            msg: e.to_string(),
7101            line: 0,
7102            col: 0,
7103            kind: None,
7104        })?;
7105        return Ok((
7106            StepKind::AssignCapture {
7107                var,
7108                decl_type,
7109                cmd: Box::new(kind),
7110            },
7111            skipped + used,
7112        ));
7113    }
7114    // `AWAIT $v` captures the task output (`$`+name ride gapless in
7115    // this atomic position, like the grammar); anything else
7116    // `AWAIT`-led goes generic below (lowering fails it, probed).
7117    if head_word.as_deref() == Some(KEYWORD_AWAIT)
7118        && rhs.len() == 3
7119        && let (Some(dollar), Some(task)) = (rhs.get(1), rhs.get(2))
7120        && matches!(&dollar.kind, TokKind::Punct('$'))
7121        && task.joint
7122        && let TokKind::Word(task_var) = &task.kind
7123        && is_ident_word(task_var)
7124    {
7125        return Ok((
7126            StepKind::AwaitCapture {
7127                out_var: var,
7128                out_type: decl_type,
7129                task_var: task_var.clone(),
7130            },
7131            skipped + 3,
7132        ));
7133    }
7134    // RUN exec form captures the structured argv (gapped bracket;
7135    // a joint bracket falls through to generic, which fails it in
7136    // lowering).
7137    if head_word.as_deref() == Some(KEYWORD_RUN)
7138        && matches!(
7139            rhs.get(1).map(|t| (&t.kind, t.joint)),
7140            Some((
7141                TokKind::Group {
7142                    delim: GroupDelim::Bracket,
7143                    ..
7144                },
7145                false
7146            ))
7147        )
7148        && rhs.len() == 2
7149    {
7150        let inner = match &rhs[1].kind {
7151            TokKind::Group { inner, .. } => inner.clone(),
7152            _ => unreachable!(),
7153        };
7154        // Non-map blocks miss the exec shape; fall through below
7155        // (known-command capture, then expression), mirroring the
7156        // grammar's ordered alternatives.
7157        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
7158            let kind =
7159                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
7160            return Ok((
7161                StepKind::AssignCapture {
7162                    var,
7163                    decl_type,
7164                    cmd: Box::new(kind),
7165                },
7166                skipped + 2,
7167            ));
7168        }
7169    }
7170    // File `IMPORT ["path" AS ALIAS]` (#115) captures the imported
7171    // pipeline's `RETURN` value like a call (`LET $r: STRING = IMPORT ...`
7172    // lowers to `AssignCapture`): exactly one file entry, no modules.
7173    // Anything else shaped like an import is a hard error; shape misses
7174    // fall through to generic below, which fails them in lowering.
7175    if head_word.as_deref() == Some(KEYWORD_IMPORT)
7176        && let Some((path, alias, used)) = parse_single_file_import(rhs, 0, stmt, ctx)?
7177    {
7178        return Ok((
7179            StepKind::AssignCapture {
7180                var,
7181                decl_type,
7182                cmd: Box::new(StepKind::ImportFile { path, alias }),
7183            },
7184            skipped + used,
7185        ));
7186    }
7187    // Known-command leads capture through the generic parser
7188    // (lowering failures are fatal here, exactly like the committed
7189    // grammar alternative: probed wrapper-alone and `ISOLATED`-led
7190    // shapes error in lowering); unknown leads parse as expressions.
7191    match &head_word {
7192        Some(head) if is_known_command(head) => {
7193            let (cmd, used) = parse_inner_command(rhs, stmt, ctx)?;
7194            let span = lowering_ctx(stmt);
7195            crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| TokenError {
7196                stmt,
7197                msg: e.to_string(),
7198                line: 0,
7199                col: 0,
7200                kind: None,
7201            })?;
7202            crate::commands::reject_pipe_stdout_in_capture(&span, &cmd).map_err(|e| {
7203                TokenError {
7204                    stmt,
7205                    msg: e.to_string(),
7206                    line: 0,
7207                    col: 0,
7208                    kind: None,
7209                }
7210            })?;
7211            // `INHERIT_ENV`-led lines land here (generic): the
7212            // nesting check rejects them (probed).
7213            crate::commands::reject_nested_inherit_env(&span, &cmd).map_err(|e| TokenError {
7214                stmt,
7215                msg: e.to_string(),
7216                line: 0,
7217                col: 0,
7218                kind: None,
7219            })?;
7220            return Ok((
7221                StepKind::AssignCapture {
7222                    var,
7223                    decl_type,
7224                    cmd: Box::new(cmd),
7225                },
7226                skipped + used,
7227            ));
7228        }
7229        _ => {}
7230    }
7231    let mut cur = Cursor::expr(rhs, stmt);
7232    let expr = parse_expr_checked(&mut cur, ctx)?;
7233    let used = skipped + cur.pos;
7234    Ok((
7235        StepKind::Assign {
7236            var,
7237            decl_type,
7238            expr,
7239        },
7240        used,
7241    ))
7242}
7243
7244/// `WITH_IO`-led LET right-hand side, mirroring
7245/// `parse_let_async_statement_from_pair`'s `with_io_command` branch:
7246/// wrapping `ASYNC` binds a pipe-wired background task (multi-step
7247/// blocks fail loudly), wrapping a sync command captures its stdout
7248/// (async bodies and `stdout` pipes fail loudly), and a bare
7249/// bracket fails validation. `None` on shape miss (bad bracket:
7250/// the caller goes generic, which fails in lowering).
7251fn try_let_with_io_rhs(
7252    rhs: &[Tok],
7253    var: String,
7254    decl_type: String,
7255    stmt: usize,
7256    ctx: &ParseCtx,
7257) -> Result<Option<(StepKind, usize)>, TokenError> {
7258    let bracket = match rhs.get(1) {
7259        Some(t)
7260            if !t.joint
7261                && matches!(
7262                    &t.kind,
7263                    TokKind::Group {
7264                        delim: GroupDelim::Bracket,
7265                        ..
7266                    }
7267                ) =>
7268        {
7269            t
7270        }
7271        _ => return Ok(None),
7272    };
7273    let inner = match &bracket.kind {
7274        TokKind::Group { inner, .. } => inner.clone(),
7275        _ => unreachable!(),
7276    };
7277    let bindings = match parse_io_bindings(&inner, stmt)? {
7278        Some(bindings) => bindings,
7279        None => return Ok(None),
7280    };
7281    let fail = |msg: String| TokenError {
7282        stmt,
7283        msg,
7284        line: 0,
7285        col: 0,
7286        kind: None,
7287    };
7288    let rest = &rhs[2..];
7289    let Some(first) = rest.first() else {
7290        // Bare bracket: the grammar's committed validation error.
7291        return Err(fail(
7292            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7293                .to_string(),
7294        ));
7295    };
7296    if first.joint {
7297        // The inner rides after a `sep`: joint followers miss the
7298        // shape and fail validation like the grammar's bare bracket.
7299        return Err(fail(
7300            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7301                .to_string(),
7302        ));
7303    }
7304    if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_ASYNC) {
7305        // `WITH_IO [..] ASYNC <single|block>`: the bindings apply
7306        // inside the task thread (same shape as a one-step body
7307        // holding one `WITH_IO` step, which the runtime supports).
7308        // A bare `ASYNC` goes generic and fails in lowering
7309        // (`unknown command: ASYNC`, probed).
7310        let after = &rest[1..];
7311        if after.is_empty() {
7312            // Bare `ASYNC`: the grammar commits to `instruction`
7313            // and lowering fails it (`unknown command: ASYNC`,
7314            // probed); mirror by running generic, staying failed
7315            // even under a lenient dispatcher.
7316            match parse_inner_command(&rest[..1], stmt, ctx) {
7317                Err(e) => return Err(e),
7318                Ok(_) => {
7319                    return Err(fail(
7320                        "LET $var: HANDLE<T> = ASYNC requires a body".to_string(),
7321                    ));
7322                }
7323            }
7324        }
7325        if let Some(second) = after.first()
7326            && matches!(
7327                &second.kind,
7328                TokKind::Group {
7329                    delim: GroupDelim::Brace,
7330                    ..
7331                }
7332            )
7333            && !is_template_brace(second)
7334        {
7335            let brace_inner = match &second.kind {
7336                TokKind::Group { inner, .. } => inner.clone(),
7337                _ => unreachable!(),
7338            };
7339            let body = parse_body_steps(&brace_inner, stmt, ctx, false)?;
7340            if body.len() != 1 {
7341                return Err(fail(
7342                        "LET $var: TYPE = WITH_IO [..] ASYNC accepts a single command; use LET $var: HANDLE<T> = ASYNC {{ ... }} with WITH_IO inside the block for multi-step tasks"
7343                            .to_string(),
7344                    ));
7345            }
7346            let wrapped = Step {
7347                guard: None,
7348                kind: StepKind::WithIo {
7349                    bindings,
7350                    cmd: Box::new(
7351                        body.into_iter()
7352                            .next()
7353                            .ok_or_else(|| {
7354                                fail("LET $var: HANDLE<T> = ASYNC requires a body".to_string())
7355                            })?
7356                            .kind,
7357                    ),
7358                },
7359                scope_enter: 0,
7360                scope_exit: 0,
7361                line: 0,
7362                col: 0,
7363            };
7364            return Ok(Some((
7365                StepKind::AssignAsync {
7366                    var,
7367                    decl_type,
7368                    body: vec![wrapped],
7369                },
7370                2 + 2,
7371            )));
7372        }
7373        if after.first().is_some_and(|t| t.joint) {
7374            // Joint followers miss the inner `sep`: same validation
7375            // error as the bare bracket.
7376            return Err(fail(
7377                "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7378                    .to_string(),
7379            ));
7380        }
7381        let (cmd, used) = parse_single_inner(
7382            rest,
7383            1,
7384            stmt,
7385            ctx,
7386            InnerRules {
7387                allow_await: false,
7388                allow_with_io: false,
7389            },
7390        )?;
7391        let wrapped = Step {
7392            guard: None,
7393            kind: StepKind::WithIo {
7394                bindings,
7395                cmd: Box::new(cmd),
7396            },
7397            scope_enter: 0,
7398            scope_exit: 0,
7399            line: 0,
7400            col: 0,
7401        };
7402        let kind = StepKind::AssignAsync {
7403            var,
7404            decl_type,
7405            body: vec![wrapped],
7406        };
7407        let span = lowering_ctx(stmt);
7408        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7409            stmt,
7410            msg: e.to_string(),
7411            line: 0,
7412            col: 0,
7413            kind: None,
7414        })?;
7415        return Ok(Some((kind, 2 + 1 + used)));
7416    }
7417    if matches!(
7418        &first.kind,
7419        TokKind::Group {
7420            delim: GroupDelim::Brace,
7421            ..
7422        }
7423    ) {
7424        // A brace is no sync command: same validation error (probed).
7425        return Err(fail(
7426            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7427                .to_string(),
7428        ));
7429    }
7430    // Sync inner: capture with the shared checks (the capture sink
7431    // owns stdout; async never runs inline).
7432    let (cmd, used) = parse_single_inner(
7433        rest,
7434        0,
7435        stmt,
7436        ctx,
7437        InnerRules {
7438            allow_await: false,
7439            allow_with_io: true,
7440        },
7441    )?;
7442    let span = lowering_ctx(stmt);
7443    if crate::commands::has_stdout_pipe(&bindings) {
7444        return Err(fail(
7445            "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
7446                .to_string(),
7447        ));
7448    }
7449    crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| TokenError {
7450        stmt,
7451        msg: e.to_string(),
7452        line: 0,
7453        col: 0,
7454        kind: None,
7455    })?;
7456    Ok(Some((
7457        StepKind::AssignCapture {
7458            var,
7459            decl_type,
7460            cmd: Box::new(StepKind::WithIo {
7461                bindings,
7462                cmd: Box::new(cmd),
7463            }),
7464        },
7465        2 + used,
7466    )))
7467}
7468
7469/// `ASYNC`-led LET right-hand side (the tokens after `ASYNC`):
7470/// a block or single command becomes the task body. No `WITH_IO`
7471/// scan (probed: this path accepts what statement `ASYNC`
7472/// rejects); nesting still fails loudly through the shared check.
7473fn parse_let_async_rhs(
7474    rest: &[Tok],
7475    var: String,
7476    decl_type: String,
7477    stmt: usize,
7478    ctx: &ParseCtx,
7479) -> Result<(StepKind, usize), TokenError> {
7480    let Some(first) = rest.first() else {
7481        return Err(TokenError {
7482            stmt,
7483            msg: "LET $var: HANDLE<T> = ASYNC requires a body".to_string(),
7484            line: 0,
7485            col: 0,
7486            kind: None,
7487        });
7488    };
7489    if matches!(
7490        &first.kind,
7491        TokKind::Group {
7492            delim: GroupDelim::Brace,
7493            ..
7494        }
7495    ) && !is_template_brace(first)
7496    {
7497        let inner = match &first.kind {
7498            TokKind::Group { inner, .. } => inner.clone(),
7499            _ => unreachable!(),
7500        };
7501        let body = parse_body_steps(&inner, stmt, ctx, false)?;
7502        let kind = StepKind::AssignAsync {
7503            var,
7504            decl_type,
7505            body,
7506        };
7507        let span = lowering_ctx(stmt);
7508        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7509            stmt,
7510            msg: e.to_string(),
7511            line: 0,
7512            col: 0,
7513            kind: None,
7514        })?;
7515        return Ok((kind, 1));
7516    }
7517    if first.joint {
7518        return Err(TokenError {
7519            stmt,
7520            msg: "LET $var: HANDLE<T> = ASYNC requires a body".to_string(),
7521            line: 0,
7522            col: 0,
7523            kind: None,
7524        });
7525    }
7526    let (cmd, used) = parse_single_inner(
7527        rest,
7528        0,
7529        stmt,
7530        ctx,
7531        InnerRules {
7532            allow_await: false,
7533            allow_with_io: false,
7534        },
7535    )?;
7536    let kind = StepKind::AssignAsync {
7537        var,
7538        decl_type,
7539        body: vec![Step {
7540            guard: None,
7541            kind: cmd,
7542            scope_enter: 0,
7543            scope_exit: 0,
7544            line: 0,
7545            col: 0,
7546        }],
7547    };
7548    let span = lowering_ctx(stmt);
7549    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7550        stmt,
7551        msg: e.to_string(),
7552        line: 0,
7553        col: 0,
7554        kind: None,
7555    })?;
7556    Ok((kind, used))
7557}
7558
7559fn parse_set_body(
7560    body: &[Tok],
7561    stmt: usize,
7562    ctx: &ParseCtx,
7563) -> Result<(StepKind, usize), TokenError> {
7564    let mut cur = Cursor::expr(body, stmt);
7565    let var = expect_dollar_var(&mut cur, "mutation requires a variable: $var = <expr>")?;
7566    let assign = find_assign_eq(&body[cur.pos..]).map(|i| i + cur.pos);
7567    let eq = match assign {
7568        Some(eq) => eq,
7569        None => {
7570            return Err(cur.err("mutation requires a variable: $var = <expr>"));
7571        }
7572    };
7573    cur.pos = eq + 1;
7574    // Leading gap comments vanish like the `=` gap.
7575    cur.skip_gap();
7576    let expr = parse_expr_checked(&mut cur, ctx)?;
7577    Ok((StepKind::Set { var, expr }, cur.pos))
7578}
7579
7580fn parse_return_body(
7581    body: &[Tok],
7582    stmt: usize,
7583    ctx: &ParseCtx,
7584) -> Result<(StepKind, usize), TokenError> {
7585    let mut cur = Cursor::expr(body, stmt);
7586    match cur.next() {
7587        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_RETURN) => {}
7588        _ => return Err(cur.err("unreachable")),
7589    }
7590    if cur.done() {
7591        return Ok((
7592            StepKind::Return {
7593                expr: Box::new(Expr::Literal(Value::string(String::new()))),
7594                is_bare: true,
7595            },
7596            cur.pos,
7597        ));
7598    }
7599    let expr = parse_expr_checked(&mut cur, ctx)?;
7600    Ok((
7601        StepKind::Return {
7602            expr: Box::new(expr),
7603            is_bare: false,
7604        },
7605        cur.pos,
7606    ))
7607}
7608
7609/// Lower one statement to steps through the element loop: the
7610/// statement guard attaches to the first element only (trailing
7611/// elements ride guardless, probed): the pending guard clears after
7612/// the first command token.
7613fn lower_stmt_steps(
7614    stmt: &Stmt,
7615    idx: usize,
7616    ctx: &ParseCtx,
7617    in_block: bool,
7618    mark: bool,
7619) -> Result<Vec<Step>, TokenError> {
7620    let guard = parse_guard_groups(&stmt.guard, idx)?;
7621    // Statement-head braces route here (mid-run braces fail inside
7622    // the element loop): templates and guardless/bare blocks fail
7623    // loudly; guarded braces open guard blocks (top level) or the
7624    // nested quirk (in bodies).
7625    let mut steps = if starts_brace(&stmt.body) {
7626        parse_brace_head(stmt, guard, idx, ctx, in_block, mark)?
7627    } else {
7628        parse_elements(&stmt.body, idx, ctx, guard, in_block)?
7629    };
7630    // Stamp the statement's source position on every directly
7631    // produced step still missing one. Nested body steps were stamped
7632    // by their own statements during recursion, so only direct
7633    // products are claimed here; inner statements keep their own
7634    // lines and columns.
7635    for step in &mut steps {
7636        if step.line == 0 {
7637            step.line = stmt.line;
7638        }
7639        if step.col == 0 {
7640            step.col = stmt.col;
7641        }
7642    }
7643    // Qualify bare placeholder calls (`{{ NAME(args) }}`) through
7644    // the shared static resolver, so templates obey exactly the
7645    // statement-position scope rule. Nested bodies were already
7646    // qualified by their own recursive statements with their own
7647    // frames, so only direct products are visited here. Both
7648    // `Arg::String` fragments (via `walk_raw_strings_mut`) and
7649    // `Expr::Literal` strings (LET/SET/RETURN/call args/list/map
7650    // literals/parenthesized args) are qualified: expression
7651    // positions expand through the same `expand_string` at runtime,
7652    // so they must see the same parse-time rewrite. `WithIo` and
7653    // `AssignCapture` box their inner command directly (no recursive
7654    // statement pass), so the helper descends into them; all other
7655    // bodies were already qualified with their own frames.
7656    // `Step.guards` carry no template text (`Guard::Attr` triples
7657    // evaluated via `guard_allows`, never expanded), so there is
7658    // nothing to qualify there.
7659    let mut failed: Option<TokenError> = None;
7660    for step in &mut steps {
7661        qualify_step_templates(step, ctx, idx, &mut failed);
7662        if failed.is_some() {
7663            break;
7664        }
7665    }
7666    if let Some(err) = failed {
7667        return Err(err);
7668    }
7669    Ok(steps)
7670}
7671
7672/// Qualify one direct statement product plus any boxed `WithIo` /
7673/// `AssignCapture` inner command (same scope frame, never a
7674/// recursive statement pass). Body vectors are skipped: their steps
7675/// were qualified by their own recursive statements.
7676fn qualify_step_templates(
7677    step: &mut Step,
7678    ctx: &ParseCtx,
7679    stmt: usize,
7680    failed: &mut Option<TokenError>,
7681) {
7682    qualify_kind_templates(&mut step.kind, ctx, stmt, failed);
7683}
7684
7685/// Qualify one `StepKind` plus boxed inner commands sharing the
7686/// same scope frame.
7687fn qualify_kind_templates(
7688    kind: &mut StepKind,
7689    ctx: &ParseCtx,
7690    stmt: usize,
7691    failed: &mut Option<TokenError>,
7692) {
7693    kind.walk_raw_strings_mut(&mut |text| {
7694        if failed.is_none() {
7695            match qualify_template_calls(text, ctx, stmt) {
7696                Ok(Some(rewritten)) => *text = rewritten,
7697                Ok(None) => {}
7698                Err(err) => *failed = Some(err),
7699            }
7700        }
7701    });
7702    if failed.is_some() {
7703        return;
7704    }
7705    kind.walk_exprs_mut(&mut |expr| {
7706        if failed.is_some() {
7707            return;
7708        }
7709        expr.walk_mut(&mut |node| {
7710            if failed.is_some() {
7711                return;
7712            }
7713            if let Expr::Literal(value) = node
7714                && let Some(text) = value.as_str()
7715            {
7716                match qualify_template_calls(text, ctx, stmt) {
7717                    Ok(Some(rewritten)) => {
7718                        *value = Value::string(rewritten);
7719                    }
7720                    Ok(None) => {}
7721                    Err(err) => *failed = Some(err),
7722                }
7723            }
7724        });
7725    });
7726    if failed.is_some() {
7727        return;
7728    }
7729    // Boxed single commands share the outer scope frame (no recursive
7730    // statement pass built them): qualify the inner kind directly.
7731    match kind {
7732        StepKind::WithIo { cmd, .. } | StepKind::AssignCapture { cmd, .. } => {
7733            qualify_kind_templates(cmd, ctx, stmt, failed);
7734        }
7735        _ => {}
7736    }
7737    if failed.is_some() {
7738        return;
7739    }
7740    // Single-command synthetic bodies share the outer frame: `TIMEOUT 5s
7741    // <cmd>`, `ISOLATED <cmd>`, `ASYNC <cmd>`, and `AssignAsync` wrappers
7742    // build their `body` inline via `parse_single_inner` with no recursive
7743    // `lower_stmt_steps` pass, so their one synthetic step needs this one.
7744    // Brace-delimited bodies are NEVER re-walked here: they were already
7745    // lowered via `parse_body_steps` with their own frames and statement
7746    // indices (mirroring `Expr::walk_mut` skipping `Expr::Block`), and
7747    // re-resolving under the outer frame would corrupt scope isolation
7748    // and error attribution. The match names only the synthetic carriers;
7749    // any other body (If/For/While/FuncDef/RemoteBlock/WithIoBlock) stays
7750    // exactly as its own recursive pass left it.
7751    match kind {
7752        StepKind::Timeout { body, .. }
7753        | StepKind::Isolated { body }
7754        | StepKind::AsyncBlock { body }
7755        | StepKind::AssignAsync { body, .. } => {
7756            for step in body.iter_mut() {
7757                if failed.is_some() {
7758                    return;
7759                }
7760                qualify_step_templates(step, ctx, stmt, failed);
7761            }
7762        }
7763        _ => {}
7764    }
7765}
7766
7767/// Statement-head `{...}` dispatcher. Template braces fail (the
7768/// grammar strands them); guardless top-level braces fail; detached
7769/// or guardless in-body braces fail (no `block_start` in
7770/// `block_element`); guarded braces open a guard scope at top level
7771/// or mirror the nested quirk formula in bodies. Trailing elements
7772/// loop on guardless outside (like the grammar's continued line).
7773fn parse_brace_head(
7774    stmt: &Stmt,
7775    guard: Option<GuardExpr>,
7776    idx: usize,
7777    ctx: &ParseCtx,
7778    in_block: bool,
7779    mark: bool,
7780) -> Result<Vec<Step>, TokenError> {
7781    let brace = &stmt.body[0];
7782    if is_template_brace(brace) {
7783        return Err(TokenError {
7784            stmt: idx,
7785            msg: "'{' without a pending guard".to_string(),
7786            line: 0,
7787            col: 0,
7788            kind: None,
7789        });
7790    }
7791    let inner = match &brace.kind {
7792        TokKind::Group { inner, .. } => inner.clone(),
7793        _ => unreachable!(),
7794    };
7795    if in_block {
7796        // Attached guarded braces only: pending holds all groups but
7797        // the last (the block's own), mirroring the pair structure.
7798        if guard.is_none() || stmt.brace_detached || stmt.guard.is_empty() {
7799            return Err(TokenError {
7800                stmt: idx,
7801                msg: "unexpected '{' in block body".to_string(),
7802                line: 0,
7803                col: 0,
7804                kind: None,
7805            });
7806        }
7807        let n = stmt.guard.len();
7808        let mut pending = None;
7809        if n > 1 {
7810            pending = parse_guard_groups(&stmt.guard[..n - 1], idx)?;
7811        }
7812        let block_guard = parse_guard_groups(&stmt.guard[n - 1..n], idx)?.ok_or(TokenError {
7813            stmt: idx,
7814            msg: "unexpected '{' in block body".to_string(),
7815            line: 0,
7816            col: 0,
7817            kind: None,
7818        })?;
7819        let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
7820        // Guard-block bodies propagate the ambient marking context
7821        // (top-level nesting marks; wrapper bodies never mark).
7822        // Quirk formula verbatim (including the dropped block guard
7823        // with inner guards, probed).
7824        for s in &mut steps {
7825            let inner_guard = s.guard.take();
7826            s.guard = Some(match (pending.clone(), inner_guard) {
7827                (Some(p), Some(e)) => GuardExpr::all(vec![p, e]),
7828                (Some(p), None) => GuardExpr::all(vec![p, block_guard.clone()]),
7829                (None, Some(e)) => e,
7830                (None, None) => block_guard.clone(),
7831            });
7832        }
7833        // Marking contexts bump each nesting level (probed top-level
7834        // double-block 2/2); wrapper bodies stay 0/0.
7835        // Trailing elements ride outside, unmarked.
7836        if mark {
7837            if let Some(first) = steps.first_mut() {
7838                first.scope_enter += 1;
7839            }
7840            if let Some(last) = steps.last_mut() {
7841                last.scope_exit += 1;
7842            }
7843        }
7844        // Trailing elements loop on guardless outside.
7845        if stmt.body.len() > 1 {
7846            let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
7847            steps.append(&mut rest);
7848        }
7849        return Ok(steps);
7850    }
7851    // Top level: guardless braces fail; guarded braces open a guard
7852    // scope (each step folds outer-then-inner with markers).
7853    let Some(outer) = guard else {
7854        return Err(TokenError {
7855            stmt: idx,
7856            msg: "'{' without a pending guard".to_string(),
7857            line: 0,
7858            col: 0,
7859            kind: None,
7860        });
7861    };
7862    let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
7863    if steps.is_empty() {
7864        return Err(TokenError {
7865            stmt: idx,
7866            msg: "guard block must contain at least one command".to_string(),
7867            line: 0,
7868            col: 0,
7869            kind: None,
7870        });
7871    }
7872    for s in &mut steps {
7873        let inner_guard = s.guard.take();
7874        s.guard = Some(match inner_guard {
7875            Some(e) => GuardExpr::all(vec![outer.clone(), e]),
7876            None => outer.clone(),
7877        });
7878    }
7879    if let Some(first) = steps.first_mut() {
7880        first.scope_enter += 1;
7881    }
7882    if let Some(last) = steps.last_mut() {
7883        last.scope_exit += 1;
7884    }
7885    if stmt.body.len() > 1 {
7886        let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
7887        steps.append(&mut rest);
7888    }
7889    Ok(steps)
7890}
7891
7892/// Parse consecutive elements to end of run (the grammar's
7893/// `element*`): structural pairs (calls, RUN-exec, await/cancel,
7894/// wrapper blocks) end mid-run and trailing elements form following
7895/// steps; instructions and expressions consume greedily to the end.
7896fn parse_elements(
7897    toks: &[Tok],
7898    stmt: usize,
7899    ctx: &ParseCtx,
7900    guard: Option<GuardExpr>,
7901    in_block: bool,
7902) -> Result<Vec<Step>, TokenError> {
7903    let mut steps = Vec::new();
7904    let mut pos = 0;
7905    // Statement guard: consumed by the first element that yields a
7906    // step. `IMPORT` yields none, so the guard leaks to the next
7907    // element (probed).
7908    let mut pending_guard: Option<GuardExpr> = guard;
7909    while pos < toks.len() {
7910        // Trailing gap comments between elements (`} #c`, `F("a")
7911        // /*c*/ ECHO`, `LET $x: INT = 1 //c` — the pair ended, so the
7912        // comment is silent like the grammar, never payload):
7913        // `#` and lexer `Comment` markers run to the run end, `//`
7914        // likewise (line comments eat `;` too, and runs hold no
7915        // newlines), `/* */` balances. Mid-run `#`/`/*` stay payload
7916        // text inside the generic path, which consumes everything
7917        // and never loops back here.
7918        if matches!(&toks[pos].kind, TokKind::Punct('#'))
7919            || matches!(&toks[pos].kind, TokKind::Comment(_))
7920        {
7921            break;
7922        }
7923        if matches!(&toks[pos].kind, TokKind::Punct('/')) && is_comment_open(toks, pos) {
7924            if matches!(
7925                toks.get(pos + 1).map(|t| &t.kind),
7926                Some(TokKind::Punct('/'))
7927            ) {
7928                break;
7929            }
7930            match skip_inline_comment(toks, pos) {
7931                Some(past) => {
7932                    pos = past;
7933                    continue;
7934                }
7935                None => {
7936                    return Err(TokenError {
7937                        stmt,
7938                        msg: "unclosed block comment".to_string(),
7939                        line: 0,
7940                        col: 0,
7941                        kind: None,
7942                    });
7943                }
7944            }
7945        }
7946        // `IMPORT` statements update the import frames; module entries
7947        // emit no step (the guard leaks to the next element, probed,
7948        // unless this is top level, where a guarded module import
7949        // fails), while each file entry emits one `ImportFile` step
7950        // carrying the guard. Shape misses fall through to generic
7951        // (lowering fails them).
7952        if matches!(
7953            toks.get(pos).map(|t| &t.kind),
7954            Some(TokKind::Word(w)) if w == KEYWORD_IMPORT
7955        ) {
7956            // Unified statement form (#115): each entry validates hard
7957            // (unknown modules, bad aliases, templates, remote URLs);
7958            // module entries update the frame and emit no step, file
7959            // and harvest entries emit one step each, in source order.
7960            // A top-level guard on a statement with module entries fails
7961            // like the historical directive; file-only statements consume
7962            // the guard like any other element.
7963            if let Some(((modules, kinds), used)) = parse_import_statement(toks, pos, stmt, ctx)? {
7964                if !modules.is_empty() && !in_block && pending_guard.is_some() {
7965                    return Err(TokenError {
7966                        stmt,
7967                        msg: "IMPORT cannot be guarded".to_string(),
7968                        line: 0,
7969                        col: 0,
7970                        kind: None,
7971                    });
7972                }
7973                // Modules-only statements stay zero-step directives: the
7974                // guard leaks to the next element (probed). Anything with
7975                // file or harvest entries consumes it.
7976                let guard = if kinds.is_empty() {
7977                    None
7978                } else {
7979                    pending_guard.take()
7980                };
7981                for kind in kinds {
7982                    steps.push(Step {
7983                        guard: guard.clone(),
7984                        kind,
7985                        scope_enter: 0,
7986                        scope_exit: 0,
7987                        line: 0,
7988                        col: 0,
7989                    });
7990                }
7991                pos += used;
7992                continue;
7993            }
7994        }
7995        let guard = pending_guard.take();
7996        let (mut got, used) = parse_element_at(toks, pos, stmt, ctx, guard, in_block)?;
7997        if used == 0 {
7998            return Err(TokenError {
7999                stmt,
8000                msg: "element consumed no input".to_string(),
8001                line: 0,
8002                col: 0,
8003                kind: None,
8004            });
8005        }
8006        steps.append(&mut got);
8007        pos += used;
8008    }
8009    Ok(steps)
8010}
8011
8012/// Parse one element at `pos`, returning built steps (guard already
8013/// assigned: `first_guard` for the first, folded per io-block inner
8014/// step) and tokens consumed.
8015fn parse_element_at(
8016    toks: &[Tok],
8017    pos: usize,
8018    stmt: usize,
8019    ctx: &ParseCtx,
8020    first_guard: Option<GuardExpr>,
8021    in_block: bool,
8022) -> Result<(Vec<Step>, usize), TokenError> {
8023    let step = |kind: StepKind| Step {
8024        guard: first_guard.clone(),
8025        kind,
8026        scope_enter: 0,
8027        scope_exit: 0,
8028        line: 0,
8029        col: 0,
8030    };
8031    let head_word = match toks.get(pos).map(|t| &t.kind) {
8032        Some(TokKind::Word(w)) => Some(w.clone()),
8033        _ => None,
8034    };
8035    // Mid-run `{...}` (after a call, wrapper block, ...): the
8036    // grammar strands it (`block_start` needs a pending guard or
8037    // `WITH_IO` wait, both consumed), so fail loudly. Statement-head
8038    // braces route through `lower_stmt_steps`, never here.
8039    if starts_brace(&toks[pos..]) {
8040        return Err(TokenError {
8041            stmt,
8042            msg: "'{' without a pending guard".to_string(),
8043            line: 0,
8044            col: 0,
8045            kind: None,
8046        });
8047    }
8048    // LET/SET/RETURN heads parse with groups intact, then trailing
8049    // elements loop on (probed `LET $x: INT = 1 ECHO bye`). LET shape
8050    // misses fall to generic (lowering fails them like a committed
8051    // `instruction` would, e.g. `LET foo`).
8052    if head_word.as_deref() == Some(KEYWORD_LET)
8053        && let Some((kind, used)) = parse_let_body(&toks[pos..], stmt, ctx)?
8054    {
8055        return Ok((vec![step(kind)], used));
8056    }
8057    if matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('$'))) {
8058        let (kind, used) = parse_set_body(&toks[pos..], stmt, ctx)?;
8059        return Ok((vec![step(kind)], used));
8060    }
8061    if head_word.as_deref() == Some(KEYWORD_RETURN) {
8062        let (kind, used) = parse_return_body(&toks[pos..], stmt, ctx)?;
8063        return Ok((vec![step(kind)], used));
8064    }
8065    // Calls route before heads (even known commands take the call
8066    // path with a joint paren, probed `ECHO("hi")`); the call ends
8067    // mid-run and trailing elements loop on (fixes the slice-4a
8068    // divergence, probed).
8069    if call_shape_at(toks, pos, true).is_some() {
8070        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8071        return Ok((vec![step(kind)], used));
8072    }
8073    // Block statements (shape misses fall to generic, which fails
8074    // them in lowering like the grammar's committed `instruction`).
8075    // `BREAK`/`CONTINUE` take no args (structural, like the grammar):
8076    // each consumes one token and trailing elements loop on (probed
8077    // `BREAK ECHO hi`); a lone trailing word fails downstream like
8078    // the grammar's committed mismatch.
8079    match head_word.as_deref() {
8080        Some(KEYWORD_BREAK) => {
8081            return Ok((vec![step(StepKind::Break)], 1));
8082        }
8083        Some(KEYWORD_CONTINUE) => {
8084            return Ok((vec![step(StepKind::Continue)], 1));
8085        }
8086        Some(KEYWORD_IF) => {
8087            if let Some((kind, used)) = parse_if_at(toks, pos, stmt, ctx)? {
8088                return Ok((vec![step(kind)], used));
8089            }
8090        }
8091        Some(KEYWORD_SWITCH) => {
8092            if let Some((kind, used)) = parse_switch_at(toks, pos, stmt, ctx)? {
8093                return Ok((vec![step(kind)], used));
8094            }
8095        }
8096        Some(KEYWORD_FOR) => {
8097            if let Some((kind, used)) = parse_for_at(toks, pos, stmt, ctx)? {
8098                return Ok((vec![step(kind)], used));
8099            }
8100        }
8101        Some(KEYWORD_WHILE) => {
8102            if let Some((kind, used)) = parse_while_single(toks, pos, stmt, ctx)? {
8103                return Ok((vec![step(kind)], used));
8104            }
8105        }
8106        Some(KEYWORD_FUNC) => {
8107            if let Some((kind, used)) = parse_func_at(toks, pos, stmt, ctx, false)? {
8108                return Ok((vec![step(kind)], used));
8109            }
8110        }
8111        Some(KEYWORD_REMOTE) => {
8112            if let Some((kind, used)) = parse_remote_single(toks, pos, stmt, ctx)? {
8113                return Ok((vec![step(kind)], used));
8114            }
8115        }
8116        _ => {}
8117    }
8118    // Wrappers (block or single); shape misses fall to generic.
8119    match head_word.as_deref() {
8120        Some(KEYWORD_WITH_IO) => {
8121            return parse_with_io_element(toks, pos, stmt, ctx, first_guard);
8122        }
8123        Some(KEYWORD_TIMEOUT) => {
8124            if let Some((kind, used)) = parse_timeout_single(toks, pos, stmt, ctx)? {
8125                return Ok((vec![step(kind)], used));
8126            }
8127        }
8128        Some(KEYWORD_ISOLATED) => {
8129            if let Some((kind, used)) = parse_isolated_single(toks, pos, stmt, ctx)? {
8130                return Ok((vec![step(kind)], used));
8131            }
8132        }
8133        Some(KEYWORD_ASYNC) => {
8134            // ASYNC FUNC definition form: prefix, parser records is_async
8135            // with no type-constraint validation (checker owns HANDLE rule).
8136            if matches!(toks.get(pos + 1).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC)
8137                && let Some((kind, used)) = parse_func_at(toks, pos + 1, stmt, ctx, true)?
8138            {
8139                return Ok((vec![step(kind)], 1 + used));
8140            }
8141            if let Some((kind, used)) = parse_async_single(toks, pos, stmt, ctx)? {
8142                return Ok((vec![step(kind)], used));
8143            }
8144        }
8145        _ => {}
8146    }
8147    // AWAIT/CANCEL statements (element level admits the `$` gap,
8148    // probed); heads without `$` go generic (lowering fails them).
8149    if matches!(
8150        head_word.as_deref(),
8151        Some(KEYWORD_AWAIT) | Some(KEYWORD_CANCEL)
8152    ) && let Some((kind, used)) = parse_await_cancel_at(toks, pos, stmt, false)?
8153    {
8154        return Ok((vec![step(kind)], used));
8155    }
8156    // `INHERIT_ENV [...]` parses strictly even at element level
8157    // (keys stay exact everywhere; slice 5 adds only the
8158    // prelude-order validation). Shape misses go generic.
8159    if head_word.as_deref() == Some(KEYWORD_INHERIT_ENV)
8160        && let Some((kind, used)) = parse_inherit_env_at(toks, pos, stmt)?
8161    {
8162        return Ok((vec![step(kind)], used));
8163    }
8164    // `EXPORT ...` records names (zero steps) or misses to generic;
8165    // level and guard violations fail loudly like the backend.
8166    if head_word.as_deref() == Some(KEYWORD_EXPORT) {
8167        if in_block {
8168            return Err(TokenError {
8169                stmt,
8170                msg: "EXPORT is only allowed at the top level".to_string(),
8171                line: 0,
8172                col: 0,
8173                kind: None,
8174            });
8175        }
8176        if first_guard.is_some() {
8177            return Err(TokenError {
8178                stmt,
8179                msg: "EXPORT cannot be guarded".to_string(),
8180                line: 0,
8181                col: 0,
8182                kind: None,
8183            });
8184        }
8185        if let Some((
8186            ExportNames {
8187                func_names,
8188                type_names,
8189            },
8190            used,
8191        )) = parse_export_at(toks, pos)
8192        {
8193            for name in &func_names {
8194                for part in name.split(MODULE_SEPARATOR) {
8195                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8196                        .map_err(|e| lower_err(stmt, e))?;
8197                }
8198                if ctx.func_exports.borrow().contains(name)
8199                    || ctx.type_exports.borrow().contains(name)
8200                {
8201                    return Err(TokenError {
8202                        stmt,
8203                        msg: format!("duplicate EXPORT `{name}`"),
8204                        line: 0,
8205                        col: 0,
8206                        kind: Some(ParseErrorKind::Validation {
8207                            command: KEYWORD_EXPORT.to_string(),
8208                        }),
8209                    });
8210                }
8211                ctx.func_exports.borrow_mut().push(name.clone());
8212            }
8213            for name in &type_names {
8214                for part in name.split(MODULE_SEPARATOR) {
8215                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8216                        .map_err(|e| lower_err(stmt, e))?;
8217                }
8218                if ctx.func_exports.borrow().contains(name)
8219                    || ctx.type_exports.borrow().contains(name)
8220                {
8221                    return Err(TokenError {
8222                        stmt,
8223                        msg: format!("duplicate EXPORT `{name}`"),
8224                        line: 0,
8225                        col: 0,
8226                        kind: Some(ParseErrorKind::Validation {
8227                            command: KEYWORD_EXPORT.to_string(),
8228                        }),
8229                    });
8230                }
8231                ctx.type_exports.borrow_mut().push(name.clone());
8232            }
8233            return Ok((Vec::new(), used));
8234        }
8235    }
8236    // `TYPE NAME = SHAPE` aliases (zero or one step); level and guard
8237    // violations fail loudly, shape misses fall to generic.
8238    if head_word.as_deref() == Some(KEYWORD_TYPE) {
8239        if in_block {
8240            return Err(TokenError {
8241                stmt,
8242                msg: "TYPE must appear at top level".to_string(),
8243                line: 0,
8244                col: 0,
8245                kind: None,
8246            });
8247        }
8248        if first_guard.is_some() {
8249            return Err(TokenError {
8250                stmt,
8251                msg: "TYPE cannot be guarded".to_string(),
8252                line: 0,
8253                col: 0,
8254                kind: None,
8255            });
8256        }
8257        if let Some((kind, used)) = parse_type_stmt_at(toks, pos, stmt)? {
8258            return Ok((vec![step(kind)], used));
8259        }
8260    }
8261    // Lowercase heads name their uppercase form (the grammar's
8262    // `command_name` mismatch): never a bare unknown-command.
8263    if let Some(head) = head_word.as_deref()
8264        && head.chars().all(|c| c.is_ascii_lowercase())
8265        && let upper = head.to_ascii_uppercase()
8266        && (is_known_command(&upper) || crate::STRUCTURAL_KEYWORDS.contains(&upper.as_str()))
8267    {
8268        return Err(TokenError {
8269            stmt,
8270            msg: format!("command must be uppercase: found `{head}`, expected `{upper}`"),
8271            line: 0,
8272            col: 0,
8273            kind: Some(ParseErrorKind::Syntax),
8274        });
8275    }
8276    // RUN-exec ends mid-run (trailing loops on, probed); generic
8277    // instructions consume everything.
8278    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8279    Ok((vec![step(kind)], used))
8280}
8281
8282/// Element-level `WITH_IO`: a same-run brace (any gap: `]{` works,
8283/// probed) opens the io-block form, wrapping every inner step with
8284/// scope markers; a joint non-brace follower is the pending-guard
8285/// error (the splitter only holds bare brackets); anything else is
8286/// the single form. Shape misses go generic.
8287fn parse_with_io_element(
8288    toks: &[Tok],
8289    pos: usize,
8290    stmt: usize,
8291    ctx: &ParseCtx,
8292    first_guard: Option<GuardExpr>,
8293) -> Result<(Vec<Step>, usize), TokenError> {
8294    // The bracket rides gapped (`sep`); anything else misses the
8295    // shape and generic fails it in lowering.
8296    let bracket = match toks.get(pos + 1) {
8297        Some(t)
8298            if !t.joint
8299                && matches!(
8300                    &t.kind,
8301                    TokKind::Group {
8302                        delim: GroupDelim::Bracket,
8303                        ..
8304                    }
8305                ) =>
8306        {
8307            Some(t)
8308        }
8309        _ => None,
8310    };
8311    let Some(bracket) = bracket else {
8312        // Shape miss: generic fails it in lowering.
8313        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8314        return Ok((
8315            vec![Step {
8316                guard: first_guard,
8317                kind,
8318                scope_enter: 0,
8319                scope_exit: 0,
8320                line: 0,
8321                col: 0,
8322            }],
8323            used,
8324        ));
8325    };
8326    let inner = match &bracket.kind {
8327        TokKind::Group { inner, .. } => inner.clone(),
8328        _ => unreachable!(),
8329    };
8330    let bindings = match parse_io_bindings(&inner, stmt)? {
8331        Some(bindings) => bindings,
8332        // Shape miss: generic fails it.
8333        None => {
8334            let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8335            return Ok((
8336                vec![Step {
8337                    guard: first_guard,
8338                    kind,
8339                    scope_enter: 0,
8340                    scope_exit: 0,
8341                    line: 0,
8342                    col: 0,
8343                }],
8344                used,
8345            ));
8346        }
8347    };
8348    let rest = pos + 2;
8349    // Same-run brace opens the io-block form (block-expanded
8350    // bindings skip the tty checks: the runtime repeats them).
8351    if let Some(next) = toks.get(rest)
8352        && matches!(
8353            &next.kind,
8354            TokKind::Group {
8355                delim: GroupDelim::Brace,
8356                ..
8357            }
8358        )
8359        && !is_template_brace(next)
8360    {
8361        let brace_inner = match &next.kind {
8362            TokKind::Group { inner, .. } => inner.clone(),
8363            _ => unreachable!(),
8364        };
8365        let mut steps = parse_body_steps(&brace_inner, stmt, ctx, false)?;
8366        if steps.is_empty() {
8367            return Err(TokenError {
8368                stmt,
8369                msg: "WITH_IO block must contain at least one command".to_string(),
8370                line: 0,
8371                col: 0,
8372                kind: None,
8373            });
8374        }
8375        // Every inner step wraps (merging when already wrapped,
8376        // like nested io scopes); the line guard folds into each
8377        // inner guard, inner-first (probed fold order).
8378        for s in &mut steps {
8379            let merged = match std::mem::replace(&mut s.kind, StepKind::Continue) {
8380                StepKind::WithIo {
8381                    bindings: inner_bindings,
8382                    cmd,
8383                } => StepKind::WithIo {
8384                    bindings: crate::commands::merge_bindings(&bindings, &inner_bindings),
8385                    cmd,
8386                },
8387                other => StepKind::WithIo {
8388                    bindings: bindings.clone(),
8389                    cmd: Box::new(other),
8390                },
8391            };
8392            s.kind = merged;
8393            s.guard = crate::commands::and_guard_exprs(s.guard.take(), first_guard.clone());
8394        }
8395        let span = lowering_ctx(stmt);
8396        for s in &steps {
8397            crate::commands::reject_nested_inherit_env(&span, &s.kind).map_err(|e| TokenError {
8398                stmt,
8399                msg: e.to_string(),
8400                line: 0,
8401                col: 0,
8402                kind: None,
8403            })?;
8404        }
8405        if let Some(first) = steps.first_mut() {
8406            first.scope_enter += 1;
8407        }
8408        if let Some(last) = steps.last_mut() {
8409            last.scope_exit += 1;
8410        }
8411        return Ok((steps, rest + 1 - pos));
8412    }
8413    if rest >= toks.len() {
8414        // Unreachable: the splitter holds bare brackets for `{`.
8415        // Kept for body-parsed runs, mirroring the transient node.
8416        return Ok((
8417            vec![Step {
8418                guard: first_guard,
8419                kind: StepKind::WithIoBlock { bindings },
8420                scope_enter: 0,
8421                scope_exit: 0,
8422                line: 0,
8423                col: 0,
8424            }],
8425            2,
8426        ));
8427    }
8428    // A joint follower misses the inner `sep`: the pending wait
8429    // fails exactly like the grammar.
8430    if toks[rest].joint {
8431        return Err(TokenError {
8432            stmt,
8433            msg: "WITH_IO block must be followed by '{'".to_string(),
8434            line: 0,
8435            col: 0,
8436            kind: None,
8437        });
8438    }
8439    // Single form, shared with single-inner (element guards the step).
8440    let (cmd, used) = parse_single_inner(
8441        toks,
8442        rest,
8443        stmt,
8444        ctx,
8445        InnerRules {
8446            allow_await: false,
8447            allow_with_io: true,
8448        },
8449    )?;
8450    let span = lowering_ctx(stmt);
8451    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| TokenError {
8452        stmt,
8453        msg: e.to_string(),
8454        line: 0,
8455        col: 0,
8456        kind: None,
8457    })?;
8458    let kind = StepKind::WithIo {
8459        bindings,
8460        cmd: Box::new(cmd),
8461    };
8462    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
8463        stmt,
8464        msg: e.to_string(),
8465        line: 0,
8466        col: 0,
8467        kind: None,
8468    })?;
8469    Ok((
8470        vec![Step {
8471            guard: first_guard,
8472            kind,
8473            scope_enter: 0,
8474            scope_exit: 0,
8475            line: 0,
8476            col: 0,
8477        }],
8478        2 + used,
8479    ))
8480}
8481
8482/// Shared inner-command parser: statement calls (joint paren, even on
8483/// known commands), RUN exec
8484/// form, and generic instructions. Returns the kind and tokens
8485/// consumed: calls and RUN-exec end mid-run (the caller continues
8486/// past them, like the grammar's `element*`); generic instructions
8487/// consume everything. Wrappers never route here (element and
8488/// single-inner dispatch own them); slice 4b reuses the call/RUN
8489/// arms for trailing elements.
8490fn parse_inner_command(
8491    body: &[Tok],
8492    stmt: usize,
8493    ctx: &ParseCtx,
8494) -> Result<(StepKind, usize), TokenError> {
8495    // Bare `NAME(...)` calls invoke functions with one syntax; the head
8496    // and `(` ride gapless or the shape stays an instruction (which
8497    // fails later as UnknownCommand), exactly like the grammar.
8498    if let Some((call_name, paren)) = call_shape_at(body, 0, true) {
8499        let inner = match &body[paren].kind {
8500            TokKind::Group { inner, .. } => inner.clone(),
8501            _ => unreachable!(),
8502        };
8503        let args = parse_call_args(&inner, stmt, ctx)?;
8504        // Statement-level `INSPECT(...)` resolves like any other call
8505        // (only expression position mints the node); unknown functions
8506        // fail in the shared resolver with identical messages.
8507        if !call_name.contains(MODULE_SEPARATOR) {
8508            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
8509                .map_err(|e| lower_err(stmt, e))?;
8510        }
8511        let qualified = resolve_name(ctx, stmt, &call_name)?;
8512        return Ok((
8513            StepKind::Call {
8514                name: qualified,
8515                args,
8516            },
8517            paren + 1,
8518        ));
8519    }
8520    let head = match body.first().map(|t| &t.kind) {
8521        Some(TokKind::Word(n)) => n.clone(),
8522        _ => {
8523            return Err(TokenError {
8524                stmt,
8525                msg: "statement must open with a command word".to_string(),
8526                line: 0,
8527                col: 0,
8528                kind: None,
8529            });
8530        }
8531    };
8532    // RUN exec form: the list routes structured through `lower` (the
8533    // mock wraps it in `Run`; production maps it to `RunExec`); the
8534    // caller continues past the list, like the grammar. The list
8535    // rides gapped (`sep`): a joint bracket is a hard error, never
8536    // a spliced arg (probed `RUN["a"]`).
8537    if head == KEYWORD_RUN
8538        && matches!(
8539            body.get(1).map(|t| &t.kind),
8540            Some(TokKind::Group {
8541                delim: GroupDelim::Bracket,
8542                ..
8543            })
8544        )
8545    {
8546        if body[1].joint {
8547            return Err(TokenError {
8548                stmt,
8549                msg: "RUN [...] requires a gap after RUN".to_string(),
8550                line: 0,
8551                col: 0,
8552                kind: None,
8553            });
8554        }
8555        let inner = match &body[1].kind {
8556            TokKind::Group { inner, .. } => inner.clone(),
8557            _ => unreachable!(),
8558        };
8559        // Non-map blocks miss the exec shape (the grammar has no
8560        // `block` alternative here); fall through to the shell path
8561        // below, which reads the bracket literally.
8562        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
8563            let kind =
8564                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
8565            return Ok((kind, 2));
8566        }
8567    }
8568    let (tokens, deferred) = build_arg_tokens(&body[1..], stmt, ctx)?;
8569    let lowered = lower_generic_args(&head, tokens, stmt, ctx);
8570    match lowered {
8571        Ok(kind) => {
8572            // Stashed call errors surface only for otherwise well-formed
8573            // statements: the command head owns its syntax, so a malformed
8574            // header keeps its tailored error instead of being masked by an
8575            // argument-position resolution failure.
8576            if let Some(err) = deferred {
8577                return Err(err);
8578            }
8579            Ok((kind, body.len()))
8580        }
8581        Err(lower_err) => {
8582            // Fallback raw strings (`NOPE()` rendered as text) can fail
8583            // argument-shape lowering with a misleading error. The
8584            // stashed unknown-callee error names the real culprit, so
8585            // it wins over every argument-level failure (`Validation`,
8586            // `Syntax`, `InvalidSyntax`, or the `None` classification
8587            // that `ENV`/`EXPAND` lowering uses). Heads owned by a
8588            // statement-header parser (`FUNC`, `LET`, `IF`, `FOR`,
8589            // `WHILE`, `TYPE`, `IMPORT`, `EXPORT`, `REMOTE`, `WITH_IO`)
8590            // keep their lowering `InvalidSyntax`: those parsers miss to
8591            // this path on shape miss (e.g. `FUNC FOO() ECHO hi` has no
8592            // body block), so the lowering error names the malformed
8593            // header while the stashed name is its definiendum, never an
8594            // argument-position call. Every other head is a plain
8595            // command, so a lowering `InvalidSyntax` there is an
8596            // argument-shape failure from the raw-text fallback, and
8597            // the stashed callee names the culprit. Only
8598            // head-identity errors (`UnknownCommand`, `Structural`)
8599            // keep their tailored diagnostic everywhere.
8600            let is_header_syntax = matches!(
8601                head.as_str(),
8602                KEYWORD_FUNC
8603                    | KEYWORD_LET
8604                    | KEYWORD_IF
8605                    | KEYWORD_SWITCH
8606                    | KEYWORD_FOR
8607                    | KEYWORD_WHILE
8608                    | KEYWORD_TYPE
8609                    | KEYWORD_IMPORT
8610                    | KEYWORD_EXPORT
8611                    | KEYWORD_REMOTE
8612                    | KEYWORD_WITH_IO
8613            ) && matches!(
8614                lower_err.kind,
8615                Some(crate::error::ParseErrorKind::InvalidSyntax { .. })
8616            );
8617            if let Some(deferred_err) = deferred
8618                && !is_header_syntax
8619                && matches!(
8620                    lower_err.kind,
8621                    Some(crate::error::ParseErrorKind::Validation { .. })
8622                        | Some(crate::error::ParseErrorKind::Syntax)
8623                        | Some(crate::error::ParseErrorKind::InvalidSyntax { .. })
8624                        | None
8625                )
8626            {
8627                return Err(deferred_err);
8628            }
8629            Err(lower_err)
8630        }
8631    }
8632}
8633
8634/// Parse a token stream (either lexer) into steps. Markers normalize to
8635/// 0/0 like the fuzz harness; scopes arrive with block slices.
8636pub fn parse_tokens(
8637    toks: &[Tok],
8638    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8639) -> Result<Vec<Step>, TokenError> {
8640    let modules = ModuleTable::default();
8641    let reserved = HashSet::new();
8642    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
8643    parse_tokens_with_ctx(toks, &ctx)
8644}
8645
8646/// Parse with an explicit context (module table for call resolution).
8647/// `parse_tokens` uses empty modules.
8648pub fn parse_tokens_with_ctx(toks: &[Tok], ctx: &ParseCtx) -> Result<Vec<Step>, TokenError> {
8649    let mut out = Vec::new();
8650    *ctx.current_line.borrow_mut() = 1;
8651    let stmts = split_statements(toks, 1)?;
8652    predeclare_forward_funcs(&stmts, ctx);
8653    for (i, s) in stmts.iter().enumerate() {
8654        *ctx.current_line.borrow_mut() = s.line;
8655        out.extend(
8656            lower_stmt_steps(s, i, ctx, false, true).map_err(|e| stamp_pos(e, s.line, s.col))?,
8657        );
8658    }
8659    // Whole-script validations through the shared validators.
8660    // `INHERIT_ENV` prelude order: only leading positions read.
8661    {
8662        let mut seen_non_prelude = false;
8663        for step in &out {
8664            match &step.kind {
8665                StepKind::InheritEnv { .. } => {
8666                    if seen_non_prelude {
8667                        return Err(TokenError {
8668                            stmt: out.len(),
8669                            msg: "INHERIT_ENV must appear before any other commands".to_string(),
8670                            line: 0,
8671                            col: 0,
8672                            kind: None,
8673                        });
8674                    }
8675                }
8676                kind => {
8677                    if crate::commands::contains_inherit_env(kind) {
8678                        return Err(TokenError {
8679                            stmt: out.len(),
8680                            msg: "INHERIT_ENV cannot be nested inside other commands".to_string(),
8681                            line: 0,
8682                            col: 0,
8683                            kind: None,
8684                        });
8685                    }
8686                    // Harvest imports stay prelude: they bind functions
8687                    // and types without executing module bodies, so they
8688                    // neither read nor disturb the inherited environment.
8689                    // File imports execute arbitrary top-level steps on
8690                    // import, so they end the prelude like any other
8691                    // side-effecting command. Host-only IMPORTs emit no
8692                    // step at all, which is why they never tripped this
8693                    // gate.
8694                    if !matches!(kind, StepKind::ImportFuncs { .. }) {
8695                        seen_non_prelude = true;
8696                    }
8697                }
8698            }
8699        }
8700    }
8701    crate::commands::validate_remote_copy_placement(&out, &lowering_ctx(out.len())).map_err(
8702        |e| TokenError {
8703            stmt: out.len(),
8704            msg: e.to_string(),
8705            line: 0,
8706            col: 0,
8707            kind: None,
8708        },
8709    )?;
8710    {
8711        let top: HashSet<String> = ctx.funcs.borrow().first().cloned().unwrap_or_default();
8712        let top_imports: Vec<String> = ctx.imports.borrow().first().cloned().unwrap_or_default();
8713        let mut top_types = HashSet::new();
8714        for step in &out {
8715            if let StepKind::TypeAlias { name, .. } = &step.kind {
8716                top_types.insert(name.clone());
8717            }
8718        }
8719        crate::commands::validate_exports(
8720            &lowering_ctx(out.len()),
8721            &ctx.func_exports.borrow(),
8722            &ctx.type_exports.borrow(),
8723            &top,
8724            &top_types,
8725            ctx.modules,
8726            &top_imports,
8727        )
8728        .map_err(|e| TokenError {
8729            stmt: out.len(),
8730            msg: e.to_string(),
8731            line: 0,
8732            col: 0,
8733            kind: None,
8734        })?;
8735    }
8736    Ok(out)
8737}
8738
8739// ---- String entry points: lex, lower, collect exports and docs ----
8740
8741/// Source text of a 1-based line. The line just past a trailing
8742/// newline (where unbalanced groups report) reads as empty text so
8743/// caret blocks still render.
8744fn source_line_of(input: &str, line: usize) -> Option<String> {
8745    let count = input.lines().count();
8746    let idx = line.checked_sub(1)?;
8747    if idx < count {
8748        input.lines().nth(idx).map(str::to_string)
8749    } else if idx == count {
8750        Some(String::new())
8751    } else {
8752        None
8753    }
8754}
8755
8756/// Last script line (end-of-script validations blame it).
8757fn last_line(input: &str) -> usize {
8758    input.lines().count().max(1)
8759}
8760
8761/// Convert a lexer failure: low-level syntax kind, exact lexer
8762/// position, and the source line for the caret block. Unclosed groups
8763/// name their opener (no grammar dumps); the closer expectation rides
8764/// along so `expected()` stays informative. A lexer-known kind (an
8765/// unclosed `WITH_IO` bracket) converts verbatim.
8766fn lex_error(input: &str, e: LexError) -> ParseError {
8767    let line = e.line.max(1);
8768    let ctx = match source_line_of(input, line) {
8769        Some(source_line) => SpanContext::full(line, e.col.max(1), e.col.max(1), source_line),
8770        None => SpanContext::line_only(line),
8771    };
8772    if let Some(ParseErrorKind::InvalidSyntax { command }) = e.kind {
8773        // Lexer-known command syntax (an unclosed `WITH_IO` bracket).
8774        return ParseError::invalid_syntax(
8775            &command,
8776            e.msg,
8777            None,
8778            vec!["`]`".to_string()],
8779            None,
8780            &ctx,
8781        );
8782    }
8783    let expected = if e.msg.starts_with("unclosed") {
8784        vec!["`}`".to_string()]
8785    } else {
8786        Vec::new()
8787    };
8788    ParseError::syntax(e.msg, expected, None, &ctx)
8789}
8790
8791/// Convert a backend failure, preserving the dispatcher's error kind
8792/// and completing line/source context the token stream knows. Spans
8793/// open at the statement's start column and cover its whole first line
8794/// (multi-line spans clamp to the start line), so caret blocks render
8795/// for every string-path error.
8796fn token_error(input: &str, e: TokenError) -> ParseError {
8797    let line = if e.line == 0 {
8798        last_line(input)
8799    } else {
8800        e.line
8801    };
8802    let start_col = e.col.max(1);
8803    let ctx = match source_line_of(input, line) {
8804        Some(source_line) => {
8805            let end = source_line.len().max(start_col);
8806            SpanContext::full(line, start_col, end, source_line)
8807        }
8808        None => SpanContext::line_only(line),
8809    };
8810    // Column spans are statement granularity (every error names its
8811    // statement's first column); the caret block still renders.
8812    match e.kind {
8813        Some(crate::error::ParseErrorKind::UnknownCommand { name }) => {
8814            ParseError::unknown_command(&name, e.msg, None, &ctx)
8815        }
8816        Some(crate::error::ParseErrorKind::InvalidSyntax { command }) => {
8817            ParseError::invalid_syntax(&command, e.msg, None, Vec::new(), None, &ctx)
8818        }
8819        Some(crate::error::ParseErrorKind::Validation { command }) => {
8820            ParseError::validation(&command, e.msg, &ctx)
8821        }
8822        Some(crate::error::ParseErrorKind::Syntax) => {
8823            ParseError::syntax(e.msg, Vec::new(), None, &ctx)
8824        }
8825        Some(crate::error::ParseErrorKind::Structural { rule }) => {
8826            ParseError::structural(&rule, e.msg, &ctx)
8827        }
8828        None => ParseError::structural("statement", e.msg, &ctx),
8829    }
8830}
8831
8832/// Shared parse driver: lex, lower with preseeded frames, and collect
8833/// `EXPORT` names (validated at end of parse, forward references
8834/// allowed).
8835fn parse_with_ctx(
8836    input: &str,
8837    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8838    reserved_names: HashSet<String>,
8839    modules: ModuleTable,
8840    preseed_funcs: HashSet<String>,
8841    preseed_imports: Vec<String>,
8842) -> ParseResult<ScriptWithExports> {
8843    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
8844    let ctx = ParseCtx::empty(&lower, &modules, &reserved_names);
8845    // Snippet re-parses seed their base frames so lookup behaves
8846    // identically; snippets never define, only read.
8847    ctx.funcs.borrow_mut()[0].extend(preseed_funcs);
8848    ctx.imports.borrow_mut()[0].extend(preseed_imports);
8849    let steps = parse_tokens_with_ctx(&toks, &ctx).map_err(|e| token_error(input, e))?;
8850    let mut steps = steps;
8851    stamp_func_docs(input, &mut steps);
8852    Ok(ScriptWithExports {
8853        steps,
8854        func_exports: ctx.func_exports.borrow().clone(),
8855        type_exports: ctx.type_exports.borrow().clone(),
8856    })
8857}
8858
8859/// Steps plus single-file `EXPORT` metadata, before `#` doc stamping.
8860/// Callers needing docs build a [`ParsedScript`] from this.
8861struct ScriptWithExports {
8862    steps: Vec<Step>,
8863    func_exports: Vec<String>,
8864    type_exports: Vec<String>,
8865}
8866
8867/// Parse a script with an unknown host environment.
8868pub fn parse_script(
8869    input: &str,
8870    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8871) -> ParseResult<Vec<Step>> {
8872    Ok(parse_with_ctx(
8873        input,
8874        lower,
8875        HashSet::new(),
8876        ModuleTable::default(),
8877        HashSet::new(),
8878        Vec::new(),
8879    )?
8880    .steps)
8881}
8882
8883/// Parse a snippet with an enclosing parse's visible scope state, so
8884/// re-parsed inner commands (async bodies) resolve calls identically.
8885/// The snippet never defines, only reads: seeds affect lookup alone.
8886pub fn parse_script_with_preseed(
8887    input: &str,
8888    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8889    reserved_names: HashSet<String>,
8890    modules: ModuleTable,
8891    preseed_funcs: HashSet<String>,
8892    preseed_imports: Vec<String>,
8893) -> ParseResult<Vec<Step>> {
8894    Ok(parse_with_ctx(
8895        input,
8896        lower,
8897        reserved_names,
8898        modules,
8899        preseed_funcs,
8900        preseed_imports,
8901    )?
8902    .steps)
8903}
8904
8905/// Parse with a module provenance table so calls resolve statically:
8906/// qualified `MODULE::NAME` checks membership, bare `NAME` resolves through
8907/// `SCRIPT` definitions and `IMPORT`ed modules, and anything else fails at
8908/// parse time instead of at runtime.
8909pub fn parse_script_with_modules(
8910    input: &str,
8911    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8912    reserved_names: HashSet<String>,
8913    modules: ModuleTable,
8914) -> ParseResult<Vec<Step>> {
8915    Ok(parse_script_with_modules_and_exports(input, lower, reserved_names, modules)?.steps)
8916}
8917
8918/// Parse with modules plus single-file `EXPORT` metadata and `#` doc
8919/// comments for top-level `FUNC`s. Used by the MCP host; the linear
8920/// runner keeps using `parse_script_with_modules` and ignores exports.
8921pub fn parse_script_with_modules_and_exports(
8922    input: &str,
8923    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8924    reserved_names: HashSet<String>,
8925    modules: ModuleTable,
8926) -> ParseResult<ParsedScript> {
8927    let ScriptWithExports {
8928        steps,
8929        func_exports,
8930        type_exports,
8931    } = parse_with_ctx(
8932        input,
8933        lower,
8934        reserved_names,
8935        modules,
8936        HashSet::new(),
8937        Vec::new(),
8938    )?;
8939    Ok(ParsedScript {
8940        func_docs: collect_func_docs(input, &steps),
8941        steps,
8942        func_exports,
8943        type_exports,
8944    })
8945}
8946
8947/// Parse without modules plus `EXPORT` metadata. Used by tests and
8948/// tooling that lower with the shared mock.
8949pub fn parse_script_with_exports(
8950    input: &str,
8951    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8952) -> ParseResult<ParsedScript> {
8953    let ScriptWithExports {
8954        steps,
8955        func_exports,
8956        type_exports,
8957    } = parse_with_ctx(
8958        input,
8959        lower,
8960        HashSet::new(),
8961        ModuleTable::default(),
8962        HashSet::new(),
8963        Vec::new(),
8964    )?;
8965    Ok(ParsedScript {
8966        func_docs: collect_func_docs(input, &steps),
8967        steps,
8968        func_exports,
8969        type_exports,
8970    })
8971}
8972
8973/// Parse one expression from source text with an empty module scope, for
8974/// tooling that shows lowering without running (docs demos, explain output).
8975/// No imports exist here, so bare function calls fail and qualified calls
8976/// fail against the empty table; only `INSPECT` passes through untouched.
8977/// Arithmetic, comparison, variables, env reads, keypaths, and literals
8978/// lower normally, with literal only subtrees folded before flattening.
8979pub fn parse_expression_str(input: &str) -> ParseResult<Expr> {
8980    // Trailing whitespace lexes unconsumed, so lex the trimmed text:
8981    // otherwise padded but valid input fails the full consumption check.
8982    let trimmed = input.trim();
8983    let toks = lex_str(trimmed).map_err(|e| lex_error(trimmed, e))?;
8984    let modules = ModuleTable::default();
8985    let reserved = HashSet::new();
8986    let lower = crate::commands::lower_command as fn(&str, Vec<Arg>) -> ParseResult<StepKind>;
8987    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
8988    *ctx.current_line.borrow_mut() = 1;
8989    parse_single_expr(&toks, 0, &ctx).map_err(|e| token_error(trimmed, e))
8990}
8991
8992/// Parse one guard expression from source text (a bare `guard_seq`:
8993/// predicates, `not`/`any`/`all`, comma lists), for tooling and tests.
8994pub fn parse_guard_expr_str(input: &str) -> ParseResult<GuardExpr> {
8995    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
8996    parse_single_guard(&toks, 0).map_err(|e| token_error(input, e))
8997}
8998
8999/// Parsed script with single-file `EXPORT` metadata. `steps` is the
9000/// linear execution plan, `func_exports` the `EXPORT` func names in
9001/// source order, `type_exports` the `EXPORT TYPE` names in source order,
9002/// and `func_docs` maps top-level `FUNC` base names to (summary, docs)
9003/// collected from the immediately preceding `#` comment block.
9004#[derive(Debug, Clone, Default)]
9005pub struct ParsedScript {
9006    pub steps: Vec<Step>,
9007    pub func_exports: Vec<String>,
9008    pub type_exports: Vec<String>,
9009    pub func_docs: std::collections::HashMap<String, (String, String)>,
9010}
9011
9012fn collect_func_docs(
9013    input: &str,
9014    steps: &[Step],
9015) -> std::collections::HashMap<String, (String, String)> {
9016    use std::collections::{HashMap, HashSet};
9017    let lines: Vec<&str> = input.lines().collect();
9018    // Top-level FUNC definition lines keyed by base name. Brace depth
9019    // tracks nesting so only depth-0 `FUNC` lines count; the first
9020    // occurrence wins because same-scope duplicates fail at lowering.
9021    let mut def_lines: HashMap<String, usize> = HashMap::new();
9022    let mut seen: HashSet<String> = HashSet::new();
9023    let mut depth: usize = 0;
9024    for (idx, line) in lines.iter().enumerate() {
9025        let trimmed = line.trim_start();
9026        let is_comment = trimmed.starts_with('#');
9027        let is_guard_only = trimmed.starts_with('[');
9028        if !is_comment
9029            && !is_guard_only
9030            && let Some(rest) = strip_func_head(trimmed)
9031            && depth == 0
9032            && !seen.contains(&rest)
9033        {
9034            seen.insert(rest.clone());
9035            def_lines.insert(rest, idx + 1);
9036        }
9037        if !is_comment {
9038            for ch in line.chars() {
9039                if ch == '{' {
9040                    depth = depth.saturating_add(1);
9041                } else if ch == '}' {
9042                    depth = depth.saturating_sub(1);
9043                }
9044            }
9045        }
9046    }
9047    let mut out: HashMap<String, (String, String)> = HashMap::new();
9048    for step in steps {
9049        if let StepKind::FuncDef { name, .. } = &step.kind
9050            && !out.contains_key(name)
9051            && let Some(&line_no) = def_lines.get(name)
9052            && let Some((summary, docs)) = docs_above(&lines, line_no)
9053        {
9054            out.insert(name.clone(), (summary, docs));
9055        }
9056    }
9057    out
9058}
9059
9060/// Stamp `#` doc blocks onto top-level `FUNC` steps, from the same map
9061/// that feeds `func_docs`, so step-carried docs and the sidecar can
9062/// never disagree. Only top-level definitions qualify (same rule as
9063/// collection); nested shadowing keeps `docs: None`.
9064fn stamp_func_docs(input: &str, steps: &mut [Step]) {
9065    let docs = collect_func_docs(input, steps);
9066    for step in steps {
9067        if let StepKind::FuncDef {
9068            name, docs: slot, ..
9069        } = &mut step.kind
9070            && slot.is_none()
9071            && let Some(pair) = docs.get(name)
9072        {
9073            *slot = Some(pair.clone());
9074        }
9075    }
9076}
9077
9078fn strip_func_head(trimmed: &str) -> Option<String> {
9079    let rest = trimmed.strip_prefix(KEYWORD_FUNC)?;
9080    let after = rest.strip_prefix([' ', '\t'])?;
9081    if after.is_empty() {
9082        return None;
9083    }
9084    let name: String = after
9085        .chars()
9086        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
9087        .collect();
9088    if name.is_empty()
9089        || !name
9090            .bytes()
9091            .all(|b| b.is_ascii_uppercase() || b == b'_' || b.is_ascii_digit())
9092    {
9093        return None;
9094    }
9095    if name.starts_with(|c: char| c.is_ascii_digit()) {
9096        return None;
9097    }
9098    Some(name)
9099}
9100
9101fn docs_above(lines: &[&str], line_no: usize) -> Option<(String, String)> {
9102    if line_no <= 1 {
9103        return None;
9104    }
9105    let mut block: Vec<String> = Vec::new();
9106    let mut idx = line_no - 1;
9107    while idx > 0 {
9108        idx -= 1;
9109        let trimmed = lines[idx].trim_start();
9110        if trimmed.is_empty() {
9111            break;
9112        }
9113        if let Some(body) = trimmed.strip_prefix('#') {
9114            let text = body.strip_prefix(' ').unwrap_or(body);
9115            block.push(text.to_string());
9116        } else {
9117            break;
9118        }
9119        if idx == 0 {
9120            break;
9121        }
9122    }
9123    if block.is_empty() {
9124        return None;
9125    }
9126    block.reverse();
9127    let summary = block.first().cloned().unwrap_or_default();
9128    let docs = block.join("\n");
9129    Some((summary, docs))
9130}
9131
9132#[cfg(test)]
9133mod tests {
9134    use super::*;
9135    use crate::test_lower_mock;
9136    use indoc::indoc;
9137
9138    fn lower(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9139        test_lower_mock::lower(name, args)
9140    }
9141
9142    /// Lexer-agreement oracle: both frontends must deliver identical
9143    /// steps through the single backend. `parse_script` is the string
9144    /// entry point; `parse_tokens` runs each lexer's output directly.
9145    fn assert_parity(text: &str) {
9146        let old = crate::parse_script(text, lower)
9147            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9148        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9149        let new = parse_tokens(&toks, lower)
9150            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9151        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9152        #[cfg(feature = "proc-macro-api")]
9153        {
9154            let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
9155            let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
9156            let new = parse_tokens(&toks, lower).expect("token path must parse token script");
9157            assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
9158        }
9159    }
9160
9161    /// String-path-only oracle for shapes `rustc` cannot carry at all
9162    /// (lifetime-like quotes). The backend must still agree there.
9163    fn assert_parity_string_only(text: &str) {
9164        let old = crate::parse_script(text, lower)
9165            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9166        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9167        let new = parse_tokens(&toks, lower)
9168            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9169        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9170    }
9171
9172    #[test]
9173    fn token_and_string_paths_agree_on_wrappers() {
9174        // Single-command wrappers, io-blocks, await/cancel,
9175        // LET wrapper forms — three-way agreement per script.
9176        for text in [
9177            "WITH_IO [stdout=$p] ECHO hi",
9178            "WITH_IO [stdin=$p] ECHO hi",
9179            "WITH_IO [stdin] ECHO hi",
9180            "WITH_IO [stdout] ECHO hi",
9181            "WITH_IO [stdin=$p, stdout=$q] ECHO hi",
9182            "WITH_IO [stdin=$p, stdin=$q] ECHO hi",
9183            "WITH_IO [tty] RUN echo hi",
9184            "WITH_IO [tty, rows=40, cols=100] RUN echo hi",
9185            "WITH_IO [rows=40, cols=100, tty] RUN echo hi",
9186            "WITH_IO [stdin =$p] ECHO hi",
9187            "WITH_IO [stdin= $p] ECHO hi",
9188            "WITH_IO [ stdin=$p ] ECHO hi",
9189            "WITH_IO [\nstdin=$p\n] ECHO hi",
9190            "WITH_IO [stdin=$p\n, stdout=$q] ECHO hi",
9191            "WITH_IO [stdout=$p] ASYNC ECHO hi",
9192            "WITH_IO [stdin=$p] WITH_IO [stderr=$e] ECHO hi",
9193            "WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
9194            "WITH_IO [stdin=$p] ISOLATED ECHO hi",
9195            "WITH_IO [stdin=$p] CANCEL $t",
9196            "WITH_IO [stdin=$p] CANCEL $t ECHO bye",
9197            "WITH_IO [stdin=$p] { ECHO hi }",
9198            "WITH_IO [stdin=$p]\n{ ECHO hi }",
9199            "WITH_IO [stdin=$p]; { ECHO hi }",
9200            "WITH_IO [stdin=$p]{ ECHO hi }",
9201            "WITH_IO [stdin=$p] { ECHO a\nECHO b }",
9202            "WITH_IO [stdin=$p] { ECHO hi } ECHO bye",
9203            "WITH_IO [rows=40] { ECHO hi }",
9204            "WITH_IO [tty] { ECHO hi }",
9205            "WITH_IO [stdin=$p] { WITH_IO [stderr=$e] ECHO hi }",
9206            "TIMEOUT 10s ECHO hi",
9207            "TIMEOUT 10 ECHO hi",
9208            "TIMEOUT 500ms ECHO hi",
9209            "TIMEOUT 5m ECHO hi",
9210            "TIMEOUT 2h ECHO hi",
9211            "TIMEOUT $d ECHO hi",
9212            "TIMEOUT \"10s\" ECHO hi",
9213            "TIMEOUT \"30 s\" ECHO hi",
9214            "TIMEOUT {{ $d }} ECHO hi",
9215            "TIMEOUT 10s AWAIT $t",
9216            "TIMEOUT 10s CANCEL $t",
9217            "TIMEOUT 10s AWAIT $t ECHO bye",
9218            "TIMEOUT 10s CANCEL $t ECHO bye",
9219            "TIMEOUT 10s { ECHO hi }",
9220            "TIMEOUT 10s {\nECHO hi\n}",
9221            "TIMEOUT 10s { ECHO hi } ECHO bye",
9222            "TIMEOUT 10s { ECHO hi } TIMEOUT 5s ECHO bye",
9223            "TIMEOUT 10s TIMEOUT 5s ECHO hi",
9224            "TIMEOUT 10s { ECHO a\nECHO b }",
9225            "TIMEOUT 10s ECHO hi extra",
9226            "ISOLATED ECHO hi",
9227            "ISOLATED { ECHO hi }",
9228            "ISOLATED { ECHO hi } ECHO bye",
9229            "ISOLATED AWAIT $t",
9230            "ISOLATED INHERIT_ENV [M]",
9231            "ISOLATED { INHERIT_ENV [M] }",
9232            "ISOLATED { INHERIT_ENV [MODE]\nECHO hi }",
9233            "ASYNC ECHO hi",
9234            "ASYNC { ECHO hi }",
9235            "ASYNC{ECHO hi}",
9236            "ASYNC { ECHO a\nECHO b }",
9237            "ASYNC { ECHO hi } ECHO bye",
9238            "ASYNC CANCEL $t",
9239            "ASYNC CANCEL $t ECHO bye",
9240            "AWAIT $t",
9241            "AWAIT$t",
9242            "AWAIT $ t",
9243            "AWAIT $T",
9244            "AWAIT $t2",
9245            "AWAIT $_t",
9246            "CANCEL $t",
9247            "CANCEL$t",
9248            "CANCEL $ t",
9249            "AWAIT $t ECHO bye",
9250            "CANCEL $t ECHO bye",
9251            "AWAIT $t AWAIT $u",
9252            "AWAIT $t\nECHO bye",
9253            "LET $t: HANDLE = ASYNC ECHO hi",
9254            "LET $t: HANDLE = ASYNC { ECHO hi }",
9255            "LET $t: HANDLE = ASYNC { ECHO hi } ECHO bye",
9256            "LET $a: STRING = ASYNC ECHO hi",
9257            "LET $t: HANDLE = ASYNC { WITH_IO [stdin=$p] ECHO hi }",
9258            "LET $w: STRING = WITH_IO [stdin=$p] ASYNC ECHO hi",
9259            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC ECHO hi",
9260            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi }",
9261            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi } ECHO bye",
9262            "LET $x: STRING = WITH_IO [stdin=$p] ECHO hi",
9263            "LET $x: STRING = WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
9264            "LET $x: STRING = TIMEOUT 10s ECHO hi",
9265            "LET $x: STRING = TIMEOUT 10s { ECHO hi }",
9266            "LET $x: STRING = TIMEOUT 10s ECHO hi ECHO bye",
9267            "LET $o: STRING = AWAIT $t",
9268            "LET $p: PIPE ECHO bye",
9269            "TIMEOUT 10s WITH_IO [stdin=$p]",
9270            "TIMEOUT 10s WITH_IO [stdin=$p]ECHO hi",
9271            "ISOLATED INHERIT_ENV [A, B]",
9272            "ISOLATED INHERIT_ENV [A-B]",
9273            "TIMEOUT 10s { [os:linux] ECHO hi }",
9274            "ASYNC { [os:linux] ECHO hi }",
9275            "ISOLATED { [os:linux] ECHO hi }",
9276            "[os:linux] WITH_IO [stdin=$p]\n{ ECHO hi }",
9277            "LET $x: INT = 1 ECHO bye",
9278            "CANCEL $t LET $x: INT = 1",
9279            "CANCEL $t $x = 1",
9280            "CANCEL $t RETURN \"hi\"",
9281            "TIMEOUT 10s { ECHO hi } LET $x: INT = 1",
9282            "RUN [\"a\"] ECHO bye",
9283            "[os:linux] AWAIT $t",
9284            "[os:linux] TIMEOUT 10s { ECHO hi } ECHO bye",
9285            "[os:linux] ASYNC CANCEL $t ECHO bye",
9286            "[os:linux] WITH_IO [stdin=$p] { [os:macos] ECHO hi }",
9287        ] {
9288            assert_parity(text);
9289        }
9290    }
9291
9292    #[test]
9293    fn token_and_string_paths_agree_on_blocks() {
9294        // Slice 5: `IF`/`FOR`/`WHILE`/`FUNC` with inline and
9295        // cross-newline `ELSE` chains, guard blocks (top-level and
9296        // nested quirk), and multi-element trailing — three-way
9297        // agreement per script.
9298        for text in [
9299            "IF true { ECHO hi }",
9300            "IF $x { ECHO hi } ELSE { ECHO bye }",
9301            "IF true { ECHO a } ELSE IF false { ECHO b } ELSE { ECHO c }",
9302            "IF true{ ECHO hi }",
9303            "IF true { ECHO hi } ECHO bye",
9304            "IF true { ECHO hi }\nELSE { ECHO bye }",
9305            "IF true { ECHO hi }\nELSE IF false { ECHO b }\nELSE { ECHO c }",
9306            "IF true { ECHO hi } //c\nELSE { ECHO bye }",
9307            "IF true { ECHO hi } #c\nELSE { ECHO bye }",
9308            "IF true { ECHO hi }//c\nELSE { ECHO bye }",
9309            "IF true { ECHO hi } /*c*/ ELSE { ECHO bye }",
9310            "IF true { ECHO hi } /*c1*/ /*c2*/\nELSE { ECHO bye }",
9311            "IF true { /*c*/ ECHO hi }",
9312            "IF true { [os:linux] ECHO hi }",
9313            "TIMEOUT 10s { IF true { ECHO hi } }",
9314            "TIMEOUT 10s { IF true { ECHO hi }\nELSE { ECHO bye } }",
9315            "FOR $x: INT IN [1] { ECHO hi }",
9316            "FOR $k: STRING, $v: INT IN $m { ECHO hi }",
9317            "FOR $k: INT IN [1] { ECHO hi }",
9318            "FOR $x: INT IN [1]{ ECHO hi }",
9319            "FOR $x: MAP<name: STRING> IN [1] { ECHO hi }",
9320            "FOR $x: INT IN [1] { ECHO hi } ECHO bye",
9321            "WHILE true { ECHO hi }",
9322            "WHILE $x { ECHO hi }",
9323            "WHILE true{ ECHO hi }",
9324            "TIMEOUT 10s WHILE true { ECHO hi }",
9325            "ASYNC WHILE true { ECHO hi }",
9326            "FUNC FOO(): INT { RETURN 1 }",
9327            "FUNC FOO(): INT { RETURN 1 }",
9328            "FUNC FOO($x: INT): INT { RETURN $x }",
9329            "FUNC FOO($x: INT, $y: STRING): INT { RETURN $x }",
9330            "FUNC FOO(): INT { FUNC FOO(): INT { RETURN 1 } }",
9331            "FUNC FOO(): INT { RETURN 1 }\nFUNC BAR(): VOID { FOO() }\nBAR()",
9332            "TYPE PERSON = MAP<name: STRING>",
9333            "TYPE A=B",
9334            "TYPE A = B | C",
9335            "TYPE A = B\nTYPE A = C",
9336            "INHERIT_ENV [A]\nECHO hi",
9337            "[os:linux] INHERIT_ENV [M]",
9338            "INHERIT_ENV [A]\nINHERIT_ENV [B]\nECHO hi",
9339            "ISOLATED INHERIT_ENV [M]",
9340            "ISOLATED { INHERIT_ENV [M] }",
9341            "ISOLATED INHERIT_ENV [A, B]",
9342            "ISOLATED INHERIT_ENV [A-B]",
9343            "REMOTE prod { ECHO hi }",
9344            "REMOTE prod [$v] { ECHO hi }",
9345            "REMOTE prod [$v, env:E] { ECHO hi }",
9346            "REMOTE prod [] { ECHO hi }",
9347            "REMOTE prod[$v] { ECHO hi }",
9348            "REMOTE prod [$v]{ ECHO hi }",
9349            "REMOTE prod{ ECHO hi }",
9350            "REMOTE  prod  { ECHO hi }",
9351            "REMOTE prod [$v, $v] { ECHO hi }",
9352            "REMOTE prod { ECHO hi } ECHO bye",
9353            "TIMEOUT 10s REMOTE prod { ECHO hi }",
9354            "ASYNC REMOTE prod [$v] { ECHO hi }",
9355            "[os:linux] { ECHO hi }",
9356            "[os:linux]\n{ ECHO hi }",
9357            "[os:linux] { [os:macos] ECHO hi }",
9358            "[os:linux] { [os:macos] ECHO hi\nECHO bye }",
9359            "[os:linux] { [os:macos] { ECHO hi } }",
9360            "TIMEOUT 10s { [os:linux] { [os:macos] ECHO hi } }",
9361            "TIMEOUT 10s { [os:linux] [os:windows] { ECHO hi } }",
9362            "TIMEOUT 10s { [os:linux] { ECHO hi } ECHO bye }",
9363            "LET $x: INT = 1 ECHO bye",
9364            KEYWORD_BREAK,
9365            KEYWORD_CONTINUE,
9366            "BREAK ECHO hi",
9367            "FOR $x: INT IN [1] { BREAK }",
9368            "LET $b: STRING = { RETURN \"hi\" }",
9369            "ECHO { RETURN \"hi\" }",
9370            "RUN [{ RETURN \"hi\" }]",
9371            "[not(env:FOO)] WRITE x",
9372            "[\nnot(env:FOO)\n] WRITE x",
9373            "WRITE env.txt \"{{ env:GREETING }}\"",
9374            "CANCEL $t LET $x: INT = 1",
9375            "RUN [\"a\"] ECHO bye",
9376        ] {
9377            assert_parity(text);
9378        }
9379    }
9380
9381    #[test]
9382    fn multi_line_generics_match_single_line_shape() {
9383        // Multi-line `<...>` shapes parse, and canonicalize exactly
9384        // like their single-line spelling.
9385        for (single, multi) in [
9386            (
9387                "TYPE R = MAP<name: STRING, value: INT>",
9388                "TYPE R = MAP<name: STRING,\nvalue: INT>",
9389            ),
9390            (
9391                "TYPE R = MAP<name: STRING, value: LIST<INT>>",
9392                "TYPE R = MAP<name: STRING,\nvalue: LIST<INT>>",
9393            ),
9394            (
9395                "TYPE R = MAP<name: STRING, value: INT>",
9396                "TYPE R = MAP<\nname: STRING,\nvalue: INT\n>",
9397            ),
9398            (
9399                "LET $m: MAP<name: STRING, value: INT> = {}",
9400                "LET $m: MAP<name: STRING,\nvalue: INT> = {}",
9401            ),
9402            (
9403                "FOR $x: LIST<INT> IN [1] { ECHO hi }",
9404                "FOR $x: LIST<\nINT> IN [1] { ECHO hi }",
9405            ),
9406            ("TYPE R = MAP<x: A | B>", "TYPE R = MAP<x: A |\nB>"),
9407        ] {
9408            assert_parity(multi);
9409            let want = crate::parse_script(single, lower)
9410                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
9411            let got = crate::parse_script(multi, lower)
9412                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
9413            assert_eq!(
9414                got, want,
9415                "multi-line must canonicalize like one line: {multi:?}"
9416            );
9417        }
9418    }
9419
9420    #[test]
9421    fn type_field_defaults_parse_to_canonical_targets() {
9422        // Token-level regression: `= literal` tails belong to the
9423        // field (floats lex as three tokens), and the statement
9424        // target canonicalizes exactly like the spelling parser.
9425        for (text, want) in [
9426            ("TYPE F = MAP<retries: INT = 2>", "MAP<retries: INT = 2>"),
9427            ("TYPE F = MAP<retries: INT=-2>", "MAP<retries: INT = -2>"),
9428            (
9429                "TYPE F = MAP<ratio: FLOAT = 2.5>",
9430                "MAP<ratio: FLOAT = 2.5>",
9431            ),
9432            ("TYPE F = MAP<on: BOOL = true>", "MAP<on: BOOL = true>"),
9433            (
9434                "TYPE F = MAP<model: STRING = \"gpt-4\">",
9435                "MAP<model: STRING = \"gpt-4\">",
9436            ),
9437            (
9438                "TYPE F = MAP<k: STRING = \"d\", n: INT = 3>",
9439                "MAP<k: STRING = \"d\", n: INT = 3>",
9440            ),
9441        ] {
9442            assert_parity(text);
9443            let steps = crate::parse_script(text, lower)
9444                .unwrap_or_else(|e| panic!("default spelling must parse {text:?}: {e}"));
9445            let target = steps
9446                .iter()
9447                .find_map(|s| match &s.kind {
9448                    StepKind::TypeAlias { target, .. } => Some(target.clone()),
9449                    _ => None,
9450                })
9451                .expect("TYPE alias step");
9452            assert_eq!(target, want, "canonical target for {text:?}");
9453        }
9454    }
9455
9456    #[test]
9457    fn multi_line_run_exec_matches_single_line_shape() {
9458        // `RUN [...]` rides the shared bracket core, so a wrapped exec
9459        // list parses exactly like its single-line spelling (and agrees
9460        // across lexer frontends).
9461        for (single, multi) in [
9462            ("RUN [\"echo\", \"hi\"]", "RUN [\"echo\",\n\"hi\"]"),
9463            ("RUN [\"echo\", \"hi\"]", "RUN [\n\"echo\",\n\"hi\"\n]"),
9464            (
9465                "LET $o: STRING = RUN [\"echo\", \"hi\"]",
9466                "LET $o: STRING = RUN [\"echo\",\n\"hi\"]",
9467            ),
9468        ] {
9469            assert_parity(multi);
9470            let want = crate::parse_script(single, lower)
9471                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
9472            let got = crate::parse_script(multi, lower)
9473                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
9474            assert_eq!(
9475                got, want,
9476                "multi-line must canonicalize like one line: {multi:?}"
9477            );
9478        }
9479    }
9480
9481    #[test]
9482    fn untyped_let_fails_in_every_rhs_shape() {
9483        // The everything-typed rule: a missing `:` is a hard error
9484        // carrying the explicit-types message, regardless of what
9485        // follows the `=`. Every binding shape is covered, so no
9486        // untyped position can slip back in unnoticed.
9487        for text in [
9488            "LET $x = 1\n",
9489            "LET $x = \"hi\"\n",
9490            "LET $x = $y\n",
9491            "LET $x = [\"a\", \"b\"]\n",
9492            "LET $x = [\"a\",\n\"b\"]\n",
9493            "LET $x = ECHO hi\n",
9494            "LET $x = AWAIT $t\n",
9495            "LET $x = ASYNC ECHO hi\n",
9496            "LET $x = {\nRETURN 1\n}\n",
9497            "LET $x = WITH_IO [stdin=$p] ASYNC ECHO hi\n",
9498        ] {
9499            let err = crate::parse_script(text, lower).expect_err("untyped LET must fail");
9500            assert!(
9501                err.to_string().contains("LET requires explicit types"),
9502                "wrong error for {text:?}: {err}"
9503            );
9504        }
9505        // Typed spellings of the same shapes keep parsing through
9506        // every lexer frontend.
9507        for text in [
9508            "LET $x: INT = 1\n",
9509            "LET $x: STRING = \"hi\"\n",
9510            "LET $x: LIST<STRING> = [\"a\", \"b\"]\n",
9511            "LET $x: LIST<STRING> = [\"a\",\n\"b\"]\n",
9512            "LET $x: STRING = ECHO hi\n",
9513            "LET $x: STRING = AWAIT $t\n",
9514            "LET $x: HANDLE<VOID> = ASYNC ECHO hi\n",
9515            "LET $x: INT = {\nRETURN 1\n}\n",
9516        ] {
9517            assert_parity(text);
9518        }
9519    }
9520
9521    #[test]
9522    fn missing_comma_points_at_the_item() {
9523        // A forgotten comma between items names the missing
9524        // comma and points at the item's line, not the statement
9525        // head. Lists and call arguments share the rule.
9526        let text = indoc! {r#"
9527            LET $x: LIST<STRING> = [
9528            "a"
9529            "b",
9530            "c"
9531            ]
9532        "#};
9533        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
9534        assert!(
9535            err.to_string().contains("missing comma between list items"),
9536            "wrong error: {err}"
9537        );
9538        assert_eq!(err.line(), 3, "caret names the item line: {err}");
9539        // Same shape on one line.
9540        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" \"b\"]\n", lower)
9541            .expect_err("missing comma must fail");
9542        assert!(
9543            err.to_string().contains("missing comma between list items"),
9544            "wrong error: {err}"
9545        );
9546        assert_eq!(err.line(), 1, "single-line points at line 1: {err}");
9547        // Call arguments share the rule.
9548        let err = crate::parse_script("LET $x: STRING = FOO(\"a\" \"b\")\n", lower)
9549            .expect_err("missing comma must fail");
9550        assert!(
9551            err.to_string()
9552                .contains("missing comma between call arguments"),
9553            "wrong error: {err}"
9554        );
9555        // Genuine trailing garbage keeps the old message but still
9556        // points at the garbage instead of the statement head.
9557        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" : \"b\"]\n", lower)
9558            .expect_err("garbage must fail");
9559        assert!(
9560            err.to_string().contains("unexpected text in list"),
9561            "wrong error: {err}"
9562        );
9563        // Maps share the rule: a forgotten comma between entries
9564        // names it at the entry's line instead of misreporting the
9565        // key as an unknown command.
9566        let text = indoc! {r#"
9567            LET $m: MAP<name: STRING> = {
9568            name: "a"
9569            value: "b"
9570            }
9571        "#};
9572        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
9573        assert!(
9574            err.to_string()
9575                .contains("missing comma between map entries"),
9576            "wrong error: {err}"
9577        );
9578        assert_eq!(err.line(), 3, "caret names the entry line: {err}");
9579        let err = crate::parse_script(
9580            "LET $m: MAP<name: STRING> = {name: \"a\" value: \"b\"}\n",
9581            lower,
9582        )
9583        .expect_err("missing comma must fail");
9584        assert!(
9585            err.to_string()
9586                .contains("missing comma between map entries"),
9587            "wrong error: {err}"
9588        );
9589    }
9590
9591    #[test]
9592    fn spaced_comparisons_still_end_the_statement() {
9593        // A spaced `<` is a comparison, never a generic open: the
9594        // newline still ends the statement.
9595        let steps = crate::parse_script("LET $b: BOOL = $a < $b\nECHO hi", lower)
9596            .expect("comparison plus follower must parse");
9597        assert_eq!(steps.len(), 2, "newline ends the comparison statement");
9598    }
9599
9600    #[test]
9601    fn token_and_string_paths_agree_on_flat_commands() {
9602        for text in [
9603            "ECHO hi",
9604            "ECHO hi\nWRITE x out",
9605            "WRITE x",
9606            "ECHO \"quoted\" unquoted",
9607            "ENV COVERAGE=covered",
9608            "ECHO a; ECHO b",
9609            "// comment\nECHO hi",
9610            "ECHO 1.0.0 --flag a/b",
9611            "ECHO $x",
9612            "\n\nECHO hi\n\n",
9613        ] {
9614            assert_parity(text);
9615        }
9616    }
9617
9618    #[cfg(feature = "proc-macro-api")]
9619    #[test]
9620    fn backslash_outside_strings_is_string_only() {
9621        // `rustc` rejects a bare `\`, so unquoted backslash escapes
9622        // cannot cross `TokenStream` (same exclusion class as raw-`"`
9623        // blocks): the string lexer keeps them, the token path fails to
9624        // tokenize before v2 is ever reached.
9625        let toks = crate::tok::lex_str("ECHO a\\nb").expect("string lex keeps escapes");
9626        let old = crate::parse_script("ECHO a\\nb", lower).expect("string path parses it");
9627        assert_eq!(
9628            parse_tokens(&toks, lower).expect("token path parses it"),
9629            old
9630        );
9631        assert!("ECHO a\\nb".parse::<proc_macro2::TokenStream>().is_err());
9632    }
9633
9634    #[test]
9635    fn escaped_backslash_pair_is_atomic() {
9636        // `"a\\"` parses (one escape pair plus the closer): the pair
9637        // scans atomically, like the block-string arm and `lex_word`.
9638        // The value stays raw (`\\` verbatim for runtime
9639        // `expand_string`), so this pins parsing, not unescaping.
9640        assert_parity("ECHO \"a\\\\\"");
9641        let steps = crate::parse_script("ECHO \"a\\\\\"", lower).expect("escaped pair must parse");
9642        match &steps[..] {
9643            [s] => assert!(
9644                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a\\\\"),
9645                "escaped pair must survive raw: {s:?}"
9646            ),
9647            _ => panic!("one step: {steps:?}"),
9648        }
9649    }
9650
9651    #[test]
9652    fn joint_double_slash_stays_literal() {
9653        // `rustc` strips `//` before the macro ever runs, so these are
9654        // string-path-only by construction: joint `a//b` is one literal
9655        // arg, and `[a //c]` closes its group (the in-group `//` copy
9656        // stops at the closer).
9657        for text in ["ECHO a//b", "ECHO [a //c]"] {
9658            assert_parity_string_only(text);
9659        }
9660        let steps = crate::parse_script("ECHO a//b", lower).expect("joint slashes parse");
9661        match &steps[..] {
9662            [s] => assert!(
9663                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a//b"),
9664                "joint `//` must glue literally: {s:?}"
9665            ),
9666            _ => panic!("one step: {steps:?}"),
9667        }
9668        let steps = crate::parse_script("ECHO [a //c]", lower).expect("group must close");
9669        assert_eq!(steps.len(), 1, "one step: {steps:?}");
9670        // Full content survives literally: the mock joins WRITE args
9671        // with spaces, so the round trip is byte-exact here.
9672        let steps = crate::parse_script("WRITE f [a //c]", lower).expect("group must close");
9673        match &steps[..] {
9674            [s] => assert!(
9675                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a //c]"),
9676                "group content must survive literally: {s:?}"
9677            ),
9678            _ => panic!("one step: {steps:?}"),
9679        }
9680    }
9681
9682    #[test]
9683    fn block_comment_in_group_closes_like_line_comment() {
9684        // `[a /* c]` reads literally on the old backend (first arg
9685        // `[a`, joined `[a /* c]`), so the in-group `/*` copy breaks
9686        // at the depth-zero closer exactly like `//` does. The bare
9687        // `/*` reads literally too.
9688        for text in ["ECHO [a /* c]", "WRITE f [a /* c]", "ECHO /*"] {
9689            assert_parity_string_only(text);
9690        }
9691        let steps = crate::parse_script("ECHO /*", lower).expect("bare block open parses");
9692        match &steps[..] {
9693            [s] => assert!(
9694                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "/*"),
9695                "bare `/*` must stay literal: {s:?}"
9696            ),
9697            _ => panic!("one step: {steps:?}"),
9698        }
9699        let steps = crate::parse_script("WRITE f [a /* c]", lower).expect("group must close");
9700        match &steps[..] {
9701            [s] => assert!(
9702                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c]"),
9703                "group content must survive literally: {s:?}"
9704            ),
9705            _ => panic!("one step: {steps:?}"),
9706        }
9707        // Terminated spans keep working through the same path: the
9708        // run carries its closer, so math still gets first refusal.
9709        let steps = crate::parse_script("WRITE f [a /* c */ d]", lower).expect("group must close");
9710        match &steps[..] {
9711            [s] => assert!(
9712                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c */ d]"),
9713                "terminated group content must survive: {s:?}"
9714            ),
9715            _ => panic!("one step: {steps:?}"),
9716        }
9717    }
9718
9719    #[test]
9720    fn single_quoted_multiline_keeps_line_tracking() {
9721        // The `'` arm counts embedded newlines like the `"` arm, so the
9722        // statement after a multiline single-quoted string keeps its
9723        // own lines (func-docs stamping keys off them).
9724        let text = "ECHO 'a\nb'\nECHO c";
9725        assert_parity_string_only(text);
9726        let steps = crate::parse_script(text, lower).expect("must parse");
9727        assert_eq!(steps.len(), 2, "two steps: {steps:?}");
9728        assert_eq!((steps[0].line, steps[0].col), (1, 1));
9729        assert_eq!((steps[1].line, steps[1].col), (3, 1), "{steps:?}");
9730    }
9731
9732    #[test]
9733    fn token_and_string_paths_agree_on_guarded_commands() {
9734        for text in [
9735            "[env:X] ECHO hi",
9736            "[env:A] [os:linux] ECHO hi",
9737            "[os:macos] WRITE x",
9738            "[not(os:windows)] WRITE f x",
9739            "[any(os:macos, os:linux)] ECHO hi",
9740            "[all(env:A, os:linux)] ECHO hi",
9741            "[eq(env:K, v)] ECHO hi",
9742            "[ne(env:K, v)] ECHO hi",
9743            "[bool:true] ECHO hi",
9744            "[arch:arm] ECHO hi",
9745            "[family:unix] ECHO hi",
9746            "[(os:linux)] ECHO hi",
9747            "[env:A, os:linux] ECHO hi",
9748            "WRITE x\n[env:X] ECHO hi",
9749            "[env:K] ECHO $x",
9750            "[__OXDOCK_INJECT_1__] ECHO hi",
9751            "[eq(env:K, \"a b\")] ECHO hi",
9752            "[\nenv:X\n] ECHO hi",
9753            // In-body brackets are raw text split on whitespace (probed
9754            // parity: `[a, b]` is args `"[a,"` + `"b]"`, quotes kept).
9755            "ECHO [a, b] hi",
9756            "WRITE f [env:X]",
9757            "ECHO [env:X] hi",
9758            "WRITE f [\"a b\"]",
9759            "ECHO foo[bar]baz",
9760            "ECHO [a ]",
9761            "ECHO [ a]",
9762            "WRITE out x [env:X]",
9763        ] {
9764            assert_parity(text);
9765        }
9766        // `rustc` lexes `'a` as a lifetime start and rejects the
9767        // space: string-path-only by construction.
9768        assert_parity_string_only("ECHO ['a b']");
9769    }
9770
9771    #[test]
9772    fn token_and_string_paths_agree_on_calls_and_exact_args() {
9773        use crate::ast::{ModuleFuncs, ModuleTable};
9774        use std::collections::{HashMap, HashSet};
9775        let std_table = || ModuleTable {
9776            modules: HashMap::from([(
9777                crate::constants::STD_MODULE_NAME.to_string(),
9778                Some(ModuleFuncs {
9779                    func_names: HashSet::from(["LEN".to_string()]),
9780                }),
9781            )]),
9782        };
9783        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9784            test_lower_mock::lower(name, args)
9785        }
9786        // One table for both pathways: STD exports LEN.
9787        // Rebuilt per case (parse-time only, keeps borrows local).
9788        for text in [
9789            "LET $n: INT = STD::LEN(\"hi\")",
9790            "STD::LEN(\"hi\")",
9791            "LET $n: INT = STD::LEN(\"a\", \"b\")",
9792            "LET $s: STRING = INSPECT($x)",
9793            "INSPECT($x)",
9794            "LET $x: STRING = ECHO hi",
9795            "LET $t: STRING = WRITE x",
9796            "LET $o: STRING = RUN echo hi",
9797            "RUN [\"echo\", \"hi\"]",
9798            "RUN echo [a]",
9799            "LET $r: STRING = RUN [\"echo\"]",
9800            "ECHO K=v",
9801            "ECHO K = v",
9802            "ECHO K=a b",
9803            "ECHO K=a, b",
9804            "ECHO K=\"a b\"",
9805            "ECHO K=$x",
9806            "ECHO K=",
9807            "ECHO a = = b",
9808            "WRITE f K=v",
9809            "ECHO $a + $b",
9810            "ECHO $a==$b",
9811            "ECHO a $x b",
9812            "ECHO 5 + 3",
9813            "WRITE f ( \"hi\" )",
9814            "ECHO [a, b] hi",
9815            "ECHO {{x}}",
9816            "ECHO {{ $x }}",
9817            "ECHO $x=K",
9818            "ECHO a$x",
9819            "ECHO a$(x)",
9820            "ECHO K=$x tail",
9821            "EXPAND K1=$x K2=$y",
9822            "EXPAND a",
9823            "ENV K = v",
9824            "COPY a b",
9825            "ECHO foo[bar]baz",
9826            "LET $x: STRING = FOOBAR",
9827            "STD::LEN(\"hi\") ECHO bye",
9828            "LET $n: INT = STD::LEN(\"a\") ECHO bye",
9829            "TIMEOUT 10s STD::LEN(\"hi\")",
9830            "TIMEOUT 10s STD::LEN(\"hi\") ECHO bye",
9831            "LET $n: INT = STD::LEN(\"a\")STD::LEN(\"b\")",
9832        ] {
9833            let table = std_table();
9834            let old =
9835                crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
9836                    .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9837            let reserved = HashSet::new();
9838            let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
9839            let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9840            let new = parse_tokens_with_ctx(&toks, &ctx)
9841                .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9842            assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9843            #[cfg(feature = "proc-macro-api")]
9844            {
9845                let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
9846                let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
9847                let new = parse_tokens_with_ctx(&toks, &ctx)
9848                    .unwrap_or_else(|e| panic!("token path must parse token {text:?}: {e}"));
9849                assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
9850            }
9851        }
9852    }
9853
9854    #[test]
9855    fn placeholder_bare_calls_resolve_like_statements() {
9856        // `{{ NAME(args) }}` obeys exactly the statement-position
9857        // scope rule: `IMPORT [MOD]` brings the names into scope,
9858        // unimported names fail naming the fix, ambiguity fails
9859        // closed. The rewrite below is byte-identical past the
9860        // qualified head, so expansion sees the same args.
9861        use crate::ast::{ModuleFuncs, ModuleTable};
9862        use std::collections::{HashMap, HashSet};
9863        let table = || ModuleTable {
9864            modules: HashMap::from([
9865                (
9866                    crate::constants::STD_MODULE_NAME.to_string(),
9867                    Some(ModuleFuncs {
9868                        func_names: HashSet::from(["LEN".to_string()]),
9869                    }),
9870                ),
9871                (
9872                    "OTHER".to_string(),
9873                    Some(ModuleFuncs {
9874                        func_names: HashSet::from(["LEN".to_string()]),
9875                    }),
9876                ),
9877            ]),
9878        };
9879        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9880            test_lower_mock::lower(name, args)
9881        }
9882        fn echo_text(steps: &[crate::Step]) -> String {
9883            match steps {
9884                [s] => match &s.kind {
9885                    StepKind::Echo(Arg::String(text, _)) => text.clone(),
9886                    other => panic!("expected ECHO string, got {other:?}"),
9887                },
9888                _ => panic!("expected one step, got {steps:?}"),
9889            }
9890        }
9891        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
9892            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
9893        }
9894        // Imported bare names qualify; everything else rides through
9895        // byte-identical for the runtime to handle as before.
9896        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }}\"\n";
9897        let out = echo_text(&parse(text, table()).expect("imported bare call parses"));
9898        assert_eq!(out, "n: {{ STD::LEN($x) }}", "bare call qualifies: {out}");
9899        let text = "IMPORT [STD]\nECHO \"n: {{ STD::LEN($x) }}\"\n";
9900        let out = echo_text(&parse(text, table()).expect("qualified parses"));
9901        assert_eq!(
9902            out, "n: {{ STD::LEN($x) }}",
9903            "qualified keys stay untouched: {out}"
9904        );
9905        let text = "IMPORT [STD]\nECHO \"hi {{ $x }} and {{ bare }} and {{ env:K }}\"\n";
9906        let out = echo_text(&parse(text, table()).expect("non-calls parse"));
9907        assert_eq!(
9908            out, "hi {{ $x }} and {{ bare }} and {{ env:K }}",
9909            "non-call keys stay untouched: {out}"
9910        );
9911        let text = "IMPORT [STD]\nECHO \"lit \\{{ LEN($x) }}\"\n";
9912        let out = echo_text(&parse(text, table()).expect("escaped parses"));
9913        assert_eq!(
9914            out, "lit \\{{ LEN($x) }}",
9915            "escaped openers stay literal: {out}"
9916        );
9917        // Nested bodies resolve against the enclosing imports, exactly
9918        // like statement-position calls in the same body.
9919        let text = indoc! {r#"
9920            IMPORT [STD]
9921            FUNC F(): VOID {
9922            ECHO "n: {{ LEN($x) }}"
9923            }
9924        "#};
9925        let steps = parse(text, table()).expect("nested bare call parses");
9926        let body = steps.iter().find_map(|s| match &s.kind {
9927            StepKind::FuncDef { body, .. } => Some(body),
9928            _ => None,
9929        });
9930        match body.map(Vec::as_slice) {
9931            Some([inner]) => match &inner.kind {
9932                StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
9933                    echoed, "n: {{ STD::LEN($x) }}",
9934                    "nested body qualifies: {echoed}"
9935                ),
9936                other => panic!("expected nested ECHO, got {other:?}"),
9937            },
9938            _ => panic!("expected one FUNC with one body step, got {steps:?}"),
9939        };
9940        // Neighboring placeholders keep their exact bytes: only the
9941        // head span changes, so payloads never lose formatting.
9942        let text = "IMPORT [STD]\nECHO \"Call {{ LEN($x) }} and value {{ $y }}\"\n";
9943        let out = echo_text(&parse(text, table()).expect("mixed template parses"));
9944        assert_eq!(
9945            out, "Call {{ STD::LEN($x) }} and value {{ $y }}",
9946            "only the head span changes: {out}"
9947        );
9948        // Unimported bare names fail exactly like statement position:
9949        // qualify it or add the import.
9950        let err = parse("ECHO \"n: {{ LEN($x) }}\"\n", table()).expect_err("must fail");
9951        assert!(
9952            err.to_string().contains("unknown function `LEN`")
9953                && err.to_string().contains("or add `IMPORT"),
9954            "names the fix: {err}"
9955        );
9956        // Two exporters fail closed instead of picking one.
9957        let err = parse(
9958            "IMPORT [STD]\nIMPORT [OTHER]\nECHO \"n: {{ LEN($x) }}\"\n",
9959            table(),
9960        )
9961        .expect_err("must fail");
9962        assert!(
9963            err.to_string().contains("ambiguous function `LEN`"),
9964            "ambiguity fails closed: {err}"
9965        );
9966        // Both lexing pathways agree on rewritten templates.
9967        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }} and {{ $y }}\"\n";
9968        let table = table();
9969        let old = crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
9970            .expect("string path parses");
9971        let reserved = HashSet::new();
9972        let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
9973        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9974        let new = parse_tokens_with_ctx(&toks, &ctx).expect("token path parses");
9975        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9976    }
9977
9978    #[test]
9979    fn placeholder_bare_calls_qualify_in_expr_positions() {
9980        // Regression: `walk_raw_strings_mut` skips `Assign`/`Set`/
9981        // `Call`/`Return`/`If`/`For`/`While`, so `LET`/`RETURN`/call
9982        // args/list/map literals never qualified and failed at
9983        // runtime as undefined variables. Both carriers now qualify.
9984        use crate::ast::{ModuleFuncs, ModuleTable};
9985        use std::collections::{HashMap, HashSet};
9986        let table = || ModuleTable {
9987            modules: HashMap::from([(
9988                crate::constants::STD_MODULE_NAME.to_string(),
9989                Some(ModuleFuncs {
9990                    func_names: HashSet::from(["LEN".to_string()]),
9991                }),
9992            )]),
9993        };
9994        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9995            test_lower_mock::lower(name, args)
9996        }
9997        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
9998            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
9999        }
10000        // LET string literal qualifies.
10001        let steps = parse(
10002            "IMPORT [STD]\nLET $s: STRING = \"n: {{ LEN($x) }}\"\n",
10003            table(),
10004        )
10005        .expect("LET template parses");
10006        match &steps[0].kind {
10007            StepKind::Assign { expr, .. } => match expr {
10008                Expr::Literal(value) => assert_eq!(
10009                    value.as_str().unwrap_or_default(),
10010                    "n: {{ STD::LEN($x) }}",
10011                    "LET qualifies"
10012                ),
10013                other => panic!("expected literal, got {other:?}"),
10014            },
10015            other => panic!("expected Assign, got {other:?}"),
10016        }
10017        // RETURN string literal qualifies.
10018        let steps = parse(
10019            "IMPORT [STD]\nFUNC F(): STRING {\nRETURN \"n: {{ LEN($x) }}\"\n}\n",
10020            table(),
10021        )
10022        .expect("RETURN template parses");
10023        let body = steps.iter().find_map(|s| match &s.kind {
10024            StepKind::FuncDef { body, .. } => Some(body),
10025            _ => None,
10026        });
10027        match body.map(Vec::as_slice) {
10028            Some([inner]) => match &inner.kind {
10029                StepKind::Return { expr, .. } => match &**expr {
10030                    Expr::Literal(value) => assert_eq!(
10031                        value.as_str().unwrap_or_default(),
10032                        "n: {{ STD::LEN($x) }}",
10033                        "RETURN qualifies"
10034                    ),
10035                    other => panic!("expected literal, got {other:?}"),
10036                },
10037                other => panic!("expected RETURN, got {other:?}"),
10038            },
10039            _ => panic!("expected one FUNC, got {steps:?}"),
10040        }
10041        // Call args, list and map literals qualify.
10042        let steps = parse(
10043            "IMPORT [STD]\nLET $y: INT = LEN(\"b: {{ LEN($x) }}\")\n",
10044            table(),
10045        )
10046        .expect("call-arg template parses");
10047        let rendered = format!("{:?}", steps[0].kind);
10048        assert!(
10049            rendered.contains("STD::LEN"),
10050            "call arg qualifies: {rendered}"
10051        );
10052        let steps = parse(
10053            "IMPORT [STD]\nLET $l: LIST<STRING> = [\"{{ LEN($x) }}\"]\n",
10054            table(),
10055        )
10056        .expect("list template parses");
10057        let rendered = format!("{:?}", steps[0].kind);
10058        assert!(rendered.contains("STD::LEN"), "list qualifies: {rendered}");
10059        // Compound placeholders are not single calls: they pass
10060        // through untouched (no partial rewrite) for the runtime to
10061        // fail closed on the whole key.
10062        let text = "IMPORT [STD]\nECHO \"v: {{ LEN($a) + LEN($b) }}\"\n";
10063        let steps = parse(text, table()).expect("compound parses");
10064        match &steps[0].kind {
10065            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10066                echoed, "v: {{ LEN($a) + LEN($b) }}",
10067                "compound untouched: {echoed}"
10068            ),
10069            other => panic!("expected ECHO string, got {other:?}"),
10070        }
10071        // Quoted parens inside args do not end the call early.
10072        let text = "IMPORT [STD]\nECHO 'v: {{ LEN(\"a(b\") }}'\n";
10073        let steps = parse(text, table()).expect("quoted paren parses");
10074        match &steps[0].kind {
10075            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10076                echoed, "v: {{ STD::LEN(\"a(b\") }}",
10077                "quoted paren qualifies: {echoed}"
10078            ),
10079            other => panic!("expected ECHO string, got {other:?}"),
10080        }
10081        // Single-quoted args balance the same way.
10082        let text = "IMPORT [STD]\nECHO \"v: {{ LEN('a(b') }}\"\n";
10083        let steps = parse(text, table()).expect("single-quoted paren parses");
10084        match &steps[0].kind {
10085            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10086                echoed, "v: {{ STD::LEN('a(b') }}",
10087                "single-quoted paren qualifies: {echoed}"
10088            ),
10089            other => panic!("expected ECHO string, got {other:?}"),
10090        }
10091        // `WithIo` boxes its inner command directly (no recursive
10092        // statement pass), so the qualifier must descend into it.
10093        // `LET $p: PIPE` plus bindings keep the shape realistic.
10094        let text = "IMPORT [STD]\nLET $p: PIPE\nWITH_IO [stdout=$p] ECHO 'v: {{ LEN($x) }}'\n";
10095        let steps = parse(text, table()).expect("with-io template parses");
10096        match &steps[1].kind {
10097            StepKind::WithIo { cmd, .. } => {
10098                let rendered = format!("{cmd:?}");
10099                assert!(
10100                    rendered.contains("STD::LEN"),
10101                    "with-io inner qualifies: {rendered}"
10102                );
10103            }
10104            other => panic!("expected WithIo, got {other:?}"),
10105        }
10106        // Single-command wrappers build synthetic body steps without a
10107        // recursive pass: `TIMEOUT 5s <cmd>` and `ASYNC <cmd>` share
10108        // the outer frame, so the qualifier must descend into bodies.
10109        let text = "IMPORT [STD]\nTIMEOUT 5s ECHO 't: {{ LEN($x) }}'\n";
10110        let steps = parse(text, table()).expect("timeout template parses");
10111        let rendered = format!("{:?}", steps[0].kind);
10112        assert!(
10113            rendered.contains("STD::LEN"),
10114            "timeout single qualifies: {rendered}"
10115        );
10116        let text = "IMPORT [STD]\nLET $h: HANDLE<ANY> = ASYNC ECHO 'a: {{ LEN($x) }}'\n";
10117        let steps = parse(text, table()).expect("async template parses");
10118        let rendered = format!("{:?}", steps[0].kind);
10119        assert!(
10120            rendered.contains("STD::LEN"),
10121            "async single qualifies: {rendered}"
10122        );
10123        // Brace bodies keep their own frames: the outer qualifier must
10124        // never re-walk them. A valid nested body qualifies via its own
10125        // recursive pass, and an unknown callee inside one fails with
10126        // the inner position, never re-resolved against the outer frame.
10127        let text = "IMPORT [STD]\nIF true {\nECHO 'v: {{ LEN($x) }}'\n}\n";
10128        let steps = parse(text, table()).expect("nested body qualifies");
10129        let rendered = format!("{:?}", steps[0].kind);
10130        assert!(
10131            rendered.contains("STD::LEN"),
10132            "nested IF body qualifies via its own frame: {rendered}"
10133        );
10134        let err = parse(
10135            "IMPORT [STD]\nIF true {\nECHO 'v: {{ NOPE($x) }}'\n}\n",
10136            table(),
10137        )
10138        .expect_err("nested unknown must fail");
10139        assert!(
10140            err.to_string().contains("unknown function `NOPE`"),
10141            "nested unknown names culprit: {err}"
10142        );
10143    }
10144
10145    #[test]
10146    fn block_conditions_name_unknown_callees() {
10147        // Regression: an unknown callee in a block header condition
10148        // used to miss to the generic `IF needs a condition and a
10149        // block` hint. Classified resolution failures now propagate
10150        // and name the culprit on all four speculative headers.
10151        use crate::ast::{ModuleFuncs, ModuleTable};
10152        use std::collections::{HashMap, HashSet};
10153        let table = || ModuleTable {
10154            modules: HashMap::from([(
10155                crate::constants::STD_MODULE_NAME.to_string(),
10156                Some(ModuleFuncs {
10157                    func_names: HashSet::from(["LEN".to_string()]),
10158                }),
10159            )]),
10160        };
10161        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10162            test_lower_mock::lower(name, args)
10163        }
10164        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10165            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10166        }
10167        for text in [
10168            "IMPORT [STD]\nIF NOPE($x) == 0 {\nECHO hi\n}\n",
10169            "IMPORT [STD]\nIF LEN($x) == 0 {\nECHO hi\n} ELSE IF NOPE($x) == 1 {\nECHO yo\n}\n",
10170            "IMPORT [STD]\nWHILE NOPE($x) > 0 {\nECHO hi\n}\n",
10171            "IMPORT [STD]\nFOR $i: STRING IN NOPE($x) {\nECHO $i\n}\n",
10172        ] {
10173            let err = parse(text, table()).expect_err("unknown callee must fail");
10174            assert!(
10175                err.to_string().contains("unknown function `NOPE`"),
10176                "names the culprit: {err}"
10177            );
10178        }
10179        // Unclassified shape misses still miss (the exact generic
10180        // hint comes from the real dispatcher, which the mock lacks).
10181        parse("IF {\nECHO hi\n}\n", table()).expect_err("empty condition must still fail");
10182    }
10183
10184    #[test]
10185    fn token_and_string_paths_agree_on_let_set_return() {
10186        for text in [
10187            "LET $x: INT = 1",
10188            "LET $s: STRING = \"hi\"",
10189            "LET $b: BOOL = true",
10190            "LET $f: FLOAT = 1.5",
10191            "LET $p: PIPE",
10192            "LET $l: LIST<STRING> = [\"a\", \"b\"]",
10193            "LET $e: LIST<STRING> = []",
10194            "LET $m: MAP = {k: 1}",
10195            "LET $m2: MAP = {\"a b\": 2, k: [1, 2]}",
10196            "LET $n: INT = $a + $b",
10197            "LET $c: BOOL = ($a == 3) && ($b == 4)",
10198            "LET $g: BOOL = !$ok",
10199            "LET $nn: BOOL = true && false",
10200            "LET $e2: STRING = env:HOME",
10201            "LET $k: STRING = $a.b.c",
10202            "LET $u: INT = -5",
10203            "LET $v: INT = 9223372036854775807",
10204            "LET $min: INT = -9223372036854775808",
10205            "LET $w: INT = 1_000",
10206            "LET $z: STRING = a/b",
10207            "LET $d: STRING = -f",
10208            "LET $t: STRING = 30s",
10209            "LET $q: STRING = \"\"\"hi\"\"\"",
10210            "LET $f2: FLOAT = 2 * -3",
10211            "LET $o: BOOL = 2 + 3 > 4",
10212            "LET $l2: LIST< MAP > = []",
10213            "LET $a1: INT = 1 + 2",
10214            "LET $s1: INT = 10 - 4 - 3",
10215            "LET $m1: INT = 2 * 3 + 4",
10216            "LET $x1: BOOL = 1 < 2 == true",
10217            "LET $or: BOOL = $a || $b",
10218            "LET $dbl: BOOL = !!$x",
10219            "LET $ver: STRING = 1.0.0",
10220            "LET $dash: STRING = a-b",
10221            "LET $div: INT = 4 / 2",
10222            "LET $bad: INT = 1__0 + 0",
10223            "LET $strdiv: STRING = 4/2",
10224            "LET $sp: INT = $a - $b",
10225            "$x = 1",
10226            "$x = $a + 1",
10227            "RETURN 1",
10228            KEYWORD_RETURN,
10229            "RETURN $x",
10230            "[env:X] LET $x: INT = 1",
10231            "[os:linux] $x = 2",
10232        ] {
10233            assert_parity(text);
10234        }
10235    }
10236
10237    #[test]
10238    fn malformed_shapes_fail_on_both_paths() {
10239        // Malformed shapes fail on both lexers (messages may differ;
10240        // success/failure must agree). Unbalanced groups fail even
10241        // earlier, at lex time: both layers reject, which is what the
10242        // oracle pins.
10243        for text in [
10244            "[a] ECHO hi",
10245            "[os:atari] ECHO hi",
10246            "[foo:bar] ECHO hi",
10247            "[any(os:linux)] ECHO hi",
10248            "[all()] ECHO hi",
10249            "[env:] ECHO hi",
10250            "[eq(env:K)] ECHO hi",
10251            "[not] ECHO hi",
10252            "ECHO [a;b]",
10253            "ECHO (a;b)",
10254            "ECHO a;b",
10255            "LET $x = 1",
10256            "LET $s: STRING",
10257            "LET $x: INT = 1 2",
10258            "LET $x: INT = (1",
10259            "LET $x: INT = 9223372036854775808",
10260            "$x =",
10261            "RETURN (",
10262            "[env:X]",
10263            "LET $x: INT = $a == $b == $c",
10264            "LET $x: BOOL = $a < $b < $c",
10265            "LET $bs: STRING = a\\nb",
10266            "FOO(\"a\")",
10267            "FOO (\"a\")",
10268            "ECHO FOO(\"a\")",
10269            "ECHO(\"hi\")",
10270            "RUN [a] extra",
10271            "RUN[\"a\"]",
10272            "TIMEOUT 10s RUN[\"a\"]",
10273            "LET $r: STRING = RUN[\"a\"]",
10274            "LET $e: STRING = ECHO",
10275            "ENV A=1 B=2",
10276            "EXPAND \"a b\" c",
10277            "ECHO {a}",
10278            "ECHO K=${x}",
10279            "[!env:A==1] RUN echo no",
10280            "run echo hi",
10281            "LET $x: STRING = AWAIT",
10282            "LET $o: STRING = CANCEL $t",
10283            "LET $x: STRING = ASYNC",
10284            "LET $x: STRING = WITH_IO",
10285            "LET $x: STRING = TIMEOUT",
10286            "LET $x: STRING = ISOLATED",
10287            "LET $x: STRING = ISOLATED ECHO hi",
10288            "COPY A=1",
10289            "WITH_IO [rows=40] RUN echo hi",
10290            "WITH_IO [tty] ECHO hi",
10291            "WITH_IO [tty, stderr=$p] RUN echo hi",
10292            "WITH_IO [tty=$p] RUN echo hi",
10293            "WITH_IO [cols=0] RUN echo hi",
10294            "WITH_IO [cols=65536] RUN echo hi",
10295            "WITH_IO [] ECHO hi",
10296            "WITH_IO [stdin=$p,] ECHO hi",
10297            "WITH_IO stdin=$p ECHO hi",
10298            "WITH_IO [STDIN=$p] ECHO hi",
10299            "WITH_IO [rows] RUN echo hi",
10300            KEYWORD_WITH_IO,
10301            "WITH_IO [stdout=$p]",
10302            "WITH_IO [stdin=$p]\n[os:linux] { ECHO hi }",
10303            "WITH_IO [stdin=$p] { }",
10304            "WITH_IO[stdin=$p] ECHO hi",
10305            "WITH_IO [stdin=$p]ECHO hi",
10306            "WITH_IO [stdin=$p] {{ $x }}",
10307            "ASYNC WITH_IO [stdout=$p] ECHO hi",
10308            "WITH_IO [stdin=$p] AWAIT $t",
10309            "ASYNC AWAIT $t",
10310            "WITH_IO [stdin=$p] RETURN \"hi\"",
10311            "ASYNC RETURN \"hi\"",
10312            "TIMEOUT 10s RETURN \"hi\"",
10313            "TIMEOUT banana ECHO hi",
10314            "TIMEOUT 10ss ECHO hi",
10315            "TIMEOUT 10 s ECHO hi",
10316            "TIMEOUT -5s ECHO hi",
10317            "TIMEOUT 0s ECHO hi",
10318            KEYWORD_TIMEOUT,
10319            "TIMEOUT 10s",
10320            "TIMEOUT { ECHO hi }",
10321            "TIMEOUT \"10s\"",
10322            "TIMEOUT 10s{ECHO hi}",
10323            "TIMEOUT 10sECHO hi",
10324            "TIMEOUT 10s {{ $d }}",
10325            "TIMEOUT 10s { $d }",
10326            "TIMEOUT { $d } ECHO hi",
10327            KEYWORD_ASYNC,
10328            KEYWORD_ISOLATED,
10329            "ISOLATED{ECHO hi}",
10330            KEYWORD_AWAIT,
10331            KEYWORD_CANCEL,
10332            "AWAIT t",
10333            "AWAIT $",
10334            "AWAIT $t extra",
10335            "CANCEL $t extra",
10336            "TIMEOUT 5s INHERIT_ENV [M]",
10337            "TIMEOUT 5s { INHERIT_ENV [M] }",
10338            "ASYNC { INHERIT_ENV [M] }",
10339            "LET $x: STRING = INHERIT_ENV [M]",
10340            "TIMEOUT 10s WITH_IO [stdin=$p] { ECHO hi }",
10341            "ISOLATED WITH_IO [stdin=$p] { ECHO hi }",
10342            "TIMEOUT 10s AWAIT $ t",
10343            "LET $o: STRING = AWAIT $ t",
10344            "ISOLATED AWAIT $ t",
10345            "WITH_IO [stdin=$p] CANCEL $ t",
10346            "LET $ x: INT = 1",
10347            "LET $x: STRING = WITH_IO [stdin=$p] { ECHO hi }",
10348            "LET $x: STRING = WITH_IO [stdin=$p] ASYNC",
10349            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO a\nECHO b }",
10350            "LET $x: STRING = WITH_IO [stdout=$p] ECHO hi",
10351            "LET $x: STRING = TIMEOUT 10s AWAIT $t",
10352            "LET $x: STRING = CANCEL $t",
10353            "LET $x: STRING = ASYNC",
10354            "LET $x: STRING = WITH_IO",
10355            "TIMEOUT 10s LET $x: INT = 1",
10356            "LET $x: STRING = FOO bar",
10357            "LET(\"a\")",
10358            "AWAIT($t)",
10359            "CANCEL($t)",
10360            "TIMEOUT(\"10s\") ECHO hi",
10361            "RETURN ECHO bye",
10362        ] {
10363            match crate::tok::lex_str(text) {
10364                Err(_) => {
10365                    assert!(
10366                        crate::parse_script(text, lower).is_err(),
10367                        "backend must also reject lex-broken input: {text:?}"
10368                    );
10369                    continue;
10370                }
10371                Ok(toks) => {
10372                    assert!(
10373                        parse_tokens(&toks, lower).is_err(),
10374                        "v2 must explicitly reject (not silently drift): {text:?}"
10375                    );
10376                }
10377            }
10378            assert!(
10379                crate::parse_script(text, lower).is_err(),
10380                "backend must also reject (oracle agreement): {text:?}"
10381            );
10382        }
10383        // No deferred shapes remain: every statement-level block and
10384        // inline-block expression parses natively.
10385    }
10386
10387    #[test]
10388    fn deferred_unknown_callee_beats_validation_arg_error() {
10389        // Directive 5: `WORKSPACE NOPE()` stashes `unknown function
10390        // NOPE` while the fallback raw string fails `WORKSPACE`
10391        // validation. On a well-formed header the stashed callee error
10392        // names the culprit instead of the misleading arg-shape error.
10393        let err =
10394            crate::parse_script("WORKSPACE NOPE()", lower).expect_err("unknown callee must fail");
10395        assert!(
10396            err.to_string().contains("unknown function `NOPE`"),
10397            "deferred must beat validation, got: {err}"
10398        );
10399    }
10400
10401    #[test]
10402    fn paren_line_break_reports_token_position() {
10403        // Directive 5: multiline paren breaks carry the offending
10404        // token's line/col, not a stamped 0/0. The break sits on line 2
10405        // while the statement opens on line 1.
10406        let err = crate::parse_script("ECHO (a\nb)", lower).expect_err("break must fail");
10407        let rendered = err.to_string();
10408        assert!(
10409            rendered.contains("unexpected line break"),
10410            "break must report, got: {rendered}"
10411        );
10412    }
10413
10414    #[test]
10415    fn deferred_unknown_callee_beats_invalid_syntax_arg_error() {
10416        // Fallback raw strings can trigger `InvalidSyntax` lowering
10417        // (for example `COPY NOPE()`). The stashed unknown-callee error
10418        // still names the culprit on a recognized head.
10419        for text in ["COPY NOPE()", "WRITE NOPE()"] {
10420            let err = crate::parse_script(text, lower).expect_err("unknown callee must fail");
10421            assert!(
10422                err.to_string().contains("unknown function `NOPE`"),
10423                "deferred must beat InvalidSyntax for {text:?}, got: {err}"
10424            );
10425        }
10426    }
10427
10428    #[test]
10429    fn deferred_beats_lowering_invalid_syntax_on_plain_heads() {
10430        // Plain command heads own no header grammar, so a lowering
10431        // `InvalidSyntax` there is an argument-shape failure from the
10432        // raw-text fallback: the stashed unknown-callee names the
10433        // culprit on every such head (no per-command allowlist).
10434        let lower_invalid =
10435            |name: &str, _args: Vec<crate::Arg>| -> crate::ParseResult<crate::StepKind> {
10436                Err(crate::ParseError::invalid_syntax(
10437                    name,
10438                    format!("{name} header is malformed"),
10439                    None,
10440                    Vec::new(),
10441                    None,
10442                    &crate::error::SpanContext::line_only(0),
10443                ))
10444            };
10445        for text in [
10446            "ASSERT_EQ $a NOSUCHFUNC()",
10447            "SYMLINK $a NOSUCHFUNC()",
10448            "COPY $a NOSUCHFUNC()",
10449            "WRITE $a NOSUCHFUNC()",
10450        ] {
10451            let err = crate::parse_script(text, lower_invalid).expect_err("arg error must fail");
10452            assert!(
10453                err.to_string().contains("unknown function `NOSUCHFUNC`"),
10454                "deferred must beat lowering InvalidSyntax for {text:?}, got: {err}"
10455            );
10456        }
10457        // Header-owned heads keep their lowering `InvalidSyntax`: the
10458        // native parser missed to the generic path on shape miss, so
10459        // the lowering error names the malformed header while the
10460        // stashed name is its definiendum, never a call.
10461        let err = crate::parse_script("FUNC $a NOSUCHFUNC()", lower_invalid)
10462            .expect_err("header syntax must fail");
10463        assert!(
10464            err.to_string().contains("header is malformed"),
10465            "header InvalidSyntax must stand on FUNC, got: {err}"
10466        );
10467    }
10468
10469    #[test]
10470    fn trailing_tokens_after_func_block_never_hoist() {
10471        // A `FUNC` header with trailing tokens after the body block is
10472        // malformed (the real path rejects it), so pre-declaration
10473        // must not hoist the name: the forward call fails instead of
10474        // resolving.
10475        let err = crate::parse_script(
10476            "LET $x: STRING = FOO()\nFUNC FOO(): STRING { RETURN \"a\" } TRAILING\n",
10477            lower,
10478        )
10479        .expect_err("trailing tokens must fail");
10480        assert!(
10481            err.to_string().contains("unknown function `FOO`"),
10482            "unhoisted forward call must fail, got: {err}"
10483        );
10484    }
10485
10486    #[test]
10487    fn forward_reference_resolves_regardless_of_order() {
10488        // `CALLER` calls `CALLEE` defined later. Top-level
10489        // pre-declaration hoists names before lowering, so order
10490        // does not matter. Runtime still executes sequentially;
10491        // the call below runs after both definitions.
10492        let steps = crate::parse_script(
10493            "FUNC CALLER(): STRING { RETURN CALLEE() }\nFUNC CALLEE(): STRING { RETURN \"forward-ok\" }\n",
10494            lower,
10495        )
10496        .expect("forward ref must parse");
10497        assert!(
10498            matches!(&steps[0].kind, crate::StepKind::FuncDef { name, .. } if name == "CALLER"),
10499            "first def kept, got: {:?}",
10500            steps[0].kind
10501        );
10502    }
10503
10504    #[test]
10505    fn forward_reference_to_guarded_func_resolves() {
10506        // Guarded definitions hoist like unguarded ones: `parse_func_at`
10507        // registers `[os:macos] FUNC FOO` unconditionally, so a forward
10508        // call before the definition must resolve identically to a
10509        // backward call after it.
10510        let steps = crate::parse_script(
10511            "LET $x: STRING = FOO()\n[os:macos] FUNC FOO(): STRING { RETURN \"guarded\" }\n",
10512            lower,
10513        )
10514        .expect("forward guarded ref must parse");
10515        assert!(
10516            matches!(&steps[1].kind, crate::StepKind::FuncDef { name, .. } if name == "FOO"),
10517            "guarded def kept, got: {:?}",
10518            steps[1].kind
10519        );
10520    }
10521}