Skip to main content

oxdock_parser/
parser.rs

1//! Script parser: [`Tok`] stream to [`Step`].
2//!
3//! The single parser for string scripts and braced-macro token
4//! streams. The string entry points at the bottom of this module lex
5//! with `lex_str` and lower here; the braced-macro frontend fuses
6//! span-adjacent literals, runs the same scanner, and lowers here.
7//!
8//! Statement boundaries resolve here from grammar state, never in the
9//! lexers: groups arrive structurally atomic, so at each nesting level
10//! a `Newline`/`Semicolon` ends the statement. Continuation exceptions
11//! (trailing `=`, `IN`, trailing `ASYNC`, bare wrapper heads) land with
12//! their structural slices; the decision point is
13//! `boundary_ends_statement`.
14//!
15//! Coverage: generic commands (head word plus gap-split args with
16//! quote-accurate joins), guards (leading `[..]` groups; in-body
17//! brackets splice to raw text), `LET`/`SET`/`RETURN` with the full
18//! expression tiers, static calls and RUN-exec with instruction
19//! exactness, single-command wrappers (`WITH_IO`/`TIMEOUT`/`ISOLATED`/
20//! `ASYNC`), io-blocks, `AWAIT`/`CANCEL`, multi-element statements,
21//! block statements (`IF`/`FOR`/`WHILE`/`FUNC`/`REMOTE`/`TYPE`/
22//! `IMPORT`/`EXPORT`), guard blocks, and a whole-script post-pass
23//! (prelude order, COPY placement, EXPORT membership). Comments ride
24//! as `TokKind::Comment` markers plus mid-line `//`/`#`/`/*` gap
25//! rules.
26//!
27//! Design record: shared lowering cores with parser-native token
28//! classification. Each item below states what is shared and what is
29//! parser-native (verified by the lexer-agreement oracle and the fuzz
30//! harness).
31//! - Argument assembly matches single-quoted-string `quoted=true` and
32//!   multi-fragment space-or-empty joins by the `joint` flag.
33//! - `key_char`/`bare_run`/`value_run` implement the guard key/value
34//!   charsets (everything but `: = ! , | ( ) ] $`, whitespace, and
35//!   comment opens; `eq` values cross gaps like the atomic span).
36//! - `ns_guard` validates namespaces with shared messages.
37//! - Guard validation strings (`any(...)/all(...)/eq(...)` shapes)
38//!   carry shared messages.
39//! - `parse_guard_groups` folds stacked brackets with `All` (the
40//!   statement-guard stash semantics).
41//! - The expression tiers implement or/and/compare/ordering/add/mul/
42//!   unary/atom precedence over [`Tok`]; lowering runs through the
43//!   shared constructors (`make_arith`, `make_compare`,
44//!   `apply_unary_neg`, `reject_boundary`, `classify_numeric_text`,
45//!   `canonicalize_spelling`, `lower_block_string`).
46//! - Static call resolution is truly shared (`resolve_call_name`,
47//!   `check_func_ident` in `resolve.rs`).
48//! - Instruction tokens are truly shared (`InsToken`,
49//!   `lower_env_tokens`, `lower_expand_tokens`,
50//!   `canonical_assignment_arg` in `commands.rs`); only the
51//!   token-level classifiers (key runs, boundaries, call shapes,
52//!   expression extension) are parser-native.
53//! - Numeric `_`-separator shape gating, bare-word charsets, and
54//!   `-`-prefix dispatch match the lexical rules (durations, paths,
55//!   and versions lex as bare words; `-f` stays literal).
56//! - Wrapper validators are truly shared (`check_tty_wrapping`,
57//!   `reject_async_in_capture`, `reject_pipe_stdout_in_capture`,
58//!   `rewrite_isolated_inherit`, `contains_inherit_env`,
59//!   `reject_nested_inherit_env`, `merge_bindings`, `IoBindingSet`,
60//!   `and_guard_exprs`, `reject_with_io_in_async` in `commands.rs`;
61//!   in `commands.rs`); only the token-level shape classifiers
62//!   (duration gate, binding splitter, await/cancel shapes,
63//!   block-vs-template, inherit keys) are parser-native.
64//! - The element loop lowers consecutive elements to end of run:
65//!   structural pairs end mid-line and trailing elements form
66//!   following steps (guards attach to the first only); the `WITH_IO`
67//!   pending wait holds bare brackets across separators.
68//! - Block headers: `IF`/`FOR`/`WHILE`
69//!   conditions miss to generic on expression failure (inline-block
70//!   failures propagate); `FUNC` paren-group params parse with `gap`
71//!   discipline; `REMOTE` targets/blocks/bindings; `TYPE` maximal
72//!   shape match; `IMPORT`/`EXPORT` lists. Shared
73//!   validators are truly shared (`validate_remote_copy_placement`,
74//!   `contains_remote_block`, `collect_remote_body_symbols`,
75//!   `validate_exports` in `commands.rs`).
76//! - Scope marking: top-level guard nesting
77//!   bumps each level (stateful `pending_scope_enters`); wrapper and
78//!   guard-block bodies pin 0/0 (`parse_body_steps` without marking).
79//! - Comment handling: statement-position
80//!   comments vanish (releasing `ELSE` holds), gap positions skip,
81//!   arg positions type or glue literally; `/*` depth protects
82//!   separators in the splitter, and group scanning copies comments
83//!   through for the recursive re-lex.
84
85use crate::ast::{
86    Arg, ArithOp, CompareOp, Expr, Guard, GuardExpr, IoBinding, IoStream, LogicalOp, ModuleTable,
87    Ns, Step, StepKind, Value,
88};
89use crate::command::ArgType;
90use crate::commands::{
91    InsToken, apply_unary_neg, canonical_assignment_arg, check_tty_wrapping, classify_numeric_text,
92    is_known_command, lower_env_tokens, lower_expand_tokens, make_arith, make_compare,
93    reject_boundary,
94};
95use crate::constants::{
96    INJECT_PREFIX, INJECT_SUFFIX, KEYWORD_AS, KEYWORD_ASYNC, KEYWORD_AWAIT, KEYWORD_BREAK,
97    KEYWORD_CANCEL, KEYWORD_CONTINUE, KEYWORD_ELSE, KEYWORD_ENV, KEYWORD_EXPAND, KEYWORD_EXPORT,
98    KEYWORD_FOR, KEYWORD_FROM, KEYWORD_FUNC, KEYWORD_IF, KEYWORD_IMPORT, KEYWORD_IN,
99    KEYWORD_INHERIT_ENV, KEYWORD_INSPECT, KEYWORD_ISOLATED, KEYWORD_LET, KEYWORD_REMOTE,
100    KEYWORD_RETURN, KEYWORD_RUN, KEYWORD_TIMEOUT, KEYWORD_TYPE, KEYWORD_WHILE, KEYWORD_WITH_IO,
101    MODULE_SEPARATOR,
102};
103use crate::error::{ParseError, ParseErrorKind, ParseResult, SpanContext};
104
105use crate::resolve::resolve_call_name;
106use crate::tok::{GroupDelim, LexError, Tok, TokKind, lex_str};
107use std::cell::RefCell;
108use std::collections::HashSet;
109use std::fmt;
110
111/// Backend error. Carries the statement index and message; the string
112/// entry points below map it to [`crate::ParseError`]. Lowering
113/// failures from the shared `lower` dispatcher stringify through here
114/// so success paths compare exactly.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct TokenError {
117    pub stmt: usize,
118    /// 1-based source line, `0` when unknown (the split loops stamp the
119    /// enclosing statement's line on the way out, so only genuinely
120    /// position-less errors stay `0`).
121    pub line: usize,
122    /// 1-based start column of the enclosing statement, `0` when
123    /// unknown (stamped alongside `line`).
124    pub col: usize,
125    pub msg: String,
126    /// Lowering failures preserve the dispatcher's classification
127    /// (`UnknownCommand`, `InvalidSyntax`, `Validation`); `None` means
128    /// a parser-native structural failure.
129    pub kind: Option<ParseErrorKind>,
130}
131
132impl fmt::Display for TokenError {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        write!(
135            f,
136            "parse error in statement {}: {}",
137            self.stmt + 1,
138            self.msg
139        )
140    }
141}
142
143impl std::error::Error for TokenError {}
144
145/// Lift a dispatcher/resolver [`ParseError`] into a [`TokenError`],
146/// preserving its machine-readable classification (the entry points
147/// convert it back verbatim, so `UnknownCommand`/`InvalidSyntax`/
148/// `Validation` survive the round trip). The message is the
149/// dispatcher's own display text; the split loops stamp the line.
150fn lower_err(stmt: usize, e: ParseError) -> TokenError {
151    TokenError {
152        stmt,
153        line: 0,
154        col: 0,
155        msg: e.to_string(),
156        kind: Some(e.kind().clone()),
157    }
158}
159
160/// One split statement: leading bracket groups (guard region) plus
161/// the body tokens. `brace_detached` records a
162/// `Newline`/`Semicolon` between the guard region and a brace-headed
163/// body: in-body such statements are hard errors (a bare `{` is
164/// illegal inside blocks), while top level merges or parses guard
165/// blocks regardless.
166#[derive(Debug, Clone)]
167struct Stmt {
168    guard: Vec<Tok>,
169    body: Vec<Tok>,
170    brace_detached: bool,
171    /// 1-based source line where the body starts (guards ride on
172    /// earlier lines; errors report this).
173    line: usize,
174    /// 1-based column where the body starts (`0` when the head token
175    /// carries no coordinates: synthetic streams). Read off the first
176    /// body token, which always has the statement's own start.
177    col: usize,
178}
179
180impl PartialEq for Stmt {
181    fn eq(&self, other: &Self) -> bool {
182        // Coordinates are provenance (never rendered, never compared),
183        // like `Step`/`Tok`: two splits of one text compare equal.
184        self.guard == other.guard
185            && self.body == other.body
186            && self.brace_detached == other.brace_detached
187    }
188}
189
190impl Eq for Stmt {}
191
192/// 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/// RUN exec-form items: atoms only, except parenthesized/calls/lists/maps
2599/// which recurse fully. Anything that is not a clean comma-separated list misses the whole
2600/// exec shape (`None`): the grammar falls through to the shell path,
2601/// which reads the bracket literally and lets the shared lowering
2602/// decide (POSIX `[ -f ... ]` stays shell; non-map blocks and malformed
2603/// shapes behave exactly like the grammar's fallthrough).
2604/// (`instruction`), which reads the bracket literally and lets the
2605/// shared lowering decide (POSIX `[ -f ... ]` stays shell, malformed
2606/// shapes fail there exactly like the grammar). Only the
2607/// joint-bracket gate stays a hard error (it precedes this function).
2608fn parse_run_exec_list(
2609    inner: &[Tok],
2610    stmt: usize,
2611    ctx: &ParseCtx,
2612) -> Result<Option<Expr>, TokenError> {
2613    let mut cur = Cursor::expr(inner, stmt);
2614    cur.skip_gap();
2615    if cur.done() {
2616        return Ok(Some(Expr::List(vec![])));
2617    }
2618    let mut items = Vec::new();
2619    loop {
2620        let item = match parse_run_exec_atom(&mut cur, ctx) {
2621            Ok(Some(item)) => item,
2622            // Not an exec shape at all: shell fallthrough.
2623            _ => return Ok(None),
2624        };
2625        if reject_boundary(&lowering_ctx(stmt), &item).is_err() {
2626            return Ok(None);
2627        }
2628        items.push(item);
2629        cur.skip_gap();
2630        if cur.eat_punct(',') {
2631            cur.skip_gap();
2632            continue;
2633        }
2634        break;
2635    }
2636    if !cur.done() {
2637        return Ok(None);
2638    }
2639    Ok(Some(Expr::List(items)))
2640}
2641
2642/// One RUN-exec item: brace groups try maps only (blocks miss);
2643/// everything else parses as a full atom (nested lists and map
2644/// values still admit blocks, like the grammar).
2645fn parse_run_exec_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Option<Expr>, TokenError> {
2646    if matches!(
2647        cur.toks.get(cur.pos).map(|t| &t.kind),
2648        Some(TokKind::Group {
2649            delim: GroupDelim::Brace,
2650            ..
2651        })
2652    ) {
2653        let inner = match &cur.toks[cur.pos].kind {
2654            TokKind::Group { inner, .. } => inner.clone(),
2655            _ => unreachable!(),
2656        };
2657        return match parse_map_literal(&inner, cur.stmt, ctx) {
2658            Ok(map) => {
2659                cur.pos += 1;
2660                Ok(Some(map))
2661            }
2662            Err(_) => Ok(None),
2663        };
2664    }
2665    parse_expr_atom(cur, ctx).map(Some)
2666}
2667
2668// ---- Single-command wrappers + AWAIT/CANCEL ----
2669// Wrappers parse through the shared validators (`check_tty_wrapping`,
2670// capture rejects, isolated rewrite, nesting reject, binding merge,
2671// guard `and`) promoted verbatim to `commands.rs`; only the
2672// token-level shape classifiers (duration gate, binding splitter,
2673// await/cancel shapes, block-vs-template) are v2-native. Statements
2674// lower to step VECTORS: structural pairs (calls, RUN-exec,
2675// await/cancel, wrapper blocks) end mid-line and trailing elements
2676// form following steps, exactly like the grammar's `element*`.
2677//
2678// Deferred: block STATEMENTS (slice 5: top-level `IF`/`FOR`/`WHILE`
2679// bodies, guard blocks, `REMOTE`, directives).
2680
2681/// Static duration shape mirror (`timeout_literal`, atomic): ASCII
2682/// digits plus one optional unit, full-match only. Anything else
2683/// (`10ss`, `banana`, `-5s`) misses the wrapper shape and falls back
2684/// to the generic instruction path, which fails in lowering exactly
2685/// like the grammar's committed `instruction`.
2686fn is_timeout_literal(text: &str) -> bool {
2687    let digits = text.len() - text.trim_start_matches(|c: char| c.is_ascii_digit()).len();
2688    if digits == 0 {
2689        return false;
2690    }
2691    matches!(&text[digits..], "" | "ms" | "s" | "m" | "h")
2692}
2693
2694/// Template-brace test: a brace group whose first inner token opens
2695/// another brace (`{{...}}`); anything else braced is a block body.
2696/// Same shape the arg engine uses; single source from here.
2697fn is_template_brace(tok: &Tok) -> bool {
2698    matches!(
2699        &tok.kind,
2700        TokKind::Group {
2701            delim: GroupDelim::Brace,
2702            inner,
2703            ..
2704        } if matches!(
2705            inner.first().map(|t| &t.kind),
2706            Some(TokKind::Group {
2707                delim: GroupDelim::Brace,
2708                ..
2709            })
2710        )
2711    )
2712}
2713
2714/// Parse one TIMEOUT duration unit at `pos` (the token after the
2715/// head, gapped like the grammar's `sep`). Returns the arg and
2716/// tokens consumed, or `None` on shape miss (caller falls back to
2717/// generic, which fails in lowering). Static
2718/// literals validate now through the shared Duration check
2719/// (`TIMEOUT 0s` fails here, probed); dynamics defer to runtime.
2720fn parse_timeout_duration_at(
2721    toks: &[Tok],
2722    pos: usize,
2723    stmt: usize,
2724) -> Result<Option<(Arg, usize)>, TokenError> {
2725    let Some(head) = toks.get(pos) else {
2726        return Ok(None);
2727    };
2728    if head.joint {
2729        return Ok(None);
2730    }
2731    let arg = match &head.kind {
2732        TokKind::Word(w) if is_timeout_literal(w) => Arg::String(w.clone(), false),
2733        TokKind::Punct('$') => match toks.get(pos + 1) {
2734            Some(var) if var.joint && matches!(&var.kind, TokKind::Word(w) if is_ident_word(w)) => {
2735                match &var.kind {
2736                    TokKind::Word(w) => Arg::Expr(Expr::Var(w.clone())),
2737                    _ => unreachable!(),
2738                }
2739            }
2740            _ => return Ok(None),
2741        },
2742        TokKind::Str { text, .. } => Arg::String(text.clone(), true),
2743        TokKind::BlockStr(full) => Arg::String(crate::command::lower_block_string(full), true),
2744        TokKind::Group {
2745            delim: GroupDelim::Brace,
2746            inner,
2747            open_joint,
2748            close_joint,
2749        } if is_template_brace(&toks[pos]) => Arg::String(
2750            render_group('{', '}', inner, *open_joint, *close_joint),
2751            false,
2752        ),
2753        _ => return Ok(None),
2754    };
2755    let used = match &head.kind {
2756        TokKind::Punct('$') => 2,
2757        _ => 1,
2758    };
2759    ArgType::Duration.check_arg(&arg).map_err(|e| TokenError {
2760        stmt,
2761        msg: e.to_string(),
2762        line: 0,
2763        col: 0,
2764        kind: None,
2765    })?;
2766    Ok(Some((arg, used)))
2767}
2768
2769/// Parse `WITH_IO [...]` bindings over a bracket group's inner
2770/// tokens: comma-separated `stream[=$var]` / `rows|cols=int`
2771/// bindings, newlines skipping freely like `ws`. Returns `None` on
2772/// shape miss (empty flags, bad stream words, missing commas or
2773/// values: the caller falls back to generic, which fails in lowering).
2774/// Grammar-matched but invalid bindings (tty
2775/// values, out-of-range geometry) fail loudly, mirroring
2776/// `parse_io_binding`'s messages one by one.
2777fn parse_io_bindings(inner: &[Tok], stmt: usize) -> Result<Option<Vec<IoBinding>>, TokenError> {
2778    let mut parts: Vec<&[Tok]> = Vec::new();
2779    let mut start = 0;
2780    for (i, tok) in inner.iter().enumerate() {
2781        // Newlines skip freely like `ws` (filtered per part below);
2782        // commas split bindings; everything else is content.
2783        if matches!(&tok.kind, TokKind::Punct(',')) {
2784            parts.push(&inner[start..i]);
2785            start = i + 1;
2786        }
2787    }
2788    parts.push(&inner[start..]);
2789    // An empty flag list (`[]`, `[,]`) misses the shape.
2790    if parts.len() == 1 && parts[0].iter().all(|t| matches!(&t.kind, TokKind::Newline)) {
2791        return Ok(None);
2792    }
2793    let mut out = Vec::new();
2794    for part in parts {
2795        let part: Vec<&Tok> = part
2796            .iter()
2797            .filter(|t| !matches!(&t.kind, TokKind::Newline))
2798            .collect();
2799        match parse_io_binding_part(&part, stmt)? {
2800            Some(binding) => out.push(binding),
2801            None => return Ok(None),
2802        }
2803    }
2804    if out.is_empty() {
2805        return Ok(None);
2806    }
2807    Ok(Some(out))
2808}
2809
2810/// One `stream[=$var]` / `rows|cols=int` binding. Gaps ride free
2811/// around `=`/`,`/names like `ws?`; only `$`+name stays gapless
2812/// (atomic `dollar_ident`). Streams and size names outside the
2813/// grammar's words miss the shape; a valued `tty` and out-of-range
2814/// geometry fail loudly with exact messages.
2815fn parse_io_binding_part(part: &[&Tok], stmt: usize) -> Result<Option<IoBinding>, TokenError> {
2816    let fail = |msg: String| TokenError {
2817        stmt,
2818        msg,
2819        line: 0,
2820        col: 0,
2821        kind: None,
2822    };
2823    let Some(first) = part.first() else {
2824        return Ok(None);
2825    };
2826    let TokKind::Word(stream) = &first.kind else {
2827        return Ok(None);
2828    };
2829    let is_stream = matches!(stream.as_str(), "stdin" | "stdout" | "stderr" | "tty");
2830    let is_size = matches!(stream.as_str(), "rows" | "cols");
2831    if !is_stream && !is_size {
2832        return Ok(None);
2833    }
2834    let rest = &part[1..];
2835    if rest.is_empty() {
2836        if is_size {
2837            // Bare `rows` misses `io_size` (`=` + digits required).
2838            return Ok(None);
2839        }
2840        return Ok(Some(IoBinding {
2841            stream: io_stream_of(stream),
2842            pipe: None,
2843        }));
2844    }
2845    // `= value` at any gap.
2846    if !matches!(rest.first().map(|t| &t.kind), Some(TokKind::Punct('='))) {
2847        return Ok(None);
2848    }
2849    let value = &rest[1..];
2850    if is_size {
2851        // Geometry: one all-digit word, 1-65535 (mirrors `parse_io_size`).
2852        if value.len() != 1 {
2853            return Ok(None);
2854        }
2855        let TokKind::Word(digits) = &value[0].kind else {
2856            return Ok(None);
2857        };
2858        if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
2859            return Ok(None);
2860        }
2861        let dim = digits
2862            .parse::<u64>()
2863            .ok()
2864            .filter(|v| (1..=u64::from(u16::MAX)).contains(v))
2865            .ok_or_else(|| {
2866                fail(
2867                    "WITH_IO terminal geometry needs a positive integer 1-65535 (e.g. `rows=40`)"
2868                        .to_string(),
2869                )
2870            })?;
2871        let dim = dim as u16;
2872        return Ok(Some(IoBinding {
2873            stream: if stream == "rows" {
2874                IoStream::Rows(dim)
2875            } else {
2876                IoStream::Cols(dim)
2877            },
2878            pipe: None,
2879        }));
2880    }
2881    // Stream pipe: `= $var` with a gapless name.
2882    if value.len() != 2 {
2883        return Ok(None);
2884    }
2885    if !matches!(&value[0].kind, TokKind::Punct('$')) {
2886        return Ok(None);
2887    }
2888    let TokKind::Word(var) = &value[1].kind else {
2889        return Ok(None);
2890    };
2891    if !value[1].joint || !is_ident_word(var) {
2892        return Ok(None);
2893    }
2894    if stream == "tty" {
2895        // `tty` is a bare flag (mirrors `parse_io_binding`).
2896        return Err(fail(
2897            "WITH_IO [tty] takes no value: use bare `tty`, with `rows = <int>` / `cols = <int>` for geometry (e.g. `[tty, rows=40, cols=100]`)"
2898                .to_string(),
2899        ));
2900    }
2901    Ok(Some(IoBinding {
2902        stream: io_stream_of(stream),
2903        pipe: Some(crate::ast::PipeTarget::Var(var.clone())),
2904    }))
2905}
2906
2907/// Stream word to [`IoStream`]: only grammar words reach here, so
2908/// the mapping is total (mirrors `parse_io_stream`).
2909fn io_stream_of(name: &str) -> IoStream {
2910    match name {
2911        "stdin" => IoStream::Stdin,
2912        "stdout" => IoStream::Stdout,
2913        "stderr" => IoStream::Stderr,
2914        _ => IoStream::Tty,
2915    }
2916}
2917
2918/// `AWAIT`/`CANCEL $var` shape at `pos`. A head without `$` misses
2919/// (`None`: generic fails it in lowering); once `$`
2920/// commits, the name must follow and parse errors stay loud, like
2921/// the grammar's committed `"$" ~ ident`. `var_joint` enforces the
2922/// atomic `$var` adjacency inside compound-atomic parents; element
2923/// level admits the gap (probed `AWAIT $ t`). The caller continues
2924/// its element loop past the shape.
2925fn parse_await_cancel_at(
2926    toks: &[Tok],
2927    pos: usize,
2928    stmt: usize,
2929    var_joint: bool,
2930) -> Result<Option<(StepKind, usize)>, TokenError> {
2931    let head = match toks.get(pos).map(|t| &t.kind) {
2932        Some(TokKind::Word(w)) if w == KEYWORD_AWAIT || w == KEYWORD_CANCEL => w.clone(),
2933        _ => return Ok(None),
2934    };
2935    if !matches!(
2936        toks.get(pos + 1).map(|t| &t.kind),
2937        Some(TokKind::Punct('$'))
2938    ) {
2939        return Ok(None);
2940    }
2941    let var = match toks.get(pos + 2) {
2942        Some(t)
2943            if matches!(&t.kind, TokKind::Word(w) if is_ident_word(w))
2944                && (!var_joint || t.joint) =>
2945        {
2946            match &t.kind {
2947                TokKind::Word(w) => w.clone(),
2948                _ => unreachable!(),
2949            }
2950        }
2951        _ => {
2952            return Err(TokenError {
2953                stmt,
2954                msg: format!("{head} requires a variable"),
2955                line: 0,
2956                col: 0,
2957                kind: None,
2958            });
2959        }
2960    };
2961    Ok(Some((
2962        if head == KEYWORD_AWAIT {
2963            StepKind::Await { var }
2964        } else {
2965            StepKind::Cancel { var }
2966        },
2967        3,
2968    )))
2969}
2970
2971/// Wrapper strictness for one single-command inner: `AWAIT` parses
2972/// dedicated in `TIMEOUT`/`ISOLATED` inners but falls to generic in
2973/// `WITH_IO`/`ASYNC` inners (where lowering fails it, probed), and
2974/// `WITH_IO` recurses everywhere but directly under `ASYNC` (where
2975/// lowering fails it, probed). Shared predicates, never restated.
2976#[derive(Clone, Copy)]
2977struct InnerRules {
2978    allow_await: bool,
2979    allow_with_io: bool,
2980}
2981
2982/// Parse one single (non-block) inner command, returning the kind
2983/// and tokens consumed: dedicated await/cancel, while/remote, calls,
2984/// RUN-exec, nested wrappers, strict `INHERIT_ENV` (the caller
2985/// rejects the nesting or rewrites it), or the generic instruction
2986/// path (which consumes everything and fails unknown heads in
2987/// lowering, exactly like the grammar's committed `instruction`).
2988fn parse_single_inner(
2989    toks: &[Tok],
2990    pos: usize,
2991    stmt: usize,
2992    ctx: &ParseCtx,
2993    rules: InnerRules,
2994) -> Result<(StepKind, usize), TokenError> {
2995    let head_word = match toks.get(pos).map(|t| &t.kind) {
2996        Some(TokKind::Word(w)) => Some(w.clone()),
2997        _ => None,
2998    };
2999    // Nested `WHILE`/`REMOTE` recurse structurally (both ride every
3000    // inner-command set in the grammar); misses fall through to
3001    // generic below.
3002    if head_word.as_deref() == Some(KEYWORD_WHILE) {
3003        match parse_while_single(toks, pos, stmt, ctx) {
3004            Ok(Some((kind, used))) => return Ok((kind, used)),
3005            Ok(None) => {}
3006            Err(e) => return Err(e),
3007        }
3008    }
3009    if head_word.as_deref() == Some(KEYWORD_REMOTE) {
3010        match parse_remote_single(toks, pos, stmt, ctx) {
3011            Ok(Some((kind, used))) => return Ok((kind, used)),
3012            Ok(None) => {}
3013            Err(e) => return Err(e),
3014        }
3015    }
3016    // File `IMPORT "path" AS ALIAS` (#115) rides every single-inner
3017    // set (TIMEOUT/ISOLATED/WITH_IO/ASYNC, LET ASYNC): exactly one file
3018    // entry and no modules, else a hard error; shape misses fall through
3019    // to generic below, which fails them in lowering.
3020    if head_word.as_deref() == Some(KEYWORD_IMPORT)
3021        && let Some((path, alias, used)) = parse_single_file_import(toks, pos, stmt, ctx)?
3022    {
3023        return Ok((StepKind::ImportFile { path, alias }, used));
3024    }
3025    // Dedicated await/cancel first (await gated by parent); anything
3026    // they decline falls through to generic below.
3027    if head_word.as_deref() == Some(KEYWORD_AWAIT)
3028        && rules.allow_await
3029        && let Some(found) = parse_await_cancel_at(toks, pos, stmt, true)?
3030    {
3031        return Ok(found);
3032    }
3033    if head_word.as_deref() == Some(KEYWORD_CANCEL)
3034        && let Some(found) = parse_await_cancel_at(toks, pos, stmt, true)?
3035    {
3036        return Ok(found);
3037    }
3038    // Calls and RUN-exec end mid-run; the caller continues past them.
3039    if let Some((call_name, paren)) = call_shape_at(toks, pos, true) {
3040        let inner = match &toks[paren].kind {
3041            TokKind::Group { inner, .. } => inner.clone(),
3042            _ => unreachable!(),
3043        };
3044        let args = parse_call_args(&inner, stmt, ctx)?;
3045        if !call_name.contains(MODULE_SEPARATOR) {
3046            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
3047                .map_err(|e| lower_err(stmt, e))?;
3048        }
3049        let qualified = resolve_name(ctx, stmt, &call_name)?;
3050        return Ok((
3051            StepKind::Call {
3052                name: qualified,
3053                args,
3054            },
3055            paren + 1 - pos,
3056        ));
3057    }
3058    if head_word.as_deref() == Some(KEYWORD_RUN)
3059        && matches!(
3060            toks.get(pos + 1).map(|t| &t.kind),
3061            Some(TokKind::Group {
3062                delim: GroupDelim::Bracket,
3063                ..
3064            })
3065        )
3066    {
3067        // Gapped like the grammar's `sep`; a joint bracket is a
3068        // hard error, never a spliced arg (probed `RUN["a"]`).
3069        if toks[pos + 1].joint {
3070            return Err(TokenError {
3071                stmt,
3072                msg: "RUN [...] requires a gap after RUN".to_string(),
3073                line: 0,
3074                col: 0,
3075                kind: None,
3076            });
3077        }
3078        let inner = match &toks[pos + 1].kind {
3079            TokKind::Group { inner, .. } => inner.clone(),
3080            _ => unreachable!(),
3081        };
3082        let exec_list = parse_run_exec_list(&inner, stmt, ctx)?;
3083        // Non-map blocks miss the exec shape (the grammar has no
3084        // `block` alternative here); fall through to generic below,
3085        // which reads the shell path literally.
3086        if let Some(list) = exec_list {
3087            let kind =
3088                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
3089            return Ok((kind, 2));
3090        }
3091    }
3092    // Nested wrappers recurse structurally; a `WITH_IO` directly
3093    // under `ASYNC` goes generic instead (lowering fails it, probed).
3094    match head_word.as_deref() {
3095        Some(KEYWORD_WITH_IO) if rules.allow_with_io => {
3096            match parse_with_io_single(toks, pos, stmt, ctx) {
3097                Ok(Some((kind, used))) => return Ok((kind, used)),
3098                Ok(None) => {}
3099                Err(e) => return Err(e),
3100            }
3101        }
3102        Some(KEYWORD_TIMEOUT) => match parse_timeout_single(toks, pos, stmt, ctx) {
3103            Ok(Some((kind, used))) => return Ok((kind, used)),
3104            Ok(None) => {}
3105            Err(e) => return Err(e),
3106        },
3107        Some(KEYWORD_ISOLATED) => match parse_isolated_single(toks, pos, stmt, ctx) {
3108            Ok(Some((kind, used))) => return Ok((kind, used)),
3109            Ok(None) => {}
3110            Err(e) => return Err(e),
3111        },
3112        Some(KEYWORD_ASYNC) => match parse_async_single(toks, pos, stmt, ctx) {
3113            Ok(Some((kind, used))) => return Ok((kind, used)),
3114            Ok(None) => {}
3115            Err(e) => return Err(e),
3116        },
3117        // `INHERIT_ENV [...]` parses strictly here (shared with
3118        // element level); the caller either rejects the nesting or
3119        // rewrites it, same as the shared validator. Trailing
3120        // elements loop on outside (a bad follower fails there, like
3121        // the grammar's line end).
3122        Some(KEYWORD_INHERIT_ENV) => {
3123            if let Some(found) = parse_inherit_env_at(toks, pos, stmt)? {
3124                return Ok(found);
3125            }
3126        }
3127        _ => {}
3128    }
3129    // Generic instruction: consumes the whole run; unknown heads
3130    // (LET/RETURN/FUNC/IF/...) fail in lowering.
3131    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
3132    Ok((kind, used))
3133}
3134
3135/// Parse an `INHERIT_ENV [...]` key list over a bracket group's
3136/// inner tokens, mirroring `inherit_list` strictly: comma-separated
3137/// keys, gaps/newlines only around keys and commas (never inside:
3138/// keys are atomic), each key a joint run validated against the
3139/// `guard_key_char` exclusions (`: = ! , | ( ) ] $`, plus the `//`
3140/// and `/*` comment opens). Groups and strings render raw (they read
3141/// as ordinary characters here); anything else misses
3142/// the shape (`None`: generic fails it in lowering).
3143/// Statement-level `INHERIT_ENV` stays generic (slice 5 directives);
3144/// this serves wrapper inners, where the nesting check (or the
3145/// isolated rewrite) consumes the result.
3146fn parse_inherit_keys(inner: &[Tok], stmt: usize) -> Result<Option<Vec<String>>, TokenError> {
3147    let mut parts: Vec<&[Tok]> = Vec::new();
3148    let mut start = 0;
3149    for (i, tok) in inner.iter().enumerate() {
3150        if matches!(&tok.kind, TokKind::Punct(',')) {
3151            parts.push(&inner[start..i]);
3152            start = i + 1;
3153        }
3154    }
3155    parts.push(&inner[start..]);
3156    let mut out = Vec::new();
3157    for part in parts {
3158        // Newlines skip at the edges only, like `ws?`.
3159        let mut part = part;
3160        while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
3161            part = &part[1..];
3162        }
3163        while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
3164            part = &part[..part.len() - 1];
3165        }
3166        let Some(key) = render_inherit_key(part, stmt)? else {
3167            return Ok(None);
3168        };
3169        out.push(key);
3170    }
3171    if out.is_empty() {
3172        return Ok(None);
3173    }
3174    Ok(Some(out))
3175}
3176
3177/// True when a `/` opens an inline comment: joint `//` or `/*`
3178/// (mirroring the grammar's comment literals, which need adjacency;
3179/// a gapped second char is payload text, like `a/ /b`). Used
3180/// everywhere `gap`/`gap_nl` admit comments.
3181fn is_comment_open(toks: &[Tok], pos: usize) -> bool {
3182    matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('/')))
3183        && matches!(
3184            toks.get(pos + 1).map(|t| (&t.kind, t.joint)),
3185            Some((TokKind::Punct('/'), true)) | Some((TokKind::Punct('*'), true))
3186        )
3187}
3188
3189/// Skip one inline comment starting at `pos` (which holds the `/`;
3190/// see [`is_comment_open`): `//` runs to a newline or the end,
3191/// `/* */` balances (nesting like the grammar) across newlines.
3192/// Returns the first position past the comment, or `None` when the
3193/// block never closes (the grammar fails unclosed comments too).
3194fn skip_inline_comment(toks: &[Tok], pos: usize) -> Option<usize> {
3195    let second = match toks.get(pos + 1).map(|t| &t.kind) {
3196        Some(TokKind::Punct('/')) => '/',
3197        Some(TokKind::Punct('*')) => '*',
3198        _ => return None,
3199    };
3200    if second == '/' {
3201        let mut p = pos + 2;
3202        while p < toks.len() && !matches!(&toks[p].kind, TokKind::Newline) {
3203            p += 1;
3204        }
3205        return Some(p);
3206    }
3207    let mut depth = 1usize;
3208    let mut p = pos + 2;
3209    while p < toks.len() {
3210        let is_open = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('/')))
3211            && matches!(
3212                toks.get(p + 1).map(|t| (&t.kind, t.joint)),
3213                Some((TokKind::Punct('*'), true))
3214            );
3215        let is_close = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('*')))
3216            && matches!(
3217                toks.get(p + 1).map(|t| (&t.kind, t.joint)),
3218                Some((TokKind::Punct('/'), true))
3219            );
3220        if is_open {
3221            depth += 1;
3222            p += 2;
3223        } else if is_close {
3224            depth -= 1;
3225            p += 2;
3226            if depth == 0 {
3227                return Some(p);
3228            }
3229        } else {
3230            p += 1;
3231        }
3232    }
3233    None
3234}
3235
3236/// Parse one inherit key: a maximal key-char run, then only
3237/// trailing gap content (`gap_nl`: newlines, comments, `#`). Key
3238/// chars exclude `: = ! , | ( ) ] $`, whitespace, and the `//` / `/*`
3239/// comment opens; a joint `#`
3240/// stays literal, a gapped one opens a trailing comment. Groups and
3241/// strings render raw for the exclusion check (they read as
3242/// ordinary characters here). `None` on shape miss.
3243fn render_inherit_key(part: &[Tok], stmt: usize) -> Result<Option<String>, TokenError> {
3244    let mut out = String::new();
3245    let mut i = 0;
3246    // Key run: words, puncts (except comment opens), groups and
3247    // strings rendered raw; ends at any gap, newline, comment, or
3248    // `//` / `/*` open.
3249    while i < part.len() {
3250        let tok = &part[i];
3251        if i > 0 && !tok.joint {
3252            break;
3253        }
3254        match &tok.kind {
3255            TokKind::Word(w) => {
3256                out.push_str(w);
3257                i += 1;
3258            }
3259            TokKind::Punct('/') if is_comment_open(part, i) => break,
3260            // `#` stays literal at key start (`#c`) or joint
3261            // (`a#b`); gapped mid-key it opens a trailing
3262            // comment like the grammar's `gap_nl`.
3263            TokKind::Punct('#') if tok.joint || out.is_empty() => {
3264                // `#` stays literal at key start (`#c`) or joint
3265                // (`a#b`).
3266                out.push('#');
3267                i += 1;
3268            }
3269            // Gapped mid-key `#` opens a trailing comment (handled
3270            // by the trailer check below, like `gap_nl`).
3271            TokKind::Punct('#') => break,
3272            TokKind::Punct(c) => {
3273                out.push(*c);
3274                i += 1;
3275            }
3276            TokKind::Semicolon => {
3277                out.push(';');
3278                i += 1;
3279            }
3280            TokKind::Str { text, quote } => {
3281                out.push(*quote);
3282                out.push_str(text);
3283                out.push(*quote);
3284                i += 1;
3285            }
3286            TokKind::BlockStr(full) => {
3287                out.push_str(full);
3288                i += 1;
3289            }
3290            TokKind::Group {
3291                delim,
3292                inner,
3293                open_joint,
3294                close_joint,
3295            } => {
3296                let (open, close) = match delim {
3297                    GroupDelim::Bracket => ('[', ']'),
3298                    GroupDelim::Paren => ('(', ')'),
3299                    GroupDelim::Brace => ('{', '}'),
3300                };
3301                out.push_str(&render_group(open, close, inner, *open_joint, *close_joint));
3302                i += 1;
3303            }
3304            // Newlines and comment markers end the key; the trailer
3305            // check below admits them.
3306            TokKind::Newline | TokKind::Comment(_) => break,
3307        }
3308    }
3309    if out.is_empty() {
3310        return Ok(None);
3311    }
3312    // Trailer: only gap content (`gap_nl`) may follow the key.
3313    let mut j = i;
3314    while j < part.len() {
3315        let tok = &part[j];
3316        match &tok.kind {
3317            TokKind::Newline | TokKind::Comment(_) => {
3318                j += 1;
3319            }
3320            TokKind::Punct('/') if is_comment_open(part, j) => {
3321                j = skip_inline_comment(part, j).ok_or(TokenError {
3322                    stmt,
3323                    msg: "unclosed block comment".to_string(),
3324                    line: 0,
3325                    col: 0,
3326                    kind: None,
3327                })?;
3328            }
3329            TokKind::Punct('#') => {
3330                // `#` comment runs to a newline or the part end.
3331                while j < part.len() && !matches!(&part[j].kind, TokKind::Newline) {
3332                    j += 1;
3333                }
3334            }
3335            _ => return Ok(None),
3336        }
3337    }
3338    // `guard_key_char` exclusions: the single-char set plus the
3339    // comment opens (`//`, `/*`); lone `/` stays legal.
3340    if out.contains("//") || out.contains("/*") {
3341        return Ok(None);
3342    }
3343    if out
3344        .chars()
3345        .any(|c| matches!(c, ':' | '=' | '!' | ',' | '|' | '(' | ')' | ']' | '$'))
3346    {
3347        return Ok(None);
3348    }
3349    Ok(Some(out))
3350}
3351
3352/// Strict `INHERIT_ENV [...]` at an element or single-inner
3353/// position: bracket riding gapped with valid keys yields the
3354/// directive (trailing elements loop on outside); anything else
3355/// misses (`None`) and generic fails it in lowering.
3356/// Serves both levels so keys stay exact everywhere; slice 5 adds
3357/// only the prelude-order validation.
3358fn parse_inherit_env_at(
3359    toks: &[Tok],
3360    pos: usize,
3361    stmt: usize,
3362) -> Result<Option<(StepKind, usize)>, TokenError> {
3363    // The bracket rides gapped (`sep`); anything else misses and
3364    // generic fails it in lowering.
3365    let bracket = match toks.get(pos + 1) {
3366        Some(t)
3367            if !t.joint
3368                && matches!(
3369                    &t.kind,
3370                    TokKind::Group {
3371                        delim: GroupDelim::Bracket,
3372                        ..
3373                    }
3374                ) =>
3375        {
3376            Some(t)
3377        }
3378        _ => None,
3379    };
3380    let Some(bracket) = bracket else {
3381        return Ok(None);
3382    };
3383    let inner = match &bracket.kind {
3384        TokKind::Group { inner, .. } => inner,
3385        _ => unreachable!(),
3386    };
3387    match parse_inherit_keys(inner, stmt)? {
3388        Some(keys) => Ok(Some((StepKind::InheritEnv { keys }, 2))),
3389        None => Ok(None),
3390    }
3391}
3392
3393/// Parse a brace block body into steps: statements split and lower
3394/// recursively, each keeping its own guard. `mark` selects scope
3395/// marking: top-level guard-block bodies mark (each nesting level
3396/// bumps first/last); wrapper bodies
3397/// (`IF`/`FOR`/`WHILE`/`FUNC`/`REMOTE`/wrappers/io-blocks) never mark
3398/// (block-element lowering pins 0/0).
3399fn parse_body_steps(
3400    inner: &[Tok],
3401    stmt: usize,
3402    ctx: &ParseCtx,
3403    mark: bool,
3404) -> Result<Vec<Step>, TokenError> {
3405    // One function/import scope per braced body (mirroring the
3406    // runtime push/pop boundary): same-block
3407    // `FUNC` redefinition errors, nested shadowing stays allowed.
3408    // Errors abort the whole parse (frames discarded with it), so no
3409    // exit runs on failure.
3410    ctx.funcs.borrow_mut().push(HashSet::new());
3411    ctx.imports.borrow_mut().push(Vec::new());
3412    // Nested splits count lines from the enclosing statement's line
3413    // (headers are single-line, so the brace shares it). Save and
3414    // restore the discipline around the loop: sibling bodies after
3415    // this one must see the enclosing line, not the last inner one.
3416    // (On error the parse aborts and the context is discarded.)
3417    let saved = *ctx.current_line.borrow();
3418    let mut out = Vec::new();
3419    for s in split_statements(inner, saved)? {
3420        // The innermost statement owns error positions: record it for
3421        // nested splits and stamp failures that have none yet (deeper
3422        // frames stamp first, so this never overwrites real positions).
3423        *ctx.current_line.borrow_mut() = s.line;
3424        out.extend(
3425            lower_stmt_steps(&s, stmt, ctx, true, mark).map_err(|e| stamp_pos(e, s.line, s.col))?,
3426        );
3427    }
3428    *ctx.current_line.borrow_mut() = saved;
3429    ctx.funcs.borrow_mut().pop();
3430    ctx.imports.borrow_mut().pop();
3431    Ok(out)
3432}
3433
3434/// Single (non-block) `WITH_IO`: bindings plus an optional inner
3435/// command. `None` on shape miss (no/gapped bracket: generic fails
3436/// it in lowering). A brace in single-inner position is
3437/// the grammar's pending-guard error, never an io-block; a bare
3438/// bracket leaks the transient `WithIoBlock` into the body (probed).
3439fn parse_with_io_single(
3440    toks: &[Tok],
3441    pos: usize,
3442    stmt: usize,
3443    ctx: &ParseCtx,
3444) -> Result<Option<(StepKind, usize)>, TokenError> {
3445    let bracket = match toks.get(pos + 1) {
3446        // The bracket rides gapped (`sep`); anything else misses the
3447        // shape and generic fails it in lowering.
3448        Some(t)
3449            if !t.joint
3450                && matches!(
3451                    &t.kind,
3452                    TokKind::Group {
3453                        delim: GroupDelim::Bracket,
3454                        ..
3455                    }
3456                ) =>
3457        {
3458            t
3459        }
3460        _ => return Ok(None),
3461    };
3462    let inner = match &bracket.kind {
3463        TokKind::Group { inner, .. } => inner.clone(),
3464        _ => unreachable!(),
3465    };
3466    let bindings = match parse_io_bindings(&inner, stmt)? {
3467        Some(bindings) => bindings,
3468        None => return Ok(None),
3469    };
3470    let rest = pos + 2;
3471    // A brace directly after the bracket is the pending-guard error
3472    // in single-inner position (probed); templates fall to generic.
3473    if let Some(next) = toks.get(rest)
3474        && matches!(
3475            &next.kind,
3476            TokKind::Group {
3477                delim: GroupDelim::Brace,
3478                ..
3479            }
3480        )
3481        && !is_template_brace(next)
3482    {
3483        return Err(TokenError {
3484            stmt,
3485            msg: "'{' without a pending guard".to_string(),
3486            line: 0,
3487            col: 0,
3488            kind: None,
3489        });
3490    }
3491    if rest >= toks.len() {
3492        // Bare bracket: the transient block node leaks into wrapper
3493        // bodies (statement level never reaches
3494        // here; the splitter holds it for `{`).
3495        return Ok(Some((StepKind::WithIoBlock { bindings }, 2)));
3496    }
3497    // A joint follower misses the inner `sep`: the bracket stands
3498    // bare (probed `TIMEOUT 10s WITH_IO [..]ECHO hi` yields the
3499    // transient node) and trailing elements loop on outside.
3500    if toks[rest].joint {
3501        return Ok(Some((StepKind::WithIoBlock { bindings }, 2)));
3502    }
3503    let (cmd, used) = parse_single_inner(
3504        toks,
3505        rest,
3506        stmt,
3507        ctx,
3508        InnerRules {
3509            allow_await: false,
3510            allow_with_io: true,
3511        },
3512    )?;
3513    let span = lowering_ctx(stmt);
3514    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| TokenError {
3515        stmt,
3516        msg: e.to_string(),
3517        line: 0,
3518        col: 0,
3519        kind: None,
3520    })?;
3521    let kind = StepKind::WithIo {
3522        bindings,
3523        cmd: Box::new(cmd),
3524    };
3525    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
3526        stmt,
3527        msg: e.to_string(),
3528        line: 0,
3529        col: 0,
3530        kind: None,
3531    })?;
3532    Ok(Some((kind, 2 + used)))
3533}
3534
3535/// Single (non-block) `TIMEOUT`: duration plus one inner command.
3536/// `None` on shape miss (bad duration, missing/joint inner: generic
3537/// fails it in lowering). Blocks parse inline; the body
3538/// holds one step for single inners.
3539fn parse_timeout_single(
3540    toks: &[Tok],
3541    pos: usize,
3542    stmt: usize,
3543    ctx: &ParseCtx,
3544) -> Result<Option<(StepKind, usize)>, TokenError> {
3545    let Some((duration, dused)) = parse_timeout_duration_at(toks, pos + 1, stmt)? else {
3546        return Ok(None);
3547    };
3548    let rest = pos + 1 + dused;
3549    let Some(next) = toks.get(rest) else {
3550        // `TIMEOUT 10s` alone is a generic instruction (lowering
3551        // fails it, probed), never a bare wrapper.
3552        return Ok(None);
3553    };
3554    if next.joint {
3555        return Ok(None);
3556    }
3557    let body = if matches!(
3558        &next.kind,
3559        TokKind::Group {
3560            delim: GroupDelim::Brace,
3561            ..
3562        }
3563    ) && !is_template_brace(next)
3564    {
3565        let inner = match &next.kind {
3566            TokKind::Group { inner, .. } => inner.clone(),
3567            _ => unreachable!(),
3568        };
3569        let steps = parse_body_steps(&inner, stmt, ctx, false)?;
3570        (steps, 1)
3571    } else {
3572        let (cmd, used) = parse_single_inner(
3573            toks,
3574            rest,
3575            stmt,
3576            ctx,
3577            InnerRules {
3578                allow_await: true,
3579                allow_with_io: true,
3580            },
3581        )?;
3582        (
3583            vec![Step {
3584                guard: None,
3585                kind: cmd,
3586                scope_enter: 0,
3587                scope_exit: 0,
3588                line: 0,
3589                col: 0,
3590            }],
3591            used,
3592        )
3593    };
3594    let kind = StepKind::Timeout {
3595        duration,
3596        body: body.0,
3597    };
3598    let span = lowering_ctx(stmt);
3599    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
3600        stmt,
3601        msg: e.to_string(),
3602        line: 0,
3603        col: 0,
3604        kind: None,
3605    })?;
3606    Ok(Some((kind, 1 + dused + body.1)))
3607}
3608
3609/// Single (non-block) `ISOLATED`: one inner command or block; the
3610/// body rewrites nested `INHERIT_ENV` through the shared pass.
3611/// `None` on shape miss (missing/joint inner: generic fails it).
3612fn parse_isolated_single(
3613    toks: &[Tok],
3614    pos: usize,
3615    stmt: usize,
3616    ctx: &ParseCtx,
3617) -> Result<Option<(StepKind, usize)>, TokenError> {
3618    let Some(next) = toks.get(pos + 1) else {
3619        return Ok(None);
3620    };
3621    if next.joint {
3622        return Ok(None);
3623    }
3624    let (mut body, used) = if matches!(
3625        &next.kind,
3626        TokKind::Group {
3627            delim: GroupDelim::Brace,
3628            ..
3629        }
3630    ) && !is_template_brace(next)
3631    {
3632        let inner = match &next.kind {
3633            TokKind::Group { inner, .. } => inner.clone(),
3634            _ => unreachable!(),
3635        };
3636        (parse_body_steps(&inner, stmt, ctx, false)?, 1)
3637    } else {
3638        let (cmd, used) = parse_single_inner(
3639            toks,
3640            pos + 1,
3641            stmt,
3642            ctx,
3643            InnerRules {
3644                allow_await: true,
3645                allow_with_io: true,
3646            },
3647        )?;
3648        (
3649            vec![Step {
3650                guard: None,
3651                kind: cmd,
3652                scope_enter: 0,
3653                scope_exit: 0,
3654                line: 0,
3655                col: 0,
3656            }],
3657            used,
3658        )
3659    };
3660    crate::commands::rewrite_isolated_inherit(&mut body);
3661    Ok(Some((StepKind::Isolated { body }, 1 + used)))
3662}
3663
3664/// Single (non-block) `ASYNC`: one inner command or block (blocks
3665/// admit a joint brace, like `async_statement_block`'s `sep?`).
3666/// Top-level `WITH_IO` steps fail through the shared reject; the
3667/// `LET` path never scans (probed: it accepts). `None` on shape
3668/// miss (missing/joint-single inner: generic fails it).
3669fn parse_async_single(
3670    toks: &[Tok],
3671    pos: usize,
3672    stmt: usize,
3673    ctx: &ParseCtx,
3674) -> Result<Option<(StepKind, usize)>, TokenError> {
3675    let Some(next) = toks.get(pos + 1) else {
3676        return Ok(None);
3677    };
3678    // Block form admits a joint brace (`ASYNC{...}`, probed); the
3679    // single form needs its `sep`.
3680    if matches!(
3681        &next.kind,
3682        TokKind::Group {
3683            delim: GroupDelim::Brace,
3684            ..
3685        }
3686    ) && !is_template_brace(next)
3687    {
3688        let inner = match &next.kind {
3689            TokKind::Group { inner, .. } => inner.clone(),
3690            _ => unreachable!(),
3691        };
3692        let body = parse_body_steps(&inner, stmt, ctx, false)?;
3693        let span = lowering_ctx(stmt);
3694        crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| TokenError {
3695            stmt,
3696            msg: e.to_string(),
3697            line: 0,
3698            col: 0,
3699            kind: None,
3700        })?;
3701        let kind = StepKind::AsyncBlock { body };
3702        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
3703            stmt,
3704            msg: e.to_string(),
3705            line: 0,
3706            col: 0,
3707            kind: None,
3708        })?;
3709        return Ok(Some((kind, 2)));
3710    }
3711    if next.joint {
3712        return Ok(None);
3713    }
3714    let (cmd, used) = parse_single_inner(
3715        toks,
3716        pos + 1,
3717        stmt,
3718        ctx,
3719        InnerRules {
3720            allow_await: false,
3721            allow_with_io: false,
3722        },
3723    )?;
3724    let body = vec![Step {
3725        guard: None,
3726        kind: cmd,
3727        scope_enter: 0,
3728        scope_exit: 0,
3729        line: 0,
3730        col: 0,
3731    }];
3732    let span = lowering_ctx(stmt);
3733    crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| TokenError {
3734        stmt,
3735        msg: e.to_string(),
3736        line: 0,
3737        col: 0,
3738        kind: None,
3739    })?;
3740    let kind = StepKind::AsyncBlock { body };
3741    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
3742        stmt,
3743        msg: e.to_string(),
3744        line: 0,
3745        col: 0,
3746        kind: None,
3747    })?;
3748    Ok(Some((kind, 1 + used)))
3749}
3750
3751// ---- Block statements, directives, REMOTE ----
3752// `IF`/`FOR`/`WHILE`/`FUNC` parse their headers token-natively with
3753// miss-to-generic fallback (the grammar's committed `instruction`
3754// path); bodies lower recursively with pushed scopes. `TYPE` builds
3755// aliases through a maximal type-shape match; `IMPORT`/`EXPORT` are
3756// zero-step frame/table directives; `REMOTE` validates targets,
3757// bindings, bodies, and outer-call containment through the shared
3758// validators. Guard blocks fold guards with scope markers at top
3759// level and mirror the nested quirk formula in bodies. A whole-script
3760// post-pass runs the shared validations (prelude order, COPY
3761// placement, EXPORT membership).
3762
3763/// Uppercase identifier mirror (`func_ident`, `type_name`,
3764/// `import_module`): ASCII upper start, upper/digit/`_` rest.
3765fn is_upper_ident(w: &str) -> bool {
3766    !w.is_empty()
3767        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
3768        && w.chars()
3769            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
3770}
3771
3772/// Lowercase identifier mirror (`field_name`): ASCII lower start,
3773/// lower/digit/`_` rest.
3774fn is_lower_ident(w: &str) -> bool {
3775    !w.is_empty()
3776        && w.chars().next().is_some_and(|c| c.is_ascii_lowercase())
3777        && w.chars()
3778            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
3779}
3780
3781/// `$name` with gapless adjacency (atomic `dollar_ident`); `None` on
3782/// shape miss (the caller falls back to generic, which fails in
3783/// lowering like the grammar's committed `instruction`).
3784fn peek_dollar_var(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
3785    match (toks.get(pos), toks.get(pos + 1)) {
3786        (Some(dollar), Some(name))
3787            if matches!(&dollar.kind, TokKind::Punct('$'))
3788                && name.joint
3789                && matches!(&name.kind, TokKind::Word(w) if is_ident_word(w)) =>
3790        {
3791            match &name.kind {
3792                TokKind::Word(w) => Some((w.clone(), 2)),
3793                _ => unreachable!(),
3794            }
3795        }
3796        _ => None,
3797    }
3798}
3799
3800/// Skip statement-level newlines (multi-line `<...>` shapes ride
3801/// them into the body) before the next type token. Narrower than
3802/// `gap_nl` on purpose: comments keep failing here exactly like
3803/// single-line shapes, so only the separator moves.
3804fn skip_type_nl(toks: &[Tok], mut p: usize) -> usize {
3805    while matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Newline)) {
3806        p += 1;
3807    }
3808    p
3809}
3810
3811/// Maximal `type_tag` match over toks (non-atomic: gaps free
3812/// everywhere): atoms with `<>` args, `|` unions, `name?:` fields.
3813/// Returns the exclusive end index, or `None` on shape miss.
3814fn parse_type_shape(toks: &[Tok], pos: usize) -> Option<usize> {
3815    let mut p = parse_type_atom(toks, skip_type_nl(toks, pos))?;
3816    loop {
3817        let q = skip_type_nl(toks, p);
3818        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('|'))) {
3819            return Some(p);
3820        }
3821        p = parse_type_atom(toks, skip_type_nl(toks, q + 1))?;
3822    }
3823}
3824
3825fn parse_type_atom(toks: &[Tok], pos: usize) -> Option<usize> {
3826    let pos = skip_type_nl(toks, pos);
3827    match toks.get(pos).map(|t| &t.kind) {
3828        Some(TokKind::Word(w)) if is_upper_ident(w) => {}
3829        _ => return None,
3830    }
3831    let mut p = skip_type_nl(toks, pos + 1);
3832    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('<'))) {
3833        p = parse_type_args(toks, skip_type_nl(toks, p + 1))?;
3834        p = skip_type_nl(toks, p);
3835        if !matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('>'))) {
3836            return None;
3837        }
3838        p += 1;
3839    }
3840    Some(p)
3841}
3842
3843fn parse_type_args(toks: &[Tok], pos: usize) -> Option<usize> {
3844    let mut p = parse_type_field(toks, skip_type_nl(toks, pos))?;
3845    loop {
3846        let q = skip_type_nl(toks, p);
3847        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(','))) {
3848            return Some(p);
3849        }
3850        p = parse_type_field(toks, skip_type_nl(toks, q + 1))?;
3851    }
3852}
3853
3854fn parse_type_field(toks: &[Tok], pos: usize) -> Option<usize> {
3855    let mut p = skip_type_nl(toks, pos);
3856    // Optional `name?:` prefix (lowercase names only, like the
3857    // grammar's `field_name`).
3858    if let Some(TokKind::Word(w)) = toks.get(p).map(|t| &t.kind)
3859        && is_lower_ident(w)
3860    {
3861        let mut q = skip_type_nl(toks, p + 1);
3862        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('?'))) {
3863            q = skip_type_nl(toks, q + 1);
3864        }
3865        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
3866            p = skip_type_nl(toks, q + 1);
3867        }
3868    }
3869    parse_type_shape(toks, p)
3870}
3871
3872/// Single (non-block) `IF`: condition plus then-block with an
3873/// opportunistic `ELSE` chain (a malformed `ELSE` stays for the
3874/// element loop, which fails it in lowering exactly like the
3875/// grammar). `None` on shape miss (missing/joint-agnostic block or
3876/// bad condition: generic fails it); expression failures
3877/// with an inline-block failure propagate (blocks lower here, so
3878/// their errors surface directly).
3879fn parse_if_at(
3880    toks: &[Tok],
3881    pos: usize,
3882    stmt: usize,
3883    ctx: &ParseCtx,
3884) -> Result<Option<(StepKind, usize)>, TokenError> {
3885    // Condition entry skips leading gap comments (`IF` uses `gap`).
3886    let mut lead = Cursor::expr(&toks[pos + 1..], stmt);
3887    lead.skip_gap();
3888    let mut cur = Cursor::expr(&toks[pos + 1 + lead.pos..], stmt);
3889    let cond = match parse_expr_checked(&mut cur, ctx) {
3890        Ok(expr) => expr,
3891        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
3892        Err(_) => return Ok(None),
3893    };
3894    let cond_end = pos + 1 + lead.pos + cur.pos;
3895    // Then-block: any gap (`gap` zero-width), never a template.
3896    let then_brace = match toks.get(cond_end) {
3897        Some(t)
3898            if matches!(
3899                &t.kind,
3900                TokKind::Group {
3901                    delim: GroupDelim::Brace,
3902                    ..
3903                }
3904            ) && !is_template_brace(t) =>
3905        {
3906            t
3907        }
3908        _ => return Ok(None),
3909    };
3910    let then_inner = match &then_brace.kind {
3911        TokKind::Group { inner, .. } => inner.clone(),
3912        _ => unreachable!(),
3913    };
3914    let then_body = parse_body_steps(&then_inner, stmt, ctx, false)?;
3915    let mut p = cond_end + 1;
3916    // Gap comments between the blocks and `ELSE` vanish (merge
3917    // junctions contribute newlines, crossed like `blank*`).
3918    {
3919        let mut gcur = Cursor::expr(&toks[p..], stmt);
3920        gcur.skip_gap_nl();
3921        p += gcur.pos;
3922    }
3923    let mut else_ifs = Vec::new();
3924    let mut else_body = None;
3925    loop {
3926        // `ELSE IF cond block`: any gaps (non-atomic chain).
3927        let is_else_if = matches!(
3928            toks.get(p).map(|t| &t.kind),
3929            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
3930        ) && matches!(
3931            toks.get(p + 1).map(|t| &t.kind),
3932            Some(TokKind::Word(w)) if w == KEYWORD_IF
3933        );
3934        if is_else_if {
3935            let mut ecur = Cursor::expr(&toks[p + 2..], stmt);
3936            ecur.skip_gap();
3937            let econd = match parse_expr_checked(&mut ecur, ctx) {
3938                Ok(expr) => expr,
3939                Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
3940                Err(_) => break,
3941            };
3942            let ebrace = p + 2 + ecur.pos;
3943            let eblock_ok = matches!(
3944                toks.get(ebrace).map(|t| &t.kind),
3945                Some(TokKind::Group {
3946                    delim: GroupDelim::Brace,
3947                    ..
3948                })
3949            ) && toks.get(ebrace).is_some_and(|t| !is_template_brace(t));
3950            if !eblock_ok {
3951                break;
3952            }
3953            let einner = match &toks[ebrace].kind {
3954                TokKind::Group { inner, .. } => inner.clone(),
3955                _ => unreachable!(),
3956            };
3957            let ebody = parse_body_steps(&einner, stmt, ctx, false)?;
3958            else_ifs.push((Box::new(econd), ebody));
3959            p = ebrace + 1;
3960            // Gap comments before a further `ELSE` vanish too
3961            // (merge junctions contribute newlines).
3962            {
3963                let mut gcur = Cursor::expr(&toks[p..], stmt);
3964                gcur.skip_gap_nl();
3965                p += gcur.pos;
3966            }
3967            continue;
3968        }
3969        // `ELSE block`: same opportunism (a bare `ELSE` stays for
3970        // the loop, failing in lowering like the grammar).
3971        let is_else = matches!(
3972            toks.get(p).map(|t| &t.kind),
3973            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
3974        ) && matches!(
3975            toks.get(p + 1).map(|t| &t.kind),
3976            Some(TokKind::Group {
3977                delim: GroupDelim::Brace,
3978                ..
3979            })
3980        ) && toks.get(p + 1).is_some_and(|t| !is_template_brace(t));
3981        if !is_else {
3982            break;
3983        }
3984        let einner = match &toks[p + 1].kind {
3985            TokKind::Group { inner, .. } => inner.clone(),
3986            _ => unreachable!(),
3987        };
3988        else_body = Some(parse_body_steps(&einner, stmt, ctx, false)?);
3989        p += 2;
3990        break;
3991    }
3992    let kind = StepKind::If {
3993        cond: Box::new(cond),
3994        then_body,
3995        else_ifs,
3996        else_body,
3997    };
3998    Ok(Some((kind, p - pos)))
3999}
4000
4001/// Single (non-block) `FOR`: `$var[: TYPE] (, $var[: TYPE])? IN
4002/// expr` plus block. Header shapes miss to generic (a third variable,
4003/// a missing block, a bad name all fail in lowering like the
4004/// grammar); completed headers validate counts and key types loudly.
4005/// Expression failures from inline blocks propagate (blocks lower
4006/// here); other expression failures miss (generic fails them like a
4007/// committed `instruction` would).
4008fn parse_for_at(
4009    toks: &[Tok],
4010    pos: usize,
4011    stmt: usize,
4012    ctx: &ParseCtx,
4013) -> Result<Option<(StepKind, usize)>, TokenError> {
4014    let mut p = pos + 1;
4015    let mut idents = Vec::new();
4016    let mut types = Vec::new();
4017    // First `$var[: TYPE]` (gapless `$var`; gaps free elsewhere).
4018    let Some((var1, _)) = peek_dollar_var(toks, p) else {
4019        return Ok(None);
4020    };
4021    idents.push(var1);
4022    p += 2;
4023    let mut cur = Cursor::expr(&toks[p..], stmt);
4024    cur.skip_gap();
4025    p += cur.pos;
4026    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4027        p += 1;
4028        let mut tcur = Cursor::expr(&toks[p..], stmt);
4029        tcur.skip_gap();
4030        let tstart = p + tcur.pos;
4031        let Some(tend) = parse_type_shape(toks, tstart) else {
4032            return Ok(None);
4033        };
4034        // `render_type_region` canonicalizes (shared spelling).
4035        types.push(render_type_region(&toks[tstart..tend], stmt)?);
4036        p = tend;
4037    }
4038    // Optional `, $var2[: TYPE2]`.
4039    {
4040        let mut ccur = Cursor::expr(&toks[p..], stmt);
4041        ccur.skip_gap();
4042        if matches!(
4043            ccur.toks.get(ccur.pos).map(|t| &t.kind),
4044            Some(TokKind::Punct(','))
4045        ) {
4046            ccur.pos += 1;
4047            ccur.skip_gap();
4048            let base = p + ccur.pos;
4049            let Some((var2, _)) = peek_dollar_var(toks, base) else {
4050                return Ok(None);
4051            };
4052            idents.push(var2);
4053            let mut q = base + 2;
4054            let mut qcur = Cursor::expr(&toks[q..], stmt);
4055            qcur.skip_gap();
4056            q += qcur.pos;
4057            if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4058                q += 1;
4059                let mut tcur = Cursor::expr(&toks[q..], stmt);
4060                tcur.skip_gap();
4061                let tstart = q + tcur.pos;
4062                let Some(tend) = parse_type_shape(toks, tstart) else {
4063                    return Ok(None);
4064                };
4065                types.push(render_type_region(&toks[tstart..tend], stmt)?);
4066                q = tend;
4067            }
4068            p = q;
4069        }
4070    }
4071    // `IN expr block`.
4072    {
4073        let mut icur = Cursor::expr(&toks[p..], stmt);
4074        icur.skip_gap();
4075        if !matches!(
4076            icur.toks.get(icur.pos).map(|t| &t.kind),
4077            Some(TokKind::Word(w)) if w == KEYWORD_IN
4078        ) {
4079            return Ok(None);
4080        }
4081        icur.pos += 1;
4082        p += icur.pos;
4083    }
4084    let mut ecur = Cursor::expr(&toks[p..], stmt);
4085    ecur.skip_gap();
4086    let in_expr = match parse_expr_checked(&mut ecur, ctx) {
4087        Ok(expr) => expr,
4088        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4089        Err(_) => return Ok(None),
4090    };
4091    p += ecur.pos;
4092    let block_ok = matches!(
4093        toks.get(p).map(|t| &t.kind),
4094        Some(TokKind::Group {
4095            delim: GroupDelim::Brace,
4096            ..
4097        })
4098    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4099    if !block_ok {
4100        return Ok(None);
4101    }
4102    let inner = match &toks[p].kind {
4103        TokKind::Group { inner, .. } => inner.clone(),
4104        _ => unreachable!(),
4105    };
4106    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4107    p += 1;
4108    if idents.len() != types.len() {
4109        return Err(TokenError {
4110            stmt,
4111            msg: format!(
4112                "FOR requires explicit types: FOR $item: TYPE IN <expr> (got {} vars, {} types)",
4113                idents.len(),
4114                types.len()
4115            ),
4116            line: 0,
4117            col: 0,
4118            kind: Some(ParseErrorKind::Validation {
4119                command: KEYWORD_FOR.to_string(),
4120            }),
4121        });
4122    }
4123    let (key_var, key_type, var, var_type) = match idents.len() {
4124        1 => (
4125            None,
4126            None,
4127            idents.into_iter().next().unwrap_or_default(),
4128            types.into_iter().next().unwrap_or_default(),
4129        ),
4130        2 => {
4131            let mut iv = idents.into_iter();
4132            let mut tv = types.into_iter();
4133            (
4134                Some(iv.next().unwrap_or_default()),
4135                Some(tv.next().unwrap_or_default()),
4136                iv.next().unwrap_or_default(),
4137                tv.next().unwrap_or_default(),
4138            )
4139        }
4140        _ => {
4141            return Err(TokenError {
4142                stmt,
4143                msg: "FOR requires one or two variables".to_string(),
4144                line: 0,
4145                col: 0,
4146                kind: Some(ParseErrorKind::Validation {
4147                    command: KEYWORD_FOR.to_string(),
4148                }),
4149            });
4150        }
4151    };
4152    if let Some(kt) = &key_type
4153        && kt != crate::TypeTag::String.name()
4154        && kt != crate::TypeTag::Int.name()
4155    {
4156        return Err(TokenError {
4157            stmt,
4158            msg: format!("FOR key variable must be INT or STRING, got {kt}"),
4159            line: 0,
4160            col: 0,
4161            kind: Some(ParseErrorKind::Validation {
4162                command: KEYWORD_FOR.to_string(),
4163            }),
4164        });
4165    }
4166    let kind = StepKind::For {
4167        key_var,
4168        key_type,
4169        var,
4170        var_type,
4171        in_expr,
4172        body,
4173    };
4174    Ok(Some((kind, p - pos)))
4175}
4176
4177/// Single (non-block) `WHILE`: condition plus block. `None` on
4178/// shape miss (missing block: generic fails it);
4179/// expression failures from inline blocks propagate, others miss
4180/// (generic fails them like a committed `instruction` would).
4181/// No leading gap-skip: `WHILE` takes `sep`, so a joint follower
4182/// never reaches here with a valid shape... (misses fall through
4183/// the same way regardless).
4184fn parse_while_single(
4185    toks: &[Tok],
4186    pos: usize,
4187    stmt: usize,
4188    ctx: &ParseCtx,
4189) -> Result<Option<(StepKind, usize)>, TokenError> {
4190    let mut cur = Cursor::expr(&toks[pos + 1..], stmt);
4191    let cond = match parse_expr_checked(&mut cur, ctx) {
4192        Ok(expr) => expr,
4193        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4194        Err(_) => return Ok(None),
4195    };
4196    let brace = pos + 1 + cur.pos;
4197    let block_ok = matches!(
4198        toks.get(brace).map(|t| &t.kind),
4199        Some(TokKind::Group {
4200            delim: GroupDelim::Brace,
4201            ..
4202        })
4203    ) && toks.get(brace).is_some_and(|t| !is_template_brace(t));
4204    if !block_ok {
4205        return Ok(None);
4206    }
4207    let inner = match &toks[brace].kind {
4208        TokKind::Group { inner, .. } => inner.clone(),
4209        _ => unreachable!(),
4210    };
4211    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4212    let kind = StepKind::While {
4213        cond: Box::new(cond),
4214        body,
4215    };
4216    Ok(Some((kind, brace + 1 - pos)))
4217}
4218
4219/// Single (non-block) `FUNC`: name, parenthesized params, block. The
4220/// shape parses purely first (misses fall to generic, declaring
4221/// nothing — the grammar only lowers matched pairs); then the name
4222/// declares in the enclosing scope before the body lowers (so
4223/// recursion resolves), and the body pushes a fresh scope.
4224/// Duplicates, reserved shadows, and parameter dupes fail loudly.
4225fn parse_func_at(
4226    toks: &[Tok],
4227    pos: usize,
4228    stmt: usize,
4229    ctx: &ParseCtx,
4230) -> Result<Option<(StepKind, usize)>, TokenError> {
4231    let fail = |msg: String| TokenError {
4232        stmt,
4233        msg,
4234        line: 0,
4235        col: 0,
4236        kind: Some(ParseErrorKind::Validation {
4237            command: KEYWORD_FUNC.to_string(),
4238        }),
4239    };
4240    // Phase 1 (pure shape): name, parens, params, block presence.
4241    // Name: UPPERCASE ident (lowercase misses to generic, probed).
4242    let def_name = match toks.get(pos + 1).map(|t| &t.kind) {
4243        Some(TokKind::Word(w))
4244            if crate::resolve::check_func_ident(&lowering_ctx(stmt), w).is_ok() =>
4245        {
4246            w.clone()
4247        }
4248        _ => return Ok(None),
4249    };
4250    // Paren group at any gap (`gap` zero-width): params live inside
4251    // its inner tokens, parsed with `gap` discipline (newlines miss,
4252    // like the grammar).
4253    let mut p = pos + 2;
4254    let paren_inner = match toks.get(p).map(|t| &t.kind) {
4255        Some(TokKind::Group {
4256            delim: GroupDelim::Paren,
4257            inner,
4258            ..
4259        }) => inner.clone(),
4260        _ => return Ok(None),
4261    };
4262    p += 1;
4263    let mut params = Vec::new();
4264    {
4265        let mut pcur = Cursor::expr(&paren_inner, stmt);
4266        pcur.skip_gap();
4267        if !pcur.done() {
4268            loop {
4269                let base = pcur.pos;
4270                let Some((pname, _)) = peek_dollar_var(&paren_inner, base) else {
4271                    return Ok(None);
4272                };
4273                pcur.pos = base + 2;
4274                pcur.skip_gap();
4275                if !pcur.eat_punct(':') {
4276                    return Ok(None);
4277                }
4278                pcur.skip_gap();
4279                let tstart = pcur.pos;
4280                let Some(tend) = parse_type_shape(&paren_inner, tstart) else {
4281                    return Ok(None);
4282                };
4283                // Post-match the span holds words/puncts only, so the
4284                // shared renderer cannot fail; stay failed regardless.
4285                let ptype =
4286                    render_type_region(&paren_inner[tstart..tend], stmt).unwrap_or_default();
4287                params.push((pname, ptype));
4288                pcur.pos = tend;
4289                pcur.skip_gap();
4290                if pcur.eat_punct(',') {
4291                    pcur.skip_gap();
4292                    // Trailing comma misses (a param must follow).
4293                    if pcur.done() {
4294                        return Ok(None);
4295                    }
4296                    continue;
4297                }
4298                break;
4299            }
4300            // Trailing junk (including newlines) misses to generic.
4301            if !pcur.done() {
4302                return Ok(None);
4303            }
4304        }
4305    }
4306    // Block at any gap (never a template); missing blocks miss to
4307    // generic (probed `FUNC FOO() ECHO hi`).
4308    let block_ok = matches!(
4309        toks.get(p).map(|t| &t.kind),
4310        Some(TokKind::Group {
4311            delim: GroupDelim::Brace,
4312            ..
4313        })
4314    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4315    if !block_ok {
4316        return Ok(None);
4317    }
4318    // Phase 2 (effects): reserved shadows and same-scope duplicates
4319    // fail at the definition line, verbatim.
4320    if ctx.reserved.contains(&def_name) || ctx.modules.reserved_base_names().contains(&def_name) {
4321        return Err(fail(format!(
4322            "FUNC {def_name} cannot shadow reserved function `{def_name}`"
4323        )));
4324    }
4325    if !ctx.declare_func(&def_name) {
4326        return Err(fail(format!(
4327            "duplicate function `{def_name}` in same scope"
4328        )));
4329    }
4330    let mut seen = HashSet::new();
4331    for (pname, _) in &params {
4332        if !seen.insert(pname.clone()) {
4333            return Err(fail(format!(
4334                "FUNC {def_name} declares duplicate parameter ${pname}"
4335            )));
4336        }
4337    }
4338    let inner = match &toks[p].kind {
4339        TokKind::Group { inner, .. } => inner.clone(),
4340        _ => unreachable!(),
4341    };
4342    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4343    let kind = StepKind::FuncDef {
4344        name: def_name,
4345        params,
4346        body,
4347        docs: None,
4348    };
4349    Ok(Some((kind, p + 1 - pos)))
4350}
4351
4352/// `REMOTE` header bindings `[$var, env:KEY]` over a bracket
4353/// group's inner tokens: comma-separated, newlines and comments free
4354/// like `gap_nl`. `$`+name and `env`+`:`+key all ride gapless (the
4355/// enclosing rule is compound-atomic). Empty lists parse (probed);
4356/// anything else misses the shape (`None`: generic fails it like
4357/// the grammar's dropped optional).
4358#[allow(clippy::type_complexity)]
4359fn parse_remote_bindings(
4360    inner: &[Tok],
4361    stmt: usize,
4362) -> Result<Option<(Vec<String>, Vec<String>)>, TokenError> {
4363    let _ = stmt;
4364    let mut parts: Vec<&[Tok]> = Vec::new();
4365    let mut start = 0;
4366    for (i, tok) in inner.iter().enumerate() {
4367        if matches!(&tok.kind, TokKind::Punct(',')) {
4368            parts.push(&inner[start..i]);
4369            start = i + 1;
4370        }
4371    }
4372    parts.push(&inner[start..]);
4373    // An empty list (`[]`, whitespace/comment-only) holds no bindings.
4374    if parts.len() == 1
4375        && parts[0]
4376            .iter()
4377            .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
4378    {
4379        return Ok(Some((Vec::new(), Vec::new())));
4380    }
4381    let mut vars = Vec::new();
4382    let mut env = Vec::new();
4383    for part in parts {
4384        // Edges admit gaps, newlines, and comments, like `gap_nl`.
4385        let mut part = part;
4386        while matches!(
4387            part.first().map(|t| &t.kind),
4388            Some(TokKind::Newline | TokKind::Comment(_))
4389        ) {
4390            part = &part[1..];
4391        }
4392        while matches!(
4393            part.last().map(|t| &t.kind),
4394            Some(TokKind::Newline | TokKind::Comment(_))
4395        ) {
4396            part = &part[..part.len() - 1];
4397        }
4398        // `$var`: gapless `$` + ident.
4399        if matches!(part.first().map(|t| &t.kind), Some(TokKind::Punct('$'))) && part.len() == 2 {
4400            if part[1].joint
4401                && let TokKind::Word(w) = &part[1].kind
4402                && is_ident_word(w)
4403            {
4404                vars.push(w.clone());
4405                continue;
4406            }
4407            return Ok(None);
4408        }
4409        // `env:KEY`: gapless triple with an uppercase key.
4410        if part.len() == 3
4411            && matches!(&part[0].kind, TokKind::Word(w) if w == "env")
4412            && matches!(&part[1].kind, TokKind::Punct(':'))
4413            && part[1].joint
4414            && part[2].joint
4415        {
4416            if let TokKind::Word(k) = &part[2].kind
4417                && is_env_key(k)
4418            {
4419                env.push(k.clone());
4420                continue;
4421            }
4422            return Ok(None);
4423        }
4424        return Ok(None);
4425    }
4426    Ok(Some((vars, env)))
4427}
4428
4429/// `IMPORT` statement at `pos` (#115): module form (`IMPORT MOD`,
4430/// `IMPORT [A, B]`), file form (`IMPORT "p" AS A`,
4431/// `IMPORT ["p" AS A]`), mixed/multi forms
4432/// (`IMPORT [STD, "p" AS A, "q" AS B]`, multi-line included), and
4433/// selective harvests (`IMPORT [[F, G FROM "p" (AS A)?]]`).
4434/// Returns module names plus `ImportFile`/`ImportFuncs` steps in source
4435/// order, plus tokens consumed (relative to `pos`), or `None` on shape
4436/// miss (generic lowering fails it like the grammar). Validation is
4437/// hard: unknown modules, bad names, collisions, templates, and remote
4438/// URLs fail here, and validated entries register immediately
4439/// (modules, aliases, and bare harvest names share the innermost
4440/// frames).
4441type ImportEntries = (Vec<String>, Vec<StepKind>);
4442
4443fn parse_import_statement(
4444    toks: &[Tok],
4445    pos: usize,
4446    stmt: usize,
4447    ctx: &ParseCtx,
4448) -> Result<Option<(ImportEntries, usize)>, TokenError> {
4449    let fail = |msg: String| TokenError {
4450        stmt,
4451        msg,
4452        line: 0,
4453        col: 0,
4454        kind: Some(ParseErrorKind::Validation {
4455            command: KEYWORD_IMPORT.to_string(),
4456        }),
4457    };
4458    let next = match toks.get(pos + 1) {
4459        // `sep` after `IMPORT`: joint followers miss.
4460        Some(t) if !t.joint => t,
4461        _ => return Ok(None),
4462    };
4463    // Parse entries first, validate in source order after.
4464    enum RawEntry {
4465        Module(String),
4466        File {
4467            path: String,
4468            alias: String,
4469        },
4470        From {
4471            func_names: Vec<String>,
4472            type_names: Vec<String>,
4473            path: String,
4474            alias: Option<String>,
4475        },
4476    }
4477    let mut raw: Vec<RawEntry> = Vec::new();
4478    let used;
4479    if matches!(
4480        &next.kind,
4481        TokKind::Group {
4482            delim: GroupDelim::Brace,
4483            ..
4484        }
4485    ) {
4486        return Ok(None);
4487    }
4488    if let TokKind::Group {
4489        delim: GroupDelim::Bracket,
4490        inner,
4491        ..
4492    } = &next.kind
4493    {
4494        // Comma-separated entries, `ws` gaps (newlines ok inside and
4495        // around entries, comments MISS — `ws` admits neither).
4496        // Single-file multi-name harvests skip the split: in
4497        // `[TYPE A, TYPE B FROM "f"]` the first comma-part (`[TYPE A]`)
4498        // carries no FROM and is invalid alone, so the whole bracket
4499        // is one harvest (see `whole_file_harvest`).
4500        // Bare-multi hint: `[FOO, BAR FROM "f"]` reads FOO as a
4501        // module for back-compat (bare words stay modules in single
4502        // brackets). If that word is not a known module but a harvest
4503        // follows, fail fast naming the two valid spellings instead
4504        // of the misleading unknown-module error.
4505        let whole = whole_file_harvest(inner);
4506        if whole.is_none()
4507            && let Some(word) = single_bare_first_part(inner)
4508            && !ctx.modules.modules.contains_key(word)
4509            && has_top_level_from_after_comma(inner)
4510        {
4511            return Err(fail(format!(
4512                "unknown module `{word}`; to harvest multiple names qualify each kind (`IMPORT [FUNC FOO, FUNC BAR FROM \"f\"]`)"
4513            )));
4514        }
4515        let mut parts: Vec<&[Tok]> = Vec::new();
4516        if whole.is_some() {
4517            parts.push(inner);
4518        } else {
4519            let mut start = 0;
4520            for (i, tok) in inner.iter().enumerate() {
4521                if matches!(&tok.kind, TokKind::Punct(',')) {
4522                    parts.push(&inner[start..i]);
4523                    start = i + 1;
4524                }
4525            }
4526            parts.push(&inner[start..]);
4527        }
4528        for part in parts {
4529            let dense: Vec<&Tok> = part
4530                .iter()
4531                .filter(|t| !matches!(&t.kind, TokKind::Newline))
4532                .collect();
4533            // `[[F, G FROM "path" (AS ALIAS)?]]`: selective function
4534            // harvest. Anything else bracketed here misses.
4535            if let [bracket] = dense.as_slice()
4536                && let TokKind::Group {
4537                    delim: GroupDelim::Bracket,
4538                    inner,
4539                    ..
4540                } = &bracket.kind
4541            {
4542                let Some(HarvestImport {
4543                    func_names,
4544                    type_names,
4545                    path,
4546                    alias,
4547                }) = parse_from_entry(inner)
4548                else {
4549                    return Ok(None);
4550                };
4551                raw.push(RawEntry::From {
4552                    func_names,
4553                    type_names,
4554                    path,
4555                    alias,
4556                });
4557                continue;
4558            }
4559            // `[F FROM "path" (AS ALIAS)?]`: single harvest without
4560            // inner brackets. The `FROM` keyword is the discriminant
4561            // (module and file parts never contain a top-level one);
4562            // multi-name harvests keep `[[F, G FROM ...]]` so the comma
4563            // stays grouped inside its own scope.
4564            if dense.len() >= 3 {
4565                let owned: Vec<Tok> = dense.iter().map(|t| (*t).clone()).collect();
4566                if let Some(HarvestImport {
4567                    func_names,
4568                    type_names,
4569                    path,
4570                    alias,
4571                }) = parse_from_entry(&owned)
4572                {
4573                    raw.push(RawEntry::From {
4574                        func_names,
4575                        type_names,
4576                        path,
4577                        alias,
4578                    });
4579                    continue;
4580                }
4581            }
4582            match dense.as_slice() {
4583                [tok] => match &tok.kind {
4584                    TokKind::Word(w) if is_upper_ident(w) => {
4585                        raw.push(RawEntry::Module(w.clone()));
4586                    }
4587                    _ => return Ok(None),
4588                },
4589                [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
4590                    let (
4591                        TokKind::Str { text, .. },
4592                        TokKind::Word(as_word),
4593                        TokKind::Word(alias_word),
4594                    ) = (&path_tok.kind, &as_tok.kind, &alias_tok.kind)
4595                    else {
4596                        return Ok(None);
4597                    };
4598                    if as_word != KEYWORD_AS {
4599                        return Ok(None);
4600                    }
4601                    raw.push(RawEntry::File {
4602                        path: text.clone(),
4603                        alias: alias_word.clone(),
4604                    });
4605                }
4606                _ => return Ok(None),
4607            }
4608        }
4609        if raw.is_empty() {
4610            return Ok(None);
4611        }
4612        used = 2;
4613    } else if let TokKind::Word(w) = &next.kind {
4614        // Bare `IMPORT MOD` (single module, probed).
4615        if !is_upper_ident(w) {
4616            return Ok(None);
4617        }
4618        raw.push(RawEntry::Module(w.clone()));
4619        used = 2;
4620    } else if let TokKind::Str { text, .. } = &next.kind {
4621        // Bare `IMPORT "path" AS ALIAS`.
4622        let (Some(as_tok), Some(alias_tok)) = (toks.get(pos + 2), toks.get(pos + 3)) else {
4623            return Ok(None);
4624        };
4625        if as_tok.joint || alias_tok.joint {
4626            return Ok(None);
4627        }
4628        let (TokKind::Word(as_word), TokKind::Word(alias_word)) = (&as_tok.kind, &alias_tok.kind)
4629        else {
4630            return Ok(None);
4631        };
4632        if as_word != KEYWORD_AS {
4633            return Ok(None);
4634        }
4635        raw.push(RawEntry::File {
4636            path: text.clone(),
4637            alias: alias_word.clone(),
4638        });
4639        used = 4;
4640    } else {
4641        return Ok(None);
4642    }
4643    // Validate in source order: unknown modules fail with the exact
4644    // backend message (sorted known list); file and harvest entries
4645    // validate hard (bad names, collisions, templates, remote URLs).
4646    let mut modules = Vec::new();
4647    let mut steps = Vec::new();
4648    for entry in raw {
4649        match entry {
4650            RawEntry::Module(module) => {
4651                if !ctx.modules.modules.contains_key(&module) {
4652                    let mut known: Vec<String> = ctx.modules.modules.keys().cloned().collect();
4653                    known.sort();
4654                    return Err(fail(format!(
4655                        "unknown module `{module}`; known modules: {}",
4656                        known.join(", ")
4657                    )));
4658                }
4659                ctx.import_into_frame(std::slice::from_ref(&module));
4660                modules.push(module);
4661            }
4662            RawEntry::File { path, alias } => {
4663                let (path, alias) = validate_file_import(&path, &alias, ctx).map_err(fail)?;
4664                steps.push(StepKind::ImportFile { path, alias });
4665            }
4666            RawEntry::From {
4667                func_names,
4668                type_names,
4669                path,
4670                alias,
4671            } => {
4672                let HarvestImport {
4673                    func_names,
4674                    type_names,
4675                    path,
4676                    alias,
4677                } = validate_from_import(&func_names, &type_names, &path, alias.as_deref(), ctx)
4678                    .map_err(fail)?;
4679                steps.push(StepKind::ImportFuncs {
4680                    path,
4681                    alias,
4682                    func_names,
4683                    type_names,
4684                });
4685            }
4686        }
4687    }
4688    Ok(Some(((modules, steps), used)))
4689}
4690
4691/// Single file import for value positions (#115): exactly one
4692/// `"path" AS ALIAS` entry and no modules. Anything else shaped like an
4693/// import is a hard error naming the restriction; shape misses return
4694/// `None` for the generic path.
4695fn parse_single_file_import(
4696    toks: &[Tok],
4697    pos: usize,
4698    stmt: usize,
4699    ctx: &ParseCtx,
4700) -> Result<Option<(String, String, usize)>, TokenError> {
4701    let Some(((modules, mut kinds), used)) = parse_import_statement(toks, pos, stmt, ctx)? else {
4702        return Ok(None);
4703    };
4704    if !modules.is_empty() || !matches!(kinds.as_slice(), [StepKind::ImportFile { .. }]) {
4705        return Err(TokenError {
4706            stmt,
4707            msg: if !modules.is_empty()
4708                || kinds
4709                    .iter()
4710                    .any(|k| matches!(k, StepKind::ImportFuncs { .. }))
4711            {
4712                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>]); modules and function harvests stay at statement level".to_string()
4713            } else {
4714                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>])"
4715                    .to_string()
4716            },
4717            line: 0,
4718            col: 0,
4719            kind: Some(ParseErrorKind::Validation {
4720                command: KEYWORD_IMPORT.to_string(),
4721            }),
4722        });
4723    }
4724    let Some(StepKind::ImportFile { path, alias }) = kinds.pop() else {
4725        unreachable!("length and variant checked above")
4726    };
4727    Ok(Some((path, alias, used)))
4728}
4729
4730/// One `EXPORT` name: an uppercase word with an optional joint
4731/// `::UPPER` tail. Returns the name and tokens consumed, or `None`
4732/// on shape miss.
4733fn parse_export_name(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
4734    let head = match toks.get(pos).map(|t| &t.kind) {
4735        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
4736        _ => return None,
4737    };
4738    let mut name = head;
4739    let mut used = 1;
4740    // Greedy-prefix `::tail` (atomic, like the grammar): a valid
4741    // tail joins, an invalid one stays trailing (failing downstream
4742    // exactly like the grammar's committed prefix).
4743    if matches!(
4744        toks.get(pos + 1).map(|t| &t.kind),
4745        Some(TokKind::Punct(':'))
4746    ) && toks.get(pos + 1).is_some_and(|t| t.joint)
4747        && matches!(
4748            toks.get(pos + 2).map(|t| &t.kind),
4749            Some(TokKind::Punct(':'))
4750        )
4751        && toks.get(pos + 2).is_some_and(|t| t.joint)
4752        && let Some(TokKind::Word(tail)) = toks.get(pos + 3).map(|t| &t.kind)
4753        && toks[pos + 3].joint
4754        && is_upper_ident(tail)
4755    {
4756        name.push_str(MODULE_SEPARATOR);
4757        name.push_str(tail);
4758        used = 4;
4759    }
4760    Some((name, used))
4761}
4762
4763/// One selective harvest (`[[F, G FROM "path" (AS ALIAS)?]]`): the
4764/// wanted function and type names plus the path and optional alias.
4765/// Bare names are functions; `TYPE`/`FUNC` prefixes select the kind
4766/// explicitly (`[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`).
4767struct HarvestImport {
4768    func_names: Vec<String>,
4769    type_names: Vec<String>,
4770    path: String,
4771    alias: Option<String>,
4772}
4773
4774/// One `[[F, G FROM "path" (AS ALIAS)?]]` entry: selective function
4775/// harvest with optional `TYPE`/`FUNC` qualifiers per name:
4776/// `[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`
4777/// (bare stays func for back-compat).
4778/// Returns the harvest, or `None` on shape miss (generic lowering fails
4779/// it). Name case is validated hard by the caller, like file aliases.
4780fn parse_from_entry(inner: &[Tok]) -> Option<HarvestImport> {
4781    let dense: Vec<&Tok> = inner
4782        .iter()
4783        .filter(|t| !matches!(&t.kind, TokKind::Newline))
4784        .collect();
4785    let from = dense
4786        .iter()
4787        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
4788    if from == 0 {
4789        return None;
4790    }
4791    // Names: comma-separated entries, each `NAME` (func) or
4792    // `TYPE NAME` / `FUNC NAME` (explicit kind for clarity).
4793    let mut func_names = Vec::new();
4794    let mut type_names = Vec::new();
4795    let mut start = 0;
4796    let head = &dense[..from];
4797    // Local helper: classify one comma-separated part.
4798    fn classify_part(part: &[&Tok]) -> Option<(bool, String)> {
4799        match part {
4800            [tok] => {
4801                let TokKind::Word(w) = &tok.kind else {
4802                    return None;
4803                };
4804                Some((false, w.clone()))
4805            }
4806            // `TYPE NAME` / `FUNC NAME`: the name must be `sep` (gapped
4807            // from the kind); the kind may be joint to a preceding `[`
4808            // or `,` (no space required there), so only the name's joint
4809            // flag matters.
4810            [kind_tok, name_tok] if !name_tok.joint => {
4811                let (TokKind::Word(kind), TokKind::Word(name)) = (&kind_tok.kind, &name_tok.kind)
4812                else {
4813                    return None;
4814                };
4815                if kind == KEYWORD_TYPE {
4816                    Some((true, name.clone()))
4817                } else if kind == KEYWORD_FUNC {
4818                    Some((false, name.clone()))
4819                } else {
4820                    None
4821                }
4822            }
4823            _ => None,
4824        }
4825    }
4826    for (i, tok) in head.iter().enumerate() {
4827        if matches!(&tok.kind, TokKind::Punct(',')) {
4828            let part = &head[start..i];
4829            let (is_type, name) = classify_part(part)?;
4830            if is_type {
4831                type_names.push(name);
4832            } else {
4833                func_names.push(name);
4834            }
4835            start = i + 1;
4836        }
4837    }
4838    let part = &head[start..];
4839    let (is_type, name) = classify_part(part)?;
4840    if is_type {
4841        type_names.push(name);
4842    } else {
4843        func_names.push(name);
4844    }
4845    // Tail: `"path"` or bare `MODULE` with an optional gapped `AS ALIAS`.
4846    // Quoted is a file path (module fallback only when no file matches);
4847    // bare is a host module (no file probe ambiguity).
4848    let tail = &dense[from + 1..];
4849    let path_text = |tok: &Tok| match &tok.kind {
4850        TokKind::Str { text, .. } => Some(text.clone()),
4851        TokKind::Word(w) if is_upper_ident(w) => Some(w.clone()),
4852        _ => None,
4853    };
4854    match tail {
4855        [path_tok] => {
4856            let text = path_text(path_tok)?;
4857            Some(HarvestImport {
4858                func_names,
4859                type_names,
4860                path: text,
4861                alias: None,
4862            })
4863        }
4864        [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
4865            let text = path_text(path_tok)?;
4866            let (TokKind::Word(as_word), TokKind::Word(alias_word)) =
4867                (&as_tok.kind, &alias_tok.kind)
4868            else {
4869                return None;
4870            };
4871            if as_word != KEYWORD_AS {
4872                return None;
4873            }
4874            Some(HarvestImport {
4875                func_names,
4876                type_names,
4877                path: text,
4878                alias: Some(alias_word.clone()),
4879            })
4880        }
4881        _ => None,
4882    }
4883}
4884
4885/// First comma-part of a bracket when it is exactly one bare
4886/// uppercase word: the back-compat module reading. Anything else
4887/// (prefixed names, groups, multiple words) is not a bare module.
4888fn single_bare_first_part(inner: &[Tok]) -> Option<&str> {
4889    let end = inner
4890        .iter()
4891        .position(|t| matches!(&t.kind, TokKind::Punct(',')))
4892        .unwrap_or(inner.len());
4893    let mut words = inner[..end]
4894        .iter()
4895        .filter(|t| !matches!(&t.kind, TokKind::Newline));
4896    match (words.next(), words.next()) {
4897        (Some(tok), None) => match &tok.kind {
4898            TokKind::Word(w) if is_upper_ident(w) => Some(w.as_str()),
4899            _ => None,
4900        },
4901        _ => None,
4902    }
4903}
4904
4905/// Whether a top-level `FROM` follows the first top-level comma:
4906/// distinguishes a module-plus-harvest entry (`[STD, T FROM "f"]`)
4907/// from a bare word the author meant as a harvest name.
4908fn has_top_level_from_after_comma(inner: &[Tok]) -> bool {
4909    let mut seen_comma = false;
4910    for tok in inner {
4911        match &tok.kind {
4912            TokKind::Punct(',') => seen_comma = true,
4913            TokKind::Word(w) if seen_comma && w == KEYWORD_FROM => return true,
4914            _ => {}
4915        }
4916    }
4917    false
4918}
4919
4920/// Whole-bracket single-file harvest (`[TYPE A, TYPE B FROM "f"]`):
4921/// the comma-split would orphan `[TYPE A]` (no FROM, invalid alone),
4922/// so the entire bracket parses as one harvest. Only explicitly
4923/// prefixed names qualify: a bare word keeps its legacy module
4924/// reading, so `[STD, TYPE T FROM "f"]` still splits into a module
4925/// plus a harvest instead of harvesting STD as a function.
4926fn whole_file_harvest(inner: &[Tok]) -> Option<HarvestImport> {
4927    let owned: Vec<Tok> = inner.to_vec();
4928    let harvest = parse_from_entry(&owned)?;
4929    let dense: Vec<&Tok> = inner
4930        .iter()
4931        .filter(|t| !matches!(&t.kind, TokKind::Newline))
4932        .collect();
4933    let from = dense
4934        .iter()
4935        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
4936    let mut start = 0;
4937    for (i, tok) in dense[..from].iter().enumerate() {
4938        if matches!(&tok.kind, TokKind::Punct(',')) {
4939            if !is_prefixed_name(&dense[start..i]) {
4940                return None;
4941            }
4942            start = i + 1;
4943        }
4944    }
4945    if !is_prefixed_name(&dense[start..from]) {
4946        return None;
4947    }
4948    Some(harvest)
4949}
4950
4951/// One explicitly prefixed name (`TYPE NAME` / `FUNC NAME`): the name
4952/// stays gapped from its kind; the kind may joint to `[` or `,`.
4953fn is_prefixed_name(part: &[&Tok]) -> bool {
4954    match part {
4955        [kind_tok, name_tok] if !name_tok.joint => {
4956            matches!(
4957                (&kind_tok.kind, &name_tok.kind),
4958                (
4959                    TokKind::Word(kind),
4960                    TokKind::Word(_)
4961                ) if kind == KEYWORD_TYPE || kind == KEYWORD_FUNC
4962            )
4963        }
4964        _ => false,
4965    }
4966}
4967
4968/// Validate an `IMPORT` alias: hard errors (never shape misses) plus
4969/// registration into the innermost import frame.
4970fn validate_import_alias(alias: &str, ctx: &ParseCtx) -> Result<String, String> {
4971    if !is_upper_ident(alias) {
4972        return Err(format!(
4973            "IMPORT alias must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{alias}`"
4974        ));
4975    }
4976    if ctx.modules.modules.contains_key(alias) {
4977        return Err(format!(
4978            "IMPORT alias `{alias}` collides with module `{alias}`"
4979        ));
4980    }
4981    let (_, imports) = ctx.visible_snapshot();
4982    if imports.contains(&alias.to_string()) {
4983        return Err(format!("duplicate IMPORT alias `{alias}`"));
4984    }
4985    ctx.import_into_frame(std::slice::from_ref(&alias.to_string()));
4986    Ok(alias.to_string())
4987}
4988
4989/// Validate an `IMPORT` path: hard errors, never shape misses.
4990fn validate_import_path(path: &str) -> Result<String, String> {
4991    if path.is_empty() {
4992        return Err("IMPORT path must not be empty".to_string());
4993    }
4994    if path.contains("{{") {
4995        return Err("IMPORT path must be a literal string (no {{ }} templates)".to_string());
4996    }
4997    if path.contains("://") {
4998        return Err(
4999            "remote imports are deferred to #270 (net: Run scripts from a remote URL)".to_string(),
5000        );
5001    }
5002    Ok(path.to_string())
5003}
5004
5005/// Validate a file-import path/alias pair: hard errors (never shape
5006/// misses) plus alias registration into the innermost import frame.
5007fn validate_file_import(
5008    path: &str,
5009    alias: &str,
5010    ctx: &ParseCtx,
5011) -> Result<(String, String), String> {
5012    let alias = validate_import_alias(alias, ctx)?;
5013    let path = validate_import_path(path)?;
5014    Ok((path, alias))
5015}
5016
5017/// Validate a `[[F, G FROM "path" (AS ALIAS)?]]` entry: hard errors
5018/// (never shape misses). Bare func names declare into the innermost
5019/// `FUNC` frame so calls resolve statically; the runtime defines them
5020/// (and fails unknown names there). Type names need no func-frame
5021/// declaration (types resolve through the global type directory);
5022/// the runtime validates them against the file's `EXPORT TYPE` list.
5023/// An alias registers like a file import.
5024fn validate_from_import(
5025    func_names: &[String],
5026    type_names: &[String],
5027    path: &str,
5028    alias: Option<&str>,
5029    ctx: &ParseCtx,
5030) -> Result<HarvestImport, String> {
5031    let path = validate_import_path(path)?;
5032    let mut out_func_names = Vec::with_capacity(func_names.len());
5033    for name in func_names {
5034        if !is_upper_ident(name) {
5035            return Err(format!(
5036                "IMPORT function names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
5037            ));
5038        }
5039        if ctx.reserved.contains(name) {
5040            return Err(format!("cannot shadow reserved function `{name}`"));
5041        }
5042        out_func_names.push(name.clone());
5043    }
5044    let mut out_type_names = Vec::with_capacity(type_names.len());
5045    for name in type_names {
5046        if !is_upper_ident(name) {
5047            return Err(format!(
5048                "IMPORT type names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
5049            ));
5050        }
5051        out_type_names.push(name.clone());
5052    }
5053    if out_func_names.is_empty() && out_type_names.is_empty() {
5054        return Err("IMPORT harvest needs at least one function or type name".to_string());
5055    }
5056    if let Some(alias) = alias {
5057        let alias = validate_import_alias(alias, ctx)?;
5058        Ok(HarvestImport {
5059            func_names: out_func_names,
5060            type_names: out_type_names,
5061            path,
5062            alias: Some(alias),
5063        })
5064    } else {
5065        for name in &out_func_names {
5066            if !ctx.declare_func(name) {
5067                return Err(format!("duplicate function `{name}` in same scope"));
5068            }
5069        }
5070        // Type harvests without alias land bare in the global type
5071        // directory: duplicates across files fail at import time
5072        // (different targets), not at parse time (targets need IO).
5073        Ok(HarvestImport {
5074            func_names: out_func_names,
5075            type_names: out_type_names,
5076            path,
5077            alias: None,
5078        })
5079    }
5080}
5081
5082/// One `EXPORT ...` name list: function names plus type names in
5083/// source order. Bare names are functions; explicit `TYPE`/`FUNC`
5084/// prefixes select the kind.
5085struct ExportNames {
5086    func_names: Vec<String>,
5087    type_names: Vec<String>,
5088}
5089
5090/// `EXPORT ...` names at `pos`: bracket list (strict, `ws` gaps:
5091/// newlines ok, comments miss) or a bare greedy-prefix name.
5092/// Supports explicit `TYPE`/`FUNC` qualifiers for clarity:
5093/// `EXPORT TYPE FOO`, `EXPORT TYPE [A, B]`, `EXPORT FUNC FOO`,
5094/// plus mixed `EXPORT [TYPE A, FUNC B, C]` (bare stays func).
5095/// Returns the name lists plus tokens consumed, or `None` on shape
5096/// miss (generic fails it in lowering like the grammar). Recording and
5097/// duplicate checks live with the caller (they need the guard and
5098/// level context).
5099fn parse_export_at(toks: &[Tok], pos: usize) -> Option<(ExportNames, usize)> {
5100    let next = match toks.get(pos + 1) {
5101        // `sep` after `EXPORT`: joint followers miss.
5102        Some(t) if !t.joint => t,
5103        _ => return None,
5104    };
5105    // Explicit `EXPORT TYPE ...` or `EXPORT FUNC ...` prefix.
5106    if let TokKind::Word(w) = &next.kind
5107        && (w == KEYWORD_TYPE || w == KEYWORD_FUNC)
5108    {
5109        let is_type = w == KEYWORD_TYPE;
5110        let after = match toks.get(pos + 2) {
5111            Some(t) if !t.joint => t,
5112            _ => return None,
5113        };
5114        if let TokKind::Group {
5115            delim: GroupDelim::Bracket,
5116            inner,
5117            ..
5118        } = &after.kind
5119        {
5120            let mut func_names = Vec::new();
5121            let mut type_names = Vec::new();
5122            for part in split_bracket_entries(inner) {
5123                let mut part = part;
5124                while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
5125                    part = &part[1..];
5126                }
5127                while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
5128                    part = &part[..part.len() - 1];
5129                }
5130                // A trailing comma leaves an empty final entry; it
5131                // carries no name and must not fail the list.
5132                if part.is_empty() {
5133                    continue;
5134                }
5135                let (name, used) = parse_export_name(part, 0)?;
5136                if used != part.len() {
5137                    return None;
5138                }
5139                if is_type {
5140                    type_names.push(name);
5141                } else {
5142                    func_names.push(name);
5143                }
5144            }
5145            if func_names.is_empty() && type_names.is_empty() {
5146                return None;
5147            }
5148            return Some((
5149                ExportNames {
5150                    func_names,
5151                    type_names,
5152                },
5153                3,
5154            ));
5155        }
5156        if matches!(&after.kind, TokKind::Group { .. }) {
5157            return None;
5158        }
5159        let (name, used) = parse_export_name(toks, pos + 2)?;
5160        // Bare name after TYPE/FUNC prefix must consume exactly one
5161        // name; trailing loops stay outside like the unprefixed case.
5162        // `used` counts from pos+2, so 1 name is valid.
5163        if used == 0 {
5164            return None;
5165        }
5166        if is_type {
5167            return Some((
5168                ExportNames {
5169                    func_names: Vec::new(),
5170                    type_names: vec![name],
5171                },
5172                2 + used,
5173            ));
5174        } else {
5175            return Some((
5176                ExportNames {
5177                    func_names: vec![name],
5178                    type_names: Vec::new(),
5179                },
5180                2 + used,
5181            ));
5182        }
5183    }
5184    if let TokKind::Group {
5185        delim: GroupDelim::Bracket,
5186        inner,
5187        ..
5188    } = &next.kind
5189    {
5190        let mut func_names = Vec::new();
5191        let mut type_names = Vec::new();
5192        for part in split_bracket_entries(inner) {
5193            let mut part = part;
5194            while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
5195                part = &part[1..];
5196            }
5197            while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
5198                part = &part[..part.len() - 1];
5199            }
5200            // A trailing comma leaves an empty final entry; it
5201            // carries no name and must not fail the list.
5202            if part.is_empty() {
5203                continue;
5204            }
5205            // Optional per-entry `TYPE`/`FUNC` prefix for mixed lists:
5206            // `EXPORT [TYPE A, FUNC B, C]` (bare stays func). The name
5207            // must be `sep` from the prefix; the prefix itself may be
5208            // joint to a preceding `[` or `,`, so only the name's joint
5209            // flag matters.
5210            let (is_type, rest) = match part {
5211                [first, second, ..]
5212                    if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_TYPE || w == KEYWORD_FUNC)
5213                        && !second.joint =>
5214                {
5215                    let is_t = matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_TYPE);
5216                    (is_t, &part[1..])
5217                }
5218                _ => (false, part),
5219            };
5220            // Exactly one name per entry (entries never trail).
5221            let (name, used) = parse_export_name(rest, 0)?;
5222            if used != rest.len() {
5223                return None;
5224            }
5225            if is_type {
5226                type_names.push(name);
5227            } else {
5228                func_names.push(name);
5229            }
5230        }
5231        if func_names.is_empty() && type_names.is_empty() {
5232            return None;
5233        }
5234        return Some((
5235            ExportNames {
5236                func_names,
5237                type_names,
5238            },
5239            2,
5240        ));
5241    }
5242    if matches!(&next.kind, TokKind::Group { .. }) {
5243        return None;
5244    }
5245    // Bare name (greedy `::` prefix; trailing loops outside). Bare
5246    // stays func for back-compat; `TYPE`/`FUNC` prefix selects above.
5247    parse_export_name(toks, pos + 1).map(|(name, used)| {
5248        (
5249            ExportNames {
5250                func_names: vec![name],
5251                type_names: Vec::new(),
5252            },
5253            1 + used,
5254        )
5255    })
5256}
5257
5258/// Split bracket inner tokens on top-level commas, preserving entries
5259/// for per-entry `TYPE`/`FUNC` handling. Newlines trim at the caller.
5260fn split_bracket_entries(inner: &[Tok]) -> Vec<&[Tok]> {
5261    let mut parts: Vec<&[Tok]> = Vec::new();
5262    let mut start = 0;
5263    for (i, tok) in inner.iter().enumerate() {
5264        if matches!(&tok.kind, TokKind::Punct(',')) {
5265            parts.push(&inner[start..i]);
5266            start = i + 1;
5267        }
5268    }
5269    parts.push(&inner[start..]);
5270    parts
5271}
5272
5273/// `TYPE NAME = SHAPE` at `pos`: uppercase name, single `=`, maximal
5274/// type-tag shape canonicalized through the shared spelling.
5275/// Returns the alias plus tokens consumed, or `None` on shape miss
5276/// (generic fails it in lowering like the grammar).
5277fn parse_type_stmt_at(
5278    toks: &[Tok],
5279    pos: usize,
5280    stmt: usize,
5281) -> Result<Option<(StepKind, usize)>, TokenError> {
5282    let name = match toks.get(pos + 1).map(|t| &t.kind) {
5283        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
5284        _ => return Ok(None),
5285    };
5286    // Single `=` at any gap (`gap` zero-width); `==` misses.
5287    if !matches!(
5288        toks.get(pos + 2).map(|t| &t.kind),
5289        Some(TokKind::Punct('='))
5290    ) {
5291        return Ok(None);
5292    }
5293    if matches!(
5294        toks.get(pos + 3).map(|t| &t.kind),
5295        Some(TokKind::Punct('='))
5296    ) {
5297        return Ok(None);
5298    }
5299    let Some(end) = parse_type_shape(toks, pos + 3) else {
5300        return Ok(None);
5301    };
5302    // Post-match the span holds words/puncts only, so the shared
5303    // renderer cannot fail; stay failed regardless.
5304    let target = render_type_region(&toks[pos + 3..end], stmt).unwrap_or_default();
5305    Ok(Some((StepKind::TypeAlias { name, target }, end - pos)))
5306}
5307
5308/// Single (non-block) `REMOTE`: target, optional bindings, block.
5309/// The target reads a maximal joint run in the grammar's superset
5310/// charset (misses fall to generic); strict validity fails loudly
5311/// with the exact backend message. Bindings miss to generic;
5312/// empty/missing bodies and nesting violations fail loudly.
5313fn parse_remote_single(
5314    toks: &[Tok],
5315    pos: usize,
5316    stmt: usize,
5317    ctx: &ParseCtx,
5318) -> Result<Option<(StepKind, usize)>, TokenError> {
5319    let fail = |msg: String| TokenError {
5320        stmt,
5321        msg,
5322        line: 0,
5323        col: 0,
5324        kind: Some(ParseErrorKind::Validation {
5325            command: KEYWORD_REMOTE.to_string(),
5326        }),
5327    };
5328    // Target: joint run in the superset charset (alnum/`_`/`-`/`.`/`:`).
5329    // Anything else (joint or not) ends the run; an empty run misses
5330    // to generic. (`sep` needs no explicit check: a joint `(` is a
5331    // call routed before this ever runs, and anything unparseable
5332    // misses the same way.)
5333    let mut target = String::new();
5334    let mut p = pos + 1;
5335    while let Some(t) = toks.get(p) {
5336        if !t.joint && !target.is_empty() {
5337            break;
5338        }
5339        match &t.kind {
5340            TokKind::Word(w)
5341                if w.chars().all(|c| {
5342                    c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' || c == ':'
5343                }) =>
5344            {
5345                // Words arrive whole from the lexer; a bad word ends
5346                // the run (never partially appends), like the grammar.
5347                target.push_str(w);
5348                p += 1;
5349            }
5350            TokKind::Punct(c)
5351                if matches!(c, '_' | '-' | '.' | ':') && (target.is_empty() || t.joint) =>
5352            {
5353                target.push(*c);
5354                p += 1;
5355            }
5356            _ => break,
5357        }
5358    }
5359    if target.is_empty() {
5360        return Ok(None);
5361    }
5362    if !crate::commands::is_valid_remote_target(&target) {
5363        return Err(fail(format!(
5364            "invalid REMOTE target `{target}`: start alphanumeric, then alphanumeric, `_`, or `-`, max 64 chars, never SNAPSHOT, LOCAL, CACHE, SYSTEM, or REMOTE"
5365        )));
5366    }
5367    // Optional bindings `[$var, env:KEY]` at any gap (even joint,
5368    // probed); malformed bindings miss the whole shape to generic.
5369    let mut vars = Vec::new();
5370    let mut env = Vec::new();
5371    if let Some(bracket) = toks.get(p)
5372        && matches!(
5373            &bracket.kind,
5374            TokKind::Group {
5375                delim: GroupDelim::Bracket,
5376                ..
5377            }
5378        )
5379    {
5380        let inner = match &bracket.kind {
5381            TokKind::Group { inner, .. } => inner.clone(),
5382            _ => unreachable!(),
5383        };
5384        match parse_remote_bindings(&inner, stmt)? {
5385            Some((v, e)) => {
5386                vars = v;
5387                env = e;
5388            }
5389            None => return Ok(None),
5390        }
5391        p += 1;
5392    }
5393    // Block required (any gap, never a template); missing blocks
5394    // miss to generic.
5395    let block_ok = matches!(
5396        toks.get(p).map(|t| &t.kind),
5397        Some(TokKind::Group {
5398            delim: GroupDelim::Brace,
5399            ..
5400        })
5401    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
5402    if !block_ok {
5403        return Ok(None);
5404    }
5405    let inner = match &toks[p].kind {
5406        TokKind::Group { inner, .. } => inner.clone(),
5407        _ => unreachable!(),
5408    };
5409    let body = parse_body_steps(&inner, stmt, ctx, false)?;
5410    p += 1;
5411    if body.is_empty() {
5412        return Err(fail("REMOTE requires a non-empty braced block".to_string()));
5413    }
5414    if crate::commands::contains_remote_block(&body) {
5415        return Err(fail(format!(
5416            "REMOTE blocks cannot nest (target `{target}` contains another REMOTE block)"
5417        )));
5418    }
5419    if body
5420        .iter()
5421        .any(|s| crate::commands::contains_inherit_env(&s.kind))
5422    {
5423        return Err(fail(
5424            "INHERIT_ENV cannot appear inside a REMOTE block: the guest inherits its own process environment".to_string(),
5425        ));
5426    }
5427    // Outer-function containment (same rule as the shared remote
5428    // validators): body calls resolving to visible
5429    // outer `SCRIPT` defs (without same-body definitions) fail.
5430    {
5431        let mut inner_defs = HashSet::new();
5432        let mut calls = Vec::new();
5433        crate::commands::collect_remote_body_symbols(&body, &mut inner_defs, &mut calls);
5434        let outer_defs: HashSet<String> = ctx.funcs.borrow().iter().flatten().cloned().collect();
5435        for call in &calls {
5436            let bare = crate::constants::base_name(call);
5437            let is_script_call = match crate::constants::split_qualified(call) {
5438                Some((module, _)) => module == crate::constants::SCRIPT_MODULE_NAME,
5439                None => true,
5440            };
5441            if is_script_call && outer_defs.contains(bare) && !inner_defs.contains(bare) {
5442                return Err(fail(format!(
5443                    "REMOTE '{target}' calls outer function '{bare}' (functions must be defined inside the block)"
5444                )));
5445            }
5446        }
5447    }
5448    Ok(Some((
5449        StepKind::RemoteBlock {
5450            target,
5451            vars,
5452            env,
5453            body,
5454        },
5455        p - pos,
5456    )))
5457}
5458// ---- LET/SET/RETURN + expressions ----
5459// Expression tiers over [`Tok`] implement the precedence chain
5460// (or > and > comparison > ordering > add > mul > unary > atom);
5461// arithmetic/comparison lowering runs through the shared constructors
5462// (`make_arith`, `make_compare`, `apply_unary_neg`), so folding, RPN
5463// compilation, and overflow behavior are identical by construction,
5464// never re-derived.
5465
5466/// Eat a one- or two-char operator: single puncts match directly;
5467/// pairs (`==`, `!=`, `<=`, `>=`, `&&`, `||`, `::`) require a joint
5468/// second punct. Newlines never skip here (expression mode).
5469fn eat_op(cur: &mut Cursor, first: char, second: Option<char>) -> bool {
5470    // Gaps (comments included) are skipped before every operator.
5471    cur.skip_gap();
5472    let (a, b) = match (cur.toks.get(cur.pos), cur.toks.get(cur.pos + 1)) {
5473        (Some(a), b) => (a, b),
5474        _ => return false,
5475    };
5476    if !matches!(&a.kind, TokKind::Punct(c) if *c == first) {
5477        return false;
5478    }
5479    match second {
5480        None => {
5481            cur.pos += 1;
5482            true
5483        }
5484        Some(c2) => match b {
5485            Some(t) if t.joint && matches!(&t.kind, TokKind::Punct(c) if *c == c2) => {
5486                cur.pos += 2;
5487                true
5488            }
5489            _ => false,
5490        },
5491    }
5492}
5493
5494/// Dummy span for the shared lowering constructors: v2 owns no source
5495/// positions yet, so only success values (span-free) participate in
5496/// parity; failures surface through [`TokenError`] text.
5497fn lowering_ctx(stmt: usize) -> SpanContext<'static> {
5498    let _ = stmt;
5499    SpanContext::line_only(0)
5500}
5501
5502fn parse_expr_or(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5503    let mut left = parse_expr_and(cur, ctx)?;
5504    while eat_op(cur, '|', Some('|')) {
5505        cur.skip_gap();
5506        let right = parse_expr_and(cur, ctx)?;
5507        // No folding, no boundary checks: unfused literal runs stay
5508        // literal here.
5509        left = Expr::Logical {
5510            op: LogicalOp::Or,
5511            left: Box::new(left),
5512            right: Box::new(right),
5513        };
5514    }
5515    Ok(left)
5516}
5517
5518fn parse_expr_and(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5519    let mut left = parse_expr_cmp(cur, ctx)?;
5520    while eat_op(cur, '&', Some('&')) {
5521        cur.skip_gap();
5522        let right = parse_expr_cmp(cur, ctx)?;
5523        reject_boundary(&lowering_ctx(cur.stmt), &left).map_err(|e| cur.err(e.to_string()))?;
5524        reject_boundary(&lowering_ctx(cur.stmt), &right).map_err(|e| cur.err(e.to_string()))?;
5525        left = Expr::Logical {
5526            op: LogicalOp::And,
5527            left: Box::new(left),
5528            right: Box::new(right),
5529        };
5530    }
5531    Ok(left)
5532}
5533
5534fn parse_expr_cmp(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5535    let left = parse_expr_ord(cur, ctx)?;
5536    let op = if eat_op(cur, '=', Some('=')) {
5537        CompareOp::Eq
5538    } else if eat_op(cur, '!', Some('=')) {
5539        CompareOp::Ne
5540    } else {
5541        return Ok(left);
5542    };
5543    cur.skip_gap();
5544    let right = parse_expr_ord(cur, ctx)?;
5545    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
5546        .map_err(|e| cur.err(e.to_string()))?;
5547    reject_chained_compare(cur, false)?;
5548    Ok(expr)
5549}
5550
5551/// Reject a comparison operator trailing a complete comparison:
5552/// no grammar position continues with one, so the shape always fails —
5553/// loudly here instead of stranding text for a confusing downstream
5554/// error. The equality tier rejects all six (`$a == $b == $c`,
5555/// `$a == $b < $c < $d`); the ordering tier rejects ordering only
5556/// (`$a < $b < $c`), since `$a < $b == $c` is a legitimate equality
5557/// over an ordering result. Probes without consuming.
5558fn reject_chained_compare(cur: &mut Cursor, ordering_only: bool) -> Result<(), TokenError> {
5559    let mut probe = Cursor::expr(cur.toks, cur.stmt);
5560    probe.pos = cur.pos;
5561    probe.skip_gap();
5562    let chained = match probe.toks.get(probe.pos).map(|t| &t.kind) {
5563        Some(TokKind::Punct('<' | '>')) => true,
5564        Some(TokKind::Punct('=' | '!')) => !ordering_only,
5565        _ => false,
5566    };
5567    if chained {
5568        return Err(cur
5569            .err("chained comparison operators need explicit parentheses, e.g. `($a < $b) < $c`"));
5570    }
5571    Ok(())
5572}
5573
5574fn parse_expr_ord(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5575    let left = parse_expr_add(cur, ctx)?;
5576    let op = if eat_op(cur, '<', Some('=')) {
5577        CompareOp::Le
5578    } else if eat_op(cur, '>', Some('=')) {
5579        CompareOp::Ge
5580    } else if eat_op(cur, '<', None) {
5581        CompareOp::Lt
5582    } else if eat_op(cur, '>', None) {
5583        CompareOp::Gt
5584    } else {
5585        return Ok(left);
5586    };
5587    cur.skip_gap();
5588    let right = parse_expr_add(cur, ctx)?;
5589    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
5590        .map_err(|e| cur.err(e.to_string()))?;
5591    reject_chained_compare(cur, true)?;
5592    Ok(expr)
5593}
5594
5595fn parse_expr_add(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5596    let mut left = parse_expr_mul(cur, ctx)?;
5597    loop {
5598        let op = if eat_op(cur, '+', None) {
5599            ArithOp::Add
5600        } else if eat_op(cur, '-', None) {
5601            ArithOp::Sub
5602        } else {
5603            break;
5604        };
5605        cur.skip_gap();
5606        let right = parse_expr_mul(cur, ctx)?;
5607        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
5608            .map_err(|e| cur.err(e.to_string()))?;
5609    }
5610    Ok(left)
5611}
5612
5613fn parse_expr_mul(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5614    let mut left = parse_expr_unary(cur, ctx)?;
5615    loop {
5616        let op = if eat_op(cur, '*', None) {
5617            ArithOp::Mul
5618        } else if eat_op(cur, '/', None) {
5619            ArithOp::Div
5620        } else {
5621            break;
5622        };
5623        cur.skip_gap();
5624        let right = parse_expr_unary(cur, ctx)?;
5625        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
5626            .map_err(|e| cur.err(e.to_string()))?;
5627    }
5628    Ok(left)
5629}
5630
5631/// A `-` opens a bare word (never negation) when gaplessly followed by
5632/// a letter, `_`, or `/` — the `neg_op` lookahead, read off `joint`.
5633fn dash_is_bare(cur: &Cursor) -> bool {
5634    let next = cur.toks.get(cur.pos + 1);
5635    match next {
5636        Some(t) if t.joint => match &t.kind {
5637            TokKind::Word(w) => w
5638                .chars()
5639                .next()
5640                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_'),
5641            TokKind::Punct('/') => true,
5642            _ => false,
5643        },
5644        _ => false,
5645    }
5646}
5647
5648fn parse_expr_unary(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5649    let mut prefixes = Vec::new();
5650    loop {
5651        match cur.toks.get(cur.pos).map(|t| &t.kind) {
5652            Some(TokKind::Punct('!')) => {
5653                cur.pos += 1;
5654                // Each prefix is gap-separated.
5655                cur.skip_gap();
5656                prefixes.push(false);
5657            }
5658            Some(TokKind::Punct('-')) if !dash_is_bare(cur) => {
5659                cur.pos += 1;
5660                cur.skip_gap();
5661                prefixes.push(true);
5662            }
5663            _ => break,
5664        }
5665    }
5666    let mut expr = parse_expr_atom(cur, ctx)?;
5667    // Innermost prefix is closest to the atom: apply in reverse order.
5668    for is_neg in prefixes.into_iter().rev() {
5669        if is_neg {
5670            expr = apply_unary_neg(&lowering_ctx(cur.stmt), expr)
5671                .map_err(|e| cur.err(e.to_string()))?;
5672        } else {
5673            reject_boundary(&lowering_ctx(cur.stmt), &expr).map_err(|e| cur.err(e.to_string()))?;
5674            expr = Expr::Not(Box::new(expr));
5675        }
5676    }
5677    Ok(expr)
5678}
5679
5680/// Identifier charset for `$var` and `.segment` parts. Segments admit
5681/// digits-only too (`$a.0`); anything else ends the key path and errors
5682/// downstream, like the grammar's backtrack to `variable`.
5683fn is_ident_word(w: &str) -> bool {
5684    !w.is_empty() && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
5685}
5686
5687fn is_key_segment(w: &str) -> bool {
5688    !w.is_empty()
5689        && (w.chars().all(|c| c.is_ascii_digit())
5690            || (w
5691                .chars()
5692                .next()
5693                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
5694                && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')))
5695}
5696
5697fn is_env_key(w: &str) -> bool {
5698    !w.is_empty()
5699        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
5700        && w.chars()
5701            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
5702}
5703
5704/// Maximal joint run of words and `-/.'/'` puncts: the bare-word
5705/// shape (which admits `/` anywhere, so `//c`, `/a`, `a/b`, and the
5706/// `/`-`c`-`/` operands of `/*c*/` math all read literally here).
5707/// Callers classify (`true`/`false`/string); the numeric path
5708/// runs first and falls back here on shape/follower mismatch.
5709/// Backslash escapes are arg-position syntax: the bare-word shape admits
5710/// no `\`, so expression runs containing one fail here (never drift
5711/// into a string the grammar rejects).
5712fn expr_bare_run(cur: &mut Cursor, leading_dash: bool) -> Result<String, TokenError> {
5713    let mut out = String::new();
5714    if leading_dash {
5715        match cur.next() {
5716            Some(t) if matches!(&t.kind, TokKind::Punct('-')) => out.push('-'),
5717            _ => return Err(cur.err("missing expression operand")),
5718        }
5719    }
5720    match cur.next() {
5721        Some(t) => match &t.kind {
5722            TokKind::Word(w) => out.push_str(w),
5723            // Leading `/` (operand position only; operators are
5724            // consumed by the tiers before operands parse).
5725            TokKind::Punct('/') => out.push('/'),
5726            _ => return Err(cur.err("missing expression operand")),
5727        },
5728        None => return Err(cur.err("missing expression operand")),
5729    }
5730    loop {
5731        let next = match cur.toks.get(cur.pos) {
5732            Some(t) if t.joint => t,
5733            _ => break,
5734        };
5735        match &next.kind {
5736            TokKind::Word(w) => {
5737                // Abutting words only continue through an operator gap
5738                // the tiers own (`a -b` never fuses); without a joint
5739                // punct between, stop. Since this token IS joint, the
5740                // previous token must have been a bare punct.
5741                out.push_str(w);
5742                cur.pos += 1;
5743            }
5744            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
5745                out.push(*c);
5746                cur.pos += 1;
5747            }
5748            _ => break,
5749        }
5750    }
5751    if out.contains('\\') {
5752        return Err(cur.err("unexpected escape in expression"));
5753    }
5754    Ok(out)
5755}
5756
5757/// Numeric literal head: digit-led word plus joint `.digits` tails.
5758/// Callers apply the separator-shape gate and the follower rule, then
5759/// the shared classifier.
5760fn number_head(cur: &mut Cursor) -> Option<String> {
5761    let first = match cur.toks.get(cur.pos).map(|t| &t.kind) {
5762        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => w.clone(),
5763        _ => return None,
5764    };
5765    let mut text = first;
5766    let mut pos = cur.pos + 1;
5767    loop {
5768        let dot = matches!(
5769            cur.toks.get(pos).map(|t| &t.kind),
5770            Some(TokKind::Punct('.'))
5771        ) && cur.toks.get(pos).is_some_and(|t| t.joint);
5772        let digits = cur.toks.get(pos + 1);
5773        let digits_ok = dot
5774            && matches!(digits.map(|t| &t.kind), Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_'))
5775            && digits.is_some_and(|t| t.joint);
5776        if !digits_ok {
5777            break;
5778        }
5779        text.push('.');
5780        if let Some(TokKind::Word(w)) = digits.map(|t| &t.kind) {
5781            text.push_str(w);
5782        }
5783        pos += 2;
5784    }
5785    Some(text)
5786}
5787
5788/// `_`-separator shape gate mirroring the `numeric_literal` rule:
5789/// digits with single-underscore separators, at most one fraction.
5790fn numeric_shape_ok(text: &str) -> bool {
5791    let mut parts = text.split('.');
5792    let int_part = parts.next().unwrap_or("");
5793    let frac_part = parts.next();
5794    if parts.next().is_some() {
5795        return false;
5796    }
5797    fn run_ok(s: &str) -> bool {
5798        !s.is_empty()
5799            && s.chars().all(|c| c.is_ascii_digit() || c == '_')
5800            && !s.starts_with('_')
5801            && !s.ends_with('_')
5802            && !s.contains("__")
5803    }
5804    run_ok(int_part) && frac_part.is_none_or(run_ok)
5805}
5806
5807/// Follower rule mirroring the `numeric_literal` trailing guard
5808/// (`!(ALNUM | "_" | "." | "/")`): a joint word, `.`, or `/` continues
5809/// into a bare word (`30s`, `1.`, `4/2`); `-`/`+`/operators let the
5810/// number stand for the tiers (`1-2` is `Sub`, like the grammar).
5811fn number_falls_to_bare(cur: &Cursor, consumed: usize) -> bool {
5812    match cur.toks.get(cur.pos + consumed) {
5813        Some(t) if t.joint => matches!(
5814            &t.kind,
5815            TokKind::Word(_) | TokKind::Punct('.') | TokKind::Punct('/')
5816        ),
5817        _ => false,
5818    }
5819}
5820
5821fn parse_expr_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5822    match cur.toks.get(cur.pos).map(|t| &t.kind) {
5823        Some(TokKind::Group {
5824            delim: GroupDelim::Paren,
5825            inner,
5826            ..
5827        }) => {
5828            let inner = inner.clone();
5829            cur.pos += 1;
5830            let mut sub = Cursor::expr(&inner, cur.stmt);
5831            sub.skip_gap_nl();
5832            let expr = parse_expr_or(&mut sub, ctx)?;
5833            sub.skip_gap_nl();
5834            if !sub.done() {
5835                return Err(sub.err("unexpected text in parentheses"));
5836            }
5837            Ok(expr)
5838        }
5839        Some(TokKind::Word(_)) if call_shape_at(cur.toks, cur.pos, false).is_some() => {
5840            let (name, paren) =
5841                call_shape_at(cur.toks, cur.pos, false).ok_or_else(|| cur.err("unreachable"))?;
5842            let inner = match &cur.toks[paren].kind {
5843                TokKind::Group { inner, .. } => inner.clone(),
5844                _ => unreachable!(),
5845            };
5846            cur.pos = paren + 1;
5847            parse_expr_call(name, &inner, cur.stmt, ctx)
5848        }
5849        Some(TokKind::Punct('$')) => {
5850            cur.pos += 1;
5851            // Atomic `variable`: `$` and the name ride gapless (the
5852            // enclosing rules are compound-atomic).
5853            let base = match cur.next() {
5854                Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
5855                    match &t.kind {
5856                        TokKind::Word(w) => w.clone(),
5857                        _ => unreachable!(),
5858                    }
5859                }
5860                _ => return Err(cur.err("`$` requires a variable name")),
5861            };
5862            let mut keys = Vec::new();
5863            loop {
5864                // Key-path dots are gapless too (`~` without `gap`).
5865                let dot = matches!(
5866                    cur.toks.get(cur.pos).map(|t| &t.kind),
5867                    Some(TokKind::Punct('.'))
5868                ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
5869                let seg = cur.toks.get(cur.pos + 1);
5870                let seg_ok = dot
5871                    && matches!(seg.map(|t| &t.kind), Some(TokKind::Word(w)) if is_key_segment(w))
5872                    && seg.is_some_and(|t| t.joint);
5873                if !seg_ok {
5874                    break;
5875                }
5876                if let Some(TokKind::Word(w)) = seg.map(|t| &t.kind) {
5877                    keys.push(w.clone());
5878                }
5879                cur.pos += 2;
5880            }
5881            if keys.is_empty() {
5882                Ok(Expr::Var(base))
5883            } else {
5884                Ok(Expr::KeyPath { base, keys })
5885            }
5886        }
5887        Some(TokKind::Word(w)) if w == "env" => {
5888            // `env:KEY` read when the full shape matches gaplessly
5889            // (atomic `env_read`); otherwise a bare word (`env` alone,
5890            // `env:k` lowercase) for the error path, exactly like the
5891            // grammar's mismatch.
5892            let key_ok = matches!(
5893                cur.toks.get(cur.pos + 1).map(|t| &t.kind),
5894                Some(TokKind::Punct(':'))
5895            ) && cur.toks.get(cur.pos + 1).is_some_and(|t| t.joint)
5896                && matches!(
5897                    cur.toks.get(cur.pos + 2).map(|t| &t.kind),
5898                    Some(TokKind::Word(k)) if is_env_key(k)
5899                )
5900                && cur.toks.get(cur.pos + 2).is_some_and(|t| t.joint);
5901            if !key_ok {
5902                return parse_bare_atom(cur, ctx, false);
5903            }
5904            cur.pos += 1;
5905            cur.pos += 1;
5906            match cur.next() {
5907                Some(t) => match &t.kind {
5908                    TokKind::Word(k) => Ok(Expr::Env(k.clone())),
5909                    _ => Err(cur.err("unreachable")),
5910                },
5911                None => Err(cur.err("unreachable")),
5912            }
5913        }
5914        Some(TokKind::Group {
5915            delim: GroupDelim::Bracket,
5916            inner,
5917            ..
5918        }) => {
5919            let inner = inner.clone();
5920            cur.pos += 1;
5921            parse_list_literal(&inner, cur.stmt, ctx)
5922        }
5923        Some(TokKind::Group {
5924            delim: GroupDelim::Brace,
5925            inner,
5926            ..
5927        }) => {
5928            let inner = inner.clone();
5929            cur.pos += 1;
5930            parse_map_or_block(&inner, cur.stmt, ctx)
5931        }
5932        Some(TokKind::Str { text, .. }) => {
5933            let text = text.clone();
5934            cur.pos += 1;
5935            Ok(Expr::Literal(Value::string(text)))
5936        }
5937        Some(TokKind::BlockStr(full)) => {
5938            let full = full.clone();
5939            cur.pos += 1;
5940            Ok(Expr::Literal(Value::string(
5941                crate::command::lower_block_string(&full),
5942            )))
5943        }
5944        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => {
5945            parse_numeric_atom(cur, ctx)
5946        }
5947        Some(TokKind::Word(_)) => parse_bare_atom(cur, ctx, false),
5948        Some(TokKind::Punct('-')) => parse_bare_atom(cur, ctx, true),
5949        Some(TokKind::Punct('/')) => parse_bare_atom(cur, ctx, false),
5950        _ => Err(cur.err("missing expression operand")),
5951    }
5952}
5953
5954/// Bare-word atom with a `-` lead (the caller proved it is not
5955/// negation): consumes the joint `-/.'/'` run for the bare-word
5956/// shape.
5957fn parse_bare_atom(
5958    cur: &mut Cursor,
5959    _ctx: &ParseCtx,
5960    leading_dash: bool,
5961) -> Result<Expr, TokenError> {
5962    let text = expr_bare_run(cur, leading_dash)?;
5963    match text.as_str() {
5964        "true" => Ok(Expr::Literal(Value::bool(true))),
5965        "false" => Ok(Expr::Literal(Value::bool(false))),
5966        _ => Ok(Expr::Literal(Value::string(text))),
5967    }
5968}
5969
5970/// Numeric atom: rejoin dotted tails, apply the shape gate and the
5971/// follower rule, then the shared classifier. Anything failing the
5972/// gate or follower reparses as a bare word (durations, versions,
5973/// paths), exactly like the grammar's numeric-literal-or-bare-word
5974/// order.
5975fn parse_numeric_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5976    let start = cur.pos;
5977    let text = number_head(cur).ok_or_else(|| cur.err("missing expression operand"))?;
5978    let consumed = {
5979        let mut n = 1;
5980        let mut p = start + 1;
5981        while matches!(cur.toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('.')))
5982            && cur.toks.get(p).is_some_and(|t| t.joint)
5983            && matches!(
5984                cur.toks.get(p + 1).map(|t| &t.kind),
5985                Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_')
5986            )
5987            && cur.toks.get(p + 1).is_some_and(|t| t.joint)
5988        {
5989            n += 2;
5990            p += 2;
5991        }
5992        n
5993    };
5994    if !numeric_shape_ok(&text) || number_falls_to_bare(cur, consumed) {
5995        return parse_bare_atom(cur, ctx, false);
5996    }
5997    cur.pos += consumed;
5998    classify_numeric_text(&text).map_err(|msg| cur.err(msg))
5999}
6000
6001/// Full expression with the top-level boundary rejection (mirrors
6002/// `parse_expr`): a stray `UnsignedIntBoundary` that no unary `-`
6003/// consumed is an overflow error.
6004fn parse_expr_checked(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6005    let expr = parse_expr_or(cur, ctx)?;
6006    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
6007        return Err(cur.err("integer overflow: 9223372036854775808 exceeds i64::MAX"));
6008    }
6009    Ok(expr)
6010}
6011
6012/// List literal over a bracket group's contents: `gap_nl` newlines
6013/// skip at the edges and after commas only, mirroring the grammar.
6014fn parse_list_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6015    let mut cur = Cursor::expr(inner, stmt);
6016    cur.skip_gap_nl();
6017    if cur.done() {
6018        return Ok(Expr::List(vec![]));
6019    }
6020    let mut items = Vec::new();
6021    loop {
6022        let item = parse_expr_checked(&mut cur, ctx)?;
6023        reject_boundary(&lowering_ctx(stmt), &item).map_err(|e| cur.err(e.to_string()))?;
6024        items.push(item);
6025        cur.skip_gap_nl();
6026        if cur.eat_punct(',') {
6027            cur.skip_gap_nl();
6028            continue;
6029        }
6030        break;
6031    }
6032    if !cur.done() {
6033        return Err(cur.err("unexpected text in list"));
6034    }
6035    Ok(Expr::List(items))
6036}
6037
6038/// Map literal attempt over a brace group's contents: comma-separated
6039/// `key: value` entries with `gap` (never newline) around the colon.
6040/// Any entry failing the shape is not a map: the caller reports the
6041/// deferred block slice (the grammar tries `block` next, which fails
6042/// the same inputs at this stage).
6043fn parse_map_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6044    let mut entries = Vec::new();
6045    // Empty (or blank/comment-only) braces are an empty map.
6046    if inner
6047        .iter()
6048        .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
6049    {
6050        return Ok(Expr::Map(vec![]));
6051    }
6052    for part in split_top_commas(inner) {
6053        let mut sub = Cursor::expr(part, stmt);
6054        sub.skip_gap_nl();
6055        let key = match sub.toks.get(sub.pos).map(|t| &t.kind) {
6056            Some(TokKind::Str { text, .. }) => {
6057                let key = text.clone();
6058                sub.pos += 1;
6059                key
6060            }
6061            Some(TokKind::BlockStr(full)) => {
6062                let key = crate::command::lower_block_string(full);
6063                sub.pos += 1;
6064                key
6065            }
6066            Some(TokKind::Word(_)) | Some(TokKind::Punct('-')) | Some(TokKind::Punct('/')) => {
6067                map_bare_key(&mut sub)?
6068            }
6069            _ => return Err(sub.err("not a map literal")),
6070        };
6071        sub.skip_gap();
6072        if !sub.eat_punct(':') {
6073            return Err(sub.err("not a map literal"));
6074        }
6075        let val = parse_expr_checked(&mut sub, ctx)?;
6076        reject_boundary(&lowering_ctx(stmt), &val).map_err(|e| sub.err(e.to_string()))?;
6077        sub.skip_gap_nl();
6078        if !sub.done() {
6079            return Err(sub.err("not a map literal"));
6080        }
6081        entries.push((key, val));
6082    }
6083    Ok(Expr::Map(entries))
6084}
6085
6086/// Bare map key: joint `-/.'/'`-run, mirroring the bare-word charset
6087/// (no bool/numeric classification: keys are always strings).
6088fn map_bare_key(sub: &mut Cursor) -> Result<String, TokenError> {
6089    let mut out = String::new();
6090    if matches!(
6091        sub.toks.get(sub.pos).map(|t| &t.kind),
6092        Some(TokKind::Punct('-'))
6093    ) {
6094        out.push('-');
6095        sub.pos += 1;
6096    }
6097    // Leading `/` reads literally too (the bare-word shape admits `/`
6098    // anywhere: `{/a: 1}`, `{//c: 1}`); the joint loop below
6099    // continues the run.
6100    if matches!(
6101        sub.toks.get(sub.pos).map(|t| &t.kind),
6102        Some(TokKind::Punct('/'))
6103    ) {
6104        out.push('/');
6105        sub.pos += 1;
6106    }
6107    match sub.toks.get(sub.pos).map(|t| &t.kind) {
6108        Some(TokKind::Word(w)) => {
6109            out.push_str(w);
6110            sub.pos += 1;
6111        }
6112        // A leading `/` above already started the run; anything
6113        // else still needs a word head.
6114        _ if !out.is_empty() => {}
6115        _ => return Err(sub.err("not a map literal")),
6116    }
6117    while let Some(t) = sub.toks.get(sub.pos) {
6118        if !t.joint {
6119            break;
6120        }
6121        match &t.kind {
6122            TokKind::Word(w) => {
6123                out.push_str(w);
6124                sub.pos += 1;
6125            }
6126            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
6127                out.push(*c);
6128                sub.pos += 1;
6129            }
6130            _ => break,
6131        }
6132    }
6133    if out.contains('\\') {
6134        return Err(sub.err("unexpected escape in map key"));
6135    }
6136    Ok(out)
6137}
6138
6139/// Map-or-block over a brace group's contents: maps parse literally;
6140/// anything else is an inline block (`Expr::Block` over the body
6141/// steps, scopes unmarked like every braced body).
6142fn parse_map_or_block(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6143    match parse_map_literal(inner, stmt, ctx) {
6144        Ok(map) => Ok(map),
6145        Err(_) => Ok(Expr::Block(parse_body_steps(inner, stmt, ctx, false)?)),
6146    }
6147}
6148
6149/// Parse one standalone expression from lexed tokens (the
6150/// `parse_expression_str` entry point): a full tier parse with
6151/// top-level boundary rejection and full consumption.
6152pub(crate) fn parse_single_expr(
6153    toks: &[Tok],
6154    stmt: usize,
6155    ctx: &ParseCtx,
6156) -> Result<Expr, TokenError> {
6157    let mut cur = Cursor::expr(toks, stmt);
6158    let expr = parse_expr_checked(&mut cur, ctx)?;
6159    if !cur.done() {
6160        return Err(cur.err("unexpected text in expression"));
6161    }
6162    Ok(expr)
6163}
6164
6165/// Assignment `=`: the first `=` neither glued to a following `=`
6166/// (`==`) nor glued after `!`/`<`/`>`/`=` (`!=`, `<=`, `>=`, second of
6167/// `==`). Glued-ness reads off the `=`'s own `joint` (gap before it)
6168/// and the follower's (gap after it). Anything else leaves the
6169/// statement bare (`LET $p: PIPE`), exactly where the grammar's `"="`
6170/// match fails.
6171fn find_assign_eq(body: &[Tok]) -> Option<usize> {
6172    for (i, tok) in body.iter().enumerate() {
6173        if !matches!(&tok.kind, TokKind::Punct('=')) {
6174            continue;
6175        }
6176        let next_eq = body
6177            .get(i + 1)
6178            .is_some_and(|t| t.joint && matches!(&t.kind, TokKind::Punct('=')));
6179        let prev_op = tok.joint
6180            && i > 0
6181            && matches!(&body[i - 1].kind, TokKind::Punct('!' | '<' | '>' | '='));
6182        if !next_eq && !prev_op {
6183            return Some(i);
6184        }
6185    }
6186    None
6187}
6188
6189/// Render a type region joint-aware (`LIST< MAP >` keeps its gaps for
6190/// the shared canonicalizer, exactly like `type_tag.as_str()`).
6191fn render_type_region(toks: &[Tok], stmt: usize) -> Result<String, TokenError> {
6192    let mut out = String::new();
6193    for tok in toks {
6194        // Ridden newlines from multi-line `<...>` shapes carry no
6195        // output, so the shape canonicalizes exactly like one line.
6196        if matches!(&tok.kind, TokKind::Newline) {
6197            continue;
6198        }
6199        if !tok.joint && !out.is_empty() {
6200            out.push(' ');
6201        }
6202        match &tok.kind {
6203            TokKind::Word(w) => out.push_str(w),
6204            TokKind::Punct(c) => out.push(*c),
6205            _ => {
6206                return Err(TokenError {
6207                    stmt,
6208                    msg: "malformed type in LET".to_string(),
6209                    line: 0,
6210                    col: 0,
6211                    kind: None,
6212                });
6213            }
6214        }
6215    }
6216    if out.is_empty() {
6217        return Err(TokenError {
6218            stmt,
6219            msg: "LET requires explicit type: LET $var: TYPE = <expr>".to_string(),
6220            line: 0,
6221            col: 0,
6222            kind: None,
6223        });
6224    }
6225    Ok(crate::canonicalize_spelling(&out))
6226}
6227
6228fn expect_dollar_var(cur: &mut Cursor, msg: &str) -> Result<String, TokenError> {
6229    // Atomic `dollar_ident`: no gap between `$` and the name (the
6230    // enclosing statements are compound-atomic, so implicit spacing is
6231    // off and only explicit `gap`s admit whitespace).
6232    match cur.next() {
6233        Some(t) if matches!(&t.kind, TokKind::Punct('$')) => {}
6234        _ => return Err(cur.err(msg)),
6235    }
6236    match cur.next() {
6237        Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
6238            match &t.kind {
6239                TokKind::Word(w) => Ok(w.clone()),
6240                _ => unreachable!(),
6241            }
6242        }
6243        _ => Err(cur.err(msg)),
6244    }
6245}
6246
6247/// `LET` body: `LET` is already matched. Returns `None` (miss to
6248/// generic, which fails in lowering like the grammar's committed
6249/// `instruction`) when the shape cannot match any `LET` form: no
6250/// gapless `$var`, or no `:` after it
6251/// (every form needs `: TYPE`). Past that the shape is committed and
6252/// malformed tails fail loudly.
6253fn parse_let_body(
6254    body: &[Tok],
6255    stmt: usize,
6256    ctx: &ParseCtx,
6257) -> Result<Option<(StepKind, usize)>, TokenError> {
6258    let mut cur = Cursor::expr(body, stmt);
6259    match cur.next() {
6260        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_LET) => {}
6261        _ => return Err(cur.err("unreachable")),
6262    }
6263    // No `$var`: no `LET` form can match (miss, never a hard fail).
6264    let var = match expect_dollar_var(&mut cur, "LET requires a variable") {
6265        Ok(var) => var,
6266        Err(_) => return Ok(None),
6267    };
6268    // The header allows gaps (comments, never newlines).
6269    cur.skip_gap();
6270    // No `:`: no `LET` form can match (miss, like `LET $x = 1`).
6271    if !cur.eat_punct(':') {
6272        return Ok(None);
6273    }
6274    // Type region runs to the assignment `=`; it cannot contain one.
6275    let type_start = cur.pos;
6276    let assign = find_assign_eq(&body[type_start..]).map(|i| i + type_start);
6277    let Some(eq) = assign else {
6278        // Bare `LET $p: PIPE` mints a fresh pipe and ends with the
6279        // type word (trailing elements loop on, probed); every other
6280        // bare type is a validation error, mirroring the grammar.
6281        if matches!(
6282            body.get(type_start).map(|t| &t.kind),
6283            Some(TokKind::Word(w)) if w == crate::TypeTag::Pipe.name()
6284        ) {
6285            return Ok(Some((
6286                StepKind::Assign {
6287                    var,
6288                    decl_type: crate::TypeTag::Pipe.name().to_string(),
6289                    expr: Expr::FreshPipe,
6290                },
6291                type_start + 1,
6292            )));
6293        }
6294        return Err(cur.err(
6295            "LET requires an expression: LET $var: TYPE = <expr> (only LET $p: PIPE omits the initializer)",
6296        ));
6297    };
6298    let decl_type = render_type_region(&body[type_start..eq], stmt)?;
6299    let (kind, rhs_used) = parse_let_rhs(&body[eq + 1..], var, decl_type, stmt, ctx)?;
6300    Ok(Some((kind, eq + 1 + rhs_used)))
6301}
6302
6303/// LET right-hand side dispatch, mirroring the grammar order
6304/// (`let_async`, then `let_capture`, then `let_statement`):
6305/// `WITH_IO`-led lines branch async/sync like
6306/// `parse_let_async_statement_from_pair`, `ASYNC`-led lines spawn
6307/// tasks, `TIMEOUT`-led lines capture through the wrapper,
6308/// `AWAIT $v` captures, RUN exec-form captures, known commands
6309/// capture through the generic parser (lowering failures fatal,
6310/// exactly like the committed grammar alternative), and anything
6311/// else parses as an expression (unknown leads included). Returns
6312/// the kind and RHS tokens consumed: captures ending in structural
6313/// pairs leave trailing elements for the caller.
6314fn parse_let_rhs(
6315    rhs: &[Tok],
6316    var: String,
6317    decl_type: String,
6318    stmt: usize,
6319    ctx: &ParseCtx,
6320) -> Result<(StepKind, usize), TokenError> {
6321    // Leading gap comments vanish like the `=` gap (but a `//`/`#`
6322    // to end of input leaves no expression, failing).
6323    let mut lead = Cursor::expr(rhs, stmt);
6324    lead.skip_gap();
6325    let (rhs, skipped) = (&rhs[lead.pos..], lead.pos);
6326    let head_word = match rhs.first().map(|t| &t.kind) {
6327        Some(TokKind::Word(w)) => Some(w.clone()),
6328        _ => None,
6329    };
6330    // `WITH_IO`-led lines share `let_async_statement` with the
6331    // `ASYNC` forms (the grammar claims every WITH_IO-led LET
6332    // there); shape misses fall through to generic below.
6333    if head_word.as_deref() == Some(KEYWORD_WITH_IO)
6334        && let Some(found) = try_let_with_io_rhs(rhs, var.clone(), decl_type.clone(), stmt, ctx)?
6335    {
6336        let (kind, used) = found;
6337        return Ok((kind, skipped + used));
6338    }
6339    // `ASYNC`-led lines (with followers; alone they commit to the
6340    // generic path like the grammar, failing in lowering) spawn
6341    // background tasks. No `WITH_IO` scan here (probed: the LET
6342    // path accepts what statement `ASYNC` rejects).
6343    if head_word.as_deref() == Some(KEYWORD_ASYNC) && rhs.len() > 1 {
6344        let (kind, used) = parse_let_async_rhs(&rhs[1..], var, decl_type, stmt, ctx)?;
6345        return Ok((kind, skipped + 1 + used));
6346    }
6347    // `TIMEOUT`-led lines capture through the wrapper (shape misses
6348    // fall through to generic, which fails in lowering).
6349    if head_word.as_deref() == Some(KEYWORD_TIMEOUT)
6350        && let Some((kind, used)) = parse_timeout_single(rhs, 0, stmt, ctx)?
6351    {
6352        let span = lowering_ctx(stmt);
6353        crate::commands::reject_async_in_capture(&span, &kind).map_err(|e| TokenError {
6354            stmt,
6355            msg: e.to_string(),
6356            line: 0,
6357            col: 0,
6358            kind: None,
6359        })?;
6360        crate::commands::reject_pipe_stdout_in_capture(&span, &kind).map_err(|e| TokenError {
6361            stmt,
6362            msg: e.to_string(),
6363            line: 0,
6364            col: 0,
6365            kind: None,
6366        })?;
6367        return Ok((
6368            StepKind::AssignCapture {
6369                var,
6370                decl_type,
6371                cmd: Box::new(kind),
6372            },
6373            skipped + used,
6374        ));
6375    }
6376    // `AWAIT $v` captures the task output (`$`+name ride gapless in
6377    // this atomic position, like the grammar); anything else
6378    // `AWAIT`-led goes generic below (lowering fails it, probed).
6379    if head_word.as_deref() == Some(KEYWORD_AWAIT)
6380        && rhs.len() == 3
6381        && let (Some(dollar), Some(task)) = (rhs.get(1), rhs.get(2))
6382        && matches!(&dollar.kind, TokKind::Punct('$'))
6383        && task.joint
6384        && let TokKind::Word(task_var) = &task.kind
6385        && is_ident_word(task_var)
6386    {
6387        return Ok((
6388            StepKind::AwaitCapture {
6389                out_var: var,
6390                out_type: decl_type,
6391                task_var: task_var.clone(),
6392            },
6393            skipped + 3,
6394        ));
6395    }
6396    // RUN exec form captures the structured argv (gapped bracket;
6397    // a joint bracket falls through to generic, which fails it in
6398    // lowering).
6399    if head_word.as_deref() == Some(KEYWORD_RUN)
6400        && matches!(
6401            rhs.get(1).map(|t| (&t.kind, t.joint)),
6402            Some((
6403                TokKind::Group {
6404                    delim: GroupDelim::Bracket,
6405                    ..
6406                },
6407                false
6408            ))
6409        )
6410        && rhs.len() == 2
6411    {
6412        let inner = match &rhs[1].kind {
6413            TokKind::Group { inner, .. } => inner.clone(),
6414            _ => unreachable!(),
6415        };
6416        // Non-map blocks miss the exec shape; fall through below
6417        // (known-command capture, then expression), mirroring the
6418        // grammar's ordered alternatives.
6419        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
6420            let kind =
6421                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
6422            return Ok((
6423                StepKind::AssignCapture {
6424                    var,
6425                    decl_type,
6426                    cmd: Box::new(kind),
6427                },
6428                skipped + 2,
6429            ));
6430        }
6431    }
6432    // File `IMPORT ["path" AS ALIAS]` (#115) captures the imported
6433    // pipeline's `RETURN` value like a call (`LET $r = IMPORT ...`
6434    // lowers to `AssignCapture`): exactly one file entry, no modules.
6435    // Anything else shaped like an import is a hard error; shape misses
6436    // fall through to generic below, which fails them in lowering.
6437    if head_word.as_deref() == Some(KEYWORD_IMPORT)
6438        && let Some((path, alias, used)) = parse_single_file_import(rhs, 0, stmt, ctx)?
6439    {
6440        return Ok((
6441            StepKind::AssignCapture {
6442                var,
6443                decl_type,
6444                cmd: Box::new(StepKind::ImportFile { path, alias }),
6445            },
6446            skipped + used,
6447        ));
6448    }
6449    // Known-command leads capture through the generic parser
6450    // (lowering failures are fatal here, exactly like the committed
6451    // grammar alternative: probed wrapper-alone and `ISOLATED`-led
6452    // shapes error in lowering); unknown leads parse as expressions.
6453    match &head_word {
6454        Some(head) if is_known_command(head) => {
6455            let (cmd, used) = parse_inner_command(rhs, stmt, ctx)?;
6456            let span = lowering_ctx(stmt);
6457            crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| TokenError {
6458                stmt,
6459                msg: e.to_string(),
6460                line: 0,
6461                col: 0,
6462                kind: None,
6463            })?;
6464            crate::commands::reject_pipe_stdout_in_capture(&span, &cmd).map_err(|e| {
6465                TokenError {
6466                    stmt,
6467                    msg: e.to_string(),
6468                    line: 0,
6469                    col: 0,
6470                    kind: None,
6471                }
6472            })?;
6473            // `INHERIT_ENV`-led lines land here (generic): the
6474            // nesting check rejects them (probed).
6475            crate::commands::reject_nested_inherit_env(&span, &cmd).map_err(|e| TokenError {
6476                stmt,
6477                msg: e.to_string(),
6478                line: 0,
6479                col: 0,
6480                kind: None,
6481            })?;
6482            return Ok((
6483                StepKind::AssignCapture {
6484                    var,
6485                    decl_type,
6486                    cmd: Box::new(cmd),
6487                },
6488                skipped + used,
6489            ));
6490        }
6491        _ => {}
6492    }
6493    let mut cur = Cursor::expr(rhs, stmt);
6494    let expr = parse_expr_checked(&mut cur, ctx)?;
6495    let used = skipped + cur.pos;
6496    Ok((
6497        StepKind::Assign {
6498            var,
6499            decl_type,
6500            expr,
6501        },
6502        used,
6503    ))
6504}
6505
6506/// `WITH_IO`-led LET right-hand side, mirroring
6507/// `parse_let_async_statement_from_pair`'s `with_io_command` branch:
6508/// wrapping `ASYNC` binds a pipe-wired background task (multi-step
6509/// blocks fail loudly), wrapping a sync command captures its stdout
6510/// (async bodies and `stdout` pipes fail loudly), and a bare
6511/// bracket fails validation. `None` on shape miss (bad bracket:
6512/// the caller goes generic, which fails in lowering).
6513fn try_let_with_io_rhs(
6514    rhs: &[Tok],
6515    var: String,
6516    decl_type: String,
6517    stmt: usize,
6518    ctx: &ParseCtx,
6519) -> Result<Option<(StepKind, usize)>, TokenError> {
6520    let bracket = match rhs.get(1) {
6521        Some(t)
6522            if !t.joint
6523                && matches!(
6524                    &t.kind,
6525                    TokKind::Group {
6526                        delim: GroupDelim::Bracket,
6527                        ..
6528                    }
6529                ) =>
6530        {
6531            t
6532        }
6533        _ => return Ok(None),
6534    };
6535    let inner = match &bracket.kind {
6536        TokKind::Group { inner, .. } => inner.clone(),
6537        _ => unreachable!(),
6538    };
6539    let bindings = match parse_io_bindings(&inner, stmt)? {
6540        Some(bindings) => bindings,
6541        None => return Ok(None),
6542    };
6543    let fail = |msg: String| TokenError {
6544        stmt,
6545        msg,
6546        line: 0,
6547        col: 0,
6548        kind: None,
6549    };
6550    let rest = &rhs[2..];
6551    let Some(first) = rest.first() else {
6552        // Bare bracket: the grammar's committed validation error.
6553        return Err(fail(
6554            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
6555                .to_string(),
6556        ));
6557    };
6558    if first.joint {
6559        // The inner rides after a `sep`: joint followers miss the
6560        // shape and fail validation like the grammar's bare bracket.
6561        return Err(fail(
6562            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
6563                .to_string(),
6564        ));
6565    }
6566    if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_ASYNC) {
6567        // `WITH_IO [..] ASYNC <single|block>`: the bindings apply
6568        // inside the task thread (same shape as a one-step body
6569        // holding one `WITH_IO` step, which the runtime supports).
6570        // A bare `ASYNC` goes generic and fails in lowering
6571        // (`unknown command: ASYNC`, probed).
6572        let after = &rest[1..];
6573        if after.is_empty() {
6574            // Bare `ASYNC`: the grammar commits to `instruction`
6575            // and lowering fails it (`unknown command: ASYNC`,
6576            // probed); mirror by running generic, staying failed
6577            // even under a lenient dispatcher.
6578            match parse_inner_command(&rest[..1], stmt, ctx) {
6579                Err(e) => return Err(e),
6580                Ok(_) => {
6581                    return Err(fail("LET $var: HANDLE = ASYNC requires a body".to_string()));
6582                }
6583            }
6584        }
6585        if let Some(second) = after.first()
6586            && matches!(
6587                &second.kind,
6588                TokKind::Group {
6589                    delim: GroupDelim::Brace,
6590                    ..
6591                }
6592            )
6593            && !is_template_brace(second)
6594        {
6595            let brace_inner = match &second.kind {
6596                TokKind::Group { inner, .. } => inner.clone(),
6597                _ => unreachable!(),
6598            };
6599            let body = parse_body_steps(&brace_inner, stmt, ctx, false)?;
6600            if body.len() != 1 {
6601                return Err(fail(
6602                        "LET $var: TYPE = WITH_IO [..] ASYNC accepts a single command; use LET $var: HANDLE = ASYNC {{ ... }} with WITH_IO inside the block for multi-step tasks"
6603                            .to_string(),
6604                    ));
6605            }
6606            let wrapped = Step {
6607                guard: None,
6608                kind: StepKind::WithIo {
6609                    bindings,
6610                    cmd: Box::new(
6611                        body.into_iter()
6612                            .next()
6613                            .ok_or_else(|| {
6614                                fail("LET $var: HANDLE = ASYNC requires a body".to_string())
6615                            })?
6616                            .kind,
6617                    ),
6618                },
6619                scope_enter: 0,
6620                scope_exit: 0,
6621                line: 0,
6622                col: 0,
6623            };
6624            return Ok(Some((
6625                StepKind::AssignAsync {
6626                    var,
6627                    decl_type,
6628                    body: vec![wrapped],
6629                },
6630                2 + 2,
6631            )));
6632        }
6633        if after.first().is_some_and(|t| t.joint) {
6634            // Joint followers miss the inner `sep`: same validation
6635            // error as the bare bracket.
6636            return Err(fail(
6637                "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
6638                    .to_string(),
6639            ));
6640        }
6641        let (cmd, used) = parse_single_inner(
6642            rest,
6643            1,
6644            stmt,
6645            ctx,
6646            InnerRules {
6647                allow_await: false,
6648                allow_with_io: false,
6649            },
6650        )?;
6651        let wrapped = Step {
6652            guard: None,
6653            kind: StepKind::WithIo {
6654                bindings,
6655                cmd: Box::new(cmd),
6656            },
6657            scope_enter: 0,
6658            scope_exit: 0,
6659            line: 0,
6660            col: 0,
6661        };
6662        let kind = StepKind::AssignAsync {
6663            var,
6664            decl_type,
6665            body: vec![wrapped],
6666        };
6667        let span = lowering_ctx(stmt);
6668        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
6669            stmt,
6670            msg: e.to_string(),
6671            line: 0,
6672            col: 0,
6673            kind: None,
6674        })?;
6675        return Ok(Some((kind, 2 + 1 + used)));
6676    }
6677    if matches!(
6678        &first.kind,
6679        TokKind::Group {
6680            delim: GroupDelim::Brace,
6681            ..
6682        }
6683    ) {
6684        // A brace is no sync command: same validation error (probed).
6685        return Err(fail(
6686            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
6687                .to_string(),
6688        ));
6689    }
6690    // Sync inner: capture with the shared checks (the capture sink
6691    // owns stdout; async never runs inline).
6692    let (cmd, used) = parse_single_inner(
6693        rest,
6694        0,
6695        stmt,
6696        ctx,
6697        InnerRules {
6698            allow_await: false,
6699            allow_with_io: true,
6700        },
6701    )?;
6702    let span = lowering_ctx(stmt);
6703    if crate::commands::has_stdout_pipe(&bindings) {
6704        return Err(fail(
6705            "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
6706                .to_string(),
6707        ));
6708    }
6709    crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| TokenError {
6710        stmt,
6711        msg: e.to_string(),
6712        line: 0,
6713        col: 0,
6714        kind: None,
6715    })?;
6716    Ok(Some((
6717        StepKind::AssignCapture {
6718            var,
6719            decl_type,
6720            cmd: Box::new(StepKind::WithIo {
6721                bindings,
6722                cmd: Box::new(cmd),
6723            }),
6724        },
6725        2 + used,
6726    )))
6727}
6728
6729/// `ASYNC`-led LET right-hand side (the tokens after `ASYNC`):
6730/// a block or single command becomes the task body. No `WITH_IO`
6731/// scan (probed: this path accepts what statement `ASYNC`
6732/// rejects); nesting still fails loudly through the shared check.
6733fn parse_let_async_rhs(
6734    rest: &[Tok],
6735    var: String,
6736    decl_type: String,
6737    stmt: usize,
6738    ctx: &ParseCtx,
6739) -> Result<(StepKind, usize), TokenError> {
6740    let Some(first) = rest.first() else {
6741        return Err(TokenError {
6742            stmt,
6743            msg: "LET $var: HANDLE = ASYNC requires a body".to_string(),
6744            line: 0,
6745            col: 0,
6746            kind: None,
6747        });
6748    };
6749    if matches!(
6750        &first.kind,
6751        TokKind::Group {
6752            delim: GroupDelim::Brace,
6753            ..
6754        }
6755    ) && !is_template_brace(first)
6756    {
6757        let inner = match &first.kind {
6758            TokKind::Group { inner, .. } => inner.clone(),
6759            _ => unreachable!(),
6760        };
6761        let body = parse_body_steps(&inner, stmt, ctx, false)?;
6762        let kind = StepKind::AssignAsync {
6763            var,
6764            decl_type,
6765            body,
6766        };
6767        let span = lowering_ctx(stmt);
6768        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
6769            stmt,
6770            msg: e.to_string(),
6771            line: 0,
6772            col: 0,
6773            kind: None,
6774        })?;
6775        return Ok((kind, 1));
6776    }
6777    if first.joint {
6778        return Err(TokenError {
6779            stmt,
6780            msg: "LET $var: HANDLE = ASYNC requires a body".to_string(),
6781            line: 0,
6782            col: 0,
6783            kind: None,
6784        });
6785    }
6786    let (cmd, used) = parse_single_inner(
6787        rest,
6788        0,
6789        stmt,
6790        ctx,
6791        InnerRules {
6792            allow_await: false,
6793            allow_with_io: false,
6794        },
6795    )?;
6796    let kind = StepKind::AssignAsync {
6797        var,
6798        decl_type,
6799        body: vec![Step {
6800            guard: None,
6801            kind: cmd,
6802            scope_enter: 0,
6803            scope_exit: 0,
6804            line: 0,
6805            col: 0,
6806        }],
6807    };
6808    let span = lowering_ctx(stmt);
6809    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
6810        stmt,
6811        msg: e.to_string(),
6812        line: 0,
6813        col: 0,
6814        kind: None,
6815    })?;
6816    Ok((kind, used))
6817}
6818
6819fn parse_set_body(
6820    body: &[Tok],
6821    stmt: usize,
6822    ctx: &ParseCtx,
6823) -> Result<(StepKind, usize), TokenError> {
6824    let mut cur = Cursor::expr(body, stmt);
6825    let var = expect_dollar_var(&mut cur, "mutation requires a variable: $var = <expr>")?;
6826    let assign = find_assign_eq(&body[cur.pos..]).map(|i| i + cur.pos);
6827    let eq = match assign {
6828        Some(eq) => eq,
6829        None => {
6830            return Err(cur.err("mutation requires a variable: $var = <expr>"));
6831        }
6832    };
6833    cur.pos = eq + 1;
6834    // Leading gap comments vanish like the `=` gap.
6835    cur.skip_gap();
6836    let expr = parse_expr_checked(&mut cur, ctx)?;
6837    Ok((StepKind::Set { var, expr }, cur.pos))
6838}
6839
6840fn parse_return_body(
6841    body: &[Tok],
6842    stmt: usize,
6843    ctx: &ParseCtx,
6844) -> Result<(StepKind, usize), TokenError> {
6845    let mut cur = Cursor::expr(body, stmt);
6846    match cur.next() {
6847        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_RETURN) => {}
6848        _ => return Err(cur.err("unreachable")),
6849    }
6850    if cur.done() {
6851        return Ok((
6852            StepKind::Return {
6853                expr: Box::new(Expr::Literal(Value::string(String::new()))),
6854            },
6855            cur.pos,
6856        ));
6857    }
6858    let expr = parse_expr_checked(&mut cur, ctx)?;
6859    Ok((
6860        StepKind::Return {
6861            expr: Box::new(expr),
6862        },
6863        cur.pos,
6864    ))
6865}
6866
6867/// Lower one statement to steps through the element loop: the
6868/// statement guard attaches to the first element only (trailing
6869/// elements ride guardless, probed): the pending guard clears after
6870/// the first command token.
6871fn lower_stmt_steps(
6872    stmt: &Stmt,
6873    idx: usize,
6874    ctx: &ParseCtx,
6875    in_block: bool,
6876    mark: bool,
6877) -> Result<Vec<Step>, TokenError> {
6878    let guard = parse_guard_groups(&stmt.guard, idx)?;
6879    // Statement-head braces route here (mid-run braces fail inside
6880    // the element loop): templates and guardless/bare blocks fail
6881    // loudly; guarded braces open guard blocks (top level) or the
6882    // nested quirk (in bodies).
6883    let mut steps = if starts_brace(&stmt.body) {
6884        parse_brace_head(stmt, guard, idx, ctx, in_block, mark)?
6885    } else {
6886        parse_elements(&stmt.body, idx, ctx, guard, in_block)?
6887    };
6888    // Stamp the statement's source position on every directly
6889    // produced step still missing one. Nested body steps were stamped
6890    // by their own statements during recursion, so only direct
6891    // products are claimed here; inner statements keep their own
6892    // lines and columns.
6893    for step in &mut steps {
6894        if step.line == 0 {
6895            step.line = stmt.line;
6896        }
6897        if step.col == 0 {
6898            step.col = stmt.col;
6899        }
6900    }
6901    Ok(steps)
6902}
6903
6904/// Statement-head `{...}` dispatcher. Template braces fail (the
6905/// grammar strands them); guardless top-level braces fail; detached
6906/// or guardless in-body braces fail (no `block_start` in
6907/// `block_element`); guarded braces open a guard scope at top level
6908/// or mirror the nested quirk formula in bodies. Trailing elements
6909/// loop on guardless outside (like the grammar's continued line).
6910fn parse_brace_head(
6911    stmt: &Stmt,
6912    guard: Option<GuardExpr>,
6913    idx: usize,
6914    ctx: &ParseCtx,
6915    in_block: bool,
6916    mark: bool,
6917) -> Result<Vec<Step>, TokenError> {
6918    let brace = &stmt.body[0];
6919    if is_template_brace(brace) {
6920        return Err(TokenError {
6921            stmt: idx,
6922            msg: "'{' without a pending guard".to_string(),
6923            line: 0,
6924            col: 0,
6925            kind: None,
6926        });
6927    }
6928    let inner = match &brace.kind {
6929        TokKind::Group { inner, .. } => inner.clone(),
6930        _ => unreachable!(),
6931    };
6932    if in_block {
6933        // Attached guarded braces only: pending holds all groups but
6934        // the last (the block's own), mirroring the pair structure.
6935        if guard.is_none() || stmt.brace_detached || stmt.guard.is_empty() {
6936            return Err(TokenError {
6937                stmt: idx,
6938                msg: "unexpected '{' in block body".to_string(),
6939                line: 0,
6940                col: 0,
6941                kind: None,
6942            });
6943        }
6944        let n = stmt.guard.len();
6945        let mut pending = None;
6946        if n > 1 {
6947            pending = parse_guard_groups(&stmt.guard[..n - 1], idx)?;
6948        }
6949        let block_guard = parse_guard_groups(&stmt.guard[n - 1..n], idx)?.ok_or(TokenError {
6950            stmt: idx,
6951            msg: "unexpected '{' in block body".to_string(),
6952            line: 0,
6953            col: 0,
6954            kind: None,
6955        })?;
6956        let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
6957        // Guard-block bodies propagate the ambient marking context
6958        // (top-level nesting marks; wrapper bodies never mark).
6959        // Quirk formula verbatim (including the dropped block guard
6960        // with inner guards, probed).
6961        for s in &mut steps {
6962            let inner_guard = s.guard.take();
6963            s.guard = Some(match (pending.clone(), inner_guard) {
6964                (Some(p), Some(e)) => GuardExpr::all(vec![p, e]),
6965                (Some(p), None) => GuardExpr::all(vec![p, block_guard.clone()]),
6966                (None, Some(e)) => e,
6967                (None, None) => block_guard.clone(),
6968            });
6969        }
6970        // Marking contexts bump each nesting level (probed top-level
6971        // double-block 2/2); wrapper bodies stay 0/0.
6972        // Trailing elements ride outside, unmarked.
6973        if mark {
6974            if let Some(first) = steps.first_mut() {
6975                first.scope_enter += 1;
6976            }
6977            if let Some(last) = steps.last_mut() {
6978                last.scope_exit += 1;
6979            }
6980        }
6981        // Trailing elements loop on guardless outside.
6982        if stmt.body.len() > 1 {
6983            let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
6984            steps.append(&mut rest);
6985        }
6986        return Ok(steps);
6987    }
6988    // Top level: guardless braces fail; guarded braces open a guard
6989    // scope (each step folds outer-then-inner with markers).
6990    let Some(outer) = guard else {
6991        return Err(TokenError {
6992            stmt: idx,
6993            msg: "'{' without a pending guard".to_string(),
6994            line: 0,
6995            col: 0,
6996            kind: None,
6997        });
6998    };
6999    let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
7000    if steps.is_empty() {
7001        return Err(TokenError {
7002            stmt: idx,
7003            msg: "guard block must contain at least one command".to_string(),
7004            line: 0,
7005            col: 0,
7006            kind: None,
7007        });
7008    }
7009    for s in &mut steps {
7010        let inner_guard = s.guard.take();
7011        s.guard = Some(match inner_guard {
7012            Some(e) => GuardExpr::all(vec![outer.clone(), e]),
7013            None => outer.clone(),
7014        });
7015    }
7016    if let Some(first) = steps.first_mut() {
7017        first.scope_enter += 1;
7018    }
7019    if let Some(last) = steps.last_mut() {
7020        last.scope_exit += 1;
7021    }
7022    if stmt.body.len() > 1 {
7023        let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
7024        steps.append(&mut rest);
7025    }
7026    Ok(steps)
7027}
7028
7029/// Parse consecutive elements to end of run (the grammar's
7030/// `element*`): structural pairs (calls, RUN-exec, await/cancel,
7031/// wrapper blocks) end mid-run and trailing elements form following
7032/// steps; instructions and expressions consume greedily to the end.
7033fn parse_elements(
7034    toks: &[Tok],
7035    stmt: usize,
7036    ctx: &ParseCtx,
7037    guard: Option<GuardExpr>,
7038    in_block: bool,
7039) -> Result<Vec<Step>, TokenError> {
7040    let mut steps = Vec::new();
7041    let mut pos = 0;
7042    // Statement guard: consumed by the first element that yields a
7043    // step. `IMPORT` yields none, so the guard leaks to the next
7044    // element (probed).
7045    let mut pending_guard: Option<GuardExpr> = guard;
7046    while pos < toks.len() {
7047        // Trailing gap comments between elements (`} #c`, `F("a")
7048        // /*c*/ ECHO`, `LET $x = 1 //c` — the pair ended, so the
7049        // comment is silent like the grammar, never payload):
7050        // `#` and lexer `Comment` markers run to the run end, `//`
7051        // likewise (line comments eat `;` too, and runs hold no
7052        // newlines), `/* */` balances. Mid-run `#`/`/*` stay payload
7053        // text inside the generic path, which consumes everything
7054        // and never loops back here.
7055        if matches!(&toks[pos].kind, TokKind::Punct('#'))
7056            || matches!(&toks[pos].kind, TokKind::Comment(_))
7057        {
7058            break;
7059        }
7060        if matches!(&toks[pos].kind, TokKind::Punct('/')) && is_comment_open(toks, pos) {
7061            if matches!(
7062                toks.get(pos + 1).map(|t| &t.kind),
7063                Some(TokKind::Punct('/'))
7064            ) {
7065                break;
7066            }
7067            match skip_inline_comment(toks, pos) {
7068                Some(past) => {
7069                    pos = past;
7070                    continue;
7071                }
7072                None => {
7073                    return Err(TokenError {
7074                        stmt,
7075                        msg: "unclosed block comment".to_string(),
7076                        line: 0,
7077                        col: 0,
7078                        kind: None,
7079                    });
7080                }
7081            }
7082        }
7083        // `IMPORT` statements update the import frames; module entries
7084        // emit no step (the guard leaks to the next element, probed,
7085        // unless this is top level, where a guarded module import
7086        // fails), while each file entry emits one `ImportFile` step
7087        // carrying the guard. Shape misses fall through to generic
7088        // (lowering fails them).
7089        if matches!(
7090            toks.get(pos).map(|t| &t.kind),
7091            Some(TokKind::Word(w)) if w == KEYWORD_IMPORT
7092        ) {
7093            // Unified statement form (#115): each entry validates hard
7094            // (unknown modules, bad aliases, templates, remote URLs);
7095            // module entries update the frame and emit no step, file
7096            // and harvest entries emit one step each, in source order.
7097            // A top-level guard on a statement with module entries fails
7098            // like the historical directive; file-only statements consume
7099            // the guard like any other element.
7100            if let Some(((modules, kinds), used)) = parse_import_statement(toks, pos, stmt, ctx)? {
7101                if !modules.is_empty() && !in_block && pending_guard.is_some() {
7102                    return Err(TokenError {
7103                        stmt,
7104                        msg: "IMPORT cannot be guarded".to_string(),
7105                        line: 0,
7106                        col: 0,
7107                        kind: None,
7108                    });
7109                }
7110                // Modules-only statements stay zero-step directives: the
7111                // guard leaks to the next element (probed). Anything with
7112                // file or harvest entries consumes it.
7113                let guard = if kinds.is_empty() {
7114                    None
7115                } else {
7116                    pending_guard.take()
7117                };
7118                for kind in kinds {
7119                    steps.push(Step {
7120                        guard: guard.clone(),
7121                        kind,
7122                        scope_enter: 0,
7123                        scope_exit: 0,
7124                        line: 0,
7125                        col: 0,
7126                    });
7127                }
7128                pos += used;
7129                continue;
7130            }
7131        }
7132        let guard = pending_guard.take();
7133        let (mut got, used) = parse_element_at(toks, pos, stmt, ctx, guard, in_block)?;
7134        if used == 0 {
7135            return Err(TokenError {
7136                stmt,
7137                msg: "element consumed no input".to_string(),
7138                line: 0,
7139                col: 0,
7140                kind: None,
7141            });
7142        }
7143        steps.append(&mut got);
7144        pos += used;
7145    }
7146    Ok(steps)
7147}
7148
7149/// Parse one element at `pos`, returning built steps (guard already
7150/// assigned: `first_guard` for the first, folded per io-block inner
7151/// step) and tokens consumed.
7152fn parse_element_at(
7153    toks: &[Tok],
7154    pos: usize,
7155    stmt: usize,
7156    ctx: &ParseCtx,
7157    first_guard: Option<GuardExpr>,
7158    in_block: bool,
7159) -> Result<(Vec<Step>, usize), TokenError> {
7160    let step = |kind: StepKind| Step {
7161        guard: first_guard.clone(),
7162        kind,
7163        scope_enter: 0,
7164        scope_exit: 0,
7165        line: 0,
7166        col: 0,
7167    };
7168    let head_word = match toks.get(pos).map(|t| &t.kind) {
7169        Some(TokKind::Word(w)) => Some(w.clone()),
7170        _ => None,
7171    };
7172    // Mid-run `{...}` (after a call, wrapper block, ...): the
7173    // grammar strands it (`block_start` needs a pending guard or
7174    // `WITH_IO` wait, both consumed), so fail loudly. Statement-head
7175    // braces route through `lower_stmt_steps`, never here.
7176    if starts_brace(&toks[pos..]) {
7177        return Err(TokenError {
7178            stmt,
7179            msg: "'{' without a pending guard".to_string(),
7180            line: 0,
7181            col: 0,
7182            kind: None,
7183        });
7184    }
7185    // LET/SET/RETURN heads parse with groups intact, then trailing
7186    // elements loop on (probed `LET $x: INT = 1 ECHO bye`). LET shape
7187    // misses fall to generic (lowering fails them like a committed
7188    // `instruction` would, e.g. `LET foo`).
7189    if head_word.as_deref() == Some(KEYWORD_LET)
7190        && let Some((kind, used)) = parse_let_body(&toks[pos..], stmt, ctx)?
7191    {
7192        return Ok((vec![step(kind)], used));
7193    }
7194    if matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('$'))) {
7195        let (kind, used) = parse_set_body(&toks[pos..], stmt, ctx)?;
7196        return Ok((vec![step(kind)], used));
7197    }
7198    if head_word.as_deref() == Some(KEYWORD_RETURN) {
7199        let (kind, used) = parse_return_body(&toks[pos..], stmt, ctx)?;
7200        return Ok((vec![step(kind)], used));
7201    }
7202    // Calls route before heads (even known commands take the call
7203    // path with a joint paren, probed `ECHO("hi")`); the call ends
7204    // mid-run and trailing elements loop on (fixes the slice-4a
7205    // divergence, probed).
7206    if call_shape_at(toks, pos, true).is_some() {
7207        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
7208        return Ok((vec![step(kind)], used));
7209    }
7210    // Block statements (shape misses fall to generic, which fails
7211    // them in lowering like the grammar's committed `instruction`).
7212    // `BREAK`/`CONTINUE` take no args (structural, like the grammar):
7213    // each consumes one token and trailing elements loop on (probed
7214    // `BREAK ECHO hi`); a lone trailing word fails downstream like
7215    // the grammar's committed mismatch.
7216    match head_word.as_deref() {
7217        Some(KEYWORD_BREAK) => {
7218            return Ok((vec![step(StepKind::Break)], 1));
7219        }
7220        Some(KEYWORD_CONTINUE) => {
7221            return Ok((vec![step(StepKind::Continue)], 1));
7222        }
7223        Some(KEYWORD_IF) => {
7224            if let Some((kind, used)) = parse_if_at(toks, pos, stmt, ctx)? {
7225                return Ok((vec![step(kind)], used));
7226            }
7227        }
7228        Some(KEYWORD_FOR) => {
7229            if let Some((kind, used)) = parse_for_at(toks, pos, stmt, ctx)? {
7230                return Ok((vec![step(kind)], used));
7231            }
7232        }
7233        Some(KEYWORD_WHILE) => {
7234            if let Some((kind, used)) = parse_while_single(toks, pos, stmt, ctx)? {
7235                return Ok((vec![step(kind)], used));
7236            }
7237        }
7238        Some(KEYWORD_FUNC) => {
7239            if let Some((kind, used)) = parse_func_at(toks, pos, stmt, ctx)? {
7240                return Ok((vec![step(kind)], used));
7241            }
7242        }
7243        Some(KEYWORD_REMOTE) => {
7244            if let Some((kind, used)) = parse_remote_single(toks, pos, stmt, ctx)? {
7245                return Ok((vec![step(kind)], used));
7246            }
7247        }
7248        _ => {}
7249    }
7250    // Wrappers (block or single); shape misses fall to generic.
7251    match head_word.as_deref() {
7252        Some(KEYWORD_WITH_IO) => {
7253            return parse_with_io_element(toks, pos, stmt, ctx, first_guard);
7254        }
7255        Some(KEYWORD_TIMEOUT) => {
7256            if let Some((kind, used)) = parse_timeout_single(toks, pos, stmt, ctx)? {
7257                return Ok((vec![step(kind)], used));
7258            }
7259        }
7260        Some(KEYWORD_ISOLATED) => {
7261            if let Some((kind, used)) = parse_isolated_single(toks, pos, stmt, ctx)? {
7262                return Ok((vec![step(kind)], used));
7263            }
7264        }
7265        Some(KEYWORD_ASYNC) => {
7266            if let Some((kind, used)) = parse_async_single(toks, pos, stmt, ctx)? {
7267                return Ok((vec![step(kind)], used));
7268            }
7269        }
7270        _ => {}
7271    }
7272    // AWAIT/CANCEL statements (element level admits the `$` gap,
7273    // probed); heads without `$` go generic (lowering fails them).
7274    if matches!(
7275        head_word.as_deref(),
7276        Some(KEYWORD_AWAIT) | Some(KEYWORD_CANCEL)
7277    ) && let Some((kind, used)) = parse_await_cancel_at(toks, pos, stmt, false)?
7278    {
7279        return Ok((vec![step(kind)], used));
7280    }
7281    // `INHERIT_ENV [...]` parses strictly even at element level
7282    // (keys stay exact everywhere; slice 5 adds only the
7283    // prelude-order validation). Shape misses go generic.
7284    if head_word.as_deref() == Some(KEYWORD_INHERIT_ENV)
7285        && let Some((kind, used)) = parse_inherit_env_at(toks, pos, stmt)?
7286    {
7287        return Ok((vec![step(kind)], used));
7288    }
7289    // `EXPORT ...` records names (zero steps) or misses to generic;
7290    // level and guard violations fail loudly like the backend.
7291    if head_word.as_deref() == Some(KEYWORD_EXPORT) {
7292        if in_block {
7293            return Err(TokenError {
7294                stmt,
7295                msg: "EXPORT is only allowed at the top level".to_string(),
7296                line: 0,
7297                col: 0,
7298                kind: None,
7299            });
7300        }
7301        if first_guard.is_some() {
7302            return Err(TokenError {
7303                stmt,
7304                msg: "EXPORT cannot be guarded".to_string(),
7305                line: 0,
7306                col: 0,
7307                kind: None,
7308            });
7309        }
7310        if let Some((
7311            ExportNames {
7312                func_names,
7313                type_names,
7314            },
7315            used,
7316        )) = parse_export_at(toks, pos)
7317        {
7318            for name in &func_names {
7319                for part in name.split(MODULE_SEPARATOR) {
7320                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
7321                        .map_err(|e| lower_err(stmt, e))?;
7322                }
7323                if ctx.func_exports.borrow().contains(name)
7324                    || ctx.type_exports.borrow().contains(name)
7325                {
7326                    return Err(TokenError {
7327                        stmt,
7328                        msg: format!("duplicate EXPORT `{name}`"),
7329                        line: 0,
7330                        col: 0,
7331                        kind: Some(ParseErrorKind::Validation {
7332                            command: KEYWORD_EXPORT.to_string(),
7333                        }),
7334                    });
7335                }
7336                ctx.func_exports.borrow_mut().push(name.clone());
7337            }
7338            for name in &type_names {
7339                for part in name.split(MODULE_SEPARATOR) {
7340                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
7341                        .map_err(|e| lower_err(stmt, e))?;
7342                }
7343                if ctx.func_exports.borrow().contains(name)
7344                    || ctx.type_exports.borrow().contains(name)
7345                {
7346                    return Err(TokenError {
7347                        stmt,
7348                        msg: format!("duplicate EXPORT `{name}`"),
7349                        line: 0,
7350                        col: 0,
7351                        kind: Some(ParseErrorKind::Validation {
7352                            command: KEYWORD_EXPORT.to_string(),
7353                        }),
7354                    });
7355                }
7356                ctx.type_exports.borrow_mut().push(name.clone());
7357            }
7358            return Ok((Vec::new(), used));
7359        }
7360    }
7361    // `TYPE NAME = SHAPE` aliases (zero or one step); level and guard
7362    // violations fail loudly, shape misses fall to generic.
7363    if head_word.as_deref() == Some(KEYWORD_TYPE) {
7364        if in_block {
7365            return Err(TokenError {
7366                stmt,
7367                msg: "TYPE must appear at top level".to_string(),
7368                line: 0,
7369                col: 0,
7370                kind: None,
7371            });
7372        }
7373        if first_guard.is_some() {
7374            return Err(TokenError {
7375                stmt,
7376                msg: "TYPE cannot be guarded".to_string(),
7377                line: 0,
7378                col: 0,
7379                kind: None,
7380            });
7381        }
7382        if let Some((kind, used)) = parse_type_stmt_at(toks, pos, stmt)? {
7383            return Ok((vec![step(kind)], used));
7384        }
7385    }
7386    // Lowercase heads name their uppercase form (the grammar's
7387    // `command_name` mismatch): never a bare unknown-command.
7388    if let Some(head) = head_word.as_deref()
7389        && head.chars().all(|c| c.is_ascii_lowercase())
7390        && let upper = head.to_ascii_uppercase()
7391        && (is_known_command(&upper) || crate::STRUCTURAL_KEYWORDS.contains(&upper.as_str()))
7392    {
7393        return Err(TokenError {
7394            stmt,
7395            msg: format!("command must be uppercase: found `{head}`, expected `{upper}`"),
7396            line: 0,
7397            col: 0,
7398            kind: Some(ParseErrorKind::Syntax),
7399        });
7400    }
7401    // RUN-exec ends mid-run (trailing loops on, probed); generic
7402    // instructions consume everything.
7403    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
7404    Ok((vec![step(kind)], used))
7405}
7406
7407/// Element-level `WITH_IO`: a same-run brace (any gap: `]{` works,
7408/// probed) opens the io-block form, wrapping every inner step with
7409/// scope markers; a joint non-brace follower is the pending-guard
7410/// error (the splitter only holds bare brackets); anything else is
7411/// the single form. Shape misses go generic.
7412fn parse_with_io_element(
7413    toks: &[Tok],
7414    pos: usize,
7415    stmt: usize,
7416    ctx: &ParseCtx,
7417    first_guard: Option<GuardExpr>,
7418) -> Result<(Vec<Step>, usize), TokenError> {
7419    // The bracket rides gapped (`sep`); anything else misses the
7420    // shape and generic fails it in lowering.
7421    let bracket = match toks.get(pos + 1) {
7422        Some(t)
7423            if !t.joint
7424                && matches!(
7425                    &t.kind,
7426                    TokKind::Group {
7427                        delim: GroupDelim::Bracket,
7428                        ..
7429                    }
7430                ) =>
7431        {
7432            Some(t)
7433        }
7434        _ => None,
7435    };
7436    let Some(bracket) = bracket else {
7437        // Shape miss: generic fails it in lowering.
7438        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
7439        return Ok((
7440            vec![Step {
7441                guard: first_guard,
7442                kind,
7443                scope_enter: 0,
7444                scope_exit: 0,
7445                line: 0,
7446                col: 0,
7447            }],
7448            used,
7449        ));
7450    };
7451    let inner = match &bracket.kind {
7452        TokKind::Group { inner, .. } => inner.clone(),
7453        _ => unreachable!(),
7454    };
7455    let bindings = match parse_io_bindings(&inner, stmt)? {
7456        Some(bindings) => bindings,
7457        // Shape miss: generic fails it.
7458        None => {
7459            let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
7460            return Ok((
7461                vec![Step {
7462                    guard: first_guard,
7463                    kind,
7464                    scope_enter: 0,
7465                    scope_exit: 0,
7466                    line: 0,
7467                    col: 0,
7468                }],
7469                used,
7470            ));
7471        }
7472    };
7473    let rest = pos + 2;
7474    // Same-run brace opens the io-block form (block-expanded
7475    // bindings skip the tty checks: the runtime repeats them).
7476    if let Some(next) = toks.get(rest)
7477        && matches!(
7478            &next.kind,
7479            TokKind::Group {
7480                delim: GroupDelim::Brace,
7481                ..
7482            }
7483        )
7484        && !is_template_brace(next)
7485    {
7486        let brace_inner = match &next.kind {
7487            TokKind::Group { inner, .. } => inner.clone(),
7488            _ => unreachable!(),
7489        };
7490        let mut steps = parse_body_steps(&brace_inner, stmt, ctx, false)?;
7491        if steps.is_empty() {
7492            return Err(TokenError {
7493                stmt,
7494                msg: "WITH_IO block must contain at least one command".to_string(),
7495                line: 0,
7496                col: 0,
7497                kind: None,
7498            });
7499        }
7500        // Every inner step wraps (merging when already wrapped,
7501        // like nested io scopes); the line guard folds into each
7502        // inner guard, inner-first (probed fold order).
7503        for s in &mut steps {
7504            let merged = match std::mem::replace(&mut s.kind, StepKind::Continue) {
7505                StepKind::WithIo {
7506                    bindings: inner_bindings,
7507                    cmd,
7508                } => StepKind::WithIo {
7509                    bindings: crate::commands::merge_bindings(&bindings, &inner_bindings),
7510                    cmd,
7511                },
7512                other => StepKind::WithIo {
7513                    bindings: bindings.clone(),
7514                    cmd: Box::new(other),
7515                },
7516            };
7517            s.kind = merged;
7518            s.guard = crate::commands::and_guard_exprs(s.guard.take(), first_guard.clone());
7519        }
7520        let span = lowering_ctx(stmt);
7521        for s in &steps {
7522            crate::commands::reject_nested_inherit_env(&span, &s.kind).map_err(|e| TokenError {
7523                stmt,
7524                msg: e.to_string(),
7525                line: 0,
7526                col: 0,
7527                kind: None,
7528            })?;
7529        }
7530        if let Some(first) = steps.first_mut() {
7531            first.scope_enter += 1;
7532        }
7533        if let Some(last) = steps.last_mut() {
7534            last.scope_exit += 1;
7535        }
7536        return Ok((steps, rest + 1 - pos));
7537    }
7538    if rest >= toks.len() {
7539        // Unreachable: the splitter holds bare brackets for `{`.
7540        // Kept for body-parsed runs, mirroring the transient node.
7541        return Ok((
7542            vec![Step {
7543                guard: first_guard,
7544                kind: StepKind::WithIoBlock { bindings },
7545                scope_enter: 0,
7546                scope_exit: 0,
7547                line: 0,
7548                col: 0,
7549            }],
7550            2,
7551        ));
7552    }
7553    // A joint follower misses the inner `sep`: the pending wait
7554    // fails exactly like the grammar.
7555    if toks[rest].joint {
7556        return Err(TokenError {
7557            stmt,
7558            msg: "WITH_IO block must be followed by '{'".to_string(),
7559            line: 0,
7560            col: 0,
7561            kind: None,
7562        });
7563    }
7564    // Single form, shared with single-inner (element guards the step).
7565    let (cmd, used) = parse_single_inner(
7566        toks,
7567        rest,
7568        stmt,
7569        ctx,
7570        InnerRules {
7571            allow_await: false,
7572            allow_with_io: true,
7573        },
7574    )?;
7575    let span = lowering_ctx(stmt);
7576    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| TokenError {
7577        stmt,
7578        msg: e.to_string(),
7579        line: 0,
7580        col: 0,
7581        kind: None,
7582    })?;
7583    let kind = StepKind::WithIo {
7584        bindings,
7585        cmd: Box::new(cmd),
7586    };
7587    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7588        stmt,
7589        msg: e.to_string(),
7590        line: 0,
7591        col: 0,
7592        kind: None,
7593    })?;
7594    Ok((
7595        vec![Step {
7596            guard: first_guard,
7597            kind,
7598            scope_enter: 0,
7599            scope_exit: 0,
7600            line: 0,
7601            col: 0,
7602        }],
7603        2 + used,
7604    ))
7605}
7606
7607/// Shared inner-command parser: statement calls (joint paren, even on
7608/// known commands), RUN exec
7609/// form, and generic instructions. Returns the kind and tokens
7610/// consumed: calls and RUN-exec end mid-run (the caller continues
7611/// past them, like the grammar's `element*`); generic instructions
7612/// consume everything. Wrappers never route here (element and
7613/// single-inner dispatch own them); slice 4b reuses the call/RUN
7614/// arms for trailing elements.
7615fn parse_inner_command(
7616    body: &[Tok],
7617    stmt: usize,
7618    ctx: &ParseCtx,
7619) -> Result<(StepKind, usize), TokenError> {
7620    // Bare `NAME(...)` calls invoke functions with one syntax; the head
7621    // and `(` ride gapless or the shape stays an instruction (which
7622    // fails later as UnknownCommand), exactly like the grammar.
7623    if let Some((call_name, paren)) = call_shape_at(body, 0, true) {
7624        let inner = match &body[paren].kind {
7625            TokKind::Group { inner, .. } => inner.clone(),
7626            _ => unreachable!(),
7627        };
7628        let args = parse_call_args(&inner, stmt, ctx)?;
7629        // Statement-level `INSPECT(...)` resolves like any other call
7630        // (only expression position mints the node); unknown functions
7631        // fail in the shared resolver with identical messages.
7632        if !call_name.contains(MODULE_SEPARATOR) {
7633            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
7634                .map_err(|e| lower_err(stmt, e))?;
7635        }
7636        let qualified = resolve_name(ctx, stmt, &call_name)?;
7637        return Ok((
7638            StepKind::Call {
7639                name: qualified,
7640                args,
7641            },
7642            paren + 1,
7643        ));
7644    }
7645    let head = match body.first().map(|t| &t.kind) {
7646        Some(TokKind::Word(n)) => n.clone(),
7647        _ => {
7648            return Err(TokenError {
7649                stmt,
7650                msg: "statement must open with a command word".to_string(),
7651                line: 0,
7652                col: 0,
7653                kind: None,
7654            });
7655        }
7656    };
7657    // RUN exec form: the list routes structured through `lower` (the
7658    // mock wraps it in `Run`; production maps it to `RunExec`); the
7659    // caller continues past the list, like the grammar. The list
7660    // rides gapped (`sep`): a joint bracket is a hard error, never
7661    // a spliced arg (probed `RUN["a"]`).
7662    if head == KEYWORD_RUN
7663        && matches!(
7664            body.get(1).map(|t| &t.kind),
7665            Some(TokKind::Group {
7666                delim: GroupDelim::Bracket,
7667                ..
7668            })
7669        )
7670    {
7671        if body[1].joint {
7672            return Err(TokenError {
7673                stmt,
7674                msg: "RUN [...] requires a gap after RUN".to_string(),
7675                line: 0,
7676                col: 0,
7677                kind: None,
7678            });
7679        }
7680        let inner = match &body[1].kind {
7681            TokKind::Group { inner, .. } => inner.clone(),
7682            _ => unreachable!(),
7683        };
7684        // Non-map blocks miss the exec shape (the grammar has no
7685        // `block` alternative here); fall through to the shell path
7686        // below, which reads the bracket literally.
7687        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
7688            let kind =
7689                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
7690            return Ok((kind, 2));
7691        }
7692    }
7693    let tokens = build_arg_tokens(&body[1..], stmt, ctx)?;
7694    let kind = lower_generic_args(&head, tokens, stmt, ctx)?;
7695    Ok((kind, body.len()))
7696}
7697
7698/// Parse a token stream (either lexer) into steps. Markers normalize to
7699/// 0/0 like the fuzz harness; scopes arrive with block slices.
7700pub fn parse_tokens(
7701    toks: &[Tok],
7702    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
7703) -> Result<Vec<Step>, TokenError> {
7704    let modules = ModuleTable::default();
7705    let reserved = HashSet::new();
7706    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
7707    parse_tokens_with_ctx(toks, &ctx)
7708}
7709
7710/// Parse with an explicit context (module table for call resolution).
7711/// `parse_tokens` uses empty modules.
7712pub fn parse_tokens_with_ctx(toks: &[Tok], ctx: &ParseCtx) -> Result<Vec<Step>, TokenError> {
7713    let mut out = Vec::new();
7714    *ctx.current_line.borrow_mut() = 1;
7715    for (i, s) in split_statements(toks, 1)?.iter().enumerate() {
7716        *ctx.current_line.borrow_mut() = s.line;
7717        out.extend(
7718            lower_stmt_steps(s, i, ctx, false, true).map_err(|e| stamp_pos(e, s.line, s.col))?,
7719        );
7720    }
7721    // Whole-script validations through the shared validators.
7722    // `INHERIT_ENV` prelude order: only leading positions read.
7723    {
7724        let mut seen_non_prelude = false;
7725        for step in &out {
7726            match &step.kind {
7727                StepKind::InheritEnv { .. } => {
7728                    if seen_non_prelude {
7729                        return Err(TokenError {
7730                            stmt: out.len(),
7731                            msg: "INHERIT_ENV must appear before any other commands".to_string(),
7732                            line: 0,
7733                            col: 0,
7734                            kind: None,
7735                        });
7736                    }
7737                }
7738                kind => {
7739                    if crate::commands::contains_inherit_env(kind) {
7740                        return Err(TokenError {
7741                            stmt: out.len(),
7742                            msg: "INHERIT_ENV cannot be nested inside other commands".to_string(),
7743                            line: 0,
7744                            col: 0,
7745                            kind: None,
7746                        });
7747                    }
7748                    seen_non_prelude = true;
7749                }
7750            }
7751        }
7752    }
7753    crate::commands::validate_remote_copy_placement(&out, &lowering_ctx(out.len())).map_err(
7754        |e| TokenError {
7755            stmt: out.len(),
7756            msg: e.to_string(),
7757            line: 0,
7758            col: 0,
7759            kind: None,
7760        },
7761    )?;
7762    {
7763        let top: HashSet<String> = ctx.funcs.borrow().first().cloned().unwrap_or_default();
7764        let top_imports: Vec<String> = ctx.imports.borrow().first().cloned().unwrap_or_default();
7765        let mut top_types = HashSet::new();
7766        for step in &out {
7767            if let StepKind::TypeAlias { name, .. } = &step.kind {
7768                top_types.insert(name.clone());
7769            }
7770        }
7771        crate::commands::validate_exports(
7772            &lowering_ctx(out.len()),
7773            &ctx.func_exports.borrow(),
7774            &ctx.type_exports.borrow(),
7775            &top,
7776            &top_types,
7777            ctx.modules,
7778            &top_imports,
7779        )
7780        .map_err(|e| TokenError {
7781            stmt: out.len(),
7782            msg: e.to_string(),
7783            line: 0,
7784            col: 0,
7785            kind: None,
7786        })?;
7787    }
7788    Ok(out)
7789}
7790
7791// ---- String entry points: lex, lower, collect exports and docs ----
7792
7793/// Source text of a 1-based line. The line just past a trailing
7794/// newline (where unbalanced groups report) reads as empty text so
7795/// caret blocks still render.
7796fn source_line_of(input: &str, line: usize) -> Option<String> {
7797    let count = input.lines().count();
7798    let idx = line.checked_sub(1)?;
7799    if idx < count {
7800        input.lines().nth(idx).map(str::to_string)
7801    } else if idx == count {
7802        Some(String::new())
7803    } else {
7804        None
7805    }
7806}
7807
7808/// Last script line (end-of-script validations blame it).
7809fn last_line(input: &str) -> usize {
7810    input.lines().count().max(1)
7811}
7812
7813/// Convert a lexer failure: low-level syntax kind, exact lexer
7814/// position, and the source line for the caret block. Unclosed groups
7815/// name their opener (no grammar dumps); the closer expectation rides
7816/// along so `expected()` stays informative. A lexer-known kind (an
7817/// unclosed `WITH_IO` bracket) converts verbatim.
7818fn lex_error(input: &str, e: LexError) -> ParseError {
7819    let line = e.line.max(1);
7820    let ctx = match source_line_of(input, line) {
7821        Some(source_line) => SpanContext::full(line, e.col.max(1), e.col.max(1), source_line),
7822        None => SpanContext::line_only(line),
7823    };
7824    if let Some(ParseErrorKind::InvalidSyntax { command }) = e.kind {
7825        // Lexer-known command syntax (an unclosed `WITH_IO` bracket).
7826        return ParseError::invalid_syntax(
7827            &command,
7828            e.msg,
7829            None,
7830            vec!["`]`".to_string()],
7831            None,
7832            &ctx,
7833        );
7834    }
7835    let expected = if e.msg.starts_with("unclosed") {
7836        vec!["`}`".to_string()]
7837    } else {
7838        Vec::new()
7839    };
7840    ParseError::syntax(e.msg, expected, None, &ctx)
7841}
7842
7843/// Convert a backend failure, preserving the dispatcher's error kind
7844/// and completing line/source context the token stream knows. Spans
7845/// open at the statement's start column and cover its whole first line
7846/// (multi-line spans clamp to the start line), so caret blocks render
7847/// for every string-path error.
7848fn token_error(input: &str, e: TokenError) -> ParseError {
7849    let line = if e.line == 0 {
7850        last_line(input)
7851    } else {
7852        e.line
7853    };
7854    let start_col = e.col.max(1);
7855    let ctx = match source_line_of(input, line) {
7856        Some(source_line) => {
7857            let end = source_line.len().max(start_col);
7858            SpanContext::full(line, start_col, end, source_line)
7859        }
7860        None => SpanContext::line_only(line),
7861    };
7862    // Column spans are statement granularity (every error names its
7863    // statement's first column); the caret block still renders.
7864    match e.kind {
7865        Some(crate::error::ParseErrorKind::UnknownCommand { name }) => {
7866            ParseError::unknown_command(&name, e.msg, None, &ctx)
7867        }
7868        Some(crate::error::ParseErrorKind::InvalidSyntax { command }) => {
7869            ParseError::invalid_syntax(&command, e.msg, None, Vec::new(), None, &ctx)
7870        }
7871        Some(crate::error::ParseErrorKind::Validation { command }) => {
7872            ParseError::validation(&command, e.msg, &ctx)
7873        }
7874        Some(crate::error::ParseErrorKind::Syntax) => {
7875            ParseError::syntax(e.msg, Vec::new(), None, &ctx)
7876        }
7877        Some(crate::error::ParseErrorKind::Structural { rule }) => {
7878            ParseError::structural(&rule, e.msg, &ctx)
7879        }
7880        None => ParseError::structural("statement", e.msg, &ctx),
7881    }
7882}
7883
7884/// Shared parse driver: lex, lower with preseeded frames, and collect
7885/// `EXPORT` names (validated at end of parse, forward references
7886/// allowed).
7887fn parse_with_ctx(
7888    input: &str,
7889    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
7890    reserved_names: HashSet<String>,
7891    modules: ModuleTable,
7892    preseed_funcs: HashSet<String>,
7893    preseed_imports: Vec<String>,
7894) -> ParseResult<ScriptWithExports> {
7895    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
7896    let ctx = ParseCtx::empty(&lower, &modules, &reserved_names);
7897    // Snippet re-parses seed their base frames so lookup behaves
7898    // identically; snippets never define, only read.
7899    ctx.funcs.borrow_mut()[0].extend(preseed_funcs);
7900    ctx.imports.borrow_mut()[0].extend(preseed_imports);
7901    let steps = parse_tokens_with_ctx(&toks, &ctx).map_err(|e| token_error(input, e))?;
7902    let mut steps = steps;
7903    stamp_func_docs(input, &mut steps);
7904    Ok(ScriptWithExports {
7905        steps,
7906        func_exports: ctx.func_exports.borrow().clone(),
7907        type_exports: ctx.type_exports.borrow().clone(),
7908    })
7909}
7910
7911/// Steps plus single-file `EXPORT` metadata, before `#` doc stamping.
7912/// Callers needing docs build a [`ParsedScript`] from this.
7913struct ScriptWithExports {
7914    steps: Vec<Step>,
7915    func_exports: Vec<String>,
7916    type_exports: Vec<String>,
7917}
7918
7919/// Parse a script with an unknown host environment.
7920pub fn parse_script(
7921    input: &str,
7922    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
7923) -> ParseResult<Vec<Step>> {
7924    Ok(parse_with_ctx(
7925        input,
7926        lower,
7927        HashSet::new(),
7928        ModuleTable::default(),
7929        HashSet::new(),
7930        Vec::new(),
7931    )?
7932    .steps)
7933}
7934
7935/// Parse a snippet with an enclosing parse's visible scope state, so
7936/// re-parsed inner commands (async bodies) resolve calls identically.
7937/// The snippet never defines, only reads: seeds affect lookup alone.
7938pub fn parse_script_with_preseed(
7939    input: &str,
7940    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
7941    reserved_names: HashSet<String>,
7942    modules: ModuleTable,
7943    preseed_funcs: HashSet<String>,
7944    preseed_imports: Vec<String>,
7945) -> ParseResult<Vec<Step>> {
7946    Ok(parse_with_ctx(
7947        input,
7948        lower,
7949        reserved_names,
7950        modules,
7951        preseed_funcs,
7952        preseed_imports,
7953    )?
7954    .steps)
7955}
7956
7957/// Parse with a module provenance table so calls resolve statically:
7958/// qualified `MODULE::NAME` checks membership, bare `NAME` resolves through
7959/// `SCRIPT` definitions and `IMPORT`ed modules, and anything else fails at
7960/// parse time instead of at runtime.
7961pub fn parse_script_with_modules(
7962    input: &str,
7963    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
7964    reserved_names: HashSet<String>,
7965    modules: ModuleTable,
7966) -> ParseResult<Vec<Step>> {
7967    Ok(parse_script_with_modules_and_exports(input, lower, reserved_names, modules)?.steps)
7968}
7969
7970/// Parse with modules plus single-file `EXPORT` metadata and `#` doc
7971/// comments for top-level `FUNC`s. Used by the MCP host; the linear
7972/// runner keeps using `parse_script_with_modules` and ignores exports.
7973pub fn parse_script_with_modules_and_exports(
7974    input: &str,
7975    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
7976    reserved_names: HashSet<String>,
7977    modules: ModuleTable,
7978) -> ParseResult<ParsedScript> {
7979    let ScriptWithExports {
7980        steps,
7981        func_exports,
7982        type_exports,
7983    } = parse_with_ctx(
7984        input,
7985        lower,
7986        reserved_names,
7987        modules,
7988        HashSet::new(),
7989        Vec::new(),
7990    )?;
7991    Ok(ParsedScript {
7992        func_docs: collect_func_docs(input, &steps),
7993        steps,
7994        func_exports,
7995        type_exports,
7996    })
7997}
7998
7999/// Parse without modules plus `EXPORT` metadata. Used by tests and
8000/// tooling that lower with the shared mock.
8001pub fn parse_script_with_exports(
8002    input: &str,
8003    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8004) -> ParseResult<ParsedScript> {
8005    let ScriptWithExports {
8006        steps,
8007        func_exports,
8008        type_exports,
8009    } = parse_with_ctx(
8010        input,
8011        lower,
8012        HashSet::new(),
8013        ModuleTable::default(),
8014        HashSet::new(),
8015        Vec::new(),
8016    )?;
8017    Ok(ParsedScript {
8018        func_docs: collect_func_docs(input, &steps),
8019        steps,
8020        func_exports,
8021        type_exports,
8022    })
8023}
8024
8025/// Parse one expression from source text with an empty module scope, for
8026/// tooling that shows lowering without running (docs demos, explain output).
8027/// No imports exist here, so bare function calls fail and qualified calls
8028/// fail against the empty table; only `INSPECT` passes through untouched.
8029/// Arithmetic, comparison, variables, env reads, keypaths, and literals
8030/// lower normally, with literal only subtrees folded before flattening.
8031pub fn parse_expression_str(input: &str) -> ParseResult<Expr> {
8032    // Trailing whitespace lexes unconsumed, so lex the trimmed text:
8033    // otherwise padded but valid input fails the full consumption check.
8034    let trimmed = input.trim();
8035    let toks = lex_str(trimmed).map_err(|e| lex_error(trimmed, e))?;
8036    let modules = ModuleTable::default();
8037    let reserved = HashSet::new();
8038    let lower = crate::commands::lower_command as fn(&str, Vec<Arg>) -> ParseResult<StepKind>;
8039    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
8040    *ctx.current_line.borrow_mut() = 1;
8041    parse_single_expr(&toks, 0, &ctx).map_err(|e| token_error(trimmed, e))
8042}
8043
8044/// Parse one guard expression from source text (a bare `guard_seq`:
8045/// predicates, `not`/`any`/`all`, comma lists), for tooling and tests.
8046pub fn parse_guard_expr_str(input: &str) -> ParseResult<GuardExpr> {
8047    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
8048    parse_single_guard(&toks, 0).map_err(|e| token_error(input, e))
8049}
8050
8051/// Parsed script with single-file `EXPORT` metadata. `steps` is the
8052/// linear execution plan, `func_exports` the `EXPORT` func names in
8053/// source order, `type_exports` the `EXPORT TYPE` names in source order,
8054/// and `func_docs` maps top-level `FUNC` base names to (summary, docs)
8055/// collected from the immediately preceding `#` comment block.
8056#[derive(Debug, Clone, Default)]
8057pub struct ParsedScript {
8058    pub steps: Vec<Step>,
8059    pub func_exports: Vec<String>,
8060    pub type_exports: Vec<String>,
8061    pub func_docs: std::collections::HashMap<String, (String, String)>,
8062}
8063
8064fn collect_func_docs(
8065    input: &str,
8066    steps: &[Step],
8067) -> std::collections::HashMap<String, (String, String)> {
8068    use std::collections::{HashMap, HashSet};
8069    let lines: Vec<&str> = input.lines().collect();
8070    // Top-level FUNC definition lines keyed by base name. Brace depth
8071    // tracks nesting so only depth-0 `FUNC` lines count; the first
8072    // occurrence wins because same-scope duplicates fail at lowering.
8073    let mut def_lines: HashMap<String, usize> = HashMap::new();
8074    let mut seen: HashSet<String> = HashSet::new();
8075    let mut depth: usize = 0;
8076    for (idx, line) in lines.iter().enumerate() {
8077        let trimmed = line.trim_start();
8078        let is_comment = trimmed.starts_with('#');
8079        let is_guard_only = trimmed.starts_with('[');
8080        if !is_comment
8081            && !is_guard_only
8082            && let Some(rest) = strip_func_head(trimmed)
8083            && depth == 0
8084            && !seen.contains(&rest)
8085        {
8086            seen.insert(rest.clone());
8087            def_lines.insert(rest, idx + 1);
8088        }
8089        if !is_comment {
8090            for ch in line.chars() {
8091                if ch == '{' {
8092                    depth = depth.saturating_add(1);
8093                } else if ch == '}' {
8094                    depth = depth.saturating_sub(1);
8095                }
8096            }
8097        }
8098    }
8099    let mut out: HashMap<String, (String, String)> = HashMap::new();
8100    for step in steps {
8101        if let StepKind::FuncDef { name, .. } = &step.kind
8102            && !out.contains_key(name)
8103            && let Some(&line_no) = def_lines.get(name)
8104            && let Some((summary, docs)) = docs_above(&lines, line_no)
8105        {
8106            out.insert(name.clone(), (summary, docs));
8107        }
8108    }
8109    out
8110}
8111
8112/// Stamp `#` doc blocks onto top-level `FUNC` steps, from the same map
8113/// that feeds `func_docs`, so step-carried docs and the sidecar can
8114/// never disagree. Only top-level definitions qualify (same rule as
8115/// collection); nested shadowing keeps `docs: None`.
8116fn stamp_func_docs(input: &str, steps: &mut [Step]) {
8117    let docs = collect_func_docs(input, steps);
8118    for step in steps {
8119        if let StepKind::FuncDef {
8120            name, docs: slot, ..
8121        } = &mut step.kind
8122            && slot.is_none()
8123            && let Some(pair) = docs.get(name)
8124        {
8125            *slot = Some(pair.clone());
8126        }
8127    }
8128}
8129
8130fn strip_func_head(trimmed: &str) -> Option<String> {
8131    let rest = trimmed.strip_prefix(KEYWORD_FUNC)?;
8132    let after = rest.strip_prefix([' ', '\t'])?;
8133    if after.is_empty() {
8134        return None;
8135    }
8136    let name: String = after
8137        .chars()
8138        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
8139        .collect();
8140    if name.is_empty()
8141        || !name
8142            .bytes()
8143            .all(|b| b.is_ascii_uppercase() || b == b'_' || b.is_ascii_digit())
8144    {
8145        return None;
8146    }
8147    if name.starts_with(|c: char| c.is_ascii_digit()) {
8148        return None;
8149    }
8150    Some(name)
8151}
8152
8153fn docs_above(lines: &[&str], line_no: usize) -> Option<(String, String)> {
8154    if line_no <= 1 {
8155        return None;
8156    }
8157    let mut block: Vec<String> = Vec::new();
8158    let mut idx = line_no - 1;
8159    while idx > 0 {
8160        idx -= 1;
8161        let trimmed = lines[idx].trim_start();
8162        if trimmed.is_empty() {
8163            break;
8164        }
8165        if let Some(body) = trimmed.strip_prefix('#') {
8166            let text = body.strip_prefix(' ').unwrap_or(body);
8167            block.push(text.to_string());
8168        } else {
8169            break;
8170        }
8171        if idx == 0 {
8172            break;
8173        }
8174    }
8175    if block.is_empty() {
8176        return None;
8177    }
8178    block.reverse();
8179    let summary = block.first().cloned().unwrap_or_default();
8180    let docs = block.join("\n");
8181    Some((summary, docs))
8182}
8183
8184#[cfg(test)]
8185mod tests {
8186    use super::*;
8187    use crate::test_lower_mock;
8188
8189    fn lower(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
8190        test_lower_mock::lower(name, args)
8191    }
8192
8193    /// Lexer-agreement oracle: both frontends must deliver identical
8194    /// steps through the single backend. `parse_script` is the string
8195    /// entry point; `parse_tokens` runs each lexer's output directly.
8196    fn assert_parity(text: &str) {
8197        let old = crate::parse_script(text, lower)
8198            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
8199        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
8200        let new = parse_tokens(&toks, lower)
8201            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
8202        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
8203        #[cfg(feature = "proc-macro-api")]
8204        {
8205            let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
8206            let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
8207            let new = parse_tokens(&toks, lower).expect("token path must parse token script");
8208            assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
8209        }
8210    }
8211
8212    /// String-path-only oracle for shapes `rustc` cannot carry at all
8213    /// (lifetime-like quotes). The backend must still agree there.
8214    fn assert_parity_string_only(text: &str) {
8215        let old = crate::parse_script(text, lower)
8216            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
8217        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
8218        let new = parse_tokens(&toks, lower)
8219            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
8220        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
8221    }
8222
8223    #[test]
8224    fn token_and_string_paths_agree_on_wrappers() {
8225        // Single-command wrappers, io-blocks, await/cancel,
8226        // LET wrapper forms — three-way agreement per script.
8227        for text in [
8228            "WITH_IO [stdout=$p] ECHO hi",
8229            "WITH_IO [stdin=$p] ECHO hi",
8230            "WITH_IO [stdin] ECHO hi",
8231            "WITH_IO [stdout] ECHO hi",
8232            "WITH_IO [stdin=$p, stdout=$q] ECHO hi",
8233            "WITH_IO [stdin=$p, stdin=$q] ECHO hi",
8234            "WITH_IO [tty] RUN echo hi",
8235            "WITH_IO [tty, rows=40, cols=100] RUN echo hi",
8236            "WITH_IO [rows=40, cols=100, tty] RUN echo hi",
8237            "WITH_IO [stdin =$p] ECHO hi",
8238            "WITH_IO [stdin= $p] ECHO hi",
8239            "WITH_IO [ stdin=$p ] ECHO hi",
8240            "WITH_IO [\nstdin=$p\n] ECHO hi",
8241            "WITH_IO [stdin=$p\n, stdout=$q] ECHO hi",
8242            "WITH_IO [stdout=$p] ASYNC ECHO hi",
8243            "WITH_IO [stdin=$p] WITH_IO [stderr=$e] ECHO hi",
8244            "WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
8245            "WITH_IO [stdin=$p] ISOLATED ECHO hi",
8246            "WITH_IO [stdin=$p] CANCEL $t",
8247            "WITH_IO [stdin=$p] CANCEL $t ECHO bye",
8248            "WITH_IO [stdin=$p] { ECHO hi }",
8249            "WITH_IO [stdin=$p]\n{ ECHO hi }",
8250            "WITH_IO [stdin=$p]; { ECHO hi }",
8251            "WITH_IO [stdin=$p]{ ECHO hi }",
8252            "WITH_IO [stdin=$p] { ECHO a\nECHO b }",
8253            "WITH_IO [stdin=$p] { ECHO hi } ECHO bye",
8254            "WITH_IO [rows=40] { ECHO hi }",
8255            "WITH_IO [tty] { ECHO hi }",
8256            "WITH_IO [stdin=$p] { WITH_IO [stderr=$e] ECHO hi }",
8257            "TIMEOUT 10s ECHO hi",
8258            "TIMEOUT 10 ECHO hi",
8259            "TIMEOUT 500ms ECHO hi",
8260            "TIMEOUT 5m ECHO hi",
8261            "TIMEOUT 2h ECHO hi",
8262            "TIMEOUT $d ECHO hi",
8263            "TIMEOUT \"10s\" ECHO hi",
8264            "TIMEOUT \"30 s\" ECHO hi",
8265            "TIMEOUT {{ $d }} ECHO hi",
8266            "TIMEOUT 10s AWAIT $t",
8267            "TIMEOUT 10s CANCEL $t",
8268            "TIMEOUT 10s AWAIT $t ECHO bye",
8269            "TIMEOUT 10s CANCEL $t ECHO bye",
8270            "TIMEOUT 10s { ECHO hi }",
8271            "TIMEOUT 10s {\nECHO hi\n}",
8272            "TIMEOUT 10s { ECHO hi } ECHO bye",
8273            "TIMEOUT 10s { ECHO hi } TIMEOUT 5s ECHO bye",
8274            "TIMEOUT 10s TIMEOUT 5s ECHO hi",
8275            "TIMEOUT 10s { ECHO a\nECHO b }",
8276            "TIMEOUT 10s ECHO hi extra",
8277            "ISOLATED ECHO hi",
8278            "ISOLATED { ECHO hi }",
8279            "ISOLATED { ECHO hi } ECHO bye",
8280            "ISOLATED AWAIT $t",
8281            "ISOLATED INHERIT_ENV [M]",
8282            "ISOLATED { INHERIT_ENV [M] }",
8283            "ISOLATED { INHERIT_ENV [MODE]\nECHO hi }",
8284            "ASYNC ECHO hi",
8285            "ASYNC { ECHO hi }",
8286            "ASYNC{ECHO hi}",
8287            "ASYNC { ECHO a\nECHO b }",
8288            "ASYNC { ECHO hi } ECHO bye",
8289            "ASYNC CANCEL $t",
8290            "ASYNC CANCEL $t ECHO bye",
8291            "AWAIT $t",
8292            "AWAIT$t",
8293            "AWAIT $ t",
8294            "AWAIT $T",
8295            "AWAIT $t2",
8296            "AWAIT $_t",
8297            "CANCEL $t",
8298            "CANCEL$t",
8299            "CANCEL $ t",
8300            "AWAIT $t ECHO bye",
8301            "CANCEL $t ECHO bye",
8302            "AWAIT $t AWAIT $u",
8303            "AWAIT $t\nECHO bye",
8304            "LET $t: HANDLE = ASYNC ECHO hi",
8305            "LET $t: HANDLE = ASYNC { ECHO hi }",
8306            "LET $t: HANDLE = ASYNC { ECHO hi } ECHO bye",
8307            "LET $a: STRING = ASYNC ECHO hi",
8308            "LET $t: HANDLE = ASYNC { WITH_IO [stdin=$p] ECHO hi }",
8309            "LET $w: STRING = WITH_IO [stdin=$p] ASYNC ECHO hi",
8310            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC ECHO hi",
8311            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi }",
8312            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi } ECHO bye",
8313            "LET $x: STRING = WITH_IO [stdin=$p] ECHO hi",
8314            "LET $x: STRING = WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
8315            "LET $x: STRING = TIMEOUT 10s ECHO hi",
8316            "LET $x: STRING = TIMEOUT 10s { ECHO hi }",
8317            "LET $x: STRING = TIMEOUT 10s ECHO hi ECHO bye",
8318            "LET $o: STRING = AWAIT $t",
8319            "LET $p: PIPE ECHO bye",
8320            "TIMEOUT 10s WITH_IO [stdin=$p]",
8321            "TIMEOUT 10s WITH_IO [stdin=$p]ECHO hi",
8322            "ISOLATED INHERIT_ENV [A, B]",
8323            "ISOLATED INHERIT_ENV [A-B]",
8324            "TIMEOUT 10s { [os:linux] ECHO hi }",
8325            "ASYNC { [os:linux] ECHO hi }",
8326            "ISOLATED { [os:linux] ECHO hi }",
8327            "[os:linux] WITH_IO [stdin=$p]\n{ ECHO hi }",
8328            "LET $x: INT = 1 ECHO bye",
8329            "CANCEL $t LET $x: INT = 1",
8330            "CANCEL $t $x = 1",
8331            "CANCEL $t RETURN \"hi\"",
8332            "TIMEOUT 10s { ECHO hi } LET $x: INT = 1",
8333            "RUN [\"a\"] ECHO bye",
8334            "[os:linux] AWAIT $t",
8335            "[os:linux] TIMEOUT 10s { ECHO hi } ECHO bye",
8336            "[os:linux] ASYNC CANCEL $t ECHO bye",
8337            "[os:linux] WITH_IO [stdin=$p] { [os:macos] ECHO hi }",
8338        ] {
8339            assert_parity(text);
8340        }
8341    }
8342
8343    #[test]
8344    fn token_and_string_paths_agree_on_blocks() {
8345        // Slice 5: `IF`/`FOR`/`WHILE`/`FUNC` with inline and
8346        // cross-newline `ELSE` chains, guard blocks (top-level and
8347        // nested quirk), and multi-element trailing — three-way
8348        // agreement per script.
8349        for text in [
8350            "IF true { ECHO hi }",
8351            "IF $x { ECHO hi } ELSE { ECHO bye }",
8352            "IF true { ECHO a } ELSE IF false { ECHO b } ELSE { ECHO c }",
8353            "IF true{ ECHO hi }",
8354            "IF true { ECHO hi } ECHO bye",
8355            "IF true { ECHO hi }\nELSE { ECHO bye }",
8356            "IF true { ECHO hi }\nELSE IF false { ECHO b }\nELSE { ECHO c }",
8357            "IF true { ECHO hi } //c\nELSE { ECHO bye }",
8358            "IF true { ECHO hi } #c\nELSE { ECHO bye }",
8359            "IF true { ECHO hi }//c\nELSE { ECHO bye }",
8360            "IF true { ECHO hi } /*c*/ ELSE { ECHO bye }",
8361            "IF true { ECHO hi } /*c1*/ /*c2*/\nELSE { ECHO bye }",
8362            "IF true { /*c*/ ECHO hi }",
8363            "IF true { [os:linux] ECHO hi }",
8364            "TIMEOUT 10s { IF true { ECHO hi } }",
8365            "TIMEOUT 10s { IF true { ECHO hi }\nELSE { ECHO bye } }",
8366            "FOR $x: INT IN [1] { ECHO hi }",
8367            "FOR $k: STRING, $v: INT IN $m { ECHO hi }",
8368            "FOR $k: INT IN [1] { ECHO hi }",
8369            "FOR $x: INT IN [1]{ ECHO hi }",
8370            "FOR $x: MAP<name: STRING> IN [1] { ECHO hi }",
8371            "FOR $x: INT IN [1] { ECHO hi } ECHO bye",
8372            "WHILE true { ECHO hi }",
8373            "WHILE $x { ECHO hi }",
8374            "WHILE true{ ECHO hi }",
8375            "TIMEOUT 10s WHILE true { ECHO hi }",
8376            "ASYNC WHILE true { ECHO hi }",
8377            "FUNC FOO() { RETURN 1 }",
8378            "FUNC FOO(){ RETURN 1 }",
8379            "FUNC FOO($x: INT) { RETURN $x }",
8380            "FUNC FOO($x: INT, $y: STRING) { RETURN $x }",
8381            "FUNC FOO() { FUNC FOO() { RETURN 1 } }",
8382            "FUNC FOO() { RETURN 1 }\nFUNC BAR() { FOO() }\nBAR()",
8383            "TYPE PERSON = MAP<name: STRING>",
8384            "TYPE A=B",
8385            "TYPE A = B | C",
8386            "TYPE A = B\nTYPE A = C",
8387            "INHERIT_ENV [A]\nECHO hi",
8388            "[os:linux] INHERIT_ENV [M]",
8389            "INHERIT_ENV [A]\nINHERIT_ENV [B]\nECHO hi",
8390            "ISOLATED INHERIT_ENV [M]",
8391            "ISOLATED { INHERIT_ENV [M] }",
8392            "ISOLATED INHERIT_ENV [A, B]",
8393            "ISOLATED INHERIT_ENV [A-B]",
8394            "REMOTE prod { ECHO hi }",
8395            "REMOTE prod [$v] { ECHO hi }",
8396            "REMOTE prod [$v, env:E] { ECHO hi }",
8397            "REMOTE prod [] { ECHO hi }",
8398            "REMOTE prod[$v] { ECHO hi }",
8399            "REMOTE prod [$v]{ ECHO hi }",
8400            "REMOTE prod{ ECHO hi }",
8401            "REMOTE  prod  { ECHO hi }",
8402            "REMOTE prod [$v, $v] { ECHO hi }",
8403            "REMOTE prod { ECHO hi } ECHO bye",
8404            "TIMEOUT 10s REMOTE prod { ECHO hi }",
8405            "ASYNC REMOTE prod [$v] { ECHO hi }",
8406            "[os:linux] { ECHO hi }",
8407            "[os:linux]\n{ ECHO hi }",
8408            "[os:linux] { [os:macos] ECHO hi }",
8409            "[os:linux] { [os:macos] ECHO hi\nECHO bye }",
8410            "[os:linux] { [os:macos] { ECHO hi } }",
8411            "TIMEOUT 10s { [os:linux] { [os:macos] ECHO hi } }",
8412            "TIMEOUT 10s { [os:linux] [os:windows] { ECHO hi } }",
8413            "TIMEOUT 10s { [os:linux] { ECHO hi } ECHO bye }",
8414            "LET $x: INT = 1 ECHO bye",
8415            KEYWORD_BREAK,
8416            KEYWORD_CONTINUE,
8417            "BREAK ECHO hi",
8418            "FOR $x: INT IN [1] { BREAK }",
8419            "LET $b: STRING = { RETURN \"hi\" }",
8420            "ECHO { RETURN \"hi\" }",
8421            "RUN [{ RETURN \"hi\" }]",
8422            "[not(env:FOO)] WRITE x",
8423            "[\nnot(env:FOO)\n] WRITE x",
8424            "WRITE env.txt \"{{ env:GREETING }}\"",
8425            "CANCEL $t LET $x: INT = 1",
8426            "RUN [\"a\"] ECHO bye",
8427        ] {
8428            assert_parity(text);
8429        }
8430    }
8431
8432    #[test]
8433    fn multi_line_generics_match_single_line_shape() {
8434        // Multi-line `<...>` shapes parse, and canonicalize exactly
8435        // like their single-line spelling.
8436        for (single, multi) in [
8437            (
8438                "TYPE R = MAP<name: STRING, value: INT>",
8439                "TYPE R = MAP<name: STRING,\nvalue: INT>",
8440            ),
8441            (
8442                "TYPE R = MAP<name: STRING, value: LIST<INT>>",
8443                "TYPE R = MAP<name: STRING,\nvalue: LIST<INT>>",
8444            ),
8445            (
8446                "TYPE R = MAP<name: STRING, value: INT>",
8447                "TYPE R = MAP<\nname: STRING,\nvalue: INT\n>",
8448            ),
8449            (
8450                "LET $m: MAP<name: STRING, value: INT> = {}",
8451                "LET $m: MAP<name: STRING,\nvalue: INT> = {}",
8452            ),
8453            (
8454                "FOR $x: LIST<INT> IN [1] { ECHO hi }",
8455                "FOR $x: LIST<\nINT> IN [1] { ECHO hi }",
8456            ),
8457            ("TYPE R = MAP<x: A | B>", "TYPE R = MAP<x: A |\nB>"),
8458        ] {
8459            assert_parity(multi);
8460            let want = crate::parse_script(single, lower)
8461                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
8462            let got = crate::parse_script(multi, lower)
8463                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
8464            assert_eq!(
8465                got, want,
8466                "multi-line must canonicalize like one line: {multi:?}"
8467            );
8468        }
8469    }
8470
8471    #[test]
8472    fn spaced_comparisons_still_end_the_statement() {
8473        // A spaced `<` is a comparison, never a generic open: the
8474        // newline still ends the statement.
8475        let steps = crate::parse_script("LET $b: BOOL = $a < $b\nECHO hi", lower)
8476            .expect("comparison plus follower must parse");
8477        assert_eq!(steps.len(), 2, "newline ends the comparison statement");
8478    }
8479
8480    #[test]
8481    fn token_and_string_paths_agree_on_flat_commands() {
8482        for text in [
8483            "ECHO hi",
8484            "ECHO hi\nWRITE x out",
8485            "WRITE x",
8486            "ECHO \"quoted\" unquoted",
8487            "ENV COVERAGE=covered",
8488            "ECHO a; ECHO b",
8489            "// comment\nECHO hi",
8490            "ECHO 1.0.0 --flag a/b",
8491            "ECHO $x",
8492            "\n\nECHO hi\n\n",
8493        ] {
8494            assert_parity(text);
8495        }
8496    }
8497
8498    #[cfg(feature = "proc-macro-api")]
8499    #[test]
8500    fn backslash_outside_strings_is_string_only() {
8501        // `rustc` rejects a bare `\`, so unquoted backslash escapes
8502        // cannot cross `TokenStream` (same exclusion class as raw-`"`
8503        // blocks): the string lexer keeps them, the token path fails to
8504        // tokenize before v2 is ever reached.
8505        let toks = crate::tok::lex_str("ECHO a\\nb").expect("string lex keeps escapes");
8506        let old = crate::parse_script("ECHO a\\nb", lower).expect("string path parses it");
8507        assert_eq!(
8508            parse_tokens(&toks, lower).expect("token path parses it"),
8509            old
8510        );
8511        assert!("ECHO a\\nb".parse::<proc_macro2::TokenStream>().is_err());
8512    }
8513
8514    #[test]
8515    fn escaped_backslash_pair_is_atomic() {
8516        // `"a\\"` parses (one escape pair plus the closer): the pair
8517        // scans atomically, like the block-string arm and `lex_word`.
8518        // The value stays raw (`\\` verbatim for runtime
8519        // `expand_string`), so this pins parsing, not unescaping.
8520        assert_parity("ECHO \"a\\\\\"");
8521        let steps = crate::parse_script("ECHO \"a\\\\\"", lower).expect("escaped pair must parse");
8522        match &steps[..] {
8523            [s] => assert!(
8524                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a\\\\"),
8525                "escaped pair must survive raw: {s:?}"
8526            ),
8527            _ => panic!("one step: {steps:?}"),
8528        }
8529    }
8530
8531    #[test]
8532    fn joint_double_slash_stays_literal() {
8533        // `rustc` strips `//` before the macro ever runs, so these are
8534        // string-path-only by construction: joint `a//b` is one literal
8535        // arg, and `[a //c]` closes its group (the in-group `//` copy
8536        // stops at the closer).
8537        for text in ["ECHO a//b", "ECHO [a //c]"] {
8538            assert_parity_string_only(text);
8539        }
8540        let steps = crate::parse_script("ECHO a//b", lower).expect("joint slashes parse");
8541        match &steps[..] {
8542            [s] => assert!(
8543                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a//b"),
8544                "joint `//` must glue literally: {s:?}"
8545            ),
8546            _ => panic!("one step: {steps:?}"),
8547        }
8548        let steps = crate::parse_script("ECHO [a //c]", lower).expect("group must close");
8549        assert_eq!(steps.len(), 1, "one step: {steps:?}");
8550        // Full content survives literally: the mock joins WRITE args
8551        // with spaces, so the round trip is byte-exact here.
8552        let steps = crate::parse_script("WRITE f [a //c]", lower).expect("group must close");
8553        match &steps[..] {
8554            [s] => assert!(
8555                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a //c]"),
8556                "group content must survive literally: {s:?}"
8557            ),
8558            _ => panic!("one step: {steps:?}"),
8559        }
8560    }
8561
8562    #[test]
8563    fn block_comment_in_group_closes_like_line_comment() {
8564        // `[a /* c]` reads literally on the old backend (first arg
8565        // `[a`, joined `[a /* c]`), so the in-group `/*` copy breaks
8566        // at the depth-zero closer exactly like `//` does. The bare
8567        // `/*` reads literally too.
8568        for text in ["ECHO [a /* c]", "WRITE f [a /* c]", "ECHO /*"] {
8569            assert_parity_string_only(text);
8570        }
8571        let steps = crate::parse_script("ECHO /*", lower).expect("bare block open parses");
8572        match &steps[..] {
8573            [s] => assert!(
8574                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "/*"),
8575                "bare `/*` must stay literal: {s:?}"
8576            ),
8577            _ => panic!("one step: {steps:?}"),
8578        }
8579        let steps = crate::parse_script("WRITE f [a /* c]", lower).expect("group must close");
8580        match &steps[..] {
8581            [s] => assert!(
8582                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c]"),
8583                "group content must survive literally: {s:?}"
8584            ),
8585            _ => panic!("one step: {steps:?}"),
8586        }
8587        // Terminated spans keep working through the same path: the
8588        // run carries its closer, so math still gets first refusal.
8589        let steps = crate::parse_script("WRITE f [a /* c */ d]", lower).expect("group must close");
8590        match &steps[..] {
8591            [s] => assert!(
8592                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c */ d]"),
8593                "terminated group content must survive: {s:?}"
8594            ),
8595            _ => panic!("one step: {steps:?}"),
8596        }
8597    }
8598
8599    #[test]
8600    fn single_quoted_multiline_keeps_line_tracking() {
8601        // The `'` arm counts embedded newlines like the `"` arm, so the
8602        // statement after a multiline single-quoted string keeps its
8603        // own lines (func-docs stamping keys off them).
8604        let text = "ECHO 'a\nb'\nECHO c";
8605        assert_parity_string_only(text);
8606        let steps = crate::parse_script(text, lower).expect("must parse");
8607        assert_eq!(steps.len(), 2, "two steps: {steps:?}");
8608        assert_eq!((steps[0].line, steps[0].col), (1, 1));
8609        assert_eq!((steps[1].line, steps[1].col), (3, 1), "{steps:?}");
8610    }
8611
8612    #[test]
8613    fn token_and_string_paths_agree_on_guarded_commands() {
8614        for text in [
8615            "[env:X] ECHO hi",
8616            "[env:A] [os:linux] ECHO hi",
8617            "[os:macos] WRITE x",
8618            "[not(os:windows)] WRITE f x",
8619            "[any(os:macos, os:linux)] ECHO hi",
8620            "[all(env:A, os:linux)] ECHO hi",
8621            "[eq(env:K, v)] ECHO hi",
8622            "[ne(env:K, v)] ECHO hi",
8623            "[bool:true] ECHO hi",
8624            "[arch:arm] ECHO hi",
8625            "[family:unix] ECHO hi",
8626            "[(os:linux)] ECHO hi",
8627            "[env:A, os:linux] ECHO hi",
8628            "WRITE x\n[env:X] ECHO hi",
8629            "[env:K] ECHO $x",
8630            "[__OXDOCK_INJECT_1__] ECHO hi",
8631            "[eq(env:K, \"a b\")] ECHO hi",
8632            "[\nenv:X\n] ECHO hi",
8633            // In-body brackets are raw text split on whitespace (probed
8634            // parity: `[a, b]` is args `"[a,"` + `"b]"`, quotes kept).
8635            "ECHO [a, b] hi",
8636            "WRITE f [env:X]",
8637            "ECHO [env:X] hi",
8638            "WRITE f [\"a b\"]",
8639            "ECHO foo[bar]baz",
8640            "ECHO [a ]",
8641            "ECHO [ a]",
8642            "WRITE out x [env:X]",
8643        ] {
8644            assert_parity(text);
8645        }
8646        // `rustc` lexes `'a` as a lifetime start and rejects the
8647        // space: string-path-only by construction.
8648        assert_parity_string_only("ECHO ['a b']");
8649    }
8650
8651    #[test]
8652    fn token_and_string_paths_agree_on_calls_and_exact_args() {
8653        use crate::ast::{ModuleFuncs, ModuleTable};
8654        use std::collections::{HashMap, HashSet};
8655        let std_table = || ModuleTable {
8656            modules: HashMap::from([(
8657                crate::constants::STD_MODULE_NAME.to_string(),
8658                Some(ModuleFuncs {
8659                    func_names: HashSet::from(["TEXT_LENGTH".to_string()]),
8660                }),
8661            )]),
8662        };
8663        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
8664            test_lower_mock::lower(name, args)
8665        }
8666        // One table for both pathways: STD exports TEXT_LENGTH.
8667        // Rebuilt per case (parse-time only, keeps borrows local).
8668        for text in [
8669            "LET $n: INT = STD::TEXT_LENGTH(\"hi\")",
8670            "STD::TEXT_LENGTH(\"hi\")",
8671            "LET $n: INT = STD::TEXT_LENGTH(\"a\", \"b\")",
8672            "LET $s: STRING = INSPECT($x)",
8673            "INSPECT($x)",
8674            "LET $x: STRING = ECHO hi",
8675            "LET $t: STRING = WRITE x",
8676            "LET $o: STRING = RUN echo hi",
8677            "RUN [\"echo\", \"hi\"]",
8678            "RUN echo [a]",
8679            "LET $r: STRING = RUN [\"echo\"]",
8680            "ECHO K=v",
8681            "ECHO K = v",
8682            "ECHO K=a b",
8683            "ECHO K=a, b",
8684            "ECHO K=\"a b\"",
8685            "ECHO K=$x",
8686            "ECHO K=",
8687            "ECHO a = = b",
8688            "WRITE f K=v",
8689            "ECHO $a + $b",
8690            "ECHO $a==$b",
8691            "ECHO a $x b",
8692            "ECHO 5 + 3",
8693            "WRITE f ( \"hi\" )",
8694            "ECHO FOO(\"a\")",
8695            "ECHO [a, b] hi",
8696            "ECHO {{x}}",
8697            "ECHO {{ $x }}",
8698            "ECHO $x=K",
8699            "ECHO a$x",
8700            "ECHO a$(x)",
8701            "ECHO K=$x tail",
8702            "EXPAND K1=$x K2=$y",
8703            "EXPAND a",
8704            "ENV K = v",
8705            "COPY a b",
8706            "ECHO foo[bar]baz",
8707            "LET $x: STRING = FOOBAR",
8708            "STD::TEXT_LENGTH(\"hi\") ECHO bye",
8709            "LET $n: INT = STD::TEXT_LENGTH(\"a\") ECHO bye",
8710            "TIMEOUT 10s STD::TEXT_LENGTH(\"hi\")",
8711            "TIMEOUT 10s STD::TEXT_LENGTH(\"hi\") ECHO bye",
8712            "LET $n: INT = STD::TEXT_LENGTH(\"a\")STD::TEXT_LENGTH(\"b\")",
8713        ] {
8714            let table = std_table();
8715            let old =
8716                crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
8717                    .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
8718            let reserved = HashSet::new();
8719            let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
8720            let toks = crate::tok::lex_str(text).expect("string lex must succeed");
8721            let new = parse_tokens_with_ctx(&toks, &ctx)
8722                .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
8723            assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
8724            #[cfg(feature = "proc-macro-api")]
8725            {
8726                let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
8727                let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
8728                let new = parse_tokens_with_ctx(&toks, &ctx)
8729                    .unwrap_or_else(|e| panic!("token path must parse token {text:?}: {e}"));
8730                assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
8731            }
8732        }
8733    }
8734
8735    #[test]
8736    fn token_and_string_paths_agree_on_let_set_return() {
8737        for text in [
8738            "LET $x: INT = 1",
8739            "LET $s: STRING = \"hi\"",
8740            "LET $b: BOOL = true",
8741            "LET $f: FLOAT = 1.5",
8742            "LET $p: PIPE",
8743            "LET $l: LIST<STRING> = [\"a\", \"b\"]",
8744            "LET $e: LIST<STRING> = []",
8745            "LET $m: MAP = {k: 1}",
8746            "LET $m2: MAP = {\"a b\": 2, k: [1, 2]}",
8747            "LET $n: INT = $a + $b",
8748            "LET $c: BOOL = ($a == 3) && ($b == 4)",
8749            "LET $g: BOOL = !$ok",
8750            "LET $nn: BOOL = true && false",
8751            "LET $e2: STRING = env:HOME",
8752            "LET $k: STRING = $a.b.c",
8753            "LET $u: INT = -5",
8754            "LET $v: INT = 9223372036854775807",
8755            "LET $min: INT = -9223372036854775808",
8756            "LET $w: INT = 1_000",
8757            "LET $z: STRING = a/b",
8758            "LET $d: STRING = -f",
8759            "LET $t: STRING = 30s",
8760            "LET $q: STRING = \"\"\"hi\"\"\"",
8761            "LET $f2: FLOAT = 2 * -3",
8762            "LET $o: BOOL = 2 + 3 > 4",
8763            "LET $l2: LIST< MAP > = []",
8764            "LET $a1: INT = 1 + 2",
8765            "LET $s1: INT = 10 - 4 - 3",
8766            "LET $m1: INT = 2 * 3 + 4",
8767            "LET $x1: BOOL = 1 < 2 == true",
8768            "LET $or: BOOL = $a || $b",
8769            "LET $dbl: BOOL = !!$x",
8770            "LET $ver: STRING = 1.0.0",
8771            "LET $dash: STRING = a-b",
8772            "LET $div: INT = 4 / 2",
8773            "LET $bad: INT = 1__0 + 0",
8774            "LET $strdiv: STRING = 4/2",
8775            "LET $sp: INT = $a - $b",
8776            "$x = 1",
8777            "$x = $a + 1",
8778            "RETURN 1",
8779            KEYWORD_RETURN,
8780            "RETURN $x",
8781            "[env:X] LET $x: INT = 1",
8782            "[os:linux] $x = 2",
8783        ] {
8784            assert_parity(text);
8785        }
8786    }
8787
8788    #[test]
8789    fn malformed_shapes_fail_on_both_paths() {
8790        // Malformed shapes fail on both lexers (messages may differ;
8791        // success/failure must agree). Unbalanced groups fail even
8792        // earlier, at lex time: both layers reject, which is what the
8793        // oracle pins.
8794        for text in [
8795            "[a] ECHO hi",
8796            "[os:atari] ECHO hi",
8797            "[foo:bar] ECHO hi",
8798            "[any(os:linux)] ECHO hi",
8799            "[all()] ECHO hi",
8800            "[env:] ECHO hi",
8801            "[eq(env:K)] ECHO hi",
8802            "[not] ECHO hi",
8803            "ECHO [a;b]",
8804            "ECHO (a;b)",
8805            "ECHO a;b",
8806            "LET $x = 1",
8807            "LET $s: STRING",
8808            "LET $x: INT = 1 2",
8809            "LET $x: INT = (1",
8810            "LET $x: INT = 9223372036854775808",
8811            "$x =",
8812            "RETURN (",
8813            "[env:X]",
8814            "LET $x: INT = $a == $b == $c",
8815            "LET $x: BOOL = $a < $b < $c",
8816            "LET $bs: STRING = a\\nb",
8817            "FOO(\"a\")",
8818            "FOO (\"a\")",
8819            "ECHO(\"hi\")",
8820            "RUN [a] extra",
8821            "RUN[\"a\"]",
8822            "TIMEOUT 10s RUN[\"a\"]",
8823            "LET $r: STRING = RUN[\"a\"]",
8824            "LET $e: STRING = ECHO",
8825            "ENV A=1 B=2",
8826            "EXPAND \"a b\" c",
8827            "ECHO {a}",
8828            "ECHO K=${x}",
8829            "[!env:A==1] RUN echo no",
8830            "run echo hi",
8831            "LET $x: STRING = AWAIT",
8832            "LET $o: STRING = CANCEL $t",
8833            "LET $x: STRING = ASYNC",
8834            "LET $x: STRING = WITH_IO",
8835            "LET $x: STRING = TIMEOUT",
8836            "LET $x: STRING = ISOLATED",
8837            "LET $x: STRING = ISOLATED ECHO hi",
8838            "COPY A=1",
8839            "WITH_IO [rows=40] RUN echo hi",
8840            "WITH_IO [tty] ECHO hi",
8841            "WITH_IO [tty, stderr=$p] RUN echo hi",
8842            "WITH_IO [tty=$p] RUN echo hi",
8843            "WITH_IO [cols=0] RUN echo hi",
8844            "WITH_IO [cols=65536] RUN echo hi",
8845            "WITH_IO [] ECHO hi",
8846            "WITH_IO [stdin=$p,] ECHO hi",
8847            "WITH_IO stdin=$p ECHO hi",
8848            "WITH_IO [STDIN=$p] ECHO hi",
8849            "WITH_IO [rows] RUN echo hi",
8850            KEYWORD_WITH_IO,
8851            "WITH_IO [stdout=$p]",
8852            "WITH_IO [stdin=$p]\n[os:linux] { ECHO hi }",
8853            "WITH_IO [stdin=$p] { }",
8854            "WITH_IO[stdin=$p] ECHO hi",
8855            "WITH_IO [stdin=$p]ECHO hi",
8856            "WITH_IO [stdin=$p] {{ $x }}",
8857            "ASYNC WITH_IO [stdout=$p] ECHO hi",
8858            "WITH_IO [stdin=$p] AWAIT $t",
8859            "ASYNC AWAIT $t",
8860            "WITH_IO [stdin=$p] RETURN \"hi\"",
8861            "ASYNC RETURN \"hi\"",
8862            "TIMEOUT 10s RETURN \"hi\"",
8863            "TIMEOUT banana ECHO hi",
8864            "TIMEOUT 10ss ECHO hi",
8865            "TIMEOUT 10 s ECHO hi",
8866            "TIMEOUT -5s ECHO hi",
8867            "TIMEOUT 0s ECHO hi",
8868            KEYWORD_TIMEOUT,
8869            "TIMEOUT 10s",
8870            "TIMEOUT { ECHO hi }",
8871            "TIMEOUT \"10s\"",
8872            "TIMEOUT 10s{ECHO hi}",
8873            "TIMEOUT 10sECHO hi",
8874            "TIMEOUT 10s {{ $d }}",
8875            "TIMEOUT 10s { $d }",
8876            "TIMEOUT { $d } ECHO hi",
8877            KEYWORD_ASYNC,
8878            KEYWORD_ISOLATED,
8879            "ISOLATED{ECHO hi}",
8880            KEYWORD_AWAIT,
8881            KEYWORD_CANCEL,
8882            "AWAIT t",
8883            "AWAIT $",
8884            "AWAIT $t extra",
8885            "CANCEL $t extra",
8886            "TIMEOUT 5s INHERIT_ENV [M]",
8887            "TIMEOUT 5s { INHERIT_ENV [M] }",
8888            "ASYNC { INHERIT_ENV [M] }",
8889            "LET $x: STRING = INHERIT_ENV [M]",
8890            "TIMEOUT 10s WITH_IO [stdin=$p] { ECHO hi }",
8891            "ISOLATED WITH_IO [stdin=$p] { ECHO hi }",
8892            "TIMEOUT 10s AWAIT $ t",
8893            "LET $o: STRING = AWAIT $ t",
8894            "ISOLATED AWAIT $ t",
8895            "WITH_IO [stdin=$p] CANCEL $ t",
8896            "LET $ x: INT = 1",
8897            "LET $x: STRING = WITH_IO [stdin=$p] { ECHO hi }",
8898            "LET $x: STRING = WITH_IO [stdin=$p] ASYNC",
8899            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO a\nECHO b }",
8900            "LET $x: STRING = WITH_IO [stdout=$p] ECHO hi",
8901            "LET $x: STRING = TIMEOUT 10s AWAIT $t",
8902            "LET $x: STRING = CANCEL $t",
8903            "LET $x: STRING = ASYNC",
8904            "LET $x: STRING = WITH_IO",
8905            "TIMEOUT 10s LET $x: INT = 1",
8906            "LET $x: STRING = FOO bar",
8907            "LET(\"a\")",
8908            "AWAIT($t)",
8909            "CANCEL($t)",
8910            "TIMEOUT(\"10s\") ECHO hi",
8911            "RETURN ECHO bye",
8912        ] {
8913            match crate::tok::lex_str(text) {
8914                Err(_) => {
8915                    assert!(
8916                        crate::parse_script(text, lower).is_err(),
8917                        "backend must also reject lex-broken input: {text:?}"
8918                    );
8919                    continue;
8920                }
8921                Ok(toks) => {
8922                    assert!(
8923                        parse_tokens(&toks, lower).is_err(),
8924                        "v2 must explicitly reject (not silently drift): {text:?}"
8925                    );
8926                }
8927            }
8928            assert!(
8929                crate::parse_script(text, lower).is_err(),
8930                "backend must also reject (oracle agreement): {text:?}"
8931            );
8932        }
8933        // No deferred shapes remain: every statement-level block and
8934        // inline-block expression parses natively.
8935    }
8936}