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_FAIL, KEYWORD_FOR, KEYWORD_FROM, KEYWORD_FUNC,
99    KEYWORD_IF, 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/// `FAIL [<code>] [<message>] [{ <block> }]`: message and/or block
3976/// required, code optional. The trailing brace (when present and not
3977/// a `{{ }}` template) parses as a child-scope body that reads
3978/// caller locals; the remaining tokens lower as 0-2 plain args (no `KEY=VAL`). One arg
3979/// is the message unless it is a bare int literal, which is the
3980/// code (`FAIL 2` exits silently, `FAIL "2"` prints); two args are
3981/// code plus message with the code statically int-checked like
3982/// `EXIT`. `None` on shape miss (joint head, `KEY=VAL`, >2 args fall
3983/// to generic, which fails with the `FAIL` hint).
3984fn parse_fail_single(
3985    toks: &[Tok],
3986    pos: usize,
3987    stmt: usize,
3988    ctx: &ParseCtx,
3989) -> Result<Option<(StepKind, usize)>, TokenError> {
3990    let head_ok =
3991        matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FAIL);
3992    if !head_ok {
3993        return Ok(None);
3994    }
3995    let next_joint = toks.get(pos + 1).is_some_and(|t| t.joint);
3996    if next_joint {
3997        return Ok(None);
3998    }
3999    let end = toks.len();
4000    let mut arg_end = end;
4001    let mut body: Vec<Step> = Vec::new();
4002    // Brace presence is tracked apart from body length: `FAIL {}`
4003    // is a valid empty block, while a missing block leaves no
4004    // braces at all.
4005    let mut has_block = false;
4006    if let Some(last) = toks.last()
4007        && matches!(
4008            &last.kind,
4009            TokKind::Group {
4010                delim: GroupDelim::Brace,
4011                ..
4012            }
4013        )
4014        && !is_template_brace(last)
4015        && end > pos + 1
4016    {
4017        let inner = match &last.kind {
4018            TokKind::Group { inner, .. } => inner.clone(),
4019            _ => unreachable!(),
4020        };
4021        body = parse_body_steps(&inner, stmt, ctx, false)?;
4022        arg_end = end - 1;
4023        has_block = true;
4024    }
4025    let arg_toks = if arg_end > pos + 1 {
4026        &toks[pos + 1..arg_end]
4027    } else {
4028        &[]
4029    };
4030    if !arg_toks.is_empty() && arg_toks.first().is_some_and(|t| t.joint) {
4031        return Ok(None);
4032    }
4033    let (tokens, deferred) = build_arg_tokens(arg_toks, stmt, ctx)?;
4034    let mut args: Vec<Arg> = Vec::with_capacity(tokens.len());
4035    for token in tokens {
4036        match token {
4037            InsToken::Pos(arg) => args.push(arg),
4038            InsToken::Assign(..) => return Ok(None),
4039        }
4040    }
4041    if args.len() > 2 {
4042        return Ok(None);
4043    }
4044    if args.is_empty() && !has_block {
4045        return Ok(None);
4046    }
4047    if let Some(err) = deferred {
4048        return Err(err);
4049    }
4050    let (code, message) = match args.len() {
4051        0 => (None, None),
4052        1 => {
4053            let mut it = args.into_iter();
4054            let only = it.next();
4055            // A lone bare int is a silent code (`FAIL 2`); anything
4056            // else (quoted text, `$var`, templates) is the message.
4057            // Quoting decides: `FAIL "2"` prints `2` and exits 1.
4058            match &only {
4059                Some(Arg::String(s, false))
4060                    if crate::command::strip_digit_separators(s)
4061                        .parse::<i64>()
4062                        .is_ok() =>
4063                {
4064                    (only, None)
4065                }
4066                _ => (None, only),
4067            }
4068        }
4069        _ => {
4070            let mut it = args.into_iter();
4071            let code = it.next();
4072            let message = it.next();
4073            // The code position is statically int-checked like
4074            // `EXIT`: a non-int literal fails here, while `$var`
4075            // and templates defer to runtime resolution.
4076            if let Some(arg) = &code {
4077                crate::command::ArgType::Int
4078                    .check_arg(arg)
4079                    .map_err(|e| TokenError {
4080                        stmt,
4081                        msg: e.to_string(),
4082                        line: 0,
4083                        col: 0,
4084                        kind: Some(ParseErrorKind::Validation {
4085                            command: KEYWORD_FAIL.to_string(),
4086                        }),
4087                    })?;
4088            }
4089            (code, message)
4090        }
4091    };
4092    crate::commands::rewrite_isolated_inherit(&mut body);
4093    let kind = StepKind::Fail {
4094        code,
4095        message,
4096        body,
4097    };
4098    let span = lowering_ctx(stmt);
4099    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
4100        stmt,
4101        msg: e.to_string(),
4102        line: 0,
4103        col: 0,
4104        kind: None,
4105    })?;
4106    Ok(Some((kind, end - pos)))
4107}
4108
4109/// Single (non-block) `ASYNC`: one inner command or block (blocks
4110/// admit a joint brace, like `async_statement_block`'s `sep?`).
4111/// Top-level `WITH_IO` steps fail through the shared reject; the
4112/// `LET` path never scans (probed: it accepts). `None` on shape
4113/// miss (missing/joint-single inner: generic fails it).
4114fn parse_async_single(
4115    toks: &[Tok],
4116    pos: usize,
4117    stmt: usize,
4118    ctx: &ParseCtx,
4119) -> Result<Option<(StepKind, usize)>, TokenError> {
4120    let Some(next) = toks.get(pos + 1) else {
4121        return Ok(None);
4122    };
4123    // Block form admits a joint brace (`ASYNC{...}`, probed); the
4124    // single form needs its `sep`.
4125    if matches!(
4126        &next.kind,
4127        TokKind::Group {
4128            delim: GroupDelim::Brace,
4129            ..
4130        }
4131    ) && !is_template_brace(next)
4132    {
4133        let inner = match &next.kind {
4134            TokKind::Group { inner, .. } => inner.clone(),
4135            _ => unreachable!(),
4136        };
4137        let body = parse_body_steps(&inner, stmt, ctx, false)?;
4138        let span = lowering_ctx(stmt);
4139        crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| TokenError {
4140            stmt,
4141            msg: e.to_string(),
4142            line: 0,
4143            col: 0,
4144            kind: None,
4145        })?;
4146        let kind = StepKind::AsyncBlock { body };
4147        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
4148            stmt,
4149            msg: e.to_string(),
4150            line: 0,
4151            col: 0,
4152            kind: None,
4153        })?;
4154        return Ok(Some((kind, 2)));
4155    }
4156    if next.joint {
4157        return Ok(None);
4158    }
4159    let (cmd, used) = parse_single_inner(
4160        toks,
4161        pos + 1,
4162        stmt,
4163        ctx,
4164        InnerRules {
4165            allow_await: false,
4166            allow_with_io: false,
4167        },
4168    )?;
4169    let body = vec![Step {
4170        guard: None,
4171        kind: cmd,
4172        scope_enter: 0,
4173        scope_exit: 0,
4174        line: 0,
4175        col: 0,
4176    }];
4177    let span = lowering_ctx(stmt);
4178    crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| TokenError {
4179        stmt,
4180        msg: e.to_string(),
4181        line: 0,
4182        col: 0,
4183        kind: None,
4184    })?;
4185    let kind = StepKind::AsyncBlock { body };
4186    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
4187        stmt,
4188        msg: e.to_string(),
4189        line: 0,
4190        col: 0,
4191        kind: None,
4192    })?;
4193    Ok(Some((kind, 1 + used)))
4194}
4195
4196// ---- Block statements, directives, REMOTE ----
4197// `IF`/`FOR`/`WHILE`/`FUNC` parse their headers token-natively with
4198// miss-to-generic fallback (the grammar's committed `instruction`
4199// path); bodies lower recursively with pushed scopes. `TYPE` builds
4200// aliases through a maximal type-shape match; `IMPORT`/`EXPORT` are
4201// zero-step frame/table directives; `REMOTE` validates targets,
4202// bindings, bodies, and outer-call containment through the shared
4203// validators. Guard blocks fold guards with scope markers at top
4204// level and mirror the nested quirk formula in bodies. A whole-script
4205// post-pass runs the shared validations (prelude order, COPY
4206// placement, EXPORT membership).
4207
4208/// Uppercase identifier mirror (`func_ident`, `type_name`,
4209/// `import_module`): ASCII upper start, upper/digit/`_` rest.
4210fn is_upper_ident(w: &str) -> bool {
4211    !w.is_empty()
4212        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
4213        && w.chars()
4214            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
4215}
4216
4217/// Lowercase identifier mirror (`field_name`): ASCII lower start,
4218/// lower/digit/`_` rest.
4219fn is_lower_ident(w: &str) -> bool {
4220    !w.is_empty()
4221        && w.chars().next().is_some_and(|c| c.is_ascii_lowercase())
4222        && w.chars()
4223            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
4224}
4225
4226/// `$name` with gapless adjacency (atomic `dollar_ident`); `None` on
4227/// shape miss (the caller falls back to generic, which fails in
4228/// lowering like the grammar's committed `instruction`).
4229fn peek_dollar_var(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
4230    match (toks.get(pos), toks.get(pos + 1)) {
4231        (Some(dollar), Some(name))
4232            if matches!(&dollar.kind, TokKind::Punct('$'))
4233                && name.joint
4234                && matches!(&name.kind, TokKind::Word(w) if is_ident_word(w)) =>
4235        {
4236            match &name.kind {
4237                TokKind::Word(w) => Some((w.clone(), 2)),
4238                _ => unreachable!(),
4239            }
4240        }
4241        _ => None,
4242    }
4243}
4244
4245/// Skip statement-level newlines (multi-line `<...>` shapes ride
4246/// them into the body) before the next type token. Narrower than
4247/// `gap_nl` on purpose: comments keep failing here exactly like
4248/// single-line shapes, so only the separator moves.
4249fn skip_type_nl(toks: &[Tok], mut p: usize) -> usize {
4250    while matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Newline)) {
4251        p += 1;
4252    }
4253    p
4254}
4255
4256/// Maximal `type_tag` match over toks (non-atomic: gaps free
4257/// everywhere): atoms with `<>` args, `|` unions, `name?:` fields,
4258/// and one `= literal` default tail per field.
4259/// Returns the exclusive end index, or `None` on shape miss.
4260fn parse_type_shape(toks: &[Tok], pos: usize) -> Option<usize> {
4261    let mut p = parse_type_atom(toks, skip_type_nl(toks, pos))?;
4262    loop {
4263        let q = skip_type_nl(toks, p);
4264        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('|'))) {
4265            return Some(p);
4266        }
4267        p = parse_type_atom(toks, skip_type_nl(toks, q + 1))?;
4268    }
4269}
4270
4271fn parse_type_atom(toks: &[Tok], pos: usize) -> Option<usize> {
4272    let pos = skip_type_nl(toks, pos);
4273    match toks.get(pos).map(|t| &t.kind) {
4274        Some(TokKind::Word(w)) if is_upper_ident(w) => {}
4275        _ => return None,
4276    }
4277    let mut p = skip_type_nl(toks, pos + 1);
4278    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('<'))) {
4279        p = parse_type_args(toks, skip_type_nl(toks, p + 1))?;
4280        p = skip_type_nl(toks, p);
4281        if !matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('>'))) {
4282            return None;
4283        }
4284        p += 1;
4285    }
4286    Some(p)
4287}
4288
4289fn parse_type_args(toks: &[Tok], pos: usize) -> Option<usize> {
4290    let mut p = parse_type_field(toks, skip_type_nl(toks, pos))?;
4291    loop {
4292        let q = skip_type_nl(toks, p);
4293        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(','))) {
4294            return Some(p);
4295        }
4296        p = parse_type_field(toks, skip_type_nl(toks, q + 1))?;
4297    }
4298}
4299
4300fn parse_type_field(toks: &[Tok], pos: usize) -> Option<usize> {
4301    let mut p = skip_type_nl(toks, pos);
4302    // Optional `name?:` prefix (lowercase names only, like the
4303    // grammar's `field_name`).
4304    if let Some(TokKind::Word(w)) = toks.get(p).map(|t| &t.kind)
4305        && is_lower_ident(w)
4306    {
4307        let mut q = skip_type_nl(toks, p + 1);
4308        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('?'))) {
4309            q = skip_type_nl(toks, q + 1);
4310        }
4311        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4312            p = skip_type_nl(toks, q + 1);
4313        }
4314    }
4315    let mut p = parse_type_shape(toks, p)?;
4316    // Optional `ALIAS name` clause (#310.5): one alternate CLI spelling
4317    // for `TYPE FLAGS` fields. Skipped as a unit here so the shape
4318    // matcher covers it; the spelling parser owns validation, and the
4319    // renderer carries the raw tokens through. Order is fixed:
4320    // `TYPE [ALIAS alias] [= default]`. The alias word itself rides
4321    // along regardless of case so a miscapitalized alias still reaches
4322    // the spelling diagnostic instead of missing to unknown-command.
4323    let q = skip_type_nl(toks, p);
4324    if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Word(w)) if w == crate::tag::ALIAS_KEYWORD)
4325    {
4326        p = skip_type_nl(toks, q + 1);
4327        if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Word(_))) {
4328            p = skip_type_nl(toks, p + 1);
4329        }
4330    }
4331    // Optional `= ...` default tail: consume to the next field
4332    // delimiter (`,`, `>`, `|` at angle depth zero), tracking `<>`
4333    // so nested shapes ride along. Any spacing, any tokens:
4334    // literals, `$vars`, `env:` reads, calls. The spelling parser
4335    // owns literal validation, so non-literals fail there naming
4336    // the alias instead of missing here as unknown-command noise.
4337    let q = skip_type_nl(toks, p);
4338    if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('=')))
4339        && !matches!(toks.get(q + 1).map(|t| &t.kind), Some(TokKind::Punct('=')))
4340    {
4341        let mut r = skip_type_nl(toks, q + 1);
4342        let mut depth = 0usize;
4343        loop {
4344            match toks.get(r).map(|t| &t.kind) {
4345                Some(TokKind::Punct('<')) => {
4346                    depth += 1;
4347                    r = skip_type_nl(toks, r + 1);
4348                }
4349                Some(TokKind::Punct('>')) => {
4350                    if depth == 0 {
4351                        break;
4352                    }
4353                    depth -= 1;
4354                    r = skip_type_nl(toks, r + 1);
4355                }
4356                Some(TokKind::Punct(',' | '|')) if depth == 0 => break,
4357                Some(_) => {
4358                    r += 1;
4359                }
4360                None => break,
4361            }
4362        }
4363        p = r;
4364    }
4365    Some(p)
4366}
4367
4368/// Single (non-block) `IF`: condition plus then-block with an
4369/// opportunistic `ELSE` chain (a malformed `ELSE` stays for the
4370/// element loop, which fails it in lowering exactly like the
4371/// grammar). `None` on shape miss (missing/joint-agnostic block or
4372/// unclassified bad condition: generic fails it); classified
4373/// expression failures (unknown/ambiguous callees) and inline-block
4374/// failures propagate (blocks lower here, so their errors surface
4375/// directly).
4376fn parse_if_at(
4377    toks: &[Tok],
4378    pos: usize,
4379    stmt: usize,
4380    ctx: &ParseCtx,
4381) -> Result<Option<(StepKind, usize)>, TokenError> {
4382    // Condition entry skips leading gap comments (`IF` uses `gap`).
4383    let mut lead = Cursor::expr(&toks[pos + 1..], stmt);
4384    lead.skip_gap();
4385    let mut cur = Cursor::expr(&toks[pos + 1 + lead.pos..], stmt);
4386    let cond = match parse_expr_checked(&mut cur, ctx) {
4387        Ok(expr) => expr,
4388        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4389        // Classified failures (unknown/ambiguous callees) name the
4390        // culprit instead of missing to the generic IF hint: the head
4391        // is unambiguously `IF`, so there is no alternative parse.
4392        Err(e) if e.kind.is_some() => return Err(e),
4393        Err(_) => return Ok(None),
4394    };
4395    let cond_end = pos + 1 + lead.pos + cur.pos;
4396    // Then-block: any gap (`gap` zero-width), never a template.
4397    let then_brace = match toks.get(cond_end) {
4398        Some(t)
4399            if matches!(
4400                &t.kind,
4401                TokKind::Group {
4402                    delim: GroupDelim::Brace,
4403                    ..
4404                }
4405            ) && !is_template_brace(t) =>
4406        {
4407            t
4408        }
4409        _ => return Ok(None),
4410    };
4411    let then_inner = match &then_brace.kind {
4412        TokKind::Group { inner, .. } => inner.clone(),
4413        _ => unreachable!(),
4414    };
4415    let then_body = parse_body_steps(&then_inner, stmt, ctx, false)?;
4416    let mut p = cond_end + 1;
4417    // Gap comments between the blocks and `ELSE` vanish (merge
4418    // junctions contribute newlines, crossed like `blank*`).
4419    {
4420        let mut gcur = Cursor::expr(&toks[p..], stmt);
4421        gcur.skip_gap_nl();
4422        p += gcur.pos;
4423    }
4424    let mut else_ifs = Vec::new();
4425    let mut else_body = None;
4426    loop {
4427        // `ELSE IF cond block`: any gaps (non-atomic chain).
4428        let is_else_if = matches!(
4429            toks.get(p).map(|t| &t.kind),
4430            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4431        ) && matches!(
4432            toks.get(p + 1).map(|t| &t.kind),
4433            Some(TokKind::Word(w)) if w == KEYWORD_IF
4434        );
4435        if is_else_if {
4436            let mut ecur = Cursor::expr(&toks[p + 2..], stmt);
4437            ecur.skip_gap();
4438            let econd = match parse_expr_checked(&mut ecur, ctx) {
4439                Ok(expr) => expr,
4440                Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4441                // Same classified-error rule as the `IF` head above:
4442                // an `ELSE IF` with a resolvable-but-unknown callee
4443                // names it instead of silently dropping the branch.
4444                Err(e) if e.kind.is_some() => return Err(e),
4445                Err(_) => break,
4446            };
4447            let ebrace = p + 2 + ecur.pos;
4448            let eblock_ok = matches!(
4449                toks.get(ebrace).map(|t| &t.kind),
4450                Some(TokKind::Group {
4451                    delim: GroupDelim::Brace,
4452                    ..
4453                })
4454            ) && toks.get(ebrace).is_some_and(|t| !is_template_brace(t));
4455            if !eblock_ok {
4456                break;
4457            }
4458            let einner = match &toks[ebrace].kind {
4459                TokKind::Group { inner, .. } => inner.clone(),
4460                _ => unreachable!(),
4461            };
4462            let ebody = parse_body_steps(&einner, stmt, ctx, false)?;
4463            else_ifs.push((Box::new(econd), ebody));
4464            p = ebrace + 1;
4465            // Gap comments before a further `ELSE` vanish too
4466            // (merge junctions contribute newlines).
4467            {
4468                let mut gcur = Cursor::expr(&toks[p..], stmt);
4469                gcur.skip_gap_nl();
4470                p += gcur.pos;
4471            }
4472            continue;
4473        }
4474        // `ELSE block`: same opportunism (a bare `ELSE` stays for
4475        // the loop, failing in lowering like the grammar).
4476        let is_else = matches!(
4477            toks.get(p).map(|t| &t.kind),
4478            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4479        ) && matches!(
4480            toks.get(p + 1).map(|t| &t.kind),
4481            Some(TokKind::Group {
4482                delim: GroupDelim::Brace,
4483                ..
4484            })
4485        ) && toks.get(p + 1).is_some_and(|t| !is_template_brace(t));
4486        if !is_else {
4487            break;
4488        }
4489        let einner = match &toks[p + 1].kind {
4490            TokKind::Group { inner, .. } => inner.clone(),
4491            _ => unreachable!(),
4492        };
4493        else_body = Some(parse_body_steps(&einner, stmt, ctx, false)?);
4494        p += 2;
4495        break;
4496    }
4497    let kind = StepKind::If {
4498        cond: Box::new(cond),
4499        then_body,
4500        else_ifs,
4501        else_body,
4502    };
4503    Ok(Some((kind, p - pos)))
4504}
4505
4506/// Parse one `CASE` value list: comma-separated expressions up to (not
4507/// including) the arm body brace. Groups are atomic tokens, so commas
4508/// inside calls, lists, and maps never split. Returns the values plus
4509/// the token count consumed past the `CASE` word.
4510fn parse_case_values(
4511    toks: &[Tok],
4512    stmt: usize,
4513    ctx: &ParseCtx,
4514) -> Result<(Vec<Expr>, usize), TokenError> {
4515    let mut values = Vec::new();
4516    let mut p = 0;
4517    loop {
4518        let mut gcur = Cursor::expr(&toks[p..], stmt);
4519        gcur.skip_gap_nl();
4520        let start = p + gcur.pos;
4521        let mut vcur = Cursor::expr(&toks[start..], stmt);
4522        let value = match parse_expr_checked(&mut vcur, ctx) {
4523            Ok(expr) => expr,
4524            Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4525            Err(e) => return Err(e),
4526        };
4527        // A `{ ... }` block is never a case value: without this, a
4528        // missing `CASE` value consumes the arm body as a block
4529        // expression and fails downstream instead of naming the miss.
4530        if matches!(value, Expr::Block(_)) {
4531            return Err(TokenError {
4532                stmt,
4533                line: 0,
4534                col: 0,
4535                msg: "SWITCH CASE requires a value or condition before '{'".to_string(),
4536                kind: None,
4537            });
4538        }
4539        values.push(value);
4540        p = start + vcur.pos;
4541        let mut gcur = Cursor::expr(&toks[p..], stmt);
4542        gcur.skip_gap_nl();
4543        p += gcur.pos;
4544        if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(','))) {
4545            p += 1;
4546            continue;
4547        }
4548        break;
4549    }
4550    Ok((values, p))
4551}
4552
4553/// Parsed `SWITCH` arms: one value list plus body per `CASE`, with
4554/// an optional trailing `DEFAULT` body.
4555type SwitchArms = (Vec<(Vec<Expr>, Vec<Step>)>, Option<Vec<Step>>);
4556
4557/// Parse the arms inside a `SWITCH` body brace: `CASE <values> { ... }`
4558/// arms plus an optional trailing `DEFAULT { ... }`. Hard errors once
4559/// committed (the `SWITCH` head is unambiguous): unknown words, empty
4560/// bodies, missing blocks, duplicate or non-trailing `DEFAULT`.
4561fn parse_switch_body(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<SwitchArms, TokenError> {
4562    let err = |msg: String| TokenError {
4563        stmt,
4564        line: 0,
4565        col: 0,
4566        msg,
4567        kind: None,
4568    };
4569    let mut cases: Vec<(Vec<Expr>, Vec<Step>)> = Vec::new();
4570    let mut default_body: Option<Vec<Step>> = None;
4571    let mut p = 0;
4572    loop {
4573        let mut gcur = Cursor::expr(&inner[p..], stmt);
4574        gcur.skip_gap_nl();
4575        p += gcur.pos;
4576        if p >= inner.len() {
4577            break;
4578        }
4579        let word = match &inner[p].kind {
4580            TokKind::Word(w) => w.clone(),
4581            _ => {
4582                return Err(err(
4583                    "SWITCH body must hold CASE or DEFAULT arms, e.g. `SWITCH $cmd { CASE \"a\" { ECHO yes } DEFAULT { ECHO no } }`".to_string(),
4584                ));
4585            }
4586        };
4587        if word == KEYWORD_CASE {
4588            if default_body.is_some() {
4589                return Err(err(
4590                    "SWITCH DEFAULT must be the last arm; no CASE may follow it".to_string(),
4591                ));
4592            }
4593            let (values, used) = parse_case_values(&inner[p + 1..], stmt, ctx)?;
4594            p += 1 + used;
4595            let mut bcur = Cursor::expr(&inner[p..], stmt);
4596            bcur.skip_gap_nl();
4597            p += bcur.pos;
4598            let arm_ok = matches!(
4599                inner.get(p).map(|t| &t.kind),
4600                Some(TokKind::Group {
4601                    delim: GroupDelim::Brace,
4602                    ..
4603                })
4604            ) && inner.get(p).is_some_and(|t| !is_template_brace(t));
4605            if !arm_ok {
4606                return Err(err(
4607                    "SWITCH CASE needs a braced block, e.g. `CASE \"a\", \"b\" { ECHO yes }`"
4608                        .to_string(),
4609                ));
4610            }
4611            let arm_inner = match &inner[p].kind {
4612                TokKind::Group { inner, .. } => inner.clone(),
4613                _ => unreachable!(),
4614            };
4615            let body = parse_body_steps(&arm_inner, stmt, ctx, false)?;
4616            cases.push((values, body));
4617            p += 1;
4618        } else if word == KEYWORD_DEFAULT {
4619            if default_body.is_some() {
4620                return Err(err("SWITCH allows only one DEFAULT arm".to_string()));
4621            }
4622            p += 1;
4623            let mut bcur = Cursor::expr(&inner[p..], stmt);
4624            bcur.skip_gap_nl();
4625            p += bcur.pos;
4626            let arm_ok = matches!(
4627                inner.get(p).map(|t| &t.kind),
4628                Some(TokKind::Group {
4629                    delim: GroupDelim::Brace,
4630                    ..
4631                })
4632            ) && inner.get(p).is_some_and(|t| !is_template_brace(t));
4633            if !arm_ok {
4634                return Err(err(
4635                    "SWITCH DEFAULT needs a braced block, e.g. `DEFAULT { ECHO fallback }`"
4636                        .to_string(),
4637                ));
4638            }
4639            let arm_inner = match &inner[p].kind {
4640                TokKind::Group { inner, .. } => inner.clone(),
4641                _ => unreachable!(),
4642            };
4643            default_body = Some(parse_body_steps(&arm_inner, stmt, ctx, false)?);
4644            p += 1;
4645        } else {
4646            return Err(err(
4647                "SWITCH body must hold CASE or DEFAULT arms, e.g. `SWITCH $cmd { CASE \"a\" { ECHO yes } DEFAULT { ECHO no } }`".to_string(),
4648            ));
4649        }
4650    }
4651    if cases.is_empty() && default_body.is_none() {
4652        return Err(err(
4653            "SWITCH needs at least one CASE or DEFAULT arm".to_string()
4654        ));
4655    }
4656    Ok((cases, default_body))
4657}
4658
4659/// `SWITCH [disc] { CASE v, ... { ... } ... [DEFAULT { ... }] }` or
4660/// bare `SWITCH { CASE <bool> { ... } ... }`. `None` on shape miss (no
4661/// outer brace: falls to generic, which fails it with the SWITCH hint);
4662/// classified expression failures propagate like `IF`, and arm errors
4663/// are hard (the head commits the shape).
4664fn parse_switch_at(
4665    toks: &[Tok],
4666    pos: usize,
4667    stmt: usize,
4668    ctx: &ParseCtx,
4669) -> Result<Option<(StepKind, usize)>, TokenError> {
4670    // Bare head: gaps skipped like the discriminant entry below; the
4671    // token then opens the body brace, so no discriminant is parsed
4672    // (every `CASE` carries its own condition).
4673    let mut gap = Cursor::expr(&toks[pos + 1..], stmt);
4674    gap.skip_gap();
4675    let brace_pos = pos + 1 + gap.pos;
4676    let bare_head = matches!(
4677        toks.get(brace_pos).map(|t| &t.kind),
4678        Some(TokKind::Group {
4679            delim: GroupDelim::Brace,
4680            ..
4681        })
4682    ) && toks.get(brace_pos).is_some_and(|t| !is_template_brace(t));
4683    let p: usize;
4684    let discriminant = if bare_head {
4685        p = brace_pos;
4686        None
4687    } else {
4688        // Discriminant entry reuses the skipped gaps above (`IF` uses
4689        // the same gap rule).
4690        let mut cur = Cursor::expr(&toks[brace_pos..], stmt);
4691        let disc = match parse_expr_checked(&mut cur, ctx) {
4692            Ok(expr) => expr,
4693            Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4694            // Same classified-error rule as the `IF` head above: the
4695            // head is unambiguous, so resolvable-but-unknown callees
4696            // name the culprit instead of the generic hint.
4697            Err(e) if e.kind.is_some() => return Err(e),
4698            Err(_) => return Ok(None),
4699        };
4700        p = brace_pos + cur.pos;
4701        Some(Box::new(disc))
4702    };
4703    let body_ok = matches!(
4704        toks.get(p).map(|t| &t.kind),
4705        Some(TokKind::Group {
4706            delim: GroupDelim::Brace,
4707            ..
4708        })
4709    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4710    if !body_ok {
4711        return Ok(None);
4712    }
4713    let inner = match &toks[p].kind {
4714        TokKind::Group { inner, .. } => inner.clone(),
4715        _ => unreachable!(),
4716    };
4717    let (cases, default_body) = parse_switch_body(&inner, stmt, ctx)?;
4718    let kind = StepKind::Switch {
4719        discriminant,
4720        cases,
4721        default_body,
4722    };
4723    Ok(Some((kind, p + 1 - pos)))
4724}
4725
4726/// Single (non-block) `FOR`: `$var[: TYPE] (, $var[: TYPE])? IN
4727/// expr` plus block. Header shapes miss to generic (a third variable,
4728/// a missing block, a bad name all fail in lowering like the
4729/// grammar); completed headers validate counts and key types loudly.
4730/// Expression failures from inline blocks propagate (blocks lower
4731/// here); other expression failures miss (generic fails them like a
4732/// committed `instruction` would).
4733fn parse_for_at(
4734    toks: &[Tok],
4735    pos: usize,
4736    stmt: usize,
4737    ctx: &ParseCtx,
4738) -> Result<Option<(StepKind, usize)>, TokenError> {
4739    let mut p = pos + 1;
4740    let mut idents = Vec::new();
4741    let mut types = Vec::new();
4742    // First `$var[: TYPE]` (gapless `$var`; gaps free elsewhere).
4743    let Some((var1, _)) = peek_dollar_var(toks, p) else {
4744        return Ok(None);
4745    };
4746    idents.push(var1);
4747    p += 2;
4748    let mut cur = Cursor::expr(&toks[p..], stmt);
4749    cur.skip_gap();
4750    p += cur.pos;
4751    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4752        p += 1;
4753        let mut tcur = Cursor::expr(&toks[p..], stmt);
4754        tcur.skip_gap();
4755        let tstart = p + tcur.pos;
4756        let Some(tend) = parse_type_shape(toks, tstart) else {
4757            return Ok(None);
4758        };
4759        // `render_type_region` canonicalizes (shared spelling).
4760        types.push(render_type_region(&toks[tstart..tend], stmt)?);
4761        p = tend;
4762    }
4763    // Optional `, $var2[: TYPE2]`.
4764    {
4765        let mut ccur = Cursor::expr(&toks[p..], stmt);
4766        ccur.skip_gap();
4767        if matches!(
4768            ccur.toks.get(ccur.pos).map(|t| &t.kind),
4769            Some(TokKind::Punct(','))
4770        ) {
4771            ccur.pos += 1;
4772            ccur.skip_gap();
4773            let base = p + ccur.pos;
4774            let Some((var2, _)) = peek_dollar_var(toks, base) else {
4775                return Ok(None);
4776            };
4777            idents.push(var2);
4778            let mut q = base + 2;
4779            let mut qcur = Cursor::expr(&toks[q..], stmt);
4780            qcur.skip_gap();
4781            q += qcur.pos;
4782            if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4783                q += 1;
4784                let mut tcur = Cursor::expr(&toks[q..], stmt);
4785                tcur.skip_gap();
4786                let tstart = q + tcur.pos;
4787                let Some(tend) = parse_type_shape(toks, tstart) else {
4788                    return Ok(None);
4789                };
4790                types.push(render_type_region(&toks[tstart..tend], stmt)?);
4791                q = tend;
4792            }
4793            p = q;
4794        }
4795    }
4796    // `IN expr block`.
4797    {
4798        let mut icur = Cursor::expr(&toks[p..], stmt);
4799        icur.skip_gap();
4800        if !matches!(
4801            icur.toks.get(icur.pos).map(|t| &t.kind),
4802            Some(TokKind::Word(w)) if w == KEYWORD_IN
4803        ) {
4804            return Ok(None);
4805        }
4806        icur.pos += 1;
4807        p += icur.pos;
4808    }
4809    let mut ecur = Cursor::expr(&toks[p..], stmt);
4810    ecur.skip_gap();
4811    let in_expr = match parse_expr_checked(&mut ecur, ctx) {
4812        Ok(expr) => expr,
4813        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4814        // Classified failures name the callee: `FOR ... IN` is
4815        // committed once the header matched this far.
4816        Err(e) if e.kind.is_some() => return Err(e),
4817        Err(_) => return Ok(None),
4818    };
4819    p += ecur.pos;
4820    let block_ok = matches!(
4821        toks.get(p).map(|t| &t.kind),
4822        Some(TokKind::Group {
4823            delim: GroupDelim::Brace,
4824            ..
4825        })
4826    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4827    if !block_ok {
4828        return Ok(None);
4829    }
4830    let inner = match &toks[p].kind {
4831        TokKind::Group { inner, .. } => inner.clone(),
4832        _ => unreachable!(),
4833    };
4834    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4835    p += 1;
4836    if idents.len() != types.len() {
4837        return Err(TokenError {
4838            stmt,
4839            msg: format!(
4840                "FOR requires explicit types: FOR $item: TYPE IN <expr> (got {} vars, {} types)",
4841                idents.len(),
4842                types.len()
4843            ),
4844            line: 0,
4845            col: 0,
4846            kind: Some(ParseErrorKind::Validation {
4847                command: KEYWORD_FOR.to_string(),
4848            }),
4849        });
4850    }
4851    let (key_var, key_type, var, var_type) = match idents.len() {
4852        1 => (
4853            None,
4854            None,
4855            idents.into_iter().next().unwrap_or_default(),
4856            types.into_iter().next().unwrap_or_default(),
4857        ),
4858        2 => {
4859            let mut iv = idents.into_iter();
4860            let mut tv = types.into_iter();
4861            (
4862                Some(iv.next().unwrap_or_default()),
4863                Some(tv.next().unwrap_or_default()),
4864                iv.next().unwrap_or_default(),
4865                tv.next().unwrap_or_default(),
4866            )
4867        }
4868        _ => {
4869            return Err(TokenError {
4870                stmt,
4871                msg: "FOR requires one or two variables".to_string(),
4872                line: 0,
4873                col: 0,
4874                kind: Some(ParseErrorKind::Validation {
4875                    command: KEYWORD_FOR.to_string(),
4876                }),
4877            });
4878        }
4879    };
4880    if let Some(kt) = &key_type
4881        && kt != crate::TypeTag::String.name()
4882        && kt != crate::TypeTag::Int.name()
4883    {
4884        return Err(TokenError {
4885            stmt,
4886            msg: format!("FOR key variable must be INT or STRING, got {kt}"),
4887            line: 0,
4888            col: 0,
4889            kind: Some(ParseErrorKind::Validation {
4890                command: KEYWORD_FOR.to_string(),
4891            }),
4892        });
4893    }
4894    let kind = StepKind::For {
4895        key_var,
4896        key_type,
4897        var,
4898        var_type,
4899        in_expr,
4900        body,
4901    };
4902    Ok(Some((kind, p - pos)))
4903}
4904
4905/// Single (non-block) `WHILE`: condition plus block. `None` on
4906/// shape miss (missing block: generic fails it); classified
4907/// expression failures and inline-block failures propagate, other
4908/// expression failures miss (generic fails them like a committed
4909/// `instruction` would).
4910/// No leading gap-skip: `WHILE` takes `sep`, so a joint follower
4911/// never reaches here with a valid shape... (misses fall through
4912/// the same way regardless).
4913fn parse_while_single(
4914    toks: &[Tok],
4915    pos: usize,
4916    stmt: usize,
4917    ctx: &ParseCtx,
4918) -> Result<Option<(StepKind, usize)>, TokenError> {
4919    let mut cur = Cursor::expr(&toks[pos + 1..], stmt);
4920    let cond = match parse_expr_checked(&mut cur, ctx) {
4921        Ok(expr) => expr,
4922        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4923        // Same rule as `IF`: the head is unambiguous, so classified
4924        // failures name the culprit instead of the generic hint.
4925        Err(e) if e.kind.is_some() => return Err(e),
4926        Err(_) => return Ok(None),
4927    };
4928    let brace = pos + 1 + cur.pos;
4929    let block_ok = matches!(
4930        toks.get(brace).map(|t| &t.kind),
4931        Some(TokKind::Group {
4932            delim: GroupDelim::Brace,
4933            ..
4934        })
4935    ) && toks.get(brace).is_some_and(|t| !is_template_brace(t));
4936    if !block_ok {
4937        return Ok(None);
4938    }
4939    let inner = match &toks[brace].kind {
4940        TokKind::Group { inner, .. } => inner.clone(),
4941        _ => unreachable!(),
4942    };
4943    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4944    let kind = StepKind::While {
4945        cond: Box::new(cond),
4946        body,
4947    };
4948    Ok(Some((kind, brace + 1 - pos)))
4949}
4950
4951/// Validated `FUNC` header shape: name, parameter list, return type,
4952/// and body block. Single owner for the header grammar, shared by
4953/// `parse_func_at` and `predeclare_forward_funcs` so the hoist set can
4954/// never admit what the real path rejects (or reject what it admits).
4955/// Returns the header plus tokens consumed; `None` on shape miss
4956/// (lowercase names, missing paren/colon/block all miss to generic,
4957/// probed). Content failures (bad params, missing return type, bad
4958/// trailing tokens) carry the bare diagnostic: `parse_func_at`
4959/// adorns it, pre-declaration drops it (silent skip, letting the main
4960/// pass own the error).
4961struct FuncHeader {
4962    name: String,
4963    params: Vec<(String, String, bool)>,
4964    return_type: String,
4965    block: usize,
4966}
4967
4968#[allow(clippy::too_many_lines)]
4969fn parse_func_header(
4970    toks: &[Tok],
4971    pos: usize,
4972    stmt: usize,
4973    keyword: &str,
4974) -> Result<Option<(FuncHeader, usize)>, String> {
4975    // Head word: `FUNC` (callers normalize `ASYNC FUNC` to `pos`
4976    // first, so the header shape stays prefix-free).
4977    if !matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC) {
4978        return Ok(None);
4979    }
4980    // Name: UPPERCASE ident (lowercase misses to generic, probed).
4981    let def_name = match toks.get(pos + 1).map(|t| &t.kind) {
4982        Some(TokKind::Word(w))
4983            if crate::resolve::check_func_ident(&lowering_ctx(stmt), w).is_ok() =>
4984        {
4985            w.clone()
4986        }
4987        _ => return Ok(None),
4988    };
4989    // Paren group at any gap (`gap` zero-width): params live inside
4990    // its inner tokens, parsed with `gap_nl` discipline (newlines ride
4991    // free like call args and generics, via the shared helper).
4992    let mut p = pos + 2;
4993    let paren_inner = match toks.get(p).map(|t| &t.kind) {
4994        Some(TokKind::Group {
4995            delim: GroupDelim::Paren,
4996            inner,
4997            ..
4998        }) => inner.clone(),
4999        _ => return Ok(None),
5000    };
5001    p += 1;
5002    let mut params = Vec::new();
5003    let mut seen_optional = false;
5004    {
5005        let mut pcur = Cursor::expr(&paren_inner, stmt);
5006        pcur.skip_gap_nl();
5007        if !pcur.done() {
5008            loop {
5009                let base = pcur.pos;
5010                let Some((pname, _)) = peek_dollar_var(&paren_inner, base) else {
5011                    return Err(format!(
5012                        "FUNC {def_name} params must be `$name: TYPE` separated by commas"
5013                    ));
5014                };
5015                pcur.pos = base + 2;
5016                pcur.skip_gap_nl();
5017                // Optional params carry `?` before the colon
5018                // (`$flag?: BOOL`); all params are otherwise required.
5019                let optional = pcur.eat_punct('?');
5020                pcur.skip_gap_nl();
5021                if !pcur.eat_punct(':') {
5022                    return Err(format!(
5023                        "FUNC {def_name} param `${pname}` needs `: TYPE` after the name"
5024                    ));
5025                }
5026                pcur.skip_gap_nl();
5027                let tstart = pcur.pos;
5028                let Some(tend) = parse_type_shape(&paren_inner, tstart) else {
5029                    let got = match paren_inner.get(tstart).map(|tok| &tok.kind) {
5030                        Some(TokKind::Word(word)) => format!("; got `{word}`"),
5031                        _ => String::new(),
5032                    };
5033                    return Err(format!(
5034                        "FUNC {def_name} param `${pname}` needs an uppercase type after `:` (e.g. STRING, INT, BOOL){got}"
5035                    ));
5036                };
5037                // Post-match the span holds words/puncts only, so the
5038                // shared renderer cannot fail; stay failed regardless.
5039                let ptype =
5040                    render_type_region(&paren_inner[tstart..tend], stmt).unwrap_or_default();
5041                if optional {
5042                    seen_optional = true;
5043                } else if seen_optional {
5044                    return Err(format!(
5045                        "FUNC {def_name} optional ? params must be trailing: `${pname}` follows an optional param"
5046                    ));
5047                }
5048                params.push((pname, ptype, optional));
5049                pcur.pos = tend;
5050                pcur.skip_gap_nl();
5051                if pcur.eat_punct(',') {
5052                    pcur.skip_gap_nl();
5053                    // Trailing comma misses (a param must follow).
5054                    if pcur.done() {
5055                        return Err(format!(
5056                            "FUNC {def_name} params must not end with a trailing comma"
5057                        ));
5058                    }
5059                    continue;
5060                }
5061                break;
5062            }
5063            // Trailing junk (including newlines) misses to generic.
5064            pcur.skip_gap_nl();
5065            if !pcur.done() {
5066                return Err(format!(
5067                    "FUNC {def_name} params must be `$name: TYPE` separated by commas"
5068                ));
5069            }
5070        }
5071    }
5072    // Mandatory return annotation: FUNC NAME(...): RET { ... }.
5073    // After paren group, require gap-optional colon then type shape.
5074    // Missing colon after matched name+parens is a hard parse error
5075    // (no legacy fallback). Non-block tails (neither colon nor brace)
5076    // miss to generic (probed FUNC FOO() ECHO hi).
5077    let is_colon = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')));
5078    if !is_colon {
5079        let is_brace = matches!(
5080            toks.get(p).map(|t| &t.kind),
5081            Some(TokKind::Group {
5082                delim: GroupDelim::Brace,
5083                ..
5084            })
5085        ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
5086        if is_brace {
5087            return Err(format!(
5088                "{keyword} {def_name} requires a return type : TYPE (e.g. : VOID, : STRING)"
5089            ));
5090        }
5091        return Ok(None);
5092    }
5093    let Some(ret_end) = parse_type_shape(toks, p + 1) else {
5094        return Err(format!(
5095            "{keyword} {def_name} requires a return type : TYPE after ':'"
5096        ));
5097    };
5098    let return_type = render_type_region(&toks[p + 1..ret_end], stmt)
5099        .map_err(|_| format!("{keyword} {def_name} requires a return type : TYPE after ':'"))?;
5100    let return_type = crate::canonicalize_spelling(&return_type);
5101    p = ret_end;
5102    // Block at any gap (never a template); missing blocks miss to
5103    // generic (probed FUNC FOO() ECHO hi).
5104    let block_ok = matches!(
5105        toks.get(p).map(|t| &t.kind),
5106        Some(TokKind::Group {
5107            delim: GroupDelim::Brace,
5108            ..
5109        })
5110    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
5111    if !block_ok {
5112        return Ok(None);
5113    }
5114    Ok(Some((
5115        FuncHeader {
5116            name: def_name,
5117            params,
5118            return_type,
5119            block: p,
5120        },
5121        p + 1 - pos,
5122    )))
5123}
5124
5125/// Single (non-block) `FUNC`: name, parenthesized params, block. The
5126/// shape parses purely first (misses fall to generic, declaring
5127/// nothing — the grammar only lowers matched pairs); then the name
5128/// declares in the enclosing scope before the body lowers (so
5129/// recursion resolves), and the body pushes a fresh scope.
5130/// Duplicates, reserved shadows, and parameter dupes fail loudly.
5131fn parse_func_at(
5132    toks: &[Tok],
5133    pos: usize,
5134    stmt: usize,
5135    ctx: &ParseCtx,
5136    is_async: bool,
5137) -> Result<Option<(StepKind, usize)>, TokenError> {
5138    let keyword = if is_async { "ASYNC FUNC" } else { KEYWORD_FUNC };
5139    let fail = |msg: String| TokenError {
5140        stmt,
5141        msg,
5142        line: 0,
5143        col: 0,
5144        kind: Some(ParseErrorKind::Validation {
5145            command: KEYWORD_FUNC.to_string(),
5146        }),
5147    };
5148    // Phase 1 (pure shape) through the single header owner:
5149    // adorn content errors with the `FUNC` / `ASYNC FUNC` keyword,
5150    // miss to generic on shape miss exactly as before.
5151    let Some((header, used)) = parse_func_header(toks, pos, stmt, keyword).map_err(fail)? else {
5152        return Ok(None);
5153    };
5154    let FuncHeader {
5155        name: def_name,
5156        params,
5157        return_type,
5158        block: p,
5159    } = header;
5160    // Phase 2 (effects): reserved shadows and same-scope duplicates
5161    // fail at the definition line, verbatim.
5162    if ctx.reserved.contains(&def_name) || ctx.modules.reserved_base_names().contains(&def_name) {
5163        return Err(fail(format!(
5164            "FUNC {def_name} cannot shadow reserved function `{def_name}`"
5165        )));
5166    }
5167    if !ctx.declare_func(&def_name) {
5168        return Err(fail(format!(
5169            "duplicate function `{def_name}` in same scope"
5170        )));
5171    }
5172    let mut seen = HashSet::new();
5173    for (pname, _, _) in &params {
5174        if !seen.insert(pname.clone()) {
5175            return Err(fail(format!(
5176                "FUNC {def_name} declares duplicate parameter ${pname}"
5177            )));
5178        }
5179    }
5180    let inner = match &toks[p].kind {
5181        TokKind::Group { inner, .. } => inner.clone(),
5182        _ => unreachable!(),
5183    };
5184    let body = parse_body_steps(&inner, stmt, ctx, false)?;
5185    let kind = StepKind::FuncDef {
5186        name: def_name,
5187        params,
5188        return_type,
5189        is_async,
5190        body,
5191        docs: None,
5192    };
5193    Ok(Some((kind, used)))
5194}
5195
5196/// `REMOTE` header bindings `[$var, env:KEY]` over a bracket
5197/// group's inner tokens: comma-separated, newlines and comments free
5198/// like `gap_nl`. `$`+name and `env`+`:`+key all ride gapless (the
5199/// enclosing rule is compound-atomic). Empty lists parse (probed);
5200/// anything else misses the shape (`None`: generic fails it like
5201/// the grammar's dropped optional).
5202#[allow(clippy::type_complexity)]
5203fn parse_remote_bindings(
5204    inner: &[Tok],
5205    stmt: usize,
5206) -> Result<Option<(Vec<String>, Vec<String>)>, TokenError> {
5207    let _ = stmt;
5208    let mut parts: Vec<&[Tok]> = Vec::new();
5209    let mut start = 0;
5210    for (i, tok) in inner.iter().enumerate() {
5211        if matches!(&tok.kind, TokKind::Punct(',')) {
5212            parts.push(&inner[start..i]);
5213            start = i + 1;
5214        }
5215    }
5216    parts.push(&inner[start..]);
5217    // An empty list (`[]`, whitespace/comment-only) holds no bindings.
5218    if parts.len() == 1
5219        && parts[0]
5220            .iter()
5221            .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
5222    {
5223        return Ok(Some((Vec::new(), Vec::new())));
5224    }
5225    let mut vars = Vec::new();
5226    let mut env = Vec::new();
5227    for part in parts {
5228        // Edges admit gaps, newlines, and comments, like `gap_nl`.
5229        let mut part = part;
5230        while matches!(
5231            part.first().map(|t| &t.kind),
5232            Some(TokKind::Newline | TokKind::Comment(_))
5233        ) {
5234            part = &part[1..];
5235        }
5236        while matches!(
5237            part.last().map(|t| &t.kind),
5238            Some(TokKind::Newline | TokKind::Comment(_))
5239        ) {
5240            part = &part[..part.len() - 1];
5241        }
5242        // `$var`: gapless `$` + ident.
5243        if matches!(part.first().map(|t| &t.kind), Some(TokKind::Punct('$'))) && part.len() == 2 {
5244            if part[1].joint
5245                && let TokKind::Word(w) = &part[1].kind
5246                && is_ident_word(w)
5247            {
5248                vars.push(w.clone());
5249                continue;
5250            }
5251            return Ok(None);
5252        }
5253        // `env:KEY`: gapless triple with an uppercase key.
5254        if part.len() == 3
5255            && matches!(&part[0].kind, TokKind::Word(w) if w == "env")
5256            && matches!(&part[1].kind, TokKind::Punct(':'))
5257            && part[1].joint
5258            && part[2].joint
5259        {
5260            if let TokKind::Word(k) = &part[2].kind
5261                && is_env_key(k)
5262            {
5263                env.push(k.clone());
5264                continue;
5265            }
5266            return Ok(None);
5267        }
5268        return Ok(None);
5269    }
5270    Ok(Some((vars, env)))
5271}
5272
5273/// `IMPORT` statement at `pos` (#115): module form (`IMPORT MOD`,
5274/// `IMPORT [A, B]`), file form (`IMPORT "p" AS A`,
5275/// `IMPORT ["p" AS A]`), mixed/multi forms
5276/// (`IMPORT [STD, "p" AS A, "q" AS B]`, multi-line included), and
5277/// selective harvests (`IMPORT [[F, G FROM "p" (AS A)?]]`).
5278/// Returns module names plus `ImportFile`/`ImportFuncs` steps in source
5279/// order, plus tokens consumed (relative to `pos`), or `None` on shape
5280/// miss (generic lowering fails it like the grammar). Validation is
5281/// hard: unknown modules, bad names, collisions, templates, and remote
5282/// URLs fail here, and validated entries register immediately
5283/// (modules, aliases, and bare harvest names share the innermost
5284/// frames).
5285type ImportEntries = (Vec<String>, Vec<StepKind>);
5286
5287fn parse_import_statement(
5288    toks: &[Tok],
5289    pos: usize,
5290    stmt: usize,
5291    ctx: &ParseCtx,
5292) -> Result<Option<(ImportEntries, usize)>, TokenError> {
5293    let fail = |msg: String| TokenError {
5294        stmt,
5295        msg,
5296        line: 0,
5297        col: 0,
5298        kind: Some(ParseErrorKind::Validation {
5299            command: KEYWORD_IMPORT.to_string(),
5300        }),
5301    };
5302    let next = match toks.get(pos + 1) {
5303        // `sep` after `IMPORT`: joint followers miss.
5304        Some(t) if !t.joint => t,
5305        _ => return Ok(None),
5306    };
5307    // Parse entries first, validate in source order after.
5308    enum RawEntry {
5309        Module(String),
5310        File {
5311            path: String,
5312            alias: String,
5313        },
5314        From {
5315            func_names: Vec<String>,
5316            type_names: Vec<String>,
5317            path: String,
5318            alias: Option<String>,
5319        },
5320    }
5321    let mut raw: Vec<RawEntry> = Vec::new();
5322    let used;
5323    if matches!(
5324        &next.kind,
5325        TokKind::Group {
5326            delim: GroupDelim::Brace,
5327            ..
5328        }
5329    ) {
5330        return Ok(None);
5331    }
5332    if let TokKind::Group {
5333        delim: GroupDelim::Bracket,
5334        inner,
5335        ..
5336    } = &next.kind
5337    {
5338        // Comma-separated entries, `ws` gaps (newlines ok inside and
5339        // around entries, comments MISS — `ws` admits neither).
5340        // Single-file multi-name harvests skip the split: in
5341        // `[TYPE A, TYPE B FROM "f"]` the first comma-part (`[TYPE A]`)
5342        // carries no FROM and is invalid alone, so the whole bracket
5343        // is one harvest (see `whole_file_harvest`).
5344        // Bare-multi hint: `[FOO, BAR FROM "f"]` reads FOO as a
5345        // module for back-compat (bare words stay modules in single
5346        // brackets). If that word is not a known module but a harvest
5347        // follows, fail fast naming the two valid spellings instead
5348        // of the misleading unknown-module error.
5349        let whole = whole_file_harvest(inner);
5350        if whole.is_none()
5351            && let Some(word) = single_bare_first_part(inner)
5352            && !ctx.modules.modules.contains_key(word)
5353            && has_top_level_from_after_comma(inner)
5354        {
5355            return Err(fail(format!(
5356                "unknown module `{word}`; to harvest multiple names qualify each kind (`IMPORT [FUNC FOO, FUNC BAR FROM \"f\"]`)"
5357            )));
5358        }
5359        let mut parts: Vec<&[Tok]> = Vec::new();
5360        if whole.is_some() {
5361            parts.push(inner);
5362        } else {
5363            let mut start = 0;
5364            for (i, tok) in inner.iter().enumerate() {
5365                if matches!(&tok.kind, TokKind::Punct(',')) {
5366                    parts.push(&inner[start..i]);
5367                    start = i + 1;
5368                }
5369            }
5370            parts.push(&inner[start..]);
5371        }
5372        for part in parts {
5373            let dense: Vec<&Tok> = part
5374                .iter()
5375                .filter(|t| !matches!(&t.kind, TokKind::Newline))
5376                .collect();
5377            // `[[F, G FROM "path" (AS ALIAS)?]]`: selective function
5378            // harvest. Anything else bracketed here misses.
5379            if let [bracket] = dense.as_slice()
5380                && let TokKind::Group {
5381                    delim: GroupDelim::Bracket,
5382                    inner,
5383                    ..
5384                } = &bracket.kind
5385            {
5386                let Some(HarvestImport {
5387                    func_names,
5388                    type_names,
5389                    path,
5390                    alias,
5391                }) = parse_from_entry(inner)
5392                else {
5393                    return Ok(None);
5394                };
5395                raw.push(RawEntry::From {
5396                    func_names,
5397                    type_names,
5398                    path,
5399                    alias,
5400                });
5401                continue;
5402            }
5403            // `[F FROM "path" (AS ALIAS)?]`: single harvest without
5404            // inner brackets. The `FROM` keyword is the discriminant
5405            // (module and file parts never contain a top-level one);
5406            // multi-name harvests keep `[[F, G FROM ...]]` so the comma
5407            // stays grouped inside its own scope.
5408            if dense.len() >= 3 {
5409                let owned: Vec<Tok> = dense.iter().map(|t| (*t).clone()).collect();
5410                if let Some(HarvestImport {
5411                    func_names,
5412                    type_names,
5413                    path,
5414                    alias,
5415                }) = parse_from_entry(&owned)
5416                {
5417                    raw.push(RawEntry::From {
5418                        func_names,
5419                        type_names,
5420                        path,
5421                        alias,
5422                    });
5423                    continue;
5424                }
5425            }
5426            match dense.as_slice() {
5427                [tok] => match &tok.kind {
5428                    TokKind::Word(w) if is_upper_ident(w) => {
5429                        raw.push(RawEntry::Module(w.clone()));
5430                    }
5431                    _ => return Ok(None),
5432                },
5433                [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5434                    let (
5435                        TokKind::Str { text, .. },
5436                        TokKind::Word(as_word),
5437                        TokKind::Word(alias_word),
5438                    ) = (&path_tok.kind, &as_tok.kind, &alias_tok.kind)
5439                    else {
5440                        return Ok(None);
5441                    };
5442                    if as_word != KEYWORD_AS {
5443                        return Ok(None);
5444                    }
5445                    raw.push(RawEntry::File {
5446                        path: text.clone(),
5447                        alias: alias_word.clone(),
5448                    });
5449                }
5450                _ => return Ok(None),
5451            }
5452        }
5453        if raw.is_empty() {
5454            return Ok(None);
5455        }
5456        used = 2;
5457    } else if let TokKind::Word(w) = &next.kind {
5458        // Bare `IMPORT MOD` (single module, probed).
5459        if !is_upper_ident(w) {
5460            return Ok(None);
5461        }
5462        raw.push(RawEntry::Module(w.clone()));
5463        used = 2;
5464    } else if let TokKind::Str { text, .. } = &next.kind {
5465        // Bare `IMPORT "path" AS ALIAS`.
5466        let (Some(as_tok), Some(alias_tok)) = (toks.get(pos + 2), toks.get(pos + 3)) else {
5467            return Ok(None);
5468        };
5469        if as_tok.joint || alias_tok.joint {
5470            return Ok(None);
5471        }
5472        let (TokKind::Word(as_word), TokKind::Word(alias_word)) = (&as_tok.kind, &alias_tok.kind)
5473        else {
5474            return Ok(None);
5475        };
5476        if as_word != KEYWORD_AS {
5477            return Ok(None);
5478        }
5479        raw.push(RawEntry::File {
5480            path: text.clone(),
5481            alias: alias_word.clone(),
5482        });
5483        used = 4;
5484    } else {
5485        return Ok(None);
5486    }
5487    // Validate in source order: unknown modules fail with the exact
5488    // backend message (sorted known list); file and harvest entries
5489    // validate hard (bad names, collisions, templates, remote URLs).
5490    let mut modules = Vec::new();
5491    let mut steps = Vec::new();
5492    for entry in raw {
5493        match entry {
5494            RawEntry::Module(module) => {
5495                if !ctx.modules.modules.contains_key(&module) {
5496                    let mut known: Vec<String> = ctx.modules.modules.keys().cloned().collect();
5497                    known.sort();
5498                    return Err(fail(format!(
5499                        "unknown module `{module}`; known modules: {}",
5500                        known.join(", ")
5501                    )));
5502                }
5503                ctx.import_into_frame(std::slice::from_ref(&module));
5504                modules.push(module);
5505            }
5506            RawEntry::File { path, alias } => {
5507                let (path, alias) = validate_file_import(&path, &alias, ctx).map_err(fail)?;
5508                steps.push(StepKind::ImportFile { path, alias });
5509            }
5510            RawEntry::From {
5511                func_names,
5512                type_names,
5513                path,
5514                alias,
5515            } => {
5516                let HarvestImport {
5517                    func_names,
5518                    type_names,
5519                    path,
5520                    alias,
5521                } = validate_from_import(&func_names, &type_names, &path, alias.as_deref(), ctx)
5522                    .map_err(fail)?;
5523                steps.push(StepKind::ImportFuncs {
5524                    path,
5525                    alias,
5526                    func_names,
5527                    type_names,
5528                });
5529            }
5530        }
5531    }
5532    Ok(Some(((modules, steps), used)))
5533}
5534
5535/// Single file import for value positions (#115): exactly one
5536/// `"path" AS ALIAS` entry and no modules. Anything else shaped like an
5537/// import is a hard error naming the restriction; shape misses return
5538/// `None` for the generic path.
5539fn parse_single_file_import(
5540    toks: &[Tok],
5541    pos: usize,
5542    stmt: usize,
5543    ctx: &ParseCtx,
5544) -> Result<Option<(String, String, usize)>, TokenError> {
5545    let Some(((modules, mut kinds), used)) = parse_import_statement(toks, pos, stmt, ctx)? else {
5546        return Ok(None);
5547    };
5548    if !modules.is_empty() || !matches!(kinds.as_slice(), [StepKind::ImportFile { .. }]) {
5549        return Err(TokenError {
5550            stmt,
5551            msg: if !modules.is_empty()
5552                || kinds
5553                    .iter()
5554                    .any(|k| matches!(k, StepKind::ImportFuncs { .. }))
5555            {
5556                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>]); modules and function harvests stay at statement level".to_string()
5557            } else {
5558                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>])"
5559                    .to_string()
5560            },
5561            line: 0,
5562            col: 0,
5563            kind: Some(ParseErrorKind::Validation {
5564                command: KEYWORD_IMPORT.to_string(),
5565            }),
5566        });
5567    }
5568    let Some(StepKind::ImportFile { path, alias }) = kinds.pop() else {
5569        unreachable!("length and variant checked above")
5570    };
5571    Ok(Some((path, alias, used)))
5572}
5573
5574/// One `EXPORT` name: an uppercase word with an optional joint
5575/// `::UPPER` tail. Returns the name and tokens consumed, or `None`
5576/// on shape miss.
5577fn parse_export_name(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
5578    let head = match toks.get(pos).map(|t| &t.kind) {
5579        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
5580        _ => return None,
5581    };
5582    let mut name = head;
5583    let mut used = 1;
5584    // Greedy-prefix `::tail` (atomic, like the grammar): a valid
5585    // tail joins, an invalid one stays trailing (failing downstream
5586    // exactly like the grammar's committed prefix).
5587    if matches!(
5588        toks.get(pos + 1).map(|t| &t.kind),
5589        Some(TokKind::Punct(':'))
5590    ) && toks.get(pos + 1).is_some_and(|t| t.joint)
5591        && matches!(
5592            toks.get(pos + 2).map(|t| &t.kind),
5593            Some(TokKind::Punct(':'))
5594        )
5595        && toks.get(pos + 2).is_some_and(|t| t.joint)
5596        && let Some(TokKind::Word(tail)) = toks.get(pos + 3).map(|t| &t.kind)
5597        && toks[pos + 3].joint
5598        && is_upper_ident(tail)
5599    {
5600        name.push_str(MODULE_SEPARATOR);
5601        name.push_str(tail);
5602        used = 4;
5603    }
5604    Some((name, used))
5605}
5606
5607/// One selective harvest (`[[F, G FROM "path" (AS ALIAS)?]]`): the
5608/// wanted function and type names plus the path and optional alias.
5609/// Bare names are functions; `TYPE`/`FUNC` prefixes select the kind
5610/// explicitly (`[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`).
5611struct HarvestImport {
5612    func_names: Vec<String>,
5613    type_names: Vec<String>,
5614    path: String,
5615    alias: Option<String>,
5616}
5617
5618/// One `[[F, G FROM "path" (AS ALIAS)?]]` entry: selective function
5619/// harvest with optional `TYPE`/`FUNC` qualifiers per name:
5620/// `[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`
5621/// (bare stays func for back-compat).
5622/// Returns the harvest, or `None` on shape miss (generic lowering fails
5623/// it). Name case is validated hard by the caller, like file aliases.
5624fn parse_from_entry(inner: &[Tok]) -> Option<HarvestImport> {
5625    let dense: Vec<&Tok> = inner
5626        .iter()
5627        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5628        .collect();
5629    let from = dense
5630        .iter()
5631        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5632    if from == 0 {
5633        return None;
5634    }
5635    // Names: comma-separated entries, each `NAME` (func) or
5636    // `TYPE NAME` / `FUNC NAME` (explicit kind for clarity).
5637    let mut func_names = Vec::new();
5638    let mut type_names = Vec::new();
5639    let mut start = 0;
5640    let head = &dense[..from];
5641    // Local helper: classify one comma-separated part.
5642    fn classify_part(part: &[&Tok]) -> Option<(bool, String)> {
5643        match part {
5644            [tok] => {
5645                let TokKind::Word(w) = &tok.kind else {
5646                    return None;
5647                };
5648                Some((false, w.clone()))
5649            }
5650            // `TYPE NAME` / `FUNC NAME`: the name must be `sep` (gapped
5651            // from the kind); the kind may be joint to a preceding `[`
5652            // or `,` (no space required there), so only the name's joint
5653            // flag matters.
5654            [kind_tok, name_tok] if !name_tok.joint => {
5655                let (TokKind::Word(kind), TokKind::Word(name)) = (&kind_tok.kind, &name_tok.kind)
5656                else {
5657                    return None;
5658                };
5659                if kind == KEYWORD_TYPE {
5660                    Some((true, name.clone()))
5661                } else if kind == KEYWORD_FUNC {
5662                    Some((false, name.clone()))
5663                } else {
5664                    None
5665                }
5666            }
5667            _ => None,
5668        }
5669    }
5670    for (i, tok) in head.iter().enumerate() {
5671        if matches!(&tok.kind, TokKind::Punct(',')) {
5672            let part = &head[start..i];
5673            let (is_type, name) = classify_part(part)?;
5674            if is_type {
5675                type_names.push(name);
5676            } else {
5677                func_names.push(name);
5678            }
5679            start = i + 1;
5680        }
5681    }
5682    let part = &head[start..];
5683    let (is_type, name) = classify_part(part)?;
5684    if is_type {
5685        type_names.push(name);
5686    } else {
5687        func_names.push(name);
5688    }
5689    // Tail: `"path"` or bare `MODULE` with an optional gapped `AS ALIAS`.
5690    // Quoted is a file path (module fallback only when no file matches);
5691    // bare is a host module (no file probe ambiguity).
5692    let tail = &dense[from + 1..];
5693    let path_text = |tok: &Tok| match &tok.kind {
5694        TokKind::Str { text, .. } => Some(text.clone()),
5695        TokKind::Word(w) if is_upper_ident(w) => Some(w.clone()),
5696        _ => None,
5697    };
5698    match tail {
5699        [path_tok] => {
5700            let text = path_text(path_tok)?;
5701            Some(HarvestImport {
5702                func_names,
5703                type_names,
5704                path: text,
5705                alias: None,
5706            })
5707        }
5708        [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5709            let text = path_text(path_tok)?;
5710            let (TokKind::Word(as_word), TokKind::Word(alias_word)) =
5711                (&as_tok.kind, &alias_tok.kind)
5712            else {
5713                return None;
5714            };
5715            if as_word != KEYWORD_AS {
5716                return None;
5717            }
5718            Some(HarvestImport {
5719                func_names,
5720                type_names,
5721                path: text,
5722                alias: Some(alias_word.clone()),
5723            })
5724        }
5725        _ => None,
5726    }
5727}
5728
5729/// First comma-part of a bracket when it is exactly one bare
5730/// uppercase word: the back-compat module reading. Anything else
5731/// (prefixed names, groups, multiple words) is not a bare module.
5732fn single_bare_first_part(inner: &[Tok]) -> Option<&str> {
5733    let end = inner
5734        .iter()
5735        .position(|t| matches!(&t.kind, TokKind::Punct(',')))
5736        .unwrap_or(inner.len());
5737    let mut words = inner[..end]
5738        .iter()
5739        .filter(|t| !matches!(&t.kind, TokKind::Newline));
5740    match (words.next(), words.next()) {
5741        (Some(tok), None) => match &tok.kind {
5742            TokKind::Word(w) if is_upper_ident(w) => Some(w.as_str()),
5743            _ => None,
5744        },
5745        _ => None,
5746    }
5747}
5748
5749/// Whether a top-level `FROM` follows the first top-level comma:
5750/// distinguishes a module-plus-harvest entry (`[STD, T FROM "f"]`)
5751/// from a bare word the author meant as a harvest name.
5752fn has_top_level_from_after_comma(inner: &[Tok]) -> bool {
5753    let mut seen_comma = false;
5754    for tok in inner {
5755        match &tok.kind {
5756            TokKind::Punct(',') => seen_comma = true,
5757            TokKind::Word(w) if seen_comma && w == KEYWORD_FROM => return true,
5758            _ => {}
5759        }
5760    }
5761    false
5762}
5763
5764/// Whole-bracket single-file harvest (`[TYPE A, TYPE B FROM "f"]`):
5765/// the comma-split would orphan `[TYPE A]` (no FROM, invalid alone),
5766/// so the entire bracket parses as one harvest. Only explicitly
5767/// prefixed names qualify: a bare word keeps its legacy module
5768/// reading, so `[STD, TYPE T FROM "f"]` still splits into a module
5769/// plus a harvest instead of harvesting STD as a function.
5770fn whole_file_harvest(inner: &[Tok]) -> Option<HarvestImport> {
5771    let owned: Vec<Tok> = inner.to_vec();
5772    let harvest = parse_from_entry(&owned)?;
5773    let dense: Vec<&Tok> = inner
5774        .iter()
5775        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5776        .collect();
5777    let from = dense
5778        .iter()
5779        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5780    let mut start = 0;
5781    for (i, tok) in dense[..from].iter().enumerate() {
5782        if matches!(&tok.kind, TokKind::Punct(',')) {
5783            if !is_prefixed_name(&dense[start..i]) {
5784                return None;
5785            }
5786            start = i + 1;
5787        }
5788    }
5789    if !is_prefixed_name(&dense[start..from]) {
5790        return None;
5791    }
5792    Some(harvest)
5793}
5794
5795/// One explicitly prefixed name (`TYPE NAME` / `FUNC NAME`): the name
5796/// stays gapped from its kind; the kind may joint to `[` or `,`.
5797fn is_prefixed_name(part: &[&Tok]) -> bool {
5798    match part {
5799        [kind_tok, name_tok] if !name_tok.joint => {
5800            matches!(
5801                (&kind_tok.kind, &name_tok.kind),
5802                (
5803                    TokKind::Word(kind),
5804                    TokKind::Word(_)
5805                ) if kind == KEYWORD_TYPE || kind == KEYWORD_FUNC
5806            )
5807        }
5808        _ => false,
5809    }
5810}
5811
5812/// Validate an `IMPORT` alias: hard errors (never shape misses) plus
5813/// registration into the innermost import frame.
5814fn validate_import_alias(alias: &str, ctx: &ParseCtx) -> Result<String, String> {
5815    if !is_upper_ident(alias) {
5816        return Err(format!(
5817            "IMPORT alias must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{alias}`"
5818        ));
5819    }
5820    if ctx.modules.modules.contains_key(alias) {
5821        return Err(format!(
5822            "IMPORT alias `{alias}` collides with module `{alias}`"
5823        ));
5824    }
5825    let (_, imports) = ctx.visible_snapshot();
5826    if imports.iter().any(|i| i == alias) {
5827        return Err(format!("duplicate IMPORT alias `{alias}`"));
5828    }
5829    ctx.import_into_frame(std::slice::from_ref(&alias.to_string()));
5830    Ok(alias.to_string())
5831}
5832
5833/// Validate an `IMPORT` path: hard errors, never shape misses.
5834fn validate_import_path(path: &str) -> Result<String, String> {
5835    if path.is_empty() {
5836        return Err("IMPORT path must not be empty".to_string());
5837    }
5838    if path.contains("{{") {
5839        return Err("IMPORT path must be a literal string (no {{ }} templates)".to_string());
5840    }
5841    if path.contains("://") {
5842        return Err(
5843            "remote imports are deferred to #270 (net: Run scripts from a remote URL)".to_string(),
5844        );
5845    }
5846    Ok(path.to_string())
5847}
5848
5849/// Validate a file-import path/alias pair: hard errors (never shape
5850/// misses) plus alias registration into the innermost import frame.
5851fn validate_file_import(
5852    path: &str,
5853    alias: &str,
5854    ctx: &ParseCtx,
5855) -> Result<(String, String), String> {
5856    let alias = validate_import_alias(alias, ctx)?;
5857    let path = validate_import_path(path)?;
5858    Ok((path, alias))
5859}
5860
5861/// Validate a `[[F, G FROM "path" (AS ALIAS)?]]` entry: hard errors
5862/// (never shape misses). Bare func names declare into the innermost
5863/// `FUNC` frame so calls resolve statically; the runtime defines them
5864/// (and fails unknown names there). Type names need no func-frame
5865/// declaration (types resolve through the global type directory);
5866/// the runtime validates them against the file's `EXPORT TYPE` list.
5867/// An alias registers like a file import.
5868fn validate_from_import(
5869    func_names: &[String],
5870    type_names: &[String],
5871    path: &str,
5872    alias: Option<&str>,
5873    ctx: &ParseCtx,
5874) -> Result<HarvestImport, String> {
5875    let path = validate_import_path(path)?;
5876    let mut out_func_names = Vec::with_capacity(func_names.len());
5877    for name in func_names {
5878        if !is_upper_ident(name) {
5879            return Err(format!(
5880                "IMPORT function names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
5881            ));
5882        }
5883        if ctx.reserved.contains(name) {
5884            return Err(format!("cannot shadow reserved function `{name}`"));
5885        }
5886        out_func_names.push(name.clone());
5887    }
5888    let mut out_type_names = Vec::with_capacity(type_names.len());
5889    for name in type_names {
5890        if !is_upper_ident(name) {
5891            return Err(format!(
5892                "IMPORT type names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
5893            ));
5894        }
5895        out_type_names.push(name.clone());
5896    }
5897    if out_func_names.is_empty() && out_type_names.is_empty() {
5898        return Err("IMPORT harvest needs at least one function or type name".to_string());
5899    }
5900    if let Some(alias) = alias {
5901        let alias = validate_import_alias(alias, ctx)?;
5902        Ok(HarvestImport {
5903            func_names: out_func_names,
5904            type_names: out_type_names,
5905            path,
5906            alias: Some(alias),
5907        })
5908    } else {
5909        for name in &out_func_names {
5910            if !ctx.declare_func(name) {
5911                return Err(format!("duplicate function `{name}` in same scope"));
5912            }
5913        }
5914        // Type harvests without alias land bare in the global type
5915        // directory: duplicates across files fail at import time
5916        // (different targets), not at parse time (targets need IO).
5917        Ok(HarvestImport {
5918            func_names: out_func_names,
5919            type_names: out_type_names,
5920            path,
5921            alias: None,
5922        })
5923    }
5924}
5925
5926/// One `EXPORT ...` name list: function names plus type names in
5927/// source order. Bare names are functions; explicit `TYPE`/`FUNC`
5928/// prefixes select the kind.
5929struct ExportNames {
5930    func_names: Vec<String>,
5931    type_names: Vec<String>,
5932}
5933
5934/// `EXPORT ...` names at `pos`: bracket list (strict, `ws` gaps:
5935/// newlines ok, comments miss) or a bare greedy-prefix name.
5936/// Supports explicit `TYPE`/`FUNC` qualifiers for clarity:
5937/// `EXPORT TYPE FOO`, `EXPORT TYPE [A, B]`, `EXPORT FUNC FOO`,
5938/// plus mixed `EXPORT [TYPE A, FUNC B, C]` (bare stays func).
5939/// Returns the name lists plus tokens consumed, or `None` on shape
5940/// miss (generic fails it in lowering like the grammar). Recording and
5941/// duplicate checks live with the caller (they need the guard and
5942/// level context).
5943fn parse_export_at(toks: &[Tok], pos: usize) -> Option<(ExportNames, usize)> {
5944    let next = match toks.get(pos + 1) {
5945        // `sep` after `EXPORT`: joint followers miss.
5946        Some(t) if !t.joint => t,
5947        _ => return None,
5948    };
5949    // Explicit `EXPORT TYPE ...` or `EXPORT FUNC ...` prefix.
5950    if let TokKind::Word(w) = &next.kind
5951        && (w == KEYWORD_TYPE || w == KEYWORD_FUNC)
5952    {
5953        let is_type = w == KEYWORD_TYPE;
5954        let after = match toks.get(pos + 2) {
5955            Some(t) if !t.joint => t,
5956            _ => return None,
5957        };
5958        if let TokKind::Group {
5959            delim: GroupDelim::Bracket,
5960            inner,
5961            ..
5962        } = &after.kind
5963        {
5964            let mut func_names = Vec::new();
5965            let mut type_names = Vec::new();
5966            for part in split_bracket_entries(inner) {
5967                let mut part = part;
5968                while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
5969                    part = &part[1..];
5970                }
5971                while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
5972                    part = &part[..part.len() - 1];
5973                }
5974                // A trailing comma leaves an empty final entry; it
5975                // carries no name and must not fail the list.
5976                if part.is_empty() {
5977                    continue;
5978                }
5979                let (name, used) = parse_export_name(part, 0)?;
5980                if used != part.len() {
5981                    return None;
5982                }
5983                if is_type {
5984                    type_names.push(name);
5985                } else {
5986                    func_names.push(name);
5987                }
5988            }
5989            if func_names.is_empty() && type_names.is_empty() {
5990                return None;
5991            }
5992            return Some((
5993                ExportNames {
5994                    func_names,
5995                    type_names,
5996                },
5997                3,
5998            ));
5999        }
6000        if matches!(&after.kind, TokKind::Group { .. }) {
6001            return None;
6002        }
6003        let (name, used) = parse_export_name(toks, pos + 2)?;
6004        // Bare name after TYPE/FUNC prefix must consume exactly one
6005        // name; trailing loops stay outside like the unprefixed case.
6006        // `used` counts from pos+2, so 1 name is valid.
6007        if used == 0 {
6008            return None;
6009        }
6010        if is_type {
6011            return Some((
6012                ExportNames {
6013                    func_names: Vec::new(),
6014                    type_names: vec![name],
6015                },
6016                2 + used,
6017            ));
6018        } else {
6019            return Some((
6020                ExportNames {
6021                    func_names: vec![name],
6022                    type_names: Vec::new(),
6023                },
6024                2 + used,
6025            ));
6026        }
6027    }
6028    if let TokKind::Group {
6029        delim: GroupDelim::Bracket,
6030        inner,
6031        ..
6032    } = &next.kind
6033    {
6034        let mut func_names = Vec::new();
6035        let mut type_names = Vec::new();
6036        for part in split_bracket_entries(inner) {
6037            let mut part = part;
6038            while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
6039                part = &part[1..];
6040            }
6041            while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
6042                part = &part[..part.len() - 1];
6043            }
6044            // A trailing comma leaves an empty final entry; it
6045            // carries no name and must not fail the list.
6046            if part.is_empty() {
6047                continue;
6048            }
6049            // Optional per-entry `TYPE`/`FUNC` prefix for mixed lists:
6050            // `EXPORT [TYPE A, FUNC B, C]` (bare stays func). The name
6051            // must be `sep` from the prefix; the prefix itself may be
6052            // joint to a preceding `[` or `,`, so only the name's joint
6053            // flag matters.
6054            let (is_type, rest) = match part {
6055                [first, second, ..]
6056                    if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_TYPE || w == KEYWORD_FUNC)
6057                        && !second.joint =>
6058                {
6059                    let is_t = matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_TYPE);
6060                    (is_t, &part[1..])
6061                }
6062                _ => (false, part),
6063            };
6064            // Exactly one name per entry (entries never trail).
6065            let (name, used) = parse_export_name(rest, 0)?;
6066            if used != rest.len() {
6067                return None;
6068            }
6069            if is_type {
6070                type_names.push(name);
6071            } else {
6072                func_names.push(name);
6073            }
6074        }
6075        if func_names.is_empty() && type_names.is_empty() {
6076            return None;
6077        }
6078        return Some((
6079            ExportNames {
6080                func_names,
6081                type_names,
6082            },
6083            2,
6084        ));
6085    }
6086    if matches!(&next.kind, TokKind::Group { .. }) {
6087        return None;
6088    }
6089    // Bare name (greedy `::` prefix; trailing loops outside). Bare
6090    // stays func for back-compat; `TYPE`/`FUNC` prefix selects above.
6091    parse_export_name(toks, pos + 1).map(|(name, used)| {
6092        (
6093            ExportNames {
6094                func_names: vec![name],
6095                type_names: Vec::new(),
6096            },
6097            1 + used,
6098        )
6099    })
6100}
6101
6102/// Split bracket inner tokens on top-level commas, preserving entries
6103/// for per-entry `TYPE`/`FUNC` handling. Newlines trim at the caller.
6104fn split_bracket_entries(inner: &[Tok]) -> Vec<&[Tok]> {
6105    let mut parts: Vec<&[Tok]> = Vec::new();
6106    let mut start = 0;
6107    for (i, tok) in inner.iter().enumerate() {
6108        if matches!(&tok.kind, TokKind::Punct(',')) {
6109            parts.push(&inner[start..i]);
6110            start = i + 1;
6111        }
6112    }
6113    parts.push(&inner[start..]);
6114    parts
6115}
6116
6117/// `TYPE NAME = SHAPE` at `pos`: uppercase name, single `=`, maximal
6118/// type-tag shape canonicalized through the shared spelling.
6119/// Returns the alias plus tokens consumed, or `None` on shape miss
6120/// (generic fails it in lowering like the grammar).
6121fn parse_type_stmt_at(
6122    toks: &[Tok],
6123    pos: usize,
6124    stmt: usize,
6125) -> Result<Option<(StepKind, usize)>, TokenError> {
6126    let name = match toks.get(pos + 1).map(|t| &t.kind) {
6127        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
6128        _ => return Ok(None),
6129    };
6130    // Single `=` at any gap (`gap` zero-width); `==` misses.
6131    if !matches!(
6132        toks.get(pos + 2).map(|t| &t.kind),
6133        Some(TokKind::Punct('='))
6134    ) {
6135        return Ok(None);
6136    }
6137    if matches!(
6138        toks.get(pos + 3).map(|t| &t.kind),
6139        Some(TokKind::Punct('='))
6140    ) {
6141        return Ok(None);
6142    }
6143    let Some(end) = parse_type_shape(toks, pos + 3) else {
6144        return Ok(None);
6145    };
6146    // Post-match the span holds words, puncts, and default literals
6147    // only, so the shared renderer cannot fail; stay failed regardless.
6148    let target = render_type_region(&toks[pos + 3..end], stmt).unwrap_or_default();
6149    Ok(Some((StepKind::TypeAlias { name, target }, end - pos)))
6150}
6151
6152/// Single (non-block) `REMOTE`: target, optional bindings, block.
6153/// The target reads a maximal joint run in the grammar's superset
6154/// charset (misses fall to generic); strict validity fails loudly
6155/// with the exact backend message. Bindings miss to generic;
6156/// empty/missing bodies and nesting violations fail loudly.
6157fn parse_remote_single(
6158    toks: &[Tok],
6159    pos: usize,
6160    stmt: usize,
6161    ctx: &ParseCtx,
6162) -> Result<Option<(StepKind, usize)>, TokenError> {
6163    let fail = |msg: String| TokenError {
6164        stmt,
6165        msg,
6166        line: 0,
6167        col: 0,
6168        kind: Some(ParseErrorKind::Validation {
6169            command: KEYWORD_REMOTE.to_string(),
6170        }),
6171    };
6172    // Target: joint run in the superset charset (alnum/`_`/`-`/`.`/`:`).
6173    // Anything else (joint or not) ends the run; an empty run misses
6174    // to generic. (`sep` needs no explicit check: a joint `(` is a
6175    // call routed before this ever runs, and anything unparseable
6176    // misses the same way.)
6177    let mut target = String::new();
6178    let mut p = pos + 1;
6179    while let Some(t) = toks.get(p) {
6180        if !t.joint && !target.is_empty() {
6181            break;
6182        }
6183        match &t.kind {
6184            TokKind::Word(w)
6185                if w.chars().all(|c| {
6186                    c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' || c == ':'
6187                }) =>
6188            {
6189                // Words arrive whole from the lexer; a bad word ends
6190                // the run (never partially appends), like the grammar.
6191                target.push_str(w);
6192                p += 1;
6193            }
6194            TokKind::Punct(c)
6195                if matches!(c, '_' | '-' | '.' | ':') && (target.is_empty() || t.joint) =>
6196            {
6197                target.push(*c);
6198                p += 1;
6199            }
6200            _ => break,
6201        }
6202    }
6203    if target.is_empty() {
6204        return Ok(None);
6205    }
6206    if !crate::commands::is_valid_remote_target(&target) {
6207        return Err(fail(format!(
6208            "invalid REMOTE target `{target}`: start alphanumeric, then alphanumeric, `_`, or `-`, max 64 chars, never SNAPSHOT, LOCAL, CACHE, SYSTEM, or REMOTE"
6209        )));
6210    }
6211    // Optional bindings `[$var, env:KEY]` at any gap (even joint,
6212    // probed); malformed bindings miss the whole shape to generic.
6213    let mut vars = Vec::new();
6214    let mut env = Vec::new();
6215    if let Some(bracket) = toks.get(p)
6216        && matches!(
6217            &bracket.kind,
6218            TokKind::Group {
6219                delim: GroupDelim::Bracket,
6220                ..
6221            }
6222        )
6223    {
6224        let inner = match &bracket.kind {
6225            TokKind::Group { inner, .. } => inner.clone(),
6226            _ => unreachable!(),
6227        };
6228        match parse_remote_bindings(&inner, stmt)? {
6229            Some((v, e)) => {
6230                vars = v;
6231                env = e;
6232            }
6233            None => return Ok(None),
6234        }
6235        p += 1;
6236    }
6237    // Block required (any gap, never a template); missing blocks
6238    // miss to generic.
6239    let block_ok = matches!(
6240        toks.get(p).map(|t| &t.kind),
6241        Some(TokKind::Group {
6242            delim: GroupDelim::Brace,
6243            ..
6244        })
6245    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
6246    if !block_ok {
6247        return Ok(None);
6248    }
6249    let inner = match &toks[p].kind {
6250        TokKind::Group { inner, .. } => inner.clone(),
6251        _ => unreachable!(),
6252    };
6253    let body = parse_body_steps(&inner, stmt, ctx, false)?;
6254    p += 1;
6255    if body.is_empty() {
6256        return Err(fail("REMOTE requires a non-empty braced block".to_string()));
6257    }
6258    if crate::commands::contains_remote_block(&body) {
6259        return Err(fail(format!(
6260            "REMOTE blocks cannot nest (target `{target}` contains another REMOTE block)"
6261        )));
6262    }
6263    if body
6264        .iter()
6265        .any(|s| crate::commands::contains_inherit_env(&s.kind))
6266    {
6267        return Err(fail(
6268            "INHERIT_ENV cannot appear inside a REMOTE block: the guest inherits its own process environment".to_string(),
6269        ));
6270    }
6271    // Outer-function containment (same rule as the shared remote
6272    // validators): body calls resolving to visible
6273    // outer `SCRIPT` defs (without same-body definitions) fail.
6274    {
6275        let mut inner_defs = HashSet::new();
6276        let mut calls = Vec::new();
6277        crate::commands::collect_remote_body_symbols(&body, &mut inner_defs, &mut calls);
6278        let outer_defs: HashSet<String> = ctx.funcs.borrow().iter().flatten().cloned().collect();
6279        for call in &calls {
6280            let bare = crate::constants::base_name(call);
6281            let is_script_call = match crate::constants::split_qualified(call) {
6282                Some((module, _)) => module == crate::constants::SCRIPT_MODULE_NAME,
6283                None => true,
6284            };
6285            if is_script_call && outer_defs.contains(bare) && !inner_defs.contains(bare) {
6286                return Err(fail(format!(
6287                    "REMOTE '{target}' calls outer function '{bare}' (functions must be defined inside the block)"
6288                )));
6289            }
6290        }
6291    }
6292    Ok(Some((
6293        StepKind::RemoteBlock {
6294            target,
6295            vars,
6296            env,
6297            body,
6298        },
6299        p - pos,
6300    )))
6301}
6302// ---- LET/SET/RETURN + expressions ----
6303// Expression tiers over [`Tok`] implement the precedence chain
6304// (or > and > comparison > ordering > add > mul > unary > atom);
6305// arithmetic/comparison lowering runs through the shared constructors
6306// (`make_arith`, `make_compare`, `apply_unary_neg`), so folding, RPN
6307// compilation, and overflow behavior are identical by construction,
6308// never re-derived.
6309
6310/// Eat a one- or two-char operator: single puncts match directly;
6311/// pairs (`==`, `!=`, `<=`, `>=`, `&&`, `||`, `::`) require a joint
6312/// second punct. Newlines never skip here (expression mode).
6313fn eat_op(cur: &mut Cursor, first: char, second: Option<char>) -> bool {
6314    // Gaps (comments included) are skipped before every operator.
6315    cur.skip_gap();
6316    let (a, b) = match (cur.toks.get(cur.pos), cur.toks.get(cur.pos + 1)) {
6317        (Some(a), b) => (a, b),
6318        _ => return false,
6319    };
6320    if !matches!(&a.kind, TokKind::Punct(c) if *c == first) {
6321        return false;
6322    }
6323    match second {
6324        None => {
6325            cur.pos += 1;
6326            true
6327        }
6328        Some(c2) => match b {
6329            Some(t) if t.joint && matches!(&t.kind, TokKind::Punct(c) if *c == c2) => {
6330                cur.pos += 2;
6331                true
6332            }
6333            _ => false,
6334        },
6335    }
6336}
6337
6338/// Dummy span for the shared lowering constructors: v2 owns no source
6339/// positions yet, so only success values (span-free) participate in
6340/// parity; failures surface through [`TokenError`] text.
6341fn lowering_ctx(stmt: usize) -> SpanContext<'static> {
6342    let _ = stmt;
6343    SpanContext::line_only(0)
6344}
6345
6346fn parse_expr_or(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6347    let mut left = parse_expr_and(cur, ctx)?;
6348    while eat_op(cur, '|', Some('|')) {
6349        cur.skip_gap();
6350        let right = parse_expr_and(cur, ctx)?;
6351        // No folding, no boundary checks: unfused literal runs stay
6352        // literal here.
6353        left = Expr::Logical {
6354            op: LogicalOp::Or,
6355            left: Box::new(left),
6356            right: Box::new(right),
6357        };
6358    }
6359    Ok(left)
6360}
6361
6362fn parse_expr_and(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6363    let mut left = parse_expr_cmp(cur, ctx)?;
6364    while eat_op(cur, '&', Some('&')) {
6365        cur.skip_gap();
6366        let right = parse_expr_cmp(cur, ctx)?;
6367        reject_boundary(&lowering_ctx(cur.stmt), &left).map_err(|e| cur.err(e.to_string()))?;
6368        reject_boundary(&lowering_ctx(cur.stmt), &right).map_err(|e| cur.err(e.to_string()))?;
6369        left = Expr::Logical {
6370            op: LogicalOp::And,
6371            left: Box::new(left),
6372            right: Box::new(right),
6373        };
6374    }
6375    Ok(left)
6376}
6377
6378fn parse_expr_cmp(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6379    let left = parse_expr_ord(cur, ctx)?;
6380    let op = if eat_op(cur, '=', Some('=')) {
6381        CompareOp::Eq
6382    } else if eat_op(cur, '!', Some('=')) {
6383        CompareOp::Ne
6384    } else {
6385        return Ok(left);
6386    };
6387    cur.skip_gap();
6388    let right = parse_expr_ord(cur, ctx)?;
6389    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
6390        .map_err(|e| cur.err(e.to_string()))?;
6391    reject_chained_compare(cur, false)?;
6392    Ok(expr)
6393}
6394
6395/// Reject a comparison operator trailing a complete comparison:
6396/// no grammar position continues with one, so the shape always fails —
6397/// loudly here instead of stranding text for a confusing downstream
6398/// error. The equality tier rejects all six (`$a == $b == $c`,
6399/// `$a == $b < $c < $d`); the ordering tier rejects ordering only
6400/// (`$a < $b < $c`), since `$a < $b == $c` is a legitimate equality
6401/// over an ordering result. Probes without consuming.
6402fn reject_chained_compare(cur: &mut Cursor, ordering_only: bool) -> Result<(), TokenError> {
6403    let mut probe = Cursor::expr(cur.toks, cur.stmt);
6404    probe.pos = cur.pos;
6405    probe.skip_gap();
6406    let chained = match probe.toks.get(probe.pos).map(|t| &t.kind) {
6407        Some(TokKind::Punct('<' | '>')) => true,
6408        Some(TokKind::Punct('=' | '!')) => !ordering_only,
6409        _ => false,
6410    };
6411    if chained {
6412        return Err(cur
6413            .err("chained comparison operators need explicit parentheses, e.g. `($a < $b) < $c`"));
6414    }
6415    Ok(())
6416}
6417
6418fn parse_expr_ord(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6419    let left = parse_expr_add(cur, ctx)?;
6420    let op = if eat_op(cur, '<', Some('=')) {
6421        CompareOp::Le
6422    } else if eat_op(cur, '>', Some('=')) {
6423        CompareOp::Ge
6424    } else if eat_op(cur, '<', None) {
6425        CompareOp::Lt
6426    } else if eat_op(cur, '>', None) {
6427        CompareOp::Gt
6428    } else {
6429        return Ok(left);
6430    };
6431    cur.skip_gap();
6432    let right = parse_expr_add(cur, ctx)?;
6433    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
6434        .map_err(|e| cur.err(e.to_string()))?;
6435    reject_chained_compare(cur, true)?;
6436    Ok(expr)
6437}
6438
6439fn parse_expr_add(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6440    let mut left = parse_expr_mul(cur, ctx)?;
6441    loop {
6442        let op = if eat_op(cur, '+', None) {
6443            ArithOp::Add
6444        } else if eat_op(cur, '-', None) {
6445            ArithOp::Sub
6446        } else {
6447            break;
6448        };
6449        cur.skip_gap();
6450        let right = parse_expr_mul(cur, ctx)?;
6451        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
6452            .map_err(|e| cur.err(e.to_string()))?;
6453    }
6454    Ok(left)
6455}
6456
6457fn parse_expr_mul(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6458    let mut left = parse_expr_unary(cur, ctx)?;
6459    loop {
6460        let op = if eat_op(cur, '*', None) {
6461            ArithOp::Mul
6462        } else if eat_op(cur, '/', None) {
6463            ArithOp::Div
6464        } else {
6465            break;
6466        };
6467        cur.skip_gap();
6468        let right = parse_expr_unary(cur, ctx)?;
6469        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
6470            .map_err(|e| cur.err(e.to_string()))?;
6471    }
6472    Ok(left)
6473}
6474
6475/// A `-` opens a bare word (never negation) when gaplessly followed by
6476/// a letter, `_`, or `/` — the `neg_op` lookahead, read off `joint`.
6477fn dash_is_bare(cur: &Cursor) -> bool {
6478    let next = cur.toks.get(cur.pos + 1);
6479    match next {
6480        Some(t) if t.joint => match &t.kind {
6481            TokKind::Word(w) => w
6482                .chars()
6483                .next()
6484                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_'),
6485            TokKind::Punct('/') => true,
6486            _ => false,
6487        },
6488        _ => false,
6489    }
6490}
6491
6492fn parse_expr_unary(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6493    let mut prefixes = Vec::new();
6494    loop {
6495        match cur.toks.get(cur.pos).map(|t| &t.kind) {
6496            Some(TokKind::Punct('!')) => {
6497                cur.pos += 1;
6498                // Each prefix is gap-separated.
6499                cur.skip_gap();
6500                prefixes.push(false);
6501            }
6502            Some(TokKind::Punct('-')) if !dash_is_bare(cur) => {
6503                cur.pos += 1;
6504                cur.skip_gap();
6505                prefixes.push(true);
6506            }
6507            _ => break,
6508        }
6509    }
6510    let mut expr = parse_expr_atom(cur, ctx)?;
6511    // Innermost prefix is closest to the atom: apply in reverse order.
6512    for is_neg in prefixes.into_iter().rev() {
6513        if is_neg {
6514            expr = apply_unary_neg(&lowering_ctx(cur.stmt), expr)
6515                .map_err(|e| cur.err(e.to_string()))?;
6516        } else {
6517            reject_boundary(&lowering_ctx(cur.stmt), &expr).map_err(|e| cur.err(e.to_string()))?;
6518            expr = Expr::Not(Box::new(expr));
6519        }
6520    }
6521    Ok(expr)
6522}
6523
6524/// Identifier charset for `$var` and `.segment` parts. Segments admit
6525/// digits-only too (`$a.0`); anything else ends the key path and errors
6526/// downstream, like the grammar's backtrack to `variable`.
6527fn is_ident_word(w: &str) -> bool {
6528    !w.is_empty() && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
6529}
6530
6531fn is_key_segment(w: &str) -> bool {
6532    !w.is_empty()
6533        && (w.chars().all(|c| c.is_ascii_digit())
6534            || (w
6535                .chars()
6536                .next()
6537                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
6538                && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')))
6539}
6540
6541fn is_env_key(w: &str) -> bool {
6542    !w.is_empty()
6543        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
6544        && w.chars()
6545            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
6546}
6547
6548/// Maximal joint run of words and `-/.'/'` puncts: the bare-word
6549/// shape (which admits `/` anywhere, so `//c`, `/a`, `a/b`, and the
6550/// `/`-`c`-`/` operands of `/*c*/` math all read literally here).
6551/// Callers classify (`true`/`false`/string); the numeric path
6552/// runs first and falls back here on shape/follower mismatch.
6553/// Backslash escapes are arg-position syntax: the bare-word shape admits
6554/// no `\`, so expression runs containing one fail here (never drift
6555/// into a string the grammar rejects).
6556fn expr_bare_run(cur: &mut Cursor, leading_dash: bool) -> Result<String, TokenError> {
6557    let mut out = String::new();
6558    if leading_dash {
6559        match cur.next() {
6560            Some(t) if matches!(&t.kind, TokKind::Punct('-')) => out.push('-'),
6561            _ => return Err(cur.err("missing expression operand")),
6562        }
6563    }
6564    match cur.next() {
6565        Some(t) => match &t.kind {
6566            TokKind::Word(w) => out.push_str(w),
6567            // Leading `/` (operand position only; operators are
6568            // consumed by the tiers before operands parse).
6569            TokKind::Punct('/') => out.push('/'),
6570            _ => return Err(cur.err("missing expression operand")),
6571        },
6572        None => return Err(cur.err("missing expression operand")),
6573    }
6574    loop {
6575        let next = match cur.toks.get(cur.pos) {
6576            Some(t) if t.joint => t,
6577            _ => break,
6578        };
6579        match &next.kind {
6580            TokKind::Word(w) => {
6581                // Abutting words only continue through an operator gap
6582                // the tiers own (`a -b` never fuses); without a joint
6583                // punct between, stop. Since this token IS joint, the
6584                // previous token must have been a bare punct.
6585                out.push_str(w);
6586                cur.pos += 1;
6587            }
6588            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
6589                out.push(*c);
6590                cur.pos += 1;
6591            }
6592            _ => break,
6593        }
6594    }
6595    if out.contains('\\') {
6596        return Err(cur.err("unexpected escape in expression"));
6597    }
6598    Ok(out)
6599}
6600
6601/// Numeric literal head: digit-led word plus joint `.digits` tails.
6602/// Callers apply the separator-shape gate and the follower rule, then
6603/// the shared classifier.
6604fn number_head(cur: &mut Cursor) -> Option<String> {
6605    let first = match cur.toks.get(cur.pos).map(|t| &t.kind) {
6606        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => w.clone(),
6607        _ => return None,
6608    };
6609    let mut text = first;
6610    let mut pos = cur.pos + 1;
6611    loop {
6612        let dot = matches!(
6613            cur.toks.get(pos).map(|t| &t.kind),
6614            Some(TokKind::Punct('.'))
6615        ) && cur.toks.get(pos).is_some_and(|t| t.joint);
6616        let digits = cur.toks.get(pos + 1);
6617        let digits_ok = dot
6618            && matches!(digits.map(|t| &t.kind), Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_'))
6619            && digits.is_some_and(|t| t.joint);
6620        if !digits_ok {
6621            break;
6622        }
6623        text.push('.');
6624        if let Some(TokKind::Word(w)) = digits.map(|t| &t.kind) {
6625            text.push_str(w);
6626        }
6627        pos += 2;
6628    }
6629    Some(text)
6630}
6631
6632/// `_`-separator shape gate mirroring the `numeric_literal` rule:
6633/// digits with single-underscore separators, at most one fraction.
6634fn numeric_shape_ok(text: &str) -> bool {
6635    let mut parts = text.split('.');
6636    let int_part = parts.next().unwrap_or("");
6637    let frac_part = parts.next();
6638    if parts.next().is_some() {
6639        return false;
6640    }
6641    fn run_ok(s: &str) -> bool {
6642        !s.is_empty()
6643            && s.chars().all(|c| c.is_ascii_digit() || c == '_')
6644            && !s.starts_with('_')
6645            && !s.ends_with('_')
6646            && !s.contains("__")
6647    }
6648    run_ok(int_part) && frac_part.is_none_or(run_ok)
6649}
6650
6651/// Follower rule mirroring the `numeric_literal` trailing guard
6652/// (`!(ALNUM | "_" | "." | "/")`): a joint word, `.`, or `/` continues
6653/// into a bare word (`30s`, `1.`, `4/2`); `-`/`+`/operators let the
6654/// number stand for the tiers (`1-2` is `Sub`, like the grammar).
6655fn number_falls_to_bare(cur: &Cursor, consumed: usize) -> bool {
6656    match cur.toks.get(cur.pos + consumed) {
6657        Some(t) if t.joint => matches!(
6658            &t.kind,
6659            TokKind::Word(_) | TokKind::Punct('.') | TokKind::Punct('/')
6660        ),
6661        _ => false,
6662    }
6663}
6664
6665fn parse_expr_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6666    match cur.toks.get(cur.pos).map(|t| &t.kind) {
6667        Some(TokKind::Group {
6668            delim: GroupDelim::Paren,
6669            inner,
6670            ..
6671        }) => {
6672            let inner = inner.clone();
6673            cur.pos += 1;
6674            let mut sub = Cursor::expr(&inner, cur.stmt);
6675            sub.skip_gap_nl();
6676            let expr = parse_expr_or(&mut sub, ctx)?;
6677            sub.skip_gap_nl();
6678            if !sub.done() {
6679                return Err(sub.err("unexpected text in parentheses"));
6680            }
6681            Ok(expr)
6682        }
6683        Some(TokKind::Word(_)) if call_shape_at(cur.toks, cur.pos, false).is_some() => {
6684            let (name, paren) =
6685                call_shape_at(cur.toks, cur.pos, false).ok_or_else(|| cur.err("unreachable"))?;
6686            let inner = match &cur.toks[paren].kind {
6687                TokKind::Group { inner, .. } => inner.clone(),
6688                _ => unreachable!(),
6689            };
6690            cur.pos = paren + 1;
6691            parse_expr_call(name, &inner, cur.stmt, ctx)
6692        }
6693        Some(TokKind::Punct('$')) => {
6694            cur.pos += 1;
6695            // Atomic `variable`: `$` and the name ride gapless (the
6696            // enclosing rules are compound-atomic).
6697            let base = match cur.next() {
6698                Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
6699                    match &t.kind {
6700                        TokKind::Word(w) => w.clone(),
6701                        _ => unreachable!(),
6702                    }
6703                }
6704                _ => return Err(cur.err("`$` requires a variable name")),
6705            };
6706            let mut keys = Vec::new();
6707            loop {
6708                // Key-path dots are gapless too (`~` without `gap`).
6709                let dot = matches!(
6710                    cur.toks.get(cur.pos).map(|t| &t.kind),
6711                    Some(TokKind::Punct('.'))
6712                ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
6713                let seg = cur.toks.get(cur.pos + 1);
6714                let seg_ok = dot
6715                    && matches!(seg.map(|t| &t.kind), Some(TokKind::Word(w)) if is_key_segment(w))
6716                    && seg.is_some_and(|t| t.joint);
6717                if !seg_ok {
6718                    break;
6719                }
6720                if let Some(TokKind::Word(w)) = seg.map(|t| &t.kind) {
6721                    keys.push(w.clone());
6722                }
6723                cur.pos += 2;
6724            }
6725            if keys.is_empty() {
6726                Ok(Expr::Var(base))
6727            } else {
6728                Ok(Expr::KeyPath { base, keys })
6729            }
6730        }
6731        Some(TokKind::Word(w)) if w == "env" => {
6732            // `env:KEY` read when the full shape matches gaplessly
6733            // (atomic `env_read`); otherwise a bare word (`env` alone,
6734            // `env:k` lowercase) for the error path, exactly like the
6735            // grammar's mismatch.
6736            let key_ok = matches!(
6737                cur.toks.get(cur.pos + 1).map(|t| &t.kind),
6738                Some(TokKind::Punct(':'))
6739            ) && cur.toks.get(cur.pos + 1).is_some_and(|t| t.joint)
6740                && matches!(
6741                    cur.toks.get(cur.pos + 2).map(|t| &t.kind),
6742                    Some(TokKind::Word(k)) if is_env_key(k)
6743                )
6744                && cur.toks.get(cur.pos + 2).is_some_and(|t| t.joint);
6745            if !key_ok {
6746                return parse_bare_atom(cur, ctx, false);
6747            }
6748            cur.pos += 1;
6749            cur.pos += 1;
6750            match cur.next() {
6751                Some(t) => match &t.kind {
6752                    TokKind::Word(k) => Ok(Expr::Env(k.clone())),
6753                    _ => Err(cur.err("unreachable")),
6754                },
6755                None => Err(cur.err("unreachable")),
6756            }
6757        }
6758        Some(TokKind::Group {
6759            delim: GroupDelim::Bracket,
6760            inner,
6761            ..
6762        }) => {
6763            let inner = inner.clone();
6764            cur.pos += 1;
6765            parse_list_literal(&inner, cur.stmt, ctx)
6766        }
6767        Some(TokKind::Group {
6768            delim: GroupDelim::Brace,
6769            inner,
6770            ..
6771        }) => {
6772            let inner = inner.clone();
6773            cur.pos += 1;
6774            parse_map_or_block(&inner, cur.stmt, ctx)
6775        }
6776        Some(TokKind::Str { text, .. }) => {
6777            let text = text.clone();
6778            cur.pos += 1;
6779            Ok(Expr::Literal(Value::string(text)))
6780        }
6781        Some(TokKind::BlockStr(full)) => {
6782            let full = full.clone();
6783            cur.pos += 1;
6784            Ok(Expr::Literal(Value::string(
6785                crate::command::lower_block_string(&full),
6786            )))
6787        }
6788        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => {
6789            parse_numeric_atom(cur, ctx)
6790        }
6791        Some(TokKind::Word(_)) => parse_bare_atom(cur, ctx, false),
6792        Some(TokKind::Punct('-')) => parse_bare_atom(cur, ctx, true),
6793        Some(TokKind::Punct('/')) => parse_bare_atom(cur, ctx, false),
6794        _ => Err(cur.err("missing expression operand")),
6795    }
6796}
6797
6798/// Bare-word atom with a `-` lead (the caller proved it is not
6799/// negation): consumes the joint `-/.'/'` run for the bare-word
6800/// shape.
6801fn parse_bare_atom(
6802    cur: &mut Cursor,
6803    _ctx: &ParseCtx,
6804    leading_dash: bool,
6805) -> Result<Expr, TokenError> {
6806    let text = expr_bare_run(cur, leading_dash)?;
6807    match text.as_str() {
6808        "true" => Ok(Expr::Literal(Value::bool(true))),
6809        "false" => Ok(Expr::Literal(Value::bool(false))),
6810        _ => Ok(Expr::Literal(Value::string(text))),
6811    }
6812}
6813
6814/// Numeric atom: rejoin dotted tails, apply the shape gate and the
6815/// follower rule, then the shared classifier. Anything failing the
6816/// gate or follower reparses as a bare word (durations, versions,
6817/// paths), exactly like the grammar's numeric-literal-or-bare-word
6818/// order.
6819fn parse_numeric_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6820    let start = cur.pos;
6821    let text = number_head(cur).ok_or_else(|| cur.err("missing expression operand"))?;
6822    let consumed = {
6823        let mut n = 1;
6824        let mut p = start + 1;
6825        while matches!(cur.toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('.')))
6826            && cur.toks.get(p).is_some_and(|t| t.joint)
6827            && matches!(
6828                cur.toks.get(p + 1).map(|t| &t.kind),
6829                Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_')
6830            )
6831            && cur.toks.get(p + 1).is_some_and(|t| t.joint)
6832        {
6833            n += 2;
6834            p += 2;
6835        }
6836        n
6837    };
6838    if !numeric_shape_ok(&text) || number_falls_to_bare(cur, consumed) {
6839        return parse_bare_atom(cur, ctx, false);
6840    }
6841    cur.pos += consumed;
6842    classify_numeric_text(&text).map_err(|msg| cur.err(msg))
6843}
6844
6845/// Full expression with the top-level boundary rejection (mirrors
6846/// `parse_expr`): a stray `UnsignedIntBoundary` that no unary `-`
6847/// consumed is an overflow error.
6848fn parse_expr_checked(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6849    let expr = parse_expr_or(cur, ctx)?;
6850    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
6851        return Err(cur.err("integer overflow: 9223372036854775808 exceeds i64::MAX"));
6852    }
6853    Ok(expr)
6854}
6855
6856/// List literal over a bracket group's contents: the shared bracket
6857/// core (see [`parse_bracket_list`]) in `Expr` mode. Expression
6858/// positions fail loudly instead of missing, so `None` is unreachable.
6859fn parse_list_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6860    parse_bracket_list(inner, stmt, ctx, BracketItems::Expr)
6861        .map(|list| list.expect("expression lists fail loudly, never miss"))
6862}
6863
6864/// Map literal attempt over a brace group's contents: comma-separated
6865/// `key: value` entries with `gap` (never newline) around the colon.
6866/// Any entry failing the shape is not a map: the caller reports the
6867/// deferred block slice (the grammar tries `block` next, which fails
6868/// the same inputs at this stage).
6869/// Marker message for a map entry run that ends without a comma
6870/// where another entry follows. Matched by exact equality in
6871/// [`parse_map_or_block`], never by prefix, so wording changes stay
6872/// local to this const and its one reader.
6873const MISSING_MAP_COMMA_MSG: &str = "missing comma between map entries";
6874
6875fn parse_map_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6876    let mut entries = Vec::new();
6877    // Empty (or blank/comment-only) braces are an empty map.
6878    if inner
6879        .iter()
6880        .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
6881    {
6882        return Ok(Expr::Map(vec![]));
6883    }
6884    for part in split_top_commas(inner) {
6885        let mut sub = Cursor::expr(part, stmt);
6886        sub.skip_gap_nl();
6887        let (key, val) = parse_map_entry(&mut sub, ctx, stmt)?;
6888        sub.skip_gap_nl();
6889        if !sub.done() {
6890            return Err(map_trailing_error(&sub, ctx, stmt));
6891        }
6892        entries.push((key, val));
6893    }
6894    Ok(Expr::Map(entries))
6895}
6896
6897/// One `key: value` map entry: string, block-string, or bare key,
6898/// a colon, then a full checked expression. Every failure reads
6899/// `not a map literal` exactly like the old inline loop, so only
6900/// the trailing rule changes the surface.
6901fn parse_map_entry(
6902    sub: &mut Cursor,
6903    ctx: &ParseCtx,
6904    stmt: usize,
6905) -> Result<(String, Expr), TokenError> {
6906    let key = match sub.toks.get(sub.pos).map(|t| &t.kind) {
6907        Some(TokKind::Str { text, .. }) => {
6908            let key = text.clone();
6909            sub.pos += 1;
6910            key
6911        }
6912        Some(TokKind::BlockStr(full)) => {
6913            let key = crate::command::lower_block_string(full);
6914            sub.pos += 1;
6915            key
6916        }
6917        Some(TokKind::Word(_)) | Some(TokKind::Punct('-')) | Some(TokKind::Punct('/')) => {
6918            map_bare_key(sub)?
6919        }
6920        _ => return Err(sub.err("not a map literal")),
6921    };
6922    sub.skip_gap();
6923    if !sub.eat_punct(':') {
6924        return Err(sub.err("not a map literal"));
6925    }
6926    let val = parse_expr_checked(sub, ctx)?;
6927    reject_boundary(&lowering_ctx(stmt), &val).map_err(|e| sub.err(e.to_string()))?;
6928    Ok((key, val))
6929}
6930
6931/// Trailing content after a complete map entry: stamps the
6932/// offending token and names the likely missing comma when the
6933/// remainder parses as another entry. Anything else keeps the old
6934/// `not a map literal` text. Error-path only.
6935fn map_trailing_error(sub: &Cursor, ctx: &ParseCtx, stmt: usize) -> TokenError {
6936    let (line, col) = sub
6937        .toks
6938        .get(sub.pos)
6939        .map(|t| (t.line, t.col))
6940        .unwrap_or((0, 0));
6941    let mut probe = Cursor::expr(&sub.toks[sub.pos.min(sub.toks.len())..], stmt);
6942    probe.skip_gap_nl();
6943    if parse_map_entry(&mut probe, ctx, stmt).is_ok() {
6944        return TokenError {
6945            stmt,
6946            line,
6947            col,
6948            msg: MISSING_MAP_COMMA_MSG.to_string(),
6949            kind: None,
6950        };
6951    }
6952    sub.err("not a map literal")
6953}
6954
6955/// Bare map key: joint `-/.'/'`-run, mirroring the bare-word charset
6956/// (no bool/numeric classification: keys are always strings).
6957fn map_bare_key(sub: &mut Cursor) -> Result<String, TokenError> {
6958    let mut out = String::new();
6959    if matches!(
6960        sub.toks.get(sub.pos).map(|t| &t.kind),
6961        Some(TokKind::Punct('-'))
6962    ) {
6963        out.push('-');
6964        sub.pos += 1;
6965    }
6966    // Leading `/` reads literally too (the bare-word shape admits `/`
6967    // anywhere: `{/a: 1}`, `{//c: 1}`); the joint loop below
6968    // continues the run.
6969    if matches!(
6970        sub.toks.get(sub.pos).map(|t| &t.kind),
6971        Some(TokKind::Punct('/'))
6972    ) {
6973        out.push('/');
6974        sub.pos += 1;
6975    }
6976    match sub.toks.get(sub.pos).map(|t| &t.kind) {
6977        Some(TokKind::Word(w)) => {
6978            out.push_str(w);
6979            sub.pos += 1;
6980        }
6981        // A leading `/` above already started the run; anything
6982        // else still needs a word head.
6983        _ if !out.is_empty() => {}
6984        _ => return Err(sub.err("not a map literal")),
6985    }
6986    while let Some(t) = sub.toks.get(sub.pos) {
6987        if !t.joint {
6988            break;
6989        }
6990        match &t.kind {
6991            TokKind::Word(w) => {
6992                out.push_str(w);
6993                sub.pos += 1;
6994            }
6995            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
6996                out.push(*c);
6997                sub.pos += 1;
6998            }
6999            _ => break,
7000        }
7001    }
7002    if out.contains('\\') {
7003        return Err(sub.err("unexpected escape in map key"));
7004    }
7005    Ok(out)
7006}
7007
7008/// Map-or-block over a brace group's contents: maps parse literally;
7009/// anything else is an inline block (`Expr::Block` over the body
7010/// steps, scopes unmarked like every braced body).
7011fn parse_map_or_block(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7012    match parse_map_literal(inner, stmt, ctx) {
7013        Ok(map) => Ok(map),
7014        // A detected missing comma is never a block: its `key:`
7015        // remainder cannot parse as a statement (a `name: "a"` line
7016        // fails as `unknown command`), so the block path can only
7017        // misreport it. Surface the map error instead; every other
7018        // map failure keeps the block fallback exactly as before.
7019        Err(e) if e.msg == MISSING_MAP_COMMA_MSG => Err(e),
7020        Err(_) => Ok(Expr::Block(parse_body_steps(inner, stmt, ctx, false)?)),
7021    }
7022}
7023
7024/// Parse one standalone expression from lexed tokens (the
7025/// `parse_expression_str` entry point): a full tier parse with
7026/// top-level boundary rejection and full consumption.
7027pub(crate) fn parse_single_expr(
7028    toks: &[Tok],
7029    stmt: usize,
7030    ctx: &ParseCtx,
7031) -> Result<Expr, TokenError> {
7032    let mut cur = Cursor::expr(toks, stmt);
7033    let expr = parse_expr_checked(&mut cur, ctx)?;
7034    if !cur.done() {
7035        return Err(cur.err("unexpected text in expression"));
7036    }
7037    Ok(expr)
7038}
7039
7040/// Assignment `=`: the first depth-zero `=` neither glued to a
7041/// following `=` (`==`) nor glued after `!`/`<`/`>`/`=` (`!=`, `<=`,
7042/// `>=`, second of `==`). `<>` shape brackets own any `=` inside
7043/// them (field defaults), so LET annotations with defaults find the
7044/// real assignment. Glued-ness reads off the `=`'s own `joint` (gap
7045/// before it) and the follower's (gap after it). Anything else leaves
7046/// the statement bare (`LET $p: PIPE`), exactly where the grammar's
7047/// `"="` match fails.
7048fn find_assign_eq(body: &[Tok]) -> Option<usize> {
7049    let mut depth = 0usize;
7050    for (i, tok) in body.iter().enumerate() {
7051        match &tok.kind {
7052            TokKind::Punct('<') => depth += 1,
7053            TokKind::Punct('>') if depth > 0 => depth -= 1,
7054            TokKind::Punct('=') if depth == 0 => {
7055                let next_eq = body
7056                    .get(i + 1)
7057                    .is_some_and(|t| t.joint && matches!(&t.kind, TokKind::Punct('=')));
7058                let prev_op = tok.joint
7059                    && i > 0
7060                    && matches!(&body[i - 1].kind, TokKind::Punct('!' | '<' | '>' | '='));
7061                if !next_eq && !prev_op {
7062                    return Some(i);
7063                }
7064            }
7065            _ => {}
7066        }
7067    }
7068    None
7069}
7070
7071/// Render a type region joint-aware (`LIST< MAP >` keeps its gaps for
7072/// the shared canonicalizer, exactly like `type_tag.as_str()`).
7073fn render_type_region(toks: &[Tok], stmt: usize) -> Result<String, TokenError> {
7074    let mut out = String::new();
7075    for tok in toks {
7076        // Ridden newlines from multi-line `<...>` shapes carry no
7077        // output, so the shape canonicalizes exactly like one line.
7078        if matches!(&tok.kind, TokKind::Newline) {
7079            continue;
7080        }
7081        if !tok.joint && !out.is_empty() {
7082            out.push(' ');
7083        }
7084        match &tok.kind {
7085            TokKind::Word(w) => out.push_str(w),
7086            TokKind::Punct(c) => out.push(*c),
7087            TokKind::Str { text, quote } => {
7088                out.push(*quote);
7089                out.push_str(text);
7090                out.push(*quote);
7091            }
7092            TokKind::BlockStr(full) => out.push_str(full),
7093            _ => {
7094                return Err(TokenError {
7095                    stmt,
7096                    msg: "malformed type in LET".to_string(),
7097                    line: 0,
7098                    col: 0,
7099                    kind: None,
7100                });
7101            }
7102        }
7103    }
7104    if out.is_empty() {
7105        return Err(TokenError {
7106            stmt,
7107            msg: "LET requires explicit type: LET $var: TYPE = <expr>".to_string(),
7108            line: 0,
7109            col: 0,
7110            kind: None,
7111        });
7112    }
7113    Ok(crate::canonicalize_spelling(&out))
7114}
7115
7116fn expect_dollar_var(cur: &mut Cursor, msg: &str) -> Result<String, TokenError> {
7117    // Atomic `dollar_ident`: no gap between `$` and the name (the
7118    // enclosing statements are compound-atomic, so implicit spacing is
7119    // off and only explicit `gap`s admit whitespace).
7120    match cur.next() {
7121        Some(t) if matches!(&t.kind, TokKind::Punct('$')) => {}
7122        _ => return Err(cur.err(msg)),
7123    }
7124    match cur.next() {
7125        Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
7126            match &t.kind {
7127                TokKind::Word(w) => Ok(w.clone()),
7128                _ => unreachable!(),
7129            }
7130        }
7131        _ => Err(cur.err(msg)),
7132    }
7133}
7134
7135/// `LET` body: `LET` is already matched. Returns `None` (miss to
7136/// generic, which fails in lowering like the grammar's committed
7137/// `instruction`) when the shape cannot match any `LET` form: no
7138/// gapless `$var`, or no `:` after it
7139/// (every form needs `: TYPE`). Past that the shape is committed and
7140/// malformed tails fail loudly.
7141fn parse_let_body(
7142    body: &[Tok],
7143    stmt: usize,
7144    ctx: &ParseCtx,
7145) -> Result<Option<(StepKind, usize)>, TokenError> {
7146    let mut cur = Cursor::expr(body, stmt);
7147    match cur.next() {
7148        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_LET) => {}
7149        _ => return Err(cur.err("unreachable")),
7150    }
7151    // No `$var`: no `LET` form can match (miss, never a hard fail).
7152    let var = match expect_dollar_var(&mut cur, "LET requires a variable") {
7153        Ok(var) => var,
7154        Err(_) => return Ok(None),
7155    };
7156    // The header allows gaps (comments, never newlines).
7157    cur.skip_gap();
7158    // No `:`: untyped LET is rejected outright. Every binding is
7159    // typed; the old miss-to-generic path only hid that behind a
7160    // rambling "invalid syntax" message. (FOR already does this.)
7161    if !cur.eat_punct(':') {
7162        return Err(TokenError {
7163            stmt,
7164            msg: "LET requires explicit types: LET $var: TYPE = <expr>".to_string(),
7165            line: 0,
7166            col: 0,
7167            kind: Some(ParseErrorKind::InvalidSyntax {
7168                command: KEYWORD_LET.to_string(),
7169            }),
7170        });
7171    }
7172    // Type region runs to the depth-zero assignment `=`; `<>`
7173    // shapes own any `=` inside them (field defaults).
7174    let type_start = cur.pos;
7175    let assign = find_assign_eq(&body[type_start..]).map(|i| i + type_start);
7176    let Some(eq) = assign else {
7177        // Bare `LET $p: PIPE` mints a fresh pipe and ends with the
7178        // type word (trailing elements loop on, probed); every other
7179        // bare type is a validation error, mirroring the grammar.
7180        if matches!(
7181            body.get(type_start).map(|t| &t.kind),
7182            Some(TokKind::Word(w)) if w == crate::TypeTag::Pipe.name()
7183        ) {
7184            return Ok(Some((
7185                StepKind::Assign {
7186                    var,
7187                    decl_type: crate::TypeTag::Pipe.name().to_string(),
7188                    expr: Expr::FreshPipe,
7189                },
7190                type_start + 1,
7191            )));
7192        }
7193        return Err(cur.err(
7194            "LET requires an expression: LET $var: TYPE = <expr> (only LET $p: PIPE omits the initializer)",
7195        ));
7196    };
7197    let decl_type = render_type_region(&body[type_start..eq], stmt)?;
7198    let (kind, rhs_used) = parse_let_rhs(&body[eq + 1..], var, decl_type, stmt, ctx)?;
7199    Ok(Some((kind, eq + 1 + rhs_used)))
7200}
7201
7202/// LET right-hand side dispatch, mirroring the grammar order
7203/// (`let_async`, then `let_capture`, then `let_statement`):
7204/// `WITH_IO`-led lines branch async/sync like
7205/// `parse_let_async_statement_from_pair`, `ASYNC`-led lines spawn
7206/// tasks, `TIMEOUT`-led lines capture through the wrapper,
7207/// `AWAIT $v` captures, RUN exec-form captures, known commands
7208/// capture through the generic parser (lowering failures fatal,
7209/// exactly like the committed grammar alternative), and anything
7210/// else parses as an expression (unknown leads included). Returns
7211/// the kind and RHS tokens consumed: captures ending in structural
7212/// pairs leave trailing elements for the caller.
7213fn parse_let_rhs(
7214    rhs: &[Tok],
7215    var: String,
7216    decl_type: String,
7217    stmt: usize,
7218    ctx: &ParseCtx,
7219) -> Result<(StepKind, usize), TokenError> {
7220    // Leading gap comments vanish like the `=` gap (but a `//`/`#`
7221    // to end of input leaves no expression, failing).
7222    let mut lead = Cursor::expr(rhs, stmt);
7223    lead.skip_gap();
7224    let (rhs, skipped) = (&rhs[lead.pos..], lead.pos);
7225    let head_word = match rhs.first().map(|t| &t.kind) {
7226        Some(TokKind::Word(w)) => Some(w.clone()),
7227        _ => None,
7228    };
7229    // `WITH_IO`-led lines share `let_async_statement` with the
7230    // `ASYNC` forms (the grammar claims every WITH_IO-led LET
7231    // there); shape misses fall through to generic below.
7232    if head_word.as_deref() == Some(KEYWORD_WITH_IO)
7233        && let Some(found) = try_let_with_io_rhs(rhs, var.clone(), decl_type.clone(), stmt, ctx)?
7234    {
7235        let (kind, used) = found;
7236        return Ok((kind, skipped + used));
7237    }
7238    // `ASYNC`-led lines (with followers; alone they commit to the
7239    // generic path like the grammar, failing in lowering) spawn
7240    // background tasks. No `WITH_IO` scan here (probed: the LET
7241    // path accepts what statement `ASYNC` rejects).
7242    if head_word.as_deref() == Some(KEYWORD_ASYNC) && rhs.len() > 1 {
7243        let (kind, used) = parse_let_async_rhs(&rhs[1..], var, decl_type, stmt, ctx)?;
7244        return Ok((kind, skipped + 1 + used));
7245    }
7246    // `TIMEOUT`-led lines capture through the wrapper (shape misses
7247    // fall through to generic, which fails in lowering).
7248    if head_word.as_deref() == Some(KEYWORD_TIMEOUT)
7249        && let Some((kind, used)) = parse_timeout_single(rhs, 0, stmt, ctx)?
7250    {
7251        let span = lowering_ctx(stmt);
7252        crate::commands::reject_async_in_capture(&span, &kind).map_err(|e| TokenError {
7253            stmt,
7254            msg: e.to_string(),
7255            line: 0,
7256            col: 0,
7257            kind: None,
7258        })?;
7259        crate::commands::reject_pipe_stdout_in_capture(&span, &kind).map_err(|e| TokenError {
7260            stmt,
7261            msg: e.to_string(),
7262            line: 0,
7263            col: 0,
7264            kind: None,
7265        })?;
7266        return Ok((
7267            StepKind::AssignCapture {
7268                var,
7269                decl_type,
7270                cmd: Box::new(kind),
7271            },
7272            skipped + used,
7273        ));
7274    }
7275    // `AWAIT $v` captures the task output (`$`+name ride gapless in
7276    // this atomic position, like the grammar); anything else
7277    // `AWAIT`-led goes generic below (lowering fails it, probed).
7278    if head_word.as_deref() == Some(KEYWORD_AWAIT)
7279        && rhs.len() == 3
7280        && let (Some(dollar), Some(task)) = (rhs.get(1), rhs.get(2))
7281        && matches!(&dollar.kind, TokKind::Punct('$'))
7282        && task.joint
7283        && let TokKind::Word(task_var) = &task.kind
7284        && is_ident_word(task_var)
7285    {
7286        return Ok((
7287            StepKind::AwaitCapture {
7288                out_var: var,
7289                out_type: decl_type,
7290                task_var: task_var.clone(),
7291            },
7292            skipped + 3,
7293        ));
7294    }
7295    // RUN exec form captures the structured argv (gapped bracket;
7296    // a joint bracket falls through to generic, which fails it in
7297    // lowering).
7298    if head_word.as_deref() == Some(KEYWORD_RUN)
7299        && matches!(
7300            rhs.get(1).map(|t| (&t.kind, t.joint)),
7301            Some((
7302                TokKind::Group {
7303                    delim: GroupDelim::Bracket,
7304                    ..
7305                },
7306                false
7307            ))
7308        )
7309        && rhs.len() == 2
7310    {
7311        let inner = match &rhs[1].kind {
7312            TokKind::Group { inner, .. } => inner.clone(),
7313            _ => unreachable!(),
7314        };
7315        // Non-map blocks miss the exec shape; fall through below
7316        // (known-command capture, then expression), mirroring the
7317        // grammar's ordered alternatives.
7318        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
7319            let kind =
7320                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
7321            return Ok((
7322                StepKind::AssignCapture {
7323                    var,
7324                    decl_type,
7325                    cmd: Box::new(kind),
7326                },
7327                skipped + 2,
7328            ));
7329        }
7330    }
7331    // File `IMPORT ["path" AS ALIAS]` (#115) captures the imported
7332    // pipeline's `RETURN` value like a call (`LET $r: STRING = IMPORT ...`
7333    // lowers to `AssignCapture`): exactly one file entry, no modules.
7334    // Anything else shaped like an import is a hard error; shape misses
7335    // fall through to generic below, which fails them in lowering.
7336    if head_word.as_deref() == Some(KEYWORD_IMPORT)
7337        && let Some((path, alias, used)) = parse_single_file_import(rhs, 0, stmt, ctx)?
7338    {
7339        return Ok((
7340            StepKind::AssignCapture {
7341                var,
7342                decl_type,
7343                cmd: Box::new(StepKind::ImportFile { path, alias }),
7344            },
7345            skipped + used,
7346        ));
7347    }
7348    // Known-command leads capture through the generic parser
7349    // (lowering failures are fatal here, exactly like the committed
7350    // grammar alternative: probed wrapper-alone and `ISOLATED`-led
7351    // shapes error in lowering); unknown leads parse as expressions.
7352    match &head_word {
7353        Some(head) if is_known_command(head) => {
7354            let (cmd, used) = parse_inner_command(rhs, stmt, ctx)?;
7355            let span = lowering_ctx(stmt);
7356            crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| TokenError {
7357                stmt,
7358                msg: e.to_string(),
7359                line: 0,
7360                col: 0,
7361                kind: None,
7362            })?;
7363            crate::commands::reject_pipe_stdout_in_capture(&span, &cmd).map_err(|e| {
7364                TokenError {
7365                    stmt,
7366                    msg: e.to_string(),
7367                    line: 0,
7368                    col: 0,
7369                    kind: None,
7370                }
7371            })?;
7372            // `INHERIT_ENV`-led lines land here (generic): the
7373            // nesting check rejects them (probed).
7374            crate::commands::reject_nested_inherit_env(&span, &cmd).map_err(|e| TokenError {
7375                stmt,
7376                msg: e.to_string(),
7377                line: 0,
7378                col: 0,
7379                kind: None,
7380            })?;
7381            return Ok((
7382                StepKind::AssignCapture {
7383                    var,
7384                    decl_type,
7385                    cmd: Box::new(cmd),
7386                },
7387                skipped + used,
7388            ));
7389        }
7390        _ => {}
7391    }
7392    let mut cur = Cursor::expr(rhs, stmt);
7393    let expr = parse_expr_checked(&mut cur, ctx)?;
7394    let used = skipped + cur.pos;
7395    Ok((
7396        StepKind::Assign {
7397            var,
7398            decl_type,
7399            expr,
7400        },
7401        used,
7402    ))
7403}
7404
7405/// `WITH_IO`-led LET right-hand side, mirroring
7406/// `parse_let_async_statement_from_pair`'s `with_io_command` branch:
7407/// wrapping `ASYNC` binds a pipe-wired background task (multi-step
7408/// blocks fail loudly), wrapping a sync command captures its stdout
7409/// (async bodies and `stdout` pipes fail loudly), and a bare
7410/// bracket fails validation. `None` on shape miss (bad bracket:
7411/// the caller goes generic, which fails in lowering).
7412fn try_let_with_io_rhs(
7413    rhs: &[Tok],
7414    var: String,
7415    decl_type: String,
7416    stmt: usize,
7417    ctx: &ParseCtx,
7418) -> Result<Option<(StepKind, usize)>, TokenError> {
7419    let bracket = match rhs.get(1) {
7420        Some(t)
7421            if !t.joint
7422                && matches!(
7423                    &t.kind,
7424                    TokKind::Group {
7425                        delim: GroupDelim::Bracket,
7426                        ..
7427                    }
7428                ) =>
7429        {
7430            t
7431        }
7432        _ => return Ok(None),
7433    };
7434    let inner = match &bracket.kind {
7435        TokKind::Group { inner, .. } => inner.clone(),
7436        _ => unreachable!(),
7437    };
7438    let bindings = match parse_io_bindings(&inner, stmt)? {
7439        Some(bindings) => bindings,
7440        None => return Ok(None),
7441    };
7442    let fail = |msg: String| TokenError {
7443        stmt,
7444        msg,
7445        line: 0,
7446        col: 0,
7447        kind: None,
7448    };
7449    let rest = &rhs[2..];
7450    let Some(first) = rest.first() else {
7451        // Bare bracket: the grammar's committed validation error.
7452        return Err(fail(
7453            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7454                .to_string(),
7455        ));
7456    };
7457    if first.joint {
7458        // The inner rides after a `sep`: joint followers miss the
7459        // shape and fail validation like the grammar's bare bracket.
7460        return Err(fail(
7461            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7462                .to_string(),
7463        ));
7464    }
7465    if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_ASYNC) {
7466        // `WITH_IO [..] ASYNC <single|block>`: the bindings apply
7467        // inside the task thread (same shape as a one-step body
7468        // holding one `WITH_IO` step, which the runtime supports).
7469        // A bare `ASYNC` goes generic and fails in lowering
7470        // (`unknown command: ASYNC`, probed).
7471        let after = &rest[1..];
7472        if after.is_empty() {
7473            // Bare `ASYNC`: the grammar commits to `instruction`
7474            // and lowering fails it (`unknown command: ASYNC`,
7475            // probed); mirror by running generic, staying failed
7476            // even under a lenient dispatcher.
7477            match parse_inner_command(&rest[..1], stmt, ctx) {
7478                Err(e) => return Err(e),
7479                Ok(_) => {
7480                    return Err(fail(
7481                        "LET $var: HANDLE<T> = ASYNC requires a body".to_string(),
7482                    ));
7483                }
7484            }
7485        }
7486        if let Some(second) = after.first()
7487            && matches!(
7488                &second.kind,
7489                TokKind::Group {
7490                    delim: GroupDelim::Brace,
7491                    ..
7492                }
7493            )
7494            && !is_template_brace(second)
7495        {
7496            let brace_inner = match &second.kind {
7497                TokKind::Group { inner, .. } => inner.clone(),
7498                _ => unreachable!(),
7499            };
7500            let body = parse_body_steps(&brace_inner, stmt, ctx, false)?;
7501            if body.len() != 1 {
7502                return Err(fail(
7503                        "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"
7504                            .to_string(),
7505                    ));
7506            }
7507            let wrapped = Step {
7508                guard: None,
7509                kind: StepKind::WithIo {
7510                    bindings,
7511                    cmd: Box::new(
7512                        body.into_iter()
7513                            .next()
7514                            .ok_or_else(|| {
7515                                fail("LET $var: HANDLE<T> = ASYNC requires a body".to_string())
7516                            })?
7517                            .kind,
7518                    ),
7519                },
7520                scope_enter: 0,
7521                scope_exit: 0,
7522                line: 0,
7523                col: 0,
7524            };
7525            return Ok(Some((
7526                StepKind::AssignAsync {
7527                    var,
7528                    decl_type,
7529                    body: vec![wrapped],
7530                },
7531                2 + 2,
7532            )));
7533        }
7534        if after.first().is_some_and(|t| t.joint) {
7535            // Joint followers miss the inner `sep`: same validation
7536            // error as the bare bracket.
7537            return Err(fail(
7538                "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7539                    .to_string(),
7540            ));
7541        }
7542        let (cmd, used) = parse_single_inner(
7543            rest,
7544            1,
7545            stmt,
7546            ctx,
7547            InnerRules {
7548                allow_await: false,
7549                allow_with_io: false,
7550            },
7551        )?;
7552        let wrapped = Step {
7553            guard: None,
7554            kind: StepKind::WithIo {
7555                bindings,
7556                cmd: Box::new(cmd),
7557            },
7558            scope_enter: 0,
7559            scope_exit: 0,
7560            line: 0,
7561            col: 0,
7562        };
7563        let kind = StepKind::AssignAsync {
7564            var,
7565            decl_type,
7566            body: vec![wrapped],
7567        };
7568        let span = lowering_ctx(stmt);
7569        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7570            stmt,
7571            msg: e.to_string(),
7572            line: 0,
7573            col: 0,
7574            kind: None,
7575        })?;
7576        return Ok(Some((kind, 2 + 1 + used)));
7577    }
7578    if matches!(
7579        &first.kind,
7580        TokKind::Group {
7581            delim: GroupDelim::Brace,
7582            ..
7583        }
7584    ) {
7585        // A brace is no sync command: same validation error (probed).
7586        return Err(fail(
7587            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7588                .to_string(),
7589        ));
7590    }
7591    // Sync inner: capture with the shared checks (the capture sink
7592    // owns stdout; async never runs inline).
7593    let (cmd, used) = parse_single_inner(
7594        rest,
7595        0,
7596        stmt,
7597        ctx,
7598        InnerRules {
7599            allow_await: false,
7600            allow_with_io: true,
7601        },
7602    )?;
7603    let span = lowering_ctx(stmt);
7604    if crate::commands::has_stdout_pipe(&bindings) {
7605        return Err(fail(
7606            "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
7607                .to_string(),
7608        ));
7609    }
7610    crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| TokenError {
7611        stmt,
7612        msg: e.to_string(),
7613        line: 0,
7614        col: 0,
7615        kind: None,
7616    })?;
7617    Ok(Some((
7618        StepKind::AssignCapture {
7619            var,
7620            decl_type,
7621            cmd: Box::new(StepKind::WithIo {
7622                bindings,
7623                cmd: Box::new(cmd),
7624            }),
7625        },
7626        2 + used,
7627    )))
7628}
7629
7630/// `ASYNC`-led LET right-hand side (the tokens after `ASYNC`):
7631/// a block or single command becomes the task body. No `WITH_IO`
7632/// scan (probed: this path accepts what statement `ASYNC`
7633/// rejects); nesting still fails loudly through the shared check.
7634fn parse_let_async_rhs(
7635    rest: &[Tok],
7636    var: String,
7637    decl_type: String,
7638    stmt: usize,
7639    ctx: &ParseCtx,
7640) -> Result<(StepKind, usize), TokenError> {
7641    let Some(first) = rest.first() else {
7642        return Err(TokenError {
7643            stmt,
7644            msg: "LET $var: HANDLE<T> = ASYNC requires a body".to_string(),
7645            line: 0,
7646            col: 0,
7647            kind: None,
7648        });
7649    };
7650    if matches!(
7651        &first.kind,
7652        TokKind::Group {
7653            delim: GroupDelim::Brace,
7654            ..
7655        }
7656    ) && !is_template_brace(first)
7657    {
7658        let inner = match &first.kind {
7659            TokKind::Group { inner, .. } => inner.clone(),
7660            _ => unreachable!(),
7661        };
7662        let body = parse_body_steps(&inner, stmt, ctx, false)?;
7663        let kind = StepKind::AssignAsync {
7664            var,
7665            decl_type,
7666            body,
7667        };
7668        let span = lowering_ctx(stmt);
7669        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7670            stmt,
7671            msg: e.to_string(),
7672            line: 0,
7673            col: 0,
7674            kind: None,
7675        })?;
7676        return Ok((kind, 1));
7677    }
7678    if first.joint {
7679        return Err(TokenError {
7680            stmt,
7681            msg: "LET $var: HANDLE<T> = ASYNC requires a body".to_string(),
7682            line: 0,
7683            col: 0,
7684            kind: None,
7685        });
7686    }
7687    let (cmd, used) = parse_single_inner(
7688        rest,
7689        0,
7690        stmt,
7691        ctx,
7692        InnerRules {
7693            allow_await: false,
7694            allow_with_io: false,
7695        },
7696    )?;
7697    let kind = StepKind::AssignAsync {
7698        var,
7699        decl_type,
7700        body: vec![Step {
7701            guard: None,
7702            kind: cmd,
7703            scope_enter: 0,
7704            scope_exit: 0,
7705            line: 0,
7706            col: 0,
7707        }],
7708    };
7709    let span = lowering_ctx(stmt);
7710    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7711        stmt,
7712        msg: e.to_string(),
7713        line: 0,
7714        col: 0,
7715        kind: None,
7716    })?;
7717    Ok((kind, used))
7718}
7719
7720fn parse_set_body(
7721    body: &[Tok],
7722    stmt: usize,
7723    ctx: &ParseCtx,
7724) -> Result<(StepKind, usize), TokenError> {
7725    let mut cur = Cursor::expr(body, stmt);
7726    let var = expect_dollar_var(&mut cur, "mutation requires a variable: $var = <expr>")?;
7727    let assign = find_assign_eq(&body[cur.pos..]).map(|i| i + cur.pos);
7728    let eq = match assign {
7729        Some(eq) => eq,
7730        None => {
7731            return Err(cur.err("mutation requires a variable: $var = <expr>"));
7732        }
7733    };
7734    cur.pos = eq + 1;
7735    // Leading gap comments vanish like the `=` gap.
7736    cur.skip_gap();
7737    let expr = parse_expr_checked(&mut cur, ctx)?;
7738    Ok((StepKind::Set { var, expr }, cur.pos))
7739}
7740
7741fn parse_return_body(
7742    body: &[Tok],
7743    stmt: usize,
7744    ctx: &ParseCtx,
7745) -> Result<(StepKind, usize), TokenError> {
7746    let mut cur = Cursor::expr(body, stmt);
7747    match cur.next() {
7748        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_RETURN) => {}
7749        _ => return Err(cur.err("unreachable")),
7750    }
7751    if cur.done() {
7752        return Ok((
7753            StepKind::Return {
7754                expr: Box::new(Expr::Literal(Value::string(String::new()))),
7755                is_bare: true,
7756            },
7757            cur.pos,
7758        ));
7759    }
7760    let expr = parse_expr_checked(&mut cur, ctx)?;
7761    Ok((
7762        StepKind::Return {
7763            expr: Box::new(expr),
7764            is_bare: false,
7765        },
7766        cur.pos,
7767    ))
7768}
7769
7770/// Lower one statement to steps through the element loop: the
7771/// statement guard attaches to the first element only (trailing
7772/// elements ride guardless, probed): the pending guard clears after
7773/// the first command token.
7774fn lower_stmt_steps(
7775    stmt: &Stmt,
7776    idx: usize,
7777    ctx: &ParseCtx,
7778    in_block: bool,
7779    mark: bool,
7780) -> Result<Vec<Step>, TokenError> {
7781    let guard = parse_guard_groups(&stmt.guard, idx)?;
7782    // Statement-head braces route here (mid-run braces fail inside
7783    // the element loop): templates and guardless/bare blocks fail
7784    // loudly; guarded braces open guard blocks (top level) or the
7785    // nested quirk (in bodies).
7786    let mut steps = if starts_brace(&stmt.body) {
7787        parse_brace_head(stmt, guard, idx, ctx, in_block, mark)?
7788    } else {
7789        parse_elements(&stmt.body, idx, ctx, guard, in_block)?
7790    };
7791    // Stamp the statement's source position on every directly
7792    // produced step still missing one. Nested body steps were stamped
7793    // by their own statements during recursion, so only direct
7794    // products are claimed here; inner statements keep their own
7795    // lines and columns.
7796    for step in &mut steps {
7797        if step.line == 0 {
7798            step.line = stmt.line;
7799        }
7800        if step.col == 0 {
7801            step.col = stmt.col;
7802        }
7803    }
7804    // Qualify bare placeholder calls (`{{ NAME(args) }}`) through
7805    // the shared static resolver, so templates obey exactly the
7806    // statement-position scope rule. Nested bodies were already
7807    // qualified by their own recursive statements with their own
7808    // frames, so only direct products are visited here. Both
7809    // `Arg::String` fragments (via `walk_raw_strings_mut`) and
7810    // `Expr::Literal` strings (LET/SET/RETURN/call args/list/map
7811    // literals/parenthesized args) are qualified: expression
7812    // positions expand through the same `expand_string` at runtime,
7813    // so they must see the same parse-time rewrite. `WithIo` and
7814    // `AssignCapture` box their inner command directly (no recursive
7815    // statement pass), so the helper descends into them; all other
7816    // bodies were already qualified with their own frames.
7817    // `Step.guards` carry no template text (`Guard::Attr` triples
7818    // evaluated via `guard_allows`, never expanded), so there is
7819    // nothing to qualify there.
7820    let mut failed: Option<TokenError> = None;
7821    for step in &mut steps {
7822        qualify_step_templates(step, ctx, idx, &mut failed);
7823        if failed.is_some() {
7824            break;
7825        }
7826    }
7827    if let Some(err) = failed {
7828        return Err(err);
7829    }
7830    Ok(steps)
7831}
7832
7833/// Qualify one direct statement product plus any boxed `WithIo` /
7834/// `AssignCapture` inner command (same scope frame, never a
7835/// recursive statement pass). Body vectors are skipped: their steps
7836/// were qualified by their own recursive statements.
7837fn qualify_step_templates(
7838    step: &mut Step,
7839    ctx: &ParseCtx,
7840    stmt: usize,
7841    failed: &mut Option<TokenError>,
7842) {
7843    qualify_kind_templates(&mut step.kind, ctx, stmt, failed);
7844}
7845
7846/// Qualify one `StepKind` plus boxed inner commands sharing the
7847/// same scope frame.
7848fn qualify_kind_templates(
7849    kind: &mut StepKind,
7850    ctx: &ParseCtx,
7851    stmt: usize,
7852    failed: &mut Option<TokenError>,
7853) {
7854    kind.walk_raw_strings_mut(&mut |text| {
7855        if failed.is_none() {
7856            match qualify_template_calls(text, ctx, stmt) {
7857                Ok(Some(rewritten)) => *text = rewritten,
7858                Ok(None) => {}
7859                Err(err) => *failed = Some(err),
7860            }
7861        }
7862    });
7863    if failed.is_some() {
7864        return;
7865    }
7866    kind.walk_exprs_mut(&mut |expr| {
7867        if failed.is_some() {
7868            return;
7869        }
7870        expr.walk_mut(&mut |node| {
7871            if failed.is_some() {
7872                return;
7873            }
7874            if let Expr::Literal(value) = node
7875                && let Some(text) = value.as_str()
7876            {
7877                match qualify_template_calls(text, ctx, stmt) {
7878                    Ok(Some(rewritten)) => {
7879                        *value = Value::string(rewritten);
7880                    }
7881                    Ok(None) => {}
7882                    Err(err) => *failed = Some(err),
7883                }
7884            }
7885        });
7886    });
7887    if failed.is_some() {
7888        return;
7889    }
7890    // Boxed single commands share the outer scope frame (no recursive
7891    // statement pass built them): qualify the inner kind directly.
7892    match kind {
7893        StepKind::WithIo { cmd, .. } | StepKind::AssignCapture { cmd, .. } => {
7894            qualify_kind_templates(cmd, ctx, stmt, failed);
7895        }
7896        _ => {}
7897    }
7898    if failed.is_some() {
7899        return;
7900    }
7901    // Single-command synthetic bodies share the outer frame: `TIMEOUT 5s
7902    // <cmd>`, `ISOLATED <cmd>`, `ASYNC <cmd>`, and `AssignAsync` wrappers
7903    // build their `body` inline via `parse_single_inner` with no recursive
7904    // `lower_stmt_steps` pass, so their one synthetic step needs this one.
7905    // Brace-delimited bodies are NEVER re-walked here: they were already
7906    // lowered via `parse_body_steps` with their own frames and statement
7907    // indices (mirroring `Expr::walk_mut` skipping `Expr::Block`), and
7908    // re-resolving under the outer frame would corrupt scope isolation
7909    // and error attribution. The match names only the synthetic carriers;
7910    // any other body (If/For/While/FuncDef/RemoteBlock/WithIoBlock) stays
7911    // exactly as its own recursive pass left it.
7912    match kind {
7913        StepKind::Timeout { body, .. }
7914        | StepKind::Isolated { body }
7915        | StepKind::AsyncBlock { body }
7916        | StepKind::AssignAsync { body, .. } => {
7917            for step in body.iter_mut() {
7918                if failed.is_some() {
7919                    return;
7920                }
7921                qualify_step_templates(step, ctx, stmt, failed);
7922            }
7923        }
7924        _ => {}
7925    }
7926}
7927
7928/// Statement-head `{...}` dispatcher. Template braces fail (the
7929/// grammar strands them); guardless top-level braces fail; detached
7930/// or guardless in-body braces fail (no `block_start` in
7931/// `block_element`); guarded braces open a guard scope at top level
7932/// or mirror the nested quirk formula in bodies. Trailing elements
7933/// loop on guardless outside (like the grammar's continued line).
7934fn parse_brace_head(
7935    stmt: &Stmt,
7936    guard: Option<GuardExpr>,
7937    idx: usize,
7938    ctx: &ParseCtx,
7939    in_block: bool,
7940    mark: bool,
7941) -> Result<Vec<Step>, TokenError> {
7942    let brace = &stmt.body[0];
7943    if is_template_brace(brace) {
7944        return Err(TokenError {
7945            stmt: idx,
7946            msg: "'{' without a pending guard".to_string(),
7947            line: 0,
7948            col: 0,
7949            kind: None,
7950        });
7951    }
7952    let inner = match &brace.kind {
7953        TokKind::Group { inner, .. } => inner.clone(),
7954        _ => unreachable!(),
7955    };
7956    if in_block {
7957        // Attached guarded braces only: pending holds all groups but
7958        // the last (the block's own), mirroring the pair structure.
7959        if guard.is_none() || stmt.brace_detached || stmt.guard.is_empty() {
7960            return Err(TokenError {
7961                stmt: idx,
7962                msg: "unexpected '{' in block body".to_string(),
7963                line: 0,
7964                col: 0,
7965                kind: None,
7966            });
7967        }
7968        let n = stmt.guard.len();
7969        let mut pending = None;
7970        if n > 1 {
7971            pending = parse_guard_groups(&stmt.guard[..n - 1], idx)?;
7972        }
7973        let block_guard = parse_guard_groups(&stmt.guard[n - 1..n], idx)?.ok_or(TokenError {
7974            stmt: idx,
7975            msg: "unexpected '{' in block body".to_string(),
7976            line: 0,
7977            col: 0,
7978            kind: None,
7979        })?;
7980        let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
7981        // Guard-block bodies propagate the ambient marking context
7982        // (top-level nesting marks; wrapper bodies never mark).
7983        // Quirk formula verbatim (including the dropped block guard
7984        // with inner guards, probed).
7985        for s in &mut steps {
7986            let inner_guard = s.guard.take();
7987            s.guard = Some(match (pending.clone(), inner_guard) {
7988                (Some(p), Some(e)) => GuardExpr::all(vec![p, e]),
7989                (Some(p), None) => GuardExpr::all(vec![p, block_guard.clone()]),
7990                (None, Some(e)) => e,
7991                (None, None) => block_guard.clone(),
7992            });
7993        }
7994        // Marking contexts bump each nesting level (probed top-level
7995        // double-block 2/2); wrapper bodies stay 0/0.
7996        // Trailing elements ride outside, unmarked.
7997        if mark {
7998            if let Some(first) = steps.first_mut() {
7999                first.scope_enter += 1;
8000            }
8001            if let Some(last) = steps.last_mut() {
8002                last.scope_exit += 1;
8003            }
8004        }
8005        // Trailing elements loop on guardless outside.
8006        if stmt.body.len() > 1 {
8007            let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
8008            steps.append(&mut rest);
8009        }
8010        return Ok(steps);
8011    }
8012    // Top level: guardless braces fail; guarded braces open a guard
8013    // scope (each step folds outer-then-inner with markers).
8014    let Some(outer) = guard else {
8015        return Err(TokenError {
8016            stmt: idx,
8017            msg: "'{' without a pending guard".to_string(),
8018            line: 0,
8019            col: 0,
8020            kind: None,
8021        });
8022    };
8023    let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
8024    if steps.is_empty() {
8025        return Err(TokenError {
8026            stmt: idx,
8027            msg: "guard block must contain at least one command".to_string(),
8028            line: 0,
8029            col: 0,
8030            kind: None,
8031        });
8032    }
8033    for s in &mut steps {
8034        let inner_guard = s.guard.take();
8035        s.guard = Some(match inner_guard {
8036            Some(e) => GuardExpr::all(vec![outer.clone(), e]),
8037            None => outer.clone(),
8038        });
8039    }
8040    if let Some(first) = steps.first_mut() {
8041        first.scope_enter += 1;
8042    }
8043    if let Some(last) = steps.last_mut() {
8044        last.scope_exit += 1;
8045    }
8046    if stmt.body.len() > 1 {
8047        let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
8048        steps.append(&mut rest);
8049    }
8050    Ok(steps)
8051}
8052
8053/// Parse consecutive elements to end of run (the grammar's
8054/// `element*`): structural pairs (calls, RUN-exec, await/cancel,
8055/// wrapper blocks) end mid-run and trailing elements form following
8056/// steps; instructions and expressions consume greedily to the end.
8057fn parse_elements(
8058    toks: &[Tok],
8059    stmt: usize,
8060    ctx: &ParseCtx,
8061    guard: Option<GuardExpr>,
8062    in_block: bool,
8063) -> Result<Vec<Step>, TokenError> {
8064    let mut steps = Vec::new();
8065    let mut pos = 0;
8066    // Statement guard: consumed by the first element that yields a
8067    // step. `IMPORT` yields none, so the guard leaks to the next
8068    // element (probed).
8069    let mut pending_guard: Option<GuardExpr> = guard;
8070    while pos < toks.len() {
8071        // Trailing gap comments between elements (`} #c`, `F("a")
8072        // /*c*/ ECHO`, `LET $x: INT = 1 //c` — the pair ended, so the
8073        // comment is silent like the grammar, never payload):
8074        // `#` and lexer `Comment` markers run to the run end, `//`
8075        // likewise (line comments eat `;` too, and runs hold no
8076        // newlines), `/* */` balances. Mid-run `#`/`/*` stay payload
8077        // text inside the generic path, which consumes everything
8078        // and never loops back here.
8079        if matches!(&toks[pos].kind, TokKind::Punct('#'))
8080            || matches!(&toks[pos].kind, TokKind::Comment(_))
8081        {
8082            break;
8083        }
8084        if matches!(&toks[pos].kind, TokKind::Punct('/')) && is_comment_open(toks, pos) {
8085            if matches!(
8086                toks.get(pos + 1).map(|t| &t.kind),
8087                Some(TokKind::Punct('/'))
8088            ) {
8089                break;
8090            }
8091            match skip_inline_comment(toks, pos) {
8092                Some(past) => {
8093                    pos = past;
8094                    continue;
8095                }
8096                None => {
8097                    return Err(TokenError {
8098                        stmt,
8099                        msg: "unclosed block comment".to_string(),
8100                        line: 0,
8101                        col: 0,
8102                        kind: None,
8103                    });
8104                }
8105            }
8106        }
8107        // `IMPORT` statements update the import frames; module entries
8108        // emit no step (the guard leaks to the next element, probed,
8109        // unless this is top level, where a guarded module import
8110        // fails), while each file entry emits one `ImportFile` step
8111        // carrying the guard. Shape misses fall through to generic
8112        // (lowering fails them).
8113        if matches!(
8114            toks.get(pos).map(|t| &t.kind),
8115            Some(TokKind::Word(w)) if w == KEYWORD_IMPORT
8116        ) {
8117            // Unified statement form (#115): each entry validates hard
8118            // (unknown modules, bad aliases, templates, remote URLs);
8119            // module entries update the frame and emit no step, file
8120            // and harvest entries emit one step each, in source order.
8121            // A top-level guard on a statement with module entries fails
8122            // like the historical directive; file-only statements consume
8123            // the guard like any other element.
8124            if let Some(((modules, kinds), used)) = parse_import_statement(toks, pos, stmt, ctx)? {
8125                if !modules.is_empty() && !in_block && pending_guard.is_some() {
8126                    return Err(TokenError {
8127                        stmt,
8128                        msg: "IMPORT cannot be guarded".to_string(),
8129                        line: 0,
8130                        col: 0,
8131                        kind: None,
8132                    });
8133                }
8134                // Modules-only statements stay zero-step directives: the
8135                // guard leaks to the next element (probed). Anything with
8136                // file or harvest entries consumes it.
8137                let guard = if kinds.is_empty() {
8138                    None
8139                } else {
8140                    pending_guard.take()
8141                };
8142                for kind in kinds {
8143                    steps.push(Step {
8144                        guard: guard.clone(),
8145                        kind,
8146                        scope_enter: 0,
8147                        scope_exit: 0,
8148                        line: 0,
8149                        col: 0,
8150                    });
8151                }
8152                pos += used;
8153                continue;
8154            }
8155        }
8156        let guard = pending_guard.take();
8157        let (mut got, used) = parse_element_at(toks, pos, stmt, ctx, guard, in_block)?;
8158        if used == 0 {
8159            return Err(TokenError {
8160                stmt,
8161                msg: "element consumed no input".to_string(),
8162                line: 0,
8163                col: 0,
8164                kind: None,
8165            });
8166        }
8167        steps.append(&mut got);
8168        pos += used;
8169    }
8170    Ok(steps)
8171}
8172
8173/// Parse one element at `pos`, returning built steps (guard already
8174/// assigned: `first_guard` for the first, folded per io-block inner
8175/// step) and tokens consumed.
8176fn parse_element_at(
8177    toks: &[Tok],
8178    pos: usize,
8179    stmt: usize,
8180    ctx: &ParseCtx,
8181    first_guard: Option<GuardExpr>,
8182    in_block: bool,
8183) -> Result<(Vec<Step>, usize), TokenError> {
8184    let step = |kind: StepKind| Step {
8185        guard: first_guard.clone(),
8186        kind,
8187        scope_enter: 0,
8188        scope_exit: 0,
8189        line: 0,
8190        col: 0,
8191    };
8192    let head_word = match toks.get(pos).map(|t| &t.kind) {
8193        Some(TokKind::Word(w)) => Some(w.clone()),
8194        _ => None,
8195    };
8196    // Mid-run `{...}` (after a call, wrapper block, ...): the
8197    // grammar strands it (`block_start` needs a pending guard or
8198    // `WITH_IO` wait, both consumed), so fail loudly. Statement-head
8199    // braces route through `lower_stmt_steps`, never here.
8200    if starts_brace(&toks[pos..]) {
8201        return Err(TokenError {
8202            stmt,
8203            msg: "'{' without a pending guard".to_string(),
8204            line: 0,
8205            col: 0,
8206            kind: None,
8207        });
8208    }
8209    // LET/SET/RETURN heads parse with groups intact, then trailing
8210    // elements loop on (probed `LET $x: INT = 1 ECHO bye`). LET shape
8211    // misses fall to generic (lowering fails them like a committed
8212    // `instruction` would, e.g. `LET foo`).
8213    if head_word.as_deref() == Some(KEYWORD_LET)
8214        && let Some((kind, used)) = parse_let_body(&toks[pos..], stmt, ctx)?
8215    {
8216        return Ok((vec![step(kind)], used));
8217    }
8218    if matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('$'))) {
8219        let (kind, used) = parse_set_body(&toks[pos..], stmt, ctx)?;
8220        return Ok((vec![step(kind)], used));
8221    }
8222    if head_word.as_deref() == Some(KEYWORD_RETURN) {
8223        let (kind, used) = parse_return_body(&toks[pos..], stmt, ctx)?;
8224        return Ok((vec![step(kind)], used));
8225    }
8226    // Calls route before heads (even known commands take the call
8227    // path with a joint paren, probed `ECHO("hi")`); the call ends
8228    // mid-run and trailing elements loop on (fixes the slice-4a
8229    // divergence, probed).
8230    if call_shape_at(toks, pos, true).is_some() {
8231        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8232        return Ok((vec![step(kind)], used));
8233    }
8234    // Block statements (shape misses fall to generic, which fails
8235    // them in lowering like the grammar's committed `instruction`).
8236    // `BREAK`/`CONTINUE` take no args (structural, like the grammar):
8237    // each consumes one token and trailing elements loop on (probed
8238    // `BREAK ECHO hi`); a lone trailing word fails downstream like
8239    // the grammar's committed mismatch.
8240    match head_word.as_deref() {
8241        Some(KEYWORD_BREAK) => {
8242            return Ok((vec![step(StepKind::Break)], 1));
8243        }
8244        Some(KEYWORD_CONTINUE) => {
8245            return Ok((vec![step(StepKind::Continue)], 1));
8246        }
8247        Some(KEYWORD_IF) => {
8248            if let Some((kind, used)) = parse_if_at(toks, pos, stmt, ctx)? {
8249                return Ok((vec![step(kind)], used));
8250            }
8251        }
8252        Some(KEYWORD_SWITCH) => {
8253            if let Some((kind, used)) = parse_switch_at(toks, pos, stmt, ctx)? {
8254                return Ok((vec![step(kind)], used));
8255            }
8256        }
8257        Some(KEYWORD_FOR) => {
8258            if let Some((kind, used)) = parse_for_at(toks, pos, stmt, ctx)? {
8259                return Ok((vec![step(kind)], used));
8260            }
8261        }
8262        Some(KEYWORD_WHILE) => {
8263            if let Some((kind, used)) = parse_while_single(toks, pos, stmt, ctx)? {
8264                return Ok((vec![step(kind)], used));
8265            }
8266        }
8267        Some(KEYWORD_FUNC) => {
8268            if let Some((kind, used)) = parse_func_at(toks, pos, stmt, ctx, false)? {
8269                return Ok((vec![step(kind)], used));
8270            }
8271        }
8272        Some(KEYWORD_REMOTE) => {
8273            if let Some((kind, used)) = parse_remote_single(toks, pos, stmt, ctx)? {
8274                return Ok((vec![step(kind)], used));
8275            }
8276        }
8277        _ => {}
8278    }
8279    // Wrappers (block or single); shape misses fall to generic.
8280    match head_word.as_deref() {
8281        Some(KEYWORD_WITH_IO) => {
8282            return parse_with_io_element(toks, pos, stmt, ctx, first_guard);
8283        }
8284        Some(KEYWORD_TIMEOUT) => {
8285            if let Some((kind, used)) = parse_timeout_single(toks, pos, stmt, ctx)? {
8286                return Ok((vec![step(kind)], used));
8287            }
8288        }
8289        Some(KEYWORD_ISOLATED) => {
8290            if let Some((kind, used)) = parse_isolated_single(toks, pos, stmt, ctx)? {
8291                return Ok((vec![step(kind)], used));
8292            }
8293        }
8294        Some(KEYWORD_FAIL) => {
8295            if let Some((kind, used)) = parse_fail_single(toks, pos, stmt, ctx)? {
8296                return Ok((vec![step(kind)], used));
8297            }
8298        }
8299        Some(KEYWORD_ASYNC) => {
8300            // ASYNC FUNC definition form: prefix, parser records is_async
8301            // with no type-constraint validation (checker owns HANDLE rule).
8302            if matches!(toks.get(pos + 1).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC)
8303                && let Some((kind, used)) = parse_func_at(toks, pos + 1, stmt, ctx, true)?
8304            {
8305                return Ok((vec![step(kind)], 1 + used));
8306            }
8307            if let Some((kind, used)) = parse_async_single(toks, pos, stmt, ctx)? {
8308                return Ok((vec![step(kind)], used));
8309            }
8310        }
8311        _ => {}
8312    }
8313    // AWAIT/CANCEL statements (element level admits the `$` gap,
8314    // probed); heads without `$` go generic (lowering fails them).
8315    if matches!(
8316        head_word.as_deref(),
8317        Some(KEYWORD_AWAIT) | Some(KEYWORD_CANCEL)
8318    ) && let Some((kind, used)) = parse_await_cancel_at(toks, pos, stmt, false)?
8319    {
8320        return Ok((vec![step(kind)], used));
8321    }
8322    // `INHERIT_ENV [...]` parses strictly even at element level
8323    // (keys stay exact everywhere; slice 5 adds only the
8324    // prelude-order validation). Shape misses go generic.
8325    if head_word.as_deref() == Some(KEYWORD_INHERIT_ENV)
8326        && let Some((kind, used)) = parse_inherit_env_at(toks, pos, stmt)?
8327    {
8328        return Ok((vec![step(kind)], used));
8329    }
8330    // `EXPORT ...` records names (zero steps) or misses to generic;
8331    // level and guard violations fail loudly like the backend.
8332    if head_word.as_deref() == Some(KEYWORD_EXPORT) {
8333        if in_block {
8334            return Err(TokenError {
8335                stmt,
8336                msg: "EXPORT is only allowed at the top level".to_string(),
8337                line: 0,
8338                col: 0,
8339                kind: None,
8340            });
8341        }
8342        if first_guard.is_some() {
8343            return Err(TokenError {
8344                stmt,
8345                msg: "EXPORT cannot be guarded".to_string(),
8346                line: 0,
8347                col: 0,
8348                kind: None,
8349            });
8350        }
8351        if let Some((
8352            ExportNames {
8353                func_names,
8354                type_names,
8355            },
8356            used,
8357        )) = parse_export_at(toks, pos)
8358        {
8359            for name in &func_names {
8360                for part in name.split(MODULE_SEPARATOR) {
8361                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8362                        .map_err(|e| lower_err(stmt, e))?;
8363                }
8364                if ctx.func_exports.borrow().contains(name)
8365                    || ctx.type_exports.borrow().contains(name)
8366                {
8367                    return Err(TokenError {
8368                        stmt,
8369                        msg: format!("duplicate EXPORT `{name}`"),
8370                        line: 0,
8371                        col: 0,
8372                        kind: Some(ParseErrorKind::Validation {
8373                            command: KEYWORD_EXPORT.to_string(),
8374                        }),
8375                    });
8376                }
8377                ctx.func_exports.borrow_mut().push(name.clone());
8378            }
8379            for name in &type_names {
8380                for part in name.split(MODULE_SEPARATOR) {
8381                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8382                        .map_err(|e| lower_err(stmt, e))?;
8383                }
8384                if ctx.func_exports.borrow().contains(name)
8385                    || ctx.type_exports.borrow().contains(name)
8386                {
8387                    return Err(TokenError {
8388                        stmt,
8389                        msg: format!("duplicate EXPORT `{name}`"),
8390                        line: 0,
8391                        col: 0,
8392                        kind: Some(ParseErrorKind::Validation {
8393                            command: KEYWORD_EXPORT.to_string(),
8394                        }),
8395                    });
8396                }
8397                ctx.type_exports.borrow_mut().push(name.clone());
8398            }
8399            return Ok((Vec::new(), used));
8400        }
8401    }
8402    // `TYPE NAME = SHAPE` aliases (zero or one step); level and guard
8403    // violations fail loudly, shape misses fall to generic.
8404    if head_word.as_deref() == Some(KEYWORD_TYPE) {
8405        if in_block {
8406            return Err(TokenError {
8407                stmt,
8408                msg: "TYPE must appear at top level".to_string(),
8409                line: 0,
8410                col: 0,
8411                kind: None,
8412            });
8413        }
8414        if first_guard.is_some() {
8415            return Err(TokenError {
8416                stmt,
8417                msg: "TYPE cannot be guarded".to_string(),
8418                line: 0,
8419                col: 0,
8420                kind: None,
8421            });
8422        }
8423        if let Some((kind, used)) = parse_type_stmt_at(toks, pos, stmt)? {
8424            return Ok((vec![step(kind)], used));
8425        }
8426    }
8427    // Lowercase heads name their uppercase form (the grammar's
8428    // `command_name` mismatch): never a bare unknown-command.
8429    if let Some(head) = head_word.as_deref()
8430        && head.chars().all(|c| c.is_ascii_lowercase())
8431        && let upper = head.to_ascii_uppercase()
8432        && (is_known_command(&upper) || crate::STRUCTURAL_KEYWORDS.contains(&upper.as_str()))
8433    {
8434        return Err(TokenError {
8435            stmt,
8436            msg: format!("command must be uppercase: found `{head}`, expected `{upper}`"),
8437            line: 0,
8438            col: 0,
8439            kind: Some(ParseErrorKind::Syntax),
8440        });
8441    }
8442    // RUN-exec ends mid-run (trailing loops on, probed); generic
8443    // instructions consume everything.
8444    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8445    Ok((vec![step(kind)], used))
8446}
8447
8448/// Element-level `WITH_IO`: a same-run brace (any gap: `]{` works,
8449/// probed) opens the io-block form, wrapping every inner step with
8450/// scope markers; a joint non-brace follower is the pending-guard
8451/// error (the splitter only holds bare brackets); anything else is
8452/// the single form. Shape misses go generic.
8453fn parse_with_io_element(
8454    toks: &[Tok],
8455    pos: usize,
8456    stmt: usize,
8457    ctx: &ParseCtx,
8458    first_guard: Option<GuardExpr>,
8459) -> Result<(Vec<Step>, usize), TokenError> {
8460    // The bracket rides gapped (`sep`); anything else misses the
8461    // shape and generic fails it in lowering.
8462    let bracket = match toks.get(pos + 1) {
8463        Some(t)
8464            if !t.joint
8465                && matches!(
8466                    &t.kind,
8467                    TokKind::Group {
8468                        delim: GroupDelim::Bracket,
8469                        ..
8470                    }
8471                ) =>
8472        {
8473            Some(t)
8474        }
8475        _ => None,
8476    };
8477    let Some(bracket) = bracket else {
8478        // Shape miss: generic fails it in lowering.
8479        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8480        return Ok((
8481            vec![Step {
8482                guard: first_guard,
8483                kind,
8484                scope_enter: 0,
8485                scope_exit: 0,
8486                line: 0,
8487                col: 0,
8488            }],
8489            used,
8490        ));
8491    };
8492    let inner = match &bracket.kind {
8493        TokKind::Group { inner, .. } => inner.clone(),
8494        _ => unreachable!(),
8495    };
8496    let bindings = match parse_io_bindings(&inner, stmt)? {
8497        Some(bindings) => bindings,
8498        // Shape miss: generic fails it.
8499        None => {
8500            let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8501            return Ok((
8502                vec![Step {
8503                    guard: first_guard,
8504                    kind,
8505                    scope_enter: 0,
8506                    scope_exit: 0,
8507                    line: 0,
8508                    col: 0,
8509                }],
8510                used,
8511            ));
8512        }
8513    };
8514    let rest = pos + 2;
8515    // Same-run brace opens the io-block form (block-expanded
8516    // bindings skip the tty checks: the runtime repeats them).
8517    if let Some(next) = toks.get(rest)
8518        && matches!(
8519            &next.kind,
8520            TokKind::Group {
8521                delim: GroupDelim::Brace,
8522                ..
8523            }
8524        )
8525        && !is_template_brace(next)
8526    {
8527        let brace_inner = match &next.kind {
8528            TokKind::Group { inner, .. } => inner.clone(),
8529            _ => unreachable!(),
8530        };
8531        let mut steps = parse_body_steps(&brace_inner, stmt, ctx, false)?;
8532        if steps.is_empty() {
8533            return Err(TokenError {
8534                stmt,
8535                msg: "WITH_IO block must contain at least one command".to_string(),
8536                line: 0,
8537                col: 0,
8538                kind: None,
8539            });
8540        }
8541        // Every inner step wraps (merging when already wrapped,
8542        // like nested io scopes); the line guard folds into each
8543        // inner guard, inner-first (probed fold order).
8544        for s in &mut steps {
8545            let merged = match std::mem::replace(&mut s.kind, StepKind::Continue) {
8546                StepKind::WithIo {
8547                    bindings: inner_bindings,
8548                    cmd,
8549                } => StepKind::WithIo {
8550                    bindings: crate::commands::merge_bindings(&bindings, &inner_bindings),
8551                    cmd,
8552                },
8553                other => StepKind::WithIo {
8554                    bindings: bindings.clone(),
8555                    cmd: Box::new(other),
8556                },
8557            };
8558            s.kind = merged;
8559            s.guard = crate::commands::and_guard_exprs(s.guard.take(), first_guard.clone());
8560        }
8561        let span = lowering_ctx(stmt);
8562        for s in &steps {
8563            crate::commands::reject_nested_inherit_env(&span, &s.kind).map_err(|e| TokenError {
8564                stmt,
8565                msg: e.to_string(),
8566                line: 0,
8567                col: 0,
8568                kind: None,
8569            })?;
8570        }
8571        if let Some(first) = steps.first_mut() {
8572            first.scope_enter += 1;
8573        }
8574        if let Some(last) = steps.last_mut() {
8575            last.scope_exit += 1;
8576        }
8577        return Ok((steps, rest + 1 - pos));
8578    }
8579    if rest >= toks.len() {
8580        // Unreachable: the splitter holds bare brackets for `{`.
8581        // Kept for body-parsed runs, mirroring the transient node.
8582        return Ok((
8583            vec![Step {
8584                guard: first_guard,
8585                kind: StepKind::WithIoBlock { bindings },
8586                scope_enter: 0,
8587                scope_exit: 0,
8588                line: 0,
8589                col: 0,
8590            }],
8591            2,
8592        ));
8593    }
8594    // A joint follower misses the inner `sep`: the pending wait
8595    // fails exactly like the grammar.
8596    if toks[rest].joint {
8597        return Err(TokenError {
8598            stmt,
8599            msg: "WITH_IO block must be followed by '{'".to_string(),
8600            line: 0,
8601            col: 0,
8602            kind: None,
8603        });
8604    }
8605    // Single form, shared with single-inner (element guards the step).
8606    let (cmd, used) = parse_single_inner(
8607        toks,
8608        rest,
8609        stmt,
8610        ctx,
8611        InnerRules {
8612            allow_await: false,
8613            allow_with_io: true,
8614        },
8615    )?;
8616    let span = lowering_ctx(stmt);
8617    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| TokenError {
8618        stmt,
8619        msg: e.to_string(),
8620        line: 0,
8621        col: 0,
8622        kind: None,
8623    })?;
8624    let kind = StepKind::WithIo {
8625        bindings,
8626        cmd: Box::new(cmd),
8627    };
8628    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
8629        stmt,
8630        msg: e.to_string(),
8631        line: 0,
8632        col: 0,
8633        kind: None,
8634    })?;
8635    Ok((
8636        vec![Step {
8637            guard: first_guard,
8638            kind,
8639            scope_enter: 0,
8640            scope_exit: 0,
8641            line: 0,
8642            col: 0,
8643        }],
8644        2 + used,
8645    ))
8646}
8647
8648/// Shared inner-command parser: statement calls (joint paren, even on
8649/// known commands), RUN exec
8650/// form, and generic instructions. Returns the kind and tokens
8651/// consumed: calls and RUN-exec end mid-run (the caller continues
8652/// past them, like the grammar's `element*`); generic instructions
8653/// consume everything. Wrappers never route here (element and
8654/// single-inner dispatch own them); slice 4b reuses the call/RUN
8655/// arms for trailing elements.
8656fn parse_inner_command(
8657    body: &[Tok],
8658    stmt: usize,
8659    ctx: &ParseCtx,
8660) -> Result<(StepKind, usize), TokenError> {
8661    // Bare `NAME(...)` calls invoke functions with one syntax; the head
8662    // and `(` ride gapless or the shape stays an instruction (which
8663    // fails later as UnknownCommand), exactly like the grammar.
8664    if let Some((call_name, paren)) = call_shape_at(body, 0, true) {
8665        let inner = match &body[paren].kind {
8666            TokKind::Group { inner, .. } => inner.clone(),
8667            _ => unreachable!(),
8668        };
8669        let args = parse_call_args(&inner, stmt, ctx)?;
8670        // Statement-level `INSPECT(...)` resolves like any other call
8671        // (only expression position mints the node); unknown functions
8672        // fail in the shared resolver with identical messages.
8673        if !call_name.contains(MODULE_SEPARATOR) {
8674            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
8675                .map_err(|e| lower_err(stmt, e))?;
8676        }
8677        let qualified = resolve_name(ctx, stmt, &call_name)?;
8678        return Ok((
8679            StepKind::Call {
8680                name: qualified,
8681                args,
8682            },
8683            paren + 1,
8684        ));
8685    }
8686    let head = match body.first().map(|t| &t.kind) {
8687        Some(TokKind::Word(n)) => n.clone(),
8688        _ => {
8689            return Err(TokenError {
8690                stmt,
8691                msg: "statement must open with a command word".to_string(),
8692                line: 0,
8693                col: 0,
8694                kind: None,
8695            });
8696        }
8697    };
8698    // RUN exec form: the list routes structured through `lower` (the
8699    // mock wraps it in `Run`; production maps it to `RunExec`); the
8700    // caller continues past the list, like the grammar. The list
8701    // rides gapped (`sep`): a joint bracket is a hard error, never
8702    // a spliced arg (probed `RUN["a"]`).
8703    if head == KEYWORD_RUN
8704        && matches!(
8705            body.get(1).map(|t| &t.kind),
8706            Some(TokKind::Group {
8707                delim: GroupDelim::Bracket,
8708                ..
8709            })
8710        )
8711    {
8712        if body[1].joint {
8713            return Err(TokenError {
8714                stmt,
8715                msg: "RUN [...] requires a gap after RUN".to_string(),
8716                line: 0,
8717                col: 0,
8718                kind: None,
8719            });
8720        }
8721        let inner = match &body[1].kind {
8722            TokKind::Group { inner, .. } => inner.clone(),
8723            _ => unreachable!(),
8724        };
8725        // Non-map blocks miss the exec shape (the grammar has no
8726        // `block` alternative here); fall through to the shell path
8727        // below, which reads the bracket literally.
8728        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
8729            let kind =
8730                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
8731            return Ok((kind, 2));
8732        }
8733    }
8734    let (tokens, deferred) = build_arg_tokens(&body[1..], stmt, ctx)?;
8735    let lowered = lower_generic_args(&head, tokens, stmt, ctx);
8736    match lowered {
8737        Ok(kind) => {
8738            // Stashed call errors surface only for otherwise well-formed
8739            // statements: the command head owns its syntax, so a malformed
8740            // header keeps its tailored error instead of being masked by an
8741            // argument-position resolution failure.
8742            if let Some(err) = deferred {
8743                return Err(err);
8744            }
8745            Ok((kind, body.len()))
8746        }
8747        Err(lower_err) => {
8748            // Fallback raw strings (`NOPE()` rendered as text) can fail
8749            // argument-shape lowering with a misleading error. The
8750            // stashed unknown-callee error names the real culprit, so
8751            // it wins over every argument-level failure (`Validation`,
8752            // `Syntax`, `InvalidSyntax`, or the `None` classification
8753            // that `ENV`/`EXPAND` lowering uses). Heads owned by a
8754            // statement-header parser (`FUNC`, `LET`, `IF`, `FOR`,
8755            // `WHILE`, `TYPE`, `IMPORT`, `EXPORT`, `REMOTE`, `WITH_IO`)
8756            // keep their lowering `InvalidSyntax`: those parsers miss to
8757            // this path on shape miss (e.g. `FUNC FOO() ECHO hi` has no
8758            // body block), so the lowering error names the malformed
8759            // header while the stashed name is its definiendum, never an
8760            // argument-position call. Every other head is a plain
8761            // command, so a lowering `InvalidSyntax` there is an
8762            // argument-shape failure from the raw-text fallback, and
8763            // the stashed callee names the culprit. Only
8764            // head-identity errors (`UnknownCommand`, `Structural`)
8765            // keep their tailored diagnostic everywhere.
8766            let is_header_syntax = matches!(
8767                head.as_str(),
8768                KEYWORD_FUNC
8769                    | KEYWORD_LET
8770                    | KEYWORD_IF
8771                    | KEYWORD_SWITCH
8772                    | KEYWORD_FOR
8773                    | KEYWORD_WHILE
8774                    | KEYWORD_TYPE
8775                    | KEYWORD_IMPORT
8776                    | KEYWORD_EXPORT
8777                    | KEYWORD_REMOTE
8778                    | KEYWORD_WITH_IO
8779            ) && matches!(
8780                lower_err.kind,
8781                Some(crate::error::ParseErrorKind::InvalidSyntax { .. })
8782            );
8783            if let Some(deferred_err) = deferred
8784                && !is_header_syntax
8785                && matches!(
8786                    lower_err.kind,
8787                    Some(crate::error::ParseErrorKind::Validation { .. })
8788                        | Some(crate::error::ParseErrorKind::Syntax)
8789                        | Some(crate::error::ParseErrorKind::InvalidSyntax { .. })
8790                        | None
8791                )
8792            {
8793                return Err(deferred_err);
8794            }
8795            Err(lower_err)
8796        }
8797    }
8798}
8799
8800/// Parse a token stream (either lexer) into steps. Markers normalize to
8801/// 0/0 like the fuzz harness; scopes arrive with block slices.
8802pub fn parse_tokens(
8803    toks: &[Tok],
8804    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8805) -> Result<Vec<Step>, TokenError> {
8806    let modules = ModuleTable::default();
8807    let reserved = HashSet::new();
8808    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
8809    parse_tokens_with_ctx(toks, &ctx)
8810}
8811
8812/// Parse with an explicit context (module table for call resolution).
8813/// `parse_tokens` uses empty modules.
8814pub fn parse_tokens_with_ctx(toks: &[Tok], ctx: &ParseCtx) -> Result<Vec<Step>, TokenError> {
8815    let mut out = Vec::new();
8816    *ctx.current_line.borrow_mut() = 1;
8817    let stmts = split_statements(toks, 1)?;
8818    predeclare_forward_funcs(&stmts, ctx);
8819    for (i, s) in stmts.iter().enumerate() {
8820        *ctx.current_line.borrow_mut() = s.line;
8821        out.extend(
8822            lower_stmt_steps(s, i, ctx, false, true).map_err(|e| stamp_pos(e, s.line, s.col))?,
8823        );
8824    }
8825    // Whole-script validations through the shared validators.
8826    // `INHERIT_ENV` prelude order: only leading positions read.
8827    {
8828        let mut seen_non_prelude = false;
8829        for step in &out {
8830            match &step.kind {
8831                StepKind::InheritEnv { .. } => {
8832                    if seen_non_prelude {
8833                        return Err(TokenError {
8834                            stmt: out.len(),
8835                            msg: "INHERIT_ENV must appear before any other commands".to_string(),
8836                            line: 0,
8837                            col: 0,
8838                            kind: None,
8839                        });
8840                    }
8841                }
8842                kind => {
8843                    if crate::commands::contains_inherit_env(kind) {
8844                        return Err(TokenError {
8845                            stmt: out.len(),
8846                            msg: "INHERIT_ENV cannot be nested inside other commands".to_string(),
8847                            line: 0,
8848                            col: 0,
8849                            kind: None,
8850                        });
8851                    }
8852                    // Harvest imports stay prelude: they bind functions
8853                    // and types without executing module bodies, so they
8854                    // neither read nor disturb the inherited environment.
8855                    // File imports execute arbitrary top-level steps on
8856                    // import, so they end the prelude like any other
8857                    // side-effecting command. Host-only IMPORTs emit no
8858                    // step at all, which is why they never tripped this
8859                    // gate.
8860                    if !matches!(kind, StepKind::ImportFuncs { .. }) {
8861                        seen_non_prelude = true;
8862                    }
8863                }
8864            }
8865        }
8866    }
8867    crate::commands::validate_remote_copy_placement(&out, &lowering_ctx(out.len())).map_err(
8868        |e| TokenError {
8869            stmt: out.len(),
8870            msg: e.to_string(),
8871            line: 0,
8872            col: 0,
8873            kind: None,
8874        },
8875    )?;
8876    {
8877        let top: HashSet<String> = ctx.funcs.borrow().first().cloned().unwrap_or_default();
8878        let top_imports: Vec<String> = ctx.imports.borrow().first().cloned().unwrap_or_default();
8879        let mut top_types = HashSet::new();
8880        for step in &out {
8881            if let StepKind::TypeAlias { name, .. } = &step.kind {
8882                top_types.insert(name.clone());
8883            }
8884        }
8885        crate::commands::validate_exports(
8886            &lowering_ctx(out.len()),
8887            &ctx.func_exports.borrow(),
8888            &ctx.type_exports.borrow(),
8889            &top,
8890            &top_types,
8891            ctx.modules,
8892            &top_imports,
8893        )
8894        .map_err(|e| TokenError {
8895            stmt: out.len(),
8896            msg: e.to_string(),
8897            line: 0,
8898            col: 0,
8899            kind: None,
8900        })?;
8901    }
8902    Ok(out)
8903}
8904
8905// ---- String entry points: lex, lower, collect exports and docs ----
8906
8907/// Source text of a 1-based line. The line just past a trailing
8908/// newline (where unbalanced groups report) reads as empty text so
8909/// caret blocks still render.
8910fn source_line_of(input: &str, line: usize) -> Option<String> {
8911    let count = input.lines().count();
8912    let idx = line.checked_sub(1)?;
8913    if idx < count {
8914        input.lines().nth(idx).map(str::to_string)
8915    } else if idx == count {
8916        Some(String::new())
8917    } else {
8918        None
8919    }
8920}
8921
8922/// Last script line (end-of-script validations blame it).
8923fn last_line(input: &str) -> usize {
8924    input.lines().count().max(1)
8925}
8926
8927/// Convert a lexer failure: low-level syntax kind, exact lexer
8928/// position, and the source line for the caret block. Unclosed groups
8929/// name their opener (no grammar dumps); the closer expectation rides
8930/// along so `expected()` stays informative. A lexer-known kind (an
8931/// unclosed `WITH_IO` bracket) converts verbatim.
8932fn lex_error(input: &str, e: LexError) -> ParseError {
8933    let line = e.line.max(1);
8934    let ctx = match source_line_of(input, line) {
8935        Some(source_line) => SpanContext::full(line, e.col.max(1), e.col.max(1), source_line),
8936        None => SpanContext::line_only(line),
8937    };
8938    if let Some(ParseErrorKind::InvalidSyntax { command }) = e.kind {
8939        // Lexer-known command syntax (an unclosed `WITH_IO` bracket).
8940        return ParseError::invalid_syntax(
8941            &command,
8942            e.msg,
8943            None,
8944            vec!["`]`".to_string()],
8945            None,
8946            &ctx,
8947        );
8948    }
8949    let expected = if e.msg.starts_with("unclosed") {
8950        vec!["`}`".to_string()]
8951    } else {
8952        Vec::new()
8953    };
8954    ParseError::syntax(e.msg, expected, None, &ctx)
8955}
8956
8957/// Convert a backend failure, preserving the dispatcher's error kind
8958/// and completing line/source context the token stream knows. Spans
8959/// open at the statement's start column and cover its whole first line
8960/// (multi-line spans clamp to the start line), so caret blocks render
8961/// for every string-path error.
8962fn token_error(input: &str, e: TokenError) -> ParseError {
8963    let line = if e.line == 0 {
8964        last_line(input)
8965    } else {
8966        e.line
8967    };
8968    let start_col = e.col.max(1);
8969    let ctx = match source_line_of(input, line) {
8970        Some(source_line) => {
8971            let end = source_line.len().max(start_col);
8972            SpanContext::full(line, start_col, end, source_line)
8973        }
8974        None => SpanContext::line_only(line),
8975    };
8976    // Column spans are statement granularity (every error names its
8977    // statement's first column); the caret block still renders.
8978    match e.kind {
8979        Some(crate::error::ParseErrorKind::UnknownCommand { name }) => {
8980            ParseError::unknown_command(&name, e.msg, None, &ctx)
8981        }
8982        Some(crate::error::ParseErrorKind::InvalidSyntax { command }) => {
8983            ParseError::invalid_syntax(&command, e.msg, None, Vec::new(), None, &ctx)
8984        }
8985        Some(crate::error::ParseErrorKind::Validation { command }) => {
8986            ParseError::validation(&command, e.msg, &ctx)
8987        }
8988        Some(crate::error::ParseErrorKind::Syntax) => {
8989            ParseError::syntax(e.msg, Vec::new(), None, &ctx)
8990        }
8991        Some(crate::error::ParseErrorKind::Structural { rule }) => {
8992            ParseError::structural(&rule, e.msg, &ctx)
8993        }
8994        None => ParseError::structural("statement", e.msg, &ctx),
8995    }
8996}
8997
8998/// Shared parse driver: lex, lower with preseeded frames, and collect
8999/// `EXPORT` names (validated at end of parse, forward references
9000/// allowed).
9001fn parse_with_ctx(
9002    input: &str,
9003    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9004    reserved_names: HashSet<String>,
9005    modules: ModuleTable,
9006    preseed_funcs: HashSet<String>,
9007    preseed_imports: Vec<String>,
9008) -> ParseResult<ScriptWithExports> {
9009    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
9010    let ctx = ParseCtx::empty(&lower, &modules, &reserved_names);
9011    // Snippet re-parses seed their base frames so lookup behaves
9012    // identically; snippets never define, only read.
9013    ctx.funcs.borrow_mut()[0].extend(preseed_funcs);
9014    ctx.imports.borrow_mut()[0].extend(preseed_imports);
9015    let steps = parse_tokens_with_ctx(&toks, &ctx).map_err(|e| token_error(input, e))?;
9016    let mut steps = steps;
9017    stamp_func_docs(input, &mut steps);
9018    Ok(ScriptWithExports {
9019        steps,
9020        func_exports: ctx.func_exports.borrow().clone(),
9021        type_exports: ctx.type_exports.borrow().clone(),
9022    })
9023}
9024
9025/// Steps plus single-file `EXPORT` metadata, before `#` doc stamping.
9026/// Callers needing docs build a [`ParsedScript`] from this.
9027struct ScriptWithExports {
9028    steps: Vec<Step>,
9029    func_exports: Vec<String>,
9030    type_exports: Vec<String>,
9031}
9032
9033/// Parse a script with an unknown host environment.
9034pub fn parse_script(
9035    input: &str,
9036    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9037) -> ParseResult<Vec<Step>> {
9038    Ok(parse_with_ctx(
9039        input,
9040        lower,
9041        HashSet::new(),
9042        ModuleTable::default(),
9043        HashSet::new(),
9044        Vec::new(),
9045    )?
9046    .steps)
9047}
9048
9049/// Parse a snippet with an enclosing parse's visible scope state, so
9050/// re-parsed inner commands (async bodies) resolve calls identically.
9051/// The snippet never defines, only reads: seeds affect lookup alone.
9052pub fn parse_script_with_preseed(
9053    input: &str,
9054    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9055    reserved_names: HashSet<String>,
9056    modules: ModuleTable,
9057    preseed_funcs: HashSet<String>,
9058    preseed_imports: Vec<String>,
9059) -> ParseResult<Vec<Step>> {
9060    Ok(parse_with_ctx(
9061        input,
9062        lower,
9063        reserved_names,
9064        modules,
9065        preseed_funcs,
9066        preseed_imports,
9067    )?
9068    .steps)
9069}
9070
9071/// Parse with a module provenance table so calls resolve statically:
9072/// qualified `MODULE::NAME` checks membership, bare `NAME` resolves through
9073/// `SCRIPT` definitions and `IMPORT`ed modules, and anything else fails at
9074/// parse time instead of at runtime.
9075pub fn parse_script_with_modules(
9076    input: &str,
9077    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9078    reserved_names: HashSet<String>,
9079    modules: ModuleTable,
9080) -> ParseResult<Vec<Step>> {
9081    Ok(parse_script_with_modules_and_exports(input, lower, reserved_names, modules)?.steps)
9082}
9083
9084/// Parse with modules plus single-file `EXPORT` metadata and `#` doc
9085/// comments for top-level `FUNC`s. Used by the MCP host; the linear
9086/// runner keeps using `parse_script_with_modules` and ignores exports.
9087pub fn parse_script_with_modules_and_exports(
9088    input: &str,
9089    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9090    reserved_names: HashSet<String>,
9091    modules: ModuleTable,
9092) -> ParseResult<ParsedScript> {
9093    let ScriptWithExports {
9094        steps,
9095        func_exports,
9096        type_exports,
9097    } = parse_with_ctx(
9098        input,
9099        lower,
9100        reserved_names,
9101        modules,
9102        HashSet::new(),
9103        Vec::new(),
9104    )?;
9105    Ok(ParsedScript {
9106        func_docs: collect_func_docs(input, &steps),
9107        steps,
9108        func_exports,
9109        type_exports,
9110    })
9111}
9112
9113/// Parse without modules plus `EXPORT` metadata. Used by tests and
9114/// tooling that lower with the shared mock.
9115pub fn parse_script_with_exports(
9116    input: &str,
9117    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9118) -> ParseResult<ParsedScript> {
9119    let ScriptWithExports {
9120        steps,
9121        func_exports,
9122        type_exports,
9123    } = parse_with_ctx(
9124        input,
9125        lower,
9126        HashSet::new(),
9127        ModuleTable::default(),
9128        HashSet::new(),
9129        Vec::new(),
9130    )?;
9131    Ok(ParsedScript {
9132        func_docs: collect_func_docs(input, &steps),
9133        steps,
9134        func_exports,
9135        type_exports,
9136    })
9137}
9138
9139/// Parse one expression from source text with an empty module scope, for
9140/// tooling that shows lowering without running (docs demos, explain output).
9141/// No imports exist here, so bare function calls fail and qualified calls
9142/// fail against the empty table; only `INSPECT` passes through untouched.
9143/// Arithmetic, comparison, variables, env reads, keypaths, and literals
9144/// lower normally, with literal only subtrees folded before flattening.
9145pub fn parse_expression_str(input: &str) -> ParseResult<Expr> {
9146    // Trailing whitespace lexes unconsumed, so lex the trimmed text:
9147    // otherwise padded but valid input fails the full consumption check.
9148    let trimmed = input.trim();
9149    let toks = lex_str(trimmed).map_err(|e| lex_error(trimmed, e))?;
9150    let modules = ModuleTable::default();
9151    let reserved = HashSet::new();
9152    let lower = crate::commands::lower_command as fn(&str, Vec<Arg>) -> ParseResult<StepKind>;
9153    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
9154    *ctx.current_line.borrow_mut() = 1;
9155    parse_single_expr(&toks, 0, &ctx).map_err(|e| token_error(trimmed, e))
9156}
9157
9158/// Parse one guard expression from source text (a bare `guard_seq`:
9159/// predicates, `not`/`any`/`all`, comma lists), for tooling and tests.
9160pub fn parse_guard_expr_str(input: &str) -> ParseResult<GuardExpr> {
9161    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
9162    parse_single_guard(&toks, 0).map_err(|e| token_error(input, e))
9163}
9164
9165/// Parsed script with single-file `EXPORT` metadata. `steps` is the
9166/// linear execution plan, `func_exports` the `EXPORT` func names in
9167/// source order, `type_exports` the `EXPORT TYPE` names in source order,
9168/// and `func_docs` maps top-level `FUNC` base names to (summary, docs)
9169/// collected from the immediately preceding `#` comment block.
9170#[derive(Debug, Clone, Default)]
9171pub struct ParsedScript {
9172    pub steps: Vec<Step>,
9173    pub func_exports: Vec<String>,
9174    pub type_exports: Vec<String>,
9175    pub func_docs: std::collections::HashMap<String, (String, String)>,
9176}
9177
9178fn collect_func_docs(
9179    input: &str,
9180    steps: &[Step],
9181) -> std::collections::HashMap<String, (String, String)> {
9182    use std::collections::{HashMap, HashSet};
9183    let lines: Vec<&str> = input.lines().collect();
9184    // Top-level FUNC definition lines keyed by base name. Brace depth
9185    // tracks nesting so only depth-0 `FUNC` lines count; the first
9186    // occurrence wins because same-scope duplicates fail at lowering.
9187    let mut def_lines: HashMap<String, usize> = HashMap::new();
9188    let mut seen: HashSet<String> = HashSet::new();
9189    let mut depth: usize = 0;
9190    for (idx, line) in lines.iter().enumerate() {
9191        let trimmed = line.trim_start();
9192        let is_comment = trimmed.starts_with('#');
9193        let is_guard_only = trimmed.starts_with('[');
9194        if !is_comment
9195            && !is_guard_only
9196            && let Some(rest) = strip_func_head(trimmed)
9197            && depth == 0
9198            && !seen.contains(&rest)
9199        {
9200            seen.insert(rest.clone());
9201            def_lines.insert(rest, idx + 1);
9202        }
9203        if !is_comment {
9204            for ch in line.chars() {
9205                if ch == '{' {
9206                    depth = depth.saturating_add(1);
9207                } else if ch == '}' {
9208                    depth = depth.saturating_sub(1);
9209                }
9210            }
9211        }
9212    }
9213    let mut out: HashMap<String, (String, String)> = HashMap::new();
9214    for step in steps {
9215        if let StepKind::FuncDef { name, .. } = &step.kind
9216            && !out.contains_key(name)
9217            && let Some(&line_no) = def_lines.get(name)
9218            && let Some((summary, docs)) = docs_above(&lines, line_no)
9219        {
9220            out.insert(name.clone(), (summary, docs));
9221        }
9222    }
9223    out
9224}
9225
9226/// Stamp `#` doc blocks onto top-level `FUNC` steps, from the same map
9227/// that feeds `func_docs`, so step-carried docs and the sidecar can
9228/// never disagree. Only top-level definitions qualify (same rule as
9229/// collection); nested shadowing keeps `docs: None`.
9230fn stamp_func_docs(input: &str, steps: &mut [Step]) {
9231    let docs = collect_func_docs(input, steps);
9232    for step in steps {
9233        if let StepKind::FuncDef {
9234            name, docs: slot, ..
9235        } = &mut step.kind
9236            && slot.is_none()
9237            && let Some(pair) = docs.get(name)
9238        {
9239            *slot = Some(pair.clone());
9240        }
9241    }
9242}
9243
9244fn strip_func_head(trimmed: &str) -> Option<String> {
9245    let rest = trimmed.strip_prefix(KEYWORD_FUNC)?;
9246    let after = rest.strip_prefix([' ', '\t'])?;
9247    if after.is_empty() {
9248        return None;
9249    }
9250    let name: String = after
9251        .chars()
9252        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
9253        .collect();
9254    if name.is_empty()
9255        || !name
9256            .bytes()
9257            .all(|b| b.is_ascii_uppercase() || b == b'_' || b.is_ascii_digit())
9258    {
9259        return None;
9260    }
9261    if name.starts_with(|c: char| c.is_ascii_digit()) {
9262        return None;
9263    }
9264    Some(name)
9265}
9266
9267fn docs_above(lines: &[&str], line_no: usize) -> Option<(String, String)> {
9268    if line_no <= 1 {
9269        return None;
9270    }
9271    let mut block: Vec<String> = Vec::new();
9272    let mut idx = line_no - 1;
9273    while idx > 0 {
9274        idx -= 1;
9275        let trimmed = lines[idx].trim_start();
9276        if trimmed.is_empty() {
9277            break;
9278        }
9279        if let Some(body) = trimmed.strip_prefix('#') {
9280            let text = body.strip_prefix(' ').unwrap_or(body);
9281            block.push(text.to_string());
9282        } else {
9283            break;
9284        }
9285        if idx == 0 {
9286            break;
9287        }
9288    }
9289    if block.is_empty() {
9290        return None;
9291    }
9292    block.reverse();
9293    let summary = block.first().cloned().unwrap_or_default();
9294    let docs = block.join("\n");
9295    Some((summary, docs))
9296}
9297
9298#[cfg(test)]
9299mod tests {
9300    use super::*;
9301    use crate::test_lower_mock;
9302    use indoc::indoc;
9303
9304    fn lower(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9305        test_lower_mock::lower(name, args)
9306    }
9307
9308    /// Lexer-agreement oracle: both frontends must deliver identical
9309    /// steps through the single backend. `parse_script` is the string
9310    /// entry point; `parse_tokens` runs each lexer's output directly.
9311    fn assert_parity(text: &str) {
9312        let old = crate::parse_script(text, lower)
9313            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9314        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9315        let new = parse_tokens(&toks, lower)
9316            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9317        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9318        #[cfg(feature = "proc-macro-api")]
9319        {
9320            let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
9321            let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
9322            let new = parse_tokens(&toks, lower).expect("token path must parse token script");
9323            assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
9324        }
9325    }
9326
9327    /// String-path-only oracle for shapes `rustc` cannot carry at all
9328    /// (lifetime-like quotes). The backend must still agree there.
9329    fn assert_parity_string_only(text: &str) {
9330        let old = crate::parse_script(text, lower)
9331            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9332        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9333        let new = parse_tokens(&toks, lower)
9334            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9335        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9336    }
9337
9338    #[test]
9339    fn token_and_string_paths_agree_on_wrappers() {
9340        // Single-command wrappers, io-blocks, await/cancel,
9341        // LET wrapper forms — three-way agreement per script.
9342        for text in [
9343            "WITH_IO [stdout=$p] ECHO hi",
9344            "WITH_IO [stdin=$p] ECHO hi",
9345            "WITH_IO [stdin] ECHO hi",
9346            "WITH_IO [stdout] ECHO hi",
9347            "WITH_IO [stdin=$p, stdout=$q] ECHO hi",
9348            "WITH_IO [stdin=$p, stdin=$q] ECHO hi",
9349            "WITH_IO [tty] RUN echo hi",
9350            "WITH_IO [tty, rows=40, cols=100] RUN echo hi",
9351            "WITH_IO [rows=40, cols=100, tty] RUN echo hi",
9352            "WITH_IO [stdin =$p] ECHO hi",
9353            "WITH_IO [stdin= $p] ECHO hi",
9354            "WITH_IO [ stdin=$p ] ECHO hi",
9355            "WITH_IO [\nstdin=$p\n] ECHO hi",
9356            "WITH_IO [stdin=$p\n, stdout=$q] ECHO hi",
9357            "WITH_IO [stdout=$p] ASYNC ECHO hi",
9358            "WITH_IO [stdin=$p] WITH_IO [stderr=$e] ECHO hi",
9359            "WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
9360            "WITH_IO [stdin=$p] ISOLATED ECHO hi",
9361            "WITH_IO [stdin=$p] CANCEL $t",
9362            "WITH_IO [stdin=$p] CANCEL $t ECHO bye",
9363            "WITH_IO [stdin=$p] { ECHO hi }",
9364            "WITH_IO [stdin=$p]\n{ ECHO hi }",
9365            "WITH_IO [stdin=$p]; { ECHO hi }",
9366            "WITH_IO [stdin=$p]{ ECHO hi }",
9367            "WITH_IO [stdin=$p] { ECHO a\nECHO b }",
9368            "WITH_IO [stdin=$p] { ECHO hi } ECHO bye",
9369            "WITH_IO [rows=40] { ECHO hi }",
9370            "WITH_IO [tty] { ECHO hi }",
9371            "WITH_IO [stdin=$p] { WITH_IO [stderr=$e] ECHO hi }",
9372            "TIMEOUT 10s ECHO hi",
9373            "TIMEOUT 10 ECHO hi",
9374            "TIMEOUT 500ms ECHO hi",
9375            "TIMEOUT 5m ECHO hi",
9376            "TIMEOUT 2h ECHO hi",
9377            "TIMEOUT $d ECHO hi",
9378            "TIMEOUT \"10s\" ECHO hi",
9379            "TIMEOUT \"30 s\" ECHO hi",
9380            "TIMEOUT {{ $d }} ECHO hi",
9381            "TIMEOUT 10s AWAIT $t",
9382            "TIMEOUT 10s CANCEL $t",
9383            "TIMEOUT 10s AWAIT $t ECHO bye",
9384            "TIMEOUT 10s CANCEL $t ECHO bye",
9385            "TIMEOUT 10s { ECHO hi }",
9386            "TIMEOUT 10s {\nECHO hi\n}",
9387            "TIMEOUT 10s { ECHO hi } ECHO bye",
9388            "TIMEOUT 10s { ECHO hi } TIMEOUT 5s ECHO bye",
9389            "TIMEOUT 10s TIMEOUT 5s ECHO hi",
9390            "TIMEOUT 10s { ECHO a\nECHO b }",
9391            "TIMEOUT 10s ECHO hi extra",
9392            "ISOLATED ECHO hi",
9393            "ISOLATED { ECHO hi }",
9394            "ISOLATED { ECHO hi } ECHO bye",
9395            "ISOLATED AWAIT $t",
9396            "ISOLATED INHERIT_ENV [M]",
9397            "ISOLATED { INHERIT_ENV [M] }",
9398            "ISOLATED { INHERIT_ENV [MODE]\nECHO hi }",
9399            "ASYNC ECHO hi",
9400            "ASYNC { ECHO hi }",
9401            "ASYNC{ECHO hi}",
9402            "ASYNC { ECHO a\nECHO b }",
9403            "ASYNC { ECHO hi } ECHO bye",
9404            "ASYNC CANCEL $t",
9405            "ASYNC CANCEL $t ECHO bye",
9406            "AWAIT $t",
9407            "AWAIT$t",
9408            "AWAIT $ t",
9409            "AWAIT $T",
9410            "AWAIT $t2",
9411            "AWAIT $_t",
9412            "CANCEL $t",
9413            "CANCEL$t",
9414            "CANCEL $ t",
9415            "AWAIT $t ECHO bye",
9416            "CANCEL $t ECHO bye",
9417            "AWAIT $t AWAIT $u",
9418            "AWAIT $t\nECHO bye",
9419            "LET $t: HANDLE = ASYNC ECHO hi",
9420            "LET $t: HANDLE = ASYNC { ECHO hi }",
9421            "LET $t: HANDLE = ASYNC { ECHO hi } ECHO bye",
9422            "LET $a: STRING = ASYNC ECHO hi",
9423            "LET $t: HANDLE = ASYNC { WITH_IO [stdin=$p] ECHO hi }",
9424            "LET $w: STRING = WITH_IO [stdin=$p] ASYNC ECHO hi",
9425            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC ECHO hi",
9426            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi }",
9427            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi } ECHO bye",
9428            "LET $x: STRING = WITH_IO [stdin=$p] ECHO hi",
9429            "LET $x: STRING = WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
9430            "LET $x: STRING = TIMEOUT 10s ECHO hi",
9431            "LET $x: STRING = TIMEOUT 10s { ECHO hi }",
9432            "LET $x: STRING = TIMEOUT 10s ECHO hi ECHO bye",
9433            "LET $o: STRING = AWAIT $t",
9434            "LET $p: PIPE ECHO bye",
9435            "TIMEOUT 10s WITH_IO [stdin=$p]",
9436            "TIMEOUT 10s WITH_IO [stdin=$p]ECHO hi",
9437            "ISOLATED INHERIT_ENV [A, B]",
9438            "ISOLATED INHERIT_ENV [A-B]",
9439            "TIMEOUT 10s { [os:linux] ECHO hi }",
9440            "ASYNC { [os:linux] ECHO hi }",
9441            "ISOLATED { [os:linux] ECHO hi }",
9442            "[os:linux] WITH_IO [stdin=$p]\n{ ECHO hi }",
9443            "LET $x: INT = 1 ECHO bye",
9444            "CANCEL $t LET $x: INT = 1",
9445            "CANCEL $t $x = 1",
9446            "CANCEL $t RETURN \"hi\"",
9447            "TIMEOUT 10s { ECHO hi } LET $x: INT = 1",
9448            "RUN [\"a\"] ECHO bye",
9449            "[os:linux] AWAIT $t",
9450            "[os:linux] TIMEOUT 10s { ECHO hi } ECHO bye",
9451            "[os:linux] ASYNC CANCEL $t ECHO bye",
9452            "[os:linux] WITH_IO [stdin=$p] { [os:macos] ECHO hi }",
9453        ] {
9454            assert_parity(text);
9455        }
9456    }
9457
9458    #[test]
9459    fn token_and_string_paths_agree_on_blocks() {
9460        // Slice 5: `IF`/`FOR`/`WHILE`/`FUNC` with inline and
9461        // cross-newline `ELSE` chains, guard blocks (top-level and
9462        // nested quirk), and multi-element trailing — three-way
9463        // agreement per script.
9464        for text in [
9465            "IF true { ECHO hi }",
9466            "IF $x { ECHO hi } ELSE { ECHO bye }",
9467            "IF true { ECHO a } ELSE IF false { ECHO b } ELSE { ECHO c }",
9468            "IF true{ ECHO hi }",
9469            "IF true { ECHO hi } ECHO bye",
9470            "IF true { ECHO hi }\nELSE { ECHO bye }",
9471            "IF true { ECHO hi }\nELSE IF false { ECHO b }\nELSE { ECHO c }",
9472            "IF true { ECHO hi } //c\nELSE { ECHO bye }",
9473            "IF true { ECHO hi } #c\nELSE { ECHO bye }",
9474            "IF true { ECHO hi }//c\nELSE { ECHO bye }",
9475            "IF true { ECHO hi } /*c*/ ELSE { ECHO bye }",
9476            "IF true { ECHO hi } /*c1*/ /*c2*/\nELSE { ECHO bye }",
9477            "IF true { /*c*/ ECHO hi }",
9478            "IF true { [os:linux] ECHO hi }",
9479            "TIMEOUT 10s { IF true { ECHO hi } }",
9480            "TIMEOUT 10s { IF true { ECHO hi }\nELSE { ECHO bye } }",
9481            "FOR $x: INT IN [1] { ECHO hi }",
9482            "FOR $k: STRING, $v: INT IN $m { ECHO hi }",
9483            "FOR $k: INT IN [1] { ECHO hi }",
9484            "FOR $x: INT IN [1]{ ECHO hi }",
9485            "FOR $x: MAP<name: STRING> IN [1] { ECHO hi }",
9486            "FOR $x: INT IN [1] { ECHO hi } ECHO bye",
9487            "WHILE true { ECHO hi }",
9488            "WHILE $x { ECHO hi }",
9489            "WHILE true{ ECHO hi }",
9490            "TIMEOUT 10s WHILE true { ECHO hi }",
9491            "ASYNC WHILE true { ECHO hi }",
9492            "FUNC FOO(): INT { RETURN 1 }",
9493            "FUNC FOO(): INT { RETURN 1 }",
9494            "FUNC FOO($x: INT): INT { RETURN $x }",
9495            "FUNC FOO($x: INT, $y: STRING): INT { RETURN $x }",
9496            "FUNC FOO(): INT { FUNC FOO(): INT { RETURN 1 } }",
9497            "FUNC FOO(): INT { RETURN 1 }\nFUNC BAR(): VOID { FOO() }\nBAR()",
9498            "TYPE PERSON = MAP<name: STRING>",
9499            "TYPE A=B",
9500            "TYPE A = B | C",
9501            "TYPE A = B\nTYPE A = C",
9502            "INHERIT_ENV [A]\nECHO hi",
9503            "[os:linux] INHERIT_ENV [M]",
9504            "INHERIT_ENV [A]\nINHERIT_ENV [B]\nECHO hi",
9505            "ISOLATED INHERIT_ENV [M]",
9506            "ISOLATED { INHERIT_ENV [M] }",
9507            "ISOLATED INHERIT_ENV [A, B]",
9508            "ISOLATED INHERIT_ENV [A-B]",
9509            "REMOTE prod { ECHO hi }",
9510            "REMOTE prod [$v] { ECHO hi }",
9511            "REMOTE prod [$v, env:E] { ECHO hi }",
9512            "REMOTE prod [] { ECHO hi }",
9513            "REMOTE prod[$v] { ECHO hi }",
9514            "REMOTE prod [$v]{ ECHO hi }",
9515            "REMOTE prod{ ECHO hi }",
9516            "REMOTE  prod  { ECHO hi }",
9517            "REMOTE prod [$v, $v] { ECHO hi }",
9518            "REMOTE prod { ECHO hi } ECHO bye",
9519            "TIMEOUT 10s REMOTE prod { ECHO hi }",
9520            "ASYNC REMOTE prod [$v] { ECHO hi }",
9521            "[os:linux] { ECHO hi }",
9522            "[os:linux]\n{ ECHO hi }",
9523            "[os:linux] { [os:macos] ECHO hi }",
9524            "[os:linux] { [os:macos] ECHO hi\nECHO bye }",
9525            "[os:linux] { [os:macos] { ECHO hi } }",
9526            "TIMEOUT 10s { [os:linux] { [os:macos] ECHO hi } }",
9527            "TIMEOUT 10s { [os:linux] [os:windows] { ECHO hi } }",
9528            "TIMEOUT 10s { [os:linux] { ECHO hi } ECHO bye }",
9529            "LET $x: INT = 1 ECHO bye",
9530            KEYWORD_BREAK,
9531            KEYWORD_CONTINUE,
9532            "BREAK ECHO hi",
9533            "FOR $x: INT IN [1] { BREAK }",
9534            "LET $b: STRING = { RETURN \"hi\" }",
9535            "ECHO { RETURN \"hi\" }",
9536            "RUN [{ RETURN \"hi\" }]",
9537            "[not(env:FOO)] WRITE x",
9538            "[\nnot(env:FOO)\n] WRITE x",
9539            "WRITE env.txt \"{{ env:GREETING }}\"",
9540            "CANCEL $t LET $x: INT = 1",
9541            "RUN [\"a\"] ECHO bye",
9542        ] {
9543            assert_parity(text);
9544        }
9545    }
9546
9547    #[test]
9548    fn multi_line_generics_match_single_line_shape() {
9549        // Multi-line `<...>` shapes parse, and canonicalize exactly
9550        // like their single-line spelling.
9551        for (single, multi) in [
9552            (
9553                "TYPE R = MAP<name: STRING, value: INT>",
9554                "TYPE R = MAP<name: STRING,\nvalue: INT>",
9555            ),
9556            (
9557                "TYPE R = MAP<name: STRING, value: LIST<INT>>",
9558                "TYPE R = MAP<name: STRING,\nvalue: LIST<INT>>",
9559            ),
9560            (
9561                "TYPE R = MAP<name: STRING, value: INT>",
9562                "TYPE R = MAP<\nname: STRING,\nvalue: INT\n>",
9563            ),
9564            (
9565                "LET $m: MAP<name: STRING, value: INT> = {}",
9566                "LET $m: MAP<name: STRING,\nvalue: INT> = {}",
9567            ),
9568            (
9569                "FOR $x: LIST<INT> IN [1] { ECHO hi }",
9570                "FOR $x: LIST<\nINT> IN [1] { ECHO hi }",
9571            ),
9572            ("TYPE R = MAP<x: A | B>", "TYPE R = MAP<x: A |\nB>"),
9573        ] {
9574            assert_parity(multi);
9575            let want = crate::parse_script(single, lower)
9576                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
9577            let got = crate::parse_script(multi, lower)
9578                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
9579            assert_eq!(
9580                got, want,
9581                "multi-line must canonicalize like one line: {multi:?}"
9582            );
9583        }
9584    }
9585
9586    #[test]
9587    fn type_field_defaults_parse_to_canonical_targets() {
9588        // Token-level regression: `= literal` tails belong to the
9589        // field (floats lex as three tokens), and the statement
9590        // target canonicalizes exactly like the spelling parser.
9591        for (text, want) in [
9592            ("TYPE F = MAP<retries: INT = 2>", "MAP<retries: INT = 2>"),
9593            ("TYPE F = MAP<retries: INT=-2>", "MAP<retries: INT = -2>"),
9594            (
9595                "TYPE F = MAP<ratio: FLOAT = 2.5>",
9596                "MAP<ratio: FLOAT = 2.5>",
9597            ),
9598            ("TYPE F = MAP<on: BOOL = true>", "MAP<on: BOOL = true>"),
9599            (
9600                "TYPE F = MAP<model: STRING = \"gpt-4\">",
9601                "MAP<model: STRING = \"gpt-4\">",
9602            ),
9603            (
9604                "TYPE F = MAP<k: STRING = \"d\", n: INT = 3>",
9605                "MAP<k: STRING = \"d\", n: INT = 3>",
9606            ),
9607        ] {
9608            assert_parity(text);
9609            let steps = crate::parse_script(text, lower)
9610                .unwrap_or_else(|e| panic!("default spelling must parse {text:?}: {e}"));
9611            let target = steps
9612                .iter()
9613                .find_map(|s| match &s.kind {
9614                    StepKind::TypeAlias { target, .. } => Some(target.clone()),
9615                    _ => None,
9616                })
9617                .expect("TYPE alias step");
9618            assert_eq!(target, want, "canonical target for {text:?}");
9619        }
9620    }
9621
9622    #[test]
9623    fn multi_line_run_exec_matches_single_line_shape() {
9624        // `RUN [...]` rides the shared bracket core, so a wrapped exec
9625        // list parses exactly like its single-line spelling (and agrees
9626        // across lexer frontends).
9627        for (single, multi) in [
9628            ("RUN [\"echo\", \"hi\"]", "RUN [\"echo\",\n\"hi\"]"),
9629            ("RUN [\"echo\", \"hi\"]", "RUN [\n\"echo\",\n\"hi\"\n]"),
9630            (
9631                "LET $o: STRING = RUN [\"echo\", \"hi\"]",
9632                "LET $o: STRING = RUN [\"echo\",\n\"hi\"]",
9633            ),
9634        ] {
9635            assert_parity(multi);
9636            let want = crate::parse_script(single, lower)
9637                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
9638            let got = crate::parse_script(multi, lower)
9639                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
9640            assert_eq!(
9641                got, want,
9642                "multi-line must canonicalize like one line: {multi:?}"
9643            );
9644        }
9645    }
9646
9647    #[test]
9648    fn untyped_let_fails_in_every_rhs_shape() {
9649        // The everything-typed rule: a missing `:` is a hard error
9650        // carrying the explicit-types message, regardless of what
9651        // follows the `=`. Every binding shape is covered, so no
9652        // untyped position can slip back in unnoticed.
9653        for text in [
9654            "LET $x = 1\n",
9655            "LET $x = \"hi\"\n",
9656            "LET $x = $y\n",
9657            "LET $x = [\"a\", \"b\"]\n",
9658            "LET $x = [\"a\",\n\"b\"]\n",
9659            "LET $x = ECHO hi\n",
9660            "LET $x = AWAIT $t\n",
9661            "LET $x = ASYNC ECHO hi\n",
9662            "LET $x = {\nRETURN 1\n}\n",
9663            "LET $x = WITH_IO [stdin=$p] ASYNC ECHO hi\n",
9664        ] {
9665            let err = crate::parse_script(text, lower).expect_err("untyped LET must fail");
9666            assert!(
9667                err.to_string().contains("LET requires explicit types"),
9668                "wrong error for {text:?}: {err}"
9669            );
9670        }
9671        // Typed spellings of the same shapes keep parsing through
9672        // every lexer frontend.
9673        for text in [
9674            "LET $x: INT = 1\n",
9675            "LET $x: STRING = \"hi\"\n",
9676            "LET $x: LIST<STRING> = [\"a\", \"b\"]\n",
9677            "LET $x: LIST<STRING> = [\"a\",\n\"b\"]\n",
9678            "LET $x: STRING = ECHO hi\n",
9679            "LET $x: STRING = AWAIT $t\n",
9680            "LET $x: HANDLE<VOID> = ASYNC ECHO hi\n",
9681            "LET $x: INT = {\nRETURN 1\n}\n",
9682        ] {
9683            assert_parity(text);
9684        }
9685    }
9686
9687    #[test]
9688    fn missing_comma_points_at_the_item() {
9689        // A forgotten comma between items names the missing
9690        // comma and points at the item's line, not the statement
9691        // head. Lists and call arguments share the rule.
9692        let text = indoc! {r#"
9693            LET $x: LIST<STRING> = [
9694            "a"
9695            "b",
9696            "c"
9697            ]
9698        "#};
9699        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
9700        assert!(
9701            err.to_string().contains("missing comma between list items"),
9702            "wrong error: {err}"
9703        );
9704        assert_eq!(err.line(), 3, "caret names the item line: {err}");
9705        // Same shape on one line.
9706        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" \"b\"]\n", lower)
9707            .expect_err("missing comma must fail");
9708        assert!(
9709            err.to_string().contains("missing comma between list items"),
9710            "wrong error: {err}"
9711        );
9712        assert_eq!(err.line(), 1, "single-line points at line 1: {err}");
9713        // Call arguments share the rule.
9714        let err = crate::parse_script("LET $x: STRING = FOO(\"a\" \"b\")\n", lower)
9715            .expect_err("missing comma must fail");
9716        assert!(
9717            err.to_string()
9718                .contains("missing comma between call arguments"),
9719            "wrong error: {err}"
9720        );
9721        // Genuine trailing garbage keeps the old message but still
9722        // points at the garbage instead of the statement head.
9723        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" : \"b\"]\n", lower)
9724            .expect_err("garbage must fail");
9725        assert!(
9726            err.to_string().contains("unexpected text in list"),
9727            "wrong error: {err}"
9728        );
9729        // Maps share the rule: a forgotten comma between entries
9730        // names it at the entry's line instead of misreporting the
9731        // key as an unknown command.
9732        let text = indoc! {r#"
9733            LET $m: MAP<name: STRING> = {
9734            name: "a"
9735            value: "b"
9736            }
9737        "#};
9738        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
9739        assert!(
9740            err.to_string()
9741                .contains("missing comma between map entries"),
9742            "wrong error: {err}"
9743        );
9744        assert_eq!(err.line(), 3, "caret names the entry line: {err}");
9745        let err = crate::parse_script(
9746            "LET $m: MAP<name: STRING> = {name: \"a\" value: \"b\"}\n",
9747            lower,
9748        )
9749        .expect_err("missing comma must fail");
9750        assert!(
9751            err.to_string()
9752                .contains("missing comma between map entries"),
9753            "wrong error: {err}"
9754        );
9755    }
9756
9757    #[test]
9758    fn spaced_comparisons_still_end_the_statement() {
9759        // A spaced `<` is a comparison, never a generic open: the
9760        // newline still ends the statement.
9761        let steps = crate::parse_script("LET $b: BOOL = $a < $b\nECHO hi", lower)
9762            .expect("comparison plus follower must parse");
9763        assert_eq!(steps.len(), 2, "newline ends the comparison statement");
9764    }
9765
9766    #[test]
9767    fn token_and_string_paths_agree_on_flat_commands() {
9768        for text in [
9769            "ECHO hi",
9770            "ECHO hi\nWRITE x out",
9771            "WRITE x",
9772            "ECHO \"quoted\" unquoted",
9773            "ENV COVERAGE=covered",
9774            "ECHO a; ECHO b",
9775            "// comment\nECHO hi",
9776            "ECHO 1.0.0 --flag a/b",
9777            "ECHO $x",
9778            "\n\nECHO hi\n\n",
9779        ] {
9780            assert_parity(text);
9781        }
9782    }
9783
9784    #[cfg(feature = "proc-macro-api")]
9785    #[test]
9786    fn backslash_outside_strings_is_string_only() {
9787        // `rustc` rejects a bare `\`, so unquoted backslash escapes
9788        // cannot cross `TokenStream` (same exclusion class as raw-`"`
9789        // blocks): the string lexer keeps them, the token path fails to
9790        // tokenize before v2 is ever reached.
9791        let toks = crate::tok::lex_str("ECHO a\\nb").expect("string lex keeps escapes");
9792        let old = crate::parse_script("ECHO a\\nb", lower).expect("string path parses it");
9793        assert_eq!(
9794            parse_tokens(&toks, lower).expect("token path parses it"),
9795            old
9796        );
9797        assert!("ECHO a\\nb".parse::<proc_macro2::TokenStream>().is_err());
9798    }
9799
9800    #[test]
9801    fn escaped_backslash_pair_is_atomic() {
9802        // `"a\\"` parses (one escape pair plus the closer): the pair
9803        // scans atomically, like the block-string arm and `lex_word`.
9804        // The value stays raw (`\\` verbatim for runtime
9805        // `expand_string`), so this pins parsing, not unescaping.
9806        assert_parity("ECHO \"a\\\\\"");
9807        let steps = crate::parse_script("ECHO \"a\\\\\"", lower).expect("escaped pair must parse");
9808        match &steps[..] {
9809            [s] => assert!(
9810                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a\\\\"),
9811                "escaped pair must survive raw: {s:?}"
9812            ),
9813            _ => panic!("one step: {steps:?}"),
9814        }
9815    }
9816
9817    #[test]
9818    fn joint_double_slash_stays_literal() {
9819        // `rustc` strips `//` before the macro ever runs, so these are
9820        // string-path-only by construction: joint `a//b` is one literal
9821        // arg, and `[a //c]` closes its group (the in-group `//` copy
9822        // stops at the closer).
9823        for text in ["ECHO a//b", "ECHO [a //c]"] {
9824            assert_parity_string_only(text);
9825        }
9826        let steps = crate::parse_script("ECHO a//b", lower).expect("joint slashes parse");
9827        match &steps[..] {
9828            [s] => assert!(
9829                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a//b"),
9830                "joint `//` must glue literally: {s:?}"
9831            ),
9832            _ => panic!("one step: {steps:?}"),
9833        }
9834        let steps = crate::parse_script("ECHO [a //c]", lower).expect("group must close");
9835        assert_eq!(steps.len(), 1, "one step: {steps:?}");
9836        // Full content survives literally: the mock joins WRITE args
9837        // with spaces, so the round trip is byte-exact here.
9838        let steps = crate::parse_script("WRITE f [a //c]", lower).expect("group must close");
9839        match &steps[..] {
9840            [s] => assert!(
9841                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a //c]"),
9842                "group content must survive literally: {s:?}"
9843            ),
9844            _ => panic!("one step: {steps:?}"),
9845        }
9846    }
9847
9848    #[test]
9849    fn block_comment_in_group_closes_like_line_comment() {
9850        // `[a /* c]` reads literally on the old backend (first arg
9851        // `[a`, joined `[a /* c]`), so the in-group `/*` copy breaks
9852        // at the depth-zero closer exactly like `//` does. The bare
9853        // `/*` reads literally too.
9854        for text in ["ECHO [a /* c]", "WRITE f [a /* c]", "ECHO /*"] {
9855            assert_parity_string_only(text);
9856        }
9857        let steps = crate::parse_script("ECHO /*", lower).expect("bare block open parses");
9858        match &steps[..] {
9859            [s] => assert!(
9860                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "/*"),
9861                "bare `/*` must stay literal: {s:?}"
9862            ),
9863            _ => panic!("one step: {steps:?}"),
9864        }
9865        let steps = crate::parse_script("WRITE f [a /* c]", lower).expect("group must close");
9866        match &steps[..] {
9867            [s] => assert!(
9868                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c]"),
9869                "group content must survive literally: {s:?}"
9870            ),
9871            _ => panic!("one step: {steps:?}"),
9872        }
9873        // Terminated spans keep working through the same path: the
9874        // run carries its closer, so math still gets first refusal.
9875        let steps = crate::parse_script("WRITE f [a /* c */ d]", lower).expect("group must close");
9876        match &steps[..] {
9877            [s] => assert!(
9878                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c */ d]"),
9879                "terminated group content must survive: {s:?}"
9880            ),
9881            _ => panic!("one step: {steps:?}"),
9882        }
9883    }
9884
9885    #[test]
9886    fn single_quoted_multiline_keeps_line_tracking() {
9887        // The `'` arm counts embedded newlines like the `"` arm, so the
9888        // statement after a multiline single-quoted string keeps its
9889        // own lines (func-docs stamping keys off them).
9890        let text = "ECHO 'a\nb'\nECHO c";
9891        assert_parity_string_only(text);
9892        let steps = crate::parse_script(text, lower).expect("must parse");
9893        assert_eq!(steps.len(), 2, "two steps: {steps:?}");
9894        assert_eq!((steps[0].line, steps[0].col), (1, 1));
9895        assert_eq!((steps[1].line, steps[1].col), (3, 1), "{steps:?}");
9896    }
9897
9898    #[test]
9899    fn token_and_string_paths_agree_on_guarded_commands() {
9900        for text in [
9901            "[env:X] ECHO hi",
9902            "[env:A] [os:linux] ECHO hi",
9903            "[os:macos] WRITE x",
9904            "[not(os:windows)] WRITE f x",
9905            "[any(os:macos, os:linux)] ECHO hi",
9906            "[all(env:A, os:linux)] ECHO hi",
9907            "[eq(env:K, v)] ECHO hi",
9908            "[ne(env:K, v)] ECHO hi",
9909            "[bool:true] ECHO hi",
9910            "[arch:arm] ECHO hi",
9911            "[family:unix] ECHO hi",
9912            "[(os:linux)] ECHO hi",
9913            "[env:A, os:linux] ECHO hi",
9914            "WRITE x\n[env:X] ECHO hi",
9915            "[env:K] ECHO $x",
9916            "[__OXDOCK_INJECT_1__] ECHO hi",
9917            "[eq(env:K, \"a b\")] ECHO hi",
9918            "[\nenv:X\n] ECHO hi",
9919            // In-body brackets are raw text split on whitespace (probed
9920            // parity: `[a, b]` is args `"[a,"` + `"b]"`, quotes kept).
9921            "ECHO [a, b] hi",
9922            "WRITE f [env:X]",
9923            "ECHO [env:X] hi",
9924            "WRITE f [\"a b\"]",
9925            "ECHO foo[bar]baz",
9926            "ECHO [a ]",
9927            "ECHO [ a]",
9928            "WRITE out x [env:X]",
9929        ] {
9930            assert_parity(text);
9931        }
9932        // `rustc` lexes `'a` as a lifetime start and rejects the
9933        // space: string-path-only by construction.
9934        assert_parity_string_only("ECHO ['a b']");
9935    }
9936
9937    #[test]
9938    fn token_and_string_paths_agree_on_calls_and_exact_args() {
9939        use crate::ast::{ModuleFuncs, ModuleTable};
9940        use std::collections::{HashMap, HashSet};
9941        let std_table = || ModuleTable {
9942            modules: HashMap::from([(
9943                crate::constants::STD_MODULE_NAME.to_string(),
9944                Some(ModuleFuncs {
9945                    func_names: HashSet::from(["LEN".to_string()]),
9946                }),
9947            )]),
9948        };
9949        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9950            test_lower_mock::lower(name, args)
9951        }
9952        // One table for both pathways: STD exports LEN.
9953        // Rebuilt per case (parse-time only, keeps borrows local).
9954        for text in [
9955            "LET $n: INT = STD::LEN(\"hi\")",
9956            "STD::LEN(\"hi\")",
9957            "LET $n: INT = STD::LEN(\"a\", \"b\")",
9958            "LET $s: STRING = INSPECT($x)",
9959            "INSPECT($x)",
9960            "LET $x: STRING = ECHO hi",
9961            "LET $t: STRING = WRITE x",
9962            "LET $o: STRING = RUN echo hi",
9963            "RUN [\"echo\", \"hi\"]",
9964            "RUN echo [a]",
9965            "LET $r: STRING = RUN [\"echo\"]",
9966            "ECHO K=v",
9967            "ECHO K = v",
9968            "ECHO K=a b",
9969            "ECHO K=a, b",
9970            "ECHO K=\"a b\"",
9971            "ECHO K=$x",
9972            "ECHO K=",
9973            "ECHO a = = b",
9974            "WRITE f K=v",
9975            "ECHO $a + $b",
9976            "ECHO $a==$b",
9977            "ECHO a $x b",
9978            "ECHO 5 + 3",
9979            "WRITE f ( \"hi\" )",
9980            "ECHO [a, b] hi",
9981            "ECHO {{x}}",
9982            "ECHO {{ $x }}",
9983            "ECHO $x=K",
9984            "ECHO a$x",
9985            "ECHO a$(x)",
9986            "ECHO K=$x tail",
9987            "EXPAND K1=$x K2=$y",
9988            "EXPAND a",
9989            "ENV K = v",
9990            "COPY a b",
9991            "ECHO foo[bar]baz",
9992            "LET $x: STRING = FOOBAR",
9993            "STD::LEN(\"hi\") ECHO bye",
9994            "LET $n: INT = STD::LEN(\"a\") ECHO bye",
9995            "TIMEOUT 10s STD::LEN(\"hi\")",
9996            "TIMEOUT 10s STD::LEN(\"hi\") ECHO bye",
9997            "LET $n: INT = STD::LEN(\"a\")STD::LEN(\"b\")",
9998        ] {
9999            let table = std_table();
10000            let old =
10001                crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
10002                    .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
10003            let reserved = HashSet::new();
10004            let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
10005            let toks = crate::tok::lex_str(text).expect("string lex must succeed");
10006            let new = parse_tokens_with_ctx(&toks, &ctx)
10007                .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
10008            assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
10009            #[cfg(feature = "proc-macro-api")]
10010            {
10011                let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
10012                let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
10013                let new = parse_tokens_with_ctx(&toks, &ctx)
10014                    .unwrap_or_else(|e| panic!("token path must parse token {text:?}: {e}"));
10015                assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
10016            }
10017        }
10018    }
10019
10020    #[test]
10021    fn placeholder_bare_calls_resolve_like_statements() {
10022        // `{{ NAME(args) }}` obeys exactly the statement-position
10023        // scope rule: `IMPORT [MOD]` brings the names into scope,
10024        // unimported names fail naming the fix, ambiguity fails
10025        // closed. The rewrite below is byte-identical past the
10026        // qualified head, so expansion sees the same args.
10027        use crate::ast::{ModuleFuncs, ModuleTable};
10028        use std::collections::{HashMap, HashSet};
10029        let table = || ModuleTable {
10030            modules: HashMap::from([
10031                (
10032                    crate::constants::STD_MODULE_NAME.to_string(),
10033                    Some(ModuleFuncs {
10034                        func_names: HashSet::from(["LEN".to_string()]),
10035                    }),
10036                ),
10037                (
10038                    "OTHER".to_string(),
10039                    Some(ModuleFuncs {
10040                        func_names: HashSet::from(["LEN".to_string()]),
10041                    }),
10042                ),
10043            ]),
10044        };
10045        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10046            test_lower_mock::lower(name, args)
10047        }
10048        fn echo_text(steps: &[crate::Step]) -> String {
10049            match steps {
10050                [s] => match &s.kind {
10051                    StepKind::Echo(Arg::String(text, _)) => text.clone(),
10052                    other => panic!("expected ECHO string, got {other:?}"),
10053                },
10054                _ => panic!("expected one step, got {steps:?}"),
10055            }
10056        }
10057        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10058            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10059        }
10060        // Imported bare names qualify; everything else rides through
10061        // byte-identical for the runtime to handle as before.
10062        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }}\"\n";
10063        let out = echo_text(&parse(text, table()).expect("imported bare call parses"));
10064        assert_eq!(out, "n: {{ STD::LEN($x) }}", "bare call qualifies: {out}");
10065        let text = "IMPORT [STD]\nECHO \"n: {{ STD::LEN($x) }}\"\n";
10066        let out = echo_text(&parse(text, table()).expect("qualified parses"));
10067        assert_eq!(
10068            out, "n: {{ STD::LEN($x) }}",
10069            "qualified keys stay untouched: {out}"
10070        );
10071        let text = "IMPORT [STD]\nECHO \"hi {{ $x }} and {{ bare }} and {{ env:K }}\"\n";
10072        let out = echo_text(&parse(text, table()).expect("non-calls parse"));
10073        assert_eq!(
10074            out, "hi {{ $x }} and {{ bare }} and {{ env:K }}",
10075            "non-call keys stay untouched: {out}"
10076        );
10077        let text = "IMPORT [STD]\nECHO \"lit \\{{ LEN($x) }}\"\n";
10078        let out = echo_text(&parse(text, table()).expect("escaped parses"));
10079        assert_eq!(
10080            out, "lit \\{{ LEN($x) }}",
10081            "escaped openers stay literal: {out}"
10082        );
10083        // Nested bodies resolve against the enclosing imports, exactly
10084        // like statement-position calls in the same body.
10085        let text = indoc! {r#"
10086            IMPORT [STD]
10087            FUNC F(): VOID {
10088            ECHO "n: {{ LEN($x) }}"
10089            }
10090        "#};
10091        let steps = parse(text, table()).expect("nested bare call parses");
10092        let body = steps.iter().find_map(|s| match &s.kind {
10093            StepKind::FuncDef { body, .. } => Some(body),
10094            _ => None,
10095        });
10096        match body.map(Vec::as_slice) {
10097            Some([inner]) => match &inner.kind {
10098                StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10099                    echoed, "n: {{ STD::LEN($x) }}",
10100                    "nested body qualifies: {echoed}"
10101                ),
10102                other => panic!("expected nested ECHO, got {other:?}"),
10103            },
10104            _ => panic!("expected one FUNC with one body step, got {steps:?}"),
10105        };
10106        // Neighboring placeholders keep their exact bytes: only the
10107        // head span changes, so payloads never lose formatting.
10108        let text = "IMPORT [STD]\nECHO \"Call {{ LEN($x) }} and value {{ $y }}\"\n";
10109        let out = echo_text(&parse(text, table()).expect("mixed template parses"));
10110        assert_eq!(
10111            out, "Call {{ STD::LEN($x) }} and value {{ $y }}",
10112            "only the head span changes: {out}"
10113        );
10114        // Unimported bare names fail exactly like statement position:
10115        // qualify it or add the import.
10116        let err = parse("ECHO \"n: {{ LEN($x) }}\"\n", table()).expect_err("must fail");
10117        assert!(
10118            err.to_string().contains("unknown function `LEN`")
10119                && err.to_string().contains("or add `IMPORT"),
10120            "names the fix: {err}"
10121        );
10122        // Two exporters fail closed instead of picking one.
10123        let err = parse(
10124            "IMPORT [STD]\nIMPORT [OTHER]\nECHO \"n: {{ LEN($x) }}\"\n",
10125            table(),
10126        )
10127        .expect_err("must fail");
10128        assert!(
10129            err.to_string().contains("ambiguous function `LEN`"),
10130            "ambiguity fails closed: {err}"
10131        );
10132        // Both lexing pathways agree on rewritten templates.
10133        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }} and {{ $y }}\"\n";
10134        let table = table();
10135        let old = crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
10136            .expect("string path parses");
10137        let reserved = HashSet::new();
10138        let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
10139        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
10140        let new = parse_tokens_with_ctx(&toks, &ctx).expect("token path parses");
10141        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
10142    }
10143
10144    #[test]
10145    fn placeholder_bare_calls_qualify_in_expr_positions() {
10146        // Regression: `walk_raw_strings_mut` skips `Assign`/`Set`/
10147        // `Call`/`Return`/`If`/`For`/`While`, so `LET`/`RETURN`/call
10148        // args/list/map literals never qualified and failed at
10149        // runtime as undefined variables. Both carriers now qualify.
10150        use crate::ast::{ModuleFuncs, ModuleTable};
10151        use std::collections::{HashMap, HashSet};
10152        let table = || ModuleTable {
10153            modules: HashMap::from([(
10154                crate::constants::STD_MODULE_NAME.to_string(),
10155                Some(ModuleFuncs {
10156                    func_names: HashSet::from(["LEN".to_string()]),
10157                }),
10158            )]),
10159        };
10160        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10161            test_lower_mock::lower(name, args)
10162        }
10163        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10164            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10165        }
10166        // LET string literal qualifies.
10167        let steps = parse(
10168            "IMPORT [STD]\nLET $s: STRING = \"n: {{ LEN($x) }}\"\n",
10169            table(),
10170        )
10171        .expect("LET template parses");
10172        match &steps[0].kind {
10173            StepKind::Assign { expr, .. } => match expr {
10174                Expr::Literal(value) => assert_eq!(
10175                    value.as_str().unwrap_or_default(),
10176                    "n: {{ STD::LEN($x) }}",
10177                    "LET qualifies"
10178                ),
10179                other => panic!("expected literal, got {other:?}"),
10180            },
10181            other => panic!("expected Assign, got {other:?}"),
10182        }
10183        // RETURN string literal qualifies.
10184        let steps = parse(
10185            "IMPORT [STD]\nFUNC F(): STRING {\nRETURN \"n: {{ LEN($x) }}\"\n}\n",
10186            table(),
10187        )
10188        .expect("RETURN template parses");
10189        let body = steps.iter().find_map(|s| match &s.kind {
10190            StepKind::FuncDef { body, .. } => Some(body),
10191            _ => None,
10192        });
10193        match body.map(Vec::as_slice) {
10194            Some([inner]) => match &inner.kind {
10195                StepKind::Return { expr, .. } => match &**expr {
10196                    Expr::Literal(value) => assert_eq!(
10197                        value.as_str().unwrap_or_default(),
10198                        "n: {{ STD::LEN($x) }}",
10199                        "RETURN qualifies"
10200                    ),
10201                    other => panic!("expected literal, got {other:?}"),
10202                },
10203                other => panic!("expected RETURN, got {other:?}"),
10204            },
10205            _ => panic!("expected one FUNC, got {steps:?}"),
10206        }
10207        // Call args, list and map literals qualify.
10208        let steps = parse(
10209            "IMPORT [STD]\nLET $y: INT = LEN(\"b: {{ LEN($x) }}\")\n",
10210            table(),
10211        )
10212        .expect("call-arg template parses");
10213        let rendered = format!("{:?}", steps[0].kind);
10214        assert!(
10215            rendered.contains("STD::LEN"),
10216            "call arg qualifies: {rendered}"
10217        );
10218        let steps = parse(
10219            "IMPORT [STD]\nLET $l: LIST<STRING> = [\"{{ LEN($x) }}\"]\n",
10220            table(),
10221        )
10222        .expect("list template parses");
10223        let rendered = format!("{:?}", steps[0].kind);
10224        assert!(rendered.contains("STD::LEN"), "list qualifies: {rendered}");
10225        // Compound placeholders are not single calls: they pass
10226        // through untouched (no partial rewrite) for the runtime to
10227        // fail closed on the whole key.
10228        let text = "IMPORT [STD]\nECHO \"v: {{ LEN($a) + LEN($b) }}\"\n";
10229        let steps = parse(text, table()).expect("compound parses");
10230        match &steps[0].kind {
10231            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10232                echoed, "v: {{ LEN($a) + LEN($b) }}",
10233                "compound untouched: {echoed}"
10234            ),
10235            other => panic!("expected ECHO string, got {other:?}"),
10236        }
10237        // Quoted parens inside args do not end the call early.
10238        let text = "IMPORT [STD]\nECHO 'v: {{ LEN(\"a(b\") }}'\n";
10239        let steps = parse(text, table()).expect("quoted paren parses");
10240        match &steps[0].kind {
10241            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10242                echoed, "v: {{ STD::LEN(\"a(b\") }}",
10243                "quoted paren qualifies: {echoed}"
10244            ),
10245            other => panic!("expected ECHO string, got {other:?}"),
10246        }
10247        // Single-quoted args balance the same way.
10248        let text = "IMPORT [STD]\nECHO \"v: {{ LEN('a(b') }}\"\n";
10249        let steps = parse(text, table()).expect("single-quoted paren parses");
10250        match &steps[0].kind {
10251            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10252                echoed, "v: {{ STD::LEN('a(b') }}",
10253                "single-quoted paren qualifies: {echoed}"
10254            ),
10255            other => panic!("expected ECHO string, got {other:?}"),
10256        }
10257        // `WithIo` boxes its inner command directly (no recursive
10258        // statement pass), so the qualifier must descend into it.
10259        // `LET $p: PIPE` plus bindings keep the shape realistic.
10260        let text = "IMPORT [STD]\nLET $p: PIPE\nWITH_IO [stdout=$p] ECHO 'v: {{ LEN($x) }}'\n";
10261        let steps = parse(text, table()).expect("with-io template parses");
10262        match &steps[1].kind {
10263            StepKind::WithIo { cmd, .. } => {
10264                let rendered = format!("{cmd:?}");
10265                assert!(
10266                    rendered.contains("STD::LEN"),
10267                    "with-io inner qualifies: {rendered}"
10268                );
10269            }
10270            other => panic!("expected WithIo, got {other:?}"),
10271        }
10272        // Single-command wrappers build synthetic body steps without a
10273        // recursive pass: `TIMEOUT 5s <cmd>` and `ASYNC <cmd>` share
10274        // the outer frame, so the qualifier must descend into bodies.
10275        let text = "IMPORT [STD]\nTIMEOUT 5s ECHO 't: {{ LEN($x) }}'\n";
10276        let steps = parse(text, table()).expect("timeout template parses");
10277        let rendered = format!("{:?}", steps[0].kind);
10278        assert!(
10279            rendered.contains("STD::LEN"),
10280            "timeout single qualifies: {rendered}"
10281        );
10282        let text = "IMPORT [STD]\nLET $h: HANDLE<ANY> = ASYNC ECHO 'a: {{ LEN($x) }}'\n";
10283        let steps = parse(text, table()).expect("async template parses");
10284        let rendered = format!("{:?}", steps[0].kind);
10285        assert!(
10286            rendered.contains("STD::LEN"),
10287            "async single qualifies: {rendered}"
10288        );
10289        // Brace bodies keep their own frames: the outer qualifier must
10290        // never re-walk them. A valid nested body qualifies via its own
10291        // recursive pass, and an unknown callee inside one fails with
10292        // the inner position, never re-resolved against the outer frame.
10293        let text = "IMPORT [STD]\nIF true {\nECHO 'v: {{ LEN($x) }}'\n}\n";
10294        let steps = parse(text, table()).expect("nested body qualifies");
10295        let rendered = format!("{:?}", steps[0].kind);
10296        assert!(
10297            rendered.contains("STD::LEN"),
10298            "nested IF body qualifies via its own frame: {rendered}"
10299        );
10300        let err = parse(
10301            "IMPORT [STD]\nIF true {\nECHO 'v: {{ NOPE($x) }}'\n}\n",
10302            table(),
10303        )
10304        .expect_err("nested unknown must fail");
10305        assert!(
10306            err.to_string().contains("unknown function `NOPE`"),
10307            "nested unknown names culprit: {err}"
10308        );
10309    }
10310
10311    #[test]
10312    fn block_conditions_name_unknown_callees() {
10313        // Regression: an unknown callee in a block header condition
10314        // used to miss to the generic `IF needs a condition and a
10315        // block` hint. Classified resolution failures now propagate
10316        // and name the culprit on all four speculative headers.
10317        use crate::ast::{ModuleFuncs, ModuleTable};
10318        use std::collections::{HashMap, HashSet};
10319        let table = || ModuleTable {
10320            modules: HashMap::from([(
10321                crate::constants::STD_MODULE_NAME.to_string(),
10322                Some(ModuleFuncs {
10323                    func_names: HashSet::from(["LEN".to_string()]),
10324                }),
10325            )]),
10326        };
10327        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10328            test_lower_mock::lower(name, args)
10329        }
10330        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10331            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10332        }
10333        for text in [
10334            "IMPORT [STD]\nIF NOPE($x) == 0 {\nECHO hi\n}\n",
10335            "IMPORT [STD]\nIF LEN($x) == 0 {\nECHO hi\n} ELSE IF NOPE($x) == 1 {\nECHO yo\n}\n",
10336            "IMPORT [STD]\nWHILE NOPE($x) > 0 {\nECHO hi\n}\n",
10337            "IMPORT [STD]\nFOR $i: STRING IN NOPE($x) {\nECHO $i\n}\n",
10338        ] {
10339            let err = parse(text, table()).expect_err("unknown callee must fail");
10340            assert!(
10341                err.to_string().contains("unknown function `NOPE`"),
10342                "names the culprit: {err}"
10343            );
10344        }
10345        // Unclassified shape misses still miss (the exact generic
10346        // hint comes from the real dispatcher, which the mock lacks).
10347        parse("IF {\nECHO hi\n}\n", table()).expect_err("empty condition must still fail");
10348    }
10349
10350    #[test]
10351    fn token_and_string_paths_agree_on_let_set_return() {
10352        for text in [
10353            "LET $x: INT = 1",
10354            "LET $s: STRING = \"hi\"",
10355            "LET $b: BOOL = true",
10356            "LET $f: FLOAT = 1.5",
10357            "LET $p: PIPE",
10358            "LET $l: LIST<STRING> = [\"a\", \"b\"]",
10359            "LET $e: LIST<STRING> = []",
10360            "LET $m: MAP = {k: 1}",
10361            "LET $m2: MAP = {\"a b\": 2, k: [1, 2]}",
10362            "LET $n: INT = $a + $b",
10363            "LET $c: BOOL = ($a == 3) && ($b == 4)",
10364            "LET $g: BOOL = !$ok",
10365            "LET $nn: BOOL = true && false",
10366            "LET $e2: STRING = env:HOME",
10367            "LET $k: STRING = $a.b.c",
10368            "LET $u: INT = -5",
10369            "LET $v: INT = 9223372036854775807",
10370            "LET $min: INT = -9223372036854775808",
10371            "LET $w: INT = 1_000",
10372            "LET $z: STRING = a/b",
10373            "LET $d: STRING = -f",
10374            "LET $t: STRING = 30s",
10375            "LET $q: STRING = \"\"\"hi\"\"\"",
10376            "LET $f2: FLOAT = 2 * -3",
10377            "LET $o: BOOL = 2 + 3 > 4",
10378            "LET $l2: LIST< MAP > = []",
10379            "LET $a1: INT = 1 + 2",
10380            "LET $s1: INT = 10 - 4 - 3",
10381            "LET $m1: INT = 2 * 3 + 4",
10382            "LET $x1: BOOL = 1 < 2 == true",
10383            "LET $or: BOOL = $a || $b",
10384            "LET $dbl: BOOL = !!$x",
10385            "LET $ver: STRING = 1.0.0",
10386            "LET $dash: STRING = a-b",
10387            "LET $div: INT = 4 / 2",
10388            "LET $bad: INT = 1__0 + 0",
10389            "LET $strdiv: STRING = 4/2",
10390            "LET $sp: INT = $a - $b",
10391            "$x = 1",
10392            "$x = $a + 1",
10393            "RETURN 1",
10394            KEYWORD_RETURN,
10395            "RETURN $x",
10396            "[env:X] LET $x: INT = 1",
10397            "[os:linux] $x = 2",
10398        ] {
10399            assert_parity(text);
10400        }
10401    }
10402
10403    #[test]
10404    fn malformed_shapes_fail_on_both_paths() {
10405        // Malformed shapes fail on both lexers (messages may differ;
10406        // success/failure must agree). Unbalanced groups fail even
10407        // earlier, at lex time: both layers reject, which is what the
10408        // oracle pins.
10409        for text in [
10410            "[a] ECHO hi",
10411            "[os:atari] ECHO hi",
10412            "[foo:bar] ECHO hi",
10413            "[any(os:linux)] ECHO hi",
10414            "[all()] ECHO hi",
10415            "[env:] ECHO hi",
10416            "[eq(env:K)] ECHO hi",
10417            "[not] ECHO hi",
10418            "ECHO [a;b]",
10419            "ECHO (a;b)",
10420            "ECHO a;b",
10421            "LET $x = 1",
10422            "LET $s: STRING",
10423            "LET $x: INT = 1 2",
10424            "LET $x: INT = (1",
10425            "LET $x: INT = 9223372036854775808",
10426            "$x =",
10427            "RETURN (",
10428            "[env:X]",
10429            "LET $x: INT = $a == $b == $c",
10430            "LET $x: BOOL = $a < $b < $c",
10431            "LET $bs: STRING = a\\nb",
10432            "FOO(\"a\")",
10433            "FOO (\"a\")",
10434            "ECHO FOO(\"a\")",
10435            "ECHO(\"hi\")",
10436            "RUN [a] extra",
10437            "RUN[\"a\"]",
10438            "TIMEOUT 10s RUN[\"a\"]",
10439            "LET $r: STRING = RUN[\"a\"]",
10440            "LET $e: STRING = ECHO",
10441            "ENV A=1 B=2",
10442            "EXPAND \"a b\" c",
10443            "ECHO {a}",
10444            "ECHO K=${x}",
10445            "[!env:A==1] RUN echo no",
10446            "run echo hi",
10447            "LET $x: STRING = AWAIT",
10448            "LET $o: STRING = CANCEL $t",
10449            "LET $x: STRING = ASYNC",
10450            "LET $x: STRING = WITH_IO",
10451            "LET $x: STRING = TIMEOUT",
10452            "LET $x: STRING = ISOLATED",
10453            "LET $x: STRING = ISOLATED ECHO hi",
10454            "COPY A=1",
10455            "WITH_IO [rows=40] RUN echo hi",
10456            "WITH_IO [tty] ECHO hi",
10457            "WITH_IO [tty, stderr=$p] RUN echo hi",
10458            "WITH_IO [tty=$p] RUN echo hi",
10459            "WITH_IO [cols=0] RUN echo hi",
10460            "WITH_IO [cols=65536] RUN echo hi",
10461            "WITH_IO [] ECHO hi",
10462            "WITH_IO [stdin=$p,] ECHO hi",
10463            "WITH_IO stdin=$p ECHO hi",
10464            "WITH_IO [STDIN=$p] ECHO hi",
10465            "WITH_IO [rows] RUN echo hi",
10466            KEYWORD_WITH_IO,
10467            "WITH_IO [stdout=$p]",
10468            "WITH_IO [stdin=$p]\n[os:linux] { ECHO hi }",
10469            "WITH_IO [stdin=$p] { }",
10470            "WITH_IO[stdin=$p] ECHO hi",
10471            "WITH_IO [stdin=$p]ECHO hi",
10472            "WITH_IO [stdin=$p] {{ $x }}",
10473            "ASYNC WITH_IO [stdout=$p] ECHO hi",
10474            "WITH_IO [stdin=$p] AWAIT $t",
10475            "ASYNC AWAIT $t",
10476            "WITH_IO [stdin=$p] RETURN \"hi\"",
10477            "ASYNC RETURN \"hi\"",
10478            "TIMEOUT 10s RETURN \"hi\"",
10479            "TIMEOUT banana ECHO hi",
10480            "TIMEOUT 10ss ECHO hi",
10481            "TIMEOUT 10 s ECHO hi",
10482            "TIMEOUT -5s ECHO hi",
10483            "TIMEOUT 0s ECHO hi",
10484            KEYWORD_TIMEOUT,
10485            "TIMEOUT 10s",
10486            "TIMEOUT { ECHO hi }",
10487            "TIMEOUT \"10s\"",
10488            "TIMEOUT 10s{ECHO hi}",
10489            "TIMEOUT 10sECHO hi",
10490            "TIMEOUT 10s {{ $d }}",
10491            "TIMEOUT 10s { $d }",
10492            "TIMEOUT { $d } ECHO hi",
10493            KEYWORD_ASYNC,
10494            KEYWORD_ISOLATED,
10495            "ISOLATED{ECHO hi}",
10496            KEYWORD_AWAIT,
10497            KEYWORD_CANCEL,
10498            "AWAIT t",
10499            "AWAIT $",
10500            "AWAIT $t extra",
10501            "CANCEL $t extra",
10502            "TIMEOUT 5s INHERIT_ENV [M]",
10503            "TIMEOUT 5s { INHERIT_ENV [M] }",
10504            "ASYNC { INHERIT_ENV [M] }",
10505            "LET $x: STRING = INHERIT_ENV [M]",
10506            "TIMEOUT 10s WITH_IO [stdin=$p] { ECHO hi }",
10507            "ISOLATED WITH_IO [stdin=$p] { ECHO hi }",
10508            "TIMEOUT 10s AWAIT $ t",
10509            "LET $o: STRING = AWAIT $ t",
10510            "ISOLATED AWAIT $ t",
10511            "WITH_IO [stdin=$p] CANCEL $ t",
10512            "LET $ x: INT = 1",
10513            "LET $x: STRING = WITH_IO [stdin=$p] { ECHO hi }",
10514            "LET $x: STRING = WITH_IO [stdin=$p] ASYNC",
10515            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO a\nECHO b }",
10516            "LET $x: STRING = WITH_IO [stdout=$p] ECHO hi",
10517            "LET $x: STRING = TIMEOUT 10s AWAIT $t",
10518            "LET $x: STRING = CANCEL $t",
10519            "LET $x: STRING = ASYNC",
10520            "LET $x: STRING = WITH_IO",
10521            "TIMEOUT 10s LET $x: INT = 1",
10522            "LET $x: STRING = FOO bar",
10523            "LET(\"a\")",
10524            "AWAIT($t)",
10525            "CANCEL($t)",
10526            "TIMEOUT(\"10s\") ECHO hi",
10527            "RETURN ECHO bye",
10528        ] {
10529            match crate::tok::lex_str(text) {
10530                Err(_) => {
10531                    assert!(
10532                        crate::parse_script(text, lower).is_err(),
10533                        "backend must also reject lex-broken input: {text:?}"
10534                    );
10535                    continue;
10536                }
10537                Ok(toks) => {
10538                    assert!(
10539                        parse_tokens(&toks, lower).is_err(),
10540                        "v2 must explicitly reject (not silently drift): {text:?}"
10541                    );
10542                }
10543            }
10544            assert!(
10545                crate::parse_script(text, lower).is_err(),
10546                "backend must also reject (oracle agreement): {text:?}"
10547            );
10548        }
10549        // No deferred shapes remain: every statement-level block and
10550        // inline-block expression parses natively.
10551    }
10552
10553    #[test]
10554    fn deferred_unknown_callee_beats_validation_arg_error() {
10555        // Directive 5: `WORKSPACE NOPE()` stashes `unknown function
10556        // NOPE` while the fallback raw string fails `WORKSPACE`
10557        // validation. On a well-formed header the stashed callee error
10558        // names the culprit instead of the misleading arg-shape error.
10559        let err =
10560            crate::parse_script("WORKSPACE NOPE()", lower).expect_err("unknown callee must fail");
10561        assert!(
10562            err.to_string().contains("unknown function `NOPE`"),
10563            "deferred must beat validation, got: {err}"
10564        );
10565    }
10566
10567    #[test]
10568    fn paren_line_break_reports_token_position() {
10569        // Directive 5: multiline paren breaks carry the offending
10570        // token's line/col, not a stamped 0/0. The break sits on line 2
10571        // while the statement opens on line 1.
10572        let err = crate::parse_script("ECHO (a\nb)", lower).expect_err("break must fail");
10573        let rendered = err.to_string();
10574        assert!(
10575            rendered.contains("unexpected line break"),
10576            "break must report, got: {rendered}"
10577        );
10578    }
10579
10580    #[test]
10581    fn deferred_unknown_callee_beats_invalid_syntax_arg_error() {
10582        // Fallback raw strings can trigger `InvalidSyntax` lowering
10583        // (for example `COPY NOPE()`). The stashed unknown-callee error
10584        // still names the culprit on a recognized head.
10585        for text in ["COPY NOPE()", "WRITE NOPE()"] {
10586            let err = crate::parse_script(text, lower).expect_err("unknown callee must fail");
10587            assert!(
10588                err.to_string().contains("unknown function `NOPE`"),
10589                "deferred must beat InvalidSyntax for {text:?}, got: {err}"
10590            );
10591        }
10592    }
10593
10594    #[test]
10595    fn deferred_beats_lowering_invalid_syntax_on_plain_heads() {
10596        // Plain command heads own no header grammar, so a lowering
10597        // `InvalidSyntax` there is an argument-shape failure from the
10598        // raw-text fallback: the stashed unknown-callee names the
10599        // culprit on every such head (no per-command allowlist).
10600        let lower_invalid =
10601            |name: &str, _args: Vec<crate::Arg>| -> crate::ParseResult<crate::StepKind> {
10602                Err(crate::ParseError::invalid_syntax(
10603                    name,
10604                    format!("{name} header is malformed"),
10605                    None,
10606                    Vec::new(),
10607                    None,
10608                    &crate::error::SpanContext::line_only(0),
10609                ))
10610            };
10611        for text in [
10612            "ASSERT_EQ $a NOSUCHFUNC()",
10613            "SYMLINK $a NOSUCHFUNC()",
10614            "COPY $a NOSUCHFUNC()",
10615            "WRITE $a NOSUCHFUNC()",
10616        ] {
10617            let err = crate::parse_script(text, lower_invalid).expect_err("arg error must fail");
10618            assert!(
10619                err.to_string().contains("unknown function `NOSUCHFUNC`"),
10620                "deferred must beat lowering InvalidSyntax for {text:?}, got: {err}"
10621            );
10622        }
10623        // Header-owned heads keep their lowering `InvalidSyntax`: the
10624        // native parser missed to the generic path on shape miss, so
10625        // the lowering error names the malformed header while the
10626        // stashed name is its definiendum, never a call.
10627        let err = crate::parse_script("FUNC $a NOSUCHFUNC()", lower_invalid)
10628            .expect_err("header syntax must fail");
10629        assert!(
10630            err.to_string().contains("header is malformed"),
10631            "header InvalidSyntax must stand on FUNC, got: {err}"
10632        );
10633    }
10634
10635    #[test]
10636    fn trailing_tokens_after_func_block_never_hoist() {
10637        // A `FUNC` header with trailing tokens after the body block is
10638        // malformed (the real path rejects it), so pre-declaration
10639        // must not hoist the name: the forward call fails instead of
10640        // resolving.
10641        let err = crate::parse_script(
10642            "LET $x: STRING = FOO()\nFUNC FOO(): STRING { RETURN \"a\" } TRAILING\n",
10643            lower,
10644        )
10645        .expect_err("trailing tokens must fail");
10646        assert!(
10647            err.to_string().contains("unknown function `FOO`"),
10648            "unhoisted forward call must fail, got: {err}"
10649        );
10650    }
10651
10652    #[test]
10653    fn forward_reference_resolves_regardless_of_order() {
10654        // `CALLER` calls `CALLEE` defined later. Top-level
10655        // pre-declaration hoists names before lowering, so order
10656        // does not matter. Runtime still executes sequentially;
10657        // the call below runs after both definitions.
10658        let steps = crate::parse_script(
10659            "FUNC CALLER(): STRING { RETURN CALLEE() }\nFUNC CALLEE(): STRING { RETURN \"forward-ok\" }\n",
10660            lower,
10661        )
10662        .expect("forward ref must parse");
10663        assert!(
10664            matches!(&steps[0].kind, crate::StepKind::FuncDef { name, .. } if name == "CALLER"),
10665            "first def kept, got: {:?}",
10666            steps[0].kind
10667        );
10668    }
10669
10670    #[test]
10671    fn forward_reference_to_guarded_func_resolves() {
10672        // Guarded definitions hoist like unguarded ones: `parse_func_at`
10673        // registers `[os:macos] FUNC FOO` unconditionally, so a forward
10674        // call before the definition must resolve identically to a
10675        // backward call after it.
10676        let steps = crate::parse_script(
10677            "LET $x: STRING = FOO()\n[os:macos] FUNC FOO(): STRING { RETURN \"guarded\" }\n",
10678            lower,
10679        )
10680        .expect("forward guarded ref must parse");
10681        assert!(
10682            matches!(&steps[1].kind, crate::StepKind::FuncDef { name, .. } if name == "FOO"),
10683            "guarded def kept, got: {:?}",
10684            steps[1].kind
10685        );
10686    }
10687}