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_CONTINUE, KEYWORD_ELSE, KEYWORD_ENV, KEYWORD_EXPAND, KEYWORD_EXPORT,
98    KEYWORD_FOR, KEYWORD_FROM, KEYWORD_FUNC, KEYWORD_IF, KEYWORD_IMPORT, KEYWORD_IN,
99    KEYWORD_INHERIT_ENV, KEYWORD_INSPECT, KEYWORD_ISOLATED, KEYWORD_LET, KEYWORD_REMOTE,
100    KEYWORD_RETURN, KEYWORD_RUN, KEYWORD_TIMEOUT, KEYWORD_TYPE, KEYWORD_WHILE, KEYWORD_WITH_IO,
101    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            TokKind::Group {
917                delim,
918                inner,
919                close_joint,
920                ..
921            } => {
922                let (open, close) = match delim {
923                    GroupDelim::Bracket => ('[', ']'),
924                    GroupDelim::Paren => ('(', ')'),
925                    GroupDelim::Brace => unreachable!(),
926                };
927                out.push(Tok::fresh(TokKind::Punct(open), tok.joint));
928                // Inside brackets raw-text rules apply: quotes are
929                // characters, blocks never dedent, and whitespace splits
930                // runs (`['a b']` is args `"['a"` + `"b']"`). Convert
931                // spliced strings back to word text (splitting it like
932                // raw text); top-level strings stay structural.
933                for t in splice_arg_groups(inner, stmt)? {
934                    match &t.kind {
935                        TokKind::Str { text, quote } => {
936                            out.extend(split_word_text(&format!("{quote}{text}{quote}"), t.joint));
937                        }
938                        TokKind::BlockStr(full) => {
939                            out.extend(split_word_text(full, t.joint));
940                        }
941                        _ => out.push(t),
942                    }
943                }
944                out.push(Tok::fresh(TokKind::Punct(close), *close_joint));
945            }
946            _ => out.push(tok.clone()),
947        }
948    }
949    Ok(out)
950}
951
952/// Split re-quoted raw text on whitespace runs. The first piece keeps the source joint flag; the rest break
953/// (whitespace separates args). Multi-space gaps normalize to one
954/// (documented edge, same class as group rendering).
955fn split_word_text(text: &str, joint: bool) -> Vec<Tok> {
956    let mut out = Vec::new();
957    let mut first = true;
958    for piece in text.split_whitespace() {
959        out.push(Tok::fresh(
960            TokKind::Word(piece.to_string()),
961            if first { joint } else { false },
962        ));
963        first = false;
964    }
965    if out.is_empty() {
966        out.push(Tok::fresh(TokKind::Word(text.to_string()), joint));
967    }
968    out
969}
970
971/// Assignment key charset, minus the `=` the
972/// classifier handles separately. Words are pre-filtered by the same
973/// set; `$`, quotes, and groups never start a key.
974fn is_assign_key_char(c: char) -> bool {
975    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':')
976}
977
978/// Match an assignment key run at an argument start: joint
979/// word/punct run in the key charset, non-empty, not `--`-led
980/// (flags keep their literal reading). Returns the key and end index.
981fn match_assign_key(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
982    let mut out = String::new();
983    let mut p = pos;
984    loop {
985        let t = toks.get(p)?;
986        if !out.is_empty() && !t.joint {
987            break;
988        }
989        match &t.kind {
990            TokKind::Word(w) => out.push_str(w),
991            TokKind::Punct(c) if is_assign_key_char(*c) => out.push(*c),
992            _ => break,
993        }
994        p += 1;
995    }
996    if out.is_empty() || out.starts_with("--") {
997        return None;
998    }
999    if !out
1000        .chars()
1001        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':'))
1002    {
1003        return None;
1004    }
1005    Some((out, p))
1006}
1007
1008/// Assignment boundary ahead (for value scanning): an argument start
1009/// holding `KEY=` (key run plus `=` at any gap).
1010/// Groups and strings are opaque: a `=` inside them never counts.
1011fn at_assign_boundary(toks: &[Tok], pos: usize) -> bool {
1012    match match_assign_key(toks, pos) {
1013        Some((_, end)) => matches!(toks.get(end).map(|t| &t.kind), Some(TokKind::Punct('='))),
1014        None => false,
1015    }
1016}
1017
1018/// Raw-text render of one gap-run (or value span): words/puncts
1019/// literally (`$`+word literally, `$` elsewhere errors), strings by
1020/// their inner bytes, blocks lowered, groups spliced. Gaps collapse
1021/// to one space like `collapse_ws`; newlines/semicolons fail (the
1022/// grammar's raw span excludes them).
1023fn render_raw_text(toks: &[Tok], stmt: usize) -> Result<String, TokenError> {
1024    let mut out = String::new();
1025    let mut i = 0;
1026    while i < toks.len() {
1027        let tok = &toks[i];
1028        if !tok.joint && !out.is_empty() {
1029            out.push(' ');
1030        }
1031        match &tok.kind {
1032            TokKind::Word(w) => out.push_str(w),
1033            TokKind::Punct(c) => {
1034                if *c == '$' {
1035                    // Lone-`$` runs never reach here (expression
1036                    // extension claims them first and fails loudly).
1037                    // Elsewhere `$` renders literally (probed `a$(x)`
1038                    // reads raw) except before a brace group, where
1039                    // the grammar strands it (probed `K=${x}` fails).
1040                    let next = toks.get(i + 1);
1041                    let brace_next = next.is_some_and(|t| {
1042                        matches!(
1043                            &t.kind,
1044                            TokKind::Group {
1045                                delim: GroupDelim::Brace,
1046                                ..
1047                            }
1048                        )
1049                    });
1050                    if brace_next {
1051                        return Err(TokenError {
1052                            stmt,
1053                            msg: "unexpected `$` in argument".to_string(),
1054                            line: 0,
1055                            col: 0,
1056                            kind: None,
1057                        });
1058                    }
1059                    out.push('$');
1060                } else {
1061                    out.push(*c);
1062                }
1063            }
1064            // Standalone quotes strip (the caller handles single-tok
1065            // runs); glued quotes keep their marks, like the grammar's
1066            // mixed fragments (`>"a"` stays quoted, `"a"` strips).
1067            TokKind::Str { text: s, quote } => {
1068                let glued = tok.joint || toks.get(i + 1).is_some_and(|t| t.joint);
1069                if toks.len() > 1 && glued {
1070                    out.push(*quote);
1071                    out.push_str(s);
1072                    out.push(*quote);
1073                } else {
1074                    out.push_str(s);
1075                }
1076            }
1077            // Comments reproduce verbatim (templates keep comment
1078            // text like the atomic grammar span); gaps collapse
1079            // around them like other fragments per the documented
1080            // single-space normalization.
1081            TokKind::Comment(text) => out.push_str(text),
1082            TokKind::BlockStr(full) => {
1083                // Glued blocks keep their delimiters, like quotes.
1084                let glued = tok.joint || toks.get(i + 1).is_some_and(|t| t.joint);
1085                if toks.len() > 1 && glued {
1086                    out.push_str(full);
1087                } else {
1088                    out.push_str(&crate::command::lower_block_string(full));
1089                }
1090            }
1091            TokKind::Group {
1092                delim: GroupDelim::Brace,
1093                inner,
1094                open_joint,
1095                close_joint,
1096                ..
1097            } => out.push_str(&render_brace_run_text(inner, *open_joint, *close_joint)),
1098            TokKind::Group {
1099                delim: GroupDelim::Bracket,
1100                inner,
1101                open_joint,
1102                close_joint,
1103                ..
1104            } => out.push_str(&render_group('[', ']', inner, *open_joint, *close_joint)),
1105            TokKind::Group {
1106                delim: GroupDelim::Paren,
1107                inner,
1108                open_joint,
1109                close_joint,
1110                ..
1111            } => out.push_str(&render_group('(', ')', inner, *open_joint, *close_joint)),
1112            TokKind::Newline | TokKind::Semicolon => {
1113                return Err(TokenError {
1114                    stmt,
1115                    msg: "unexpected line break in argument".to_string(),
1116                    line: 0,
1117                    col: 0,
1118                    kind: None,
1119                });
1120            }
1121        }
1122        i += 1;
1123    }
1124    Ok(out)
1125}
1126
1127/// Build an assignment value `Arg` over a region that runs to the next
1128/// boundary or end. Single quoted/block strings keep `quoted=true`; a
1129/// region that is exactly one lone `$var`/keypath/`env:`/call shape
1130/// stays typed (calls resolve through the shared resolver, matching
1131/// `assign_expr`); everything else renders raw. A quoted unit followed
1132/// by joint content errors (probed: `K="a"b` fails), like the grammar.
1133fn build_value_arg(
1134    region: &[Tok],
1135    stmt: usize,
1136    ctx: &ParseCtx,
1137    lone_ok: bool,
1138) -> Result<Arg, TokenError> {
1139    if region.is_empty() {
1140        return Ok(Arg::String(String::new(), false));
1141    }
1142    if region.len() == 1 {
1143        match &region[0].kind {
1144            TokKind::Str { text: s, .. } => return Ok(Arg::String(s.clone(), true)),
1145            TokKind::BlockStr(full) => {
1146                return Ok(Arg::String(crate::command::lower_block_string(full), true));
1147            }
1148            _ => {}
1149        }
1150    }
1151    if region.len() > 1
1152        && matches!(&region[0].kind, TokKind::Str { .. } | TokKind::BlockStr(_))
1153        && region[1].joint
1154    {
1155        return Err(TokenError {
1156            stmt,
1157            msg: "unexpected text after quoted value".to_string(),
1158            line: 0,
1159            col: 0,
1160            kind: None,
1161        });
1162    }
1163    // Single-quoted values mid-line (`K='a b'`): the string lexer only
1164    // opens `'` gapped, so these arrive as fragments; the grammar's
1165    // `quoted_string` admits them anywhere. Reassemble a region that
1166    // opens with `'` and closes at its end, stripping exactly like a
1167    // structural string (escapes intact for runtime, like `Str`).
1168    if matches!(&region[0].kind, TokKind::Punct('\''))
1169        && let Some(text) = try_squote_value(region)
1170    {
1171        return Ok(Arg::String(text, true));
1172    }
1173    // Lone typed values apply only at a true end/boundary, never
1174    // past a comment (the grammar's `!assign_expr_cont` guard).
1175    if lone_ok && let Some(expr) = try_lone_value_expr(region, stmt, ctx)? {
1176        return Ok(expr);
1177    }
1178    Ok(Arg::String(render_raw_text(region, stmt)?, false))
1179}
1180
1181/// Reassemble a single-quoted assignment value (`K='a b'`) from its
1182/// lexer fragments: the opener must close at the region end (a
1183/// trailing fragment falls back to raw text, which fails downstream
1184/// like the grammar). Inner gaps join with one space and nested
1185/// double quotes re-quote (the atomic span keeps them); `\'` escapes
1186/// pass through intact for runtime, like structural strings. `None`
1187/// on shape miss.
1188fn try_squote_value(region: &[Tok]) -> Option<String> {
1189    // Closing `'`: first unescaped quote past the opener.
1190    let mut close = None;
1191    let mut i = 1;
1192    while i < region.len() {
1193        match &region[i].kind {
1194            TokKind::Punct('\\') => i += 2,
1195            TokKind::Punct('\'') => {
1196                close = Some(i);
1197                break;
1198            }
1199            _ => i += 1,
1200        }
1201    }
1202    if close != Some(region.len() - 1) {
1203        return None;
1204    }
1205    let mut out = String::new();
1206    for tok in &region[1..region.len() - 1] {
1207        if !tok.joint && !out.is_empty() {
1208            out.push(' ');
1209        }
1210        match &tok.kind {
1211            TokKind::Word(w) => out.push_str(w),
1212            TokKind::Punct(c) => out.push(*c),
1213            TokKind::Semicolon => out.push(';'),
1214            // Nested double quotes keep their marks (the atomic span
1215            // never strips them); triple quotes pass through whole.
1216            TokKind::Str { text, quote } => {
1217                out.push(*quote);
1218                out.push_str(text);
1219                out.push(*quote);
1220            }
1221            TokKind::BlockStr(full) => out.push_str(full),
1222            // Groups and newlines never occur in value regions (the
1223            // splitter owns them); anything else breaks the shape.
1224            _ => return None,
1225        }
1226    }
1227    Some(out)
1228}
1229
1230/// Lone assignable shapes (`assign_expr` without continuation): `$var`,
1231/// key paths, `env:KEY`, and full-region calls (resolved). Anything
1232/// longer renders raw; the caller decides strictness.
1233fn try_lone_value_expr(
1234    region: &[Tok],
1235    stmt: usize,
1236    ctx: &ParseCtx,
1237) -> Result<Option<Arg>, TokenError> {
1238    // `$` shapes: exactly Punct+Word or dotted runs, all joint past
1239    // the first (the region starts at an argument start by construction).
1240    if matches!(region.first().map(|t| &t.kind), Some(TokKind::Punct('$'))) {
1241        let mut cur = Cursor::expr(region, stmt);
1242        cur.pos += 1;
1243        let base = match cur.next() {
1244            Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
1245                match &t.kind {
1246                    TokKind::Word(w) => w.clone(),
1247                    _ => unreachable!(),
1248                }
1249            }
1250            _ => return Ok(None),
1251        };
1252        let mut keys = Vec::new();
1253        loop {
1254            let dot = matches!(
1255                cur.toks.get(cur.pos).map(|t| &t.kind),
1256                Some(TokKind::Punct('.'))
1257            ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
1258            let seg = cur.toks.get(cur.pos + 1);
1259            let seg_ok = dot
1260                && matches!(seg.map(|t| &t.kind), Some(TokKind::Word(w)) if is_key_segment(w))
1261                && seg.is_some_and(|t| t.joint);
1262            if !seg_ok {
1263                break;
1264            }
1265            if let Some(TokKind::Word(w)) = seg.map(|t| &t.kind) {
1266                keys.push(w.clone());
1267            }
1268            cur.pos += 2;
1269        }
1270        if cur.pos != region.len() {
1271            return Ok(None);
1272        }
1273        return Ok(Some(Arg::Expr(if keys.is_empty() {
1274            Expr::Var(base)
1275        } else {
1276            Expr::KeyPath { base, keys }
1277        })));
1278    }
1279    // `env:KEY` read, gapless and exact.
1280    if region.len() == 3
1281        && matches!(&region[0].kind, TokKind::Word(w) if w == "env")
1282        && matches!(&region[1].kind, TokKind::Punct(':'))
1283        && region[1].joint
1284        && let TokKind::Word(k) = &region[2].kind
1285        && is_env_key(k)
1286        && region[2].joint
1287    {
1288        return Ok(Some(Arg::Expr(Expr::Env(k.clone()))));
1289    }
1290    // Full-region call: resolve and keep typed (canonical rendering
1291    // happens per command: verbatim for ENV/EXPAND, `K=`-joined text
1292    // elsewhere, all from the same `Arg::Expr`).
1293    if let Some((name, paren)) = call_shape_at(region, 0, false)
1294        && paren + 1 == region.len()
1295        && let TokKind::Group { inner, .. } = &region[paren].kind
1296    {
1297        let inner = inner.clone();
1298        let args = parse_call_args(&inner, stmt, ctx)?;
1299        if name == KEYWORD_INSPECT {
1300            let [arg] = args.as_slice() else {
1301                return Err(TokenError {
1302                    stmt,
1303                    msg: "INSPECT requires exactly one argument: INSPECT($var)".to_string(),
1304                    line: 0,
1305                    col: 0,
1306                    kind: None,
1307                });
1308            };
1309            if let Expr::Var(var) = arg {
1310                return Ok(Some(Arg::Expr(Expr::Inspect(var.clone()))));
1311            }
1312            return Err(TokenError {
1313                stmt,
1314                msg: format!("INSPECT requires a $variable argument, found {arg:?}"),
1315                line: 0,
1316                col: 0,
1317                kind: None,
1318            });
1319        }
1320        let qualified = resolve_name(ctx, stmt, &name)?;
1321        return Ok(Some(Arg::Expr(Expr::Call {
1322            name: qualified,
1323            args,
1324        })));
1325    }
1326    Ok(None)
1327}
1328
1329/// Expression extension for `$`/`env:`-led argument starts: parse a
1330/// full expression (operators reach across gaps exactly like the
1331/// grammar's inner `gap`s). Ending at a gap/end yields a typed single
1332/// group; ending mid-run falls back to raw text of the run (`$x=K`);
1333/// parse failure is fatal (every fragment alternative failed).
1334/// Returns the arg and tokens consumed.
1335fn try_expr_arg(
1336    toks: &[Tok],
1337    pos: usize,
1338    stmt: usize,
1339    ctx: &ParseCtx,
1340) -> Result<Option<(Arg, usize)>, TokenError> {
1341    let extend = matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('$')))
1342        || matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == "env");
1343    if !extend {
1344        return Ok(None);
1345    }
1346    // A bare `env` head only extends into a real `env:KEY` read (joint
1347    // `:`); dotted bare words (`env.txt`) stay raw strings like the
1348    // grammar's `unquoted_arg`, which precedes `expr`.
1349    if matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == "env")
1350        && !matches!(
1351            (
1352                toks.get(pos + 1).map(|t| &t.kind),
1353                toks.get(pos + 1).map(|t| t.joint)
1354            ),
1355            (Some(TokKind::Punct(':')), Some(true))
1356        )
1357    {
1358        return Ok(None);
1359    }
1360    let mut cur = Cursor::expr(&toks[pos..], stmt);
1361    let expr = parse_expr_or(&mut cur, ctx)?;
1362    let end = pos + cur.pos;
1363    // Mid-run stop (joint follower): the whole run renders raw
1364    // (`$x=K`, `$a$b`); the run always ends the fallback span here
1365    // because extension starts groups.
1366    if toks.get(end).is_some_and(|t| t.joint) {
1367        let mut run_end = end;
1368        while toks.get(run_end).is_some_and(|t| t.joint) {
1369            run_end += 1;
1370        }
1371        let text = render_raw_text(&toks[pos..run_end], stmt)?;
1372        return Ok(Some((Arg::String(text, false), run_end - pos)));
1373    }
1374    Ok(Some((Arg::Expr(expr), end - pos)))
1375}
1376
1377/// Render a brace group inside raw text (`{{..}}` templates and
1378/// mid-run `{..}` shapes): verbatim bytes, single-space-normalized
1379/// gaps. Run-start non-template braces never reach here (they parse
1380/// as maps/blocks in `build_arg_tokens`).
1381fn render_brace_run_text(inner: &[Tok], open_joint: bool, close_joint: bool) -> String {
1382    render_group('{', '}', inner, open_joint, close_joint)
1383}
1384
1385/// Inner bytes of a fully-quoted word (`"hi"`, `'a'`): the re-quoted
1386/// standalone strings spliced from groups strip exactly like
1387/// structural ones. Triple-quote pieces never qualify (block lowering
1388/// owns them); glued quotes (`['a`) never reach here as sole runs.
1389fn quoted_word_inner(w: &str) -> Option<String> {
1390    if w.len() >= 2 && !w.starts_with("\"\"\"") {
1391        let q = w.as_bytes()[0] as char;
1392        if (q == '"' || q == '\'') && w.ends_with(q) {
1393            return Some(w[1..w.len() - 1].to_string());
1394        }
1395    }
1396    None
1397}
1398
1399/// Build instruction tokens over generic args, mirroring
1400/// `assignment | argument` order at every argument start: assignments
1401/// merge across gaps to the next boundary, `$`/`env:`-led runs extend
1402/// as expressions, brace-led runs try templates then maps/blocks, and
1403/// everything else renders raw. Single quoted strings keep their flag.
1404fn build_arg_tokens(
1405    toks: &[Tok],
1406    stmt: usize,
1407    ctx: &ParseCtx,
1408) -> Result<Vec<InsToken>, TokenError> {
1409    // Splice bracket/paren groups first: they read as ordinary
1410    // characters (whitespace splits inside them), with strings
1411    // re-quoted back to word text. Brace groups stay structural
1412    // (templates render whole; blocks parse as expressions).
1413    let flat = splice_arg_groups(toks, stmt)?;
1414    let mut out = Vec::new();
1415    let mut pos = 0;
1416    while pos < flat.len() {
1417        // 1. Assignment: key run plus `=` at any gap.
1418        if let Some((key, key_end)) = match_assign_key(&flat, pos)
1419            && let Some(tok) = flat.get(key_end)
1420            && matches!(&tok.kind, TokKind::Punct('='))
1421        {
1422            // Value runs to the next boundary, but raw text also
1423            // stops at `//` / `/*` (raw-text rule):
1424            // a line comment swallows the rest silently, a block
1425            // comment must be followed by nothing or a boundary
1426            // (anything else strands text and fails the line, like
1427            // the grammar). Lone typed values (`$x`, calls) apply
1428            // only at a true end/boundary, never past a comment
1429            // (the grammar's `!assign_expr_cont` guard).
1430            let mut vend = key_end + 1;
1431            let mut lone_ok = true;
1432            let mut failed: Option<String> = None;
1433            'scan: while vend < flat.len() {
1434                if !flat[vend].joint && at_assign_boundary(&flat, vend) {
1435                    break;
1436                }
1437                // Lexer comment markers end the raw span like `//`
1438                // (they run to end of line by construction).
1439                if matches!(&flat[vend].kind, TokKind::Comment(_)) {
1440                    lone_ok = false;
1441                    vend = flat.len();
1442                    break;
1443                }
1444                if matches!(&flat[vend].kind, TokKind::Punct('/')) && is_comment_open(&flat, vend) {
1445                    // Comments end the raw span: line comments eat
1446                    // the rest silently, block comments must be
1447                    // followed by nothing, a boundary, or more
1448                    // comments (stranded text fails the line, like
1449                    // the grammar).
1450                    lone_ok = false;
1451                    loop {
1452                        if vend >= flat.len()
1453                            || (!flat[vend].joint && at_assign_boundary(&flat, vend))
1454                        {
1455                            break 'scan;
1456                        }
1457                        if !matches!(&flat[vend].kind, TokKind::Punct('/'))
1458                            || !is_comment_open(&flat, vend)
1459                        {
1460                            failed = Some("unexpected text after assignment value".to_string());
1461                            break 'scan;
1462                        }
1463                        if matches!(
1464                            flat.get(vend + 1).map(|t| &t.kind),
1465                            Some(TokKind::Punct('/'))
1466                        ) {
1467                            vend = flat.len();
1468                            break 'scan;
1469                        }
1470                        match skip_inline_comment(&flat, vend) {
1471                            None => {
1472                                failed = Some("unclosed block comment".to_string());
1473                                break 'scan;
1474                            }
1475                            Some(past) => vend = past,
1476                        }
1477                    }
1478                }
1479                vend += 1;
1480            }
1481            if let Some(msg) = failed {
1482                return Err(TokenError {
1483                    stmt,
1484                    msg,
1485                    line: 0,
1486                    col: 0,
1487                    kind: None,
1488                });
1489            }
1490            let value = build_value_arg(&flat[key_end + 1..vend], stmt, ctx, lone_ok)?;
1491            out.push(InsToken::Assign(key, value));
1492            pos = vend;
1493            continue;
1494        }
1495        // 2. Brace-led run: template text, else map/block expression.
1496        if matches!(
1497            flat.get(pos).map(|t| &t.kind),
1498            Some(TokKind::Group {
1499                delim: GroupDelim::Brace,
1500                ..
1501            })
1502        ) {
1503            let mut run_end = pos + 1;
1504            while flat.get(run_end).is_some_and(|t| t.joint) {
1505                run_end += 1;
1506            }
1507            let run = &flat[pos..run_end];
1508            let is_template = is_template_brace(&run[0]);
1509            if is_template {
1510                out.push(InsToken::Pos(Arg::String(
1511                    render_raw_text(run, stmt)?,
1512                    false,
1513                )));
1514            } else {
1515                let inner = match &run[0].kind {
1516                    TokKind::Group { inner, .. } => inner.clone(),
1517                    _ => unreachable!(),
1518                };
1519                // Map success alone stays typed; map success with a
1520                // joint tail renders raw (`{k:1}x`, like the grammar's
1521                // mixed fragments); map failure defers/errors exactly
1522                // like the expression path.
1523                match parse_map_or_block(&inner, stmt, ctx) {
1524                    Ok(expr) if run.len() == 1 => {
1525                        out.push(InsToken::Pos(Arg::Expr(expr)));
1526                    }
1527                    Ok(_) => out.push(InsToken::Pos(Arg::String(
1528                        render_raw_text(run, stmt)?,
1529                        false,
1530                    ))),
1531                    Err(e) => return Err(e),
1532                }
1533            }
1534            pos = run_end;
1535            continue;
1536        }
1537        // 3. `$`/`env:`-led expression extension.
1538        if let Some((arg, used)) = try_expr_arg(&flat, pos, stmt, ctx)? {
1539            // A lone expression group stays typed; the fallback
1540            // already rendered text above.
1541            out.push(InsToken::Pos(arg));
1542            pos += used;
1543            continue;
1544        }
1545        // 4. Raw text run to the next gap.
1546        let mut run_end = pos + 1;
1547        while flat.get(run_end).is_some_and(|t| t.joint) {
1548            run_end += 1;
1549        }
1550        let run = &flat[pos..run_end];
1551        // Slash-pair-led runs (`/*c*/`; `//` arrives as `Comment`
1552        // toks) parse as expression fragments (typed when single,
1553        // glued verbatim otherwise).
1554        if is_slash_run(run) {
1555            out.push(InsToken::Pos(parse_slash_run(run, stmt, ctx)?));
1556            pos = run_end;
1557            continue;
1558        }
1559        // Trailing `Comment` (`//` to end of line) glues as a
1560        // literal fragment (typed when alone, verbatim otherwise),
1561        // exactly like the grammar's expression fragments.
1562        if let Some(TokKind::Comment(text)) = run.last().map(|t| &t.kind) {
1563            if run.len() == 1 {
1564                out.push(InsToken::Pos(Arg::Expr(Expr::Literal(Value::string(
1565                    text.clone(),
1566                )))));
1567            } else {
1568                let mut bytes = render_raw_text(&run[..run.len() - 1], stmt)?;
1569                bytes.push_str(text);
1570                out.push(InsToken::Pos(Arg::String(bytes, false)));
1571            }
1572            pos = run_end;
1573            continue;
1574        }
1575        if run.len() == 1 {
1576            match &run[0].kind {
1577                TokKind::Str { text: s, .. } => {
1578                    out.push(InsToken::Pos(Arg::String(s.clone(), true)));
1579                    pos = run_end;
1580                    continue;
1581                }
1582                TokKind::BlockStr(full) => {
1583                    out.push(InsToken::Pos(Arg::String(
1584                        crate::command::lower_block_string(full),
1585                        true,
1586                    )));
1587                    pos = run_end;
1588                    continue;
1589                }
1590                // Re-quoted standalone strings (spliced from groups)
1591                // strip exactly like structural ones (`( "hi" )` gives
1592                // `hi`); glued quotes stay literal (`['a` keeps its
1593                // mark). Triple-quote pieces never qualify.
1594                TokKind::Word(w) if quoted_word_inner(w).is_some() => {
1595                    out.push(InsToken::Pos(Arg::String(
1596                        quoted_word_inner(w).unwrap(),
1597                        true,
1598                    )));
1599                    pos = run_end;
1600                    continue;
1601                }
1602                _ => {}
1603            }
1604        }
1605        out.push(InsToken::Pos(Arg::String(
1606            render_raw_text(run, stmt)?,
1607            false,
1608        )));
1609        pos = run_end;
1610    }
1611    Ok(out)
1612}
1613
1614/// A raw run starting with `//` or `/*` (a slash-pair: `/` plus a
1615/// joint `/` or `*`) parses as expression fragments: both route to
1616/// `expr` there (so `//c` types as a literal and `/*c*/` as math). A single
1617/// fully-consuming expression stays typed; anything longer glues to
1618/// verbatim text exactly like the grammar's mixed fragments (byte
1619/// for byte, since joint runs admit no span gaps). An unparseable
1620/// unterminated block open (`/*` with no `*/` in the run) reads
1621/// literally like the old backend (`ECHO /*`, `[a /* c]`); a
1622/// terminated span keeps the loud failure.
1623fn parse_slash_run(run: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Arg, TokenError> {
1624    let mut cur = Cursor::expr(run, stmt);
1625    match parse_expr_checked(&mut cur, ctx) {
1626        Ok(expr) if cur.done() => Ok(Arg::Expr(expr)),
1627        Ok(_) => Ok(Arg::String(render_raw_text(run, stmt)?, false)),
1628        Err(_) if !run_has_block_close(run) => Ok(Arg::String(render_raw_text(run, stmt)?, false)),
1629        Err(e) => Err(e),
1630    }
1631}
1632
1633/// True when the run holds a `*/` close pair (`*` plus a joint `/`),
1634/// mirroring [`skip_inline_comment`]'s terminator: only unterminated
1635/// block opens read literally.
1636fn run_has_block_close(run: &[Tok]) -> bool {
1637    run.windows(2).any(|w| {
1638        matches!(&w[0].kind, TokKind::Punct('*'))
1639            && matches!(&w[1].kind, TokKind::Punct('/'))
1640            && w[1].joint
1641    })
1642}
1643
1644/// True when a raw run opens with a slash-pair (`/` plus a joint
1645/// `/` or `*`), routing it to expression fragments (see
1646/// [`parse_slash_run`]). A lone `/` (`/a`, `/`) stays raw text.
1647fn is_slash_run(run: &[Tok]) -> bool {
1648    matches!(run.first().map(|t| &t.kind), Some(TokKind::Punct('/')))
1649        && matches!(
1650            run.get(1).map(|t| (&t.kind, t.joint)),
1651            Some((TokKind::Punct('/'), true)) | Some((TokKind::Punct('*'), true))
1652        )
1653}
1654
1655/// Lower generic args through the shared cores: `ENV`/`EXPAND` bypass
1656/// the injected dispatcher; everything else
1657/// canonicalizes assignments and calls it.
1658fn lower_generic_args(
1659    name: &str,
1660    tokens: Vec<InsToken>,
1661    stmt: usize,
1662    ctx: &ParseCtx,
1663) -> Result<StepKind, TokenError> {
1664    if name == KEYWORD_ENV {
1665        return lower_env_tokens(&lowering_ctx(stmt), tokens).map_err(|e| TokenError {
1666            stmt,
1667            msg: e.to_string(),
1668            line: 0,
1669            col: 0,
1670            kind: None,
1671        });
1672    }
1673    if name == KEYWORD_EXPAND {
1674        return lower_expand_tokens(&lowering_ctx(stmt), tokens).map_err(|e| TokenError {
1675            stmt,
1676            msg: e.to_string(),
1677            line: 0,
1678            col: 0,
1679            kind: None,
1680        });
1681    }
1682    let args = tokens
1683        .into_iter()
1684        .map(|token| match token {
1685            InsToken::Pos(arg) => arg,
1686            InsToken::Assign(key, value) => canonical_assignment_arg(&key, &value),
1687        })
1688        .collect();
1689    (ctx.lower)(name, args).map_err(|e| lower_err(stmt, e))
1690}
1691
1692/// Render a bracket/paren/brace group back to source text for raw-text
1693/// positions (in-body groups are args, template braces render whole).
1694/// Fragments join with a space on gaps and glue on `joint`, so both
1695/// lexers render the same source identically; quote styles round-trip
1696/// exactly. Known normalization (documented, not silent): multi-space
1697/// gaps collapse to one.
1698fn render_group(
1699    open: char,
1700    close: char,
1701    inner: &[Tok],
1702    open_joint: bool,
1703    close_joint: bool,
1704) -> String {
1705    let mut out = String::from(open);
1706    if !open_joint && !inner.is_empty() {
1707        out.push(' ');
1708    }
1709    let mut first = true;
1710    for tok in inner {
1711        match &tok.kind {
1712            TokKind::Newline => out.push('\n'),
1713            TokKind::Semicolon => out.push(';'),
1714            // Comments reproduce verbatim (templates keep comment
1715            // text like the atomic grammar span); like newlines they
1716            // carry their own separation, never a synthetic space.
1717            TokKind::Comment(text) => out.push_str(text),
1718            _ => {
1719                if !first && !tok.joint {
1720                    out.push(' ');
1721                }
1722                match &tok.kind {
1723                    TokKind::Word(w) => out.push_str(w),
1724                    TokKind::Punct(c) => out.push(*c),
1725                    TokKind::Str { text, quote } => {
1726                        out.push(*quote);
1727                        out.push_str(text);
1728                        out.push(*quote);
1729                    }
1730                    TokKind::BlockStr(full) => out.push_str(full),
1731                    TokKind::Group {
1732                        delim: GroupDelim::Bracket,
1733                        inner,
1734                        open_joint,
1735                        close_joint,
1736                        ..
1737                    } => out.push_str(&render_group('[', ']', inner, *open_joint, *close_joint)),
1738                    TokKind::Group {
1739                        delim: GroupDelim::Paren,
1740                        inner,
1741                        open_joint,
1742                        close_joint,
1743                        ..
1744                    } => out.push_str(&render_group('(', ')', inner, *open_joint, *close_joint)),
1745                    TokKind::Group {
1746                        delim: GroupDelim::Brace,
1747                        inner,
1748                        open_joint,
1749                        close_joint,
1750                        ..
1751                    } => out.push_str(&render_group('{', '}', inner, *open_joint, *close_joint)),
1752                    // Comments reproduce verbatim (nested groups keep
1753                    // comment text like the atomic grammar span).
1754                    TokKind::Comment(text) => out.push_str(text),
1755                    TokKind::Newline | TokKind::Semicolon => unreachable!(),
1756                }
1757            }
1758        }
1759        first = false;
1760    }
1761    if !close_joint && !inner.is_empty() {
1762        out.push(' ');
1763    }
1764    out.push(close);
1765    out
1766}
1767
1768/// Positional cursor over guard/group token slices. Newlines skip
1769/// freely between tokens (`ws` admits linebreaks in the grammar);
1770/// bare key/value runs never cross them (the grammar excludes
1771/// linebreaks there), so runs read raw.
1772///
1773/// Expression parsing reuses this cursor with `nl_skip = false`:
1774/// expressions are single-line (`gap`, never `gap_nl`, between
1775/// operands), so a newline terminates instead of vanishing. Newlines
1776/// inside group inners (call args, lists, maps) skip via explicit
1777/// `skip_newlines` calls at the grammar's `gap_nl` junctures.
1778struct Cursor<'t> {
1779    toks: &'t [Tok],
1780    pos: usize,
1781    stmt: usize,
1782    nl_skip: bool,
1783}
1784
1785impl<'t> Cursor<'t> {
1786    fn new(toks: &'t [Tok], stmt: usize) -> Self {
1787        Self {
1788            toks,
1789            pos: 0,
1790            stmt,
1791            nl_skip: true,
1792        }
1793    }
1794
1795    /// Expression-mode cursor: newlines stop, never skip.
1796    fn expr(toks: &'t [Tok], stmt: usize) -> Self {
1797        Self {
1798            toks,
1799            pos: 0,
1800            stmt,
1801            nl_skip: false,
1802        }
1803    }
1804
1805    fn err(&self, msg: impl Into<String>) -> TokenError {
1806        TokenError {
1807            stmt: self.stmt,
1808            line: 0,
1809            col: 0,
1810            msg: msg.into(),
1811            kind: None,
1812        }
1813    }
1814
1815    fn skip_newlines(&mut self) {
1816        while matches!(
1817            self.toks.get(self.pos).map(|t| &t.kind),
1818            Some(TokKind::Newline)
1819        ) {
1820            self.pos += 1;
1821        }
1822    }
1823
1824    fn peek(&mut self) -> Option<&'t Tok> {
1825        if self.nl_skip {
1826            self.skip_newlines();
1827        }
1828        self.toks.get(self.pos)
1829    }
1830
1831    fn next(&mut self) -> Option<&'t Tok> {
1832        if self.nl_skip {
1833            self.skip_newlines();
1834        }
1835        let t = self.toks.get(self.pos)?;
1836        self.pos += 1;
1837        Some(t)
1838    }
1839
1840    fn done(&mut self) -> bool {
1841        if self.nl_skip {
1842            self.skip_newlines();
1843        }
1844        self.pos >= self.toks.len()
1845    }
1846
1847    fn eat_punct(&mut self, c: char) -> bool {
1848        if self.nl_skip {
1849            self.skip_newlines();
1850        }
1851        match self.peek() {
1852            Some(t) if matches!(&t.kind, TokKind::Punct(p) if *p == c) => {
1853                self.pos += 1;
1854                true
1855            }
1856            _ => false,
1857        }
1858    }
1859
1860    /// Skip one gap's worth of comments (`gap`: `//`-to-newline,
1861    /// balanced `/* */` even across newlines, `#`-to-newline —
1862    /// never a standalone newline, which ends single-line
1863    /// expressions. Greedy gap before operators and operands; whitespace itself is
1864    /// already invisible in the token stream.
1865    fn skip_gap(&mut self) {
1866        loop {
1867            match self.toks.get(self.pos).map(|t| &t.kind) {
1868                Some(TokKind::Comment(_)) => {
1869                    self.pos += 1;
1870                }
1871                Some(TokKind::Punct('/')) if is_comment_open(self.toks, self.pos) => {
1872                    match skip_inline_comment(self.toks, self.pos) {
1873                        Some(next) => self.pos = next,
1874                        // Unclosed block comments fail the gap (and
1875                        // the enclosing rule) like the grammar.
1876                        None => break,
1877                    }
1878                }
1879                Some(TokKind::Punct('#')) => {
1880                    while self.pos < self.toks.len()
1881                        && !matches!(&self.toks[self.pos].kind, TokKind::Newline)
1882                    {
1883                        self.pos += 1;
1884                    }
1885                }
1886                _ => break,
1887            }
1888        }
1889    }
1890
1891    /// Skip gap comments plus standalone newlines (`gap_nl`: call
1892    /// args, list items, maps, parenthesized expressions).
1893    fn skip_gap_nl(&mut self) {
1894        loop {
1895            match self.toks.get(self.pos).map(|t| &t.kind) {
1896                Some(TokKind::Newline) => {
1897                    self.pos += 1;
1898                }
1899                _ => {
1900                    let before = self.pos;
1901                    self.skip_gap();
1902                    if self.pos == before {
1903                        break;
1904                    }
1905                }
1906            }
1907        }
1908    }
1909
1910    /// Consume the parenthesized group following a call word (`not`,
1911    /// `any`, `all`, `eq`, `ne`), ignoring gap width exactly like the
1912    /// grammar's implicit whitespace.
1913    fn eat_paren_group(&mut self) -> Option<Vec<Tok>> {
1914        match self.peek() {
1915            Some(t) => match &t.kind {
1916                TokKind::Group {
1917                    delim: GroupDelim::Paren,
1918                    inner,
1919                    ..
1920                } => {
1921                    let inner = inner.clone();
1922                    self.pos += 1;
1923                    Some(inner)
1924                }
1925                _ => None,
1926            },
1927            None => None,
1928        }
1929    }
1930}
1931
1932/// Split a flat token slice on top-level commas (nesting lives inside
1933/// atomic groups, so a flat scan is exact).
1934fn split_top_commas(toks: &[Tok]) -> Vec<&[Tok]> {
1935    let mut parts = Vec::new();
1936    let mut start = 0;
1937    for (i, t) in toks.iter().enumerate() {
1938        if matches!(&t.kind, TokKind::Punct(',')) {
1939            parts.push(&toks[start..i]);
1940            start = i + 1;
1941        }
1942    }
1943    parts.push(&toks[start..]);
1944    parts
1945}
1946
1947/// Punctuation admissible inside bare guard key runs: everything but
1948/// the terminators the parser enforces separately. `;` arrives as its
1949/// own token kind; the key charset admits it, so runs accept it literally.
1950fn key_char(c: char) -> bool {
1951    !matches!(c, ':' | '=' | '!' | ',' | '|' | '(' | ')' | ']' | '$')
1952}
1953
1954/// Consume a joint run of words/punctuation as one bare key or value.
1955/// Gaps end the run; terminators and groups end or fail it per `extra`.
1956fn bare_run(cur: &mut Cursor, extra: fn(char) -> bool, what: &str) -> Result<String, TokenError> {
1957    let mut out = String::new();
1958    loop {
1959        let tok = match cur.toks.get(cur.pos) {
1960            Some(t) if matches!(&t.kind, TokKind::Newline) => break,
1961            Some(t) => t,
1962            None => break,
1963        };
1964        // First element may follow a gap; continuations must be gapless.
1965        if !out.is_empty() && !tok.joint {
1966            break;
1967        }
1968        match &tok.kind {
1969            TokKind::Word(w) => out.push_str(w),
1970            TokKind::Punct(c) if key_char(*c) && extra(*c) => out.push(*c),
1971            TokKind::Semicolon if extra(';') => out.push(';'),
1972            _ => break,
1973        }
1974        cur.pos += 1;
1975    }
1976    if out.is_empty() {
1977        return Err(cur.err(format!("missing {what}")));
1978    }
1979    Ok(out)
1980}
1981
1982/// The `guard_term` negative lookahead: a complete term followed by
1983/// `(`, `:`, `=`, or `!` is malformed, never a longer form.
1984fn check_term_end(cur: &mut Cursor) -> Result<(), TokenError> {
1985    cur.skip_newlines();
1986    match cur.toks.get(cur.pos) {
1987        Some(t) => match &t.kind {
1988            TokKind::Group {
1989                delim: GroupDelim::Paren,
1990                ..
1991            } => Err(cur.err("unexpected `(` after guard term")),
1992            TokKind::Punct(c) if matches!(c, ':' | '=' | '!') => {
1993                Err(cur.err(format!("unexpected `{c}` after guard term")))
1994            }
1995            _ => Ok(()),
1996        },
1997        None => Ok(()),
1998    }
1999}
2000
2001fn os_guard(value: &str) -> GuardExpr {
2002    GuardExpr::Predicate(Guard::Attr {
2003        ns: Ns::Os,
2004        key: None,
2005        val: Some(value.to_string()),
2006    })
2007}
2008
2009/// Namespace validation for guard predicates with closed domains
2010/// (`family`, `os`, `arch`); open namespaces pass through.
2011fn ns_guard(ns: &str, val: &str, cur: &Cursor) -> Result<GuardExpr, TokenError> {
2012    match ns {
2013        "family" => match val {
2014            "unix" => Ok(GuardExpr::or(vec![os_guard("macos"), os_guard("linux")])),
2015            "windows" => Ok(os_guard("windows")),
2016            _ => Err(cur.err(format!(
2017                "unknown family '{val}'; known values: unix, windows"
2018            ))),
2019        },
2020        "os" => match val {
2021            "macos" | "linux" | "windows" => Ok(os_guard(val)),
2022            _ => Err(cur.err(format!(
2023                "unknown os '{val}'; known values: macos, linux, windows"
2024            ))),
2025        },
2026        "arch" => {
2027            if crate::ARCH_VALUES.contains(&val) {
2028                Ok(GuardExpr::Predicate(Guard::Attr {
2029                    ns: Ns::Arch,
2030                    key: None,
2031                    val: Some(val.to_string()),
2032                }))
2033            } else {
2034                Err(cur.err(format!(
2035                    "unknown arch '{val}'; known values: {}",
2036                    crate::ARCH_VALUES.join(", ")
2037                )))
2038            }
2039        }
2040        _ => Err(cur.err(format!(
2041            "unknown guard namespace '{ns}'; known namespaces: family, os, arch, env, bool"
2042        ))),
2043    }
2044}
2045
2046fn parse_guard_term(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2047    let tok = cur
2048        .next()
2049        .ok_or_else(|| cur.err("missing guard predicate"))?;
2050    // A `!` prefix is never negation in guards (only `not(...)` negates).
2051    if matches!(&tok.kind, TokKind::Punct('!')) {
2052        return Err(cur.err("unexpected `!` in guard; negation uses `not(...)`"));
2053    }
2054    let word = match &tok.kind {
2055        TokKind::Word(w) => w.clone(),
2056        _ => return Err(cur.err("missing guard predicate")),
2057    };
2058    // `__OXDOCK_INJECT_N__` interpolation placeholder: env-key shape.
2059    if let Some(rest) = word.strip_prefix(INJECT_PREFIX) {
2060        if !rest.is_empty()
2061            && rest
2062                .strip_suffix(INJECT_SUFFIX)
2063                .is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()))
2064        {
2065            return Ok(GuardExpr::Predicate(Guard::Attr {
2066                ns: Ns::Env,
2067                key: Some(word),
2068                val: None,
2069            }));
2070        }
2071        return Err(cur.err("missing guard predicate"));
2072    }
2073    match word.as_str() {
2074        "eq" | "ne" => {
2075            let inner = cur
2076                .eat_paren_group()
2077                .ok_or_else(|| cur.err(format!("`{word}` requires `(env:KEY, value)`")))?;
2078            let mut arg = Cursor::new(&inner, cur.stmt);
2079            if arg.next().map(|t| &t.kind) != Some(&TokKind::Word("env".to_string())) {
2080                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2081            }
2082            if !arg.eat_punct(':') {
2083                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2084            }
2085            let key = bare_run(&mut arg, |_| true, "guard key")?;
2086            if !arg.eat_punct(',') {
2087                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2088            }
2089            arg.skip_newlines();
2090            let value = match arg.next() {
2091                Some(t) => match &t.kind {
2092                    TokKind::Str { text, .. } => text.clone(),
2093                    TokKind::BlockStr(full) => crate::command::lower_block_string(full),
2094                    _ => {
2095                        // Bare value: runs to the region end (commas and
2096                        // groups terminate it with an error, matching the
2097                        // bare-value exclusions).
2098                        arg.pos -= 1;
2099                        value_run(&mut arg)?
2100                    }
2101                },
2102                None => return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`"))),
2103            };
2104            if !arg.done() {
2105                return Err(arg.err(format!("unexpected text after `{word}` value")));
2106            }
2107            let pred = GuardExpr::Predicate(Guard::Attr {
2108                ns: Ns::Env,
2109                key: Some(key),
2110                val: Some(value),
2111            });
2112            if word == "ne" {
2113                Ok(GuardExpr::Not(Box::new(pred)))
2114            } else {
2115                Ok(pred)
2116            }
2117        }
2118        "bool" => {
2119            if !cur.eat_punct(':') {
2120                return Err(cur.err("`bool` requires `:value`"));
2121            }
2122            let val = bare_run(cur, |_| true, "bool value")?;
2123            check_term_end(cur)?;
2124            Ok(GuardExpr::Predicate(Guard::Attr {
2125                ns: Ns::Bool,
2126                key: None,
2127                val: Some(val),
2128            }))
2129        }
2130        "env" => {
2131            if !cur.eat_punct(':') {
2132                return Err(cur.err("`env` requires `:KEY`"));
2133            }
2134            let key = bare_run(cur, |_| true, "guard key")?;
2135            check_term_end(cur)?;
2136            Ok(GuardExpr::Predicate(Guard::Attr {
2137                ns: Ns::Env,
2138                key: Some(key),
2139                val: None,
2140            }))
2141        }
2142        _ => {
2143            if !cur.eat_punct(':') {
2144                return Err(cur.err("missing guard predicate"));
2145            }
2146            let val = bare_run(cur, |_| true, "guard value")?;
2147            check_term_end(cur)?;
2148            ns_guard(&word, &val, cur)
2149        }
2150    }
2151}
2152
2153/// Bare `eq`/`ne` value run: key charset plus `:`/`=`/`!` (the grammar
2154/// admits them in values, never in keys), with nested groups rendered
2155/// for the pathological `(`-in-value shape. `$`, `|`, `,` terminate
2156/// with an error downstream.
2157/// Bare `eq`/`ne` value with atomic bare-value semantics:
2158/// everything except `, | ) ] $`, linebreaks, and comment opens —
2159/// gaps included (joined with one space; the token stream cannot
2160/// preserve gap width). Quotes ride literally mid-run (the atomic
2161/// span keeps them); a *leading* quote never reaches here (the
2162/// caller strips it as the `quoted_string` alternative, which then
2163/// requires end-of-region like the grammar's committed choice).
2164fn value_run(arg: &mut Cursor) -> Result<String, TokenError> {
2165    let mut out = String::new();
2166    while let Some(tok) = arg.toks.get(arg.pos) {
2167        // Terminators: the grammar's negative-lookahead set.
2168        match &tok.kind {
2169            TokKind::Newline | TokKind::Comment(_) => break,
2170            TokKind::Punct(',')
2171            | TokKind::Punct('|')
2172            | TokKind::Punct(']')
2173            | TokKind::Punct(')') => break,
2174            TokKind::Punct('$') => break,
2175            TokKind::Punct('/') if is_comment_open(arg.toks, arg.pos) => break,
2176            TokKind::Group { .. } => break,
2177            _ => {}
2178        }
2179        if !out.is_empty() && !tok.joint {
2180            out.push(' ');
2181        }
2182        match &tok.kind {
2183            TokKind::Word(w) => out.push_str(w),
2184            TokKind::Punct(c) => out.push(*c),
2185            TokKind::Semicolon => out.push(';'),
2186            // Mid-run quotes keep their marks, like the atomic span.
2187            TokKind::Str { text, quote } => {
2188                out.push(*quote);
2189                out.push_str(text);
2190                out.push(*quote);
2191            }
2192            TokKind::BlockStr(full) => out.push_str(full),
2193            _ => break,
2194        }
2195        arg.pos += 1;
2196    }
2197    if out.is_empty() {
2198        return Err(arg.err("missing guard value"));
2199    }
2200    Ok(out)
2201}
2202
2203/// True when the cursor sits on `name` followed (over newlines,
2204/// like the grammar's implicit whitespace) by a paren group.
2205fn at_call(cur: &Cursor, name: &str) -> bool {
2206    let mut pos = cur.pos;
2207    // Leading newlines skip (the grammar's implicit whitespace gaps
2208    // multi-line guards, e.g. `[\nnot(env:K)\n]`).
2209    while matches!(cur.toks.get(pos).map(|t| &t.kind), Some(TokKind::Newline)) {
2210        pos += 1;
2211    }
2212    match cur.toks.get(pos) {
2213        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == name) => pos += 1,
2214        _ => return false,
2215    }
2216    while matches!(cur.toks.get(pos).map(|t| &t.kind), Some(TokKind::Newline)) {
2217        pos += 1;
2218    }
2219    matches!(
2220        cur.toks.get(pos).map(|t| &t.kind),
2221        Some(TokKind::Group {
2222            delim: GroupDelim::Paren,
2223            ..
2224        })
2225    )
2226}
2227
2228fn parse_guard_primary(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2229    // Call shapes dispatch on word + paren group regardless of gap
2230    // width (the grammar's implicit whitespace); anything else is a term.
2231    for name in ["not", "any", "all"] {
2232        if at_call(cur, name) {
2233            cur.next();
2234            let inner = cur
2235                .eat_paren_group()
2236                .ok_or_else(|| cur.err("unreachable"))?;
2237            let parts = split_top_commas(&inner);
2238            match name {
2239                "not" => {
2240                    if parts.len() != 1 {
2241                        return Err(cur.err("`not` takes exactly one guard expression"));
2242                    }
2243                    let mut sub = Cursor::new(parts[0], cur.stmt);
2244                    let expr = parse_guard_seq(&mut sub)?;
2245                    if !sub.done() {
2246                        return Err(sub.err("unexpected text in `not`"));
2247                    }
2248                    return Ok(GuardExpr::Not(Box::new(expr)));
2249                }
2250                "any" => {
2251                    if parts.len() < 2 {
2252                        return Err(cur.err("any(...) requires at least two guard expressions"));
2253                    }
2254                    let mut exprs = Vec::new();
2255                    for part in parts {
2256                        let mut sub = Cursor::new(part, cur.stmt);
2257                        exprs.push(parse_guard_seq(&mut sub)?);
2258                        if !sub.done() {
2259                            return Err(sub.err("unexpected text in `any`"));
2260                        }
2261                    }
2262                    return Ok(GuardExpr::or(exprs));
2263                }
2264                _ => {
2265                    if parts.is_empty() {
2266                        return Err(cur.err("all(...) requires at least one guard expression"));
2267                    }
2268                    let mut exprs = Vec::new();
2269                    for part in parts {
2270                        if part.iter().all(|t| matches!(&t.kind, TokKind::Newline)) {
2271                            return Err(cur.err("all(...) requires at least one guard expression"));
2272                        }
2273                        let mut sub = Cursor::new(part, cur.stmt);
2274                        exprs.push(parse_guard_seq(&mut sub)?);
2275                        if !sub.done() {
2276                            return Err(sub.err("unexpected text in `all`"));
2277                        }
2278                    }
2279                    return Ok(GuardExpr::all(exprs));
2280                }
2281            }
2282        }
2283    }
2284    match cur.peek() {
2285        Some(t) => match &t.kind {
2286            TokKind::Group {
2287                delim: GroupDelim::Paren,
2288                inner,
2289                ..
2290            } => {
2291                let inner = inner.clone();
2292                cur.next();
2293                let mut sub = Cursor::new(&inner, cur.stmt);
2294                let expr = parse_guard_seq(&mut sub)?;
2295                if !sub.done() {
2296                    return Err(sub.err("unexpected text in guard group"));
2297                }
2298                Ok(expr)
2299            }
2300            _ => parse_guard_term(cur),
2301        },
2302        None => Err(cur.err("missing guard expression")),
2303    }
2304}
2305
2306fn parse_guard_seq(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2307    let first = parse_guard_primary(cur)?;
2308    let mut rest = vec![first];
2309    while cur.eat_punct(',') {
2310        rest.push(parse_guard_primary(cur)?);
2311    }
2312    if rest.len() == 1 {
2313        Ok(rest.pop().unwrap())
2314    } else {
2315        Ok(GuardExpr::all(rest))
2316    }
2317}
2318
2319/// Parse one bracket group's contents as a guard expression.
2320fn parse_guard_inner(inner: &[Tok], stmt: usize) -> Result<GuardExpr, TokenError> {
2321    let mut cur = Cursor::new(inner, stmt);
2322    let expr = parse_guard_seq(&mut cur)?;
2323    if !cur.done() {
2324        return Err(cur.err("unexpected text in guard"));
2325    }
2326    Ok(expr)
2327}
2328
2329/// Parse one standalone guard expression from lexed tokens (the
2330/// `parse_guard_expr_str` entry point): a bare `guard_seq` with full
2331/// consumption.
2332pub(crate) fn parse_single_guard(toks: &[Tok], stmt: usize) -> Result<GuardExpr, TokenError> {
2333    let mut cur = Cursor::new(toks, stmt);
2334    if cur.done() {
2335        return Err(cur.err("empty guard"));
2336    }
2337    let expr = parse_guard_seq(&mut cur)?;
2338    if !cur.done() {
2339        return Err(cur.err("unexpected text in guard"));
2340    }
2341    Ok(expr)
2342}
2343
2344/// Combine a statement's leading guard groups: stacked brackets `All`
2345/// together, a single bracket stands alone.
2346fn parse_guard_groups(guard: &[Tok], stmt: usize) -> Result<Option<GuardExpr>, TokenError> {
2347    let mut acc: Option<GuardExpr> = None;
2348    for tok in guard {
2349        let inner = match &tok.kind {
2350            TokKind::Group {
2351                delim: GroupDelim::Bracket,
2352                inner,
2353                ..
2354            } => inner.clone(),
2355            _ => {
2356                return Err(TokenError {
2357                    stmt,
2358                    msg: "unsupported non-bracket guard".to_string(),
2359                    line: 0,
2360                    col: 0,
2361                    kind: None,
2362                });
2363            }
2364        };
2365        let expr = parse_guard_inner(&inner, stmt)?;
2366        acc = Some(match acc {
2367            None => expr,
2368            Some(prev) => GuardExpr::all(vec![prev, expr]),
2369        });
2370    }
2371    Ok(acc)
2372}
2373
2374// ---- Calls, RUN-exec, instruction exactness ----
2375// Static call resolution runs through the shared `resolve_call_name`
2376// (same module table, same messages); only the token-level call-shape
2377// detector is v2-native. Generic arguments classify like the
2378// `assignment | argument` grammar order (assignments merge across
2379// gaps, `$`/`env:`-led runs extend as expressions, everything else
2380// renders raw), and `ENV`/`EXPAND` lower through the shared direct
2381// cores instead of the injected dispatcher.
2382
2383/// Parse context: shared lowering dispatcher plus module table for
2384/// static call resolution, with `FUNC`/import frames per braced body.
2385pub struct ParseCtx<'a> {
2386    pub lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
2387    pub modules: &'a ModuleTable,
2388    /// Host-registered function names for the `FUNC` shadow check
2389    /// (empty when hosts are unknown).
2390    pub reserved: &'a HashSet<String>,
2391    /// `FUNC` scopes (innermost last) and import frames, pushed per
2392    /// braced body; short borrows only,
2393    /// never held across recursive parses.
2394    pub funcs: RefCell<Vec<HashSet<String>>>,
2395    pub imports: RefCell<Vec<Vec<String>>>,
2396    /// `EXPORT` func names in source order, validated at end of parse
2397    /// (forward references allowed).
2398    pub func_exports: RefCell<Vec<String>>,
2399    /// `EXPORT TYPE` names in source order, validated at end of parse
2400    /// (forward references allowed). Separate from func exports so the
2401    /// MCP server never confuses a type for a tool.
2402    pub type_exports: RefCell<Vec<String>>,
2403    /// 1-based source line of the statement currently lowering (the
2404    /// innermost split statement; updated per statement by the body
2405    /// loops, read as the base for nested splits). Lets every error
2406    /// carry its statement's line without threading it through every
2407    /// header function by hand.
2408    pub current_line: RefCell<usize>,
2409}
2410
2411impl<'a> ParseCtx<'a> {
2412    /// Context with empty tables.
2413    pub fn empty(
2414        lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
2415        modules: &'a ModuleTable,
2416        reserved: &'a HashSet<String>,
2417    ) -> Self {
2418        Self {
2419            lower,
2420            modules,
2421            reserved,
2422            funcs: RefCell::new(vec![HashSet::new()]),
2423            imports: RefCell::new(vec![Vec::new()]),
2424            func_exports: RefCell::new(Vec::new()),
2425            type_exports: RefCell::new(Vec::new()),
2426            current_line: RefCell::new(0),
2427        }
2428    }
2429
2430    /// Snapshot of everything visible at this point: `FUNC` names
2431    /// unioned across frames plus imports flattened outer-to-inner
2432    /// (unions `FUNC` names across frames, flattens imports outer-to-inner).
2433    fn visible_snapshot(&self) -> (HashSet<String>, Vec<String>) {
2434        let mut funcs = HashSet::new();
2435        for scope in self.funcs.borrow().iter() {
2436            funcs.extend(scope.iter().cloned());
2437        }
2438        let mut imports = Vec::new();
2439        for frame in self.imports.borrow().iter() {
2440            for module in frame {
2441                if !imports.contains(module) {
2442                    imports.push(module.clone());
2443                }
2444            }
2445        }
2446        (funcs, imports)
2447    }
2448
2449    /// Record a `FUNC` name in the innermost scope. Returns false when
2450    /// already defined in that same scope (nested shadowing stays
2451    /// allowed (nested shadowing stays permitted).
2452    fn declare_func(&self, name: &str) -> bool {
2453        match self.funcs.borrow_mut().last_mut() {
2454            Some(current) => current.insert(name.to_string()),
2455            None => true,
2456        }
2457    }
2458
2459    /// Record `IMPORT`ed modules in the innermost frame (deduped,
2460    /// (deduped; the unknown-module table check lives at the import site),
2461    /// which lives at the import site).
2462    fn import_into_frame(&self, modules: &[String]) {
2463        match self.imports.borrow_mut().last_mut() {
2464            Some(frame) => {
2465                for module in modules {
2466                    if !frame.contains(module) {
2467                        frame.push(module.clone());
2468                    }
2469                }
2470            }
2471            None => {
2472                self.imports.borrow_mut().push(modules.to_vec());
2473            }
2474        }
2475    }
2476}
2477
2478fn resolve_name(ctx: &ParseCtx, stmt: usize, name: &str) -> Result<String, TokenError> {
2479    let (funcs, imports) = ctx.visible_snapshot();
2480    resolve_call_name(ctx.modules, &funcs, &imports, &lowering_ctx(stmt), name)
2481        .map_err(|e| lower_err(stmt, e))
2482}
2483
2484/// Qualify bare placeholder calls in template text through the
2485/// shared static resolver, so `{{ NAME(args) }}` obeys exactly the
2486/// same scope rule as statement-position calls: `IMPORT [MOD]`
2487/// brings the names into scope, unimported names fail naming the
2488/// fix, ambiguity fails closed. Qualified (`MOD::FUNC`), variable
2489/// (`$x`, `bare_key`), env (`env:K`), and non-call keys pass
2490/// through untouched for the runtime to handle exactly as before;
2491/// only keys that are entirely one bare call shape are rewritten,
2492/// and only the head identifier's bytes change: surrounding
2493/// spacing and neighboring placeholders stay byte-identical, so
2494/// string payloads never lose formatting. Returns `None` when
2495/// nothing qualified, leaving the text completely untouched.
2496/// Shape detection is the shared `template::parse_placeholder_call`
2497/// grammar (also behind runtime dispatch), so parse and runtime
2498/// can never disagree on what counts as one call.
2499fn qualify_template_calls(
2500    text: &str,
2501    ctx: &ParseCtx,
2502    stmt: usize,
2503) -> Result<Option<String>, TokenError> {
2504    use crate::template::{TemplateSegment, TemplateSegments, parse_placeholder_call};
2505    let mut out = String::with_capacity(text.len());
2506    let mut changed = false;
2507    for segment in TemplateSegments::new(text) {
2508        match segment {
2509            TemplateSegment::Text(raw) => out.push_str(raw),
2510            TemplateSegment::Placeholder { key, raw } => {
2511                let call = match parse_placeholder_call(key) {
2512                    Some(call) if call.module.is_none() => call,
2513                    _ => {
2514                        out.push_str(raw);
2515                        continue;
2516                    }
2517                };
2518                let head = call.name;
2519                let resolved = resolve_name(ctx, stmt, head)?;
2520                if !resolved.contains(MODULE_SEPARATOR) {
2521                    // Unqualified resolutions (`INSPECT`) keep today's
2522                    // runtime handling untouched.
2523                    out.push_str(raw);
2524                    continue;
2525                }
2526                changed = true;
2527                // Splice only the head span: `name_span` is the byte
2528                // range of the head inside `key`, and `key` is the
2529                // trimmed interior of `raw`, so the raw offset is the
2530                // interior start plus the span start.
2531                let key_off = raw.find(key).expect("key is trimmed interior");
2532                let off = key_off + call.name_span.start;
2533                out.push_str(&raw[..off]);
2534                out.push_str(&resolved);
2535                out.push_str(&raw[off + head.len()..]);
2536            }
2537        }
2538    }
2539    if changed { Ok(Some(out)) } else { Ok(None) }
2540}
2541
2542/// Call shape at `pos`: UPPERCASE head plus joint `::` segments and a
2543/// paren group (joint iff required: statements forbid the gap;
2544/// expressions allow it).
2545/// Peek-only; anything else falls through (not a call shape).
2546/// Returns the dotted name and paren index.
2547fn call_shape_at(toks: &[Tok], pos: usize, joint_paren: bool) -> Option<(String, usize)> {
2548    let head = match toks.get(pos).map(|t| &t.kind) {
2549        Some(TokKind::Word(w))
2550            if !w.is_empty()
2551                && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
2552                && w.chars()
2553                    .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') =>
2554        {
2555            w.clone()
2556        }
2557        _ => return None,
2558    };
2559    let mut name = head;
2560    let mut p = pos + 1;
2561    loop {
2562        let colons = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')))
2563            && toks.get(p).is_some_and(|t| t.joint)
2564            && matches!(toks.get(p + 1).map(|t| &t.kind), Some(TokKind::Punct(':')))
2565            && toks.get(p + 1).is_some_and(|t| t.joint)
2566            && matches!(toks.get(p + 2).map(|t| &t.kind), Some(TokKind::Word(_)))
2567            && toks.get(p + 2).is_some_and(|t| t.joint);
2568        if !colons {
2569            break;
2570        }
2571        if let Some(TokKind::Word(seg)) = toks.get(p + 2).map(|t| &t.kind) {
2572            name.push_str(MODULE_SEPARATOR);
2573            name.push_str(seg);
2574        }
2575        p += 3;
2576    }
2577    match toks.get(p).map(|t| &t.kind) {
2578        Some(TokKind::Group {
2579            delim: GroupDelim::Paren,
2580            ..
2581        }) => {
2582            if joint_paren && !toks[p].joint {
2583                return None;
2584            }
2585            Some((name, p))
2586        }
2587        _ => None,
2588    }
2589}
2590
2591/// Call arguments over a paren group's contents: comma-separated full
2592/// expressions with `gap_nl` newlines at the edges (each arg rejects
2593/// a stray boundary).
2594fn parse_call_args(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Vec<Expr>, TokenError> {
2595    let mut cur = Cursor::expr(inner, stmt);
2596    cur.skip_gap_nl();
2597    if cur.done() {
2598        return Ok(vec![]);
2599    }
2600    let mut args = Vec::new();
2601    loop {
2602        let arg = parse_expr_or(&mut cur, ctx)?;
2603        reject_boundary(&lowering_ctx(stmt), &arg).map_err(|e| cur.err(e.to_string()))?;
2604        args.push(arg);
2605        cur.skip_gap_nl();
2606        if cur.eat_punct(',') {
2607            cur.skip_gap_nl();
2608            continue;
2609        }
2610        break;
2611    }
2612    if !cur.done() {
2613        return Err(trailing_items_error(
2614            &cur,
2615            ctx,
2616            stmt,
2617            "call arguments",
2618            "unexpected text in call",
2619        ));
2620    }
2621    Ok(args)
2622}
2623
2624/// Lower a call-shape to `Expr`: `INSPECT` keeps its variable
2625/// unevaluated; everything else
2626/// resolves statically through the shared resolver.
2627fn parse_expr_call(
2628    name: String,
2629    inner: &[Tok],
2630    stmt: usize,
2631    ctx: &ParseCtx,
2632) -> Result<Expr, TokenError> {
2633    let args = parse_call_args(inner, stmt, ctx)?;
2634    if name == KEYWORD_INSPECT {
2635        let [arg] = args.as_slice() else {
2636            return Err(TokenError {
2637                stmt,
2638                msg: "INSPECT requires exactly one argument: INSPECT($var)".to_string(),
2639                line: 0,
2640                col: 0,
2641                kind: None,
2642            });
2643        };
2644        if let Expr::Var(var) = arg {
2645            return Ok(Expr::Inspect(var.clone()));
2646        }
2647        return Err(TokenError {
2648            stmt,
2649            msg: format!("INSPECT requires a $variable argument, found {arg:?}"),
2650            line: 0,
2651            col: 0,
2652            kind: None,
2653        });
2654    }
2655    let qualified = resolve_name(ctx, stmt, &name)?;
2656    Ok(Expr::Call {
2657        name: qualified,
2658        args,
2659    })
2660}
2661
2662/// Item rule selecting which `[...]` position the shared list core
2663/// parses for. The loop, comma rule, empty rule, trailing-content rule,
2664/// and newline tolerance are identical for every position (see
2665/// [`parse_bracket_list`]); only items and miss handling differ.
2666#[derive(Clone, Copy)]
2667enum BracketItems {
2668    /// Full checked expressions; a miss fails loudly.
2669    Expr,
2670    /// RUN-exec restricted atoms (brace groups try maps only, so blocks
2671    /// miss); a miss is shell fallthrough (`None`), never an error, so
2672    /// POSIX `[ -f ... ]` and malformed shapes stay shell.
2673    Exec,
2674}
2675
2676/// Trailing-content error for comma-separated positions (list
2677/// items, call arguments): stamps the offending token's position so
2678/// the caret names the line that actually fails instead of the
2679/// statement head, and names the likely missing comma when the
2680/// remainder parses as another item. Genuine trailing garbage keeps
2681/// the previous message verbatim. Error-path only, so the probe
2682/// parse costs nothing on success.
2683fn trailing_items_error(
2684    cur: &Cursor,
2685    ctx: &ParseCtx,
2686    stmt: usize,
2687    missing_what: &str,
2688    fallback: &str,
2689) -> TokenError {
2690    let (line, col) = cur
2691        .toks
2692        .get(cur.pos)
2693        .map(|t| (t.line, t.col))
2694        .unwrap_or((0, 0));
2695    let mut probe = Cursor::expr(&cur.toks[cur.pos.min(cur.toks.len())..], stmt);
2696    let msg = if parse_expr_checked(&mut probe, ctx).is_ok() {
2697        format!("missing comma between {missing_what}")
2698    } else {
2699        fallback.to_string()
2700    };
2701    TokenError {
2702        stmt,
2703        line,
2704        col,
2705        msg,
2706        kind: None,
2707    }
2708}
2709
2710/// Shared comma-separated `[...]` core behind every bracket position.
2711/// There is exactly one list loop: one empty rule, one comma rule, one
2712/// trailing-content rule, newlines riding every gap. A bracket group
2713/// already lexes across lines, so rejecting newlines here only strands
2714/// the statement in raw-text rendering.
2715fn parse_bracket_list(
2716    inner: &[Tok],
2717    stmt: usize,
2718    ctx: &ParseCtx,
2719    items: BracketItems,
2720) -> Result<Option<Expr>, TokenError> {
2721    let mut cur = Cursor::expr(inner, stmt);
2722    cur.skip_gap_nl();
2723    if cur.done() {
2724        return Ok(Some(Expr::List(vec![])));
2725    }
2726    let mut list = Vec::new();
2727    loop {
2728        let item = match items {
2729            BracketItems::Expr => parse_expr_checked(&mut cur, ctx),
2730            BracketItems::Exec => match parse_run_exec_atom(&mut cur, ctx) {
2731                Ok(Some(atom)) => Ok(atom),
2732                // Not an exec shape at all: shell fallthrough.
2733                Ok(None) | Err(_) => return Ok(None),
2734            },
2735        };
2736        // Only expression positions can fail here: exec misses
2737        // return `None` above.
2738        let item = item?;
2739        match reject_boundary(&lowering_ctx(stmt), &item) {
2740            Ok(()) => {}
2741            Err(e) if matches!(items, BracketItems::Expr) => {
2742                return Err(cur.err(e.to_string()));
2743            }
2744            Err(_) => return Ok(None),
2745        }
2746        list.push(item);
2747        cur.skip_gap_nl();
2748        if cur.eat_punct(',') {
2749            cur.skip_gap_nl();
2750            continue;
2751        }
2752        break;
2753    }
2754    if !cur.done() {
2755        return match items {
2756            BracketItems::Expr => Err(trailing_items_error(
2757                &cur,
2758                ctx,
2759                stmt,
2760                "list items",
2761                "unexpected text in list",
2762            )),
2763            BracketItems::Exec => Ok(None),
2764        };
2765    }
2766    Ok(Some(Expr::List(list)))
2767}
2768
2769/// RUN exec-form list: the shared bracket core in `Exec` mode (atoms
2770/// only, except parenthesized/calls/lists/maps which recurse fully).
2771/// Anything that is not a clean comma-separated list misses the whole
2772/// exec shape (`None`): the grammar falls through to the shell path,
2773/// which reads the bracket literally and lets the shared lowering
2774/// decide (POSIX `[ -f ... ]` stays shell; non-map blocks and malformed
2775/// shapes behave exactly like the grammar's fallthrough).
2776/// (`instruction`), which reads the bracket literally and lets the
2777/// shared lowering decide (POSIX `[ -f ... ]` stays shell, malformed
2778/// shapes fail there exactly like the grammar). Only the
2779/// joint-bracket gate stays a hard error (it precedes this function).
2780fn parse_run_exec_list(
2781    inner: &[Tok],
2782    stmt: usize,
2783    ctx: &ParseCtx,
2784) -> Result<Option<Expr>, TokenError> {
2785    parse_bracket_list(inner, stmt, ctx, BracketItems::Exec)
2786}
2787
2788/// One RUN-exec item: brace groups try maps only (blocks miss);
2789/// everything else parses as a full atom (nested lists and map
2790/// values still admit blocks, like the grammar).
2791fn parse_run_exec_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Option<Expr>, TokenError> {
2792    if matches!(
2793        cur.toks.get(cur.pos).map(|t| &t.kind),
2794        Some(TokKind::Group {
2795            delim: GroupDelim::Brace,
2796            ..
2797        })
2798    ) {
2799        let inner = match &cur.toks[cur.pos].kind {
2800            TokKind::Group { inner, .. } => inner.clone(),
2801            _ => unreachable!(),
2802        };
2803        return match parse_map_literal(&inner, cur.stmt, ctx) {
2804            Ok(map) => {
2805                cur.pos += 1;
2806                Ok(Some(map))
2807            }
2808            Err(_) => Ok(None),
2809        };
2810    }
2811    parse_expr_atom(cur, ctx).map(Some)
2812}
2813
2814// ---- Single-command wrappers + AWAIT/CANCEL ----
2815// Wrappers parse through the shared validators (`check_tty_wrapping`,
2816// capture rejects, isolated rewrite, nesting reject, binding merge,
2817// guard `and`) promoted verbatim to `commands.rs`; only the
2818// token-level shape classifiers (duration gate, binding splitter,
2819// await/cancel shapes, block-vs-template) are v2-native. Statements
2820// lower to step VECTORS: structural pairs (calls, RUN-exec,
2821// await/cancel, wrapper blocks) end mid-line and trailing elements
2822// form following steps, exactly like the grammar's `element*`.
2823//
2824// Deferred: block STATEMENTS (slice 5: top-level `IF`/`FOR`/`WHILE`
2825// bodies, guard blocks, `REMOTE`, directives).
2826
2827/// Static duration shape mirror (`timeout_literal`, atomic): ASCII
2828/// digits plus one optional unit, full-match only. Anything else
2829/// (`10ss`, `banana`, `-5s`) misses the wrapper shape and falls back
2830/// to the generic instruction path, which fails in lowering exactly
2831/// like the grammar's committed `instruction`.
2832fn is_timeout_literal(text: &str) -> bool {
2833    let digits = text.len() - text.trim_start_matches(|c: char| c.is_ascii_digit()).len();
2834    if digits == 0 {
2835        return false;
2836    }
2837    matches!(&text[digits..], "" | "ms" | "s" | "m" | "h")
2838}
2839
2840/// Template-brace test: a brace group whose first inner token opens
2841/// another brace (`{{...}}`); anything else braced is a block body.
2842/// Same shape the arg engine uses; single source from here.
2843fn is_template_brace(tok: &Tok) -> bool {
2844    matches!(
2845        &tok.kind,
2846        TokKind::Group {
2847            delim: GroupDelim::Brace,
2848            inner,
2849            ..
2850        } if matches!(
2851            inner.first().map(|t| &t.kind),
2852            Some(TokKind::Group {
2853                delim: GroupDelim::Brace,
2854                ..
2855            })
2856        )
2857    )
2858}
2859
2860/// Parse one TIMEOUT duration unit at `pos` (the token after the
2861/// head, gapped like the grammar's `sep`). Returns the arg and
2862/// tokens consumed, or `None` on shape miss (caller falls back to
2863/// generic, which fails in lowering). Static
2864/// literals validate now through the shared Duration check
2865/// (`TIMEOUT 0s` fails here, probed); dynamics defer to runtime.
2866fn parse_timeout_duration_at(
2867    toks: &[Tok],
2868    pos: usize,
2869    stmt: usize,
2870) -> Result<Option<(Arg, usize)>, TokenError> {
2871    let Some(head) = toks.get(pos) else {
2872        return Ok(None);
2873    };
2874    if head.joint {
2875        return Ok(None);
2876    }
2877    let arg = match &head.kind {
2878        TokKind::Word(w) if is_timeout_literal(w) => Arg::String(w.clone(), false),
2879        TokKind::Punct('$') => match toks.get(pos + 1) {
2880            Some(var) if var.joint && matches!(&var.kind, TokKind::Word(w) if is_ident_word(w)) => {
2881                match &var.kind {
2882                    TokKind::Word(w) => Arg::Expr(Expr::Var(w.clone())),
2883                    _ => unreachable!(),
2884                }
2885            }
2886            _ => return Ok(None),
2887        },
2888        TokKind::Str { text, .. } => Arg::String(text.clone(), true),
2889        TokKind::BlockStr(full) => Arg::String(crate::command::lower_block_string(full), true),
2890        TokKind::Group {
2891            delim: GroupDelim::Brace,
2892            inner,
2893            open_joint,
2894            close_joint,
2895        } if is_template_brace(&toks[pos]) => Arg::String(
2896            render_group('{', '}', inner, *open_joint, *close_joint),
2897            false,
2898        ),
2899        _ => return Ok(None),
2900    };
2901    let used = match &head.kind {
2902        TokKind::Punct('$') => 2,
2903        _ => 1,
2904    };
2905    ArgType::Duration.check_arg(&arg).map_err(|e| TokenError {
2906        stmt,
2907        msg: e.to_string(),
2908        line: 0,
2909        col: 0,
2910        kind: None,
2911    })?;
2912    Ok(Some((arg, used)))
2913}
2914
2915/// Parse `WITH_IO [...]` bindings over a bracket group's inner
2916/// tokens: comma-separated `stream[=$var]` / `rows|cols=int`
2917/// bindings, newlines skipping freely like `ws`. Returns `None` on
2918/// shape miss (empty flags, bad stream words, missing commas or
2919/// values: the caller falls back to generic, which fails in lowering).
2920/// Grammar-matched but invalid bindings (tty
2921/// values, out-of-range geometry) fail loudly, mirroring
2922/// `parse_io_binding`'s messages one by one.
2923fn parse_io_bindings(inner: &[Tok], stmt: usize) -> Result<Option<Vec<IoBinding>>, TokenError> {
2924    let mut parts: Vec<&[Tok]> = Vec::new();
2925    let mut start = 0;
2926    for (i, tok) in inner.iter().enumerate() {
2927        // Newlines skip freely like `ws` (filtered per part below);
2928        // commas split bindings; everything else is content.
2929        if matches!(&tok.kind, TokKind::Punct(',')) {
2930            parts.push(&inner[start..i]);
2931            start = i + 1;
2932        }
2933    }
2934    parts.push(&inner[start..]);
2935    // An empty flag list (`[]`, `[,]`) misses the shape.
2936    if parts.len() == 1 && parts[0].iter().all(|t| matches!(&t.kind, TokKind::Newline)) {
2937        return Ok(None);
2938    }
2939    let mut out = Vec::new();
2940    for part in parts {
2941        let part: Vec<&Tok> = part
2942            .iter()
2943            .filter(|t| !matches!(&t.kind, TokKind::Newline))
2944            .collect();
2945        match parse_io_binding_part(&part, stmt)? {
2946            Some(binding) => out.push(binding),
2947            None => return Ok(None),
2948        }
2949    }
2950    if out.is_empty() {
2951        return Ok(None);
2952    }
2953    Ok(Some(out))
2954}
2955
2956/// One `stream[=$var]` / `rows|cols=int` binding. Gaps ride free
2957/// around `=`/`,`/names like `ws?`; only `$`+name stays gapless
2958/// (atomic `dollar_ident`). Streams and size names outside the
2959/// grammar's words miss the shape; a valued `tty` and out-of-range
2960/// geometry fail loudly with exact messages.
2961fn parse_io_binding_part(part: &[&Tok], stmt: usize) -> Result<Option<IoBinding>, TokenError> {
2962    let fail = |msg: String| TokenError {
2963        stmt,
2964        msg,
2965        line: 0,
2966        col: 0,
2967        kind: None,
2968    };
2969    let Some(first) = part.first() else {
2970        return Ok(None);
2971    };
2972    let TokKind::Word(stream) = &first.kind else {
2973        return Ok(None);
2974    };
2975    let is_stream = matches!(stream.as_str(), "stdin" | "stdout" | "stderr" | "tty");
2976    let is_size = matches!(stream.as_str(), "rows" | "cols");
2977    if !is_stream && !is_size {
2978        return Ok(None);
2979    }
2980    let rest = &part[1..];
2981    if rest.is_empty() {
2982        if is_size {
2983            // Bare `rows` misses `io_size` (`=` + digits required).
2984            return Ok(None);
2985        }
2986        return Ok(Some(IoBinding {
2987            stream: io_stream_of(stream),
2988            pipe: None,
2989        }));
2990    }
2991    // `= value` at any gap.
2992    if !matches!(rest.first().map(|t| &t.kind), Some(TokKind::Punct('='))) {
2993        return Ok(None);
2994    }
2995    let value = &rest[1..];
2996    if is_size {
2997        // Geometry: one all-digit word, 1-65535 (mirrors `parse_io_size`).
2998        if value.len() != 1 {
2999            return Ok(None);
3000        }
3001        let TokKind::Word(digits) = &value[0].kind else {
3002            return Ok(None);
3003        };
3004        if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
3005            return Ok(None);
3006        }
3007        let dim = digits
3008            .parse::<u64>()
3009            .ok()
3010            .filter(|v| (1..=u64::from(u16::MAX)).contains(v))
3011            .ok_or_else(|| {
3012                fail(
3013                    "WITH_IO terminal geometry needs a positive integer 1-65535 (e.g. `rows=40`)"
3014                        .to_string(),
3015                )
3016            })?;
3017        let dim = dim as u16;
3018        return Ok(Some(IoBinding {
3019            stream: if stream == "rows" {
3020                IoStream::Rows(dim)
3021            } else {
3022                IoStream::Cols(dim)
3023            },
3024            pipe: None,
3025        }));
3026    }
3027    // Stream pipe: `= $var` with a gapless name.
3028    if value.len() != 2 {
3029        return Ok(None);
3030    }
3031    if !matches!(&value[0].kind, TokKind::Punct('$')) {
3032        return Ok(None);
3033    }
3034    let TokKind::Word(var) = &value[1].kind else {
3035        return Ok(None);
3036    };
3037    if !value[1].joint || !is_ident_word(var) {
3038        return Ok(None);
3039    }
3040    if stream == "tty" {
3041        // `tty` is a bare flag (mirrors `parse_io_binding`).
3042        return Err(fail(
3043            "WITH_IO [tty] takes no value: use bare `tty`, with `rows = <int>` / `cols = <int>` for geometry (e.g. `[tty, rows=40, cols=100]`)"
3044                .to_string(),
3045        ));
3046    }
3047    Ok(Some(IoBinding {
3048        stream: io_stream_of(stream),
3049        pipe: Some(crate::ast::PipeTarget::Var(var.clone())),
3050    }))
3051}
3052
3053/// Stream word to [`IoStream`]: only grammar words reach here, so
3054/// the mapping is total (mirrors `parse_io_stream`).
3055fn io_stream_of(name: &str) -> IoStream {
3056    match name {
3057        "stdin" => IoStream::Stdin,
3058        "stdout" => IoStream::Stdout,
3059        "stderr" => IoStream::Stderr,
3060        _ => IoStream::Tty,
3061    }
3062}
3063
3064/// `AWAIT`/`CANCEL $var` shape at `pos`. A head without `$` misses
3065/// (`None`: generic fails it in lowering); once `$`
3066/// commits, the name must follow and parse errors stay loud, like
3067/// the grammar's committed `"$" ~ ident`. `var_joint` enforces the
3068/// atomic `$var` adjacency inside compound-atomic parents; element
3069/// level admits the gap (probed `AWAIT $ t`). The caller continues
3070/// its element loop past the shape.
3071fn parse_await_cancel_at(
3072    toks: &[Tok],
3073    pos: usize,
3074    stmt: usize,
3075    var_joint: bool,
3076) -> Result<Option<(StepKind, usize)>, TokenError> {
3077    let head = match toks.get(pos).map(|t| &t.kind) {
3078        Some(TokKind::Word(w)) if w == KEYWORD_AWAIT || w == KEYWORD_CANCEL => w.clone(),
3079        _ => return Ok(None),
3080    };
3081    if !matches!(
3082        toks.get(pos + 1).map(|t| &t.kind),
3083        Some(TokKind::Punct('$'))
3084    ) {
3085        return Ok(None);
3086    }
3087    let var = match toks.get(pos + 2) {
3088        Some(t)
3089            if matches!(&t.kind, TokKind::Word(w) if is_ident_word(w))
3090                && (!var_joint || t.joint) =>
3091        {
3092            match &t.kind {
3093                TokKind::Word(w) => w.clone(),
3094                _ => unreachable!(),
3095            }
3096        }
3097        _ => {
3098            return Err(TokenError {
3099                stmt,
3100                msg: format!("{head} requires a variable"),
3101                line: 0,
3102                col: 0,
3103                kind: None,
3104            });
3105        }
3106    };
3107    Ok(Some((
3108        if head == KEYWORD_AWAIT {
3109            StepKind::Await { var }
3110        } else {
3111            StepKind::Cancel { var }
3112        },
3113        3,
3114    )))
3115}
3116
3117/// Wrapper strictness for one single-command inner: `AWAIT` parses
3118/// dedicated in `TIMEOUT`/`ISOLATED` inners but falls to generic in
3119/// `WITH_IO`/`ASYNC` inners (where lowering fails it, probed), and
3120/// `WITH_IO` recurses everywhere but directly under `ASYNC` (where
3121/// lowering fails it, probed). Shared predicates, never restated.
3122#[derive(Clone, Copy)]
3123struct InnerRules {
3124    allow_await: bool,
3125    allow_with_io: bool,
3126}
3127
3128/// Parse one single (non-block) inner command, returning the kind
3129/// and tokens consumed: dedicated await/cancel, while/remote, calls,
3130/// RUN-exec, nested wrappers, strict `INHERIT_ENV` (the caller
3131/// rejects the nesting or rewrites it), or the generic instruction
3132/// path (which consumes everything and fails unknown heads in
3133/// lowering, exactly like the grammar's committed `instruction`).
3134fn parse_single_inner(
3135    toks: &[Tok],
3136    pos: usize,
3137    stmt: usize,
3138    ctx: &ParseCtx,
3139    rules: InnerRules,
3140) -> Result<(StepKind, usize), TokenError> {
3141    let head_word = match toks.get(pos).map(|t| &t.kind) {
3142        Some(TokKind::Word(w)) => Some(w.clone()),
3143        _ => None,
3144    };
3145    // Nested `WHILE`/`REMOTE` recurse structurally (both ride every
3146    // inner-command set in the grammar); misses fall through to
3147    // generic below.
3148    if head_word.as_deref() == Some(KEYWORD_WHILE) {
3149        match parse_while_single(toks, pos, stmt, ctx) {
3150            Ok(Some((kind, used))) => return Ok((kind, used)),
3151            Ok(None) => {}
3152            Err(e) => return Err(e),
3153        }
3154    }
3155    if head_word.as_deref() == Some(KEYWORD_REMOTE) {
3156        match parse_remote_single(toks, pos, stmt, ctx) {
3157            Ok(Some((kind, used))) => return Ok((kind, used)),
3158            Ok(None) => {}
3159            Err(e) => return Err(e),
3160        }
3161    }
3162    // File `IMPORT "path" AS ALIAS` (#115) rides every single-inner
3163    // set (TIMEOUT/ISOLATED/WITH_IO/ASYNC, LET ASYNC): exactly one file
3164    // entry and no modules, else a hard error; shape misses fall through
3165    // to generic below, which fails them in lowering.
3166    if head_word.as_deref() == Some(KEYWORD_IMPORT)
3167        && let Some((path, alias, used)) = parse_single_file_import(toks, pos, stmt, ctx)?
3168    {
3169        return Ok((StepKind::ImportFile { path, alias }, used));
3170    }
3171    // Dedicated await/cancel first (await gated by parent); anything
3172    // they decline falls through to generic below.
3173    if head_word.as_deref() == Some(KEYWORD_AWAIT)
3174        && rules.allow_await
3175        && let Some(found) = parse_await_cancel_at(toks, pos, stmt, true)?
3176    {
3177        return Ok(found);
3178    }
3179    if head_word.as_deref() == Some(KEYWORD_CANCEL)
3180        && let Some(found) = parse_await_cancel_at(toks, pos, stmt, true)?
3181    {
3182        return Ok(found);
3183    }
3184    // Calls and RUN-exec end mid-run; the caller continues past them.
3185    if let Some((call_name, paren)) = call_shape_at(toks, pos, true) {
3186        let inner = match &toks[paren].kind {
3187            TokKind::Group { inner, .. } => inner.clone(),
3188            _ => unreachable!(),
3189        };
3190        let args = parse_call_args(&inner, stmt, ctx)?;
3191        if !call_name.contains(MODULE_SEPARATOR) {
3192            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
3193                .map_err(|e| lower_err(stmt, e))?;
3194        }
3195        let qualified = resolve_name(ctx, stmt, &call_name)?;
3196        return Ok((
3197            StepKind::Call {
3198                name: qualified,
3199                args,
3200            },
3201            paren + 1 - pos,
3202        ));
3203    }
3204    if head_word.as_deref() == Some(KEYWORD_RUN)
3205        && matches!(
3206            toks.get(pos + 1).map(|t| &t.kind),
3207            Some(TokKind::Group {
3208                delim: GroupDelim::Bracket,
3209                ..
3210            })
3211        )
3212    {
3213        // Gapped like the grammar's `sep`; a joint bracket is a
3214        // hard error, never a spliced arg (probed `RUN["a"]`).
3215        if toks[pos + 1].joint {
3216            return Err(TokenError {
3217                stmt,
3218                msg: "RUN [...] requires a gap after RUN".to_string(),
3219                line: 0,
3220                col: 0,
3221                kind: None,
3222            });
3223        }
3224        let inner = match &toks[pos + 1].kind {
3225            TokKind::Group { inner, .. } => inner.clone(),
3226            _ => unreachable!(),
3227        };
3228        let exec_list = parse_run_exec_list(&inner, stmt, ctx)?;
3229        // Non-map blocks miss the exec shape (the grammar has no
3230        // `block` alternative here); fall through to generic below,
3231        // which reads the shell path literally.
3232        if let Some(list) = exec_list {
3233            let kind =
3234                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
3235            return Ok((kind, 2));
3236        }
3237    }
3238    // Nested wrappers recurse structurally; a `WITH_IO` directly
3239    // under `ASYNC` goes generic instead (lowering fails it, probed).
3240    match head_word.as_deref() {
3241        Some(KEYWORD_WITH_IO) if rules.allow_with_io => {
3242            match parse_with_io_single(toks, pos, stmt, ctx) {
3243                Ok(Some((kind, used))) => return Ok((kind, used)),
3244                Ok(None) => {}
3245                Err(e) => return Err(e),
3246            }
3247        }
3248        Some(KEYWORD_TIMEOUT) => match parse_timeout_single(toks, pos, stmt, ctx) {
3249            Ok(Some((kind, used))) => return Ok((kind, used)),
3250            Ok(None) => {}
3251            Err(e) => return Err(e),
3252        },
3253        Some(KEYWORD_ISOLATED) => match parse_isolated_single(toks, pos, stmt, ctx) {
3254            Ok(Some((kind, used))) => return Ok((kind, used)),
3255            Ok(None) => {}
3256            Err(e) => return Err(e),
3257        },
3258        Some(KEYWORD_ASYNC) => match parse_async_single(toks, pos, stmt, ctx) {
3259            Ok(Some((kind, used))) => return Ok((kind, used)),
3260            Ok(None) => {}
3261            Err(e) => return Err(e),
3262        },
3263        // `INHERIT_ENV [...]` parses strictly here (shared with
3264        // element level); the caller either rejects the nesting or
3265        // rewrites it, same as the shared validator. Trailing
3266        // elements loop on outside (a bad follower fails there, like
3267        // the grammar's line end).
3268        Some(KEYWORD_INHERIT_ENV) => {
3269            if let Some(found) = parse_inherit_env_at(toks, pos, stmt)? {
3270                return Ok(found);
3271            }
3272        }
3273        _ => {}
3274    }
3275    // Generic instruction: consumes the whole run; unknown heads
3276    // (LET/RETURN/FUNC/IF/...) fail in lowering.
3277    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
3278    Ok((kind, used))
3279}
3280
3281/// Parse an `INHERIT_ENV [...]` key list over a bracket group's
3282/// inner tokens, mirroring `inherit_list` strictly: comma-separated
3283/// keys, gaps/newlines only around keys and commas (never inside:
3284/// keys are atomic), each key a joint run validated against the
3285/// `guard_key_char` exclusions (`: = ! , | ( ) ] $`, plus the `//`
3286/// and `/*` comment opens). Groups and strings render raw (they read
3287/// as ordinary characters here); anything else misses
3288/// the shape (`None`: generic fails it in lowering).
3289/// Statement-level `INHERIT_ENV` stays generic (slice 5 directives);
3290/// this serves wrapper inners, where the nesting check (or the
3291/// isolated rewrite) consumes the result.
3292fn parse_inherit_keys(inner: &[Tok], stmt: usize) -> Result<Option<Vec<String>>, TokenError> {
3293    let mut parts: Vec<&[Tok]> = Vec::new();
3294    let mut start = 0;
3295    for (i, tok) in inner.iter().enumerate() {
3296        if matches!(&tok.kind, TokKind::Punct(',')) {
3297            parts.push(&inner[start..i]);
3298            start = i + 1;
3299        }
3300    }
3301    parts.push(&inner[start..]);
3302    let mut out = Vec::new();
3303    for part in parts {
3304        // Newlines skip at the edges only, like `ws?`.
3305        let mut part = part;
3306        while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
3307            part = &part[1..];
3308        }
3309        while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
3310            part = &part[..part.len() - 1];
3311        }
3312        let Some(key) = render_inherit_key(part, stmt)? else {
3313            return Ok(None);
3314        };
3315        out.push(key);
3316    }
3317    if out.is_empty() {
3318        return Ok(None);
3319    }
3320    Ok(Some(out))
3321}
3322
3323/// True when a `/` opens an inline comment: joint `//` or `/*`
3324/// (mirroring the grammar's comment literals, which need adjacency;
3325/// a gapped second char is payload text, like `a/ /b`). Used
3326/// everywhere `gap`/`gap_nl` admit comments.
3327fn is_comment_open(toks: &[Tok], pos: usize) -> bool {
3328    matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('/')))
3329        && matches!(
3330            toks.get(pos + 1).map(|t| (&t.kind, t.joint)),
3331            Some((TokKind::Punct('/'), true)) | Some((TokKind::Punct('*'), true))
3332        )
3333}
3334
3335/// Skip one inline comment starting at `pos` (which holds the `/`;
3336/// see [`is_comment_open`): `//` runs to a newline or the end,
3337/// `/* */` balances (nesting like the grammar) across newlines.
3338/// Returns the first position past the comment, or `None` when the
3339/// block never closes (the grammar fails unclosed comments too).
3340fn skip_inline_comment(toks: &[Tok], pos: usize) -> Option<usize> {
3341    let second = match toks.get(pos + 1).map(|t| &t.kind) {
3342        Some(TokKind::Punct('/')) => '/',
3343        Some(TokKind::Punct('*')) => '*',
3344        _ => return None,
3345    };
3346    if second == '/' {
3347        let mut p = pos + 2;
3348        while p < toks.len() && !matches!(&toks[p].kind, TokKind::Newline) {
3349            p += 1;
3350        }
3351        return Some(p);
3352    }
3353    let mut depth = 1usize;
3354    let mut p = pos + 2;
3355    while p < toks.len() {
3356        let is_open = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('/')))
3357            && matches!(
3358                toks.get(p + 1).map(|t| (&t.kind, t.joint)),
3359                Some((TokKind::Punct('*'), true))
3360            );
3361        let is_close = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('*')))
3362            && matches!(
3363                toks.get(p + 1).map(|t| (&t.kind, t.joint)),
3364                Some((TokKind::Punct('/'), true))
3365            );
3366        if is_open {
3367            depth += 1;
3368            p += 2;
3369        } else if is_close {
3370            depth -= 1;
3371            p += 2;
3372            if depth == 0 {
3373                return Some(p);
3374            }
3375        } else {
3376            p += 1;
3377        }
3378    }
3379    None
3380}
3381
3382/// Parse one inherit key: a maximal key-char run, then only
3383/// trailing gap content (`gap_nl`: newlines, comments, `#`). Key
3384/// chars exclude `: = ! , | ( ) ] $`, whitespace, and the `//` / `/*`
3385/// comment opens; a joint `#`
3386/// stays literal, a gapped one opens a trailing comment. Groups and
3387/// strings render raw for the exclusion check (they read as
3388/// ordinary characters here). `None` on shape miss.
3389fn render_inherit_key(part: &[Tok], stmt: usize) -> Result<Option<String>, TokenError> {
3390    let mut out = String::new();
3391    let mut i = 0;
3392    // Key run: words, puncts (except comment opens), groups and
3393    // strings rendered raw; ends at any gap, newline, comment, or
3394    // `//` / `/*` open.
3395    while i < part.len() {
3396        let tok = &part[i];
3397        if i > 0 && !tok.joint {
3398            break;
3399        }
3400        match &tok.kind {
3401            TokKind::Word(w) => {
3402                out.push_str(w);
3403                i += 1;
3404            }
3405            TokKind::Punct('/') if is_comment_open(part, i) => break,
3406            // `#` stays literal at key start (`#c`) or joint
3407            // (`a#b`); gapped mid-key it opens a trailing
3408            // comment like the grammar's `gap_nl`.
3409            TokKind::Punct('#') if tok.joint || out.is_empty() => {
3410                // `#` stays literal at key start (`#c`) or joint
3411                // (`a#b`).
3412                out.push('#');
3413                i += 1;
3414            }
3415            // Gapped mid-key `#` opens a trailing comment (handled
3416            // by the trailer check below, like `gap_nl`).
3417            TokKind::Punct('#') => break,
3418            TokKind::Punct(c) => {
3419                out.push(*c);
3420                i += 1;
3421            }
3422            TokKind::Semicolon => {
3423                out.push(';');
3424                i += 1;
3425            }
3426            TokKind::Str { text, quote } => {
3427                out.push(*quote);
3428                out.push_str(text);
3429                out.push(*quote);
3430                i += 1;
3431            }
3432            TokKind::BlockStr(full) => {
3433                out.push_str(full);
3434                i += 1;
3435            }
3436            TokKind::Group {
3437                delim,
3438                inner,
3439                open_joint,
3440                close_joint,
3441            } => {
3442                let (open, close) = match delim {
3443                    GroupDelim::Bracket => ('[', ']'),
3444                    GroupDelim::Paren => ('(', ')'),
3445                    GroupDelim::Brace => ('{', '}'),
3446                };
3447                out.push_str(&render_group(open, close, inner, *open_joint, *close_joint));
3448                i += 1;
3449            }
3450            // Newlines and comment markers end the key; the trailer
3451            // check below admits them.
3452            TokKind::Newline | TokKind::Comment(_) => break,
3453        }
3454    }
3455    if out.is_empty() {
3456        return Ok(None);
3457    }
3458    // Trailer: only gap content (`gap_nl`) may follow the key.
3459    let mut j = i;
3460    while j < part.len() {
3461        let tok = &part[j];
3462        match &tok.kind {
3463            TokKind::Newline | TokKind::Comment(_) => {
3464                j += 1;
3465            }
3466            TokKind::Punct('/') if is_comment_open(part, j) => {
3467                j = skip_inline_comment(part, j).ok_or(TokenError {
3468                    stmt,
3469                    msg: "unclosed block comment".to_string(),
3470                    line: 0,
3471                    col: 0,
3472                    kind: None,
3473                })?;
3474            }
3475            TokKind::Punct('#') => {
3476                // `#` comment runs to a newline or the part end.
3477                while j < part.len() && !matches!(&part[j].kind, TokKind::Newline) {
3478                    j += 1;
3479                }
3480            }
3481            _ => return Ok(None),
3482        }
3483    }
3484    // `guard_key_char` exclusions: the single-char set plus the
3485    // comment opens (`//`, `/*`); lone `/` stays legal.
3486    if out.contains("//") || out.contains("/*") {
3487        return Ok(None);
3488    }
3489    if out
3490        .chars()
3491        .any(|c| matches!(c, ':' | '=' | '!' | ',' | '|' | '(' | ')' | ']' | '$'))
3492    {
3493        return Ok(None);
3494    }
3495    Ok(Some(out))
3496}
3497
3498/// Strict `INHERIT_ENV [...]` at an element or single-inner
3499/// position: bracket riding gapped with valid keys yields the
3500/// directive (trailing elements loop on outside); anything else
3501/// misses (`None`) and generic fails it in lowering.
3502/// Serves both levels so keys stay exact everywhere; slice 5 adds
3503/// only the prelude-order validation.
3504fn parse_inherit_env_at(
3505    toks: &[Tok],
3506    pos: usize,
3507    stmt: usize,
3508) -> Result<Option<(StepKind, usize)>, TokenError> {
3509    // The bracket rides gapped (`sep`); anything else misses and
3510    // generic fails it in lowering.
3511    let bracket = match toks.get(pos + 1) {
3512        Some(t)
3513            if !t.joint
3514                && matches!(
3515                    &t.kind,
3516                    TokKind::Group {
3517                        delim: GroupDelim::Bracket,
3518                        ..
3519                    }
3520                ) =>
3521        {
3522            Some(t)
3523        }
3524        _ => None,
3525    };
3526    let Some(bracket) = bracket else {
3527        return Ok(None);
3528    };
3529    let inner = match &bracket.kind {
3530        TokKind::Group { inner, .. } => inner,
3531        _ => unreachable!(),
3532    };
3533    match parse_inherit_keys(inner, stmt)? {
3534        Some(keys) => Ok(Some((StepKind::InheritEnv { keys }, 2))),
3535        None => Ok(None),
3536    }
3537}
3538
3539/// Parse a brace block body into steps: statements split and lower
3540/// recursively, each keeping its own guard. `mark` selects scope
3541/// marking: top-level guard-block bodies mark (each nesting level
3542/// bumps first/last); wrapper bodies
3543/// (`IF`/`FOR`/`WHILE`/`FUNC`/`REMOTE`/wrappers/io-blocks) never mark
3544/// (block-element lowering pins 0/0).
3545fn parse_body_steps(
3546    inner: &[Tok],
3547    stmt: usize,
3548    ctx: &ParseCtx,
3549    mark: bool,
3550) -> Result<Vec<Step>, TokenError> {
3551    // One function/import scope per braced body (mirroring the
3552    // runtime push/pop boundary): same-block
3553    // `FUNC` redefinition errors, nested shadowing stays allowed.
3554    // Errors abort the whole parse (frames discarded with it), so no
3555    // exit runs on failure.
3556    ctx.funcs.borrow_mut().push(HashSet::new());
3557    ctx.imports.borrow_mut().push(Vec::new());
3558    // Nested splits count lines from the enclosing statement's line
3559    // (headers are single-line, so the brace shares it). Save and
3560    // restore the discipline around the loop: sibling bodies after
3561    // this one must see the enclosing line, not the last inner one.
3562    // (On error the parse aborts and the context is discarded.)
3563    let saved = *ctx.current_line.borrow();
3564    let mut out = Vec::new();
3565    for s in split_statements(inner, saved)? {
3566        // The innermost statement owns error positions: record it for
3567        // nested splits and stamp failures that have none yet (deeper
3568        // frames stamp first, so this never overwrites real positions).
3569        *ctx.current_line.borrow_mut() = s.line;
3570        out.extend(
3571            lower_stmt_steps(&s, stmt, ctx, true, mark).map_err(|e| stamp_pos(e, s.line, s.col))?,
3572        );
3573    }
3574    *ctx.current_line.borrow_mut() = saved;
3575    ctx.funcs.borrow_mut().pop();
3576    ctx.imports.borrow_mut().pop();
3577    Ok(out)
3578}
3579
3580/// Single (non-block) `WITH_IO`: bindings plus an optional inner
3581/// command. `None` on shape miss (no/gapped bracket: generic fails
3582/// it in lowering). A brace in single-inner position is
3583/// the grammar's pending-guard error, never an io-block; a bare
3584/// bracket leaks the transient `WithIoBlock` into the body (probed).
3585fn parse_with_io_single(
3586    toks: &[Tok],
3587    pos: usize,
3588    stmt: usize,
3589    ctx: &ParseCtx,
3590) -> Result<Option<(StepKind, usize)>, TokenError> {
3591    let bracket = match toks.get(pos + 1) {
3592        // The bracket rides gapped (`sep`); anything else misses the
3593        // shape and generic fails it in lowering.
3594        Some(t)
3595            if !t.joint
3596                && matches!(
3597                    &t.kind,
3598                    TokKind::Group {
3599                        delim: GroupDelim::Bracket,
3600                        ..
3601                    }
3602                ) =>
3603        {
3604            t
3605        }
3606        _ => return Ok(None),
3607    };
3608    let inner = match &bracket.kind {
3609        TokKind::Group { inner, .. } => inner.clone(),
3610        _ => unreachable!(),
3611    };
3612    let bindings = match parse_io_bindings(&inner, stmt)? {
3613        Some(bindings) => bindings,
3614        None => return Ok(None),
3615    };
3616    let rest = pos + 2;
3617    // A brace directly after the bracket is the pending-guard error
3618    // in single-inner position (probed); templates fall to generic.
3619    if let Some(next) = toks.get(rest)
3620        && matches!(
3621            &next.kind,
3622            TokKind::Group {
3623                delim: GroupDelim::Brace,
3624                ..
3625            }
3626        )
3627        && !is_template_brace(next)
3628    {
3629        return Err(TokenError {
3630            stmt,
3631            msg: "'{' without a pending guard".to_string(),
3632            line: 0,
3633            col: 0,
3634            kind: None,
3635        });
3636    }
3637    if rest >= toks.len() {
3638        // Bare bracket: the transient block node leaks into wrapper
3639        // bodies (statement level never reaches
3640        // here; the splitter holds it for `{`).
3641        return Ok(Some((StepKind::WithIoBlock { bindings }, 2)));
3642    }
3643    // A joint follower misses the inner `sep`: the bracket stands
3644    // bare (probed `TIMEOUT 10s WITH_IO [..]ECHO hi` yields the
3645    // transient node) and trailing elements loop on outside.
3646    if toks[rest].joint {
3647        return Ok(Some((StepKind::WithIoBlock { bindings }, 2)));
3648    }
3649    let (cmd, used) = parse_single_inner(
3650        toks,
3651        rest,
3652        stmt,
3653        ctx,
3654        InnerRules {
3655            allow_await: false,
3656            allow_with_io: true,
3657        },
3658    )?;
3659    let span = lowering_ctx(stmt);
3660    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| TokenError {
3661        stmt,
3662        msg: e.to_string(),
3663        line: 0,
3664        col: 0,
3665        kind: None,
3666    })?;
3667    let kind = StepKind::WithIo {
3668        bindings,
3669        cmd: Box::new(cmd),
3670    };
3671    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
3672        stmt,
3673        msg: e.to_string(),
3674        line: 0,
3675        col: 0,
3676        kind: None,
3677    })?;
3678    Ok(Some((kind, 2 + used)))
3679}
3680
3681/// Single (non-block) `TIMEOUT`: duration plus one inner command.
3682/// `None` on shape miss (bad duration, missing/joint inner: generic
3683/// fails it in lowering). Blocks parse inline; the body
3684/// holds one step for single inners.
3685fn parse_timeout_single(
3686    toks: &[Tok],
3687    pos: usize,
3688    stmt: usize,
3689    ctx: &ParseCtx,
3690) -> Result<Option<(StepKind, usize)>, TokenError> {
3691    let Some((duration, dused)) = parse_timeout_duration_at(toks, pos + 1, stmt)? else {
3692        return Ok(None);
3693    };
3694    let rest = pos + 1 + dused;
3695    let Some(next) = toks.get(rest) else {
3696        // `TIMEOUT 10s` alone is a generic instruction (lowering
3697        // fails it, probed), never a bare wrapper.
3698        return Ok(None);
3699    };
3700    if next.joint {
3701        return Ok(None);
3702    }
3703    let body = if matches!(
3704        &next.kind,
3705        TokKind::Group {
3706            delim: GroupDelim::Brace,
3707            ..
3708        }
3709    ) && !is_template_brace(next)
3710    {
3711        let inner = match &next.kind {
3712            TokKind::Group { inner, .. } => inner.clone(),
3713            _ => unreachable!(),
3714        };
3715        let steps = parse_body_steps(&inner, stmt, ctx, false)?;
3716        (steps, 1)
3717    } else {
3718        let (cmd, used) = parse_single_inner(
3719            toks,
3720            rest,
3721            stmt,
3722            ctx,
3723            InnerRules {
3724                allow_await: true,
3725                allow_with_io: true,
3726            },
3727        )?;
3728        (
3729            vec![Step {
3730                guard: None,
3731                kind: cmd,
3732                scope_enter: 0,
3733                scope_exit: 0,
3734                line: 0,
3735                col: 0,
3736            }],
3737            used,
3738        )
3739    };
3740    let kind = StepKind::Timeout {
3741        duration,
3742        body: body.0,
3743    };
3744    let span = lowering_ctx(stmt);
3745    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
3746        stmt,
3747        msg: e.to_string(),
3748        line: 0,
3749        col: 0,
3750        kind: None,
3751    })?;
3752    Ok(Some((kind, 1 + dused + body.1)))
3753}
3754
3755/// Single (non-block) `ISOLATED`: one inner command or block; the
3756/// body rewrites nested `INHERIT_ENV` through the shared pass.
3757/// `None` on shape miss (missing/joint inner: generic fails it).
3758fn parse_isolated_single(
3759    toks: &[Tok],
3760    pos: usize,
3761    stmt: usize,
3762    ctx: &ParseCtx,
3763) -> Result<Option<(StepKind, usize)>, TokenError> {
3764    let Some(next) = toks.get(pos + 1) else {
3765        return Ok(None);
3766    };
3767    if next.joint {
3768        return Ok(None);
3769    }
3770    let (mut body, used) = if matches!(
3771        &next.kind,
3772        TokKind::Group {
3773            delim: GroupDelim::Brace,
3774            ..
3775        }
3776    ) && !is_template_brace(next)
3777    {
3778        let inner = match &next.kind {
3779            TokKind::Group { inner, .. } => inner.clone(),
3780            _ => unreachable!(),
3781        };
3782        (parse_body_steps(&inner, stmt, ctx, false)?, 1)
3783    } else {
3784        let (cmd, used) = parse_single_inner(
3785            toks,
3786            pos + 1,
3787            stmt,
3788            ctx,
3789            InnerRules {
3790                allow_await: true,
3791                allow_with_io: true,
3792            },
3793        )?;
3794        (
3795            vec![Step {
3796                guard: None,
3797                kind: cmd,
3798                scope_enter: 0,
3799                scope_exit: 0,
3800                line: 0,
3801                col: 0,
3802            }],
3803            used,
3804        )
3805    };
3806    crate::commands::rewrite_isolated_inherit(&mut body);
3807    Ok(Some((StepKind::Isolated { body }, 1 + used)))
3808}
3809
3810/// Single (non-block) `ASYNC`: one inner command or block (blocks
3811/// admit a joint brace, like `async_statement_block`'s `sep?`).
3812/// Top-level `WITH_IO` steps fail through the shared reject; the
3813/// `LET` path never scans (probed: it accepts). `None` on shape
3814/// miss (missing/joint-single inner: generic fails it).
3815fn parse_async_single(
3816    toks: &[Tok],
3817    pos: usize,
3818    stmt: usize,
3819    ctx: &ParseCtx,
3820) -> Result<Option<(StepKind, usize)>, TokenError> {
3821    let Some(next) = toks.get(pos + 1) else {
3822        return Ok(None);
3823    };
3824    // Block form admits a joint brace (`ASYNC{...}`, probed); the
3825    // single form needs its `sep`.
3826    if matches!(
3827        &next.kind,
3828        TokKind::Group {
3829            delim: GroupDelim::Brace,
3830            ..
3831        }
3832    ) && !is_template_brace(next)
3833    {
3834        let inner = match &next.kind {
3835            TokKind::Group { inner, .. } => inner.clone(),
3836            _ => unreachable!(),
3837        };
3838        let body = parse_body_steps(&inner, stmt, ctx, false)?;
3839        let span = lowering_ctx(stmt);
3840        crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| TokenError {
3841            stmt,
3842            msg: e.to_string(),
3843            line: 0,
3844            col: 0,
3845            kind: None,
3846        })?;
3847        let kind = StepKind::AsyncBlock { body };
3848        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
3849            stmt,
3850            msg: e.to_string(),
3851            line: 0,
3852            col: 0,
3853            kind: None,
3854        })?;
3855        return Ok(Some((kind, 2)));
3856    }
3857    if next.joint {
3858        return Ok(None);
3859    }
3860    let (cmd, used) = parse_single_inner(
3861        toks,
3862        pos + 1,
3863        stmt,
3864        ctx,
3865        InnerRules {
3866            allow_await: false,
3867            allow_with_io: false,
3868        },
3869    )?;
3870    let body = vec![Step {
3871        guard: None,
3872        kind: cmd,
3873        scope_enter: 0,
3874        scope_exit: 0,
3875        line: 0,
3876        col: 0,
3877    }];
3878    let span = lowering_ctx(stmt);
3879    crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| TokenError {
3880        stmt,
3881        msg: e.to_string(),
3882        line: 0,
3883        col: 0,
3884        kind: None,
3885    })?;
3886    let kind = StepKind::AsyncBlock { body };
3887    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
3888        stmt,
3889        msg: e.to_string(),
3890        line: 0,
3891        col: 0,
3892        kind: None,
3893    })?;
3894    Ok(Some((kind, 1 + used)))
3895}
3896
3897// ---- Block statements, directives, REMOTE ----
3898// `IF`/`FOR`/`WHILE`/`FUNC` parse their headers token-natively with
3899// miss-to-generic fallback (the grammar's committed `instruction`
3900// path); bodies lower recursively with pushed scopes. `TYPE` builds
3901// aliases through a maximal type-shape match; `IMPORT`/`EXPORT` are
3902// zero-step frame/table directives; `REMOTE` validates targets,
3903// bindings, bodies, and outer-call containment through the shared
3904// validators. Guard blocks fold guards with scope markers at top
3905// level and mirror the nested quirk formula in bodies. A whole-script
3906// post-pass runs the shared validations (prelude order, COPY
3907// placement, EXPORT membership).
3908
3909/// Uppercase identifier mirror (`func_ident`, `type_name`,
3910/// `import_module`): ASCII upper start, upper/digit/`_` rest.
3911fn is_upper_ident(w: &str) -> bool {
3912    !w.is_empty()
3913        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
3914        && w.chars()
3915            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
3916}
3917
3918/// Lowercase identifier mirror (`field_name`): ASCII lower start,
3919/// lower/digit/`_` rest.
3920fn is_lower_ident(w: &str) -> bool {
3921    !w.is_empty()
3922        && w.chars().next().is_some_and(|c| c.is_ascii_lowercase())
3923        && w.chars()
3924            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
3925}
3926
3927/// `$name` with gapless adjacency (atomic `dollar_ident`); `None` on
3928/// shape miss (the caller falls back to generic, which fails in
3929/// lowering like the grammar's committed `instruction`).
3930fn peek_dollar_var(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
3931    match (toks.get(pos), toks.get(pos + 1)) {
3932        (Some(dollar), Some(name))
3933            if matches!(&dollar.kind, TokKind::Punct('$'))
3934                && name.joint
3935                && matches!(&name.kind, TokKind::Word(w) if is_ident_word(w)) =>
3936        {
3937            match &name.kind {
3938                TokKind::Word(w) => Some((w.clone(), 2)),
3939                _ => unreachable!(),
3940            }
3941        }
3942        _ => None,
3943    }
3944}
3945
3946/// Skip statement-level newlines (multi-line `<...>` shapes ride
3947/// them into the body) before the next type token. Narrower than
3948/// `gap_nl` on purpose: comments keep failing here exactly like
3949/// single-line shapes, so only the separator moves.
3950fn skip_type_nl(toks: &[Tok], mut p: usize) -> usize {
3951    while matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Newline)) {
3952        p += 1;
3953    }
3954    p
3955}
3956
3957/// Maximal `type_tag` match over toks (non-atomic: gaps free
3958/// everywhere): atoms with `<>` args, `|` unions, `name?:` fields.
3959/// Returns the exclusive end index, or `None` on shape miss.
3960fn parse_type_shape(toks: &[Tok], pos: usize) -> Option<usize> {
3961    let mut p = parse_type_atom(toks, skip_type_nl(toks, pos))?;
3962    loop {
3963        let q = skip_type_nl(toks, p);
3964        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('|'))) {
3965            return Some(p);
3966        }
3967        p = parse_type_atom(toks, skip_type_nl(toks, q + 1))?;
3968    }
3969}
3970
3971fn parse_type_atom(toks: &[Tok], pos: usize) -> Option<usize> {
3972    let pos = skip_type_nl(toks, pos);
3973    match toks.get(pos).map(|t| &t.kind) {
3974        Some(TokKind::Word(w)) if is_upper_ident(w) => {}
3975        _ => return None,
3976    }
3977    let mut p = skip_type_nl(toks, pos + 1);
3978    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('<'))) {
3979        p = parse_type_args(toks, skip_type_nl(toks, p + 1))?;
3980        p = skip_type_nl(toks, p);
3981        if !matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('>'))) {
3982            return None;
3983        }
3984        p += 1;
3985    }
3986    Some(p)
3987}
3988
3989fn parse_type_args(toks: &[Tok], pos: usize) -> Option<usize> {
3990    let mut p = parse_type_field(toks, skip_type_nl(toks, pos))?;
3991    loop {
3992        let q = skip_type_nl(toks, p);
3993        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(','))) {
3994            return Some(p);
3995        }
3996        p = parse_type_field(toks, skip_type_nl(toks, q + 1))?;
3997    }
3998}
3999
4000fn parse_type_field(toks: &[Tok], pos: usize) -> Option<usize> {
4001    let mut p = skip_type_nl(toks, pos);
4002    // Optional `name?:` prefix (lowercase names only, like the
4003    // grammar's `field_name`).
4004    if let Some(TokKind::Word(w)) = toks.get(p).map(|t| &t.kind)
4005        && is_lower_ident(w)
4006    {
4007        let mut q = skip_type_nl(toks, p + 1);
4008        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('?'))) {
4009            q = skip_type_nl(toks, q + 1);
4010        }
4011        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4012            p = skip_type_nl(toks, q + 1);
4013        }
4014    }
4015    parse_type_shape(toks, p)
4016}
4017
4018/// Single (non-block) `IF`: condition plus then-block with an
4019/// opportunistic `ELSE` chain (a malformed `ELSE` stays for the
4020/// element loop, which fails it in lowering exactly like the
4021/// grammar). `None` on shape miss (missing/joint-agnostic block or
4022/// unclassified bad condition: generic fails it); classified
4023/// expression failures (unknown/ambiguous callees) and inline-block
4024/// failures propagate (blocks lower here, so their errors surface
4025/// directly).
4026fn parse_if_at(
4027    toks: &[Tok],
4028    pos: usize,
4029    stmt: usize,
4030    ctx: &ParseCtx,
4031) -> Result<Option<(StepKind, usize)>, TokenError> {
4032    // Condition entry skips leading gap comments (`IF` uses `gap`).
4033    let mut lead = Cursor::expr(&toks[pos + 1..], stmt);
4034    lead.skip_gap();
4035    let mut cur = Cursor::expr(&toks[pos + 1 + lead.pos..], stmt);
4036    let cond = match parse_expr_checked(&mut cur, ctx) {
4037        Ok(expr) => expr,
4038        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4039        // Classified failures (unknown/ambiguous callees) name the
4040        // culprit instead of missing to the generic IF hint: the head
4041        // is unambiguously `IF`, so there is no alternative parse.
4042        Err(e) if e.kind.is_some() => return Err(e),
4043        Err(_) => return Ok(None),
4044    };
4045    let cond_end = pos + 1 + lead.pos + cur.pos;
4046    // Then-block: any gap (`gap` zero-width), never a template.
4047    let then_brace = match toks.get(cond_end) {
4048        Some(t)
4049            if matches!(
4050                &t.kind,
4051                TokKind::Group {
4052                    delim: GroupDelim::Brace,
4053                    ..
4054                }
4055            ) && !is_template_brace(t) =>
4056        {
4057            t
4058        }
4059        _ => return Ok(None),
4060    };
4061    let then_inner = match &then_brace.kind {
4062        TokKind::Group { inner, .. } => inner.clone(),
4063        _ => unreachable!(),
4064    };
4065    let then_body = parse_body_steps(&then_inner, stmt, ctx, false)?;
4066    let mut p = cond_end + 1;
4067    // Gap comments between the blocks and `ELSE` vanish (merge
4068    // junctions contribute newlines, crossed like `blank*`).
4069    {
4070        let mut gcur = Cursor::expr(&toks[p..], stmt);
4071        gcur.skip_gap_nl();
4072        p += gcur.pos;
4073    }
4074    let mut else_ifs = Vec::new();
4075    let mut else_body = None;
4076    loop {
4077        // `ELSE IF cond block`: any gaps (non-atomic chain).
4078        let is_else_if = matches!(
4079            toks.get(p).map(|t| &t.kind),
4080            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4081        ) && matches!(
4082            toks.get(p + 1).map(|t| &t.kind),
4083            Some(TokKind::Word(w)) if w == KEYWORD_IF
4084        );
4085        if is_else_if {
4086            let mut ecur = Cursor::expr(&toks[p + 2..], stmt);
4087            ecur.skip_gap();
4088            let econd = match parse_expr_checked(&mut ecur, ctx) {
4089                Ok(expr) => expr,
4090                Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4091                // Same classified-error rule as the `IF` head above:
4092                // an `ELSE IF` with a resolvable-but-unknown callee
4093                // names it instead of silently dropping the branch.
4094                Err(e) if e.kind.is_some() => return Err(e),
4095                Err(_) => break,
4096            };
4097            let ebrace = p + 2 + ecur.pos;
4098            let eblock_ok = matches!(
4099                toks.get(ebrace).map(|t| &t.kind),
4100                Some(TokKind::Group {
4101                    delim: GroupDelim::Brace,
4102                    ..
4103                })
4104            ) && toks.get(ebrace).is_some_and(|t| !is_template_brace(t));
4105            if !eblock_ok {
4106                break;
4107            }
4108            let einner = match &toks[ebrace].kind {
4109                TokKind::Group { inner, .. } => inner.clone(),
4110                _ => unreachable!(),
4111            };
4112            let ebody = parse_body_steps(&einner, stmt, ctx, false)?;
4113            else_ifs.push((Box::new(econd), ebody));
4114            p = ebrace + 1;
4115            // Gap comments before a further `ELSE` vanish too
4116            // (merge junctions contribute newlines).
4117            {
4118                let mut gcur = Cursor::expr(&toks[p..], stmt);
4119                gcur.skip_gap_nl();
4120                p += gcur.pos;
4121            }
4122            continue;
4123        }
4124        // `ELSE block`: same opportunism (a bare `ELSE` stays for
4125        // the loop, failing in lowering like the grammar).
4126        let is_else = matches!(
4127            toks.get(p).map(|t| &t.kind),
4128            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4129        ) && matches!(
4130            toks.get(p + 1).map(|t| &t.kind),
4131            Some(TokKind::Group {
4132                delim: GroupDelim::Brace,
4133                ..
4134            })
4135        ) && toks.get(p + 1).is_some_and(|t| !is_template_brace(t));
4136        if !is_else {
4137            break;
4138        }
4139        let einner = match &toks[p + 1].kind {
4140            TokKind::Group { inner, .. } => inner.clone(),
4141            _ => unreachable!(),
4142        };
4143        else_body = Some(parse_body_steps(&einner, stmt, ctx, false)?);
4144        p += 2;
4145        break;
4146    }
4147    let kind = StepKind::If {
4148        cond: Box::new(cond),
4149        then_body,
4150        else_ifs,
4151        else_body,
4152    };
4153    Ok(Some((kind, p - pos)))
4154}
4155
4156/// Single (non-block) `FOR`: `$var[: TYPE] (, $var[: TYPE])? IN
4157/// expr` plus block. Header shapes miss to generic (a third variable,
4158/// a missing block, a bad name all fail in lowering like the
4159/// grammar); completed headers validate counts and key types loudly.
4160/// Expression failures from inline blocks propagate (blocks lower
4161/// here); other expression failures miss (generic fails them like a
4162/// committed `instruction` would).
4163fn parse_for_at(
4164    toks: &[Tok],
4165    pos: usize,
4166    stmt: usize,
4167    ctx: &ParseCtx,
4168) -> Result<Option<(StepKind, usize)>, TokenError> {
4169    let mut p = pos + 1;
4170    let mut idents = Vec::new();
4171    let mut types = Vec::new();
4172    // First `$var[: TYPE]` (gapless `$var`; gaps free elsewhere).
4173    let Some((var1, _)) = peek_dollar_var(toks, p) else {
4174        return Ok(None);
4175    };
4176    idents.push(var1);
4177    p += 2;
4178    let mut cur = Cursor::expr(&toks[p..], stmt);
4179    cur.skip_gap();
4180    p += cur.pos;
4181    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4182        p += 1;
4183        let mut tcur = Cursor::expr(&toks[p..], stmt);
4184        tcur.skip_gap();
4185        let tstart = p + tcur.pos;
4186        let Some(tend) = parse_type_shape(toks, tstart) else {
4187            return Ok(None);
4188        };
4189        // `render_type_region` canonicalizes (shared spelling).
4190        types.push(render_type_region(&toks[tstart..tend], stmt)?);
4191        p = tend;
4192    }
4193    // Optional `, $var2[: TYPE2]`.
4194    {
4195        let mut ccur = Cursor::expr(&toks[p..], stmt);
4196        ccur.skip_gap();
4197        if matches!(
4198            ccur.toks.get(ccur.pos).map(|t| &t.kind),
4199            Some(TokKind::Punct(','))
4200        ) {
4201            ccur.pos += 1;
4202            ccur.skip_gap();
4203            let base = p + ccur.pos;
4204            let Some((var2, _)) = peek_dollar_var(toks, base) else {
4205                return Ok(None);
4206            };
4207            idents.push(var2);
4208            let mut q = base + 2;
4209            let mut qcur = Cursor::expr(&toks[q..], stmt);
4210            qcur.skip_gap();
4211            q += qcur.pos;
4212            if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4213                q += 1;
4214                let mut tcur = Cursor::expr(&toks[q..], stmt);
4215                tcur.skip_gap();
4216                let tstart = q + tcur.pos;
4217                let Some(tend) = parse_type_shape(toks, tstart) else {
4218                    return Ok(None);
4219                };
4220                types.push(render_type_region(&toks[tstart..tend], stmt)?);
4221                q = tend;
4222            }
4223            p = q;
4224        }
4225    }
4226    // `IN expr block`.
4227    {
4228        let mut icur = Cursor::expr(&toks[p..], stmt);
4229        icur.skip_gap();
4230        if !matches!(
4231            icur.toks.get(icur.pos).map(|t| &t.kind),
4232            Some(TokKind::Word(w)) if w == KEYWORD_IN
4233        ) {
4234            return Ok(None);
4235        }
4236        icur.pos += 1;
4237        p += icur.pos;
4238    }
4239    let mut ecur = Cursor::expr(&toks[p..], stmt);
4240    ecur.skip_gap();
4241    let in_expr = match parse_expr_checked(&mut ecur, ctx) {
4242        Ok(expr) => expr,
4243        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4244        // Classified failures name the callee: `FOR ... IN` is
4245        // committed once the header matched this far.
4246        Err(e) if e.kind.is_some() => return Err(e),
4247        Err(_) => return Ok(None),
4248    };
4249    p += ecur.pos;
4250    let block_ok = matches!(
4251        toks.get(p).map(|t| &t.kind),
4252        Some(TokKind::Group {
4253            delim: GroupDelim::Brace,
4254            ..
4255        })
4256    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4257    if !block_ok {
4258        return Ok(None);
4259    }
4260    let inner = match &toks[p].kind {
4261        TokKind::Group { inner, .. } => inner.clone(),
4262        _ => unreachable!(),
4263    };
4264    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4265    p += 1;
4266    if idents.len() != types.len() {
4267        return Err(TokenError {
4268            stmt,
4269            msg: format!(
4270                "FOR requires explicit types: FOR $item: TYPE IN <expr> (got {} vars, {} types)",
4271                idents.len(),
4272                types.len()
4273            ),
4274            line: 0,
4275            col: 0,
4276            kind: Some(ParseErrorKind::Validation {
4277                command: KEYWORD_FOR.to_string(),
4278            }),
4279        });
4280    }
4281    let (key_var, key_type, var, var_type) = match idents.len() {
4282        1 => (
4283            None,
4284            None,
4285            idents.into_iter().next().unwrap_or_default(),
4286            types.into_iter().next().unwrap_or_default(),
4287        ),
4288        2 => {
4289            let mut iv = idents.into_iter();
4290            let mut tv = types.into_iter();
4291            (
4292                Some(iv.next().unwrap_or_default()),
4293                Some(tv.next().unwrap_or_default()),
4294                iv.next().unwrap_or_default(),
4295                tv.next().unwrap_or_default(),
4296            )
4297        }
4298        _ => {
4299            return Err(TokenError {
4300                stmt,
4301                msg: "FOR requires one or two variables".to_string(),
4302                line: 0,
4303                col: 0,
4304                kind: Some(ParseErrorKind::Validation {
4305                    command: KEYWORD_FOR.to_string(),
4306                }),
4307            });
4308        }
4309    };
4310    if let Some(kt) = &key_type
4311        && kt != crate::TypeTag::String.name()
4312        && kt != crate::TypeTag::Int.name()
4313    {
4314        return Err(TokenError {
4315            stmt,
4316            msg: format!("FOR key variable must be INT or STRING, got {kt}"),
4317            line: 0,
4318            col: 0,
4319            kind: Some(ParseErrorKind::Validation {
4320                command: KEYWORD_FOR.to_string(),
4321            }),
4322        });
4323    }
4324    let kind = StepKind::For {
4325        key_var,
4326        key_type,
4327        var,
4328        var_type,
4329        in_expr,
4330        body,
4331    };
4332    Ok(Some((kind, p - pos)))
4333}
4334
4335/// Single (non-block) `WHILE`: condition plus block. `None` on
4336/// shape miss (missing block: generic fails it); classified
4337/// expression failures and inline-block failures propagate, other
4338/// expression failures miss (generic fails them like a committed
4339/// `instruction` would).
4340/// No leading gap-skip: `WHILE` takes `sep`, so a joint follower
4341/// never reaches here with a valid shape... (misses fall through
4342/// the same way regardless).
4343fn parse_while_single(
4344    toks: &[Tok],
4345    pos: usize,
4346    stmt: usize,
4347    ctx: &ParseCtx,
4348) -> Result<Option<(StepKind, usize)>, TokenError> {
4349    let mut cur = Cursor::expr(&toks[pos + 1..], stmt);
4350    let cond = match parse_expr_checked(&mut cur, ctx) {
4351        Ok(expr) => expr,
4352        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4353        // Same rule as `IF`: the head is unambiguous, so classified
4354        // failures name the culprit instead of the generic hint.
4355        Err(e) if e.kind.is_some() => return Err(e),
4356        Err(_) => return Ok(None),
4357    };
4358    let brace = pos + 1 + cur.pos;
4359    let block_ok = matches!(
4360        toks.get(brace).map(|t| &t.kind),
4361        Some(TokKind::Group {
4362            delim: GroupDelim::Brace,
4363            ..
4364        })
4365    ) && toks.get(brace).is_some_and(|t| !is_template_brace(t));
4366    if !block_ok {
4367        return Ok(None);
4368    }
4369    let inner = match &toks[brace].kind {
4370        TokKind::Group { inner, .. } => inner.clone(),
4371        _ => unreachable!(),
4372    };
4373    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4374    let kind = StepKind::While {
4375        cond: Box::new(cond),
4376        body,
4377    };
4378    Ok(Some((kind, brace + 1 - pos)))
4379}
4380
4381/// Single (non-block) `FUNC`: name, parenthesized params, block. The
4382/// shape parses purely first (misses fall to generic, declaring
4383/// nothing — the grammar only lowers matched pairs); then the name
4384/// declares in the enclosing scope before the body lowers (so
4385/// recursion resolves), and the body pushes a fresh scope.
4386/// Duplicates, reserved shadows, and parameter dupes fail loudly.
4387fn parse_func_at(
4388    toks: &[Tok],
4389    pos: usize,
4390    stmt: usize,
4391    ctx: &ParseCtx,
4392    is_async: bool,
4393) -> Result<Option<(StepKind, usize)>, TokenError> {
4394    let keyword = if is_async { "ASYNC FUNC" } else { KEYWORD_FUNC };
4395    let fail = |msg: String| TokenError {
4396        stmt,
4397        msg,
4398        line: 0,
4399        col: 0,
4400        kind: Some(ParseErrorKind::Validation {
4401            command: KEYWORD_FUNC.to_string(),
4402        }),
4403    };
4404    // Phase 1 (pure shape): name, parens, params, block presence.
4405    // Name: UPPERCASE ident (lowercase misses to generic, probed).
4406    let def_name = match toks.get(pos + 1).map(|t| &t.kind) {
4407        Some(TokKind::Word(w))
4408            if crate::resolve::check_func_ident(&lowering_ctx(stmt), w).is_ok() =>
4409        {
4410            w.clone()
4411        }
4412        _ => return Ok(None),
4413    };
4414    // Paren group at any gap (`gap` zero-width): params live inside
4415    // its inner tokens, parsed with `gap_nl` discipline (newlines ride
4416    // free like call args and generics, via the shared helper).
4417    let mut p = pos + 2;
4418    let paren_inner = match toks.get(p).map(|t| &t.kind) {
4419        Some(TokKind::Group {
4420            delim: GroupDelim::Paren,
4421            inner,
4422            ..
4423        }) => inner.clone(),
4424        _ => return Ok(None),
4425    };
4426    p += 1;
4427    let mut params = Vec::new();
4428    let mut seen_optional = false;
4429    {
4430        let mut pcur = Cursor::expr(&paren_inner, stmt);
4431        pcur.skip_gap_nl();
4432        if !pcur.done() {
4433            loop {
4434                let base = pcur.pos;
4435                let Some((pname, _)) = peek_dollar_var(&paren_inner, base) else {
4436                    return Err(fail(format!(
4437                        "FUNC {def_name} params must be `$name: TYPE` separated by commas"
4438                    )));
4439                };
4440                pcur.pos = base + 2;
4441                pcur.skip_gap_nl();
4442                // Optional params carry `?` before the colon
4443                // (`$flag?: BOOL`); all params are otherwise required.
4444                let optional = pcur.eat_punct('?');
4445                pcur.skip_gap_nl();
4446                if !pcur.eat_punct(':') {
4447                    return Err(fail(format!(
4448                        "FUNC {def_name} param `${pname}` needs `: TYPE` after the name"
4449                    )));
4450                }
4451                pcur.skip_gap_nl();
4452                let tstart = pcur.pos;
4453                let Some(tend) = parse_type_shape(&paren_inner, tstart) else {
4454                    let got = match paren_inner.get(tstart).map(|tok| &tok.kind) {
4455                        Some(TokKind::Word(word)) => format!("; got `{word}`"),
4456                        _ => String::new(),
4457                    };
4458                    return Err(fail(format!(
4459                        "FUNC {def_name} param `${pname}` needs an uppercase type after `:` (e.g. STRING, INT, BOOL){got}"
4460                    )));
4461                };
4462                // Post-match the span holds words/puncts only, so the
4463                // shared renderer cannot fail; stay failed regardless.
4464                let ptype =
4465                    render_type_region(&paren_inner[tstart..tend], stmt).unwrap_or_default();
4466                if optional {
4467                    seen_optional = true;
4468                } else if seen_optional {
4469                    return Err(fail(format!(
4470                        "FUNC {def_name} optional ? params must be trailing: `${pname}` follows an optional param"
4471                    )));
4472                }
4473                params.push((pname, ptype, optional));
4474                pcur.pos = tend;
4475                pcur.skip_gap_nl();
4476                if pcur.eat_punct(',') {
4477                    pcur.skip_gap_nl();
4478                    // Trailing comma misses (a param must follow).
4479                    if pcur.done() {
4480                        return Err(fail(format!(
4481                            "FUNC {def_name} params must not end with a trailing comma"
4482                        )));
4483                    }
4484                    continue;
4485                }
4486                break;
4487            }
4488            // Trailing junk (including newlines) misses to generic.
4489            pcur.skip_gap_nl();
4490            if !pcur.done() {
4491                return Err(fail(format!(
4492                    "FUNC {def_name} params must be `$name: TYPE` separated by commas"
4493                )));
4494            }
4495        }
4496    }
4497    // Mandatory return annotation: FUNC NAME(...): RET { ... }.
4498    // After paren group, require gap-optional colon then type shape.
4499    // Missing colon after matched name+parens is a hard parse error
4500    // (no legacy fallback). Non-block tails (neither colon nor brace)
4501    // miss to generic (probed FUNC FOO() ECHO hi).
4502    let is_colon = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')));
4503    if !is_colon {
4504        let is_brace = matches!(
4505            toks.get(p).map(|t| &t.kind),
4506            Some(TokKind::Group {
4507                delim: GroupDelim::Brace,
4508                ..
4509            })
4510        ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4511        if is_brace {
4512            return Err(fail(format!(
4513                "{keyword} {def_name} requires a return type : TYPE (e.g. : VOID, : STRING)"
4514            )));
4515        }
4516        return Ok(None);
4517    }
4518    let Some(ret_end) = parse_type_shape(toks, p + 1) else {
4519        return Err(fail(format!(
4520            "{keyword} {def_name} requires a return type : TYPE after ':'"
4521        )));
4522    };
4523    let return_type = render_type_region(&toks[p + 1..ret_end], stmt).map_err(|_| {
4524        fail(format!(
4525            "{keyword} {def_name} requires a return type : TYPE after ':'"
4526        ))
4527    })?;
4528    let return_type = crate::canonicalize_spelling(&return_type);
4529    p = ret_end;
4530    // Block at any gap (never a template); missing blocks miss to
4531    // generic (probed FUNC FOO() ECHO hi).
4532    let block_ok = matches!(
4533        toks.get(p).map(|t| &t.kind),
4534        Some(TokKind::Group {
4535            delim: GroupDelim::Brace,
4536            ..
4537        })
4538    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4539    if !block_ok {
4540        return Ok(None);
4541    }
4542    // Phase 2 (effects): reserved shadows and same-scope duplicates
4543    // fail at the definition line, verbatim.
4544    if ctx.reserved.contains(&def_name) || ctx.modules.reserved_base_names().contains(&def_name) {
4545        return Err(fail(format!(
4546            "FUNC {def_name} cannot shadow reserved function `{def_name}`"
4547        )));
4548    }
4549    if !ctx.declare_func(&def_name) {
4550        return Err(fail(format!(
4551            "duplicate function `{def_name}` in same scope"
4552        )));
4553    }
4554    let mut seen = HashSet::new();
4555    for (pname, _, _) in &params {
4556        if !seen.insert(pname.clone()) {
4557            return Err(fail(format!(
4558                "FUNC {def_name} declares duplicate parameter ${pname}"
4559            )));
4560        }
4561    }
4562    let inner = match &toks[p].kind {
4563        TokKind::Group { inner, .. } => inner.clone(),
4564        _ => unreachable!(),
4565    };
4566    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4567    let kind = StepKind::FuncDef {
4568        name: def_name,
4569        params,
4570        return_type,
4571        is_async,
4572        body,
4573        docs: None,
4574    };
4575    Ok(Some((kind, p + 1 - pos)))
4576}
4577
4578/// `REMOTE` header bindings `[$var, env:KEY]` over a bracket
4579/// group's inner tokens: comma-separated, newlines and comments free
4580/// like `gap_nl`. `$`+name and `env`+`:`+key all ride gapless (the
4581/// enclosing rule is compound-atomic). Empty lists parse (probed);
4582/// anything else misses the shape (`None`: generic fails it like
4583/// the grammar's dropped optional).
4584#[allow(clippy::type_complexity)]
4585fn parse_remote_bindings(
4586    inner: &[Tok],
4587    stmt: usize,
4588) -> Result<Option<(Vec<String>, Vec<String>)>, TokenError> {
4589    let _ = stmt;
4590    let mut parts: Vec<&[Tok]> = Vec::new();
4591    let mut start = 0;
4592    for (i, tok) in inner.iter().enumerate() {
4593        if matches!(&tok.kind, TokKind::Punct(',')) {
4594            parts.push(&inner[start..i]);
4595            start = i + 1;
4596        }
4597    }
4598    parts.push(&inner[start..]);
4599    // An empty list (`[]`, whitespace/comment-only) holds no bindings.
4600    if parts.len() == 1
4601        && parts[0]
4602            .iter()
4603            .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
4604    {
4605        return Ok(Some((Vec::new(), Vec::new())));
4606    }
4607    let mut vars = Vec::new();
4608    let mut env = Vec::new();
4609    for part in parts {
4610        // Edges admit gaps, newlines, and comments, like `gap_nl`.
4611        let mut part = part;
4612        while matches!(
4613            part.first().map(|t| &t.kind),
4614            Some(TokKind::Newline | TokKind::Comment(_))
4615        ) {
4616            part = &part[1..];
4617        }
4618        while matches!(
4619            part.last().map(|t| &t.kind),
4620            Some(TokKind::Newline | TokKind::Comment(_))
4621        ) {
4622            part = &part[..part.len() - 1];
4623        }
4624        // `$var`: gapless `$` + ident.
4625        if matches!(part.first().map(|t| &t.kind), Some(TokKind::Punct('$'))) && part.len() == 2 {
4626            if part[1].joint
4627                && let TokKind::Word(w) = &part[1].kind
4628                && is_ident_word(w)
4629            {
4630                vars.push(w.clone());
4631                continue;
4632            }
4633            return Ok(None);
4634        }
4635        // `env:KEY`: gapless triple with an uppercase key.
4636        if part.len() == 3
4637            && matches!(&part[0].kind, TokKind::Word(w) if w == "env")
4638            && matches!(&part[1].kind, TokKind::Punct(':'))
4639            && part[1].joint
4640            && part[2].joint
4641        {
4642            if let TokKind::Word(k) = &part[2].kind
4643                && is_env_key(k)
4644            {
4645                env.push(k.clone());
4646                continue;
4647            }
4648            return Ok(None);
4649        }
4650        return Ok(None);
4651    }
4652    Ok(Some((vars, env)))
4653}
4654
4655/// `IMPORT` statement at `pos` (#115): module form (`IMPORT MOD`,
4656/// `IMPORT [A, B]`), file form (`IMPORT "p" AS A`,
4657/// `IMPORT ["p" AS A]`), mixed/multi forms
4658/// (`IMPORT [STD, "p" AS A, "q" AS B]`, multi-line included), and
4659/// selective harvests (`IMPORT [[F, G FROM "p" (AS A)?]]`).
4660/// Returns module names plus `ImportFile`/`ImportFuncs` steps in source
4661/// order, plus tokens consumed (relative to `pos`), or `None` on shape
4662/// miss (generic lowering fails it like the grammar). Validation is
4663/// hard: unknown modules, bad names, collisions, templates, and remote
4664/// URLs fail here, and validated entries register immediately
4665/// (modules, aliases, and bare harvest names share the innermost
4666/// frames).
4667type ImportEntries = (Vec<String>, Vec<StepKind>);
4668
4669fn parse_import_statement(
4670    toks: &[Tok],
4671    pos: usize,
4672    stmt: usize,
4673    ctx: &ParseCtx,
4674) -> Result<Option<(ImportEntries, usize)>, TokenError> {
4675    let fail = |msg: String| TokenError {
4676        stmt,
4677        msg,
4678        line: 0,
4679        col: 0,
4680        kind: Some(ParseErrorKind::Validation {
4681            command: KEYWORD_IMPORT.to_string(),
4682        }),
4683    };
4684    let next = match toks.get(pos + 1) {
4685        // `sep` after `IMPORT`: joint followers miss.
4686        Some(t) if !t.joint => t,
4687        _ => return Ok(None),
4688    };
4689    // Parse entries first, validate in source order after.
4690    enum RawEntry {
4691        Module(String),
4692        File {
4693            path: String,
4694            alias: String,
4695        },
4696        From {
4697            func_names: Vec<String>,
4698            type_names: Vec<String>,
4699            path: String,
4700            alias: Option<String>,
4701        },
4702    }
4703    let mut raw: Vec<RawEntry> = Vec::new();
4704    let used;
4705    if matches!(
4706        &next.kind,
4707        TokKind::Group {
4708            delim: GroupDelim::Brace,
4709            ..
4710        }
4711    ) {
4712        return Ok(None);
4713    }
4714    if let TokKind::Group {
4715        delim: GroupDelim::Bracket,
4716        inner,
4717        ..
4718    } = &next.kind
4719    {
4720        // Comma-separated entries, `ws` gaps (newlines ok inside and
4721        // around entries, comments MISS — `ws` admits neither).
4722        // Single-file multi-name harvests skip the split: in
4723        // `[TYPE A, TYPE B FROM "f"]` the first comma-part (`[TYPE A]`)
4724        // carries no FROM and is invalid alone, so the whole bracket
4725        // is one harvest (see `whole_file_harvest`).
4726        // Bare-multi hint: `[FOO, BAR FROM "f"]` reads FOO as a
4727        // module for back-compat (bare words stay modules in single
4728        // brackets). If that word is not a known module but a harvest
4729        // follows, fail fast naming the two valid spellings instead
4730        // of the misleading unknown-module error.
4731        let whole = whole_file_harvest(inner);
4732        if whole.is_none()
4733            && let Some(word) = single_bare_first_part(inner)
4734            && !ctx.modules.modules.contains_key(word)
4735            && has_top_level_from_after_comma(inner)
4736        {
4737            return Err(fail(format!(
4738                "unknown module `{word}`; to harvest multiple names qualify each kind (`IMPORT [FUNC FOO, FUNC BAR FROM \"f\"]`)"
4739            )));
4740        }
4741        let mut parts: Vec<&[Tok]> = Vec::new();
4742        if whole.is_some() {
4743            parts.push(inner);
4744        } else {
4745            let mut start = 0;
4746            for (i, tok) in inner.iter().enumerate() {
4747                if matches!(&tok.kind, TokKind::Punct(',')) {
4748                    parts.push(&inner[start..i]);
4749                    start = i + 1;
4750                }
4751            }
4752            parts.push(&inner[start..]);
4753        }
4754        for part in parts {
4755            let dense: Vec<&Tok> = part
4756                .iter()
4757                .filter(|t| !matches!(&t.kind, TokKind::Newline))
4758                .collect();
4759            // `[[F, G FROM "path" (AS ALIAS)?]]`: selective function
4760            // harvest. Anything else bracketed here misses.
4761            if let [bracket] = dense.as_slice()
4762                && let TokKind::Group {
4763                    delim: GroupDelim::Bracket,
4764                    inner,
4765                    ..
4766                } = &bracket.kind
4767            {
4768                let Some(HarvestImport {
4769                    func_names,
4770                    type_names,
4771                    path,
4772                    alias,
4773                }) = parse_from_entry(inner)
4774                else {
4775                    return Ok(None);
4776                };
4777                raw.push(RawEntry::From {
4778                    func_names,
4779                    type_names,
4780                    path,
4781                    alias,
4782                });
4783                continue;
4784            }
4785            // `[F FROM "path" (AS ALIAS)?]`: single harvest without
4786            // inner brackets. The `FROM` keyword is the discriminant
4787            // (module and file parts never contain a top-level one);
4788            // multi-name harvests keep `[[F, G FROM ...]]` so the comma
4789            // stays grouped inside its own scope.
4790            if dense.len() >= 3 {
4791                let owned: Vec<Tok> = dense.iter().map(|t| (*t).clone()).collect();
4792                if let Some(HarvestImport {
4793                    func_names,
4794                    type_names,
4795                    path,
4796                    alias,
4797                }) = parse_from_entry(&owned)
4798                {
4799                    raw.push(RawEntry::From {
4800                        func_names,
4801                        type_names,
4802                        path,
4803                        alias,
4804                    });
4805                    continue;
4806                }
4807            }
4808            match dense.as_slice() {
4809                [tok] => match &tok.kind {
4810                    TokKind::Word(w) if is_upper_ident(w) => {
4811                        raw.push(RawEntry::Module(w.clone()));
4812                    }
4813                    _ => return Ok(None),
4814                },
4815                [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
4816                    let (
4817                        TokKind::Str { text, .. },
4818                        TokKind::Word(as_word),
4819                        TokKind::Word(alias_word),
4820                    ) = (&path_tok.kind, &as_tok.kind, &alias_tok.kind)
4821                    else {
4822                        return Ok(None);
4823                    };
4824                    if as_word != KEYWORD_AS {
4825                        return Ok(None);
4826                    }
4827                    raw.push(RawEntry::File {
4828                        path: text.clone(),
4829                        alias: alias_word.clone(),
4830                    });
4831                }
4832                _ => return Ok(None),
4833            }
4834        }
4835        if raw.is_empty() {
4836            return Ok(None);
4837        }
4838        used = 2;
4839    } else if let TokKind::Word(w) = &next.kind {
4840        // Bare `IMPORT MOD` (single module, probed).
4841        if !is_upper_ident(w) {
4842            return Ok(None);
4843        }
4844        raw.push(RawEntry::Module(w.clone()));
4845        used = 2;
4846    } else if let TokKind::Str { text, .. } = &next.kind {
4847        // Bare `IMPORT "path" AS ALIAS`.
4848        let (Some(as_tok), Some(alias_tok)) = (toks.get(pos + 2), toks.get(pos + 3)) else {
4849            return Ok(None);
4850        };
4851        if as_tok.joint || alias_tok.joint {
4852            return Ok(None);
4853        }
4854        let (TokKind::Word(as_word), TokKind::Word(alias_word)) = (&as_tok.kind, &alias_tok.kind)
4855        else {
4856            return Ok(None);
4857        };
4858        if as_word != KEYWORD_AS {
4859            return Ok(None);
4860        }
4861        raw.push(RawEntry::File {
4862            path: text.clone(),
4863            alias: alias_word.clone(),
4864        });
4865        used = 4;
4866    } else {
4867        return Ok(None);
4868    }
4869    // Validate in source order: unknown modules fail with the exact
4870    // backend message (sorted known list); file and harvest entries
4871    // validate hard (bad names, collisions, templates, remote URLs).
4872    let mut modules = Vec::new();
4873    let mut steps = Vec::new();
4874    for entry in raw {
4875        match entry {
4876            RawEntry::Module(module) => {
4877                if !ctx.modules.modules.contains_key(&module) {
4878                    let mut known: Vec<String> = ctx.modules.modules.keys().cloned().collect();
4879                    known.sort();
4880                    return Err(fail(format!(
4881                        "unknown module `{module}`; known modules: {}",
4882                        known.join(", ")
4883                    )));
4884                }
4885                ctx.import_into_frame(std::slice::from_ref(&module));
4886                modules.push(module);
4887            }
4888            RawEntry::File { path, alias } => {
4889                let (path, alias) = validate_file_import(&path, &alias, ctx).map_err(fail)?;
4890                steps.push(StepKind::ImportFile { path, alias });
4891            }
4892            RawEntry::From {
4893                func_names,
4894                type_names,
4895                path,
4896                alias,
4897            } => {
4898                let HarvestImport {
4899                    func_names,
4900                    type_names,
4901                    path,
4902                    alias,
4903                } = validate_from_import(&func_names, &type_names, &path, alias.as_deref(), ctx)
4904                    .map_err(fail)?;
4905                steps.push(StepKind::ImportFuncs {
4906                    path,
4907                    alias,
4908                    func_names,
4909                    type_names,
4910                });
4911            }
4912        }
4913    }
4914    Ok(Some(((modules, steps), used)))
4915}
4916
4917/// Single file import for value positions (#115): exactly one
4918/// `"path" AS ALIAS` entry and no modules. Anything else shaped like an
4919/// import is a hard error naming the restriction; shape misses return
4920/// `None` for the generic path.
4921fn parse_single_file_import(
4922    toks: &[Tok],
4923    pos: usize,
4924    stmt: usize,
4925    ctx: &ParseCtx,
4926) -> Result<Option<(String, String, usize)>, TokenError> {
4927    let Some(((modules, mut kinds), used)) = parse_import_statement(toks, pos, stmt, ctx)? else {
4928        return Ok(None);
4929    };
4930    if !modules.is_empty() || !matches!(kinds.as_slice(), [StepKind::ImportFile { .. }]) {
4931        return Err(TokenError {
4932            stmt,
4933            msg: if !modules.is_empty()
4934                || kinds
4935                    .iter()
4936                    .any(|k| matches!(k, StepKind::ImportFuncs { .. }))
4937            {
4938                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>]); modules and function harvests stay at statement level".to_string()
4939            } else {
4940                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>])"
4941                    .to_string()
4942            },
4943            line: 0,
4944            col: 0,
4945            kind: Some(ParseErrorKind::Validation {
4946                command: KEYWORD_IMPORT.to_string(),
4947            }),
4948        });
4949    }
4950    let Some(StepKind::ImportFile { path, alias }) = kinds.pop() else {
4951        unreachable!("length and variant checked above")
4952    };
4953    Ok(Some((path, alias, used)))
4954}
4955
4956/// One `EXPORT` name: an uppercase word with an optional joint
4957/// `::UPPER` tail. Returns the name and tokens consumed, or `None`
4958/// on shape miss.
4959fn parse_export_name(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
4960    let head = match toks.get(pos).map(|t| &t.kind) {
4961        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
4962        _ => return None,
4963    };
4964    let mut name = head;
4965    let mut used = 1;
4966    // Greedy-prefix `::tail` (atomic, like the grammar): a valid
4967    // tail joins, an invalid one stays trailing (failing downstream
4968    // exactly like the grammar's committed prefix).
4969    if matches!(
4970        toks.get(pos + 1).map(|t| &t.kind),
4971        Some(TokKind::Punct(':'))
4972    ) && toks.get(pos + 1).is_some_and(|t| t.joint)
4973        && matches!(
4974            toks.get(pos + 2).map(|t| &t.kind),
4975            Some(TokKind::Punct(':'))
4976        )
4977        && toks.get(pos + 2).is_some_and(|t| t.joint)
4978        && let Some(TokKind::Word(tail)) = toks.get(pos + 3).map(|t| &t.kind)
4979        && toks[pos + 3].joint
4980        && is_upper_ident(tail)
4981    {
4982        name.push_str(MODULE_SEPARATOR);
4983        name.push_str(tail);
4984        used = 4;
4985    }
4986    Some((name, used))
4987}
4988
4989/// One selective harvest (`[[F, G FROM "path" (AS ALIAS)?]]`): the
4990/// wanted function and type names plus the path and optional alias.
4991/// Bare names are functions; `TYPE`/`FUNC` prefixes select the kind
4992/// explicitly (`[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`).
4993struct HarvestImport {
4994    func_names: Vec<String>,
4995    type_names: Vec<String>,
4996    path: String,
4997    alias: Option<String>,
4998}
4999
5000/// One `[[F, G FROM "path" (AS ALIAS)?]]` entry: selective function
5001/// harvest with optional `TYPE`/`FUNC` qualifiers per name:
5002/// `[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`
5003/// (bare stays func for back-compat).
5004/// Returns the harvest, or `None` on shape miss (generic lowering fails
5005/// it). Name case is validated hard by the caller, like file aliases.
5006fn parse_from_entry(inner: &[Tok]) -> Option<HarvestImport> {
5007    let dense: Vec<&Tok> = inner
5008        .iter()
5009        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5010        .collect();
5011    let from = dense
5012        .iter()
5013        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5014    if from == 0 {
5015        return None;
5016    }
5017    // Names: comma-separated entries, each `NAME` (func) or
5018    // `TYPE NAME` / `FUNC NAME` (explicit kind for clarity).
5019    let mut func_names = Vec::new();
5020    let mut type_names = Vec::new();
5021    let mut start = 0;
5022    let head = &dense[..from];
5023    // Local helper: classify one comma-separated part.
5024    fn classify_part(part: &[&Tok]) -> Option<(bool, String)> {
5025        match part {
5026            [tok] => {
5027                let TokKind::Word(w) = &tok.kind else {
5028                    return None;
5029                };
5030                Some((false, w.clone()))
5031            }
5032            // `TYPE NAME` / `FUNC NAME`: the name must be `sep` (gapped
5033            // from the kind); the kind may be joint to a preceding `[`
5034            // or `,` (no space required there), so only the name's joint
5035            // flag matters.
5036            [kind_tok, name_tok] if !name_tok.joint => {
5037                let (TokKind::Word(kind), TokKind::Word(name)) = (&kind_tok.kind, &name_tok.kind)
5038                else {
5039                    return None;
5040                };
5041                if kind == KEYWORD_TYPE {
5042                    Some((true, name.clone()))
5043                } else if kind == KEYWORD_FUNC {
5044                    Some((false, name.clone()))
5045                } else {
5046                    None
5047                }
5048            }
5049            _ => None,
5050        }
5051    }
5052    for (i, tok) in head.iter().enumerate() {
5053        if matches!(&tok.kind, TokKind::Punct(',')) {
5054            let part = &head[start..i];
5055            let (is_type, name) = classify_part(part)?;
5056            if is_type {
5057                type_names.push(name);
5058            } else {
5059                func_names.push(name);
5060            }
5061            start = i + 1;
5062        }
5063    }
5064    let part = &head[start..];
5065    let (is_type, name) = classify_part(part)?;
5066    if is_type {
5067        type_names.push(name);
5068    } else {
5069        func_names.push(name);
5070    }
5071    // Tail: `"path"` or bare `MODULE` with an optional gapped `AS ALIAS`.
5072    // Quoted is a file path (module fallback only when no file matches);
5073    // bare is a host module (no file probe ambiguity).
5074    let tail = &dense[from + 1..];
5075    let path_text = |tok: &Tok| match &tok.kind {
5076        TokKind::Str { text, .. } => Some(text.clone()),
5077        TokKind::Word(w) if is_upper_ident(w) => Some(w.clone()),
5078        _ => None,
5079    };
5080    match tail {
5081        [path_tok] => {
5082            let text = path_text(path_tok)?;
5083            Some(HarvestImport {
5084                func_names,
5085                type_names,
5086                path: text,
5087                alias: None,
5088            })
5089        }
5090        [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5091            let text = path_text(path_tok)?;
5092            let (TokKind::Word(as_word), TokKind::Word(alias_word)) =
5093                (&as_tok.kind, &alias_tok.kind)
5094            else {
5095                return None;
5096            };
5097            if as_word != KEYWORD_AS {
5098                return None;
5099            }
5100            Some(HarvestImport {
5101                func_names,
5102                type_names,
5103                path: text,
5104                alias: Some(alias_word.clone()),
5105            })
5106        }
5107        _ => None,
5108    }
5109}
5110
5111/// First comma-part of a bracket when it is exactly one bare
5112/// uppercase word: the back-compat module reading. Anything else
5113/// (prefixed names, groups, multiple words) is not a bare module.
5114fn single_bare_first_part(inner: &[Tok]) -> Option<&str> {
5115    let end = inner
5116        .iter()
5117        .position(|t| matches!(&t.kind, TokKind::Punct(',')))
5118        .unwrap_or(inner.len());
5119    let mut words = inner[..end]
5120        .iter()
5121        .filter(|t| !matches!(&t.kind, TokKind::Newline));
5122    match (words.next(), words.next()) {
5123        (Some(tok), None) => match &tok.kind {
5124            TokKind::Word(w) if is_upper_ident(w) => Some(w.as_str()),
5125            _ => None,
5126        },
5127        _ => None,
5128    }
5129}
5130
5131/// Whether a top-level `FROM` follows the first top-level comma:
5132/// distinguishes a module-plus-harvest entry (`[STD, T FROM "f"]`)
5133/// from a bare word the author meant as a harvest name.
5134fn has_top_level_from_after_comma(inner: &[Tok]) -> bool {
5135    let mut seen_comma = false;
5136    for tok in inner {
5137        match &tok.kind {
5138            TokKind::Punct(',') => seen_comma = true,
5139            TokKind::Word(w) if seen_comma && w == KEYWORD_FROM => return true,
5140            _ => {}
5141        }
5142    }
5143    false
5144}
5145
5146/// Whole-bracket single-file harvest (`[TYPE A, TYPE B FROM "f"]`):
5147/// the comma-split would orphan `[TYPE A]` (no FROM, invalid alone),
5148/// so the entire bracket parses as one harvest. Only explicitly
5149/// prefixed names qualify: a bare word keeps its legacy module
5150/// reading, so `[STD, TYPE T FROM "f"]` still splits into a module
5151/// plus a harvest instead of harvesting STD as a function.
5152fn whole_file_harvest(inner: &[Tok]) -> Option<HarvestImport> {
5153    let owned: Vec<Tok> = inner.to_vec();
5154    let harvest = parse_from_entry(&owned)?;
5155    let dense: Vec<&Tok> = inner
5156        .iter()
5157        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5158        .collect();
5159    let from = dense
5160        .iter()
5161        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5162    let mut start = 0;
5163    for (i, tok) in dense[..from].iter().enumerate() {
5164        if matches!(&tok.kind, TokKind::Punct(',')) {
5165            if !is_prefixed_name(&dense[start..i]) {
5166                return None;
5167            }
5168            start = i + 1;
5169        }
5170    }
5171    if !is_prefixed_name(&dense[start..from]) {
5172        return None;
5173    }
5174    Some(harvest)
5175}
5176
5177/// One explicitly prefixed name (`TYPE NAME` / `FUNC NAME`): the name
5178/// stays gapped from its kind; the kind may joint to `[` or `,`.
5179fn is_prefixed_name(part: &[&Tok]) -> bool {
5180    match part {
5181        [kind_tok, name_tok] if !name_tok.joint => {
5182            matches!(
5183                (&kind_tok.kind, &name_tok.kind),
5184                (
5185                    TokKind::Word(kind),
5186                    TokKind::Word(_)
5187                ) if kind == KEYWORD_TYPE || kind == KEYWORD_FUNC
5188            )
5189        }
5190        _ => false,
5191    }
5192}
5193
5194/// Validate an `IMPORT` alias: hard errors (never shape misses) plus
5195/// registration into the innermost import frame.
5196fn validate_import_alias(alias: &str, ctx: &ParseCtx) -> Result<String, String> {
5197    if !is_upper_ident(alias) {
5198        return Err(format!(
5199            "IMPORT alias must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{alias}`"
5200        ));
5201    }
5202    if ctx.modules.modules.contains_key(alias) {
5203        return Err(format!(
5204            "IMPORT alias `{alias}` collides with module `{alias}`"
5205        ));
5206    }
5207    let (_, imports) = ctx.visible_snapshot();
5208    if imports.iter().any(|i| i == alias) {
5209        return Err(format!("duplicate IMPORT alias `{alias}`"));
5210    }
5211    ctx.import_into_frame(std::slice::from_ref(&alias.to_string()));
5212    Ok(alias.to_string())
5213}
5214
5215/// Validate an `IMPORT` path: hard errors, never shape misses.
5216fn validate_import_path(path: &str) -> Result<String, String> {
5217    if path.is_empty() {
5218        return Err("IMPORT path must not be empty".to_string());
5219    }
5220    if path.contains("{{") {
5221        return Err("IMPORT path must be a literal string (no {{ }} templates)".to_string());
5222    }
5223    if path.contains("://") {
5224        return Err(
5225            "remote imports are deferred to #270 (net: Run scripts from a remote URL)".to_string(),
5226        );
5227    }
5228    Ok(path.to_string())
5229}
5230
5231/// Validate a file-import path/alias pair: hard errors (never shape
5232/// misses) plus alias registration into the innermost import frame.
5233fn validate_file_import(
5234    path: &str,
5235    alias: &str,
5236    ctx: &ParseCtx,
5237) -> Result<(String, String), String> {
5238    let alias = validate_import_alias(alias, ctx)?;
5239    let path = validate_import_path(path)?;
5240    Ok((path, alias))
5241}
5242
5243/// Validate a `[[F, G FROM "path" (AS ALIAS)?]]` entry: hard errors
5244/// (never shape misses). Bare func names declare into the innermost
5245/// `FUNC` frame so calls resolve statically; the runtime defines them
5246/// (and fails unknown names there). Type names need no func-frame
5247/// declaration (types resolve through the global type directory);
5248/// the runtime validates them against the file's `EXPORT TYPE` list.
5249/// An alias registers like a file import.
5250fn validate_from_import(
5251    func_names: &[String],
5252    type_names: &[String],
5253    path: &str,
5254    alias: Option<&str>,
5255    ctx: &ParseCtx,
5256) -> Result<HarvestImport, String> {
5257    let path = validate_import_path(path)?;
5258    let mut out_func_names = Vec::with_capacity(func_names.len());
5259    for name in func_names {
5260        if !is_upper_ident(name) {
5261            return Err(format!(
5262                "IMPORT function names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
5263            ));
5264        }
5265        if ctx.reserved.contains(name) {
5266            return Err(format!("cannot shadow reserved function `{name}`"));
5267        }
5268        out_func_names.push(name.clone());
5269    }
5270    let mut out_type_names = Vec::with_capacity(type_names.len());
5271    for name in type_names {
5272        if !is_upper_ident(name) {
5273            return Err(format!(
5274                "IMPORT type names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
5275            ));
5276        }
5277        out_type_names.push(name.clone());
5278    }
5279    if out_func_names.is_empty() && out_type_names.is_empty() {
5280        return Err("IMPORT harvest needs at least one function or type name".to_string());
5281    }
5282    if let Some(alias) = alias {
5283        let alias = validate_import_alias(alias, ctx)?;
5284        Ok(HarvestImport {
5285            func_names: out_func_names,
5286            type_names: out_type_names,
5287            path,
5288            alias: Some(alias),
5289        })
5290    } else {
5291        for name in &out_func_names {
5292            if !ctx.declare_func(name) {
5293                return Err(format!("duplicate function `{name}` in same scope"));
5294            }
5295        }
5296        // Type harvests without alias land bare in the global type
5297        // directory: duplicates across files fail at import time
5298        // (different targets), not at parse time (targets need IO).
5299        Ok(HarvestImport {
5300            func_names: out_func_names,
5301            type_names: out_type_names,
5302            path,
5303            alias: None,
5304        })
5305    }
5306}
5307
5308/// One `EXPORT ...` name list: function names plus type names in
5309/// source order. Bare names are functions; explicit `TYPE`/`FUNC`
5310/// prefixes select the kind.
5311struct ExportNames {
5312    func_names: Vec<String>,
5313    type_names: Vec<String>,
5314}
5315
5316/// `EXPORT ...` names at `pos`: bracket list (strict, `ws` gaps:
5317/// newlines ok, comments miss) or a bare greedy-prefix name.
5318/// Supports explicit `TYPE`/`FUNC` qualifiers for clarity:
5319/// `EXPORT TYPE FOO`, `EXPORT TYPE [A, B]`, `EXPORT FUNC FOO`,
5320/// plus mixed `EXPORT [TYPE A, FUNC B, C]` (bare stays func).
5321/// Returns the name lists plus tokens consumed, or `None` on shape
5322/// miss (generic fails it in lowering like the grammar). Recording and
5323/// duplicate checks live with the caller (they need the guard and
5324/// level context).
5325fn parse_export_at(toks: &[Tok], pos: usize) -> Option<(ExportNames, usize)> {
5326    let next = match toks.get(pos + 1) {
5327        // `sep` after `EXPORT`: joint followers miss.
5328        Some(t) if !t.joint => t,
5329        _ => return None,
5330    };
5331    // Explicit `EXPORT TYPE ...` or `EXPORT FUNC ...` prefix.
5332    if let TokKind::Word(w) = &next.kind
5333        && (w == KEYWORD_TYPE || w == KEYWORD_FUNC)
5334    {
5335        let is_type = w == KEYWORD_TYPE;
5336        let after = match toks.get(pos + 2) {
5337            Some(t) if !t.joint => t,
5338            _ => return None,
5339        };
5340        if let TokKind::Group {
5341            delim: GroupDelim::Bracket,
5342            inner,
5343            ..
5344        } = &after.kind
5345        {
5346            let mut func_names = Vec::new();
5347            let mut type_names = Vec::new();
5348            for part in split_bracket_entries(inner) {
5349                let mut part = part;
5350                while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
5351                    part = &part[1..];
5352                }
5353                while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
5354                    part = &part[..part.len() - 1];
5355                }
5356                // A trailing comma leaves an empty final entry; it
5357                // carries no name and must not fail the list.
5358                if part.is_empty() {
5359                    continue;
5360                }
5361                let (name, used) = parse_export_name(part, 0)?;
5362                if used != part.len() {
5363                    return None;
5364                }
5365                if is_type {
5366                    type_names.push(name);
5367                } else {
5368                    func_names.push(name);
5369                }
5370            }
5371            if func_names.is_empty() && type_names.is_empty() {
5372                return None;
5373            }
5374            return Some((
5375                ExportNames {
5376                    func_names,
5377                    type_names,
5378                },
5379                3,
5380            ));
5381        }
5382        if matches!(&after.kind, TokKind::Group { .. }) {
5383            return None;
5384        }
5385        let (name, used) = parse_export_name(toks, pos + 2)?;
5386        // Bare name after TYPE/FUNC prefix must consume exactly one
5387        // name; trailing loops stay outside like the unprefixed case.
5388        // `used` counts from pos+2, so 1 name is valid.
5389        if used == 0 {
5390            return None;
5391        }
5392        if is_type {
5393            return Some((
5394                ExportNames {
5395                    func_names: Vec::new(),
5396                    type_names: vec![name],
5397                },
5398                2 + used,
5399            ));
5400        } else {
5401            return Some((
5402                ExportNames {
5403                    func_names: vec![name],
5404                    type_names: Vec::new(),
5405                },
5406                2 + used,
5407            ));
5408        }
5409    }
5410    if let TokKind::Group {
5411        delim: GroupDelim::Bracket,
5412        inner,
5413        ..
5414    } = &next.kind
5415    {
5416        let mut func_names = Vec::new();
5417        let mut type_names = Vec::new();
5418        for part in split_bracket_entries(inner) {
5419            let mut part = part;
5420            while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
5421                part = &part[1..];
5422            }
5423            while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
5424                part = &part[..part.len() - 1];
5425            }
5426            // A trailing comma leaves an empty final entry; it
5427            // carries no name and must not fail the list.
5428            if part.is_empty() {
5429                continue;
5430            }
5431            // Optional per-entry `TYPE`/`FUNC` prefix for mixed lists:
5432            // `EXPORT [TYPE A, FUNC B, C]` (bare stays func). The name
5433            // must be `sep` from the prefix; the prefix itself may be
5434            // joint to a preceding `[` or `,`, so only the name's joint
5435            // flag matters.
5436            let (is_type, rest) = match part {
5437                [first, second, ..]
5438                    if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_TYPE || w == KEYWORD_FUNC)
5439                        && !second.joint =>
5440                {
5441                    let is_t = matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_TYPE);
5442                    (is_t, &part[1..])
5443                }
5444                _ => (false, part),
5445            };
5446            // Exactly one name per entry (entries never trail).
5447            let (name, used) = parse_export_name(rest, 0)?;
5448            if used != rest.len() {
5449                return None;
5450            }
5451            if is_type {
5452                type_names.push(name);
5453            } else {
5454                func_names.push(name);
5455            }
5456        }
5457        if func_names.is_empty() && type_names.is_empty() {
5458            return None;
5459        }
5460        return Some((
5461            ExportNames {
5462                func_names,
5463                type_names,
5464            },
5465            2,
5466        ));
5467    }
5468    if matches!(&next.kind, TokKind::Group { .. }) {
5469        return None;
5470    }
5471    // Bare name (greedy `::` prefix; trailing loops outside). Bare
5472    // stays func for back-compat; `TYPE`/`FUNC` prefix selects above.
5473    parse_export_name(toks, pos + 1).map(|(name, used)| {
5474        (
5475            ExportNames {
5476                func_names: vec![name],
5477                type_names: Vec::new(),
5478            },
5479            1 + used,
5480        )
5481    })
5482}
5483
5484/// Split bracket inner tokens on top-level commas, preserving entries
5485/// for per-entry `TYPE`/`FUNC` handling. Newlines trim at the caller.
5486fn split_bracket_entries(inner: &[Tok]) -> Vec<&[Tok]> {
5487    let mut parts: Vec<&[Tok]> = Vec::new();
5488    let mut start = 0;
5489    for (i, tok) in inner.iter().enumerate() {
5490        if matches!(&tok.kind, TokKind::Punct(',')) {
5491            parts.push(&inner[start..i]);
5492            start = i + 1;
5493        }
5494    }
5495    parts.push(&inner[start..]);
5496    parts
5497}
5498
5499/// `TYPE NAME = SHAPE` at `pos`: uppercase name, single `=`, maximal
5500/// type-tag shape canonicalized through the shared spelling.
5501/// Returns the alias plus tokens consumed, or `None` on shape miss
5502/// (generic fails it in lowering like the grammar).
5503fn parse_type_stmt_at(
5504    toks: &[Tok],
5505    pos: usize,
5506    stmt: usize,
5507) -> Result<Option<(StepKind, usize)>, TokenError> {
5508    let name = match toks.get(pos + 1).map(|t| &t.kind) {
5509        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
5510        _ => return Ok(None),
5511    };
5512    // Single `=` at any gap (`gap` zero-width); `==` misses.
5513    if !matches!(
5514        toks.get(pos + 2).map(|t| &t.kind),
5515        Some(TokKind::Punct('='))
5516    ) {
5517        return Ok(None);
5518    }
5519    if matches!(
5520        toks.get(pos + 3).map(|t| &t.kind),
5521        Some(TokKind::Punct('='))
5522    ) {
5523        return Ok(None);
5524    }
5525    let Some(end) = parse_type_shape(toks, pos + 3) else {
5526        return Ok(None);
5527    };
5528    // Post-match the span holds words/puncts only, so the shared
5529    // renderer cannot fail; stay failed regardless.
5530    let target = render_type_region(&toks[pos + 3..end], stmt).unwrap_or_default();
5531    Ok(Some((StepKind::TypeAlias { name, target }, end - pos)))
5532}
5533
5534/// Single (non-block) `REMOTE`: target, optional bindings, block.
5535/// The target reads a maximal joint run in the grammar's superset
5536/// charset (misses fall to generic); strict validity fails loudly
5537/// with the exact backend message. Bindings miss to generic;
5538/// empty/missing bodies and nesting violations fail loudly.
5539fn parse_remote_single(
5540    toks: &[Tok],
5541    pos: usize,
5542    stmt: usize,
5543    ctx: &ParseCtx,
5544) -> Result<Option<(StepKind, usize)>, TokenError> {
5545    let fail = |msg: String| TokenError {
5546        stmt,
5547        msg,
5548        line: 0,
5549        col: 0,
5550        kind: Some(ParseErrorKind::Validation {
5551            command: KEYWORD_REMOTE.to_string(),
5552        }),
5553    };
5554    // Target: joint run in the superset charset (alnum/`_`/`-`/`.`/`:`).
5555    // Anything else (joint or not) ends the run; an empty run misses
5556    // to generic. (`sep` needs no explicit check: a joint `(` is a
5557    // call routed before this ever runs, and anything unparseable
5558    // misses the same way.)
5559    let mut target = String::new();
5560    let mut p = pos + 1;
5561    while let Some(t) = toks.get(p) {
5562        if !t.joint && !target.is_empty() {
5563            break;
5564        }
5565        match &t.kind {
5566            TokKind::Word(w)
5567                if w.chars().all(|c| {
5568                    c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' || c == ':'
5569                }) =>
5570            {
5571                // Words arrive whole from the lexer; a bad word ends
5572                // the run (never partially appends), like the grammar.
5573                target.push_str(w);
5574                p += 1;
5575            }
5576            TokKind::Punct(c)
5577                if matches!(c, '_' | '-' | '.' | ':') && (target.is_empty() || t.joint) =>
5578            {
5579                target.push(*c);
5580                p += 1;
5581            }
5582            _ => break,
5583        }
5584    }
5585    if target.is_empty() {
5586        return Ok(None);
5587    }
5588    if !crate::commands::is_valid_remote_target(&target) {
5589        return Err(fail(format!(
5590            "invalid REMOTE target `{target}`: start alphanumeric, then alphanumeric, `_`, or `-`, max 64 chars, never SNAPSHOT, LOCAL, CACHE, SYSTEM, or REMOTE"
5591        )));
5592    }
5593    // Optional bindings `[$var, env:KEY]` at any gap (even joint,
5594    // probed); malformed bindings miss the whole shape to generic.
5595    let mut vars = Vec::new();
5596    let mut env = Vec::new();
5597    if let Some(bracket) = toks.get(p)
5598        && matches!(
5599            &bracket.kind,
5600            TokKind::Group {
5601                delim: GroupDelim::Bracket,
5602                ..
5603            }
5604        )
5605    {
5606        let inner = match &bracket.kind {
5607            TokKind::Group { inner, .. } => inner.clone(),
5608            _ => unreachable!(),
5609        };
5610        match parse_remote_bindings(&inner, stmt)? {
5611            Some((v, e)) => {
5612                vars = v;
5613                env = e;
5614            }
5615            None => return Ok(None),
5616        }
5617        p += 1;
5618    }
5619    // Block required (any gap, never a template); missing blocks
5620    // miss to generic.
5621    let block_ok = matches!(
5622        toks.get(p).map(|t| &t.kind),
5623        Some(TokKind::Group {
5624            delim: GroupDelim::Brace,
5625            ..
5626        })
5627    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
5628    if !block_ok {
5629        return Ok(None);
5630    }
5631    let inner = match &toks[p].kind {
5632        TokKind::Group { inner, .. } => inner.clone(),
5633        _ => unreachable!(),
5634    };
5635    let body = parse_body_steps(&inner, stmt, ctx, false)?;
5636    p += 1;
5637    if body.is_empty() {
5638        return Err(fail("REMOTE requires a non-empty braced block".to_string()));
5639    }
5640    if crate::commands::contains_remote_block(&body) {
5641        return Err(fail(format!(
5642            "REMOTE blocks cannot nest (target `{target}` contains another REMOTE block)"
5643        )));
5644    }
5645    if body
5646        .iter()
5647        .any(|s| crate::commands::contains_inherit_env(&s.kind))
5648    {
5649        return Err(fail(
5650            "INHERIT_ENV cannot appear inside a REMOTE block: the guest inherits its own process environment".to_string(),
5651        ));
5652    }
5653    // Outer-function containment (same rule as the shared remote
5654    // validators): body calls resolving to visible
5655    // outer `SCRIPT` defs (without same-body definitions) fail.
5656    {
5657        let mut inner_defs = HashSet::new();
5658        let mut calls = Vec::new();
5659        crate::commands::collect_remote_body_symbols(&body, &mut inner_defs, &mut calls);
5660        let outer_defs: HashSet<String> = ctx.funcs.borrow().iter().flatten().cloned().collect();
5661        for call in &calls {
5662            let bare = crate::constants::base_name(call);
5663            let is_script_call = match crate::constants::split_qualified(call) {
5664                Some((module, _)) => module == crate::constants::SCRIPT_MODULE_NAME,
5665                None => true,
5666            };
5667            if is_script_call && outer_defs.contains(bare) && !inner_defs.contains(bare) {
5668                return Err(fail(format!(
5669                    "REMOTE '{target}' calls outer function '{bare}' (functions must be defined inside the block)"
5670                )));
5671            }
5672        }
5673    }
5674    Ok(Some((
5675        StepKind::RemoteBlock {
5676            target,
5677            vars,
5678            env,
5679            body,
5680        },
5681        p - pos,
5682    )))
5683}
5684// ---- LET/SET/RETURN + expressions ----
5685// Expression tiers over [`Tok`] implement the precedence chain
5686// (or > and > comparison > ordering > add > mul > unary > atom);
5687// arithmetic/comparison lowering runs through the shared constructors
5688// (`make_arith`, `make_compare`, `apply_unary_neg`), so folding, RPN
5689// compilation, and overflow behavior are identical by construction,
5690// never re-derived.
5691
5692/// Eat a one- or two-char operator: single puncts match directly;
5693/// pairs (`==`, `!=`, `<=`, `>=`, `&&`, `||`, `::`) require a joint
5694/// second punct. Newlines never skip here (expression mode).
5695fn eat_op(cur: &mut Cursor, first: char, second: Option<char>) -> bool {
5696    // Gaps (comments included) are skipped before every operator.
5697    cur.skip_gap();
5698    let (a, b) = match (cur.toks.get(cur.pos), cur.toks.get(cur.pos + 1)) {
5699        (Some(a), b) => (a, b),
5700        _ => return false,
5701    };
5702    if !matches!(&a.kind, TokKind::Punct(c) if *c == first) {
5703        return false;
5704    }
5705    match second {
5706        None => {
5707            cur.pos += 1;
5708            true
5709        }
5710        Some(c2) => match b {
5711            Some(t) if t.joint && matches!(&t.kind, TokKind::Punct(c) if *c == c2) => {
5712                cur.pos += 2;
5713                true
5714            }
5715            _ => false,
5716        },
5717    }
5718}
5719
5720/// Dummy span for the shared lowering constructors: v2 owns no source
5721/// positions yet, so only success values (span-free) participate in
5722/// parity; failures surface through [`TokenError`] text.
5723fn lowering_ctx(stmt: usize) -> SpanContext<'static> {
5724    let _ = stmt;
5725    SpanContext::line_only(0)
5726}
5727
5728fn parse_expr_or(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5729    let mut left = parse_expr_and(cur, ctx)?;
5730    while eat_op(cur, '|', Some('|')) {
5731        cur.skip_gap();
5732        let right = parse_expr_and(cur, ctx)?;
5733        // No folding, no boundary checks: unfused literal runs stay
5734        // literal here.
5735        left = Expr::Logical {
5736            op: LogicalOp::Or,
5737            left: Box::new(left),
5738            right: Box::new(right),
5739        };
5740    }
5741    Ok(left)
5742}
5743
5744fn parse_expr_and(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5745    let mut left = parse_expr_cmp(cur, ctx)?;
5746    while eat_op(cur, '&', Some('&')) {
5747        cur.skip_gap();
5748        let right = parse_expr_cmp(cur, ctx)?;
5749        reject_boundary(&lowering_ctx(cur.stmt), &left).map_err(|e| cur.err(e.to_string()))?;
5750        reject_boundary(&lowering_ctx(cur.stmt), &right).map_err(|e| cur.err(e.to_string()))?;
5751        left = Expr::Logical {
5752            op: LogicalOp::And,
5753            left: Box::new(left),
5754            right: Box::new(right),
5755        };
5756    }
5757    Ok(left)
5758}
5759
5760fn parse_expr_cmp(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5761    let left = parse_expr_ord(cur, ctx)?;
5762    let op = if eat_op(cur, '=', Some('=')) {
5763        CompareOp::Eq
5764    } else if eat_op(cur, '!', Some('=')) {
5765        CompareOp::Ne
5766    } else {
5767        return Ok(left);
5768    };
5769    cur.skip_gap();
5770    let right = parse_expr_ord(cur, ctx)?;
5771    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
5772        .map_err(|e| cur.err(e.to_string()))?;
5773    reject_chained_compare(cur, false)?;
5774    Ok(expr)
5775}
5776
5777/// Reject a comparison operator trailing a complete comparison:
5778/// no grammar position continues with one, so the shape always fails —
5779/// loudly here instead of stranding text for a confusing downstream
5780/// error. The equality tier rejects all six (`$a == $b == $c`,
5781/// `$a == $b < $c < $d`); the ordering tier rejects ordering only
5782/// (`$a < $b < $c`), since `$a < $b == $c` is a legitimate equality
5783/// over an ordering result. Probes without consuming.
5784fn reject_chained_compare(cur: &mut Cursor, ordering_only: bool) -> Result<(), TokenError> {
5785    let mut probe = Cursor::expr(cur.toks, cur.stmt);
5786    probe.pos = cur.pos;
5787    probe.skip_gap();
5788    let chained = match probe.toks.get(probe.pos).map(|t| &t.kind) {
5789        Some(TokKind::Punct('<' | '>')) => true,
5790        Some(TokKind::Punct('=' | '!')) => !ordering_only,
5791        _ => false,
5792    };
5793    if chained {
5794        return Err(cur
5795            .err("chained comparison operators need explicit parentheses, e.g. `($a < $b) < $c`"));
5796    }
5797    Ok(())
5798}
5799
5800fn parse_expr_ord(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5801    let left = parse_expr_add(cur, ctx)?;
5802    let op = if eat_op(cur, '<', Some('=')) {
5803        CompareOp::Le
5804    } else if eat_op(cur, '>', Some('=')) {
5805        CompareOp::Ge
5806    } else if eat_op(cur, '<', None) {
5807        CompareOp::Lt
5808    } else if eat_op(cur, '>', None) {
5809        CompareOp::Gt
5810    } else {
5811        return Ok(left);
5812    };
5813    cur.skip_gap();
5814    let right = parse_expr_add(cur, ctx)?;
5815    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
5816        .map_err(|e| cur.err(e.to_string()))?;
5817    reject_chained_compare(cur, true)?;
5818    Ok(expr)
5819}
5820
5821fn parse_expr_add(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5822    let mut left = parse_expr_mul(cur, ctx)?;
5823    loop {
5824        let op = if eat_op(cur, '+', None) {
5825            ArithOp::Add
5826        } else if eat_op(cur, '-', None) {
5827            ArithOp::Sub
5828        } else {
5829            break;
5830        };
5831        cur.skip_gap();
5832        let right = parse_expr_mul(cur, ctx)?;
5833        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
5834            .map_err(|e| cur.err(e.to_string()))?;
5835    }
5836    Ok(left)
5837}
5838
5839fn parse_expr_mul(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5840    let mut left = parse_expr_unary(cur, ctx)?;
5841    loop {
5842        let op = if eat_op(cur, '*', None) {
5843            ArithOp::Mul
5844        } else if eat_op(cur, '/', None) {
5845            ArithOp::Div
5846        } else {
5847            break;
5848        };
5849        cur.skip_gap();
5850        let right = parse_expr_unary(cur, ctx)?;
5851        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
5852            .map_err(|e| cur.err(e.to_string()))?;
5853    }
5854    Ok(left)
5855}
5856
5857/// A `-` opens a bare word (never negation) when gaplessly followed by
5858/// a letter, `_`, or `/` — the `neg_op` lookahead, read off `joint`.
5859fn dash_is_bare(cur: &Cursor) -> bool {
5860    let next = cur.toks.get(cur.pos + 1);
5861    match next {
5862        Some(t) if t.joint => match &t.kind {
5863            TokKind::Word(w) => w
5864                .chars()
5865                .next()
5866                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_'),
5867            TokKind::Punct('/') => true,
5868            _ => false,
5869        },
5870        _ => false,
5871    }
5872}
5873
5874fn parse_expr_unary(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5875    let mut prefixes = Vec::new();
5876    loop {
5877        match cur.toks.get(cur.pos).map(|t| &t.kind) {
5878            Some(TokKind::Punct('!')) => {
5879                cur.pos += 1;
5880                // Each prefix is gap-separated.
5881                cur.skip_gap();
5882                prefixes.push(false);
5883            }
5884            Some(TokKind::Punct('-')) if !dash_is_bare(cur) => {
5885                cur.pos += 1;
5886                cur.skip_gap();
5887                prefixes.push(true);
5888            }
5889            _ => break,
5890        }
5891    }
5892    let mut expr = parse_expr_atom(cur, ctx)?;
5893    // Innermost prefix is closest to the atom: apply in reverse order.
5894    for is_neg in prefixes.into_iter().rev() {
5895        if is_neg {
5896            expr = apply_unary_neg(&lowering_ctx(cur.stmt), expr)
5897                .map_err(|e| cur.err(e.to_string()))?;
5898        } else {
5899            reject_boundary(&lowering_ctx(cur.stmt), &expr).map_err(|e| cur.err(e.to_string()))?;
5900            expr = Expr::Not(Box::new(expr));
5901        }
5902    }
5903    Ok(expr)
5904}
5905
5906/// Identifier charset for `$var` and `.segment` parts. Segments admit
5907/// digits-only too (`$a.0`); anything else ends the key path and errors
5908/// downstream, like the grammar's backtrack to `variable`.
5909fn is_ident_word(w: &str) -> bool {
5910    !w.is_empty() && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
5911}
5912
5913fn is_key_segment(w: &str) -> bool {
5914    !w.is_empty()
5915        && (w.chars().all(|c| c.is_ascii_digit())
5916            || (w
5917                .chars()
5918                .next()
5919                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
5920                && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')))
5921}
5922
5923fn is_env_key(w: &str) -> bool {
5924    !w.is_empty()
5925        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
5926        && w.chars()
5927            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
5928}
5929
5930/// Maximal joint run of words and `-/.'/'` puncts: the bare-word
5931/// shape (which admits `/` anywhere, so `//c`, `/a`, `a/b`, and the
5932/// `/`-`c`-`/` operands of `/*c*/` math all read literally here).
5933/// Callers classify (`true`/`false`/string); the numeric path
5934/// runs first and falls back here on shape/follower mismatch.
5935/// Backslash escapes are arg-position syntax: the bare-word shape admits
5936/// no `\`, so expression runs containing one fail here (never drift
5937/// into a string the grammar rejects).
5938fn expr_bare_run(cur: &mut Cursor, leading_dash: bool) -> Result<String, TokenError> {
5939    let mut out = String::new();
5940    if leading_dash {
5941        match cur.next() {
5942            Some(t) if matches!(&t.kind, TokKind::Punct('-')) => out.push('-'),
5943            _ => return Err(cur.err("missing expression operand")),
5944        }
5945    }
5946    match cur.next() {
5947        Some(t) => match &t.kind {
5948            TokKind::Word(w) => out.push_str(w),
5949            // Leading `/` (operand position only; operators are
5950            // consumed by the tiers before operands parse).
5951            TokKind::Punct('/') => out.push('/'),
5952            _ => return Err(cur.err("missing expression operand")),
5953        },
5954        None => return Err(cur.err("missing expression operand")),
5955    }
5956    loop {
5957        let next = match cur.toks.get(cur.pos) {
5958            Some(t) if t.joint => t,
5959            _ => break,
5960        };
5961        match &next.kind {
5962            TokKind::Word(w) => {
5963                // Abutting words only continue through an operator gap
5964                // the tiers own (`a -b` never fuses); without a joint
5965                // punct between, stop. Since this token IS joint, the
5966                // previous token must have been a bare punct.
5967                out.push_str(w);
5968                cur.pos += 1;
5969            }
5970            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
5971                out.push(*c);
5972                cur.pos += 1;
5973            }
5974            _ => break,
5975        }
5976    }
5977    if out.contains('\\') {
5978        return Err(cur.err("unexpected escape in expression"));
5979    }
5980    Ok(out)
5981}
5982
5983/// Numeric literal head: digit-led word plus joint `.digits` tails.
5984/// Callers apply the separator-shape gate and the follower rule, then
5985/// the shared classifier.
5986fn number_head(cur: &mut Cursor) -> Option<String> {
5987    let first = match cur.toks.get(cur.pos).map(|t| &t.kind) {
5988        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => w.clone(),
5989        _ => return None,
5990    };
5991    let mut text = first;
5992    let mut pos = cur.pos + 1;
5993    loop {
5994        let dot = matches!(
5995            cur.toks.get(pos).map(|t| &t.kind),
5996            Some(TokKind::Punct('.'))
5997        ) && cur.toks.get(pos).is_some_and(|t| t.joint);
5998        let digits = cur.toks.get(pos + 1);
5999        let digits_ok = dot
6000            && matches!(digits.map(|t| &t.kind), Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_'))
6001            && digits.is_some_and(|t| t.joint);
6002        if !digits_ok {
6003            break;
6004        }
6005        text.push('.');
6006        if let Some(TokKind::Word(w)) = digits.map(|t| &t.kind) {
6007            text.push_str(w);
6008        }
6009        pos += 2;
6010    }
6011    Some(text)
6012}
6013
6014/// `_`-separator shape gate mirroring the `numeric_literal` rule:
6015/// digits with single-underscore separators, at most one fraction.
6016fn numeric_shape_ok(text: &str) -> bool {
6017    let mut parts = text.split('.');
6018    let int_part = parts.next().unwrap_or("");
6019    let frac_part = parts.next();
6020    if parts.next().is_some() {
6021        return false;
6022    }
6023    fn run_ok(s: &str) -> bool {
6024        !s.is_empty()
6025            && s.chars().all(|c| c.is_ascii_digit() || c == '_')
6026            && !s.starts_with('_')
6027            && !s.ends_with('_')
6028            && !s.contains("__")
6029    }
6030    run_ok(int_part) && frac_part.is_none_or(run_ok)
6031}
6032
6033/// Follower rule mirroring the `numeric_literal` trailing guard
6034/// (`!(ALNUM | "_" | "." | "/")`): a joint word, `.`, or `/` continues
6035/// into a bare word (`30s`, `1.`, `4/2`); `-`/`+`/operators let the
6036/// number stand for the tiers (`1-2` is `Sub`, like the grammar).
6037fn number_falls_to_bare(cur: &Cursor, consumed: usize) -> bool {
6038    match cur.toks.get(cur.pos + consumed) {
6039        Some(t) if t.joint => matches!(
6040            &t.kind,
6041            TokKind::Word(_) | TokKind::Punct('.') | TokKind::Punct('/')
6042        ),
6043        _ => false,
6044    }
6045}
6046
6047fn parse_expr_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6048    match cur.toks.get(cur.pos).map(|t| &t.kind) {
6049        Some(TokKind::Group {
6050            delim: GroupDelim::Paren,
6051            inner,
6052            ..
6053        }) => {
6054            let inner = inner.clone();
6055            cur.pos += 1;
6056            let mut sub = Cursor::expr(&inner, cur.stmt);
6057            sub.skip_gap_nl();
6058            let expr = parse_expr_or(&mut sub, ctx)?;
6059            sub.skip_gap_nl();
6060            if !sub.done() {
6061                return Err(sub.err("unexpected text in parentheses"));
6062            }
6063            Ok(expr)
6064        }
6065        Some(TokKind::Word(_)) if call_shape_at(cur.toks, cur.pos, false).is_some() => {
6066            let (name, paren) =
6067                call_shape_at(cur.toks, cur.pos, false).ok_or_else(|| cur.err("unreachable"))?;
6068            let inner = match &cur.toks[paren].kind {
6069                TokKind::Group { inner, .. } => inner.clone(),
6070                _ => unreachable!(),
6071            };
6072            cur.pos = paren + 1;
6073            parse_expr_call(name, &inner, cur.stmt, ctx)
6074        }
6075        Some(TokKind::Punct('$')) => {
6076            cur.pos += 1;
6077            // Atomic `variable`: `$` and the name ride gapless (the
6078            // enclosing rules are compound-atomic).
6079            let base = match cur.next() {
6080                Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
6081                    match &t.kind {
6082                        TokKind::Word(w) => w.clone(),
6083                        _ => unreachable!(),
6084                    }
6085                }
6086                _ => return Err(cur.err("`$` requires a variable name")),
6087            };
6088            let mut keys = Vec::new();
6089            loop {
6090                // Key-path dots are gapless too (`~` without `gap`).
6091                let dot = matches!(
6092                    cur.toks.get(cur.pos).map(|t| &t.kind),
6093                    Some(TokKind::Punct('.'))
6094                ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
6095                let seg = cur.toks.get(cur.pos + 1);
6096                let seg_ok = dot
6097                    && matches!(seg.map(|t| &t.kind), Some(TokKind::Word(w)) if is_key_segment(w))
6098                    && seg.is_some_and(|t| t.joint);
6099                if !seg_ok {
6100                    break;
6101                }
6102                if let Some(TokKind::Word(w)) = seg.map(|t| &t.kind) {
6103                    keys.push(w.clone());
6104                }
6105                cur.pos += 2;
6106            }
6107            if keys.is_empty() {
6108                Ok(Expr::Var(base))
6109            } else {
6110                Ok(Expr::KeyPath { base, keys })
6111            }
6112        }
6113        Some(TokKind::Word(w)) if w == "env" => {
6114            // `env:KEY` read when the full shape matches gaplessly
6115            // (atomic `env_read`); otherwise a bare word (`env` alone,
6116            // `env:k` lowercase) for the error path, exactly like the
6117            // grammar's mismatch.
6118            let key_ok = matches!(
6119                cur.toks.get(cur.pos + 1).map(|t| &t.kind),
6120                Some(TokKind::Punct(':'))
6121            ) && cur.toks.get(cur.pos + 1).is_some_and(|t| t.joint)
6122                && matches!(
6123                    cur.toks.get(cur.pos + 2).map(|t| &t.kind),
6124                    Some(TokKind::Word(k)) if is_env_key(k)
6125                )
6126                && cur.toks.get(cur.pos + 2).is_some_and(|t| t.joint);
6127            if !key_ok {
6128                return parse_bare_atom(cur, ctx, false);
6129            }
6130            cur.pos += 1;
6131            cur.pos += 1;
6132            match cur.next() {
6133                Some(t) => match &t.kind {
6134                    TokKind::Word(k) => Ok(Expr::Env(k.clone())),
6135                    _ => Err(cur.err("unreachable")),
6136                },
6137                None => Err(cur.err("unreachable")),
6138            }
6139        }
6140        Some(TokKind::Group {
6141            delim: GroupDelim::Bracket,
6142            inner,
6143            ..
6144        }) => {
6145            let inner = inner.clone();
6146            cur.pos += 1;
6147            parse_list_literal(&inner, cur.stmt, ctx)
6148        }
6149        Some(TokKind::Group {
6150            delim: GroupDelim::Brace,
6151            inner,
6152            ..
6153        }) => {
6154            let inner = inner.clone();
6155            cur.pos += 1;
6156            parse_map_or_block(&inner, cur.stmt, ctx)
6157        }
6158        Some(TokKind::Str { text, .. }) => {
6159            let text = text.clone();
6160            cur.pos += 1;
6161            Ok(Expr::Literal(Value::string(text)))
6162        }
6163        Some(TokKind::BlockStr(full)) => {
6164            let full = full.clone();
6165            cur.pos += 1;
6166            Ok(Expr::Literal(Value::string(
6167                crate::command::lower_block_string(&full),
6168            )))
6169        }
6170        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => {
6171            parse_numeric_atom(cur, ctx)
6172        }
6173        Some(TokKind::Word(_)) => parse_bare_atom(cur, ctx, false),
6174        Some(TokKind::Punct('-')) => parse_bare_atom(cur, ctx, true),
6175        Some(TokKind::Punct('/')) => parse_bare_atom(cur, ctx, false),
6176        _ => Err(cur.err("missing expression operand")),
6177    }
6178}
6179
6180/// Bare-word atom with a `-` lead (the caller proved it is not
6181/// negation): consumes the joint `-/.'/'` run for the bare-word
6182/// shape.
6183fn parse_bare_atom(
6184    cur: &mut Cursor,
6185    _ctx: &ParseCtx,
6186    leading_dash: bool,
6187) -> Result<Expr, TokenError> {
6188    let text = expr_bare_run(cur, leading_dash)?;
6189    match text.as_str() {
6190        "true" => Ok(Expr::Literal(Value::bool(true))),
6191        "false" => Ok(Expr::Literal(Value::bool(false))),
6192        _ => Ok(Expr::Literal(Value::string(text))),
6193    }
6194}
6195
6196/// Numeric atom: rejoin dotted tails, apply the shape gate and the
6197/// follower rule, then the shared classifier. Anything failing the
6198/// gate or follower reparses as a bare word (durations, versions,
6199/// paths), exactly like the grammar's numeric-literal-or-bare-word
6200/// order.
6201fn parse_numeric_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6202    let start = cur.pos;
6203    let text = number_head(cur).ok_or_else(|| cur.err("missing expression operand"))?;
6204    let consumed = {
6205        let mut n = 1;
6206        let mut p = start + 1;
6207        while matches!(cur.toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('.')))
6208            && cur.toks.get(p).is_some_and(|t| t.joint)
6209            && matches!(
6210                cur.toks.get(p + 1).map(|t| &t.kind),
6211                Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_')
6212            )
6213            && cur.toks.get(p + 1).is_some_and(|t| t.joint)
6214        {
6215            n += 2;
6216            p += 2;
6217        }
6218        n
6219    };
6220    if !numeric_shape_ok(&text) || number_falls_to_bare(cur, consumed) {
6221        return parse_bare_atom(cur, ctx, false);
6222    }
6223    cur.pos += consumed;
6224    classify_numeric_text(&text).map_err(|msg| cur.err(msg))
6225}
6226
6227/// Full expression with the top-level boundary rejection (mirrors
6228/// `parse_expr`): a stray `UnsignedIntBoundary` that no unary `-`
6229/// consumed is an overflow error.
6230fn parse_expr_checked(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6231    let expr = parse_expr_or(cur, ctx)?;
6232    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
6233        return Err(cur.err("integer overflow: 9223372036854775808 exceeds i64::MAX"));
6234    }
6235    Ok(expr)
6236}
6237
6238/// List literal over a bracket group's contents: the shared bracket
6239/// core (see [`parse_bracket_list`]) in `Expr` mode. Expression
6240/// positions fail loudly instead of missing, so `None` is unreachable.
6241fn parse_list_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6242    parse_bracket_list(inner, stmt, ctx, BracketItems::Expr)
6243        .map(|list| list.expect("expression lists fail loudly, never miss"))
6244}
6245
6246/// Map literal attempt over a brace group's contents: comma-separated
6247/// `key: value` entries with `gap` (never newline) around the colon.
6248/// Any entry failing the shape is not a map: the caller reports the
6249/// deferred block slice (the grammar tries `block` next, which fails
6250/// the same inputs at this stage).
6251/// Marker message for a map entry run that ends without a comma
6252/// where another entry follows. Matched by exact equality in
6253/// [`parse_map_or_block`], never by prefix, so wording changes stay
6254/// local to this const and its one reader.
6255const MISSING_MAP_COMMA_MSG: &str = "missing comma between map entries";
6256
6257fn parse_map_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6258    let mut entries = Vec::new();
6259    // Empty (or blank/comment-only) braces are an empty map.
6260    if inner
6261        .iter()
6262        .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
6263    {
6264        return Ok(Expr::Map(vec![]));
6265    }
6266    for part in split_top_commas(inner) {
6267        let mut sub = Cursor::expr(part, stmt);
6268        sub.skip_gap_nl();
6269        let (key, val) = parse_map_entry(&mut sub, ctx, stmt)?;
6270        sub.skip_gap_nl();
6271        if !sub.done() {
6272            return Err(map_trailing_error(&sub, ctx, stmt));
6273        }
6274        entries.push((key, val));
6275    }
6276    Ok(Expr::Map(entries))
6277}
6278
6279/// One `key: value` map entry: string, block-string, or bare key,
6280/// a colon, then a full checked expression. Every failure reads
6281/// `not a map literal` exactly like the old inline loop, so only
6282/// the trailing rule changes the surface.
6283fn parse_map_entry(
6284    sub: &mut Cursor,
6285    ctx: &ParseCtx,
6286    stmt: usize,
6287) -> Result<(String, Expr), TokenError> {
6288    let key = match sub.toks.get(sub.pos).map(|t| &t.kind) {
6289        Some(TokKind::Str { text, .. }) => {
6290            let key = text.clone();
6291            sub.pos += 1;
6292            key
6293        }
6294        Some(TokKind::BlockStr(full)) => {
6295            let key = crate::command::lower_block_string(full);
6296            sub.pos += 1;
6297            key
6298        }
6299        Some(TokKind::Word(_)) | Some(TokKind::Punct('-')) | Some(TokKind::Punct('/')) => {
6300            map_bare_key(sub)?
6301        }
6302        _ => return Err(sub.err("not a map literal")),
6303    };
6304    sub.skip_gap();
6305    if !sub.eat_punct(':') {
6306        return Err(sub.err("not a map literal"));
6307    }
6308    let val = parse_expr_checked(sub, ctx)?;
6309    reject_boundary(&lowering_ctx(stmt), &val).map_err(|e| sub.err(e.to_string()))?;
6310    Ok((key, val))
6311}
6312
6313/// Trailing content after a complete map entry: stamps the
6314/// offending token and names the likely missing comma when the
6315/// remainder parses as another entry. Anything else keeps the old
6316/// `not a map literal` text. Error-path only.
6317fn map_trailing_error(sub: &Cursor, ctx: &ParseCtx, stmt: usize) -> TokenError {
6318    let (line, col) = sub
6319        .toks
6320        .get(sub.pos)
6321        .map(|t| (t.line, t.col))
6322        .unwrap_or((0, 0));
6323    let mut probe = Cursor::expr(&sub.toks[sub.pos.min(sub.toks.len())..], stmt);
6324    probe.skip_gap_nl();
6325    if parse_map_entry(&mut probe, ctx, stmt).is_ok() {
6326        return TokenError {
6327            stmt,
6328            line,
6329            col,
6330            msg: MISSING_MAP_COMMA_MSG.to_string(),
6331            kind: None,
6332        };
6333    }
6334    sub.err("not a map literal")
6335}
6336
6337/// Bare map key: joint `-/.'/'`-run, mirroring the bare-word charset
6338/// (no bool/numeric classification: keys are always strings).
6339fn map_bare_key(sub: &mut Cursor) -> Result<String, TokenError> {
6340    let mut out = String::new();
6341    if matches!(
6342        sub.toks.get(sub.pos).map(|t| &t.kind),
6343        Some(TokKind::Punct('-'))
6344    ) {
6345        out.push('-');
6346        sub.pos += 1;
6347    }
6348    // Leading `/` reads literally too (the bare-word shape admits `/`
6349    // anywhere: `{/a: 1}`, `{//c: 1}`); the joint loop below
6350    // continues the run.
6351    if matches!(
6352        sub.toks.get(sub.pos).map(|t| &t.kind),
6353        Some(TokKind::Punct('/'))
6354    ) {
6355        out.push('/');
6356        sub.pos += 1;
6357    }
6358    match sub.toks.get(sub.pos).map(|t| &t.kind) {
6359        Some(TokKind::Word(w)) => {
6360            out.push_str(w);
6361            sub.pos += 1;
6362        }
6363        // A leading `/` above already started the run; anything
6364        // else still needs a word head.
6365        _ if !out.is_empty() => {}
6366        _ => return Err(sub.err("not a map literal")),
6367    }
6368    while let Some(t) = sub.toks.get(sub.pos) {
6369        if !t.joint {
6370            break;
6371        }
6372        match &t.kind {
6373            TokKind::Word(w) => {
6374                out.push_str(w);
6375                sub.pos += 1;
6376            }
6377            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
6378                out.push(*c);
6379                sub.pos += 1;
6380            }
6381            _ => break,
6382        }
6383    }
6384    if out.contains('\\') {
6385        return Err(sub.err("unexpected escape in map key"));
6386    }
6387    Ok(out)
6388}
6389
6390/// Map-or-block over a brace group's contents: maps parse literally;
6391/// anything else is an inline block (`Expr::Block` over the body
6392/// steps, scopes unmarked like every braced body).
6393fn parse_map_or_block(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6394    match parse_map_literal(inner, stmt, ctx) {
6395        Ok(map) => Ok(map),
6396        // A detected missing comma is never a block: its `key:`
6397        // remainder cannot parse as a statement (a `name: "a"` line
6398        // fails as `unknown command`), so the block path can only
6399        // misreport it. Surface the map error instead; every other
6400        // map failure keeps the block fallback exactly as before.
6401        Err(e) if e.msg == MISSING_MAP_COMMA_MSG => Err(e),
6402        Err(_) => Ok(Expr::Block(parse_body_steps(inner, stmt, ctx, false)?)),
6403    }
6404}
6405
6406/// Parse one standalone expression from lexed tokens (the
6407/// `parse_expression_str` entry point): a full tier parse with
6408/// top-level boundary rejection and full consumption.
6409pub(crate) fn parse_single_expr(
6410    toks: &[Tok],
6411    stmt: usize,
6412    ctx: &ParseCtx,
6413) -> Result<Expr, TokenError> {
6414    let mut cur = Cursor::expr(toks, stmt);
6415    let expr = parse_expr_checked(&mut cur, ctx)?;
6416    if !cur.done() {
6417        return Err(cur.err("unexpected text in expression"));
6418    }
6419    Ok(expr)
6420}
6421
6422/// Assignment `=`: the first `=` neither glued to a following `=`
6423/// (`==`) nor glued after `!`/`<`/`>`/`=` (`!=`, `<=`, `>=`, second of
6424/// `==`). Glued-ness reads off the `=`'s own `joint` (gap before it)
6425/// and the follower's (gap after it). Anything else leaves the
6426/// statement bare (`LET $p: PIPE`), exactly where the grammar's `"="`
6427/// match fails.
6428fn find_assign_eq(body: &[Tok]) -> Option<usize> {
6429    for (i, tok) in body.iter().enumerate() {
6430        if !matches!(&tok.kind, TokKind::Punct('=')) {
6431            continue;
6432        }
6433        let next_eq = body
6434            .get(i + 1)
6435            .is_some_and(|t| t.joint && matches!(&t.kind, TokKind::Punct('=')));
6436        let prev_op = tok.joint
6437            && i > 0
6438            && matches!(&body[i - 1].kind, TokKind::Punct('!' | '<' | '>' | '='));
6439        if !next_eq && !prev_op {
6440            return Some(i);
6441        }
6442    }
6443    None
6444}
6445
6446/// Render a type region joint-aware (`LIST< MAP >` keeps its gaps for
6447/// the shared canonicalizer, exactly like `type_tag.as_str()`).
6448fn render_type_region(toks: &[Tok], stmt: usize) -> Result<String, TokenError> {
6449    let mut out = String::new();
6450    for tok in toks {
6451        // Ridden newlines from multi-line `<...>` shapes carry no
6452        // output, so the shape canonicalizes exactly like one line.
6453        if matches!(&tok.kind, TokKind::Newline) {
6454            continue;
6455        }
6456        if !tok.joint && !out.is_empty() {
6457            out.push(' ');
6458        }
6459        match &tok.kind {
6460            TokKind::Word(w) => out.push_str(w),
6461            TokKind::Punct(c) => out.push(*c),
6462            _ => {
6463                return Err(TokenError {
6464                    stmt,
6465                    msg: "malformed type in LET".to_string(),
6466                    line: 0,
6467                    col: 0,
6468                    kind: None,
6469                });
6470            }
6471        }
6472    }
6473    if out.is_empty() {
6474        return Err(TokenError {
6475            stmt,
6476            msg: "LET requires explicit type: LET $var: TYPE = <expr>".to_string(),
6477            line: 0,
6478            col: 0,
6479            kind: None,
6480        });
6481    }
6482    Ok(crate::canonicalize_spelling(&out))
6483}
6484
6485fn expect_dollar_var(cur: &mut Cursor, msg: &str) -> Result<String, TokenError> {
6486    // Atomic `dollar_ident`: no gap between `$` and the name (the
6487    // enclosing statements are compound-atomic, so implicit spacing is
6488    // off and only explicit `gap`s admit whitespace).
6489    match cur.next() {
6490        Some(t) if matches!(&t.kind, TokKind::Punct('$')) => {}
6491        _ => return Err(cur.err(msg)),
6492    }
6493    match cur.next() {
6494        Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
6495            match &t.kind {
6496                TokKind::Word(w) => Ok(w.clone()),
6497                _ => unreachable!(),
6498            }
6499        }
6500        _ => Err(cur.err(msg)),
6501    }
6502}
6503
6504/// `LET` body: `LET` is already matched. Returns `None` (miss to
6505/// generic, which fails in lowering like the grammar's committed
6506/// `instruction`) when the shape cannot match any `LET` form: no
6507/// gapless `$var`, or no `:` after it
6508/// (every form needs `: TYPE`). Past that the shape is committed and
6509/// malformed tails fail loudly.
6510fn parse_let_body(
6511    body: &[Tok],
6512    stmt: usize,
6513    ctx: &ParseCtx,
6514) -> Result<Option<(StepKind, usize)>, TokenError> {
6515    let mut cur = Cursor::expr(body, stmt);
6516    match cur.next() {
6517        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_LET) => {}
6518        _ => return Err(cur.err("unreachable")),
6519    }
6520    // No `$var`: no `LET` form can match (miss, never a hard fail).
6521    let var = match expect_dollar_var(&mut cur, "LET requires a variable") {
6522        Ok(var) => var,
6523        Err(_) => return Ok(None),
6524    };
6525    // The header allows gaps (comments, never newlines).
6526    cur.skip_gap();
6527    // No `:`: untyped LET is rejected outright. Every binding is
6528    // typed; the old miss-to-generic path only hid that behind a
6529    // rambling "invalid syntax" message. (FOR already does this.)
6530    if !cur.eat_punct(':') {
6531        return Err(TokenError {
6532            stmt,
6533            msg: "LET requires explicit types: LET $var: TYPE = <expr>".to_string(),
6534            line: 0,
6535            col: 0,
6536            kind: Some(ParseErrorKind::InvalidSyntax {
6537                command: "LET".to_string(),
6538            }),
6539        });
6540    }
6541    // Type region runs to the assignment `=`; it cannot contain one.
6542    let type_start = cur.pos;
6543    let assign = find_assign_eq(&body[type_start..]).map(|i| i + type_start);
6544    let Some(eq) = assign else {
6545        // Bare `LET $p: PIPE` mints a fresh pipe and ends with the
6546        // type word (trailing elements loop on, probed); every other
6547        // bare type is a validation error, mirroring the grammar.
6548        if matches!(
6549            body.get(type_start).map(|t| &t.kind),
6550            Some(TokKind::Word(w)) if w == crate::TypeTag::Pipe.name()
6551        ) {
6552            return Ok(Some((
6553                StepKind::Assign {
6554                    var,
6555                    decl_type: crate::TypeTag::Pipe.name().to_string(),
6556                    expr: Expr::FreshPipe,
6557                },
6558                type_start + 1,
6559            )));
6560        }
6561        return Err(cur.err(
6562            "LET requires an expression: LET $var: TYPE = <expr> (only LET $p: PIPE omits the initializer)",
6563        ));
6564    };
6565    let decl_type = render_type_region(&body[type_start..eq], stmt)?;
6566    let (kind, rhs_used) = parse_let_rhs(&body[eq + 1..], var, decl_type, stmt, ctx)?;
6567    Ok(Some((kind, eq + 1 + rhs_used)))
6568}
6569
6570/// LET right-hand side dispatch, mirroring the grammar order
6571/// (`let_async`, then `let_capture`, then `let_statement`):
6572/// `WITH_IO`-led lines branch async/sync like
6573/// `parse_let_async_statement_from_pair`, `ASYNC`-led lines spawn
6574/// tasks, `TIMEOUT`-led lines capture through the wrapper,
6575/// `AWAIT $v` captures, RUN exec-form captures, known commands
6576/// capture through the generic parser (lowering failures fatal,
6577/// exactly like the committed grammar alternative), and anything
6578/// else parses as an expression (unknown leads included). Returns
6579/// the kind and RHS tokens consumed: captures ending in structural
6580/// pairs leave trailing elements for the caller.
6581fn parse_let_rhs(
6582    rhs: &[Tok],
6583    var: String,
6584    decl_type: String,
6585    stmt: usize,
6586    ctx: &ParseCtx,
6587) -> Result<(StepKind, usize), TokenError> {
6588    // Leading gap comments vanish like the `=` gap (but a `//`/`#`
6589    // to end of input leaves no expression, failing).
6590    let mut lead = Cursor::expr(rhs, stmt);
6591    lead.skip_gap();
6592    let (rhs, skipped) = (&rhs[lead.pos..], lead.pos);
6593    let head_word = match rhs.first().map(|t| &t.kind) {
6594        Some(TokKind::Word(w)) => Some(w.clone()),
6595        _ => None,
6596    };
6597    // `WITH_IO`-led lines share `let_async_statement` with the
6598    // `ASYNC` forms (the grammar claims every WITH_IO-led LET
6599    // there); shape misses fall through to generic below.
6600    if head_word.as_deref() == Some(KEYWORD_WITH_IO)
6601        && let Some(found) = try_let_with_io_rhs(rhs, var.clone(), decl_type.clone(), stmt, ctx)?
6602    {
6603        let (kind, used) = found;
6604        return Ok((kind, skipped + used));
6605    }
6606    // `ASYNC`-led lines (with followers; alone they commit to the
6607    // generic path like the grammar, failing in lowering) spawn
6608    // background tasks. No `WITH_IO` scan here (probed: the LET
6609    // path accepts what statement `ASYNC` rejects).
6610    if head_word.as_deref() == Some(KEYWORD_ASYNC) && rhs.len() > 1 {
6611        let (kind, used) = parse_let_async_rhs(&rhs[1..], var, decl_type, stmt, ctx)?;
6612        return Ok((kind, skipped + 1 + used));
6613    }
6614    // `TIMEOUT`-led lines capture through the wrapper (shape misses
6615    // fall through to generic, which fails in lowering).
6616    if head_word.as_deref() == Some(KEYWORD_TIMEOUT)
6617        && let Some((kind, used)) = parse_timeout_single(rhs, 0, stmt, ctx)?
6618    {
6619        let span = lowering_ctx(stmt);
6620        crate::commands::reject_async_in_capture(&span, &kind).map_err(|e| TokenError {
6621            stmt,
6622            msg: e.to_string(),
6623            line: 0,
6624            col: 0,
6625            kind: None,
6626        })?;
6627        crate::commands::reject_pipe_stdout_in_capture(&span, &kind).map_err(|e| TokenError {
6628            stmt,
6629            msg: e.to_string(),
6630            line: 0,
6631            col: 0,
6632            kind: None,
6633        })?;
6634        return Ok((
6635            StepKind::AssignCapture {
6636                var,
6637                decl_type,
6638                cmd: Box::new(kind),
6639            },
6640            skipped + used,
6641        ));
6642    }
6643    // `AWAIT $v` captures the task output (`$`+name ride gapless in
6644    // this atomic position, like the grammar); anything else
6645    // `AWAIT`-led goes generic below (lowering fails it, probed).
6646    if head_word.as_deref() == Some(KEYWORD_AWAIT)
6647        && rhs.len() == 3
6648        && let (Some(dollar), Some(task)) = (rhs.get(1), rhs.get(2))
6649        && matches!(&dollar.kind, TokKind::Punct('$'))
6650        && task.joint
6651        && let TokKind::Word(task_var) = &task.kind
6652        && is_ident_word(task_var)
6653    {
6654        return Ok((
6655            StepKind::AwaitCapture {
6656                out_var: var,
6657                out_type: decl_type,
6658                task_var: task_var.clone(),
6659            },
6660            skipped + 3,
6661        ));
6662    }
6663    // RUN exec form captures the structured argv (gapped bracket;
6664    // a joint bracket falls through to generic, which fails it in
6665    // lowering).
6666    if head_word.as_deref() == Some(KEYWORD_RUN)
6667        && matches!(
6668            rhs.get(1).map(|t| (&t.kind, t.joint)),
6669            Some((
6670                TokKind::Group {
6671                    delim: GroupDelim::Bracket,
6672                    ..
6673                },
6674                false
6675            ))
6676        )
6677        && rhs.len() == 2
6678    {
6679        let inner = match &rhs[1].kind {
6680            TokKind::Group { inner, .. } => inner.clone(),
6681            _ => unreachable!(),
6682        };
6683        // Non-map blocks miss the exec shape; fall through below
6684        // (known-command capture, then expression), mirroring the
6685        // grammar's ordered alternatives.
6686        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
6687            let kind =
6688                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
6689            return Ok((
6690                StepKind::AssignCapture {
6691                    var,
6692                    decl_type,
6693                    cmd: Box::new(kind),
6694                },
6695                skipped + 2,
6696            ));
6697        }
6698    }
6699    // File `IMPORT ["path" AS ALIAS]` (#115) captures the imported
6700    // pipeline's `RETURN` value like a call (`LET $r: STRING = IMPORT ...`
6701    // lowers to `AssignCapture`): exactly one file entry, no modules.
6702    // Anything else shaped like an import is a hard error; shape misses
6703    // fall through to generic below, which fails them in lowering.
6704    if head_word.as_deref() == Some(KEYWORD_IMPORT)
6705        && let Some((path, alias, used)) = parse_single_file_import(rhs, 0, stmt, ctx)?
6706    {
6707        return Ok((
6708            StepKind::AssignCapture {
6709                var,
6710                decl_type,
6711                cmd: Box::new(StepKind::ImportFile { path, alias }),
6712            },
6713            skipped + used,
6714        ));
6715    }
6716    // Known-command leads capture through the generic parser
6717    // (lowering failures are fatal here, exactly like the committed
6718    // grammar alternative: probed wrapper-alone and `ISOLATED`-led
6719    // shapes error in lowering); unknown leads parse as expressions.
6720    match &head_word {
6721        Some(head) if is_known_command(head) => {
6722            let (cmd, used) = parse_inner_command(rhs, stmt, ctx)?;
6723            let span = lowering_ctx(stmt);
6724            crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| TokenError {
6725                stmt,
6726                msg: e.to_string(),
6727                line: 0,
6728                col: 0,
6729                kind: None,
6730            })?;
6731            crate::commands::reject_pipe_stdout_in_capture(&span, &cmd).map_err(|e| {
6732                TokenError {
6733                    stmt,
6734                    msg: e.to_string(),
6735                    line: 0,
6736                    col: 0,
6737                    kind: None,
6738                }
6739            })?;
6740            // `INHERIT_ENV`-led lines land here (generic): the
6741            // nesting check rejects them (probed).
6742            crate::commands::reject_nested_inherit_env(&span, &cmd).map_err(|e| TokenError {
6743                stmt,
6744                msg: e.to_string(),
6745                line: 0,
6746                col: 0,
6747                kind: None,
6748            })?;
6749            return Ok((
6750                StepKind::AssignCapture {
6751                    var,
6752                    decl_type,
6753                    cmd: Box::new(cmd),
6754                },
6755                skipped + used,
6756            ));
6757        }
6758        _ => {}
6759    }
6760    let mut cur = Cursor::expr(rhs, stmt);
6761    let expr = parse_expr_checked(&mut cur, ctx)?;
6762    let used = skipped + cur.pos;
6763    Ok((
6764        StepKind::Assign {
6765            var,
6766            decl_type,
6767            expr,
6768        },
6769        used,
6770    ))
6771}
6772
6773/// `WITH_IO`-led LET right-hand side, mirroring
6774/// `parse_let_async_statement_from_pair`'s `with_io_command` branch:
6775/// wrapping `ASYNC` binds a pipe-wired background task (multi-step
6776/// blocks fail loudly), wrapping a sync command captures its stdout
6777/// (async bodies and `stdout` pipes fail loudly), and a bare
6778/// bracket fails validation. `None` on shape miss (bad bracket:
6779/// the caller goes generic, which fails in lowering).
6780fn try_let_with_io_rhs(
6781    rhs: &[Tok],
6782    var: String,
6783    decl_type: String,
6784    stmt: usize,
6785    ctx: &ParseCtx,
6786) -> Result<Option<(StepKind, usize)>, TokenError> {
6787    let bracket = match rhs.get(1) {
6788        Some(t)
6789            if !t.joint
6790                && matches!(
6791                    &t.kind,
6792                    TokKind::Group {
6793                        delim: GroupDelim::Bracket,
6794                        ..
6795                    }
6796                ) =>
6797        {
6798            t
6799        }
6800        _ => return Ok(None),
6801    };
6802    let inner = match &bracket.kind {
6803        TokKind::Group { inner, .. } => inner.clone(),
6804        _ => unreachable!(),
6805    };
6806    let bindings = match parse_io_bindings(&inner, stmt)? {
6807        Some(bindings) => bindings,
6808        None => return Ok(None),
6809    };
6810    let fail = |msg: String| TokenError {
6811        stmt,
6812        msg,
6813        line: 0,
6814        col: 0,
6815        kind: None,
6816    };
6817    let rest = &rhs[2..];
6818    let Some(first) = rest.first() else {
6819        // Bare bracket: the grammar's committed validation error.
6820        return Err(fail(
6821            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
6822                .to_string(),
6823        ));
6824    };
6825    if first.joint {
6826        // The inner rides after a `sep`: joint followers miss the
6827        // shape and fail validation like the grammar's bare bracket.
6828        return Err(fail(
6829            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
6830                .to_string(),
6831        ));
6832    }
6833    if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_ASYNC) {
6834        // `WITH_IO [..] ASYNC <single|block>`: the bindings apply
6835        // inside the task thread (same shape as a one-step body
6836        // holding one `WITH_IO` step, which the runtime supports).
6837        // A bare `ASYNC` goes generic and fails in lowering
6838        // (`unknown command: ASYNC`, probed).
6839        let after = &rest[1..];
6840        if after.is_empty() {
6841            // Bare `ASYNC`: the grammar commits to `instruction`
6842            // and lowering fails it (`unknown command: ASYNC`,
6843            // probed); mirror by running generic, staying failed
6844            // even under a lenient dispatcher.
6845            match parse_inner_command(&rest[..1], stmt, ctx) {
6846                Err(e) => return Err(e),
6847                Ok(_) => {
6848                    return Err(fail(
6849                        "LET $var: HANDLE<T> = ASYNC requires a body".to_string(),
6850                    ));
6851                }
6852            }
6853        }
6854        if let Some(second) = after.first()
6855            && matches!(
6856                &second.kind,
6857                TokKind::Group {
6858                    delim: GroupDelim::Brace,
6859                    ..
6860                }
6861            )
6862            && !is_template_brace(second)
6863        {
6864            let brace_inner = match &second.kind {
6865                TokKind::Group { inner, .. } => inner.clone(),
6866                _ => unreachable!(),
6867            };
6868            let body = parse_body_steps(&brace_inner, stmt, ctx, false)?;
6869            if body.len() != 1 {
6870                return Err(fail(
6871                        "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"
6872                            .to_string(),
6873                    ));
6874            }
6875            let wrapped = Step {
6876                guard: None,
6877                kind: StepKind::WithIo {
6878                    bindings,
6879                    cmd: Box::new(
6880                        body.into_iter()
6881                            .next()
6882                            .ok_or_else(|| {
6883                                fail("LET $var: HANDLE<T> = ASYNC requires a body".to_string())
6884                            })?
6885                            .kind,
6886                    ),
6887                },
6888                scope_enter: 0,
6889                scope_exit: 0,
6890                line: 0,
6891                col: 0,
6892            };
6893            return Ok(Some((
6894                StepKind::AssignAsync {
6895                    var,
6896                    decl_type,
6897                    body: vec![wrapped],
6898                },
6899                2 + 2,
6900            )));
6901        }
6902        if after.first().is_some_and(|t| t.joint) {
6903            // Joint followers miss the inner `sep`: same validation
6904            // error as the bare bracket.
6905            return Err(fail(
6906                "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
6907                    .to_string(),
6908            ));
6909        }
6910        let (cmd, used) = parse_single_inner(
6911            rest,
6912            1,
6913            stmt,
6914            ctx,
6915            InnerRules {
6916                allow_await: false,
6917                allow_with_io: false,
6918            },
6919        )?;
6920        let wrapped = Step {
6921            guard: None,
6922            kind: StepKind::WithIo {
6923                bindings,
6924                cmd: Box::new(cmd),
6925            },
6926            scope_enter: 0,
6927            scope_exit: 0,
6928            line: 0,
6929            col: 0,
6930        };
6931        let kind = StepKind::AssignAsync {
6932            var,
6933            decl_type,
6934            body: vec![wrapped],
6935        };
6936        let span = lowering_ctx(stmt);
6937        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
6938            stmt,
6939            msg: e.to_string(),
6940            line: 0,
6941            col: 0,
6942            kind: None,
6943        })?;
6944        return Ok(Some((kind, 2 + 1 + used)));
6945    }
6946    if matches!(
6947        &first.kind,
6948        TokKind::Group {
6949            delim: GroupDelim::Brace,
6950            ..
6951        }
6952    ) {
6953        // A brace is no sync command: same validation error (probed).
6954        return Err(fail(
6955            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
6956                .to_string(),
6957        ));
6958    }
6959    // Sync inner: capture with the shared checks (the capture sink
6960    // owns stdout; async never runs inline).
6961    let (cmd, used) = parse_single_inner(
6962        rest,
6963        0,
6964        stmt,
6965        ctx,
6966        InnerRules {
6967            allow_await: false,
6968            allow_with_io: true,
6969        },
6970    )?;
6971    let span = lowering_ctx(stmt);
6972    if crate::commands::has_stdout_pipe(&bindings) {
6973        return Err(fail(
6974            "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
6975                .to_string(),
6976        ));
6977    }
6978    crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| TokenError {
6979        stmt,
6980        msg: e.to_string(),
6981        line: 0,
6982        col: 0,
6983        kind: None,
6984    })?;
6985    Ok(Some((
6986        StepKind::AssignCapture {
6987            var,
6988            decl_type,
6989            cmd: Box::new(StepKind::WithIo {
6990                bindings,
6991                cmd: Box::new(cmd),
6992            }),
6993        },
6994        2 + used,
6995    )))
6996}
6997
6998/// `ASYNC`-led LET right-hand side (the tokens after `ASYNC`):
6999/// a block or single command becomes the task body. No `WITH_IO`
7000/// scan (probed: this path accepts what statement `ASYNC`
7001/// rejects); nesting still fails loudly through the shared check.
7002fn parse_let_async_rhs(
7003    rest: &[Tok],
7004    var: String,
7005    decl_type: String,
7006    stmt: usize,
7007    ctx: &ParseCtx,
7008) -> Result<(StepKind, usize), TokenError> {
7009    let Some(first) = rest.first() else {
7010        return Err(TokenError {
7011            stmt,
7012            msg: "LET $var: HANDLE<T> = ASYNC requires a body".to_string(),
7013            line: 0,
7014            col: 0,
7015            kind: None,
7016        });
7017    };
7018    if matches!(
7019        &first.kind,
7020        TokKind::Group {
7021            delim: GroupDelim::Brace,
7022            ..
7023        }
7024    ) && !is_template_brace(first)
7025    {
7026        let inner = match &first.kind {
7027            TokKind::Group { inner, .. } => inner.clone(),
7028            _ => unreachable!(),
7029        };
7030        let body = parse_body_steps(&inner, stmt, ctx, false)?;
7031        let kind = StepKind::AssignAsync {
7032            var,
7033            decl_type,
7034            body,
7035        };
7036        let span = lowering_ctx(stmt);
7037        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7038            stmt,
7039            msg: e.to_string(),
7040            line: 0,
7041            col: 0,
7042            kind: None,
7043        })?;
7044        return Ok((kind, 1));
7045    }
7046    if first.joint {
7047        return Err(TokenError {
7048            stmt,
7049            msg: "LET $var: HANDLE<T> = ASYNC requires a body".to_string(),
7050            line: 0,
7051            col: 0,
7052            kind: None,
7053        });
7054    }
7055    let (cmd, used) = parse_single_inner(
7056        rest,
7057        0,
7058        stmt,
7059        ctx,
7060        InnerRules {
7061            allow_await: false,
7062            allow_with_io: false,
7063        },
7064    )?;
7065    let kind = StepKind::AssignAsync {
7066        var,
7067        decl_type,
7068        body: vec![Step {
7069            guard: None,
7070            kind: cmd,
7071            scope_enter: 0,
7072            scope_exit: 0,
7073            line: 0,
7074            col: 0,
7075        }],
7076    };
7077    let span = lowering_ctx(stmt);
7078    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7079        stmt,
7080        msg: e.to_string(),
7081        line: 0,
7082        col: 0,
7083        kind: None,
7084    })?;
7085    Ok((kind, used))
7086}
7087
7088fn parse_set_body(
7089    body: &[Tok],
7090    stmt: usize,
7091    ctx: &ParseCtx,
7092) -> Result<(StepKind, usize), TokenError> {
7093    let mut cur = Cursor::expr(body, stmt);
7094    let var = expect_dollar_var(&mut cur, "mutation requires a variable: $var = <expr>")?;
7095    let assign = find_assign_eq(&body[cur.pos..]).map(|i| i + cur.pos);
7096    let eq = match assign {
7097        Some(eq) => eq,
7098        None => {
7099            return Err(cur.err("mutation requires a variable: $var = <expr>"));
7100        }
7101    };
7102    cur.pos = eq + 1;
7103    // Leading gap comments vanish like the `=` gap.
7104    cur.skip_gap();
7105    let expr = parse_expr_checked(&mut cur, ctx)?;
7106    Ok((StepKind::Set { var, expr }, cur.pos))
7107}
7108
7109fn parse_return_body(
7110    body: &[Tok],
7111    stmt: usize,
7112    ctx: &ParseCtx,
7113) -> Result<(StepKind, usize), TokenError> {
7114    let mut cur = Cursor::expr(body, stmt);
7115    match cur.next() {
7116        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_RETURN) => {}
7117        _ => return Err(cur.err("unreachable")),
7118    }
7119    if cur.done() {
7120        return Ok((
7121            StepKind::Return {
7122                expr: Box::new(Expr::Literal(Value::string(String::new()))),
7123                is_bare: true,
7124            },
7125            cur.pos,
7126        ));
7127    }
7128    let expr = parse_expr_checked(&mut cur, ctx)?;
7129    Ok((
7130        StepKind::Return {
7131            expr: Box::new(expr),
7132            is_bare: false,
7133        },
7134        cur.pos,
7135    ))
7136}
7137
7138/// Lower one statement to steps through the element loop: the
7139/// statement guard attaches to the first element only (trailing
7140/// elements ride guardless, probed): the pending guard clears after
7141/// the first command token.
7142fn lower_stmt_steps(
7143    stmt: &Stmt,
7144    idx: usize,
7145    ctx: &ParseCtx,
7146    in_block: bool,
7147    mark: bool,
7148) -> Result<Vec<Step>, TokenError> {
7149    let guard = parse_guard_groups(&stmt.guard, idx)?;
7150    // Statement-head braces route here (mid-run braces fail inside
7151    // the element loop): templates and guardless/bare blocks fail
7152    // loudly; guarded braces open guard blocks (top level) or the
7153    // nested quirk (in bodies).
7154    let mut steps = if starts_brace(&stmt.body) {
7155        parse_brace_head(stmt, guard, idx, ctx, in_block, mark)?
7156    } else {
7157        parse_elements(&stmt.body, idx, ctx, guard, in_block)?
7158    };
7159    // Stamp the statement's source position on every directly
7160    // produced step still missing one. Nested body steps were stamped
7161    // by their own statements during recursion, so only direct
7162    // products are claimed here; inner statements keep their own
7163    // lines and columns.
7164    for step in &mut steps {
7165        if step.line == 0 {
7166            step.line = stmt.line;
7167        }
7168        if step.col == 0 {
7169            step.col = stmt.col;
7170        }
7171    }
7172    // Qualify bare placeholder calls (`{{ NAME(args) }}`) through
7173    // the shared static resolver, so templates obey exactly the
7174    // statement-position scope rule. Nested bodies were already
7175    // qualified by their own recursive statements with their own
7176    // frames, so only direct products are visited here. Both
7177    // `Arg::String` fragments (via `walk_raw_strings_mut`) and
7178    // `Expr::Literal` strings (LET/SET/RETURN/call args/list/map
7179    // literals/parenthesized args) are qualified: expression
7180    // positions expand through the same `expand_string` at runtime,
7181    // so they must see the same parse-time rewrite. `WithIo` and
7182    // `AssignCapture` box their inner command directly (no recursive
7183    // statement pass), so the helper descends into them; all other
7184    // bodies were already qualified with their own frames.
7185    // `Step.guards` carry no template text (`Guard::Attr` triples
7186    // evaluated via `guard_allows`, never expanded), so there is
7187    // nothing to qualify there.
7188    let mut failed: Option<TokenError> = None;
7189    for step in &mut steps {
7190        qualify_step_templates(step, ctx, idx, &mut failed);
7191        if failed.is_some() {
7192            break;
7193        }
7194    }
7195    if let Some(err) = failed {
7196        return Err(err);
7197    }
7198    Ok(steps)
7199}
7200
7201/// Qualify one direct statement product plus any boxed `WithIo` /
7202/// `AssignCapture` inner command (same scope frame, never a
7203/// recursive statement pass). Body vectors are skipped: their steps
7204/// were qualified by their own recursive statements.
7205fn qualify_step_templates(
7206    step: &mut Step,
7207    ctx: &ParseCtx,
7208    stmt: usize,
7209    failed: &mut Option<TokenError>,
7210) {
7211    qualify_kind_templates(&mut step.kind, ctx, stmt, failed);
7212}
7213
7214/// Qualify one `StepKind` plus boxed inner commands sharing the
7215/// same scope frame.
7216fn qualify_kind_templates(
7217    kind: &mut StepKind,
7218    ctx: &ParseCtx,
7219    stmt: usize,
7220    failed: &mut Option<TokenError>,
7221) {
7222    kind.walk_raw_strings_mut(&mut |text| {
7223        if failed.is_none() {
7224            match qualify_template_calls(text, ctx, stmt) {
7225                Ok(Some(rewritten)) => *text = rewritten,
7226                Ok(None) => {}
7227                Err(err) => *failed = Some(err),
7228            }
7229        }
7230    });
7231    if failed.is_some() {
7232        return;
7233    }
7234    kind.walk_exprs_mut(&mut |expr| {
7235        if failed.is_some() {
7236            return;
7237        }
7238        expr.walk_mut(&mut |node| {
7239            if failed.is_some() {
7240                return;
7241            }
7242            if let Expr::Literal(value) = node
7243                && let Some(text) = value.as_str()
7244            {
7245                match qualify_template_calls(text, ctx, stmt) {
7246                    Ok(Some(rewritten)) => {
7247                        *value = Value::string(rewritten);
7248                    }
7249                    Ok(None) => {}
7250                    Err(err) => *failed = Some(err),
7251                }
7252            }
7253        });
7254    });
7255    if failed.is_some() {
7256        return;
7257    }
7258    // Boxed single commands share the outer scope frame (no recursive
7259    // statement pass built them): qualify the inner kind directly.
7260    match kind {
7261        StepKind::WithIo { cmd, .. } | StepKind::AssignCapture { cmd, .. } => {
7262            qualify_kind_templates(cmd, ctx, stmt, failed);
7263        }
7264        _ => {}
7265    }
7266    if failed.is_some() {
7267        return;
7268    }
7269    // Single-command synthetic bodies share the outer frame: `TIMEOUT 5s
7270    // <cmd>`, `ISOLATED <cmd>`, `ASYNC <cmd>`, and `AssignAsync` wrappers
7271    // build their `body` inline via `parse_single_inner` with no recursive
7272    // `lower_stmt_steps` pass, so their one synthetic step needs this one.
7273    // Brace-delimited bodies are NEVER re-walked here: they were already
7274    // lowered via `parse_body_steps` with their own frames and statement
7275    // indices (mirroring `Expr::walk_mut` skipping `Expr::Block`), and
7276    // re-resolving under the outer frame would corrupt scope isolation
7277    // and error attribution. The match names only the synthetic carriers;
7278    // any other body (If/For/While/FuncDef/RemoteBlock/WithIoBlock) stays
7279    // exactly as its own recursive pass left it.
7280    match kind {
7281        StepKind::Timeout { body, .. }
7282        | StepKind::Isolated { body }
7283        | StepKind::AsyncBlock { body }
7284        | StepKind::AssignAsync { body, .. } => {
7285            for step in body.iter_mut() {
7286                if failed.is_some() {
7287                    return;
7288                }
7289                qualify_step_templates(step, ctx, stmt, failed);
7290            }
7291        }
7292        _ => {}
7293    }
7294}
7295
7296/// Statement-head `{...}` dispatcher. Template braces fail (the
7297/// grammar strands them); guardless top-level braces fail; detached
7298/// or guardless in-body braces fail (no `block_start` in
7299/// `block_element`); guarded braces open a guard scope at top level
7300/// or mirror the nested quirk formula in bodies. Trailing elements
7301/// loop on guardless outside (like the grammar's continued line).
7302fn parse_brace_head(
7303    stmt: &Stmt,
7304    guard: Option<GuardExpr>,
7305    idx: usize,
7306    ctx: &ParseCtx,
7307    in_block: bool,
7308    mark: bool,
7309) -> Result<Vec<Step>, TokenError> {
7310    let brace = &stmt.body[0];
7311    if is_template_brace(brace) {
7312        return Err(TokenError {
7313            stmt: idx,
7314            msg: "'{' without a pending guard".to_string(),
7315            line: 0,
7316            col: 0,
7317            kind: None,
7318        });
7319    }
7320    let inner = match &brace.kind {
7321        TokKind::Group { inner, .. } => inner.clone(),
7322        _ => unreachable!(),
7323    };
7324    if in_block {
7325        // Attached guarded braces only: pending holds all groups but
7326        // the last (the block's own), mirroring the pair structure.
7327        if guard.is_none() || stmt.brace_detached || stmt.guard.is_empty() {
7328            return Err(TokenError {
7329                stmt: idx,
7330                msg: "unexpected '{' in block body".to_string(),
7331                line: 0,
7332                col: 0,
7333                kind: None,
7334            });
7335        }
7336        let n = stmt.guard.len();
7337        let mut pending = None;
7338        if n > 1 {
7339            pending = parse_guard_groups(&stmt.guard[..n - 1], idx)?;
7340        }
7341        let block_guard = parse_guard_groups(&stmt.guard[n - 1..n], idx)?.ok_or(TokenError {
7342            stmt: idx,
7343            msg: "unexpected '{' in block body".to_string(),
7344            line: 0,
7345            col: 0,
7346            kind: None,
7347        })?;
7348        let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
7349        // Guard-block bodies propagate the ambient marking context
7350        // (top-level nesting marks; wrapper bodies never mark).
7351        // Quirk formula verbatim (including the dropped block guard
7352        // with inner guards, probed).
7353        for s in &mut steps {
7354            let inner_guard = s.guard.take();
7355            s.guard = Some(match (pending.clone(), inner_guard) {
7356                (Some(p), Some(e)) => GuardExpr::all(vec![p, e]),
7357                (Some(p), None) => GuardExpr::all(vec![p, block_guard.clone()]),
7358                (None, Some(e)) => e,
7359                (None, None) => block_guard.clone(),
7360            });
7361        }
7362        // Marking contexts bump each nesting level (probed top-level
7363        // double-block 2/2); wrapper bodies stay 0/0.
7364        // Trailing elements ride outside, unmarked.
7365        if mark {
7366            if let Some(first) = steps.first_mut() {
7367                first.scope_enter += 1;
7368            }
7369            if let Some(last) = steps.last_mut() {
7370                last.scope_exit += 1;
7371            }
7372        }
7373        // Trailing elements loop on guardless outside.
7374        if stmt.body.len() > 1 {
7375            let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
7376            steps.append(&mut rest);
7377        }
7378        return Ok(steps);
7379    }
7380    // Top level: guardless braces fail; guarded braces open a guard
7381    // scope (each step folds outer-then-inner with markers).
7382    let Some(outer) = guard else {
7383        return Err(TokenError {
7384            stmt: idx,
7385            msg: "'{' without a pending guard".to_string(),
7386            line: 0,
7387            col: 0,
7388            kind: None,
7389        });
7390    };
7391    let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
7392    if steps.is_empty() {
7393        return Err(TokenError {
7394            stmt: idx,
7395            msg: "guard block must contain at least one command".to_string(),
7396            line: 0,
7397            col: 0,
7398            kind: None,
7399        });
7400    }
7401    for s in &mut steps {
7402        let inner_guard = s.guard.take();
7403        s.guard = Some(match inner_guard {
7404            Some(e) => GuardExpr::all(vec![outer.clone(), e]),
7405            None => outer.clone(),
7406        });
7407    }
7408    if let Some(first) = steps.first_mut() {
7409        first.scope_enter += 1;
7410    }
7411    if let Some(last) = steps.last_mut() {
7412        last.scope_exit += 1;
7413    }
7414    if stmt.body.len() > 1 {
7415        let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
7416        steps.append(&mut rest);
7417    }
7418    Ok(steps)
7419}
7420
7421/// Parse consecutive elements to end of run (the grammar's
7422/// `element*`): structural pairs (calls, RUN-exec, await/cancel,
7423/// wrapper blocks) end mid-run and trailing elements form following
7424/// steps; instructions and expressions consume greedily to the end.
7425fn parse_elements(
7426    toks: &[Tok],
7427    stmt: usize,
7428    ctx: &ParseCtx,
7429    guard: Option<GuardExpr>,
7430    in_block: bool,
7431) -> Result<Vec<Step>, TokenError> {
7432    let mut steps = Vec::new();
7433    let mut pos = 0;
7434    // Statement guard: consumed by the first element that yields a
7435    // step. `IMPORT` yields none, so the guard leaks to the next
7436    // element (probed).
7437    let mut pending_guard: Option<GuardExpr> = guard;
7438    while pos < toks.len() {
7439        // Trailing gap comments between elements (`} #c`, `F("a")
7440        // /*c*/ ECHO`, `LET $x: INT = 1 //c` — the pair ended, so the
7441        // comment is silent like the grammar, never payload):
7442        // `#` and lexer `Comment` markers run to the run end, `//`
7443        // likewise (line comments eat `;` too, and runs hold no
7444        // newlines), `/* */` balances. Mid-run `#`/`/*` stay payload
7445        // text inside the generic path, which consumes everything
7446        // and never loops back here.
7447        if matches!(&toks[pos].kind, TokKind::Punct('#'))
7448            || matches!(&toks[pos].kind, TokKind::Comment(_))
7449        {
7450            break;
7451        }
7452        if matches!(&toks[pos].kind, TokKind::Punct('/')) && is_comment_open(toks, pos) {
7453            if matches!(
7454                toks.get(pos + 1).map(|t| &t.kind),
7455                Some(TokKind::Punct('/'))
7456            ) {
7457                break;
7458            }
7459            match skip_inline_comment(toks, pos) {
7460                Some(past) => {
7461                    pos = past;
7462                    continue;
7463                }
7464                None => {
7465                    return Err(TokenError {
7466                        stmt,
7467                        msg: "unclosed block comment".to_string(),
7468                        line: 0,
7469                        col: 0,
7470                        kind: None,
7471                    });
7472                }
7473            }
7474        }
7475        // `IMPORT` statements update the import frames; module entries
7476        // emit no step (the guard leaks to the next element, probed,
7477        // unless this is top level, where a guarded module import
7478        // fails), while each file entry emits one `ImportFile` step
7479        // carrying the guard. Shape misses fall through to generic
7480        // (lowering fails them).
7481        if matches!(
7482            toks.get(pos).map(|t| &t.kind),
7483            Some(TokKind::Word(w)) if w == KEYWORD_IMPORT
7484        ) {
7485            // Unified statement form (#115): each entry validates hard
7486            // (unknown modules, bad aliases, templates, remote URLs);
7487            // module entries update the frame and emit no step, file
7488            // and harvest entries emit one step each, in source order.
7489            // A top-level guard on a statement with module entries fails
7490            // like the historical directive; file-only statements consume
7491            // the guard like any other element.
7492            if let Some(((modules, kinds), used)) = parse_import_statement(toks, pos, stmt, ctx)? {
7493                if !modules.is_empty() && !in_block && pending_guard.is_some() {
7494                    return Err(TokenError {
7495                        stmt,
7496                        msg: "IMPORT cannot be guarded".to_string(),
7497                        line: 0,
7498                        col: 0,
7499                        kind: None,
7500                    });
7501                }
7502                // Modules-only statements stay zero-step directives: the
7503                // guard leaks to the next element (probed). Anything with
7504                // file or harvest entries consumes it.
7505                let guard = if kinds.is_empty() {
7506                    None
7507                } else {
7508                    pending_guard.take()
7509                };
7510                for kind in kinds {
7511                    steps.push(Step {
7512                        guard: guard.clone(),
7513                        kind,
7514                        scope_enter: 0,
7515                        scope_exit: 0,
7516                        line: 0,
7517                        col: 0,
7518                    });
7519                }
7520                pos += used;
7521                continue;
7522            }
7523        }
7524        let guard = pending_guard.take();
7525        let (mut got, used) = parse_element_at(toks, pos, stmt, ctx, guard, in_block)?;
7526        if used == 0 {
7527            return Err(TokenError {
7528                stmt,
7529                msg: "element consumed no input".to_string(),
7530                line: 0,
7531                col: 0,
7532                kind: None,
7533            });
7534        }
7535        steps.append(&mut got);
7536        pos += used;
7537    }
7538    Ok(steps)
7539}
7540
7541/// Parse one element at `pos`, returning built steps (guard already
7542/// assigned: `first_guard` for the first, folded per io-block inner
7543/// step) and tokens consumed.
7544fn parse_element_at(
7545    toks: &[Tok],
7546    pos: usize,
7547    stmt: usize,
7548    ctx: &ParseCtx,
7549    first_guard: Option<GuardExpr>,
7550    in_block: bool,
7551) -> Result<(Vec<Step>, usize), TokenError> {
7552    let step = |kind: StepKind| Step {
7553        guard: first_guard.clone(),
7554        kind,
7555        scope_enter: 0,
7556        scope_exit: 0,
7557        line: 0,
7558        col: 0,
7559    };
7560    let head_word = match toks.get(pos).map(|t| &t.kind) {
7561        Some(TokKind::Word(w)) => Some(w.clone()),
7562        _ => None,
7563    };
7564    // Mid-run `{...}` (after a call, wrapper block, ...): the
7565    // grammar strands it (`block_start` needs a pending guard or
7566    // `WITH_IO` wait, both consumed), so fail loudly. Statement-head
7567    // braces route through `lower_stmt_steps`, never here.
7568    if starts_brace(&toks[pos..]) {
7569        return Err(TokenError {
7570            stmt,
7571            msg: "'{' without a pending guard".to_string(),
7572            line: 0,
7573            col: 0,
7574            kind: None,
7575        });
7576    }
7577    // LET/SET/RETURN heads parse with groups intact, then trailing
7578    // elements loop on (probed `LET $x: INT = 1 ECHO bye`). LET shape
7579    // misses fall to generic (lowering fails them like a committed
7580    // `instruction` would, e.g. `LET foo`).
7581    if head_word.as_deref() == Some(KEYWORD_LET)
7582        && let Some((kind, used)) = parse_let_body(&toks[pos..], stmt, ctx)?
7583    {
7584        return Ok((vec![step(kind)], used));
7585    }
7586    if matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('$'))) {
7587        let (kind, used) = parse_set_body(&toks[pos..], stmt, ctx)?;
7588        return Ok((vec![step(kind)], used));
7589    }
7590    if head_word.as_deref() == Some(KEYWORD_RETURN) {
7591        let (kind, used) = parse_return_body(&toks[pos..], stmt, ctx)?;
7592        return Ok((vec![step(kind)], used));
7593    }
7594    // Calls route before heads (even known commands take the call
7595    // path with a joint paren, probed `ECHO("hi")`); the call ends
7596    // mid-run and trailing elements loop on (fixes the slice-4a
7597    // divergence, probed).
7598    if call_shape_at(toks, pos, true).is_some() {
7599        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
7600        return Ok((vec![step(kind)], used));
7601    }
7602    // Block statements (shape misses fall to generic, which fails
7603    // them in lowering like the grammar's committed `instruction`).
7604    // `BREAK`/`CONTINUE` take no args (structural, like the grammar):
7605    // each consumes one token and trailing elements loop on (probed
7606    // `BREAK ECHO hi`); a lone trailing word fails downstream like
7607    // the grammar's committed mismatch.
7608    match head_word.as_deref() {
7609        Some(KEYWORD_BREAK) => {
7610            return Ok((vec![step(StepKind::Break)], 1));
7611        }
7612        Some(KEYWORD_CONTINUE) => {
7613            return Ok((vec![step(StepKind::Continue)], 1));
7614        }
7615        Some(KEYWORD_IF) => {
7616            if let Some((kind, used)) = parse_if_at(toks, pos, stmt, ctx)? {
7617                return Ok((vec![step(kind)], used));
7618            }
7619        }
7620        Some(KEYWORD_FOR) => {
7621            if let Some((kind, used)) = parse_for_at(toks, pos, stmt, ctx)? {
7622                return Ok((vec![step(kind)], used));
7623            }
7624        }
7625        Some(KEYWORD_WHILE) => {
7626            if let Some((kind, used)) = parse_while_single(toks, pos, stmt, ctx)? {
7627                return Ok((vec![step(kind)], used));
7628            }
7629        }
7630        Some(KEYWORD_FUNC) => {
7631            if let Some((kind, used)) = parse_func_at(toks, pos, stmt, ctx, false)? {
7632                return Ok((vec![step(kind)], used));
7633            }
7634        }
7635        Some(KEYWORD_REMOTE) => {
7636            if let Some((kind, used)) = parse_remote_single(toks, pos, stmt, ctx)? {
7637                return Ok((vec![step(kind)], used));
7638            }
7639        }
7640        _ => {}
7641    }
7642    // Wrappers (block or single); shape misses fall to generic.
7643    match head_word.as_deref() {
7644        Some(KEYWORD_WITH_IO) => {
7645            return parse_with_io_element(toks, pos, stmt, ctx, first_guard);
7646        }
7647        Some(KEYWORD_TIMEOUT) => {
7648            if let Some((kind, used)) = parse_timeout_single(toks, pos, stmt, ctx)? {
7649                return Ok((vec![step(kind)], used));
7650            }
7651        }
7652        Some(KEYWORD_ISOLATED) => {
7653            if let Some((kind, used)) = parse_isolated_single(toks, pos, stmt, ctx)? {
7654                return Ok((vec![step(kind)], used));
7655            }
7656        }
7657        Some(KEYWORD_ASYNC) => {
7658            // ASYNC FUNC definition form: prefix, parser records is_async
7659            // with no type-constraint validation (checker owns HANDLE rule).
7660            if matches!(toks.get(pos + 1).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC)
7661                && let Some((kind, used)) = parse_func_at(toks, pos + 1, stmt, ctx, true)?
7662            {
7663                return Ok((vec![step(kind)], 1 + used));
7664            }
7665            if let Some((kind, used)) = parse_async_single(toks, pos, stmt, ctx)? {
7666                return Ok((vec![step(kind)], used));
7667            }
7668        }
7669        _ => {}
7670    }
7671    // AWAIT/CANCEL statements (element level admits the `$` gap,
7672    // probed); heads without `$` go generic (lowering fails them).
7673    if matches!(
7674        head_word.as_deref(),
7675        Some(KEYWORD_AWAIT) | Some(KEYWORD_CANCEL)
7676    ) && let Some((kind, used)) = parse_await_cancel_at(toks, pos, stmt, false)?
7677    {
7678        return Ok((vec![step(kind)], used));
7679    }
7680    // `INHERIT_ENV [...]` parses strictly even at element level
7681    // (keys stay exact everywhere; slice 5 adds only the
7682    // prelude-order validation). Shape misses go generic.
7683    if head_word.as_deref() == Some(KEYWORD_INHERIT_ENV)
7684        && let Some((kind, used)) = parse_inherit_env_at(toks, pos, stmt)?
7685    {
7686        return Ok((vec![step(kind)], used));
7687    }
7688    // `EXPORT ...` records names (zero steps) or misses to generic;
7689    // level and guard violations fail loudly like the backend.
7690    if head_word.as_deref() == Some(KEYWORD_EXPORT) {
7691        if in_block {
7692            return Err(TokenError {
7693                stmt,
7694                msg: "EXPORT is only allowed at the top level".to_string(),
7695                line: 0,
7696                col: 0,
7697                kind: None,
7698            });
7699        }
7700        if first_guard.is_some() {
7701            return Err(TokenError {
7702                stmt,
7703                msg: "EXPORT cannot be guarded".to_string(),
7704                line: 0,
7705                col: 0,
7706                kind: None,
7707            });
7708        }
7709        if let Some((
7710            ExportNames {
7711                func_names,
7712                type_names,
7713            },
7714            used,
7715        )) = parse_export_at(toks, pos)
7716        {
7717            for name in &func_names {
7718                for part in name.split(MODULE_SEPARATOR) {
7719                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
7720                        .map_err(|e| lower_err(stmt, e))?;
7721                }
7722                if ctx.func_exports.borrow().contains(name)
7723                    || ctx.type_exports.borrow().contains(name)
7724                {
7725                    return Err(TokenError {
7726                        stmt,
7727                        msg: format!("duplicate EXPORT `{name}`"),
7728                        line: 0,
7729                        col: 0,
7730                        kind: Some(ParseErrorKind::Validation {
7731                            command: KEYWORD_EXPORT.to_string(),
7732                        }),
7733                    });
7734                }
7735                ctx.func_exports.borrow_mut().push(name.clone());
7736            }
7737            for name in &type_names {
7738                for part in name.split(MODULE_SEPARATOR) {
7739                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
7740                        .map_err(|e| lower_err(stmt, e))?;
7741                }
7742                if ctx.func_exports.borrow().contains(name)
7743                    || ctx.type_exports.borrow().contains(name)
7744                {
7745                    return Err(TokenError {
7746                        stmt,
7747                        msg: format!("duplicate EXPORT `{name}`"),
7748                        line: 0,
7749                        col: 0,
7750                        kind: Some(ParseErrorKind::Validation {
7751                            command: KEYWORD_EXPORT.to_string(),
7752                        }),
7753                    });
7754                }
7755                ctx.type_exports.borrow_mut().push(name.clone());
7756            }
7757            return Ok((Vec::new(), used));
7758        }
7759    }
7760    // `TYPE NAME = SHAPE` aliases (zero or one step); level and guard
7761    // violations fail loudly, shape misses fall to generic.
7762    if head_word.as_deref() == Some(KEYWORD_TYPE) {
7763        if in_block {
7764            return Err(TokenError {
7765                stmt,
7766                msg: "TYPE must appear at top level".to_string(),
7767                line: 0,
7768                col: 0,
7769                kind: None,
7770            });
7771        }
7772        if first_guard.is_some() {
7773            return Err(TokenError {
7774                stmt,
7775                msg: "TYPE cannot be guarded".to_string(),
7776                line: 0,
7777                col: 0,
7778                kind: None,
7779            });
7780        }
7781        if let Some((kind, used)) = parse_type_stmt_at(toks, pos, stmt)? {
7782            return Ok((vec![step(kind)], used));
7783        }
7784    }
7785    // Lowercase heads name their uppercase form (the grammar's
7786    // `command_name` mismatch): never a bare unknown-command.
7787    if let Some(head) = head_word.as_deref()
7788        && head.chars().all(|c| c.is_ascii_lowercase())
7789        && let upper = head.to_ascii_uppercase()
7790        && (is_known_command(&upper) || crate::STRUCTURAL_KEYWORDS.contains(&upper.as_str()))
7791    {
7792        return Err(TokenError {
7793            stmt,
7794            msg: format!("command must be uppercase: found `{head}`, expected `{upper}`"),
7795            line: 0,
7796            col: 0,
7797            kind: Some(ParseErrorKind::Syntax),
7798        });
7799    }
7800    // RUN-exec ends mid-run (trailing loops on, probed); generic
7801    // instructions consume everything.
7802    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
7803    Ok((vec![step(kind)], used))
7804}
7805
7806/// Element-level `WITH_IO`: a same-run brace (any gap: `]{` works,
7807/// probed) opens the io-block form, wrapping every inner step with
7808/// scope markers; a joint non-brace follower is the pending-guard
7809/// error (the splitter only holds bare brackets); anything else is
7810/// the single form. Shape misses go generic.
7811fn parse_with_io_element(
7812    toks: &[Tok],
7813    pos: usize,
7814    stmt: usize,
7815    ctx: &ParseCtx,
7816    first_guard: Option<GuardExpr>,
7817) -> Result<(Vec<Step>, usize), TokenError> {
7818    // The bracket rides gapped (`sep`); anything else misses the
7819    // shape and generic fails it in lowering.
7820    let bracket = match toks.get(pos + 1) {
7821        Some(t)
7822            if !t.joint
7823                && matches!(
7824                    &t.kind,
7825                    TokKind::Group {
7826                        delim: GroupDelim::Bracket,
7827                        ..
7828                    }
7829                ) =>
7830        {
7831            Some(t)
7832        }
7833        _ => None,
7834    };
7835    let Some(bracket) = bracket else {
7836        // Shape miss: generic fails it in lowering.
7837        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
7838        return Ok((
7839            vec![Step {
7840                guard: first_guard,
7841                kind,
7842                scope_enter: 0,
7843                scope_exit: 0,
7844                line: 0,
7845                col: 0,
7846            }],
7847            used,
7848        ));
7849    };
7850    let inner = match &bracket.kind {
7851        TokKind::Group { inner, .. } => inner.clone(),
7852        _ => unreachable!(),
7853    };
7854    let bindings = match parse_io_bindings(&inner, stmt)? {
7855        Some(bindings) => bindings,
7856        // Shape miss: generic fails it.
7857        None => {
7858            let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
7859            return Ok((
7860                vec![Step {
7861                    guard: first_guard,
7862                    kind,
7863                    scope_enter: 0,
7864                    scope_exit: 0,
7865                    line: 0,
7866                    col: 0,
7867                }],
7868                used,
7869            ));
7870        }
7871    };
7872    let rest = pos + 2;
7873    // Same-run brace opens the io-block form (block-expanded
7874    // bindings skip the tty checks: the runtime repeats them).
7875    if let Some(next) = toks.get(rest)
7876        && matches!(
7877            &next.kind,
7878            TokKind::Group {
7879                delim: GroupDelim::Brace,
7880                ..
7881            }
7882        )
7883        && !is_template_brace(next)
7884    {
7885        let brace_inner = match &next.kind {
7886            TokKind::Group { inner, .. } => inner.clone(),
7887            _ => unreachable!(),
7888        };
7889        let mut steps = parse_body_steps(&brace_inner, stmt, ctx, false)?;
7890        if steps.is_empty() {
7891            return Err(TokenError {
7892                stmt,
7893                msg: "WITH_IO block must contain at least one command".to_string(),
7894                line: 0,
7895                col: 0,
7896                kind: None,
7897            });
7898        }
7899        // Every inner step wraps (merging when already wrapped,
7900        // like nested io scopes); the line guard folds into each
7901        // inner guard, inner-first (probed fold order).
7902        for s in &mut steps {
7903            let merged = match std::mem::replace(&mut s.kind, StepKind::Continue) {
7904                StepKind::WithIo {
7905                    bindings: inner_bindings,
7906                    cmd,
7907                } => StepKind::WithIo {
7908                    bindings: crate::commands::merge_bindings(&bindings, &inner_bindings),
7909                    cmd,
7910                },
7911                other => StepKind::WithIo {
7912                    bindings: bindings.clone(),
7913                    cmd: Box::new(other),
7914                },
7915            };
7916            s.kind = merged;
7917            s.guard = crate::commands::and_guard_exprs(s.guard.take(), first_guard.clone());
7918        }
7919        let span = lowering_ctx(stmt);
7920        for s in &steps {
7921            crate::commands::reject_nested_inherit_env(&span, &s.kind).map_err(|e| TokenError {
7922                stmt,
7923                msg: e.to_string(),
7924                line: 0,
7925                col: 0,
7926                kind: None,
7927            })?;
7928        }
7929        if let Some(first) = steps.first_mut() {
7930            first.scope_enter += 1;
7931        }
7932        if let Some(last) = steps.last_mut() {
7933            last.scope_exit += 1;
7934        }
7935        return Ok((steps, rest + 1 - pos));
7936    }
7937    if rest >= toks.len() {
7938        // Unreachable: the splitter holds bare brackets for `{`.
7939        // Kept for body-parsed runs, mirroring the transient node.
7940        return Ok((
7941            vec![Step {
7942                guard: first_guard,
7943                kind: StepKind::WithIoBlock { bindings },
7944                scope_enter: 0,
7945                scope_exit: 0,
7946                line: 0,
7947                col: 0,
7948            }],
7949            2,
7950        ));
7951    }
7952    // A joint follower misses the inner `sep`: the pending wait
7953    // fails exactly like the grammar.
7954    if toks[rest].joint {
7955        return Err(TokenError {
7956            stmt,
7957            msg: "WITH_IO block must be followed by '{'".to_string(),
7958            line: 0,
7959            col: 0,
7960            kind: None,
7961        });
7962    }
7963    // Single form, shared with single-inner (element guards the step).
7964    let (cmd, used) = parse_single_inner(
7965        toks,
7966        rest,
7967        stmt,
7968        ctx,
7969        InnerRules {
7970            allow_await: false,
7971            allow_with_io: true,
7972        },
7973    )?;
7974    let span = lowering_ctx(stmt);
7975    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| TokenError {
7976        stmt,
7977        msg: e.to_string(),
7978        line: 0,
7979        col: 0,
7980        kind: None,
7981    })?;
7982    let kind = StepKind::WithIo {
7983        bindings,
7984        cmd: Box::new(cmd),
7985    };
7986    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7987        stmt,
7988        msg: e.to_string(),
7989        line: 0,
7990        col: 0,
7991        kind: None,
7992    })?;
7993    Ok((
7994        vec![Step {
7995            guard: first_guard,
7996            kind,
7997            scope_enter: 0,
7998            scope_exit: 0,
7999            line: 0,
8000            col: 0,
8001        }],
8002        2 + used,
8003    ))
8004}
8005
8006/// Shared inner-command parser: statement calls (joint paren, even on
8007/// known commands), RUN exec
8008/// form, and generic instructions. Returns the kind and tokens
8009/// consumed: calls and RUN-exec end mid-run (the caller continues
8010/// past them, like the grammar's `element*`); generic instructions
8011/// consume everything. Wrappers never route here (element and
8012/// single-inner dispatch own them); slice 4b reuses the call/RUN
8013/// arms for trailing elements.
8014fn parse_inner_command(
8015    body: &[Tok],
8016    stmt: usize,
8017    ctx: &ParseCtx,
8018) -> Result<(StepKind, usize), TokenError> {
8019    // Bare `NAME(...)` calls invoke functions with one syntax; the head
8020    // and `(` ride gapless or the shape stays an instruction (which
8021    // fails later as UnknownCommand), exactly like the grammar.
8022    if let Some((call_name, paren)) = call_shape_at(body, 0, true) {
8023        let inner = match &body[paren].kind {
8024            TokKind::Group { inner, .. } => inner.clone(),
8025            _ => unreachable!(),
8026        };
8027        let args = parse_call_args(&inner, stmt, ctx)?;
8028        // Statement-level `INSPECT(...)` resolves like any other call
8029        // (only expression position mints the node); unknown functions
8030        // fail in the shared resolver with identical messages.
8031        if !call_name.contains(MODULE_SEPARATOR) {
8032            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
8033                .map_err(|e| lower_err(stmt, e))?;
8034        }
8035        let qualified = resolve_name(ctx, stmt, &call_name)?;
8036        return Ok((
8037            StepKind::Call {
8038                name: qualified,
8039                args,
8040            },
8041            paren + 1,
8042        ));
8043    }
8044    let head = match body.first().map(|t| &t.kind) {
8045        Some(TokKind::Word(n)) => n.clone(),
8046        _ => {
8047            return Err(TokenError {
8048                stmt,
8049                msg: "statement must open with a command word".to_string(),
8050                line: 0,
8051                col: 0,
8052                kind: None,
8053            });
8054        }
8055    };
8056    // RUN exec form: the list routes structured through `lower` (the
8057    // mock wraps it in `Run`; production maps it to `RunExec`); the
8058    // caller continues past the list, like the grammar. The list
8059    // rides gapped (`sep`): a joint bracket is a hard error, never
8060    // a spliced arg (probed `RUN["a"]`).
8061    if head == KEYWORD_RUN
8062        && matches!(
8063            body.get(1).map(|t| &t.kind),
8064            Some(TokKind::Group {
8065                delim: GroupDelim::Bracket,
8066                ..
8067            })
8068        )
8069    {
8070        if body[1].joint {
8071            return Err(TokenError {
8072                stmt,
8073                msg: "RUN [...] requires a gap after RUN".to_string(),
8074                line: 0,
8075                col: 0,
8076                kind: None,
8077            });
8078        }
8079        let inner = match &body[1].kind {
8080            TokKind::Group { inner, .. } => inner.clone(),
8081            _ => unreachable!(),
8082        };
8083        // Non-map blocks miss the exec shape (the grammar has no
8084        // `block` alternative here); fall through to the shell path
8085        // below, which reads the bracket literally.
8086        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
8087            let kind =
8088                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
8089            return Ok((kind, 2));
8090        }
8091    }
8092    let tokens = build_arg_tokens(&body[1..], stmt, ctx)?;
8093    let kind = lower_generic_args(&head, tokens, stmt, ctx)?;
8094    Ok((kind, body.len()))
8095}
8096
8097/// Parse a token stream (either lexer) into steps. Markers normalize to
8098/// 0/0 like the fuzz harness; scopes arrive with block slices.
8099pub fn parse_tokens(
8100    toks: &[Tok],
8101    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8102) -> Result<Vec<Step>, TokenError> {
8103    let modules = ModuleTable::default();
8104    let reserved = HashSet::new();
8105    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
8106    parse_tokens_with_ctx(toks, &ctx)
8107}
8108
8109/// Parse with an explicit context (module table for call resolution).
8110/// `parse_tokens` uses empty modules.
8111pub fn parse_tokens_with_ctx(toks: &[Tok], ctx: &ParseCtx) -> Result<Vec<Step>, TokenError> {
8112    let mut out = Vec::new();
8113    *ctx.current_line.borrow_mut() = 1;
8114    for (i, s) in split_statements(toks, 1)?.iter().enumerate() {
8115        *ctx.current_line.borrow_mut() = s.line;
8116        out.extend(
8117            lower_stmt_steps(s, i, ctx, false, true).map_err(|e| stamp_pos(e, s.line, s.col))?,
8118        );
8119    }
8120    // Whole-script validations through the shared validators.
8121    // `INHERIT_ENV` prelude order: only leading positions read.
8122    {
8123        let mut seen_non_prelude = false;
8124        for step in &out {
8125            match &step.kind {
8126                StepKind::InheritEnv { .. } => {
8127                    if seen_non_prelude {
8128                        return Err(TokenError {
8129                            stmt: out.len(),
8130                            msg: "INHERIT_ENV must appear before any other commands".to_string(),
8131                            line: 0,
8132                            col: 0,
8133                            kind: None,
8134                        });
8135                    }
8136                }
8137                kind => {
8138                    if crate::commands::contains_inherit_env(kind) {
8139                        return Err(TokenError {
8140                            stmt: out.len(),
8141                            msg: "INHERIT_ENV cannot be nested inside other commands".to_string(),
8142                            line: 0,
8143                            col: 0,
8144                            kind: None,
8145                        });
8146                    }
8147                    seen_non_prelude = true;
8148                }
8149            }
8150        }
8151    }
8152    crate::commands::validate_remote_copy_placement(&out, &lowering_ctx(out.len())).map_err(
8153        |e| TokenError {
8154            stmt: out.len(),
8155            msg: e.to_string(),
8156            line: 0,
8157            col: 0,
8158            kind: None,
8159        },
8160    )?;
8161    {
8162        let top: HashSet<String> = ctx.funcs.borrow().first().cloned().unwrap_or_default();
8163        let top_imports: Vec<String> = ctx.imports.borrow().first().cloned().unwrap_or_default();
8164        let mut top_types = HashSet::new();
8165        for step in &out {
8166            if let StepKind::TypeAlias { name, .. } = &step.kind {
8167                top_types.insert(name.clone());
8168            }
8169        }
8170        crate::commands::validate_exports(
8171            &lowering_ctx(out.len()),
8172            &ctx.func_exports.borrow(),
8173            &ctx.type_exports.borrow(),
8174            &top,
8175            &top_types,
8176            ctx.modules,
8177            &top_imports,
8178        )
8179        .map_err(|e| TokenError {
8180            stmt: out.len(),
8181            msg: e.to_string(),
8182            line: 0,
8183            col: 0,
8184            kind: None,
8185        })?;
8186    }
8187    Ok(out)
8188}
8189
8190// ---- String entry points: lex, lower, collect exports and docs ----
8191
8192/// Source text of a 1-based line. The line just past a trailing
8193/// newline (where unbalanced groups report) reads as empty text so
8194/// caret blocks still render.
8195fn source_line_of(input: &str, line: usize) -> Option<String> {
8196    let count = input.lines().count();
8197    let idx = line.checked_sub(1)?;
8198    if idx < count {
8199        input.lines().nth(idx).map(str::to_string)
8200    } else if idx == count {
8201        Some(String::new())
8202    } else {
8203        None
8204    }
8205}
8206
8207/// Last script line (end-of-script validations blame it).
8208fn last_line(input: &str) -> usize {
8209    input.lines().count().max(1)
8210}
8211
8212/// Convert a lexer failure: low-level syntax kind, exact lexer
8213/// position, and the source line for the caret block. Unclosed groups
8214/// name their opener (no grammar dumps); the closer expectation rides
8215/// along so `expected()` stays informative. A lexer-known kind (an
8216/// unclosed `WITH_IO` bracket) converts verbatim.
8217fn lex_error(input: &str, e: LexError) -> ParseError {
8218    let line = e.line.max(1);
8219    let ctx = match source_line_of(input, line) {
8220        Some(source_line) => SpanContext::full(line, e.col.max(1), e.col.max(1), source_line),
8221        None => SpanContext::line_only(line),
8222    };
8223    if let Some(ParseErrorKind::InvalidSyntax { command }) = e.kind {
8224        // Lexer-known command syntax (an unclosed `WITH_IO` bracket).
8225        return ParseError::invalid_syntax(
8226            &command,
8227            e.msg,
8228            None,
8229            vec!["`]`".to_string()],
8230            None,
8231            &ctx,
8232        );
8233    }
8234    let expected = if e.msg.starts_with("unclosed") {
8235        vec!["`}`".to_string()]
8236    } else {
8237        Vec::new()
8238    };
8239    ParseError::syntax(e.msg, expected, None, &ctx)
8240}
8241
8242/// Convert a backend failure, preserving the dispatcher's error kind
8243/// and completing line/source context the token stream knows. Spans
8244/// open at the statement's start column and cover its whole first line
8245/// (multi-line spans clamp to the start line), so caret blocks render
8246/// for every string-path error.
8247fn token_error(input: &str, e: TokenError) -> ParseError {
8248    let line = if e.line == 0 {
8249        last_line(input)
8250    } else {
8251        e.line
8252    };
8253    let start_col = e.col.max(1);
8254    let ctx = match source_line_of(input, line) {
8255        Some(source_line) => {
8256            let end = source_line.len().max(start_col);
8257            SpanContext::full(line, start_col, end, source_line)
8258        }
8259        None => SpanContext::line_only(line),
8260    };
8261    // Column spans are statement granularity (every error names its
8262    // statement's first column); the caret block still renders.
8263    match e.kind {
8264        Some(crate::error::ParseErrorKind::UnknownCommand { name }) => {
8265            ParseError::unknown_command(&name, e.msg, None, &ctx)
8266        }
8267        Some(crate::error::ParseErrorKind::InvalidSyntax { command }) => {
8268            ParseError::invalid_syntax(&command, e.msg, None, Vec::new(), None, &ctx)
8269        }
8270        Some(crate::error::ParseErrorKind::Validation { command }) => {
8271            ParseError::validation(&command, e.msg, &ctx)
8272        }
8273        Some(crate::error::ParseErrorKind::Syntax) => {
8274            ParseError::syntax(e.msg, Vec::new(), None, &ctx)
8275        }
8276        Some(crate::error::ParseErrorKind::Structural { rule }) => {
8277            ParseError::structural(&rule, e.msg, &ctx)
8278        }
8279        None => ParseError::structural("statement", e.msg, &ctx),
8280    }
8281}
8282
8283/// Shared parse driver: lex, lower with preseeded frames, and collect
8284/// `EXPORT` names (validated at end of parse, forward references
8285/// allowed).
8286fn parse_with_ctx(
8287    input: &str,
8288    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8289    reserved_names: HashSet<String>,
8290    modules: ModuleTable,
8291    preseed_funcs: HashSet<String>,
8292    preseed_imports: Vec<String>,
8293) -> ParseResult<ScriptWithExports> {
8294    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
8295    let ctx = ParseCtx::empty(&lower, &modules, &reserved_names);
8296    // Snippet re-parses seed their base frames so lookup behaves
8297    // identically; snippets never define, only read.
8298    ctx.funcs.borrow_mut()[0].extend(preseed_funcs);
8299    ctx.imports.borrow_mut()[0].extend(preseed_imports);
8300    let steps = parse_tokens_with_ctx(&toks, &ctx).map_err(|e| token_error(input, e))?;
8301    let mut steps = steps;
8302    stamp_func_docs(input, &mut steps);
8303    Ok(ScriptWithExports {
8304        steps,
8305        func_exports: ctx.func_exports.borrow().clone(),
8306        type_exports: ctx.type_exports.borrow().clone(),
8307    })
8308}
8309
8310/// Steps plus single-file `EXPORT` metadata, before `#` doc stamping.
8311/// Callers needing docs build a [`ParsedScript`] from this.
8312struct ScriptWithExports {
8313    steps: Vec<Step>,
8314    func_exports: Vec<String>,
8315    type_exports: Vec<String>,
8316}
8317
8318/// Parse a script with an unknown host environment.
8319pub fn parse_script(
8320    input: &str,
8321    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8322) -> ParseResult<Vec<Step>> {
8323    Ok(parse_with_ctx(
8324        input,
8325        lower,
8326        HashSet::new(),
8327        ModuleTable::default(),
8328        HashSet::new(),
8329        Vec::new(),
8330    )?
8331    .steps)
8332}
8333
8334/// Parse a snippet with an enclosing parse's visible scope state, so
8335/// re-parsed inner commands (async bodies) resolve calls identically.
8336/// The snippet never defines, only reads: seeds affect lookup alone.
8337pub fn parse_script_with_preseed(
8338    input: &str,
8339    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8340    reserved_names: HashSet<String>,
8341    modules: ModuleTable,
8342    preseed_funcs: HashSet<String>,
8343    preseed_imports: Vec<String>,
8344) -> ParseResult<Vec<Step>> {
8345    Ok(parse_with_ctx(
8346        input,
8347        lower,
8348        reserved_names,
8349        modules,
8350        preseed_funcs,
8351        preseed_imports,
8352    )?
8353    .steps)
8354}
8355
8356/// Parse with a module provenance table so calls resolve statically:
8357/// qualified `MODULE::NAME` checks membership, bare `NAME` resolves through
8358/// `SCRIPT` definitions and `IMPORT`ed modules, and anything else fails at
8359/// parse time instead of at runtime.
8360pub fn parse_script_with_modules(
8361    input: &str,
8362    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8363    reserved_names: HashSet<String>,
8364    modules: ModuleTable,
8365) -> ParseResult<Vec<Step>> {
8366    Ok(parse_script_with_modules_and_exports(input, lower, reserved_names, modules)?.steps)
8367}
8368
8369/// Parse with modules plus single-file `EXPORT` metadata and `#` doc
8370/// comments for top-level `FUNC`s. Used by the MCP host; the linear
8371/// runner keeps using `parse_script_with_modules` and ignores exports.
8372pub fn parse_script_with_modules_and_exports(
8373    input: &str,
8374    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8375    reserved_names: HashSet<String>,
8376    modules: ModuleTable,
8377) -> ParseResult<ParsedScript> {
8378    let ScriptWithExports {
8379        steps,
8380        func_exports,
8381        type_exports,
8382    } = parse_with_ctx(
8383        input,
8384        lower,
8385        reserved_names,
8386        modules,
8387        HashSet::new(),
8388        Vec::new(),
8389    )?;
8390    Ok(ParsedScript {
8391        func_docs: collect_func_docs(input, &steps),
8392        steps,
8393        func_exports,
8394        type_exports,
8395    })
8396}
8397
8398/// Parse without modules plus `EXPORT` metadata. Used by tests and
8399/// tooling that lower with the shared mock.
8400pub fn parse_script_with_exports(
8401    input: &str,
8402    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8403) -> ParseResult<ParsedScript> {
8404    let ScriptWithExports {
8405        steps,
8406        func_exports,
8407        type_exports,
8408    } = parse_with_ctx(
8409        input,
8410        lower,
8411        HashSet::new(),
8412        ModuleTable::default(),
8413        HashSet::new(),
8414        Vec::new(),
8415    )?;
8416    Ok(ParsedScript {
8417        func_docs: collect_func_docs(input, &steps),
8418        steps,
8419        func_exports,
8420        type_exports,
8421    })
8422}
8423
8424/// Parse one expression from source text with an empty module scope, for
8425/// tooling that shows lowering without running (docs demos, explain output).
8426/// No imports exist here, so bare function calls fail and qualified calls
8427/// fail against the empty table; only `INSPECT` passes through untouched.
8428/// Arithmetic, comparison, variables, env reads, keypaths, and literals
8429/// lower normally, with literal only subtrees folded before flattening.
8430pub fn parse_expression_str(input: &str) -> ParseResult<Expr> {
8431    // Trailing whitespace lexes unconsumed, so lex the trimmed text:
8432    // otherwise padded but valid input fails the full consumption check.
8433    let trimmed = input.trim();
8434    let toks = lex_str(trimmed).map_err(|e| lex_error(trimmed, e))?;
8435    let modules = ModuleTable::default();
8436    let reserved = HashSet::new();
8437    let lower = crate::commands::lower_command as fn(&str, Vec<Arg>) -> ParseResult<StepKind>;
8438    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
8439    *ctx.current_line.borrow_mut() = 1;
8440    parse_single_expr(&toks, 0, &ctx).map_err(|e| token_error(trimmed, e))
8441}
8442
8443/// Parse one guard expression from source text (a bare `guard_seq`:
8444/// predicates, `not`/`any`/`all`, comma lists), for tooling and tests.
8445pub fn parse_guard_expr_str(input: &str) -> ParseResult<GuardExpr> {
8446    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
8447    parse_single_guard(&toks, 0).map_err(|e| token_error(input, e))
8448}
8449
8450/// Parsed script with single-file `EXPORT` metadata. `steps` is the
8451/// linear execution plan, `func_exports` the `EXPORT` func names in
8452/// source order, `type_exports` the `EXPORT TYPE` names in source order,
8453/// and `func_docs` maps top-level `FUNC` base names to (summary, docs)
8454/// collected from the immediately preceding `#` comment block.
8455#[derive(Debug, Clone, Default)]
8456pub struct ParsedScript {
8457    pub steps: Vec<Step>,
8458    pub func_exports: Vec<String>,
8459    pub type_exports: Vec<String>,
8460    pub func_docs: std::collections::HashMap<String, (String, String)>,
8461}
8462
8463fn collect_func_docs(
8464    input: &str,
8465    steps: &[Step],
8466) -> std::collections::HashMap<String, (String, String)> {
8467    use std::collections::{HashMap, HashSet};
8468    let lines: Vec<&str> = input.lines().collect();
8469    // Top-level FUNC definition lines keyed by base name. Brace depth
8470    // tracks nesting so only depth-0 `FUNC` lines count; the first
8471    // occurrence wins because same-scope duplicates fail at lowering.
8472    let mut def_lines: HashMap<String, usize> = HashMap::new();
8473    let mut seen: HashSet<String> = HashSet::new();
8474    let mut depth: usize = 0;
8475    for (idx, line) in lines.iter().enumerate() {
8476        let trimmed = line.trim_start();
8477        let is_comment = trimmed.starts_with('#');
8478        let is_guard_only = trimmed.starts_with('[');
8479        if !is_comment
8480            && !is_guard_only
8481            && let Some(rest) = strip_func_head(trimmed)
8482            && depth == 0
8483            && !seen.contains(&rest)
8484        {
8485            seen.insert(rest.clone());
8486            def_lines.insert(rest, idx + 1);
8487        }
8488        if !is_comment {
8489            for ch in line.chars() {
8490                if ch == '{' {
8491                    depth = depth.saturating_add(1);
8492                } else if ch == '}' {
8493                    depth = depth.saturating_sub(1);
8494                }
8495            }
8496        }
8497    }
8498    let mut out: HashMap<String, (String, String)> = HashMap::new();
8499    for step in steps {
8500        if let StepKind::FuncDef { name, .. } = &step.kind
8501            && !out.contains_key(name)
8502            && let Some(&line_no) = def_lines.get(name)
8503            && let Some((summary, docs)) = docs_above(&lines, line_no)
8504        {
8505            out.insert(name.clone(), (summary, docs));
8506        }
8507    }
8508    out
8509}
8510
8511/// Stamp `#` doc blocks onto top-level `FUNC` steps, from the same map
8512/// that feeds `func_docs`, so step-carried docs and the sidecar can
8513/// never disagree. Only top-level definitions qualify (same rule as
8514/// collection); nested shadowing keeps `docs: None`.
8515fn stamp_func_docs(input: &str, steps: &mut [Step]) {
8516    let docs = collect_func_docs(input, steps);
8517    for step in steps {
8518        if let StepKind::FuncDef {
8519            name, docs: slot, ..
8520        } = &mut step.kind
8521            && slot.is_none()
8522            && let Some(pair) = docs.get(name)
8523        {
8524            *slot = Some(pair.clone());
8525        }
8526    }
8527}
8528
8529fn strip_func_head(trimmed: &str) -> Option<String> {
8530    let rest = trimmed.strip_prefix(KEYWORD_FUNC)?;
8531    let after = rest.strip_prefix([' ', '\t'])?;
8532    if after.is_empty() {
8533        return None;
8534    }
8535    let name: String = after
8536        .chars()
8537        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
8538        .collect();
8539    if name.is_empty()
8540        || !name
8541            .bytes()
8542            .all(|b| b.is_ascii_uppercase() || b == b'_' || b.is_ascii_digit())
8543    {
8544        return None;
8545    }
8546    if name.starts_with(|c: char| c.is_ascii_digit()) {
8547        return None;
8548    }
8549    Some(name)
8550}
8551
8552fn docs_above(lines: &[&str], line_no: usize) -> Option<(String, String)> {
8553    if line_no <= 1 {
8554        return None;
8555    }
8556    let mut block: Vec<String> = Vec::new();
8557    let mut idx = line_no - 1;
8558    while idx > 0 {
8559        idx -= 1;
8560        let trimmed = lines[idx].trim_start();
8561        if trimmed.is_empty() {
8562            break;
8563        }
8564        if let Some(body) = trimmed.strip_prefix('#') {
8565            let text = body.strip_prefix(' ').unwrap_or(body);
8566            block.push(text.to_string());
8567        } else {
8568            break;
8569        }
8570        if idx == 0 {
8571            break;
8572        }
8573    }
8574    if block.is_empty() {
8575        return None;
8576    }
8577    block.reverse();
8578    let summary = block.first().cloned().unwrap_or_default();
8579    let docs = block.join("\n");
8580    Some((summary, docs))
8581}
8582
8583#[cfg(test)]
8584mod tests {
8585    use super::*;
8586    use crate::test_lower_mock;
8587    use indoc::indoc;
8588
8589    fn lower(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
8590        test_lower_mock::lower(name, args)
8591    }
8592
8593    /// Lexer-agreement oracle: both frontends must deliver identical
8594    /// steps through the single backend. `parse_script` is the string
8595    /// entry point; `parse_tokens` runs each lexer's output directly.
8596    fn assert_parity(text: &str) {
8597        let old = crate::parse_script(text, lower)
8598            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
8599        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
8600        let new = parse_tokens(&toks, lower)
8601            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
8602        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
8603        #[cfg(feature = "proc-macro-api")]
8604        {
8605            let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
8606            let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
8607            let new = parse_tokens(&toks, lower).expect("token path must parse token script");
8608            assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
8609        }
8610    }
8611
8612    /// String-path-only oracle for shapes `rustc` cannot carry at all
8613    /// (lifetime-like quotes). The backend must still agree there.
8614    fn assert_parity_string_only(text: &str) {
8615        let old = crate::parse_script(text, lower)
8616            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
8617        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
8618        let new = parse_tokens(&toks, lower)
8619            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
8620        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
8621    }
8622
8623    #[test]
8624    fn token_and_string_paths_agree_on_wrappers() {
8625        // Single-command wrappers, io-blocks, await/cancel,
8626        // LET wrapper forms — three-way agreement per script.
8627        for text in [
8628            "WITH_IO [stdout=$p] ECHO hi",
8629            "WITH_IO [stdin=$p] ECHO hi",
8630            "WITH_IO [stdin] ECHO hi",
8631            "WITH_IO [stdout] ECHO hi",
8632            "WITH_IO [stdin=$p, stdout=$q] ECHO hi",
8633            "WITH_IO [stdin=$p, stdin=$q] ECHO hi",
8634            "WITH_IO [tty] RUN echo hi",
8635            "WITH_IO [tty, rows=40, cols=100] RUN echo hi",
8636            "WITH_IO [rows=40, cols=100, tty] RUN echo hi",
8637            "WITH_IO [stdin =$p] ECHO hi",
8638            "WITH_IO [stdin= $p] ECHO hi",
8639            "WITH_IO [ stdin=$p ] ECHO hi",
8640            "WITH_IO [\nstdin=$p\n] ECHO hi",
8641            "WITH_IO [stdin=$p\n, stdout=$q] ECHO hi",
8642            "WITH_IO [stdout=$p] ASYNC ECHO hi",
8643            "WITH_IO [stdin=$p] WITH_IO [stderr=$e] ECHO hi",
8644            "WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
8645            "WITH_IO [stdin=$p] ISOLATED ECHO hi",
8646            "WITH_IO [stdin=$p] CANCEL $t",
8647            "WITH_IO [stdin=$p] CANCEL $t ECHO bye",
8648            "WITH_IO [stdin=$p] { ECHO hi }",
8649            "WITH_IO [stdin=$p]\n{ ECHO hi }",
8650            "WITH_IO [stdin=$p]; { ECHO hi }",
8651            "WITH_IO [stdin=$p]{ ECHO hi }",
8652            "WITH_IO [stdin=$p] { ECHO a\nECHO b }",
8653            "WITH_IO [stdin=$p] { ECHO hi } ECHO bye",
8654            "WITH_IO [rows=40] { ECHO hi }",
8655            "WITH_IO [tty] { ECHO hi }",
8656            "WITH_IO [stdin=$p] { WITH_IO [stderr=$e] ECHO hi }",
8657            "TIMEOUT 10s ECHO hi",
8658            "TIMEOUT 10 ECHO hi",
8659            "TIMEOUT 500ms ECHO hi",
8660            "TIMEOUT 5m ECHO hi",
8661            "TIMEOUT 2h ECHO hi",
8662            "TIMEOUT $d ECHO hi",
8663            "TIMEOUT \"10s\" ECHO hi",
8664            "TIMEOUT \"30 s\" ECHO hi",
8665            "TIMEOUT {{ $d }} ECHO hi",
8666            "TIMEOUT 10s AWAIT $t",
8667            "TIMEOUT 10s CANCEL $t",
8668            "TIMEOUT 10s AWAIT $t ECHO bye",
8669            "TIMEOUT 10s CANCEL $t ECHO bye",
8670            "TIMEOUT 10s { ECHO hi }",
8671            "TIMEOUT 10s {\nECHO hi\n}",
8672            "TIMEOUT 10s { ECHO hi } ECHO bye",
8673            "TIMEOUT 10s { ECHO hi } TIMEOUT 5s ECHO bye",
8674            "TIMEOUT 10s TIMEOUT 5s ECHO hi",
8675            "TIMEOUT 10s { ECHO a\nECHO b }",
8676            "TIMEOUT 10s ECHO hi extra",
8677            "ISOLATED ECHO hi",
8678            "ISOLATED { ECHO hi }",
8679            "ISOLATED { ECHO hi } ECHO bye",
8680            "ISOLATED AWAIT $t",
8681            "ISOLATED INHERIT_ENV [M]",
8682            "ISOLATED { INHERIT_ENV [M] }",
8683            "ISOLATED { INHERIT_ENV [MODE]\nECHO hi }",
8684            "ASYNC ECHO hi",
8685            "ASYNC { ECHO hi }",
8686            "ASYNC{ECHO hi}",
8687            "ASYNC { ECHO a\nECHO b }",
8688            "ASYNC { ECHO hi } ECHO bye",
8689            "ASYNC CANCEL $t",
8690            "ASYNC CANCEL $t ECHO bye",
8691            "AWAIT $t",
8692            "AWAIT$t",
8693            "AWAIT $ t",
8694            "AWAIT $T",
8695            "AWAIT $t2",
8696            "AWAIT $_t",
8697            "CANCEL $t",
8698            "CANCEL$t",
8699            "CANCEL $ t",
8700            "AWAIT $t ECHO bye",
8701            "CANCEL $t ECHO bye",
8702            "AWAIT $t AWAIT $u",
8703            "AWAIT $t\nECHO bye",
8704            "LET $t: HANDLE = ASYNC ECHO hi",
8705            "LET $t: HANDLE = ASYNC { ECHO hi }",
8706            "LET $t: HANDLE = ASYNC { ECHO hi } ECHO bye",
8707            "LET $a: STRING = ASYNC ECHO hi",
8708            "LET $t: HANDLE = ASYNC { WITH_IO [stdin=$p] ECHO hi }",
8709            "LET $w: STRING = WITH_IO [stdin=$p] ASYNC ECHO hi",
8710            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC ECHO hi",
8711            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi }",
8712            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi } ECHO bye",
8713            "LET $x: STRING = WITH_IO [stdin=$p] ECHO hi",
8714            "LET $x: STRING = WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
8715            "LET $x: STRING = TIMEOUT 10s ECHO hi",
8716            "LET $x: STRING = TIMEOUT 10s { ECHO hi }",
8717            "LET $x: STRING = TIMEOUT 10s ECHO hi ECHO bye",
8718            "LET $o: STRING = AWAIT $t",
8719            "LET $p: PIPE ECHO bye",
8720            "TIMEOUT 10s WITH_IO [stdin=$p]",
8721            "TIMEOUT 10s WITH_IO [stdin=$p]ECHO hi",
8722            "ISOLATED INHERIT_ENV [A, B]",
8723            "ISOLATED INHERIT_ENV [A-B]",
8724            "TIMEOUT 10s { [os:linux] ECHO hi }",
8725            "ASYNC { [os:linux] ECHO hi }",
8726            "ISOLATED { [os:linux] ECHO hi }",
8727            "[os:linux] WITH_IO [stdin=$p]\n{ ECHO hi }",
8728            "LET $x: INT = 1 ECHO bye",
8729            "CANCEL $t LET $x: INT = 1",
8730            "CANCEL $t $x = 1",
8731            "CANCEL $t RETURN \"hi\"",
8732            "TIMEOUT 10s { ECHO hi } LET $x: INT = 1",
8733            "RUN [\"a\"] ECHO bye",
8734            "[os:linux] AWAIT $t",
8735            "[os:linux] TIMEOUT 10s { ECHO hi } ECHO bye",
8736            "[os:linux] ASYNC CANCEL $t ECHO bye",
8737            "[os:linux] WITH_IO [stdin=$p] { [os:macos] ECHO hi }",
8738        ] {
8739            assert_parity(text);
8740        }
8741    }
8742
8743    #[test]
8744    fn token_and_string_paths_agree_on_blocks() {
8745        // Slice 5: `IF`/`FOR`/`WHILE`/`FUNC` with inline and
8746        // cross-newline `ELSE` chains, guard blocks (top-level and
8747        // nested quirk), and multi-element trailing — three-way
8748        // agreement per script.
8749        for text in [
8750            "IF true { ECHO hi }",
8751            "IF $x { ECHO hi } ELSE { ECHO bye }",
8752            "IF true { ECHO a } ELSE IF false { ECHO b } ELSE { ECHO c }",
8753            "IF true{ ECHO hi }",
8754            "IF true { ECHO hi } ECHO bye",
8755            "IF true { ECHO hi }\nELSE { ECHO bye }",
8756            "IF true { ECHO hi }\nELSE IF false { ECHO b }\nELSE { ECHO c }",
8757            "IF true { ECHO hi } //c\nELSE { ECHO bye }",
8758            "IF true { ECHO hi } #c\nELSE { ECHO bye }",
8759            "IF true { ECHO hi }//c\nELSE { ECHO bye }",
8760            "IF true { ECHO hi } /*c*/ ELSE { ECHO bye }",
8761            "IF true { ECHO hi } /*c1*/ /*c2*/\nELSE { ECHO bye }",
8762            "IF true { /*c*/ ECHO hi }",
8763            "IF true { [os:linux] ECHO hi }",
8764            "TIMEOUT 10s { IF true { ECHO hi } }",
8765            "TIMEOUT 10s { IF true { ECHO hi }\nELSE { ECHO bye } }",
8766            "FOR $x: INT IN [1] { ECHO hi }",
8767            "FOR $k: STRING, $v: INT IN $m { ECHO hi }",
8768            "FOR $k: INT IN [1] { ECHO hi }",
8769            "FOR $x: INT IN [1]{ ECHO hi }",
8770            "FOR $x: MAP<name: STRING> IN [1] { ECHO hi }",
8771            "FOR $x: INT IN [1] { ECHO hi } ECHO bye",
8772            "WHILE true { ECHO hi }",
8773            "WHILE $x { ECHO hi }",
8774            "WHILE true{ ECHO hi }",
8775            "TIMEOUT 10s WHILE true { ECHO hi }",
8776            "ASYNC WHILE true { ECHO hi }",
8777            "FUNC FOO(): INT { RETURN 1 }",
8778            "FUNC FOO(): INT { RETURN 1 }",
8779            "FUNC FOO($x: INT): INT { RETURN $x }",
8780            "FUNC FOO($x: INT, $y: STRING): INT { RETURN $x }",
8781            "FUNC FOO(): INT { FUNC FOO(): INT { RETURN 1 } }",
8782            "FUNC FOO(): INT { RETURN 1 }\nFUNC BAR(): VOID { FOO() }\nBAR()",
8783            "TYPE PERSON = MAP<name: STRING>",
8784            "TYPE A=B",
8785            "TYPE A = B | C",
8786            "TYPE A = B\nTYPE A = C",
8787            "INHERIT_ENV [A]\nECHO hi",
8788            "[os:linux] INHERIT_ENV [M]",
8789            "INHERIT_ENV [A]\nINHERIT_ENV [B]\nECHO hi",
8790            "ISOLATED INHERIT_ENV [M]",
8791            "ISOLATED { INHERIT_ENV [M] }",
8792            "ISOLATED INHERIT_ENV [A, B]",
8793            "ISOLATED INHERIT_ENV [A-B]",
8794            "REMOTE prod { ECHO hi }",
8795            "REMOTE prod [$v] { ECHO hi }",
8796            "REMOTE prod [$v, env:E] { ECHO hi }",
8797            "REMOTE prod [] { ECHO hi }",
8798            "REMOTE prod[$v] { ECHO hi }",
8799            "REMOTE prod [$v]{ ECHO hi }",
8800            "REMOTE prod{ ECHO hi }",
8801            "REMOTE  prod  { ECHO hi }",
8802            "REMOTE prod [$v, $v] { ECHO hi }",
8803            "REMOTE prod { ECHO hi } ECHO bye",
8804            "TIMEOUT 10s REMOTE prod { ECHO hi }",
8805            "ASYNC REMOTE prod [$v] { ECHO hi }",
8806            "[os:linux] { ECHO hi }",
8807            "[os:linux]\n{ ECHO hi }",
8808            "[os:linux] { [os:macos] ECHO hi }",
8809            "[os:linux] { [os:macos] ECHO hi\nECHO bye }",
8810            "[os:linux] { [os:macos] { ECHO hi } }",
8811            "TIMEOUT 10s { [os:linux] { [os:macos] ECHO hi } }",
8812            "TIMEOUT 10s { [os:linux] [os:windows] { ECHO hi } }",
8813            "TIMEOUT 10s { [os:linux] { ECHO hi } ECHO bye }",
8814            "LET $x: INT = 1 ECHO bye",
8815            KEYWORD_BREAK,
8816            KEYWORD_CONTINUE,
8817            "BREAK ECHO hi",
8818            "FOR $x: INT IN [1] { BREAK }",
8819            "LET $b: STRING = { RETURN \"hi\" }",
8820            "ECHO { RETURN \"hi\" }",
8821            "RUN [{ RETURN \"hi\" }]",
8822            "[not(env:FOO)] WRITE x",
8823            "[\nnot(env:FOO)\n] WRITE x",
8824            "WRITE env.txt \"{{ env:GREETING }}\"",
8825            "CANCEL $t LET $x: INT = 1",
8826            "RUN [\"a\"] ECHO bye",
8827        ] {
8828            assert_parity(text);
8829        }
8830    }
8831
8832    #[test]
8833    fn multi_line_generics_match_single_line_shape() {
8834        // Multi-line `<...>` shapes parse, and canonicalize exactly
8835        // like their single-line spelling.
8836        for (single, multi) in [
8837            (
8838                "TYPE R = MAP<name: STRING, value: INT>",
8839                "TYPE R = MAP<name: STRING,\nvalue: INT>",
8840            ),
8841            (
8842                "TYPE R = MAP<name: STRING, value: LIST<INT>>",
8843                "TYPE R = MAP<name: STRING,\nvalue: LIST<INT>>",
8844            ),
8845            (
8846                "TYPE R = MAP<name: STRING, value: INT>",
8847                "TYPE R = MAP<\nname: STRING,\nvalue: INT\n>",
8848            ),
8849            (
8850                "LET $m: MAP<name: STRING, value: INT> = {}",
8851                "LET $m: MAP<name: STRING,\nvalue: INT> = {}",
8852            ),
8853            (
8854                "FOR $x: LIST<INT> IN [1] { ECHO hi }",
8855                "FOR $x: LIST<\nINT> IN [1] { ECHO hi }",
8856            ),
8857            ("TYPE R = MAP<x: A | B>", "TYPE R = MAP<x: A |\nB>"),
8858        ] {
8859            assert_parity(multi);
8860            let want = crate::parse_script(single, lower)
8861                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
8862            let got = crate::parse_script(multi, lower)
8863                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
8864            assert_eq!(
8865                got, want,
8866                "multi-line must canonicalize like one line: {multi:?}"
8867            );
8868        }
8869    }
8870
8871    #[test]
8872    fn multi_line_run_exec_matches_single_line_shape() {
8873        // `RUN [...]` rides the shared bracket core, so a wrapped exec
8874        // list parses exactly like its single-line spelling (and agrees
8875        // across lexer frontends).
8876        for (single, multi) in [
8877            ("RUN [\"echo\", \"hi\"]", "RUN [\"echo\",\n\"hi\"]"),
8878            ("RUN [\"echo\", \"hi\"]", "RUN [\n\"echo\",\n\"hi\"\n]"),
8879            (
8880                "LET $o: STRING = RUN [\"echo\", \"hi\"]",
8881                "LET $o: STRING = RUN [\"echo\",\n\"hi\"]",
8882            ),
8883        ] {
8884            assert_parity(multi);
8885            let want = crate::parse_script(single, lower)
8886                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
8887            let got = crate::parse_script(multi, lower)
8888                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
8889            assert_eq!(
8890                got, want,
8891                "multi-line must canonicalize like one line: {multi:?}"
8892            );
8893        }
8894    }
8895
8896    #[test]
8897    fn untyped_let_fails_in_every_rhs_shape() {
8898        // The everything-typed rule: a missing `:` is a hard error
8899        // carrying the explicit-types message, regardless of what
8900        // follows the `=`. Every binding shape is covered, so no
8901        // untyped position can slip back in unnoticed.
8902        for text in [
8903            "LET $x = 1\n",
8904            "LET $x = \"hi\"\n",
8905            "LET $x = $y\n",
8906            "LET $x = [\"a\", \"b\"]\n",
8907            "LET $x = [\"a\",\n\"b\"]\n",
8908            "LET $x = ECHO hi\n",
8909            "LET $x = AWAIT $t\n",
8910            "LET $x = ASYNC ECHO hi\n",
8911            "LET $x = {\nRETURN 1\n}\n",
8912            "LET $x = WITH_IO [stdin=$p] ASYNC ECHO hi\n",
8913        ] {
8914            let err = crate::parse_script(text, lower).expect_err("untyped LET must fail");
8915            assert!(
8916                err.to_string().contains("LET requires explicit types"),
8917                "wrong error for {text:?}: {err}"
8918            );
8919        }
8920        // Typed spellings of the same shapes keep parsing through
8921        // every lexer frontend.
8922        for text in [
8923            "LET $x: INT = 1\n",
8924            "LET $x: STRING = \"hi\"\n",
8925            "LET $x: LIST<STRING> = [\"a\", \"b\"]\n",
8926            "LET $x: LIST<STRING> = [\"a\",\n\"b\"]\n",
8927            "LET $x: STRING = ECHO hi\n",
8928            "LET $x: STRING = AWAIT $t\n",
8929            "LET $x: HANDLE<VOID> = ASYNC ECHO hi\n",
8930            "LET $x: INT = {\nRETURN 1\n}\n",
8931        ] {
8932            assert_parity(text);
8933        }
8934    }
8935
8936    #[test]
8937    fn missing_comma_points_at_the_item() {
8938        // A forgotten comma between items names the missing
8939        // comma and points at the item's line, not the statement
8940        // head. Lists and call arguments share the rule.
8941        let text = indoc! {r#"
8942            LET $x: LIST<STRING> = [
8943            "a"
8944            "b",
8945            "c"
8946            ]
8947        "#};
8948        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
8949        assert!(
8950            err.to_string().contains("missing comma between list items"),
8951            "wrong error: {err}"
8952        );
8953        assert_eq!(err.line(), 3, "caret names the item line: {err}");
8954        // Same shape on one line.
8955        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" \"b\"]\n", lower)
8956            .expect_err("missing comma must fail");
8957        assert!(
8958            err.to_string().contains("missing comma between list items"),
8959            "wrong error: {err}"
8960        );
8961        assert_eq!(err.line(), 1, "single-line points at line 1: {err}");
8962        // Call arguments share the rule.
8963        let err = crate::parse_script("LET $x: STRING = FOO(\"a\" \"b\")\n", lower)
8964            .expect_err("missing comma must fail");
8965        assert!(
8966            err.to_string()
8967                .contains("missing comma between call arguments"),
8968            "wrong error: {err}"
8969        );
8970        // Genuine trailing garbage keeps the old message but still
8971        // points at the garbage instead of the statement head.
8972        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" : \"b\"]\n", lower)
8973            .expect_err("garbage must fail");
8974        assert!(
8975            err.to_string().contains("unexpected text in list"),
8976            "wrong error: {err}"
8977        );
8978        // Maps share the rule: a forgotten comma between entries
8979        // names it at the entry's line instead of misreporting the
8980        // key as an unknown command.
8981        let text = indoc! {r#"
8982            LET $m: MAP<name: STRING> = {
8983            name: "a"
8984            value: "b"
8985            }
8986        "#};
8987        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
8988        assert!(
8989            err.to_string()
8990                .contains("missing comma between map entries"),
8991            "wrong error: {err}"
8992        );
8993        assert_eq!(err.line(), 3, "caret names the entry line: {err}");
8994        let err = crate::parse_script(
8995            "LET $m: MAP<name: STRING> = {name: \"a\" value: \"b\"}\n",
8996            lower,
8997        )
8998        .expect_err("missing comma must fail");
8999        assert!(
9000            err.to_string()
9001                .contains("missing comma between map entries"),
9002            "wrong error: {err}"
9003        );
9004    }
9005
9006    #[test]
9007    fn spaced_comparisons_still_end_the_statement() {
9008        // A spaced `<` is a comparison, never a generic open: the
9009        // newline still ends the statement.
9010        let steps = crate::parse_script("LET $b: BOOL = $a < $b\nECHO hi", lower)
9011            .expect("comparison plus follower must parse");
9012        assert_eq!(steps.len(), 2, "newline ends the comparison statement");
9013    }
9014
9015    #[test]
9016    fn token_and_string_paths_agree_on_flat_commands() {
9017        for text in [
9018            "ECHO hi",
9019            "ECHO hi\nWRITE x out",
9020            "WRITE x",
9021            "ECHO \"quoted\" unquoted",
9022            "ENV COVERAGE=covered",
9023            "ECHO a; ECHO b",
9024            "// comment\nECHO hi",
9025            "ECHO 1.0.0 --flag a/b",
9026            "ECHO $x",
9027            "\n\nECHO hi\n\n",
9028        ] {
9029            assert_parity(text);
9030        }
9031    }
9032
9033    #[cfg(feature = "proc-macro-api")]
9034    #[test]
9035    fn backslash_outside_strings_is_string_only() {
9036        // `rustc` rejects a bare `\`, so unquoted backslash escapes
9037        // cannot cross `TokenStream` (same exclusion class as raw-`"`
9038        // blocks): the string lexer keeps them, the token path fails to
9039        // tokenize before v2 is ever reached.
9040        let toks = crate::tok::lex_str("ECHO a\\nb").expect("string lex keeps escapes");
9041        let old = crate::parse_script("ECHO a\\nb", lower).expect("string path parses it");
9042        assert_eq!(
9043            parse_tokens(&toks, lower).expect("token path parses it"),
9044            old
9045        );
9046        assert!("ECHO a\\nb".parse::<proc_macro2::TokenStream>().is_err());
9047    }
9048
9049    #[test]
9050    fn escaped_backslash_pair_is_atomic() {
9051        // `"a\\"` parses (one escape pair plus the closer): the pair
9052        // scans atomically, like the block-string arm and `lex_word`.
9053        // The value stays raw (`\\` verbatim for runtime
9054        // `expand_string`), so this pins parsing, not unescaping.
9055        assert_parity("ECHO \"a\\\\\"");
9056        let steps = crate::parse_script("ECHO \"a\\\\\"", lower).expect("escaped pair must parse");
9057        match &steps[..] {
9058            [s] => assert!(
9059                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a\\\\"),
9060                "escaped pair must survive raw: {s:?}"
9061            ),
9062            _ => panic!("one step: {steps:?}"),
9063        }
9064    }
9065
9066    #[test]
9067    fn joint_double_slash_stays_literal() {
9068        // `rustc` strips `//` before the macro ever runs, so these are
9069        // string-path-only by construction: joint `a//b` is one literal
9070        // arg, and `[a //c]` closes its group (the in-group `//` copy
9071        // stops at the closer).
9072        for text in ["ECHO a//b", "ECHO [a //c]"] {
9073            assert_parity_string_only(text);
9074        }
9075        let steps = crate::parse_script("ECHO a//b", lower).expect("joint slashes parse");
9076        match &steps[..] {
9077            [s] => assert!(
9078                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a//b"),
9079                "joint `//` must glue literally: {s:?}"
9080            ),
9081            _ => panic!("one step: {steps:?}"),
9082        }
9083        let steps = crate::parse_script("ECHO [a //c]", lower).expect("group must close");
9084        assert_eq!(steps.len(), 1, "one step: {steps:?}");
9085        // Full content survives literally: the mock joins WRITE args
9086        // with spaces, so the round trip is byte-exact here.
9087        let steps = crate::parse_script("WRITE f [a //c]", lower).expect("group must close");
9088        match &steps[..] {
9089            [s] => assert!(
9090                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a //c]"),
9091                "group content must survive literally: {s:?}"
9092            ),
9093            _ => panic!("one step: {steps:?}"),
9094        }
9095    }
9096
9097    #[test]
9098    fn block_comment_in_group_closes_like_line_comment() {
9099        // `[a /* c]` reads literally on the old backend (first arg
9100        // `[a`, joined `[a /* c]`), so the in-group `/*` copy breaks
9101        // at the depth-zero closer exactly like `//` does. The bare
9102        // `/*` reads literally too.
9103        for text in ["ECHO [a /* c]", "WRITE f [a /* c]", "ECHO /*"] {
9104            assert_parity_string_only(text);
9105        }
9106        let steps = crate::parse_script("ECHO /*", lower).expect("bare block open parses");
9107        match &steps[..] {
9108            [s] => assert!(
9109                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "/*"),
9110                "bare `/*` must stay literal: {s:?}"
9111            ),
9112            _ => panic!("one step: {steps:?}"),
9113        }
9114        let steps = crate::parse_script("WRITE f [a /* c]", lower).expect("group must close");
9115        match &steps[..] {
9116            [s] => assert!(
9117                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c]"),
9118                "group content must survive literally: {s:?}"
9119            ),
9120            _ => panic!("one step: {steps:?}"),
9121        }
9122        // Terminated spans keep working through the same path: the
9123        // run carries its closer, so math still gets first refusal.
9124        let steps = crate::parse_script("WRITE f [a /* c */ d]", lower).expect("group must close");
9125        match &steps[..] {
9126            [s] => assert!(
9127                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c */ d]"),
9128                "terminated group content must survive: {s:?}"
9129            ),
9130            _ => panic!("one step: {steps:?}"),
9131        }
9132    }
9133
9134    #[test]
9135    fn single_quoted_multiline_keeps_line_tracking() {
9136        // The `'` arm counts embedded newlines like the `"` arm, so the
9137        // statement after a multiline single-quoted string keeps its
9138        // own lines (func-docs stamping keys off them).
9139        let text = "ECHO 'a\nb'\nECHO c";
9140        assert_parity_string_only(text);
9141        let steps = crate::parse_script(text, lower).expect("must parse");
9142        assert_eq!(steps.len(), 2, "two steps: {steps:?}");
9143        assert_eq!((steps[0].line, steps[0].col), (1, 1));
9144        assert_eq!((steps[1].line, steps[1].col), (3, 1), "{steps:?}");
9145    }
9146
9147    #[test]
9148    fn token_and_string_paths_agree_on_guarded_commands() {
9149        for text in [
9150            "[env:X] ECHO hi",
9151            "[env:A] [os:linux] ECHO hi",
9152            "[os:macos] WRITE x",
9153            "[not(os:windows)] WRITE f x",
9154            "[any(os:macos, os:linux)] ECHO hi",
9155            "[all(env:A, os:linux)] ECHO hi",
9156            "[eq(env:K, v)] ECHO hi",
9157            "[ne(env:K, v)] ECHO hi",
9158            "[bool:true] ECHO hi",
9159            "[arch:arm] ECHO hi",
9160            "[family:unix] ECHO hi",
9161            "[(os:linux)] ECHO hi",
9162            "[env:A, os:linux] ECHO hi",
9163            "WRITE x\n[env:X] ECHO hi",
9164            "[env:K] ECHO $x",
9165            "[__OXDOCK_INJECT_1__] ECHO hi",
9166            "[eq(env:K, \"a b\")] ECHO hi",
9167            "[\nenv:X\n] ECHO hi",
9168            // In-body brackets are raw text split on whitespace (probed
9169            // parity: `[a, b]` is args `"[a,"` + `"b]"`, quotes kept).
9170            "ECHO [a, b] hi",
9171            "WRITE f [env:X]",
9172            "ECHO [env:X] hi",
9173            "WRITE f [\"a b\"]",
9174            "ECHO foo[bar]baz",
9175            "ECHO [a ]",
9176            "ECHO [ a]",
9177            "WRITE out x [env:X]",
9178        ] {
9179            assert_parity(text);
9180        }
9181        // `rustc` lexes `'a` as a lifetime start and rejects the
9182        // space: string-path-only by construction.
9183        assert_parity_string_only("ECHO ['a b']");
9184    }
9185
9186    #[test]
9187    fn token_and_string_paths_agree_on_calls_and_exact_args() {
9188        use crate::ast::{ModuleFuncs, ModuleTable};
9189        use std::collections::{HashMap, HashSet};
9190        let std_table = || ModuleTable {
9191            modules: HashMap::from([(
9192                crate::constants::STD_MODULE_NAME.to_string(),
9193                Some(ModuleFuncs {
9194                    func_names: HashSet::from(["LEN".to_string()]),
9195                }),
9196            )]),
9197        };
9198        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9199            test_lower_mock::lower(name, args)
9200        }
9201        // One table for both pathways: STD exports LEN.
9202        // Rebuilt per case (parse-time only, keeps borrows local).
9203        for text in [
9204            "LET $n: INT = STD::LEN(\"hi\")",
9205            "STD::LEN(\"hi\")",
9206            "LET $n: INT = STD::LEN(\"a\", \"b\")",
9207            "LET $s: STRING = INSPECT($x)",
9208            "INSPECT($x)",
9209            "LET $x: STRING = ECHO hi",
9210            "LET $t: STRING = WRITE x",
9211            "LET $o: STRING = RUN echo hi",
9212            "RUN [\"echo\", \"hi\"]",
9213            "RUN echo [a]",
9214            "LET $r: STRING = RUN [\"echo\"]",
9215            "ECHO K=v",
9216            "ECHO K = v",
9217            "ECHO K=a b",
9218            "ECHO K=a, b",
9219            "ECHO K=\"a b\"",
9220            "ECHO K=$x",
9221            "ECHO K=",
9222            "ECHO a = = b",
9223            "WRITE f K=v",
9224            "ECHO $a + $b",
9225            "ECHO $a==$b",
9226            "ECHO a $x b",
9227            "ECHO 5 + 3",
9228            "WRITE f ( \"hi\" )",
9229            "ECHO FOO(\"a\")",
9230            "ECHO [a, b] hi",
9231            "ECHO {{x}}",
9232            "ECHO {{ $x }}",
9233            "ECHO $x=K",
9234            "ECHO a$x",
9235            "ECHO a$(x)",
9236            "ECHO K=$x tail",
9237            "EXPAND K1=$x K2=$y",
9238            "EXPAND a",
9239            "ENV K = v",
9240            "COPY a b",
9241            "ECHO foo[bar]baz",
9242            "LET $x: STRING = FOOBAR",
9243            "STD::LEN(\"hi\") ECHO bye",
9244            "LET $n: INT = STD::LEN(\"a\") ECHO bye",
9245            "TIMEOUT 10s STD::LEN(\"hi\")",
9246            "TIMEOUT 10s STD::LEN(\"hi\") ECHO bye",
9247            "LET $n: INT = STD::LEN(\"a\")STD::LEN(\"b\")",
9248        ] {
9249            let table = std_table();
9250            let old =
9251                crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
9252                    .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9253            let reserved = HashSet::new();
9254            let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
9255            let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9256            let new = parse_tokens_with_ctx(&toks, &ctx)
9257                .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9258            assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9259            #[cfg(feature = "proc-macro-api")]
9260            {
9261                let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
9262                let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
9263                let new = parse_tokens_with_ctx(&toks, &ctx)
9264                    .unwrap_or_else(|e| panic!("token path must parse token {text:?}: {e}"));
9265                assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
9266            }
9267        }
9268    }
9269
9270    #[test]
9271    fn placeholder_bare_calls_resolve_like_statements() {
9272        // `{{ NAME(args) }}` obeys exactly the statement-position
9273        // scope rule: `IMPORT [MOD]` brings the names into scope,
9274        // unimported names fail naming the fix, ambiguity fails
9275        // closed. The rewrite below is byte-identical past the
9276        // qualified head, so expansion sees the same args.
9277        use crate::ast::{ModuleFuncs, ModuleTable};
9278        use std::collections::{HashMap, HashSet};
9279        let table = || ModuleTable {
9280            modules: HashMap::from([
9281                (
9282                    crate::constants::STD_MODULE_NAME.to_string(),
9283                    Some(ModuleFuncs {
9284                        func_names: HashSet::from(["LEN".to_string()]),
9285                    }),
9286                ),
9287                (
9288                    "OTHER".to_string(),
9289                    Some(ModuleFuncs {
9290                        func_names: HashSet::from(["LEN".to_string()]),
9291                    }),
9292                ),
9293            ]),
9294        };
9295        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9296            test_lower_mock::lower(name, args)
9297        }
9298        fn echo_text(steps: &[crate::Step]) -> String {
9299            match steps {
9300                [s] => match &s.kind {
9301                    StepKind::Echo(Arg::String(text, _)) => text.clone(),
9302                    other => panic!("expected ECHO string, got {other:?}"),
9303                },
9304                _ => panic!("expected one step, got {steps:?}"),
9305            }
9306        }
9307        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
9308            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
9309        }
9310        // Imported bare names qualify; everything else rides through
9311        // byte-identical for the runtime to handle as before.
9312        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }}\"\n";
9313        let out = echo_text(&parse(text, table()).expect("imported bare call parses"));
9314        assert_eq!(out, "n: {{ STD::LEN($x) }}", "bare call qualifies: {out}");
9315        let text = "IMPORT [STD]\nECHO \"n: {{ STD::LEN($x) }}\"\n";
9316        let out = echo_text(&parse(text, table()).expect("qualified parses"));
9317        assert_eq!(
9318            out, "n: {{ STD::LEN($x) }}",
9319            "qualified keys stay untouched: {out}"
9320        );
9321        let text = "IMPORT [STD]\nECHO \"hi {{ $x }} and {{ bare }} and {{ env:K }}\"\n";
9322        let out = echo_text(&parse(text, table()).expect("non-calls parse"));
9323        assert_eq!(
9324            out, "hi {{ $x }} and {{ bare }} and {{ env:K }}",
9325            "non-call keys stay untouched: {out}"
9326        );
9327        let text = "IMPORT [STD]\nECHO \"lit \\{{ LEN($x) }}\"\n";
9328        let out = echo_text(&parse(text, table()).expect("escaped parses"));
9329        assert_eq!(
9330            out, "lit \\{{ LEN($x) }}",
9331            "escaped openers stay literal: {out}"
9332        );
9333        // Nested bodies resolve against the enclosing imports, exactly
9334        // like statement-position calls in the same body.
9335        let text = indoc! {r#"
9336            IMPORT [STD]
9337            FUNC F(): VOID {
9338            ECHO "n: {{ LEN($x) }}"
9339            }
9340        "#};
9341        let steps = parse(text, table()).expect("nested bare call parses");
9342        let body = steps.iter().find_map(|s| match &s.kind {
9343            StepKind::FuncDef { body, .. } => Some(body),
9344            _ => None,
9345        });
9346        match body.map(Vec::as_slice) {
9347            Some([inner]) => match &inner.kind {
9348                StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
9349                    echoed, "n: {{ STD::LEN($x) }}",
9350                    "nested body qualifies: {echoed}"
9351                ),
9352                other => panic!("expected nested ECHO, got {other:?}"),
9353            },
9354            _ => panic!("expected one FUNC with one body step, got {steps:?}"),
9355        };
9356        // Neighboring placeholders keep their exact bytes: only the
9357        // head span changes, so payloads never lose formatting.
9358        let text = "IMPORT [STD]\nECHO \"Call {{ LEN($x) }} and value {{ $y }}\"\n";
9359        let out = echo_text(&parse(text, table()).expect("mixed template parses"));
9360        assert_eq!(
9361            out, "Call {{ STD::LEN($x) }} and value {{ $y }}",
9362            "only the head span changes: {out}"
9363        );
9364        // Unimported bare names fail exactly like statement position:
9365        // qualify it or add the import.
9366        let err = parse("ECHO \"n: {{ LEN($x) }}\"\n", table()).expect_err("must fail");
9367        assert!(
9368            err.to_string().contains("unknown function `LEN`")
9369                && err.to_string().contains("or add `IMPORT"),
9370            "names the fix: {err}"
9371        );
9372        // Two exporters fail closed instead of picking one.
9373        let err = parse(
9374            "IMPORT [STD]\nIMPORT [OTHER]\nECHO \"n: {{ LEN($x) }}\"\n",
9375            table(),
9376        )
9377        .expect_err("must fail");
9378        assert!(
9379            err.to_string().contains("ambiguous function `LEN`"),
9380            "ambiguity fails closed: {err}"
9381        );
9382        // Both lexing pathways agree on rewritten templates.
9383        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }} and {{ $y }}\"\n";
9384        let table = table();
9385        let old = crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
9386            .expect("string path parses");
9387        let reserved = HashSet::new();
9388        let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
9389        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9390        let new = parse_tokens_with_ctx(&toks, &ctx).expect("token path parses");
9391        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9392    }
9393
9394    #[test]
9395    fn placeholder_bare_calls_qualify_in_expr_positions() {
9396        // Regression: `walk_raw_strings_mut` skips `Assign`/`Set`/
9397        // `Call`/`Return`/`If`/`For`/`While`, so `LET`/`RETURN`/call
9398        // args/list/map literals never qualified and failed at
9399        // runtime as undefined variables. Both carriers now qualify.
9400        use crate::ast::{ModuleFuncs, ModuleTable};
9401        use std::collections::{HashMap, HashSet};
9402        let table = || ModuleTable {
9403            modules: HashMap::from([(
9404                crate::constants::STD_MODULE_NAME.to_string(),
9405                Some(ModuleFuncs {
9406                    func_names: HashSet::from(["LEN".to_string()]),
9407                }),
9408            )]),
9409        };
9410        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9411            test_lower_mock::lower(name, args)
9412        }
9413        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
9414            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
9415        }
9416        // LET string literal qualifies.
9417        let steps = parse(
9418            "IMPORT [STD]\nLET $s: STRING = \"n: {{ LEN($x) }}\"\n",
9419            table(),
9420        )
9421        .expect("LET template parses");
9422        match &steps[0].kind {
9423            StepKind::Assign { expr, .. } => match expr {
9424                Expr::Literal(value) => assert_eq!(
9425                    value.as_str().unwrap_or_default(),
9426                    "n: {{ STD::LEN($x) }}",
9427                    "LET qualifies"
9428                ),
9429                other => panic!("expected literal, got {other:?}"),
9430            },
9431            other => panic!("expected Assign, got {other:?}"),
9432        }
9433        // RETURN string literal qualifies.
9434        let steps = parse(
9435            "IMPORT [STD]\nFUNC F(): STRING {\nRETURN \"n: {{ LEN($x) }}\"\n}\n",
9436            table(),
9437        )
9438        .expect("RETURN template parses");
9439        let body = steps.iter().find_map(|s| match &s.kind {
9440            StepKind::FuncDef { body, .. } => Some(body),
9441            _ => None,
9442        });
9443        match body.map(Vec::as_slice) {
9444            Some([inner]) => match &inner.kind {
9445                StepKind::Return { expr, .. } => match &**expr {
9446                    Expr::Literal(value) => assert_eq!(
9447                        value.as_str().unwrap_or_default(),
9448                        "n: {{ STD::LEN($x) }}",
9449                        "RETURN qualifies"
9450                    ),
9451                    other => panic!("expected literal, got {other:?}"),
9452                },
9453                other => panic!("expected RETURN, got {other:?}"),
9454            },
9455            _ => panic!("expected one FUNC, got {steps:?}"),
9456        }
9457        // Call args, list and map literals qualify.
9458        let steps = parse(
9459            "IMPORT [STD]\nLET $y: INT = LEN(\"b: {{ LEN($x) }}\")\n",
9460            table(),
9461        )
9462        .expect("call-arg template parses");
9463        let rendered = format!("{:?}", steps[0].kind);
9464        assert!(
9465            rendered.contains("STD::LEN"),
9466            "call arg qualifies: {rendered}"
9467        );
9468        let steps = parse(
9469            "IMPORT [STD]\nLET $l: LIST<STRING> = [\"{{ LEN($x) }}\"]\n",
9470            table(),
9471        )
9472        .expect("list template parses");
9473        let rendered = format!("{:?}", steps[0].kind);
9474        assert!(rendered.contains("STD::LEN"), "list qualifies: {rendered}");
9475        // Compound placeholders are not single calls: they pass
9476        // through untouched (no partial rewrite) for the runtime to
9477        // fail closed on the whole key.
9478        let text = "IMPORT [STD]\nECHO \"v: {{ LEN($a) + LEN($b) }}\"\n";
9479        let steps = parse(text, table()).expect("compound parses");
9480        match &steps[0].kind {
9481            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
9482                echoed, "v: {{ LEN($a) + LEN($b) }}",
9483                "compound untouched: {echoed}"
9484            ),
9485            other => panic!("expected ECHO string, got {other:?}"),
9486        }
9487        // Quoted parens inside args do not end the call early.
9488        let text = "IMPORT [STD]\nECHO 'v: {{ LEN(\"a(b\") }}'\n";
9489        let steps = parse(text, table()).expect("quoted paren parses");
9490        match &steps[0].kind {
9491            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
9492                echoed, "v: {{ STD::LEN(\"a(b\") }}",
9493                "quoted paren qualifies: {echoed}"
9494            ),
9495            other => panic!("expected ECHO string, got {other:?}"),
9496        }
9497        // Single-quoted args balance the same way.
9498        let text = "IMPORT [STD]\nECHO \"v: {{ LEN('a(b') }}\"\n";
9499        let steps = parse(text, table()).expect("single-quoted paren parses");
9500        match &steps[0].kind {
9501            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
9502                echoed, "v: {{ STD::LEN('a(b') }}",
9503                "single-quoted paren qualifies: {echoed}"
9504            ),
9505            other => panic!("expected ECHO string, got {other:?}"),
9506        }
9507        // `WithIo` boxes its inner command directly (no recursive
9508        // statement pass), so the qualifier must descend into it.
9509        // `LET $p: PIPE` plus bindings keep the shape realistic.
9510        let text = "IMPORT [STD]\nLET $p: PIPE\nWITH_IO [stdout=$p] ECHO 'v: {{ LEN($x) }}'\n";
9511        let steps = parse(text, table()).expect("with-io template parses");
9512        match &steps[1].kind {
9513            StepKind::WithIo { cmd, .. } => {
9514                let rendered = format!("{cmd:?}");
9515                assert!(
9516                    rendered.contains("STD::LEN"),
9517                    "with-io inner qualifies: {rendered}"
9518                );
9519            }
9520            other => panic!("expected WithIo, got {other:?}"),
9521        }
9522        // Single-command wrappers build synthetic body steps without a
9523        // recursive pass: `TIMEOUT 5s <cmd>` and `ASYNC <cmd>` share
9524        // the outer frame, so the qualifier must descend into bodies.
9525        let text = "IMPORT [STD]\nTIMEOUT 5s ECHO 't: {{ LEN($x) }}'\n";
9526        let steps = parse(text, table()).expect("timeout template parses");
9527        let rendered = format!("{:?}", steps[0].kind);
9528        assert!(
9529            rendered.contains("STD::LEN"),
9530            "timeout single qualifies: {rendered}"
9531        );
9532        let text = "IMPORT [STD]\nLET $h: HANDLE<ANY> = ASYNC ECHO 'a: {{ LEN($x) }}'\n";
9533        let steps = parse(text, table()).expect("async template parses");
9534        let rendered = format!("{:?}", steps[0].kind);
9535        assert!(
9536            rendered.contains("STD::LEN"),
9537            "async single qualifies: {rendered}"
9538        );
9539        // Brace bodies keep their own frames: the outer qualifier must
9540        // never re-walk them. A valid nested body qualifies via its own
9541        // recursive pass, and an unknown callee inside one fails with
9542        // the inner position, never re-resolved against the outer frame.
9543        let text = "IMPORT [STD]\nIF true {\nECHO 'v: {{ LEN($x) }}'\n}\n";
9544        let steps = parse(text, table()).expect("nested body qualifies");
9545        let rendered = format!("{:?}", steps[0].kind);
9546        assert!(
9547            rendered.contains("STD::LEN"),
9548            "nested IF body qualifies via its own frame: {rendered}"
9549        );
9550        let err = parse(
9551            "IMPORT [STD]\nIF true {\nECHO 'v: {{ NOPE($x) }}'\n}\n",
9552            table(),
9553        )
9554        .expect_err("nested unknown must fail");
9555        assert!(
9556            err.to_string().contains("unknown function `NOPE`"),
9557            "nested unknown names culprit: {err}"
9558        );
9559    }
9560
9561    #[test]
9562    fn block_conditions_name_unknown_callees() {
9563        // Regression: an unknown callee in a block header condition
9564        // used to miss to the generic `IF needs a condition and a
9565        // block` hint. Classified resolution failures now propagate
9566        // and name the culprit on all four speculative headers.
9567        use crate::ast::{ModuleFuncs, ModuleTable};
9568        use std::collections::{HashMap, HashSet};
9569        let table = || ModuleTable {
9570            modules: HashMap::from([(
9571                crate::constants::STD_MODULE_NAME.to_string(),
9572                Some(ModuleFuncs {
9573                    func_names: HashSet::from(["LEN".to_string()]),
9574                }),
9575            )]),
9576        };
9577        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9578            test_lower_mock::lower(name, args)
9579        }
9580        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
9581            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
9582        }
9583        for text in [
9584            "IMPORT [STD]\nIF NOPE($x) == 0 {\nECHO hi\n}\n",
9585            "IMPORT [STD]\nIF LEN($x) == 0 {\nECHO hi\n} ELSE IF NOPE($x) == 1 {\nECHO yo\n}\n",
9586            "IMPORT [STD]\nWHILE NOPE($x) > 0 {\nECHO hi\n}\n",
9587            "IMPORT [STD]\nFOR $i: STRING IN NOPE($x) {\nECHO $i\n}\n",
9588        ] {
9589            let err = parse(text, table()).expect_err("unknown callee must fail");
9590            assert!(
9591                err.to_string().contains("unknown function `NOPE`"),
9592                "names the culprit: {err}"
9593            );
9594        }
9595        // Unclassified shape misses still miss (the exact generic
9596        // hint comes from the real dispatcher, which the mock lacks).
9597        parse("IF {\nECHO hi\n}\n", table()).expect_err("empty condition must still fail");
9598    }
9599
9600    #[test]
9601    fn token_and_string_paths_agree_on_let_set_return() {
9602        for text in [
9603            "LET $x: INT = 1",
9604            "LET $s: STRING = \"hi\"",
9605            "LET $b: BOOL = true",
9606            "LET $f: FLOAT = 1.5",
9607            "LET $p: PIPE",
9608            "LET $l: LIST<STRING> = [\"a\", \"b\"]",
9609            "LET $e: LIST<STRING> = []",
9610            "LET $m: MAP = {k: 1}",
9611            "LET $m2: MAP = {\"a b\": 2, k: [1, 2]}",
9612            "LET $n: INT = $a + $b",
9613            "LET $c: BOOL = ($a == 3) && ($b == 4)",
9614            "LET $g: BOOL = !$ok",
9615            "LET $nn: BOOL = true && false",
9616            "LET $e2: STRING = env:HOME",
9617            "LET $k: STRING = $a.b.c",
9618            "LET $u: INT = -5",
9619            "LET $v: INT = 9223372036854775807",
9620            "LET $min: INT = -9223372036854775808",
9621            "LET $w: INT = 1_000",
9622            "LET $z: STRING = a/b",
9623            "LET $d: STRING = -f",
9624            "LET $t: STRING = 30s",
9625            "LET $q: STRING = \"\"\"hi\"\"\"",
9626            "LET $f2: FLOAT = 2 * -3",
9627            "LET $o: BOOL = 2 + 3 > 4",
9628            "LET $l2: LIST< MAP > = []",
9629            "LET $a1: INT = 1 + 2",
9630            "LET $s1: INT = 10 - 4 - 3",
9631            "LET $m1: INT = 2 * 3 + 4",
9632            "LET $x1: BOOL = 1 < 2 == true",
9633            "LET $or: BOOL = $a || $b",
9634            "LET $dbl: BOOL = !!$x",
9635            "LET $ver: STRING = 1.0.0",
9636            "LET $dash: STRING = a-b",
9637            "LET $div: INT = 4 / 2",
9638            "LET $bad: INT = 1__0 + 0",
9639            "LET $strdiv: STRING = 4/2",
9640            "LET $sp: INT = $a - $b",
9641            "$x = 1",
9642            "$x = $a + 1",
9643            "RETURN 1",
9644            KEYWORD_RETURN,
9645            "RETURN $x",
9646            "[env:X] LET $x: INT = 1",
9647            "[os:linux] $x = 2",
9648        ] {
9649            assert_parity(text);
9650        }
9651    }
9652
9653    #[test]
9654    fn malformed_shapes_fail_on_both_paths() {
9655        // Malformed shapes fail on both lexers (messages may differ;
9656        // success/failure must agree). Unbalanced groups fail even
9657        // earlier, at lex time: both layers reject, which is what the
9658        // oracle pins.
9659        for text in [
9660            "[a] ECHO hi",
9661            "[os:atari] ECHO hi",
9662            "[foo:bar] ECHO hi",
9663            "[any(os:linux)] ECHO hi",
9664            "[all()] ECHO hi",
9665            "[env:] ECHO hi",
9666            "[eq(env:K)] ECHO hi",
9667            "[not] ECHO hi",
9668            "ECHO [a;b]",
9669            "ECHO (a;b)",
9670            "ECHO a;b",
9671            "LET $x = 1",
9672            "LET $s: STRING",
9673            "LET $x: INT = 1 2",
9674            "LET $x: INT = (1",
9675            "LET $x: INT = 9223372036854775808",
9676            "$x =",
9677            "RETURN (",
9678            "[env:X]",
9679            "LET $x: INT = $a == $b == $c",
9680            "LET $x: BOOL = $a < $b < $c",
9681            "LET $bs: STRING = a\\nb",
9682            "FOO(\"a\")",
9683            "FOO (\"a\")",
9684            "ECHO(\"hi\")",
9685            "RUN [a] extra",
9686            "RUN[\"a\"]",
9687            "TIMEOUT 10s RUN[\"a\"]",
9688            "LET $r: STRING = RUN[\"a\"]",
9689            "LET $e: STRING = ECHO",
9690            "ENV A=1 B=2",
9691            "EXPAND \"a b\" c",
9692            "ECHO {a}",
9693            "ECHO K=${x}",
9694            "[!env:A==1] RUN echo no",
9695            "run echo hi",
9696            "LET $x: STRING = AWAIT",
9697            "LET $o: STRING = CANCEL $t",
9698            "LET $x: STRING = ASYNC",
9699            "LET $x: STRING = WITH_IO",
9700            "LET $x: STRING = TIMEOUT",
9701            "LET $x: STRING = ISOLATED",
9702            "LET $x: STRING = ISOLATED ECHO hi",
9703            "COPY A=1",
9704            "WITH_IO [rows=40] RUN echo hi",
9705            "WITH_IO [tty] ECHO hi",
9706            "WITH_IO [tty, stderr=$p] RUN echo hi",
9707            "WITH_IO [tty=$p] RUN echo hi",
9708            "WITH_IO [cols=0] RUN echo hi",
9709            "WITH_IO [cols=65536] RUN echo hi",
9710            "WITH_IO [] ECHO hi",
9711            "WITH_IO [stdin=$p,] ECHO hi",
9712            "WITH_IO stdin=$p ECHO hi",
9713            "WITH_IO [STDIN=$p] ECHO hi",
9714            "WITH_IO [rows] RUN echo hi",
9715            KEYWORD_WITH_IO,
9716            "WITH_IO [stdout=$p]",
9717            "WITH_IO [stdin=$p]\n[os:linux] { ECHO hi }",
9718            "WITH_IO [stdin=$p] { }",
9719            "WITH_IO[stdin=$p] ECHO hi",
9720            "WITH_IO [stdin=$p]ECHO hi",
9721            "WITH_IO [stdin=$p] {{ $x }}",
9722            "ASYNC WITH_IO [stdout=$p] ECHO hi",
9723            "WITH_IO [stdin=$p] AWAIT $t",
9724            "ASYNC AWAIT $t",
9725            "WITH_IO [stdin=$p] RETURN \"hi\"",
9726            "ASYNC RETURN \"hi\"",
9727            "TIMEOUT 10s RETURN \"hi\"",
9728            "TIMEOUT banana ECHO hi",
9729            "TIMEOUT 10ss ECHO hi",
9730            "TIMEOUT 10 s ECHO hi",
9731            "TIMEOUT -5s ECHO hi",
9732            "TIMEOUT 0s ECHO hi",
9733            KEYWORD_TIMEOUT,
9734            "TIMEOUT 10s",
9735            "TIMEOUT { ECHO hi }",
9736            "TIMEOUT \"10s\"",
9737            "TIMEOUT 10s{ECHO hi}",
9738            "TIMEOUT 10sECHO hi",
9739            "TIMEOUT 10s {{ $d }}",
9740            "TIMEOUT 10s { $d }",
9741            "TIMEOUT { $d } ECHO hi",
9742            KEYWORD_ASYNC,
9743            KEYWORD_ISOLATED,
9744            "ISOLATED{ECHO hi}",
9745            KEYWORD_AWAIT,
9746            KEYWORD_CANCEL,
9747            "AWAIT t",
9748            "AWAIT $",
9749            "AWAIT $t extra",
9750            "CANCEL $t extra",
9751            "TIMEOUT 5s INHERIT_ENV [M]",
9752            "TIMEOUT 5s { INHERIT_ENV [M] }",
9753            "ASYNC { INHERIT_ENV [M] }",
9754            "LET $x: STRING = INHERIT_ENV [M]",
9755            "TIMEOUT 10s WITH_IO [stdin=$p] { ECHO hi }",
9756            "ISOLATED WITH_IO [stdin=$p] { ECHO hi }",
9757            "TIMEOUT 10s AWAIT $ t",
9758            "LET $o: STRING = AWAIT $ t",
9759            "ISOLATED AWAIT $ t",
9760            "WITH_IO [stdin=$p] CANCEL $ t",
9761            "LET $ x: INT = 1",
9762            "LET $x: STRING = WITH_IO [stdin=$p] { ECHO hi }",
9763            "LET $x: STRING = WITH_IO [stdin=$p] ASYNC",
9764            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO a\nECHO b }",
9765            "LET $x: STRING = WITH_IO [stdout=$p] ECHO hi",
9766            "LET $x: STRING = TIMEOUT 10s AWAIT $t",
9767            "LET $x: STRING = CANCEL $t",
9768            "LET $x: STRING = ASYNC",
9769            "LET $x: STRING = WITH_IO",
9770            "TIMEOUT 10s LET $x: INT = 1",
9771            "LET $x: STRING = FOO bar",
9772            "LET(\"a\")",
9773            "AWAIT($t)",
9774            "CANCEL($t)",
9775            "TIMEOUT(\"10s\") ECHO hi",
9776            "RETURN ECHO bye",
9777        ] {
9778            match crate::tok::lex_str(text) {
9779                Err(_) => {
9780                    assert!(
9781                        crate::parse_script(text, lower).is_err(),
9782                        "backend must also reject lex-broken input: {text:?}"
9783                    );
9784                    continue;
9785                }
9786                Ok(toks) => {
9787                    assert!(
9788                        parse_tokens(&toks, lower).is_err(),
9789                        "v2 must explicitly reject (not silently drift): {text:?}"
9790                    );
9791                }
9792            }
9793            assert!(
9794                crate::parse_script(text, lower).is_err(),
9795                "backend must also reject (oracle agreement): {text:?}"
9796            );
9797        }
9798        // No deferred shapes remain: every statement-level block and
9799        // inline-block expression parses natively.
9800    }
9801}