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