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