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