Skip to main content

oxdock_parser/
parser.rs

1//! Script parser: [`Tok`] stream to [`Step`].
2//!
3//! The single parser for string scripts and braced-macro token
4//! streams. The string entry points at the bottom of this module lex
5//! with `lex_str` and lower here; the braced-macro frontend fuses
6//! span-adjacent literals, runs the same scanner, and lowers here.
7//!
8//! Statement boundaries resolve here from grammar state, never in the
9//! lexers: groups arrive structurally atomic, so at each nesting level
10//! a `Newline`/`Semicolon` ends the statement. Continuation exceptions
11//! (trailing `=`, `IN`, trailing `ASYNC`, bare wrapper heads) land with
12//! their structural slices; the decision point is
13//! `boundary_ends_statement`.
14//!
15//! Coverage: generic commands (head word plus gap-split args with
16//! quote-accurate joins), guards (leading `[..]` groups; in-body
17//! brackets splice to raw text), `LET`/`SET`/`RETURN` with the full
18//! expression tiers, static calls and RUN-exec with instruction
19//! exactness, single-command wrappers (`WITH_IO`/`TIMEOUT`/`ISOLATED`/
20//! `ASYNC`), io-blocks, `AWAIT`/`CANCEL`, multi-element statements,
21//! block statements (`IF`/`FOR`/`WHILE`/`FUNC`/`REMOTE`/`TYPE`/
22//! `IMPORT`/`EXPORT`), guard blocks, and a whole-script post-pass
23//! (prelude order, COPY placement, EXPORT membership). Comments ride
24//! as `TokKind::Comment` markers plus mid-line `//`/`#`/`/*` gap
25//! rules.
26//!
27//! Design record: shared lowering cores with parser-native token
28//! classification. Each item below states what is shared and what is
29//! parser-native (verified by the lexer-agreement oracle and the fuzz
30//! harness).
31//! - Argument assembly matches single-quoted-string `quoted=true` and
32//!   multi-fragment space-or-empty joins by the `joint` flag.
33//! - `key_char`/`bare_run`/`value_run` implement the guard key/value
34//!   charsets (everything but `: = ! , | ( ) ] $`, whitespace, and
35//!   comment opens; `eq` values cross gaps like the atomic span).
36//! - `ns_guard` validates namespaces with shared messages.
37//! - Guard validation strings (`any(...)/all(...)/eq(...)` shapes)
38//!   carry shared messages.
39//! - `parse_guard_groups` folds stacked brackets with `All` (the
40//!   statement-guard stash semantics).
41//! - The expression tiers implement or/and/compare/ordering/add/mul/
42//!   unary/atom precedence over [`Tok`]; lowering runs through the
43//!   shared constructors (`make_arith`, `make_compare`,
44//!   `apply_unary_neg`, `reject_boundary`, `classify_numeric_text`,
45//!   `canonicalize_spelling`, `lower_block_string`).
46//! - Static call resolution is truly shared (`resolve_call_name`,
47//!   `check_func_ident` in `resolve.rs`).
48//! - Instruction tokens are truly shared (`InsToken`,
49//!   `lower_env_tokens`, `lower_expand_tokens`,
50//!   `canonical_assignment_arg` in `commands.rs`); only the
51//!   token-level classifiers (key runs, boundaries, call shapes,
52//!   expression extension) are parser-native.
53//! - Numeric `_`-separator shape gating, bare-word charsets, and
54//!   `-`-prefix dispatch match the lexical rules (durations, paths,
55//!   and versions lex as bare words; `-f` stays literal).
56//! - Wrapper validators are truly shared (`check_tty_wrapping`,
57//!   `reject_async_in_capture`, `reject_pipe_stdout_in_capture`,
58//!   `rewrite_isolated_inherit`, `contains_inherit_env`,
59//!   `reject_nested_inherit_env`, `merge_bindings`, `IoBindingSet`,
60//!   `and_guard_exprs`, `reject_with_io_in_async` in `commands.rs`;
61//!   in `commands.rs`); only the token-level shape classifiers
62//!   (duration gate, binding splitter, await/cancel shapes,
63//!   block-vs-template, inherit keys) are parser-native.
64//! - The element loop lowers consecutive elements to end of run:
65//!   structural pairs end mid-line and trailing elements form
66//!   following steps (guards attach to the first only); the `WITH_IO`
67//!   pending wait holds bare brackets across separators.
68//! - Block headers: `IF`/`FOR`/`WHILE` conditions miss to generic
69//!   on unclassified expression failure (classified callee failures
70//!   and inline-block failures propagate); `FUNC` paren-group params parse with `gap_nl`
71//!   discipline (shared helper, like call args); `REMOTE` targets/blocks/bindings; `TYPE` maximal
72//!   shape match; `IMPORT`/`EXPORT` lists. Shared
73//!   validators are truly shared (`validate_remote_copy_placement`,
74//!   `contains_remote_block`, `collect_remote_body_symbols`,
75//!   `validate_exports` in `commands.rs`).
76//! - Scope marking: top-level guard nesting
77//!   bumps each level (stateful `pending_scope_enters`); wrapper and
78//!   guard-block bodies pin 0/0 (`parse_body_steps` without marking).
79//! - Comment handling: statement-position
80//!   comments vanish (releasing `ELSE` holds), gap positions skip,
81//!   arg positions type or glue literally; `/*` depth protects
82//!   separators in the splitter, and group scanning copies comments
83//!   through for the recursive re-lex.
84
85use crate::ast::{
86    Arg, ArithOp, CompareOp, Expr, Guard, GuardExpr, IoBinding, IoStream, LogicalOp, ModuleTable,
87    Ns, Step, StepKind, Value,
88};
89use crate::command::ArgType;
90use crate::commands::{
91    InsToken, apply_unary_neg, canonical_assignment_arg, check_tty_wrapping, classify_numeric_text,
92    is_known_command, lower_env_tokens, lower_expand_tokens, make_arith, make_compare,
93    reject_boundary,
94};
95use crate::constants::{
96    INJECT_PREFIX, INJECT_SUFFIX, KEYWORD_AS, KEYWORD_ASYNC, KEYWORD_AWAIT, KEYWORD_BREAK,
97    KEYWORD_CANCEL, KEYWORD_CONTINUE, KEYWORD_ELSE, KEYWORD_ENV, KEYWORD_EXPAND, KEYWORD_EXPORT,
98    KEYWORD_FOR, KEYWORD_FROM, KEYWORD_FUNC, KEYWORD_IF, KEYWORD_IMPORT, KEYWORD_IN,
99    KEYWORD_INHERIT_ENV, KEYWORD_INSPECT, KEYWORD_ISOLATED, KEYWORD_LET, KEYWORD_REMOTE,
100    KEYWORD_RETURN, KEYWORD_RUN, KEYWORD_TIMEOUT, KEYWORD_TYPE, KEYWORD_WHILE, KEYWORD_WITH_IO,
101    MODULE_SEPARATOR,
102};
103use crate::error::{ParseError, ParseErrorKind, ParseResult, SpanContext};
104
105use crate::resolve::resolve_call_name;
106use crate::tok::{GroupDelim, LexError, Tok, TokKind, lex_str};
107use std::cell::RefCell;
108use std::collections::HashSet;
109use std::fmt;
110
111/// Backend error. Carries the statement index and message; the string
112/// entry points below map it to [`crate::ParseError`]. Lowering
113/// failures from the shared `lower` dispatcher stringify through here
114/// so success paths compare exactly.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct TokenError {
117    pub stmt: usize,
118    /// 1-based source line, `0` when unknown (the split loops stamp the
119    /// enclosing statement's line on the way out, so only genuinely
120    /// position-less errors stay `0`).
121    pub line: usize,
122    /// 1-based start column of the enclosing statement, `0` when
123    /// unknown (stamped alongside `line`).
124    pub col: usize,
125    pub msg: String,
126    /// Lowering failures preserve the dispatcher's classification
127    /// (`UnknownCommand`, `InvalidSyntax`, `Validation`); `None` means
128    /// a parser-native structural failure.
129    pub kind: Option<ParseErrorKind>,
130}
131
132impl fmt::Display for TokenError {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        write!(
135            f,
136            "parse error in statement {}: {}",
137            self.stmt + 1,
138            self.msg
139        )
140    }
141}
142
143impl std::error::Error for TokenError {}
144
145/// Lift a dispatcher/resolver [`ParseError`] into a [`TokenError`],
146/// preserving its machine-readable classification (the entry points
147/// convert it back verbatim, so `UnknownCommand`/`InvalidSyntax`/
148/// `Validation` survive the round trip). The message is the
149/// dispatcher's own display text; the split loops stamp the line.
150fn lower_err(stmt: usize, e: ParseError) -> TokenError {
151    TokenError {
152        stmt,
153        line: 0,
154        col: 0,
155        msg: e.to_string(),
156        kind: Some(e.kind().clone()),
157    }
158}
159
160/// One split statement: leading bracket groups (guard region) plus
161/// the body tokens. `brace_detached` records a
162/// `Newline`/`Semicolon` between the guard region and a brace-headed
163/// body: in-body such statements are hard errors (a bare `{` is
164/// illegal inside blocks), while top level merges or parses guard
165/// blocks regardless.
166#[derive(Debug, Clone)]
167struct Stmt {
168    guard: Vec<Tok>,
169    body: Vec<Tok>,
170    brace_detached: bool,
171    /// 1-based source line where the body starts (guards ride on
172    /// earlier lines; errors report this).
173    line: usize,
174    /// 1-based column where the body starts (`0` when the head token
175    /// carries no coordinates: synthetic streams). Read off the first
176    /// body token, which always has the statement's own start.
177    col: usize,
178}
179
180impl PartialEq for Stmt {
181    fn eq(&self, other: &Self) -> bool {
182        // Coordinates are provenance (never rendered, never compared),
183        // like `Step`/`Tok`: two splits of one text compare equal.
184        self.guard == other.guard
185            && self.body == other.body
186            && self.brace_detached == other.brace_detached
187    }
188}
189
190impl Eq for Stmt {}
191
192/// True when a newline continues the statement for a multi-line
193/// generic: the body opens a type-carrying statement (TYPE/LET/FOR)
194/// and holds an unclosed `<...>` shape. Only a joint `<` after an
195/// uppercase word opens (never `<=`, never `$VAR<`), so spaced
196/// comparisons keep ending the statement as before. FUNC needs no
197/// gate: parameter types ride inside the atomic paren group, and the
198/// grammar defines no return-type position after the group.
199fn type_continuation_rides(body: &[Tok], next: Option<&Tok>) -> bool {
200    if !matches!(
201        body.first().map(|t| &t.kind),
202        Some(TokKind::Word(w)) if w == KEYWORD_TYPE || w == KEYWORD_LET || w == KEYWORD_FOR
203    ) {
204        return false;
205    }
206    open_generic_depth(body, next) > 0
207}
208
209/// Unclosed `<...>` depth over a statement body: a joint `<` after
210/// an uppercase word opens (generic instantiation), `>` closes.
211fn open_generic_depth(body: &[Tok], next: Option<&Tok>) -> usize {
212    let mut depth = 0usize;
213    for (idx, tok) in body.iter().enumerate() {
214        if !matches!(&tok.kind, TokKind::Punct('<')) {
215            if matches!(&tok.kind, TokKind::Punct('>')) && depth > 0 {
216                depth -= 1;
217            }
218            continue;
219        }
220        if !tok.joint {
221            continue;
222        }
223        if idx == 0 {
224            continue;
225        }
226        if !matches!(
227            body.get(idx - 1).map(|t| &t.kind),
228            Some(TokKind::Word(w)) if is_upper_ident(w)
229        ) {
230            continue;
231        }
232        // `$VAR<` is a comparison, never a generic.
233        if idx >= 2
234            && body.get(idx - 1).is_some_and(|t| t.joint)
235            && matches!(
236                body.get(idx - 2).map(|t| &t.kind),
237                Some(TokKind::Punct('$'))
238            )
239        {
240            continue;
241        }
242        // `<=` is a comparison lead, never a generic open.
243        let followed_by_eq = matches!(
244            body.get(idx + 1).map(|t| &t.kind),
245            Some(TokKind::Punct('='))
246        ) || (idx + 1 == body.len()
247            && matches!(next.map(|t| &t.kind), Some(TokKind::Punct('='))));
248        if !followed_by_eq {
249            depth += 1;
250        }
251    }
252    depth
253}
254
255/// Grammar-state boundary decision: does this `Newline`/`Semicolon`
256/// end the statement? Groups are atomic, so every statement fits one
257/// logical token line; every keyword-headed statement (commands,
258/// wrappers, `LET`/`AWAIT`, block statements, directives) ends here.
259/// Only non-word heads fail, exactly like the grammar's element
260/// mismatch.
261fn boundary_ends_statement(body: &[Tok]) -> Result<bool, String> {
262    let head = match body.first() {
263        None => return Ok(true),
264        Some(t) => t,
265    };
266    match &head.kind {
267        TokKind::Word(_) | TokKind::Punct('$') => Ok(true),
268        // A lone leading `{...}` ends here too: the splitter merges
269        // it into pending waits (`WITH_IO`, `IF`/`ELSE` chains) or
270        // emits it for block-statement lowering, never splitting
271        // inside.
272        TokKind::Group {
273            delim: GroupDelim::Brace,
274            ..
275        } => Ok(true),
276        _ => Err("statement must open with a command word".to_string()),
277    }
278}
279
280/// Bare `WITH_IO [..]` with no inner command: holds the line for a
281/// following `{...}` block (bare-bracket hold), which merges into one
282/// io-block statement. Anything else (or EOF) fails exactly like the
283/// grammar's `must be followed by '{'`.
284fn is_bare_with_io(body: &[Tok]) -> bool {
285    matches!(body.first().map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_WITH_IO)
286        && matches!(
287            body.get(1).map(|t| (&t.kind, t.joint)),
288            Some((
289                TokKind::Group {
290                    delim: GroupDelim::Bracket,
291                    ..
292                },
293                false
294            ))
295        )
296        && body.len() == 2
297}
298
299/// An if-tailed statement body: head `IF`, ends with a non-template
300/// brace (the then/else-if block), ignoring trailing gap comments.
301/// Trailing `//`/`#` runs and balanced `/* */` strip backward (the
302/// grammar's `gap` eats them before the `ELSE` chain, joint state
303/// irrelevant after a complete pair); anything else trailing (text,
304/// groups, strings) breaks the tail. Over-holding is safe: a merged
305/// non-`ELSE` follower releases, and a merged `ELSE` parses exactly
306/// where the grammar would.
307fn is_if_tail(body: &[Tok]) -> bool {
308    if !matches!(body.first().map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_IF) {
309        return false;
310    }
311    let mut end = body.len();
312    loop {
313        // Lexer comment markers.
314        while end > 0 && matches!(&body[end - 1].kind, TokKind::Comment(_)) {
315            end -= 1;
316        }
317        // Earliest comment opener (`//`-pair, `#`, `/*`-pair) starts
318        // trailing comment territory.
319        let mut cut = None;
320        let mut k = 0;
321        while k < end {
322            match &body[k].kind {
323                TokKind::Punct('#') => {
324                    cut = Some(k);
325                    break;
326                }
327                TokKind::Punct('/') if is_comment_open(&body[..end], k) => {
328                    cut = Some(k);
329                    break;
330                }
331                _ => k += 1,
332            }
333        }
334        match cut {
335            Some(k) => {
336                // A balanced `/* */` may be followed by more gap
337                // comments; anything else ends the strip for the
338                // brace check below.
339                if matches!(&body[k].kind, TokKind::Punct('/'))
340                    && !matches!(body.get(k + 1).map(|t| &t.kind), Some(TokKind::Punct('/')))
341                {
342                    match skip_inline_comment(&body[..end], k) {
343                        Some(past) if past < end => {
344                            end = past;
345                            continue;
346                        }
347                        _ => {}
348                    }
349                }
350                end = k;
351                continue;
352            }
353            None => break,
354        }
355    }
356    matches!(
357        body[..end].last().map(|t| &t.kind),
358        Some(TokKind::Group {
359            delim: GroupDelim::Brace,
360            ..
361        })
362    ) && body[..end].last().is_some_and(|t| !is_template_brace(t))
363}
364
365/// True when a body opens with a brace group (guard-block position
366/// or bare block).
367fn starts_brace(body: &[Tok]) -> bool {
368    matches!(
369        body.first().map(|t| &t.kind),
370        Some(TokKind::Group {
371            delim: GroupDelim::Brace,
372            ..
373        })
374    )
375}
376
377/// Source lines spanned by one token (for the splitter's line
378/// counter): newlines, `/* */` comment interiors, and nested group
379/// contents. Everything else occupies its own line.
380fn tok_newlines(tok: &Tok) -> usize {
381    match &tok.kind {
382        TokKind::Newline => 1,
383        TokKind::Comment(text) => text.matches('\n').count(),
384        TokKind::Group { inner, .. } => inner.iter().map(tok_newlines).sum(),
385        _ => 0,
386    }
387}
388
389/// Stamp an error with the innermost statement's position when it
390/// has none yet (deeper frames stamp first, so outer frames never
391/// overwrite real positions). Each component fills independently.
392fn stamp_pos(err: TokenError, line: usize, col: usize) -> TokenError {
393    TokenError {
394        line: if err.line == 0 { line } else { err.line },
395        col: if err.col == 0 { col } else { err.col },
396        ..err
397    }
398}
399
400/// Split top-level tokens into statements. Leading `[..]` groups attach
401/// to the following statement as its guard region; `Newline`/`Semicolon`
402/// end statements per [`boundary_ends_statement`]. Empty statements
403/// (blank lines, stray `;`) drop, matching the blank/semicolon
404/// grammar elements. Comment markers drop silently everywhere except
405/// pending `ELSE` waits, which a comment line breaks exactly like the
406/// grammar. Mid-line `//` runs and `#`/`/*` opens with an empty body
407/// skip as comments (statement position, like the grammar's silent
408/// elements); anywhere else they stay payload text for the arg engine.
409fn split_statements(toks: &[Tok], base: usize) -> Result<Vec<Stmt>, TokenError> {
410    let mut stmts = Vec::new();
411    let mut guard = Vec::new();
412    let mut body: Vec<Tok> = Vec::new();
413    let mut stmt_idx = 0;
414    // 1-based source line tracker: `base` is the line `toks[0]` starts
415    // on (1 at top level, the enclosing statement's line inside
416    // groups, where headers are single-line so the brace shares it).
417    // Groups and block comments advance past their inner newlines;
418    // every pushed statement records its body's start line for errors.
419    let mut line = base;
420    let mut start_line = base;
421    let mut start_col = 0;
422    // Bare `WITH_IO [..]` awaiting its `{...}` block (see
423    // `is_bare_with_io`): the guard and body hold across any
424    // separator until the brace arrives or the wait fails.
425    // Pending holds carry their body's start line with them.
426    let mut pending_io: Option<(Vec<Tok>, Vec<Tok>, usize, usize)> = None;
427    // If-tailed statement awaiting an `ELSE` continuation across
428    // newlines only (a `;` breaks the chain like the grammar).
429    let mut pending_if: Option<(Vec<Tok>, Vec<Tok>, usize, usize)> = None;
430    // Separator crossed between the guard region and the body start:
431    // only observed for brace-headed bodies (`brace_detached`).
432    let mut detached = false;
433    // Flush a statement, resolving pending waits first. `via_newline`
434    // records the separator kind: only newlines hold/merge `ELSE`
435    // chains; `;` and EOF release them. `line` is the current tracker
436    // for wait-failure errors; `start_line` is this body's start.
437    let flush_or_hold = |stmts: &mut Vec<Stmt>,
438                         guard: &mut Vec<Tok>,
439                         body: &mut Vec<Tok>,
440                         detached: &mut bool,
441                         stmt_idx: &mut usize,
442                         pending_io: &mut Option<(Vec<Tok>, Vec<Tok>, usize, usize)>,
443                         pending_if: &mut Option<(Vec<Tok>, Vec<Tok>, usize, usize)>,
444                         via_newline: bool,
445                         start_line: usize,
446                         start_col: usize,
447                         line: usize|
448     -> Result<(), TokenError> {
449        if body.is_empty() {
450            guard.clear();
451            *detached = false;
452            return Ok(());
453        }
454        // Pending `WITH_IO` wait takes precedence (the holds are
455        // mutually exclusive: setting either returns first).
456        if let Some((pending_guard, mut pending_body, pending_line, pending_col)) =
457            pending_io.take()
458        {
459            // Only a lone guard-less `{...}` group satisfies the wait;
460            // anything else (commands, guarded braces) fails like the
461            // grammar's `must be followed by '{'`.
462            let lone_brace = guard.is_empty()
463                && body.len() == 1
464                && matches!(
465                    body.first().map(|t| &t.kind),
466                    Some(TokKind::Group {
467                        delim: GroupDelim::Brace,
468                        ..
469                    })
470                );
471            if !lone_brace {
472                return Err(TokenError {
473                    stmt: *stmt_idx,
474                    msg: "WITH_IO block must be followed by '{'".to_string(),
475                    line: pending_line,
476                    col: pending_col,
477                    kind: None,
478                });
479            }
480            pending_body.extend(std::mem::take(body));
481            guard.clear();
482            *detached = false;
483            stmts.push(Stmt {
484                guard: pending_guard,
485                body: pending_body,
486                brace_detached: false,
487                line: pending_line,
488                col: pending_col,
489            });
490            *stmt_idx += 1;
491            return Ok(());
492        }
493        // Pending `ELSE` wait: merge guard-less `ELSE`-led statements.
494        // The wait was set across a newline (only newlines hold), so
495        // the separator kind of *this* flush is irrelevant — `;` and
496        // EOF merge too; anything else releases the held IF.
497        if let Some((held_guard, mut held_body, held_line, held_col)) = pending_if.take() {
498            let else_start = guard.is_empty()
499                && matches!(
500                    body.first().map(|t| &t.kind),
501                    Some(TokKind::Word(w)) if w == KEYWORD_ELSE
502                );
503            if !else_start {
504                stmts.push(Stmt {
505                    guard: held_guard,
506                    body: held_body,
507                    brace_detached: false,
508                    line: held_line,
509                    col: held_col,
510                });
511                *stmt_idx += 1;
512            } else {
513                // The merged chain may hold again for a further
514                // `ELSE`, newlines only, like the grammar. A newline
515                // marker joins the parts: `#` comments end at it
516                // (their extent is unrecoverable post-merge), while
517                // `//`/`/*` carry their own extents.
518                held_body.push(Tok::fresh(TokKind::Newline, false));
519                held_body.extend(std::mem::take(body));
520                guard.clear();
521                *detached = false;
522                if via_newline && is_if_tail(&held_body) {
523                    *pending_if = Some((held_guard, held_body, held_line, held_col));
524                    return Ok(());
525                }
526                stmts.push(Stmt {
527                    guard: held_guard,
528                    body: held_body,
529                    brace_detached: false,
530                    line: held_line,
531                    col: held_col,
532                });
533                *stmt_idx += 1;
534                return Ok(());
535            }
536        }
537        if is_bare_with_io(body) {
538            if pending_io.is_some() {
539                return Err(TokenError {
540                    stmt: *stmt_idx,
541                    msg: "previous WITH_IO block is still waiting for '{'".to_string(),
542                    line,
543                    col: start_col,
544                    kind: None,
545                });
546            }
547            *pending_io = Some((
548                std::mem::take(guard),
549                std::mem::take(body),
550                start_line,
551                start_col,
552            ));
553            *detached = false;
554            return Ok(());
555        }
556        // Ordinary statement: emit it, holding if-tailed bodies for
557        // an `ELSE` continuation across newlines only.
558        if via_newline && is_if_tail(body) {
559            *pending_if = Some((
560                std::mem::take(guard),
561                std::mem::take(body),
562                start_line,
563                start_col,
564            ));
565            *detached = false;
566            return Ok(());
567        }
568        let brace_detached = *detached && !guard.is_empty() && starts_brace(body);
569        stmts.push(Stmt {
570            guard: std::mem::take(guard),
571            body: std::mem::take(body),
572            brace_detached,
573            line: start_line,
574            col: start_col,
575        });
576        *detached = false;
577        *stmt_idx += 1;
578        Ok(())
579    };
580    // Release a pending `ELSE` wait by emitting the held IF as-is.
581    // (Inlined at use sites: a closure would collide with
582    // `flush_or_hold`'s borrow of the statement buffer.)
583    let mut i = 0;
584    // Open text-`/*` depth (line-start comments arrive as `Comment`
585    // toks; `//` never spans separators): newlines and semicolons
586    // inside never split, and `[` never guards (the closer, an
587    // error, or downstream rules resolve everything, exactly like
588    // the grammar).
589    let mut comment_depth = 0usize;
590    // True when `toks[i]` opens a text block comment (`/` plus a
591    // joint `*`; `//` is line-comment territory, handled elsewhere).
592    let block_open_at = |toks: &[Tok], i: usize| {
593        matches!(toks.get(i).map(|t| &t.kind), Some(TokKind::Punct('/')))
594            && matches!(
595                toks.get(i + 1).map(|t| (&t.kind, t.joint)),
596                Some((TokKind::Punct('*'), true))
597            )
598    };
599    // True when `toks[i]` closes one (`*` plus a joint `/`).
600    let block_close_at = |toks: &[Tok], i: usize| {
601        matches!(toks.get(i).map(|t| &t.kind), Some(TokKind::Punct('*')))
602            && matches!(
603                toks.get(i + 1).map(|t| (&t.kind, t.joint)),
604                Some((TokKind::Punct('/'), true))
605            )
606    };
607    while i < toks.len() {
608        let tok = &toks[i];
609        // Statement-start `/*` (silent gap position): skip balanced,
610        // failing unclosed like the grammar; mid-body opens only
611        // deepen the tracker below and ride into args as payload.
612        if body.is_empty() && comment_depth == 0 && block_open_at(toks, i) {
613            match skip_inline_comment(toks, i) {
614                Some(past) => {
615                    // The skipped span may cross lines (`/*a\nb*/`).
616                    line += toks[i..past].iter().map(tok_newlines).sum::<usize>();
617                    i = past;
618                    continue;
619                }
620                None => {
621                    return Err(TokenError {
622                        stmt: stmt_idx,
623                        msg: "unclosed block comment".to_string(),
624                        line,
625                        col: tok.col,
626                        kind: None,
627                    });
628                }
629            }
630        }
631        // Nesting transitions on text pairs (mid-body opens deepen;
632        // closers pop when nested).
633        if block_open_at(toks, i) && (comment_depth > 0 || !body.is_empty()) {
634            comment_depth += 1;
635        } else if block_close_at(toks, i) && comment_depth > 0 {
636            comment_depth -= 1;
637        }
638        // Inside a block comment everything rides into the current
639        // body (never splits, never guards, never releases waits,
640        // never skips): gap positions swallow it downstream, arg
641        // positions fail or math over it, exactly like the grammar.
642        if comment_depth > 0 {
643            if body.is_empty() {
644                // Head-token coordinates are authoritative: the line
645                // tracker lags content stripped before lexing (comments
646                // vanish on the token path, leaving no newline behind).
647                // Zero coordinates (synthetic streams) keep the tracker.
648                if tok.line > 0 {
649                    start_line = tok.line;
650                } else {
651                    start_line = line;
652                }
653                if tok.col > 0 {
654                    start_col = tok.col;
655                }
656            }
657            line += tok_newlines(tok);
658            body.push(tok.clone());
659            detached = false;
660            i += 1;
661            continue;
662        }
663        match &tok.kind {
664            TokKind::Newline => {
665                if body.is_empty() {
666                    // A separator between the guard region and a
667                    // following brace matters (see `brace_detached`).
668                    detached = true;
669                    line += 1;
670                    i += 1;
671                    continue;
672                }
673                // Multi-line generics: a newline inside an unclosed
674                // `<...>` rides into the body, so `MAP<...>` shapes may
675                // span lines. Anything else ends here as before.
676                if type_continuation_rides(&body, toks.get(i + 1)) {
677                    line += 1;
678                    body.push(tok.clone());
679                    detached = false;
680                    i += 1;
681                    continue;
682                }
683                match boundary_ends_statement(&body) {
684                    Ok(true) => flush_or_hold(
685                        &mut stmts,
686                        &mut guard,
687                        &mut body,
688                        &mut detached,
689                        &mut stmt_idx,
690                        &mut pending_io,
691                        &mut pending_if,
692                        true,
693                        start_line,
694                        start_col,
695                        line,
696                    )?,
697                    Ok(false) => {}
698                    Err(msg) => {
699                        return Err(TokenError {
700                            stmt: stmt_idx,
701                            msg,
702                            line: start_line,
703                            col: start_col,
704                            kind: None,
705                        });
706                    }
707                }
708                line += 1;
709                i += 1;
710            }
711            TokKind::Semicolon => {
712                if body.is_empty() {
713                    // A `;` breaks `ELSE` chains (release the hold)
714                    // but not `WITH_IO` waits (probed `;` merge).
715                    if let Some((held_guard, held_body, held_line, held_col)) = pending_if.take() {
716                        stmts.push(Stmt {
717                            guard: held_guard,
718                            body: held_body,
719                            brace_detached: false,
720                            line: held_line,
721                            col: held_col,
722                        });
723                        stmt_idx += 1;
724                    }
725                    detached = true;
726                    i += 1;
727                    continue;
728                }
729                match boundary_ends_statement(&body) {
730                    Ok(true) => flush_or_hold(
731                        &mut stmts,
732                        &mut guard,
733                        &mut body,
734                        &mut detached,
735                        &mut stmt_idx,
736                        &mut pending_io,
737                        &mut pending_if,
738                        false,
739                        start_line,
740                        start_col,
741                        line,
742                    )?,
743                    Ok(false) => {}
744                    Err(msg) => {
745                        return Err(TokenError {
746                            stmt: stmt_idx,
747                            msg,
748                            line: start_line,
749                            col: start_col,
750                            kind: None,
751                        });
752                    }
753                }
754                i += 1;
755            }
756            // Lexer comment markers drop silently, but release a
757            // pending `ELSE` wait (a comment line breaks the chain
758            // like the grammar); `WITH_IO` waits survive comments.
759            TokKind::Comment(text) => {
760                if let Some((held_guard, held_body, held_line, held_col)) = pending_if.take() {
761                    stmts.push(Stmt {
762                        guard: held_guard,
763                        body: held_body,
764                        brace_detached: false,
765                        line: held_line,
766                        col: held_col,
767                    });
768                    stmt_idx += 1;
769                }
770                // A joint marker (`a//b`) is payload, not trivia: it
771                // rides into the body so arg assembly glues it
772                // literally, exactly like the grammar. Gapped and
773                // line-start markers drop.
774                if tok.joint && !body.is_empty() {
775                    line += text.matches('\n').count();
776                    body.push(tok.clone());
777                    detached = false;
778                    i += 1;
779                    continue;
780                }
781                // Block markers may span lines (`/*a\nb*/`).
782                line += text.matches('\n').count();
783                i += 1;
784            }
785            // A `//` run with an empty body (mid-line, e.g. after
786            // `;`) is a comment to the line end; with a non-empty
787            // body the slash-run rule owns it as payload text.
788            TokKind::Punct('/') if body.is_empty() && is_comment_open(toks, i) => {
789                if matches!(toks.get(i + 1).map(|t| &t.kind), Some(TokKind::Punct('/'))) {
790                    while i < toks.len() && !matches!(&toks[i].kind, TokKind::Newline) {
791                        i += 1;
792                    }
793                } else {
794                    match skip_inline_comment(toks, i) {
795                        Some(past) => i = past,
796                        None => {
797                            return Err(TokenError {
798                                stmt: stmt_idx,
799                                msg: "unclosed block comment".to_string(),
800                                line,
801                                col: tok.col,
802                                kind: None,
803                            });
804                        }
805                    }
806                }
807            }
808            // `#` with an empty body (e.g. after `;`) is a comment
809            // to the line end; mid-body it stays arg text.
810            TokKind::Punct('#') if body.is_empty() => {
811                while i < toks.len() && !matches!(&toks[i].kind, TokKind::Newline) {
812                    i += 1;
813                }
814            }
815            TokKind::Group { delim, .. } if body.is_empty() && *delim == GroupDelim::Bracket => {
816                // Guard groups may span lines; the body starts after.
817                line += tok_newlines(tok);
818                guard.push(tok.clone());
819                detached = false;
820                i += 1;
821            }
822            _ => {
823                if body.is_empty() {
824                    // Head-token coordinates are authoritative (see
825                    // above); the tracker is the fallback.
826                    if tok.line > 0 {
827                        start_line = tok.line;
828                    } else {
829                        start_line = line;
830                    }
831                    if tok.col > 0 {
832                        start_col = tok.col;
833                    }
834                }
835                line += tok_newlines(tok);
836                body.push(tok.clone());
837                i += 1;
838            }
839        }
840    }
841    if !body.is_empty() {
842        match boundary_ends_statement(&body) {
843            Ok(_) => flush_or_hold(
844                &mut stmts,
845                &mut guard,
846                &mut body,
847                &mut detached,
848                &mut stmt_idx,
849                &mut pending_io,
850                &mut pending_if,
851                false,
852                start_line,
853                start_col,
854                line,
855            )?,
856            Err(msg) => {
857                return Err(TokenError {
858                    stmt: stmt_idx,
859                    msg,
860                    line: start_line,
861                    col: start_col,
862                    kind: None,
863                });
864            }
865        }
866    } else if !guard.is_empty() {
867        // Trailing guards with no following command error (probed: a
868        // lone `[env:X]` is an error), never drop silently.
869        return Err(TokenError {
870            stmt: stmt_idx,
871            msg: "guard declared without a following command".to_string(),
872            line,
873            col: 0,
874            kind: None,
875        });
876    }
877    // Release a trailing `ELSE` wait; a trailing `WITH_IO` wait fails.
878    if let Some((held_guard, held_body, held_line, held_col)) = pending_if.take() {
879        stmts.push(Stmt {
880            guard: held_guard,
881            body: held_body,
882            brace_detached: false,
883            line: held_line,
884            col: held_col,
885        });
886    }
887    if let Some((_, _, pending_line, pending_col)) = pending_io.take() {
888        return Err(TokenError {
889            stmt: stmt_idx,
890            msg: "WITH_IO block must be followed by '{'".to_string(),
891            line: pending_line,
892            col: pending_col,
893            kind: None,
894        });
895    }
896    Ok(stmts)
897}
898
899/// Splice in-body bracket/paren groups to flat raw text: arg-position
900/// brackets read as ordinary characters split purely on whitespace
901/// (`ECHO [a, b]` is args `"[a,"` + `"b]"`), so the parser expands
902/// each group to open-punct + inner + close-punct and lets the normal
903/// gap-split/render reproduce the bytes exactly (probed parity).
904/// Recursion handles nesting; edge joints ride along untouched. Brace
905/// groups stay put (blocks, never args). Newlines/semicolons spliced
906/// from multi-line groups fail loudly in assembly.
907fn splice_arg_groups(body: &[Tok], stmt: usize) -> Result<Vec<Tok>, TokenError> {
908    let _ = stmt;
909    let mut out = Vec::new();
910    for tok in body.iter() {
911        match &tok.kind {
912            TokKind::Group {
913                delim: GroupDelim::Brace,
914                ..
915            } => out.push(tok.clone()),
916            // Call parens stay structural: exploding them to puncts
917            // would strand full-region calls (`MAKE()` in arg position)
918            // as raw text, disagreeing with assignment values and
919            // RUN-exec items, which both parse calls. Brackets keep
920            // the raw-text splicing below (whitespace splits inside
921            // them, strings de-quote to words).
922            TokKind::Group {
923                delim: GroupDelim::Paren,
924                ..
925            } => out.push(tok.clone()),
926            TokKind::Group {
927                delim: GroupDelim::Bracket,
928                inner,
929                close_joint,
930                ..
931            } => {
932                out.push(Tok::fresh(TokKind::Punct('['), tok.joint));
933                // Inside brackets raw-text rules apply: quotes are
934                // characters, blocks never dedent, and whitespace splits
935                // runs (`['a b']` is args `"['a"` + `"b']"`). Convert
936                // spliced strings back to word text (splitting it like
937                // raw text); top-level strings stay structural.
938                for t in splice_arg_groups(inner, stmt)? {
939                    match &t.kind {
940                        TokKind::Str { text, quote } => {
941                            out.extend(split_word_text(&format!("{quote}{text}{quote}"), t.joint));
942                        }
943                        TokKind::BlockStr(full) => {
944                            out.extend(split_word_text(full, t.joint));
945                        }
946                        _ => out.push(t),
947                    }
948                }
949                out.push(Tok::fresh(TokKind::Punct(']'), *close_joint));
950            }
951            _ => out.push(tok.clone()),
952        }
953    }
954    Ok(out)
955}
956
957/// Split re-quoted raw text on whitespace runs. The first piece keeps the source joint flag; the rest break
958/// (whitespace separates args). Multi-space gaps normalize to one
959/// (documented edge, same class as group rendering).
960fn split_word_text(text: &str, joint: bool) -> Vec<Tok> {
961    let mut out = Vec::new();
962    let mut first = true;
963    for piece in text.split_whitespace() {
964        out.push(Tok::fresh(
965            TokKind::Word(piece.to_string()),
966            if first { joint } else { false },
967        ));
968        first = false;
969    }
970    if out.is_empty() {
971        out.push(Tok::fresh(TokKind::Word(text.to_string()), joint));
972    }
973    out
974}
975
976/// Assignment key charset, minus the `=` the
977/// classifier handles separately. Words are pre-filtered by the same
978/// set; `$`, quotes, and groups never start a key.
979fn is_assign_key_char(c: char) -> bool {
980    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':')
981}
982
983/// Match an assignment key run at an argument start: joint
984/// word/punct run in the key charset, non-empty, not `--`-led
985/// (flags keep their literal reading). Returns the key and end index.
986fn match_assign_key(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
987    let mut out = String::new();
988    let mut p = pos;
989    loop {
990        let t = toks.get(p)?;
991        if !out.is_empty() && !t.joint {
992            break;
993        }
994        match &t.kind {
995            TokKind::Word(w) => out.push_str(w),
996            TokKind::Punct(c) if is_assign_key_char(*c) => out.push(*c),
997            _ => break,
998        }
999        p += 1;
1000    }
1001    if out.is_empty() || out.starts_with("--") {
1002        return None;
1003    }
1004    if !out
1005        .chars()
1006        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':'))
1007    {
1008        return None;
1009    }
1010    Some((out, p))
1011}
1012
1013/// Assignment boundary ahead (for value scanning): an argument start
1014/// holding `KEY=` (key run plus `=` at any gap).
1015/// Groups and strings are opaque: a `=` inside them never counts.
1016fn at_assign_boundary(toks: &[Tok], pos: usize) -> bool {
1017    match match_assign_key(toks, pos) {
1018        Some((_, end)) => matches!(toks.get(end).map(|t| &t.kind), Some(TokKind::Punct('='))),
1019        None => false,
1020    }
1021}
1022
1023/// Line breaks nested in a raw paren run fail like flat ones did
1024/// before parens stayed structural: splicing used to surface every
1025/// `;`/newline to `render_raw_text`'s reject arm. Brace contents are
1026/// skipped (templates and blocks render whole, then and now);
1027/// brackets nested in parens were spliced before, so their breaks
1028/// fail here too. Single owner for the rule; both raw fallbacks
1029/// (positional args, assignment values) ride `render_raw_text`.
1030fn reject_paren_line_breaks(inner: &[Tok], stmt: usize) -> Result<(), TokenError> {
1031    for tok in inner {
1032        match &tok.kind {
1033            TokKind::Newline | TokKind::Semicolon => {
1034                return Err(TokenError {
1035                    stmt,
1036                    msg: "unexpected line break in argument".to_string(),
1037                    line: tok.line,
1038                    col: tok.col,
1039                    kind: None,
1040                });
1041            }
1042            TokKind::Group {
1043                delim: GroupDelim::Brace,
1044                ..
1045            } => {}
1046            TokKind::Group { inner, .. } => reject_paren_line_breaks(inner, stmt)?,
1047            _ => {}
1048        }
1049    }
1050    Ok(())
1051}
1052
1053/// Raw-text render of one gap-run (or value span): words/puncts
1054/// literally (`$`+word literally, `$` elsewhere errors), strings by
1055/// their inner bytes, blocks lowered, groups spliced. Gaps collapse
1056/// to one space like `collapse_ws`; newlines/semicolons fail (the
1057/// grammar's raw span excludes them).
1058fn render_raw_text(toks: &[Tok], stmt: usize) -> Result<String, TokenError> {
1059    let mut out = String::new();
1060    let mut i = 0;
1061    while i < toks.len() {
1062        let tok = &toks[i];
1063        if !tok.joint && !out.is_empty() {
1064            out.push(' ');
1065        }
1066        match &tok.kind {
1067            TokKind::Word(w) => out.push_str(w),
1068            TokKind::Punct(c) => {
1069                if *c == '$' {
1070                    // Lone-`$` runs never reach here (expression
1071                    // extension claims them first and fails loudly).
1072                    // Elsewhere `$` renders literally (probed `a$(x)`
1073                    // reads raw) except before a brace group, where
1074                    // the grammar strands it (probed `K=${x}` fails).
1075                    let next = toks.get(i + 1);
1076                    let brace_next = next.is_some_and(|t| {
1077                        matches!(
1078                            &t.kind,
1079                            TokKind::Group {
1080                                delim: GroupDelim::Brace,
1081                                ..
1082                            }
1083                        )
1084                    });
1085                    if brace_next {
1086                        return Err(TokenError {
1087                            stmt,
1088                            msg: "unexpected `$` in argument".to_string(),
1089                            line: 0,
1090                            col: 0,
1091                            kind: None,
1092                        });
1093                    }
1094                    out.push('$');
1095                } else {
1096                    out.push(*c);
1097                }
1098            }
1099            // Standalone quotes strip (the caller handles single-tok
1100            // runs); glued quotes keep their marks, like the grammar's
1101            // mixed fragments (`>"a"` stays quoted, `"a"` strips).
1102            TokKind::Str { text: s, quote } => {
1103                let glued = tok.joint || toks.get(i + 1).is_some_and(|t| t.joint);
1104                if toks.len() > 1 && glued {
1105                    out.push(*quote);
1106                    out.push_str(s);
1107                    out.push(*quote);
1108                } else {
1109                    out.push_str(s);
1110                }
1111            }
1112            // Comments reproduce verbatim (templates keep comment
1113            // text like the atomic grammar span); gaps collapse
1114            // around them like other fragments per the documented
1115            // single-space normalization.
1116            TokKind::Comment(text) => out.push_str(text),
1117            TokKind::BlockStr(full) => {
1118                // Glued blocks keep their delimiters, like quotes.
1119                let glued = tok.joint || toks.get(i + 1).is_some_and(|t| t.joint);
1120                if toks.len() > 1 && glued {
1121                    out.push_str(full);
1122                } else {
1123                    out.push_str(&crate::command::lower_block_string(full));
1124                }
1125            }
1126            TokKind::Group {
1127                delim: GroupDelim::Brace,
1128                inner,
1129                open_joint,
1130                close_joint,
1131                ..
1132            } => out.push_str(&render_brace_run_text(inner, *open_joint, *close_joint)),
1133            TokKind::Group {
1134                delim: GroupDelim::Bracket,
1135                inner,
1136                open_joint,
1137                close_joint,
1138                ..
1139            } => out.push_str(&render_group('[', ']', inner, *open_joint, *close_joint)),
1140            TokKind::Group {
1141                delim: GroupDelim::Paren,
1142                inner,
1143                open_joint,
1144                close_joint,
1145                ..
1146            } => {
1147                // Parens stayed structural (call shapes need them), so
1148                // surface the breaks splicing used to expose: a `;` or
1149                // newline anywhere inside fails exactly like a flat one
1150                // did. Brace contents keep the verbatim whole-render
1151                // below; brackets nested in parens were spliced before,
1152                // so their breaks fail here too.
1153                reject_paren_line_breaks(inner, stmt)?;
1154                out.push_str(&render_group('(', ')', inner, *open_joint, *close_joint))
1155            }
1156            TokKind::Newline | TokKind::Semicolon => {
1157                return Err(TokenError {
1158                    stmt,
1159                    msg: "unexpected line break in argument".to_string(),
1160                    line: 0,
1161                    col: 0,
1162                    kind: None,
1163                });
1164            }
1165        }
1166        i += 1;
1167    }
1168    Ok(out)
1169}
1170
1171/// Build an assignment value `Arg` over a region that runs to the next
1172/// boundary or end. Single quoted/block strings keep `quoted=true`; a
1173/// region that is exactly one lone `$var`/keypath/`env:`/call shape
1174/// stays typed (calls resolve through the shared resolver, matching
1175/// `assign_expr`); everything else renders raw. A quoted unit followed
1176/// by joint content errors (probed: `K="a"b` fails), like the grammar.
1177/// Lone-shape failures stash into `deferred` and render raw: the
1178/// command's own lowering error (if any) takes precedence, and the
1179/// stashed call error surfaces only when lowering succeeds.
1180fn build_value_arg(
1181    region: &[Tok],
1182    stmt: usize,
1183    ctx: &ParseCtx,
1184    lone_ok: bool,
1185    deferred: &mut Option<TokenError>,
1186) -> Result<Arg, TokenError> {
1187    if region.is_empty() {
1188        return Ok(Arg::String(String::new(), false));
1189    }
1190    if region.len() == 1 {
1191        match &region[0].kind {
1192            TokKind::Str { text: s, .. } => return Ok(Arg::String(s.clone(), true)),
1193            TokKind::BlockStr(full) => {
1194                return Ok(Arg::String(crate::command::lower_block_string(full), true));
1195            }
1196            _ => {}
1197        }
1198    }
1199    if region.len() > 1
1200        && matches!(&region[0].kind, TokKind::Str { .. } | TokKind::BlockStr(_))
1201        && region[1].joint
1202    {
1203        return Err(TokenError {
1204            stmt,
1205            msg: "unexpected text after quoted value".to_string(),
1206            line: 0,
1207            col: 0,
1208            kind: None,
1209        });
1210    }
1211    // Single-quoted values mid-line (`K='a b'`): the string lexer only
1212    // opens `'` gapped, so these arrive as fragments; the grammar's
1213    // `quoted_string` admits them anywhere. Reassemble a region that
1214    // opens with `'` and closes at its end, stripping exactly like a
1215    // structural string (escapes intact for runtime, like `Str`).
1216    if matches!(&region[0].kind, TokKind::Punct('\''))
1217        && let Some(text) = try_squote_value(region)
1218    {
1219        return Ok(Arg::String(text, true));
1220    }
1221    // Lone typed values apply only at a true end/boundary, never
1222    // past a comment (the grammar's `!assign_expr_cont` guard).
1223    // Failures stash (see above) so command syntax owns precedence.
1224    if lone_ok {
1225        match try_lone_value_expr(region, stmt, ctx) {
1226            Ok(Some(expr)) => return Ok(expr),
1227            Ok(None) => {}
1228            Err(err) => {
1229                deferred.get_or_insert(err);
1230            }
1231        }
1232    }
1233    Ok(Arg::String(render_raw_text(region, stmt)?, false))
1234}
1235
1236/// Reassemble a single-quoted assignment value (`K='a b'`) from its
1237/// lexer fragments: the opener must close at the region end (a
1238/// trailing fragment falls back to raw text, which fails downstream
1239/// like the grammar). Inner gaps join with one space and nested
1240/// double quotes re-quote (the atomic span keeps them); `\'` escapes
1241/// pass through intact for runtime, like structural strings. `None`
1242/// on shape miss.
1243fn try_squote_value(region: &[Tok]) -> Option<String> {
1244    // Closing `'`: first unescaped quote past the opener.
1245    let mut close = None;
1246    let mut i = 1;
1247    while i < region.len() {
1248        match &region[i].kind {
1249            TokKind::Punct('\\') => i += 2,
1250            TokKind::Punct('\'') => {
1251                close = Some(i);
1252                break;
1253            }
1254            _ => i += 1,
1255        }
1256    }
1257    if close != Some(region.len() - 1) {
1258        return None;
1259    }
1260    let mut out = String::new();
1261    for tok in &region[1..region.len() - 1] {
1262        if !tok.joint && !out.is_empty() {
1263            out.push(' ');
1264        }
1265        match &tok.kind {
1266            TokKind::Word(w) => out.push_str(w),
1267            TokKind::Punct(c) => out.push(*c),
1268            TokKind::Semicolon => out.push(';'),
1269            // Nested double quotes keep their marks (the atomic span
1270            // never strips them); triple quotes pass through whole.
1271            TokKind::Str { text, quote } => {
1272                out.push(*quote);
1273                out.push_str(text);
1274                out.push(*quote);
1275            }
1276            TokKind::BlockStr(full) => out.push_str(full),
1277            // Groups and newlines never occur in value regions (the
1278            // splitter owns them); anything else breaks the shape.
1279            _ => return None,
1280        }
1281    }
1282    Some(out)
1283}
1284
1285/// Lone assignable shapes (`assign_expr` without continuation): `$var`,
1286/// key paths, `env:KEY`, and full-region calls (resolved). Anything
1287/// longer renders raw; the caller decides strictness.
1288fn try_lone_value_expr(
1289    region: &[Tok],
1290    stmt: usize,
1291    ctx: &ParseCtx,
1292) -> Result<Option<Arg>, TokenError> {
1293    // `$` shapes: exactly Punct+Word or dotted runs, all joint past
1294    // the first (the region starts at an argument start by construction).
1295    if matches!(region.first().map(|t| &t.kind), Some(TokKind::Punct('$'))) {
1296        let mut cur = Cursor::expr(region, stmt);
1297        cur.pos += 1;
1298        let base = match cur.next() {
1299            Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
1300                match &t.kind {
1301                    TokKind::Word(w) => w.clone(),
1302                    _ => unreachable!(),
1303                }
1304            }
1305            _ => return Ok(None),
1306        };
1307        let mut keys = Vec::new();
1308        loop {
1309            let dot = matches!(
1310                cur.toks.get(cur.pos).map(|t| &t.kind),
1311                Some(TokKind::Punct('.'))
1312            ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
1313            let seg = cur.toks.get(cur.pos + 1);
1314            let seg_ok = dot
1315                && matches!(seg.map(|t| &t.kind), Some(TokKind::Word(w)) if is_key_segment(w))
1316                && seg.is_some_and(|t| t.joint);
1317            if !seg_ok {
1318                break;
1319            }
1320            if let Some(TokKind::Word(w)) = seg.map(|t| &t.kind) {
1321                keys.push(w.clone());
1322            }
1323            cur.pos += 2;
1324        }
1325        if cur.pos != region.len() {
1326            return Ok(None);
1327        }
1328        return Ok(Some(Arg::Expr(if keys.is_empty() {
1329            Expr::Var(base)
1330        } else {
1331            Expr::KeyPath { base, keys }
1332        })));
1333    }
1334    // `env:KEY` read, gapless and exact.
1335    if region.len() == 3
1336        && matches!(&region[0].kind, TokKind::Word(w) if w == "env")
1337        && matches!(&region[1].kind, TokKind::Punct(':'))
1338        && region[1].joint
1339        && let TokKind::Word(k) = &region[2].kind
1340        && is_env_key(k)
1341        && region[2].joint
1342    {
1343        return Ok(Some(Arg::Expr(Expr::Env(k.clone()))));
1344    }
1345    // Full-region call: resolve and keep typed (canonical rendering
1346    // happens per command: verbatim for ENV/EXPAND, `K=`-joined text
1347    // elsewhere, all from the same `Arg::Expr`). Single owner for the
1348    // call tail; positional args share it (see `build_arg_tokens`).
1349    if let Some(arg) = try_lone_call_expr(region, stmt, ctx)? {
1350        return Ok(Some(arg));
1351    }
1352    Ok(None)
1353}
1354
1355/// Full-region call shape (`NAME(...)`, `MOD::NAME(...)`) over one
1356/// argument run: parse args through the shared call owner and resolve
1357/// through the shared resolver, so assignment values, RUN-exec items,
1358/// and generic positional args can never disagree on what a call is.
1359/// `None` on shape miss (caller renders raw); errors propagate, so a
1360/// misspelled callee fails loud instead of going literal.
1361fn try_lone_call_expr(
1362    region: &[Tok],
1363    stmt: usize,
1364    ctx: &ParseCtx,
1365) -> Result<Option<Arg>, TokenError> {
1366    if let Some((name, paren)) = call_shape_at(region, 0, false)
1367        && paren + 1 == region.len()
1368        && let TokKind::Group { inner, .. } = &region[paren].kind
1369    {
1370        let inner = inner.clone();
1371        let args = parse_call_args(&inner, stmt, ctx)?;
1372        if name == KEYWORD_INSPECT {
1373            let [arg] = args.as_slice() else {
1374                return Err(TokenError {
1375                    stmt,
1376                    msg: "INSPECT requires exactly one argument: INSPECT($var)".to_string(),
1377                    line: 0,
1378                    col: 0,
1379                    kind: None,
1380                });
1381            };
1382            if let Expr::Var(var) = arg {
1383                return Ok(Some(Arg::Expr(Expr::Inspect(var.clone()))));
1384            }
1385            return Err(TokenError {
1386                stmt,
1387                msg: format!("INSPECT requires a $variable argument, found {arg:?}"),
1388                line: 0,
1389                col: 0,
1390                kind: None,
1391            });
1392        }
1393        let qualified = resolve_name(ctx, stmt, &name)?;
1394        return Ok(Some(Arg::Expr(Expr::Call {
1395            name: qualified,
1396            args,
1397        })));
1398    }
1399    Ok(None)
1400}
1401
1402/// Expression extension for `$`/`env:`-led argument starts: parse a
1403/// full expression (operators reach across gaps exactly like the
1404/// grammar's inner `gap`s). Ending at a gap/end yields a typed single
1405/// group; ending mid-run falls back to raw text of the run (`$x=K`);
1406/// parse failure is fatal (every fragment alternative failed).
1407/// Returns the arg and tokens consumed.
1408fn try_expr_arg(
1409    toks: &[Tok],
1410    pos: usize,
1411    stmt: usize,
1412    ctx: &ParseCtx,
1413) -> Result<Option<(Arg, usize)>, TokenError> {
1414    let extend = matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('$')))
1415        || matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == "env");
1416    if !extend {
1417        return Ok(None);
1418    }
1419    // A bare `env` head only extends into a real `env:KEY` read (joint
1420    // `:`); dotted bare words (`env.txt`) stay raw strings like the
1421    // grammar's `unquoted_arg`, which precedes `expr`.
1422    if matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == "env")
1423        && !matches!(
1424            (
1425                toks.get(pos + 1).map(|t| &t.kind),
1426                toks.get(pos + 1).map(|t| t.joint)
1427            ),
1428            (Some(TokKind::Punct(':')), Some(true))
1429        )
1430    {
1431        return Ok(None);
1432    }
1433    let mut cur = Cursor::expr(&toks[pos..], stmt);
1434    let expr = parse_expr_or(&mut cur, ctx)?;
1435    let end = pos + cur.pos;
1436    // Mid-run stop (joint follower): the whole run renders raw
1437    // (`$x=K`, `$a$b`); the run always ends the fallback span here
1438    // because extension starts groups.
1439    if toks.get(end).is_some_and(|t| t.joint) {
1440        let mut run_end = end;
1441        while toks.get(run_end).is_some_and(|t| t.joint) {
1442            run_end += 1;
1443        }
1444        let text = render_raw_text(&toks[pos..run_end], stmt)?;
1445        return Ok(Some((Arg::String(text, false), run_end - pos)));
1446    }
1447    Ok(Some((Arg::Expr(expr), end - pos)))
1448}
1449
1450/// Render a brace group inside raw text (`{{..}}` templates and
1451/// mid-run `{..}` shapes): verbatim bytes, single-space-normalized
1452/// gaps. Run-start non-template braces never reach here (they parse
1453/// as maps/blocks in `build_arg_tokens`).
1454fn render_brace_run_text(inner: &[Tok], open_joint: bool, close_joint: bool) -> String {
1455    render_group('{', '}', inner, open_joint, close_joint)
1456}
1457
1458/// Inner bytes of a fully-quoted word (`"hi"`, `'a'`): the re-quoted
1459/// standalone strings spliced from groups strip exactly like
1460/// structural ones. Triple-quote pieces never qualify (block lowering
1461/// owns them); glued quotes (`['a`) never reach here as sole runs.
1462fn quoted_word_inner(w: &str) -> Option<String> {
1463    if w.len() >= 2 && !w.starts_with("\"\"\"") {
1464        let q = w.as_bytes()[0] as char;
1465        if (q == '"' || q == '\'') && w.ends_with(q) {
1466            return Some(w[1..w.len() - 1].to_string());
1467        }
1468    }
1469    None
1470}
1471
1472/// Build instruction tokens over generic args, mirroring
1473/// `assignment | argument` order at every argument start: assignments
1474/// merge across gaps to the next boundary, `$`/`env:`-led runs extend
1475/// as expressions, brace-led runs try templates then maps/blocks, and
1476/// everything else renders raw. Single quoted strings keep their flag.
1477fn build_arg_tokens(
1478    toks: &[Tok],
1479    stmt: usize,
1480    ctx: &ParseCtx,
1481) -> Result<(Vec<InsToken>, Option<TokenError>), TokenError> {
1482    // Splice bracket groups first: they read as ordinary
1483    // characters (whitespace splits inside them), with strings
1484    // re-quoted back to word text. Paren groups stay structural (see
1485    // `splice_arg_groups`); brace groups stay structural
1486    // (templates render whole; blocks parse as expressions).
1487    let flat = splice_arg_groups(toks, stmt)?;
1488    let mut deferred: Option<TokenError> = None;
1489    let mut out = Vec::new();
1490    let mut pos = 0;
1491    while pos < flat.len() {
1492        // 1. Assignment: key run plus `=` at any gap.
1493        if let Some((key, key_end)) = match_assign_key(&flat, pos)
1494            && let Some(tok) = flat.get(key_end)
1495            && matches!(&tok.kind, TokKind::Punct('='))
1496        {
1497            // Value runs to the next boundary, but raw text also
1498            // stops at `//` / `/*` (raw-text rule):
1499            // a line comment swallows the rest silently, a block
1500            // comment must be followed by nothing or a boundary
1501            // (anything else strands text and fails the line, like
1502            // the grammar). Lone typed values (`$x`, calls) apply
1503            // only at a true end/boundary, never past a comment
1504            // (the grammar's `!assign_expr_cont` guard).
1505            let mut vend = key_end + 1;
1506            let mut lone_ok = true;
1507            let mut failed: Option<String> = None;
1508            'scan: while vend < flat.len() {
1509                if !flat[vend].joint && at_assign_boundary(&flat, vend) {
1510                    break;
1511                }
1512                // Lexer comment markers end the raw span like `//`
1513                // (they run to end of line by construction).
1514                if matches!(&flat[vend].kind, TokKind::Comment(_)) {
1515                    lone_ok = false;
1516                    vend = flat.len();
1517                    break;
1518                }
1519                if matches!(&flat[vend].kind, TokKind::Punct('/')) && is_comment_open(&flat, vend) {
1520                    // Comments end the raw span: line comments eat
1521                    // the rest silently, block comments must be
1522                    // followed by nothing, a boundary, or more
1523                    // comments (stranded text fails the line, like
1524                    // the grammar).
1525                    lone_ok = false;
1526                    loop {
1527                        if vend >= flat.len()
1528                            || (!flat[vend].joint && at_assign_boundary(&flat, vend))
1529                        {
1530                            break 'scan;
1531                        }
1532                        if !matches!(&flat[vend].kind, TokKind::Punct('/'))
1533                            || !is_comment_open(&flat, vend)
1534                        {
1535                            failed = Some("unexpected text after assignment value".to_string());
1536                            break 'scan;
1537                        }
1538                        if matches!(
1539                            flat.get(vend + 1).map(|t| &t.kind),
1540                            Some(TokKind::Punct('/'))
1541                        ) {
1542                            vend = flat.len();
1543                            break 'scan;
1544                        }
1545                        match skip_inline_comment(&flat, vend) {
1546                            None => {
1547                                failed = Some("unclosed block comment".to_string());
1548                                break 'scan;
1549                            }
1550                            Some(past) => vend = past,
1551                        }
1552                    }
1553                }
1554                vend += 1;
1555            }
1556            if let Some(msg) = failed {
1557                return Err(TokenError {
1558                    stmt,
1559                    msg,
1560                    line: 0,
1561                    col: 0,
1562                    kind: None,
1563                });
1564            }
1565            let value =
1566                build_value_arg(&flat[key_end + 1..vend], stmt, ctx, lone_ok, &mut deferred)?;
1567            out.push(InsToken::Assign(key, value));
1568            pos = vend;
1569            continue;
1570        }
1571        // 2. Brace-led run: template text, else map/block expression.
1572        if matches!(
1573            flat.get(pos).map(|t| &t.kind),
1574            Some(TokKind::Group {
1575                delim: GroupDelim::Brace,
1576                ..
1577            })
1578        ) {
1579            let mut run_end = pos + 1;
1580            while flat.get(run_end).is_some_and(|t| t.joint) {
1581                run_end += 1;
1582            }
1583            let run = &flat[pos..run_end];
1584            let is_template = is_template_brace(&run[0]);
1585            if is_template {
1586                out.push(InsToken::Pos(Arg::String(
1587                    render_raw_text(run, stmt)?,
1588                    false,
1589                )));
1590            } else {
1591                let inner = match &run[0].kind {
1592                    TokKind::Group { inner, .. } => inner.clone(),
1593                    _ => unreachable!(),
1594                };
1595                // Map success alone stays typed; map success with a
1596                // joint tail renders raw (`{k:1}x`, like the grammar's
1597                // mixed fragments); map failure defers/errors exactly
1598                // like the expression path.
1599                match parse_map_or_block(&inner, stmt, ctx) {
1600                    Ok(expr) if run.len() == 1 => {
1601                        out.push(InsToken::Pos(Arg::Expr(expr)));
1602                    }
1603                    Ok(_) => out.push(InsToken::Pos(Arg::String(
1604                        render_raw_text(run, stmt)?,
1605                        false,
1606                    ))),
1607                    Err(e) => return Err(e),
1608                }
1609            }
1610            pos = run_end;
1611            continue;
1612        }
1613        // 3. `$`/`env:`-led expression extension.
1614        if let Some((arg, used)) = try_expr_arg(&flat, pos, stmt, ctx)? {
1615            // A lone expression group stays typed; the fallback
1616            // already rendered text above.
1617            out.push(InsToken::Pos(arg));
1618            pos += used;
1619            continue;
1620        }
1621        // 4. Raw text run to the next gap.
1622        let mut run_end = pos + 1;
1623        while flat.get(run_end).is_some_and(|t| t.joint) {
1624            run_end += 1;
1625        }
1626        let run = &flat[pos..run_end];
1627        // Slash-pair-led runs (`/*c*/`; `//` arrives as `Comment`
1628        // toks) parse as expression fragments (typed when single,
1629        // glued verbatim otherwise).
1630        if is_slash_run(run) {
1631            out.push(InsToken::Pos(parse_slash_run(run, stmt, ctx)?));
1632            pos = run_end;
1633            continue;
1634        }
1635        // Trailing `Comment` (`//` to end of line) glues as a
1636        // literal fragment (typed when alone, verbatim otherwise),
1637        // exactly like the grammar's expression fragments.
1638        if let Some(TokKind::Comment(text)) = run.last().map(|t| &t.kind) {
1639            if run.len() == 1 {
1640                out.push(InsToken::Pos(Arg::Expr(Expr::Literal(Value::string(
1641                    text.clone(),
1642                )))));
1643            } else {
1644                let mut bytes = render_raw_text(&run[..run.len() - 1], stmt)?;
1645                bytes.push_str(text);
1646                out.push(InsToken::Pos(Arg::String(bytes, false)));
1647            }
1648            pos = run_end;
1649            continue;
1650        }
1651        if run.len() == 1 {
1652            match &run[0].kind {
1653                TokKind::Str { text: s, .. } => {
1654                    out.push(InsToken::Pos(Arg::String(s.clone(), true)));
1655                    pos = run_end;
1656                    continue;
1657                }
1658                TokKind::BlockStr(full) => {
1659                    out.push(InsToken::Pos(Arg::String(
1660                        crate::command::lower_block_string(full),
1661                        true,
1662                    )));
1663                    pos = run_end;
1664                    continue;
1665                }
1666                // Re-quoted standalone strings (spliced from groups)
1667                // strip exactly like structural ones (`["hi"]` gives
1668                // `hi`); glued quotes stay literal (`['a` keeps its
1669                // mark). Triple-quote pieces never qualify.
1670                TokKind::Word(w) if quoted_word_inner(w).is_some() => {
1671                    out.push(InsToken::Pos(Arg::String(
1672                        quoted_word_inner(w).unwrap(),
1673                        true,
1674                    )));
1675                    pos = run_end;
1676                    continue;
1677                }
1678                _ => {}
1679            }
1680        }
1681        // Bare full-region calls stay typed like assignment values and
1682        // RUN-exec items (same owner, `try_lone_call_expr`), so every
1683        // argument position evaluates them instead of one silently
1684        // appending the source text. Failures stash: the command's own
1685        // lowering error (if any) takes precedence, and the stashed
1686        // call error surfaces only when lowering succeeds.
1687        match try_lone_call_expr(run, stmt, ctx) {
1688            Ok(Some(arg)) => {
1689                out.push(InsToken::Pos(arg));
1690                pos = run_end;
1691                continue;
1692            }
1693            Ok(None) => {}
1694            Err(err) => {
1695                deferred.get_or_insert(err);
1696            }
1697        }
1698        out.push(InsToken::Pos(Arg::String(
1699            render_raw_text(run, stmt)?,
1700            false,
1701        )));
1702        pos = run_end;
1703    }
1704    Ok((out, deferred))
1705}
1706
1707/// A raw run starting with `//` or `/*` (a slash-pair: `/` plus a
1708/// joint `/` or `*`) parses as expression fragments: both route to
1709/// `expr` there (so `//c` types as a literal and `/*c*/` as math). A single
1710/// fully-consuming expression stays typed; anything longer glues to
1711/// verbatim text exactly like the grammar's mixed fragments (byte
1712/// for byte, since joint runs admit no span gaps). An unparseable
1713/// unterminated block open (`/*` with no `*/` in the run) reads
1714/// literally like the old backend (`ECHO /*`, `[a /* c]`); a
1715/// terminated span keeps the loud failure.
1716fn parse_slash_run(run: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Arg, TokenError> {
1717    let mut cur = Cursor::expr(run, stmt);
1718    match parse_expr_checked(&mut cur, ctx) {
1719        Ok(expr) if cur.done() => Ok(Arg::Expr(expr)),
1720        Ok(_) => Ok(Arg::String(render_raw_text(run, stmt)?, false)),
1721        Err(_) if !run_has_block_close(run) => Ok(Arg::String(render_raw_text(run, stmt)?, false)),
1722        Err(e) => Err(e),
1723    }
1724}
1725
1726/// True when the run holds a `*/` close pair (`*` plus a joint `/`),
1727/// mirroring [`skip_inline_comment`]'s terminator: only unterminated
1728/// block opens read literally.
1729fn run_has_block_close(run: &[Tok]) -> bool {
1730    run.windows(2).any(|w| {
1731        matches!(&w[0].kind, TokKind::Punct('*'))
1732            && matches!(&w[1].kind, TokKind::Punct('/'))
1733            && w[1].joint
1734    })
1735}
1736
1737/// True when a raw run opens with a slash-pair (`/` plus a joint
1738/// `/` or `*`), routing it to expression fragments (see
1739/// [`parse_slash_run`]). A lone `/` (`/a`, `/`) stays raw text.
1740fn is_slash_run(run: &[Tok]) -> bool {
1741    matches!(run.first().map(|t| &t.kind), Some(TokKind::Punct('/')))
1742        && matches!(
1743            run.get(1).map(|t| (&t.kind, t.joint)),
1744            Some((TokKind::Punct('/'), true)) | Some((TokKind::Punct('*'), true))
1745        )
1746}
1747
1748/// Lower generic args through the shared cores: `ENV`/`EXPAND` bypass
1749/// the injected dispatcher; everything else
1750/// canonicalizes assignments and calls it.
1751fn lower_generic_args(
1752    name: &str,
1753    tokens: Vec<InsToken>,
1754    stmt: usize,
1755    ctx: &ParseCtx,
1756) -> Result<StepKind, TokenError> {
1757    if name == KEYWORD_ENV {
1758        return lower_env_tokens(&lowering_ctx(stmt), tokens).map_err(|e| TokenError {
1759            stmt,
1760            msg: e.to_string(),
1761            line: 0,
1762            col: 0,
1763            kind: None,
1764        });
1765    }
1766    if name == KEYWORD_EXPAND {
1767        return lower_expand_tokens(&lowering_ctx(stmt), tokens).map_err(|e| TokenError {
1768            stmt,
1769            msg: e.to_string(),
1770            line: 0,
1771            col: 0,
1772            kind: None,
1773        });
1774    }
1775    let args = tokens
1776        .into_iter()
1777        .map(|token| match token {
1778            InsToken::Pos(arg) => arg,
1779            InsToken::Assign(key, value) => canonical_assignment_arg(&key, &value),
1780        })
1781        .collect();
1782    (ctx.lower)(name, args).map_err(|e| lower_err(stmt, e))
1783}
1784
1785/// Render a bracket/paren/brace group back to source text for raw-text
1786/// positions (in-body groups are args, template braces render whole).
1787/// Fragments join with a space on gaps and glue on `joint`, so both
1788/// lexers render the same source identically; quote styles round-trip
1789/// exactly. Known normalization (documented, not silent): multi-space
1790/// gaps collapse to one.
1791fn render_group(
1792    open: char,
1793    close: char,
1794    inner: &[Tok],
1795    open_joint: bool,
1796    close_joint: bool,
1797) -> String {
1798    let mut out = String::from(open);
1799    if !open_joint && !inner.is_empty() {
1800        out.push(' ');
1801    }
1802    let mut first = true;
1803    for tok in inner {
1804        match &tok.kind {
1805            TokKind::Newline => out.push('\n'),
1806            TokKind::Semicolon => out.push(';'),
1807            // Comments reproduce verbatim (templates keep comment
1808            // text like the atomic grammar span); like newlines they
1809            // carry their own separation, never a synthetic space.
1810            TokKind::Comment(text) => out.push_str(text),
1811            _ => {
1812                if !first && !tok.joint {
1813                    out.push(' ');
1814                }
1815                match &tok.kind {
1816                    TokKind::Word(w) => out.push_str(w),
1817                    TokKind::Punct(c) => out.push(*c),
1818                    TokKind::Str { text, quote } => {
1819                        out.push(*quote);
1820                        out.push_str(text);
1821                        out.push(*quote);
1822                    }
1823                    TokKind::BlockStr(full) => out.push_str(full),
1824                    TokKind::Group {
1825                        delim: GroupDelim::Bracket,
1826                        inner,
1827                        open_joint,
1828                        close_joint,
1829                        ..
1830                    } => out.push_str(&render_group('[', ']', inner, *open_joint, *close_joint)),
1831                    TokKind::Group {
1832                        delim: GroupDelim::Paren,
1833                        inner,
1834                        open_joint,
1835                        close_joint,
1836                        ..
1837                    } => out.push_str(&render_group('(', ')', inner, *open_joint, *close_joint)),
1838                    TokKind::Group {
1839                        delim: GroupDelim::Brace,
1840                        inner,
1841                        open_joint,
1842                        close_joint,
1843                        ..
1844                    } => out.push_str(&render_group('{', '}', inner, *open_joint, *close_joint)),
1845                    // Comments reproduce verbatim (nested groups keep
1846                    // comment text like the atomic grammar span).
1847                    TokKind::Comment(text) => out.push_str(text),
1848                    TokKind::Newline | TokKind::Semicolon => unreachable!(),
1849                }
1850            }
1851        }
1852        first = false;
1853    }
1854    if !close_joint && !inner.is_empty() {
1855        out.push(' ');
1856    }
1857    out.push(close);
1858    out
1859}
1860
1861/// Positional cursor over guard/group token slices. Newlines skip
1862/// freely between tokens (`ws` admits linebreaks in the grammar);
1863/// bare key/value runs never cross them (the grammar excludes
1864/// linebreaks there), so runs read raw.
1865///
1866/// Expression parsing reuses this cursor with `nl_skip = false`:
1867/// expressions are single-line (`gap`, never `gap_nl`, between
1868/// operands), so a newline terminates instead of vanishing. Newlines
1869/// inside group inners (call args, lists, maps) skip via explicit
1870/// `skip_newlines` calls at the grammar's `gap_nl` junctures.
1871struct Cursor<'t> {
1872    toks: &'t [Tok],
1873    pos: usize,
1874    stmt: usize,
1875    nl_skip: bool,
1876}
1877
1878impl<'t> Cursor<'t> {
1879    fn new(toks: &'t [Tok], stmt: usize) -> Self {
1880        Self {
1881            toks,
1882            pos: 0,
1883            stmt,
1884            nl_skip: true,
1885        }
1886    }
1887
1888    /// Expression-mode cursor: newlines stop, never skip.
1889    fn expr(toks: &'t [Tok], stmt: usize) -> Self {
1890        Self {
1891            toks,
1892            pos: 0,
1893            stmt,
1894            nl_skip: false,
1895        }
1896    }
1897
1898    fn err(&self, msg: impl Into<String>) -> TokenError {
1899        TokenError {
1900            stmt: self.stmt,
1901            line: 0,
1902            col: 0,
1903            msg: msg.into(),
1904            kind: None,
1905        }
1906    }
1907
1908    fn skip_newlines(&mut self) {
1909        while matches!(
1910            self.toks.get(self.pos).map(|t| &t.kind),
1911            Some(TokKind::Newline)
1912        ) {
1913            self.pos += 1;
1914        }
1915    }
1916
1917    fn peek(&mut self) -> Option<&'t Tok> {
1918        if self.nl_skip {
1919            self.skip_newlines();
1920        }
1921        self.toks.get(self.pos)
1922    }
1923
1924    fn next(&mut self) -> Option<&'t Tok> {
1925        if self.nl_skip {
1926            self.skip_newlines();
1927        }
1928        let t = self.toks.get(self.pos)?;
1929        self.pos += 1;
1930        Some(t)
1931    }
1932
1933    fn done(&mut self) -> bool {
1934        if self.nl_skip {
1935            self.skip_newlines();
1936        }
1937        self.pos >= self.toks.len()
1938    }
1939
1940    fn eat_punct(&mut self, c: char) -> bool {
1941        if self.nl_skip {
1942            self.skip_newlines();
1943        }
1944        match self.peek() {
1945            Some(t) if matches!(&t.kind, TokKind::Punct(p) if *p == c) => {
1946                self.pos += 1;
1947                true
1948            }
1949            _ => false,
1950        }
1951    }
1952
1953    /// Skip one gap's worth of comments (`gap`: `//`-to-newline,
1954    /// balanced `/* */` even across newlines, `#`-to-newline —
1955    /// never a standalone newline, which ends single-line
1956    /// expressions. Greedy gap before operators and operands; whitespace itself is
1957    /// already invisible in the token stream.
1958    fn skip_gap(&mut self) {
1959        loop {
1960            match self.toks.get(self.pos).map(|t| &t.kind) {
1961                Some(TokKind::Comment(_)) => {
1962                    self.pos += 1;
1963                }
1964                Some(TokKind::Punct('/')) if is_comment_open(self.toks, self.pos) => {
1965                    match skip_inline_comment(self.toks, self.pos) {
1966                        Some(next) => self.pos = next,
1967                        // Unclosed block comments fail the gap (and
1968                        // the enclosing rule) like the grammar.
1969                        None => break,
1970                    }
1971                }
1972                Some(TokKind::Punct('#')) => {
1973                    while self.pos < self.toks.len()
1974                        && !matches!(&self.toks[self.pos].kind, TokKind::Newline)
1975                    {
1976                        self.pos += 1;
1977                    }
1978                }
1979                _ => break,
1980            }
1981        }
1982    }
1983
1984    /// Skip gap comments plus standalone newlines (`gap_nl`: call
1985    /// args, list items, maps, parenthesized expressions).
1986    fn skip_gap_nl(&mut self) {
1987        loop {
1988            match self.toks.get(self.pos).map(|t| &t.kind) {
1989                Some(TokKind::Newline) => {
1990                    self.pos += 1;
1991                }
1992                _ => {
1993                    let before = self.pos;
1994                    self.skip_gap();
1995                    if self.pos == before {
1996                        break;
1997                    }
1998                }
1999            }
2000        }
2001    }
2002
2003    /// Consume the parenthesized group following a call word (`not`,
2004    /// `any`, `all`, `eq`, `ne`), ignoring gap width exactly like the
2005    /// grammar's implicit whitespace.
2006    fn eat_paren_group(&mut self) -> Option<Vec<Tok>> {
2007        match self.peek() {
2008            Some(t) => match &t.kind {
2009                TokKind::Group {
2010                    delim: GroupDelim::Paren,
2011                    inner,
2012                    ..
2013                } => {
2014                    let inner = inner.clone();
2015                    self.pos += 1;
2016                    Some(inner)
2017                }
2018                _ => None,
2019            },
2020            None => None,
2021        }
2022    }
2023}
2024
2025/// Split a flat token slice on top-level commas (nesting lives inside
2026/// atomic groups, so a flat scan is exact).
2027fn split_top_commas(toks: &[Tok]) -> Vec<&[Tok]> {
2028    let mut parts = Vec::new();
2029    let mut start = 0;
2030    for (i, t) in toks.iter().enumerate() {
2031        if matches!(&t.kind, TokKind::Punct(',')) {
2032            parts.push(&toks[start..i]);
2033            start = i + 1;
2034        }
2035    }
2036    parts.push(&toks[start..]);
2037    parts
2038}
2039
2040/// Punctuation admissible inside bare guard key runs: everything but
2041/// the terminators the parser enforces separately. `;` arrives as its
2042/// own token kind; the key charset admits it, so runs accept it literally.
2043fn key_char(c: char) -> bool {
2044    !matches!(c, ':' | '=' | '!' | ',' | '|' | '(' | ')' | ']' | '$')
2045}
2046
2047/// Consume a joint run of words/punctuation as one bare key or value.
2048/// Gaps end the run; terminators and groups end or fail it per `extra`.
2049fn bare_run(cur: &mut Cursor, extra: fn(char) -> bool, what: &str) -> Result<String, TokenError> {
2050    let mut out = String::new();
2051    loop {
2052        let tok = match cur.toks.get(cur.pos) {
2053            Some(t) if matches!(&t.kind, TokKind::Newline) => break,
2054            Some(t) => t,
2055            None => break,
2056        };
2057        // First element may follow a gap; continuations must be gapless.
2058        if !out.is_empty() && !tok.joint {
2059            break;
2060        }
2061        match &tok.kind {
2062            TokKind::Word(w) => out.push_str(w),
2063            TokKind::Punct(c) if key_char(*c) && extra(*c) => out.push(*c),
2064            TokKind::Semicolon if extra(';') => out.push(';'),
2065            _ => break,
2066        }
2067        cur.pos += 1;
2068    }
2069    if out.is_empty() {
2070        return Err(cur.err(format!("missing {what}")));
2071    }
2072    Ok(out)
2073}
2074
2075/// The `guard_term` negative lookahead: a complete term followed by
2076/// `(`, `:`, `=`, or `!` is malformed, never a longer form.
2077fn check_term_end(cur: &mut Cursor) -> Result<(), TokenError> {
2078    cur.skip_newlines();
2079    match cur.toks.get(cur.pos) {
2080        Some(t) => match &t.kind {
2081            TokKind::Group {
2082                delim: GroupDelim::Paren,
2083                ..
2084            } => Err(cur.err("unexpected `(` after guard term")),
2085            TokKind::Punct(c) if matches!(c, ':' | '=' | '!') => {
2086                Err(cur.err(format!("unexpected `{c}` after guard term")))
2087            }
2088            _ => Ok(()),
2089        },
2090        None => Ok(()),
2091    }
2092}
2093
2094fn os_guard(value: &str) -> GuardExpr {
2095    GuardExpr::Predicate(Guard::Attr {
2096        ns: Ns::Os,
2097        key: None,
2098        val: Some(value.to_string()),
2099    })
2100}
2101
2102/// Namespace validation for guard predicates with closed domains
2103/// (`family`, `os`, `arch`); open namespaces pass through.
2104fn ns_guard(ns: &str, val: &str, cur: &Cursor) -> Result<GuardExpr, TokenError> {
2105    match ns {
2106        "family" => match val {
2107            "unix" => Ok(GuardExpr::or(vec![os_guard("macos"), os_guard("linux")])),
2108            "windows" => Ok(os_guard("windows")),
2109            _ => Err(cur.err(format!(
2110                "unknown family '{val}'; known values: unix, windows"
2111            ))),
2112        },
2113        "os" => match val {
2114            "macos" | "linux" | "windows" => Ok(os_guard(val)),
2115            _ => Err(cur.err(format!(
2116                "unknown os '{val}'; known values: macos, linux, windows"
2117            ))),
2118        },
2119        "arch" => {
2120            if crate::ARCH_VALUES.contains(&val) {
2121                Ok(GuardExpr::Predicate(Guard::Attr {
2122                    ns: Ns::Arch,
2123                    key: None,
2124                    val: Some(val.to_string()),
2125                }))
2126            } else {
2127                Err(cur.err(format!(
2128                    "unknown arch '{val}'; known values: {}",
2129                    crate::ARCH_VALUES.join(", ")
2130                )))
2131            }
2132        }
2133        _ => Err(cur.err(format!(
2134            "unknown guard namespace '{ns}'; known namespaces: family, os, arch, env, bool"
2135        ))),
2136    }
2137}
2138
2139fn parse_guard_term(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2140    let tok = cur
2141        .next()
2142        .ok_or_else(|| cur.err("missing guard predicate"))?;
2143    // A `!` prefix is never negation in guards (only `not(...)` negates).
2144    if matches!(&tok.kind, TokKind::Punct('!')) {
2145        return Err(cur.err("unexpected `!` in guard; negation uses `not(...)`"));
2146    }
2147    let word = match &tok.kind {
2148        TokKind::Word(w) => w.clone(),
2149        _ => return Err(cur.err("missing guard predicate")),
2150    };
2151    // `__OXDOCK_INJECT_N__` interpolation placeholder: env-key shape.
2152    if let Some(rest) = word.strip_prefix(INJECT_PREFIX) {
2153        if !rest.is_empty()
2154            && rest
2155                .strip_suffix(INJECT_SUFFIX)
2156                .is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()))
2157        {
2158            return Ok(GuardExpr::Predicate(Guard::Attr {
2159                ns: Ns::Env,
2160                key: Some(word),
2161                val: None,
2162            }));
2163        }
2164        return Err(cur.err("missing guard predicate"));
2165    }
2166    match word.as_str() {
2167        "eq" | "ne" => {
2168            let inner = cur
2169                .eat_paren_group()
2170                .ok_or_else(|| cur.err(format!("`{word}` requires `(env:KEY, value)`")))?;
2171            let mut arg = Cursor::new(&inner, cur.stmt);
2172            if arg.next().map(|t| &t.kind) != Some(&TokKind::Word("env".to_string())) {
2173                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2174            }
2175            if !arg.eat_punct(':') {
2176                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2177            }
2178            let key = bare_run(&mut arg, |_| true, "guard key")?;
2179            if !arg.eat_punct(',') {
2180                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2181            }
2182            arg.skip_newlines();
2183            let value = match arg.next() {
2184                Some(t) => match &t.kind {
2185                    TokKind::Str { text, .. } => text.clone(),
2186                    TokKind::BlockStr(full) => crate::command::lower_block_string(full),
2187                    _ => {
2188                        // Bare value: runs to the region end (commas and
2189                        // groups terminate it with an error, matching the
2190                        // bare-value exclusions).
2191                        arg.pos -= 1;
2192                        value_run(&mut arg)?
2193                    }
2194                },
2195                None => return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`"))),
2196            };
2197            if !arg.done() {
2198                return Err(arg.err(format!("unexpected text after `{word}` value")));
2199            }
2200            let pred = GuardExpr::Predicate(Guard::Attr {
2201                ns: Ns::Env,
2202                key: Some(key),
2203                val: Some(value),
2204            });
2205            if word == "ne" {
2206                Ok(GuardExpr::Not(Box::new(pred)))
2207            } else {
2208                Ok(pred)
2209            }
2210        }
2211        "bool" => {
2212            if !cur.eat_punct(':') {
2213                return Err(cur.err("`bool` requires `:value`"));
2214            }
2215            let val = bare_run(cur, |_| true, "bool value")?;
2216            check_term_end(cur)?;
2217            Ok(GuardExpr::Predicate(Guard::Attr {
2218                ns: Ns::Bool,
2219                key: None,
2220                val: Some(val),
2221            }))
2222        }
2223        "env" => {
2224            if !cur.eat_punct(':') {
2225                return Err(cur.err("`env` requires `:KEY`"));
2226            }
2227            let key = bare_run(cur, |_| true, "guard key")?;
2228            check_term_end(cur)?;
2229            Ok(GuardExpr::Predicate(Guard::Attr {
2230                ns: Ns::Env,
2231                key: Some(key),
2232                val: None,
2233            }))
2234        }
2235        _ => {
2236            if !cur.eat_punct(':') {
2237                return Err(cur.err("missing guard predicate"));
2238            }
2239            let val = bare_run(cur, |_| true, "guard value")?;
2240            check_term_end(cur)?;
2241            ns_guard(&word, &val, cur)
2242        }
2243    }
2244}
2245
2246/// Bare `eq`/`ne` value run: key charset plus `:`/`=`/`!` (the grammar
2247/// admits them in values, never in keys), with nested groups rendered
2248/// for the pathological `(`-in-value shape. `$`, `|`, `,` terminate
2249/// with an error downstream.
2250/// Bare `eq`/`ne` value with atomic bare-value semantics:
2251/// everything except `, | ) ] $`, linebreaks, and comment opens —
2252/// gaps included (joined with one space; the token stream cannot
2253/// preserve gap width). Quotes ride literally mid-run (the atomic
2254/// span keeps them); a *leading* quote never reaches here (the
2255/// caller strips it as the `quoted_string` alternative, which then
2256/// requires end-of-region like the grammar's committed choice).
2257fn value_run(arg: &mut Cursor) -> Result<String, TokenError> {
2258    let mut out = String::new();
2259    while let Some(tok) = arg.toks.get(arg.pos) {
2260        // Terminators: the grammar's negative-lookahead set.
2261        match &tok.kind {
2262            TokKind::Newline | TokKind::Comment(_) => break,
2263            TokKind::Punct(',')
2264            | TokKind::Punct('|')
2265            | TokKind::Punct(']')
2266            | TokKind::Punct(')') => break,
2267            TokKind::Punct('$') => break,
2268            TokKind::Punct('/') if is_comment_open(arg.toks, arg.pos) => break,
2269            TokKind::Group { .. } => break,
2270            _ => {}
2271        }
2272        if !out.is_empty() && !tok.joint {
2273            out.push(' ');
2274        }
2275        match &tok.kind {
2276            TokKind::Word(w) => out.push_str(w),
2277            TokKind::Punct(c) => out.push(*c),
2278            TokKind::Semicolon => out.push(';'),
2279            // Mid-run quotes keep their marks, like the atomic span.
2280            TokKind::Str { text, quote } => {
2281                out.push(*quote);
2282                out.push_str(text);
2283                out.push(*quote);
2284            }
2285            TokKind::BlockStr(full) => out.push_str(full),
2286            _ => break,
2287        }
2288        arg.pos += 1;
2289    }
2290    if out.is_empty() {
2291        return Err(arg.err("missing guard value"));
2292    }
2293    Ok(out)
2294}
2295
2296/// True when the cursor sits on `name` followed (over newlines,
2297/// like the grammar's implicit whitespace) by a paren group.
2298fn at_call(cur: &Cursor, name: &str) -> bool {
2299    let mut pos = cur.pos;
2300    // Leading newlines skip (the grammar's implicit whitespace gaps
2301    // multi-line guards, e.g. `[\nnot(env:K)\n]`).
2302    while matches!(cur.toks.get(pos).map(|t| &t.kind), Some(TokKind::Newline)) {
2303        pos += 1;
2304    }
2305    match cur.toks.get(pos) {
2306        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == name) => pos += 1,
2307        _ => return false,
2308    }
2309    while matches!(cur.toks.get(pos).map(|t| &t.kind), Some(TokKind::Newline)) {
2310        pos += 1;
2311    }
2312    matches!(
2313        cur.toks.get(pos).map(|t| &t.kind),
2314        Some(TokKind::Group {
2315            delim: GroupDelim::Paren,
2316            ..
2317        })
2318    )
2319}
2320
2321fn parse_guard_primary(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2322    // Call shapes dispatch on word + paren group regardless of gap
2323    // width (the grammar's implicit whitespace); anything else is a term.
2324    for name in ["not", "any", "all"] {
2325        if at_call(cur, name) {
2326            cur.next();
2327            let inner = cur
2328                .eat_paren_group()
2329                .ok_or_else(|| cur.err("unreachable"))?;
2330            let parts = split_top_commas(&inner);
2331            match name {
2332                "not" => {
2333                    if parts.len() != 1 {
2334                        return Err(cur.err("`not` takes exactly one guard expression"));
2335                    }
2336                    let mut sub = Cursor::new(parts[0], cur.stmt);
2337                    let expr = parse_guard_seq(&mut sub)?;
2338                    if !sub.done() {
2339                        return Err(sub.err("unexpected text in `not`"));
2340                    }
2341                    return Ok(GuardExpr::Not(Box::new(expr)));
2342                }
2343                "any" => {
2344                    if parts.len() < 2 {
2345                        return Err(cur.err("any(...) requires at least two guard expressions"));
2346                    }
2347                    let mut exprs = Vec::new();
2348                    for part in parts {
2349                        let mut sub = Cursor::new(part, cur.stmt);
2350                        exprs.push(parse_guard_seq(&mut sub)?);
2351                        if !sub.done() {
2352                            return Err(sub.err("unexpected text in `any`"));
2353                        }
2354                    }
2355                    return Ok(GuardExpr::or(exprs));
2356                }
2357                _ => {
2358                    if parts.is_empty() {
2359                        return Err(cur.err("all(...) requires at least one guard expression"));
2360                    }
2361                    let mut exprs = Vec::new();
2362                    for part in parts {
2363                        if part.iter().all(|t| matches!(&t.kind, TokKind::Newline)) {
2364                            return Err(cur.err("all(...) requires at least one guard expression"));
2365                        }
2366                        let mut sub = Cursor::new(part, cur.stmt);
2367                        exprs.push(parse_guard_seq(&mut sub)?);
2368                        if !sub.done() {
2369                            return Err(sub.err("unexpected text in `all`"));
2370                        }
2371                    }
2372                    return Ok(GuardExpr::all(exprs));
2373                }
2374            }
2375        }
2376    }
2377    match cur.peek() {
2378        Some(t) => match &t.kind {
2379            TokKind::Group {
2380                delim: GroupDelim::Paren,
2381                inner,
2382                ..
2383            } => {
2384                let inner = inner.clone();
2385                cur.next();
2386                let mut sub = Cursor::new(&inner, cur.stmt);
2387                let expr = parse_guard_seq(&mut sub)?;
2388                if !sub.done() {
2389                    return Err(sub.err("unexpected text in guard group"));
2390                }
2391                Ok(expr)
2392            }
2393            _ => parse_guard_term(cur),
2394        },
2395        None => Err(cur.err("missing guard expression")),
2396    }
2397}
2398
2399fn parse_guard_seq(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2400    let first = parse_guard_primary(cur)?;
2401    let mut rest = vec![first];
2402    while cur.eat_punct(',') {
2403        rest.push(parse_guard_primary(cur)?);
2404    }
2405    if rest.len() == 1 {
2406        Ok(rest.pop().unwrap())
2407    } else {
2408        Ok(GuardExpr::all(rest))
2409    }
2410}
2411
2412/// Parse one bracket group's contents as a guard expression.
2413fn parse_guard_inner(inner: &[Tok], stmt: usize) -> Result<GuardExpr, TokenError> {
2414    let mut cur = Cursor::new(inner, stmt);
2415    let expr = parse_guard_seq(&mut cur)?;
2416    if !cur.done() {
2417        return Err(cur.err("unexpected text in guard"));
2418    }
2419    Ok(expr)
2420}
2421
2422/// Parse one standalone guard expression from lexed tokens (the
2423/// `parse_guard_expr_str` entry point): a bare `guard_seq` with full
2424/// consumption.
2425pub(crate) fn parse_single_guard(toks: &[Tok], stmt: usize) -> Result<GuardExpr, TokenError> {
2426    let mut cur = Cursor::new(toks, stmt);
2427    if cur.done() {
2428        return Err(cur.err("empty guard"));
2429    }
2430    let expr = parse_guard_seq(&mut cur)?;
2431    if !cur.done() {
2432        return Err(cur.err("unexpected text in guard"));
2433    }
2434    Ok(expr)
2435}
2436
2437/// Combine a statement's leading guard groups: stacked brackets `All`
2438/// together, a single bracket stands alone.
2439fn parse_guard_groups(guard: &[Tok], stmt: usize) -> Result<Option<GuardExpr>, TokenError> {
2440    let mut acc: Option<GuardExpr> = None;
2441    for tok in guard {
2442        let inner = match &tok.kind {
2443            TokKind::Group {
2444                delim: GroupDelim::Bracket,
2445                inner,
2446                ..
2447            } => inner.clone(),
2448            _ => {
2449                return Err(TokenError {
2450                    stmt,
2451                    msg: "unsupported non-bracket guard".to_string(),
2452                    line: 0,
2453                    col: 0,
2454                    kind: None,
2455                });
2456            }
2457        };
2458        let expr = parse_guard_inner(&inner, stmt)?;
2459        acc = Some(match acc {
2460            None => expr,
2461            Some(prev) => GuardExpr::all(vec![prev, expr]),
2462        });
2463    }
2464    Ok(acc)
2465}
2466
2467// ---- Calls, RUN-exec, instruction exactness ----
2468// Static call resolution runs through the shared `resolve_call_name`
2469// (same module table, same messages); only the token-level call-shape
2470// detector is v2-native. Generic arguments classify like the
2471// `assignment | argument` grammar order (assignments merge across
2472// gaps, `$`/`env:`-led runs extend as expressions, everything else
2473// renders raw), and `ENV`/`EXPAND` lower through the shared direct
2474// cores instead of the injected dispatcher.
2475
2476/// Parse context: shared lowering dispatcher plus module table for
2477/// static call resolution, with `FUNC`/import frames per braced body.
2478pub struct ParseCtx<'a> {
2479    pub lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
2480    pub modules: &'a ModuleTable,
2481    /// Host-registered function names for the `FUNC` shadow check
2482    /// (empty when hosts are unknown).
2483    pub reserved: &'a HashSet<String>,
2484    /// `FUNC` scopes (innermost last) and import frames, pushed per
2485    /// braced body; short borrows only,
2486    /// never held across recursive parses.
2487    pub funcs: RefCell<Vec<HashSet<String>>>,
2488    pub imports: RefCell<Vec<Vec<String>>>,
2489    /// `EXPORT` func names in source order, validated at end of parse
2490    /// (forward references allowed).
2491    pub func_exports: RefCell<Vec<String>>,
2492    /// `EXPORT TYPE` names in source order, validated at end of parse
2493    /// (forward references allowed). Separate from func exports so the
2494    /// MCP server never confuses a type for a tool.
2495    pub type_exports: RefCell<Vec<String>>,
2496    /// Top-level `FUNC` names pre-declared before lowering, so forward
2497    /// references resolve regardless of order. Separate from `funcs`
2498    /// frames so duplicate detection in `declare_func` stays intact;
2499    /// `visible_snapshot` unions this set.
2500    pub forward: RefCell<Vec<HashSet<String>>>,
2501    /// 1-based source line of the statement currently lowering (the
2502    /// innermost split statement; updated per statement by the body
2503    /// loops, read as the base for nested splits). Lets every error
2504    /// carry its statement's line without threading it through every
2505    /// header function by hand.
2506    pub current_line: RefCell<usize>,
2507}
2508
2509impl<'a> ParseCtx<'a> {
2510    /// Context with empty tables.
2511    pub fn empty(
2512        lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
2513        modules: &'a ModuleTable,
2514        reserved: &'a HashSet<String>,
2515    ) -> Self {
2516        Self {
2517            lower,
2518            modules,
2519            reserved,
2520            funcs: RefCell::new(vec![HashSet::new()]),
2521            imports: RefCell::new(vec![Vec::new()]),
2522            func_exports: RefCell::new(Vec::new()),
2523            type_exports: RefCell::new(Vec::new()),
2524            forward: RefCell::new(vec![HashSet::new()]),
2525            current_line: RefCell::new(0),
2526        }
2527    }
2528
2529    /// Snapshot of everything visible at this point: `FUNC` names
2530    /// unioned across frames plus imports flattened outer-to-inner
2531    /// (unions `FUNC` names across frames, flattens imports outer-to-inner).
2532    fn visible_snapshot(&self) -> (HashSet<String>, Vec<String>) {
2533        let mut funcs = HashSet::new();
2534        for scope in self.funcs.borrow().iter() {
2535            funcs.extend(scope.iter().cloned());
2536        }
2537        funcs.extend(
2538            self.forward
2539                .borrow()
2540                .iter()
2541                .flat_map(|frame| frame.iter().cloned()),
2542        );
2543        let mut imports = Vec::new();
2544        for frame in self.imports.borrow().iter() {
2545            for module in frame {
2546                if !imports.contains(module) {
2547                    imports.push(module.clone());
2548                }
2549            }
2550        }
2551        (funcs, imports)
2552    }
2553
2554    /// Record a `FUNC` name in the innermost scope. Returns false when
2555    /// already defined in that same scope (nested shadowing stays
2556    /// allowed (nested shadowing stays permitted).
2557    fn declare_func(&self, name: &str) -> bool {
2558        match self.funcs.borrow_mut().last_mut() {
2559            Some(current) => current.insert(name.to_string()),
2560            None => true,
2561        }
2562    }
2563
2564    /// Record `IMPORT`ed modules in the innermost frame (deduped,
2565    /// (deduped; the unknown-module table check lives at the import site),
2566    /// which lives at the import site).
2567    fn import_into_frame(&self, modules: &[String]) {
2568        match self.imports.borrow_mut().last_mut() {
2569            Some(frame) => {
2570                for module in modules {
2571                    if !frame.contains(module) {
2572                        frame.push(module.clone());
2573                    }
2574                }
2575            }
2576            None => {
2577                self.imports.borrow_mut().push(modules.to_vec());
2578            }
2579        }
2580    }
2581}
2582
2583fn resolve_name(ctx: &ParseCtx, stmt: usize, name: &str) -> Result<String, TokenError> {
2584    let (funcs, imports) = ctx.visible_snapshot();
2585    resolve_call_name(ctx.modules, &funcs, &imports, &lowering_ctx(stmt), name)
2586        .map_err(|e| lower_err(stmt, e))
2587}
2588
2589/// Pre-declare `FUNC` names before lowering, so forward references
2590/// resolve regardless of order. Only valid non-reserved headers hoist:
2591/// the head (`FUNC NAME`, `ASYNC FUNC NAME`), a parameter Paren group,
2592/// a `:` return-type shape (via the shared `parse_type_shape` owner),
2593/// and a trailing non-template Brace body. Malformed headers
2594/// (`FUNC FOO() ECHO hi`) and reserved names (`FUNC LEN`) stay silent
2595/// here so the main pass owns their diagnostics. Runs per scope: the
2596/// caller pre-declares each statement list into its own frame, so
2597/// nested blocks resolve forward without leaking outward.
2598fn predeclare_forward_funcs(stmts: &[Stmt], ctx: &ParseCtx) {
2599    // Guarded definitions hoist like unguarded ones: `parse_func_at`
2600    // registers the name in `ctx.funcs` unconditionally, so the
2601    // forward set must see the same statement regardless of its
2602    // guard, or forward calls to `[os:macos] FUNC FOO` would fail
2603    // while backward calls resolve.
2604    for stmt in stmts {
2605        let body = &stmt.body;
2606        // `ASYNC FUNC` carries the prefix; the shared header owner
2607        // takes `pos` at `FUNC` in both cases.
2608        let pos = match body.first().map(|t| &t.kind) {
2609            Some(TokKind::Word(w)) if w == KEYWORD_FUNC => 0,
2610            Some(TokKind::Word(w)) if w == KEYWORD_ASYNC => match body.get(1).map(|t| &t.kind) {
2611                Some(TokKind::Word(next)) if next == KEYWORD_FUNC => 1,
2612                _ => continue,
2613            },
2614            _ => continue,
2615        };
2616        // Header grammar lives in the single owner: parameter lists,
2617        // return types, and trailing tokens validate exactly like the
2618        // real path, so malformed headers never hoist. Diagnostics
2619        // drop here (silent skip); the main pass owns the error.
2620        let Ok(Some((header, _))) = parse_func_header(body, pos, 0, KEYWORD_FUNC) else {
2621            continue;
2622        };
2623        if ctx.reserved.contains(&header.name)
2624            || ctx.modules.reserved_base_names().contains(&header.name)
2625        {
2626            continue;
2627        }
2628        // Trailing tokens after the body block are malformed (the real
2629        // path consumes the header exactly, leaving them to fail as the
2630        // next element), so such headers never hoist into `forward`:
2631        // only gap trivia may follow.
2632        if body.len() != header.block + 1
2633            && !body[header.block + 1..]
2634                .iter()
2635                .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
2636        {
2637            continue;
2638        }
2639        if let Some(frame) = ctx.forward.borrow_mut().last_mut() {
2640            frame.insert(header.name.clone());
2641        }
2642    }
2643}
2644
2645/// Qualify bare placeholder calls in template text through the
2646/// shared static resolver, so `{{ NAME(args) }}` obeys exactly the
2647/// same scope rule as statement-position calls: `IMPORT [MOD]`
2648/// brings the names into scope, unimported names fail naming the
2649/// fix, ambiguity fails closed. Qualified (`MOD::FUNC`), variable
2650/// (`$x`, `bare_key`), env (`env:K`), and non-call keys pass
2651/// through untouched for the runtime to handle exactly as before;
2652/// only keys that are entirely one bare call shape are rewritten,
2653/// and only the head identifier's bytes change: surrounding
2654/// spacing and neighboring placeholders stay byte-identical, so
2655/// string payloads never lose formatting. Returns `None` when
2656/// nothing qualified, leaving the text completely untouched.
2657/// Shape detection is the shared `template::parse_placeholder_call`
2658/// grammar (also behind runtime dispatch), so parse and runtime
2659/// can never disagree on what counts as one call.
2660fn qualify_template_calls(
2661    text: &str,
2662    ctx: &ParseCtx,
2663    stmt: usize,
2664) -> Result<Option<String>, TokenError> {
2665    use crate::template::{TemplateSegment, TemplateSegments, parse_placeholder_call};
2666    let mut out = String::with_capacity(text.len());
2667    let mut changed = false;
2668    for segment in TemplateSegments::new(text) {
2669        match segment {
2670            TemplateSegment::Text(raw) => out.push_str(raw),
2671            TemplateSegment::Placeholder { key, raw } => {
2672                let call = match parse_placeholder_call(key) {
2673                    Some(call) if call.module.is_none() => call,
2674                    _ => {
2675                        out.push_str(raw);
2676                        continue;
2677                    }
2678                };
2679                let head = call.name;
2680                let resolved = resolve_name(ctx, stmt, head)?;
2681                if !resolved.contains(MODULE_SEPARATOR) {
2682                    // Unqualified resolutions (`INSPECT`) keep today's
2683                    // runtime handling untouched.
2684                    out.push_str(raw);
2685                    continue;
2686                }
2687                changed = true;
2688                // Splice only the head span: `name_span` is the byte
2689                // range of the head inside `key`, and `key` is the
2690                // trimmed interior of `raw`, so the raw offset is the
2691                // interior start plus the span start.
2692                let key_off = raw.find(key).expect("key is trimmed interior");
2693                let off = key_off + call.name_span.start;
2694                out.push_str(&raw[..off]);
2695                out.push_str(&resolved);
2696                out.push_str(&raw[off + head.len()..]);
2697            }
2698        }
2699    }
2700    if changed { Ok(Some(out)) } else { Ok(None) }
2701}
2702
2703/// Call shape at `pos`: UPPERCASE head plus joint `::` segments and a
2704/// paren group (joint iff required: statements forbid the gap;
2705/// expressions allow it).
2706/// Peek-only; anything else falls through (not a call shape).
2707/// Returns the dotted name and paren index.
2708fn call_shape_at(toks: &[Tok], pos: usize, joint_paren: bool) -> Option<(String, usize)> {
2709    let head = match toks.get(pos).map(|t| &t.kind) {
2710        Some(TokKind::Word(w))
2711            if !w.is_empty()
2712                && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
2713                && w.chars()
2714                    .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') =>
2715        {
2716            w.clone()
2717        }
2718        _ => return None,
2719    };
2720    let mut name = head;
2721    let mut p = pos + 1;
2722    loop {
2723        let colons = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')))
2724            && toks.get(p).is_some_and(|t| t.joint)
2725            && matches!(toks.get(p + 1).map(|t| &t.kind), Some(TokKind::Punct(':')))
2726            && toks.get(p + 1).is_some_and(|t| t.joint)
2727            && matches!(toks.get(p + 2).map(|t| &t.kind), Some(TokKind::Word(_)))
2728            && toks.get(p + 2).is_some_and(|t| t.joint);
2729        if !colons {
2730            break;
2731        }
2732        if let Some(TokKind::Word(seg)) = toks.get(p + 2).map(|t| &t.kind) {
2733            name.push_str(MODULE_SEPARATOR);
2734            name.push_str(seg);
2735        }
2736        p += 3;
2737    }
2738    match toks.get(p).map(|t| &t.kind) {
2739        Some(TokKind::Group {
2740            delim: GroupDelim::Paren,
2741            ..
2742        }) => {
2743            if joint_paren && !toks[p].joint {
2744                return None;
2745            }
2746            Some((name, p))
2747        }
2748        _ => None,
2749    }
2750}
2751
2752/// Call arguments over a paren group's contents: comma-separated full
2753/// expressions with `gap_nl` newlines at the edges (each arg rejects
2754/// a stray boundary).
2755fn parse_call_args(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Vec<Expr>, TokenError> {
2756    let mut cur = Cursor::expr(inner, stmt);
2757    cur.skip_gap_nl();
2758    if cur.done() {
2759        return Ok(vec![]);
2760    }
2761    let mut args = Vec::new();
2762    loop {
2763        let arg = parse_expr_or(&mut cur, ctx)?;
2764        reject_boundary(&lowering_ctx(stmt), &arg).map_err(|e| cur.err(e.to_string()))?;
2765        args.push(arg);
2766        cur.skip_gap_nl();
2767        if cur.eat_punct(',') {
2768            cur.skip_gap_nl();
2769            continue;
2770        }
2771        break;
2772    }
2773    if !cur.done() {
2774        return Err(trailing_items_error(
2775            &cur,
2776            ctx,
2777            stmt,
2778            "call arguments",
2779            "unexpected text in call",
2780        ));
2781    }
2782    Ok(args)
2783}
2784
2785/// Lower a call-shape to `Expr`: `INSPECT` keeps its variable
2786/// unevaluated; everything else
2787/// resolves statically through the shared resolver.
2788fn parse_expr_call(
2789    name: String,
2790    inner: &[Tok],
2791    stmt: usize,
2792    ctx: &ParseCtx,
2793) -> Result<Expr, TokenError> {
2794    let args = parse_call_args(inner, stmt, ctx)?;
2795    if name == KEYWORD_INSPECT {
2796        let [arg] = args.as_slice() else {
2797            return Err(TokenError {
2798                stmt,
2799                msg: "INSPECT requires exactly one argument: INSPECT($var)".to_string(),
2800                line: 0,
2801                col: 0,
2802                kind: None,
2803            });
2804        };
2805        if let Expr::Var(var) = arg {
2806            return Ok(Expr::Inspect(var.clone()));
2807        }
2808        return Err(TokenError {
2809            stmt,
2810            msg: format!("INSPECT requires a $variable argument, found {arg:?}"),
2811            line: 0,
2812            col: 0,
2813            kind: None,
2814        });
2815    }
2816    let qualified = resolve_name(ctx, stmt, &name)?;
2817    Ok(Expr::Call {
2818        name: qualified,
2819        args,
2820    })
2821}
2822
2823/// Item rule selecting which `[...]` position the shared list core
2824/// parses for. The loop, comma rule, empty rule, trailing-content rule,
2825/// and newline tolerance are identical for every position (see
2826/// [`parse_bracket_list`]); only items and miss handling differ.
2827#[derive(Clone, Copy)]
2828enum BracketItems {
2829    /// Full checked expressions; a miss fails loudly.
2830    Expr,
2831    /// RUN-exec restricted atoms (brace groups try maps only, so blocks
2832    /// miss); a miss is shell fallthrough (`None`), never an error, so
2833    /// POSIX `[ -f ... ]` and malformed shapes stay shell.
2834    Exec,
2835}
2836
2837/// Trailing-content error for comma-separated positions (list
2838/// items, call arguments): stamps the offending token's position so
2839/// the caret names the line that actually fails instead of the
2840/// statement head, and names the likely missing comma when the
2841/// remainder parses as another item. Genuine trailing garbage keeps
2842/// the previous message verbatim. Error-path only, so the probe
2843/// parse costs nothing on success.
2844fn trailing_items_error(
2845    cur: &Cursor,
2846    ctx: &ParseCtx,
2847    stmt: usize,
2848    missing_what: &str,
2849    fallback: &str,
2850) -> TokenError {
2851    let (line, col) = cur
2852        .toks
2853        .get(cur.pos)
2854        .map(|t| (t.line, t.col))
2855        .unwrap_or((0, 0));
2856    let mut probe = Cursor::expr(&cur.toks[cur.pos.min(cur.toks.len())..], stmt);
2857    let msg = if parse_expr_checked(&mut probe, ctx).is_ok() {
2858        format!("missing comma between {missing_what}")
2859    } else {
2860        fallback.to_string()
2861    };
2862    TokenError {
2863        stmt,
2864        line,
2865        col,
2866        msg,
2867        kind: None,
2868    }
2869}
2870
2871/// Shared comma-separated `[...]` core behind every bracket position.
2872/// There is exactly one list loop: one empty rule, one comma rule, one
2873/// trailing-content rule, newlines riding every gap. A bracket group
2874/// already lexes across lines, so rejecting newlines here only strands
2875/// the statement in raw-text rendering.
2876fn parse_bracket_list(
2877    inner: &[Tok],
2878    stmt: usize,
2879    ctx: &ParseCtx,
2880    items: BracketItems,
2881) -> Result<Option<Expr>, TokenError> {
2882    let mut cur = Cursor::expr(inner, stmt);
2883    cur.skip_gap_nl();
2884    if cur.done() {
2885        return Ok(Some(Expr::List(vec![])));
2886    }
2887    let mut list = Vec::new();
2888    loop {
2889        let item = match items {
2890            BracketItems::Expr => parse_expr_checked(&mut cur, ctx),
2891            BracketItems::Exec => match parse_run_exec_atom(&mut cur, ctx) {
2892                Ok(Some(atom)) => Ok(atom),
2893                // Not an exec shape at all: shell fallthrough.
2894                Ok(None) | Err(_) => return Ok(None),
2895            },
2896        };
2897        // Only expression positions can fail here: exec misses
2898        // return `None` above.
2899        let item = item?;
2900        match reject_boundary(&lowering_ctx(stmt), &item) {
2901            Ok(()) => {}
2902            Err(e) if matches!(items, BracketItems::Expr) => {
2903                return Err(cur.err(e.to_string()));
2904            }
2905            Err(_) => return Ok(None),
2906        }
2907        list.push(item);
2908        cur.skip_gap_nl();
2909        if cur.eat_punct(',') {
2910            cur.skip_gap_nl();
2911            continue;
2912        }
2913        break;
2914    }
2915    if !cur.done() {
2916        return match items {
2917            BracketItems::Expr => Err(trailing_items_error(
2918                &cur,
2919                ctx,
2920                stmt,
2921                "list items",
2922                "unexpected text in list",
2923            )),
2924            BracketItems::Exec => Ok(None),
2925        };
2926    }
2927    Ok(Some(Expr::List(list)))
2928}
2929
2930/// RUN exec-form list: the shared bracket core in `Exec` mode (atoms
2931/// only, except parenthesized/calls/lists/maps which recurse fully).
2932/// Anything that is not a clean comma-separated list misses the whole
2933/// exec shape (`None`): the grammar falls through to the shell path,
2934/// which reads the bracket literally and lets the shared lowering
2935/// decide (POSIX `[ -f ... ]` stays shell; non-map blocks and malformed
2936/// shapes behave exactly like the grammar's fallthrough).
2937/// (`instruction`), which reads the bracket literally and lets the
2938/// shared lowering decide (POSIX `[ -f ... ]` stays shell, malformed
2939/// shapes fail there exactly like the grammar). Only the
2940/// joint-bracket gate stays a hard error (it precedes this function).
2941fn parse_run_exec_list(
2942    inner: &[Tok],
2943    stmt: usize,
2944    ctx: &ParseCtx,
2945) -> Result<Option<Expr>, TokenError> {
2946    parse_bracket_list(inner, stmt, ctx, BracketItems::Exec)
2947}
2948
2949/// One RUN-exec item: brace groups try maps only (blocks miss);
2950/// everything else parses as a full atom (nested lists and map
2951/// values still admit blocks, like the grammar).
2952fn parse_run_exec_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Option<Expr>, TokenError> {
2953    if matches!(
2954        cur.toks.get(cur.pos).map(|t| &t.kind),
2955        Some(TokKind::Group {
2956            delim: GroupDelim::Brace,
2957            ..
2958        })
2959    ) {
2960        let inner = match &cur.toks[cur.pos].kind {
2961            TokKind::Group { inner, .. } => inner.clone(),
2962            _ => unreachable!(),
2963        };
2964        return match parse_map_literal(&inner, cur.stmt, ctx) {
2965            Ok(map) => {
2966                cur.pos += 1;
2967                Ok(Some(map))
2968            }
2969            Err(_) => Ok(None),
2970        };
2971    }
2972    parse_expr_atom(cur, ctx).map(Some)
2973}
2974
2975// ---- Single-command wrappers + AWAIT/CANCEL ----
2976// Wrappers parse through the shared validators (`check_tty_wrapping`,
2977// capture rejects, isolated rewrite, nesting reject, binding merge,
2978// guard `and`) promoted verbatim to `commands.rs`; only the
2979// token-level shape classifiers (duration gate, binding splitter,
2980// await/cancel shapes, block-vs-template) are v2-native. Statements
2981// lower to step VECTORS: structural pairs (calls, RUN-exec,
2982// await/cancel, wrapper blocks) end mid-line and trailing elements
2983// form following steps, exactly like the grammar's `element*`.
2984//
2985// Deferred: block STATEMENTS (slice 5: top-level `IF`/`FOR`/`WHILE`
2986// bodies, guard blocks, `REMOTE`, directives).
2987
2988/// Static duration shape mirror (`timeout_literal`, atomic): ASCII
2989/// digits plus one optional unit, full-match only. Anything else
2990/// (`10ss`, `banana`, `-5s`) misses the wrapper shape and falls back
2991/// to the generic instruction path, which fails in lowering exactly
2992/// like the grammar's committed `instruction`.
2993fn is_timeout_literal(text: &str) -> bool {
2994    let digits = text.len() - text.trim_start_matches(|c: char| c.is_ascii_digit()).len();
2995    if digits == 0 {
2996        return false;
2997    }
2998    matches!(&text[digits..], "" | "ms" | "s" | "m" | "h")
2999}
3000
3001/// Template-brace test: a brace group whose first inner token opens
3002/// another brace (`{{...}}`); anything else braced is a block body.
3003/// Same shape the arg engine uses; single source from here.
3004fn is_template_brace(tok: &Tok) -> bool {
3005    matches!(
3006        &tok.kind,
3007        TokKind::Group {
3008            delim: GroupDelim::Brace,
3009            inner,
3010            ..
3011        } if matches!(
3012            inner.first().map(|t| &t.kind),
3013            Some(TokKind::Group {
3014                delim: GroupDelim::Brace,
3015                ..
3016            })
3017        )
3018    )
3019}
3020
3021/// Parse one TIMEOUT duration unit at `pos` (the token after the
3022/// head, gapped like the grammar's `sep`). Returns the arg and
3023/// tokens consumed, or `None` on shape miss (caller falls back to
3024/// generic, which fails in lowering). Static
3025/// literals validate now through the shared Duration check
3026/// (`TIMEOUT 0s` fails here, probed); dynamics defer to runtime.
3027fn parse_timeout_duration_at(
3028    toks: &[Tok],
3029    pos: usize,
3030    stmt: usize,
3031) -> Result<Option<(Arg, usize)>, TokenError> {
3032    let Some(head) = toks.get(pos) else {
3033        return Ok(None);
3034    };
3035    if head.joint {
3036        return Ok(None);
3037    }
3038    let arg = match &head.kind {
3039        TokKind::Word(w) if is_timeout_literal(w) => Arg::String(w.clone(), false),
3040        TokKind::Punct('$') => match toks.get(pos + 1) {
3041            Some(var) if var.joint && matches!(&var.kind, TokKind::Word(w) if is_ident_word(w)) => {
3042                match &var.kind {
3043                    TokKind::Word(w) => Arg::Expr(Expr::Var(w.clone())),
3044                    _ => unreachable!(),
3045                }
3046            }
3047            _ => return Ok(None),
3048        },
3049        TokKind::Str { text, .. } => Arg::String(text.clone(), true),
3050        TokKind::BlockStr(full) => Arg::String(crate::command::lower_block_string(full), true),
3051        TokKind::Group {
3052            delim: GroupDelim::Brace,
3053            inner,
3054            open_joint,
3055            close_joint,
3056        } if is_template_brace(&toks[pos]) => Arg::String(
3057            render_group('{', '}', inner, *open_joint, *close_joint),
3058            false,
3059        ),
3060        _ => return Ok(None),
3061    };
3062    let used = match &head.kind {
3063        TokKind::Punct('$') => 2,
3064        _ => 1,
3065    };
3066    ArgType::Duration.check_arg(&arg).map_err(|e| TokenError {
3067        stmt,
3068        msg: e.to_string(),
3069        line: 0,
3070        col: 0,
3071        kind: None,
3072    })?;
3073    Ok(Some((arg, used)))
3074}
3075
3076/// Parse `WITH_IO [...]` bindings over a bracket group's inner
3077/// tokens: comma-separated `stream[=$var]` / `rows|cols=int`
3078/// bindings, newlines skipping freely like `ws`. Returns `None` on
3079/// shape miss (empty flags, bad stream words, missing commas or
3080/// values: the caller falls back to generic, which fails in lowering).
3081/// Grammar-matched but invalid bindings (tty
3082/// values, out-of-range geometry) fail loudly, mirroring
3083/// `parse_io_binding`'s messages one by one.
3084fn parse_io_bindings(inner: &[Tok], stmt: usize) -> Result<Option<Vec<IoBinding>>, TokenError> {
3085    let mut parts: Vec<&[Tok]> = Vec::new();
3086    let mut start = 0;
3087    for (i, tok) in inner.iter().enumerate() {
3088        // Newlines skip freely like `ws` (filtered per part below);
3089        // commas split bindings; everything else is content.
3090        if matches!(&tok.kind, TokKind::Punct(',')) {
3091            parts.push(&inner[start..i]);
3092            start = i + 1;
3093        }
3094    }
3095    parts.push(&inner[start..]);
3096    // An empty flag list (`[]`, `[,]`) misses the shape.
3097    if parts.len() == 1 && parts[0].iter().all(|t| matches!(&t.kind, TokKind::Newline)) {
3098        return Ok(None);
3099    }
3100    let mut out = Vec::new();
3101    for part in parts {
3102        let part: Vec<&Tok> = part
3103            .iter()
3104            .filter(|t| !matches!(&t.kind, TokKind::Newline))
3105            .collect();
3106        match parse_io_binding_part(&part, stmt)? {
3107            Some(binding) => out.push(binding),
3108            None => return Ok(None),
3109        }
3110    }
3111    if out.is_empty() {
3112        return Ok(None);
3113    }
3114    Ok(Some(out))
3115}
3116
3117/// One `stream[=$var]` / `rows|cols=int` binding. Gaps ride free
3118/// around `=`/`,`/names like `ws?`; only `$`+name stays gapless
3119/// (atomic `dollar_ident`). Streams and size names outside the
3120/// grammar's words miss the shape; a valued `tty` and out-of-range
3121/// geometry fail loudly with exact messages.
3122fn parse_io_binding_part(part: &[&Tok], stmt: usize) -> Result<Option<IoBinding>, TokenError> {
3123    let fail = |msg: String| TokenError {
3124        stmt,
3125        msg,
3126        line: 0,
3127        col: 0,
3128        kind: None,
3129    };
3130    let Some(first) = part.first() else {
3131        return Ok(None);
3132    };
3133    let TokKind::Word(stream) = &first.kind else {
3134        return Ok(None);
3135    };
3136    let is_stream = matches!(stream.as_str(), "stdin" | "stdout" | "stderr" | "tty");
3137    let is_size = matches!(stream.as_str(), "rows" | "cols");
3138    if !is_stream && !is_size {
3139        return Ok(None);
3140    }
3141    let rest = &part[1..];
3142    if rest.is_empty() {
3143        if is_size {
3144            // Bare `rows` misses `io_size` (`=` + digits required).
3145            return Ok(None);
3146        }
3147        return Ok(Some(IoBinding {
3148            stream: io_stream_of(stream),
3149            pipe: None,
3150        }));
3151    }
3152    // `= value` at any gap.
3153    if !matches!(rest.first().map(|t| &t.kind), Some(TokKind::Punct('='))) {
3154        return Ok(None);
3155    }
3156    let value = &rest[1..];
3157    if is_size {
3158        // Geometry: one all-digit word, 1-65535 (mirrors `parse_io_size`).
3159        if value.len() != 1 {
3160            return Ok(None);
3161        }
3162        let TokKind::Word(digits) = &value[0].kind else {
3163            return Ok(None);
3164        };
3165        if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
3166            return Ok(None);
3167        }
3168        let dim = digits
3169            .parse::<u64>()
3170            .ok()
3171            .filter(|v| (1..=u64::from(u16::MAX)).contains(v))
3172            .ok_or_else(|| {
3173                fail(
3174                    "WITH_IO terminal geometry needs a positive integer 1-65535 (e.g. `rows=40`)"
3175                        .to_string(),
3176                )
3177            })?;
3178        let dim = dim as u16;
3179        return Ok(Some(IoBinding {
3180            stream: if stream == "rows" {
3181                IoStream::Rows(dim)
3182            } else {
3183                IoStream::Cols(dim)
3184            },
3185            pipe: None,
3186        }));
3187    }
3188    // Stream pipe: `= $var` with a gapless name.
3189    if value.len() != 2 {
3190        return Ok(None);
3191    }
3192    if !matches!(&value[0].kind, TokKind::Punct('$')) {
3193        return Ok(None);
3194    }
3195    let TokKind::Word(var) = &value[1].kind else {
3196        return Ok(None);
3197    };
3198    if !value[1].joint || !is_ident_word(var) {
3199        return Ok(None);
3200    }
3201    if stream == "tty" {
3202        // `tty` is a bare flag (mirrors `parse_io_binding`).
3203        return Err(fail(
3204            "WITH_IO [tty] takes no value: use bare `tty`, with `rows = <int>` / `cols = <int>` for geometry (e.g. `[tty, rows=40, cols=100]`)"
3205                .to_string(),
3206        ));
3207    }
3208    Ok(Some(IoBinding {
3209        stream: io_stream_of(stream),
3210        pipe: Some(crate::ast::PipeTarget::Var(var.clone())),
3211    }))
3212}
3213
3214/// Stream word to [`IoStream`]: only grammar words reach here, so
3215/// the mapping is total (mirrors `parse_io_stream`).
3216fn io_stream_of(name: &str) -> IoStream {
3217    match name {
3218        "stdin" => IoStream::Stdin,
3219        "stdout" => IoStream::Stdout,
3220        "stderr" => IoStream::Stderr,
3221        _ => IoStream::Tty,
3222    }
3223}
3224
3225/// `AWAIT`/`CANCEL $var` shape at `pos`. A head without `$` misses
3226/// (`None`: generic fails it in lowering); once `$`
3227/// commits, the name must follow and parse errors stay loud, like
3228/// the grammar's committed `"$" ~ ident`. `var_joint` enforces the
3229/// atomic `$var` adjacency inside compound-atomic parents; element
3230/// level admits the gap (probed `AWAIT $ t`). The caller continues
3231/// its element loop past the shape.
3232fn parse_await_cancel_at(
3233    toks: &[Tok],
3234    pos: usize,
3235    stmt: usize,
3236    var_joint: bool,
3237) -> Result<Option<(StepKind, usize)>, TokenError> {
3238    let head = match toks.get(pos).map(|t| &t.kind) {
3239        Some(TokKind::Word(w)) if w == KEYWORD_AWAIT || w == KEYWORD_CANCEL => w.clone(),
3240        _ => return Ok(None),
3241    };
3242    if !matches!(
3243        toks.get(pos + 1).map(|t| &t.kind),
3244        Some(TokKind::Punct('$'))
3245    ) {
3246        return Ok(None);
3247    }
3248    let var = match toks.get(pos + 2) {
3249        Some(t)
3250            if matches!(&t.kind, TokKind::Word(w) if is_ident_word(w))
3251                && (!var_joint || t.joint) =>
3252        {
3253            match &t.kind {
3254                TokKind::Word(w) => w.clone(),
3255                _ => unreachable!(),
3256            }
3257        }
3258        _ => {
3259            return Err(TokenError {
3260                stmt,
3261                msg: format!("{head} requires a variable"),
3262                line: 0,
3263                col: 0,
3264                kind: None,
3265            });
3266        }
3267    };
3268    Ok(Some((
3269        if head == KEYWORD_AWAIT {
3270            StepKind::Await { var }
3271        } else {
3272            StepKind::Cancel { var }
3273        },
3274        3,
3275    )))
3276}
3277
3278/// Wrapper strictness for one single-command inner: `AWAIT` parses
3279/// dedicated in `TIMEOUT`/`ISOLATED` inners but falls to generic in
3280/// `WITH_IO`/`ASYNC` inners (where lowering fails it, probed), and
3281/// `WITH_IO` recurses everywhere but directly under `ASYNC` (where
3282/// lowering fails it, probed). Shared predicates, never restated.
3283#[derive(Clone, Copy)]
3284struct InnerRules {
3285    allow_await: bool,
3286    allow_with_io: bool,
3287}
3288
3289/// Parse one single (non-block) inner command, returning the kind
3290/// and tokens consumed: dedicated await/cancel, while/remote, calls,
3291/// RUN-exec, nested wrappers, strict `INHERIT_ENV` (the caller
3292/// rejects the nesting or rewrites it), or the generic instruction
3293/// path (which consumes everything and fails unknown heads in
3294/// lowering, exactly like the grammar's committed `instruction`).
3295fn parse_single_inner(
3296    toks: &[Tok],
3297    pos: usize,
3298    stmt: usize,
3299    ctx: &ParseCtx,
3300    rules: InnerRules,
3301) -> Result<(StepKind, usize), TokenError> {
3302    let head_word = match toks.get(pos).map(|t| &t.kind) {
3303        Some(TokKind::Word(w)) => Some(w.clone()),
3304        _ => None,
3305    };
3306    // Nested `WHILE`/`REMOTE` recurse structurally (both ride every
3307    // inner-command set in the grammar); misses fall through to
3308    // generic below.
3309    if head_word.as_deref() == Some(KEYWORD_WHILE) {
3310        match parse_while_single(toks, pos, stmt, ctx) {
3311            Ok(Some((kind, used))) => return Ok((kind, used)),
3312            Ok(None) => {}
3313            Err(e) => return Err(e),
3314        }
3315    }
3316    if head_word.as_deref() == Some(KEYWORD_REMOTE) {
3317        match parse_remote_single(toks, pos, stmt, ctx) {
3318            Ok(Some((kind, used))) => return Ok((kind, used)),
3319            Ok(None) => {}
3320            Err(e) => return Err(e),
3321        }
3322    }
3323    // File `IMPORT "path" AS ALIAS` (#115) rides every single-inner
3324    // set (TIMEOUT/ISOLATED/WITH_IO/ASYNC, LET ASYNC): exactly one file
3325    // entry and no modules, else a hard error; shape misses fall through
3326    // to generic below, which fails them in lowering.
3327    if head_word.as_deref() == Some(KEYWORD_IMPORT)
3328        && let Some((path, alias, used)) = parse_single_file_import(toks, pos, stmt, ctx)?
3329    {
3330        return Ok((StepKind::ImportFile { path, alias }, used));
3331    }
3332    // Dedicated await/cancel first (await gated by parent); anything
3333    // they decline falls through to generic below.
3334    if head_word.as_deref() == Some(KEYWORD_AWAIT)
3335        && rules.allow_await
3336        && let Some(found) = parse_await_cancel_at(toks, pos, stmt, true)?
3337    {
3338        return Ok(found);
3339    }
3340    if head_word.as_deref() == Some(KEYWORD_CANCEL)
3341        && let Some(found) = parse_await_cancel_at(toks, pos, stmt, true)?
3342    {
3343        return Ok(found);
3344    }
3345    // Calls and RUN-exec end mid-run; the caller continues past them.
3346    if let Some((call_name, paren)) = call_shape_at(toks, pos, true) {
3347        let inner = match &toks[paren].kind {
3348            TokKind::Group { inner, .. } => inner.clone(),
3349            _ => unreachable!(),
3350        };
3351        let args = parse_call_args(&inner, stmt, ctx)?;
3352        if !call_name.contains(MODULE_SEPARATOR) {
3353            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
3354                .map_err(|e| lower_err(stmt, e))?;
3355        }
3356        let qualified = resolve_name(ctx, stmt, &call_name)?;
3357        return Ok((
3358            StepKind::Call {
3359                name: qualified,
3360                args,
3361            },
3362            paren + 1 - pos,
3363        ));
3364    }
3365    if head_word.as_deref() == Some(KEYWORD_RUN)
3366        && matches!(
3367            toks.get(pos + 1).map(|t| &t.kind),
3368            Some(TokKind::Group {
3369                delim: GroupDelim::Bracket,
3370                ..
3371            })
3372        )
3373    {
3374        // Gapped like the grammar's `sep`; a joint bracket is a
3375        // hard error, never a spliced arg (probed `RUN["a"]`).
3376        if toks[pos + 1].joint {
3377            return Err(TokenError {
3378                stmt,
3379                msg: "RUN [...] requires a gap after RUN".to_string(),
3380                line: 0,
3381                col: 0,
3382                kind: None,
3383            });
3384        }
3385        let inner = match &toks[pos + 1].kind {
3386            TokKind::Group { inner, .. } => inner.clone(),
3387            _ => unreachable!(),
3388        };
3389        let exec_list = parse_run_exec_list(&inner, stmt, ctx)?;
3390        // Non-map blocks miss the exec shape (the grammar has no
3391        // `block` alternative here); fall through to generic below,
3392        // which reads the shell path literally.
3393        if let Some(list) = exec_list {
3394            let kind =
3395                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
3396            return Ok((kind, 2));
3397        }
3398    }
3399    // Nested wrappers recurse structurally; a `WITH_IO` directly
3400    // under `ASYNC` goes generic instead (lowering fails it, probed).
3401    match head_word.as_deref() {
3402        Some(KEYWORD_WITH_IO) if rules.allow_with_io => {
3403            match parse_with_io_single(toks, pos, stmt, ctx) {
3404                Ok(Some((kind, used))) => return Ok((kind, used)),
3405                Ok(None) => {}
3406                Err(e) => return Err(e),
3407            }
3408        }
3409        Some(KEYWORD_TIMEOUT) => match parse_timeout_single(toks, pos, stmt, ctx) {
3410            Ok(Some((kind, used))) => return Ok((kind, used)),
3411            Ok(None) => {}
3412            Err(e) => return Err(e),
3413        },
3414        Some(KEYWORD_ISOLATED) => match parse_isolated_single(toks, pos, stmt, ctx) {
3415            Ok(Some((kind, used))) => return Ok((kind, used)),
3416            Ok(None) => {}
3417            Err(e) => return Err(e),
3418        },
3419        Some(KEYWORD_ASYNC) => match parse_async_single(toks, pos, stmt, ctx) {
3420            Ok(Some((kind, used))) => return Ok((kind, used)),
3421            Ok(None) => {}
3422            Err(e) => return Err(e),
3423        },
3424        // `INHERIT_ENV [...]` parses strictly here (shared with
3425        // element level); the caller either rejects the nesting or
3426        // rewrites it, same as the shared validator. Trailing
3427        // elements loop on outside (a bad follower fails there, like
3428        // the grammar's line end).
3429        Some(KEYWORD_INHERIT_ENV) => {
3430            if let Some(found) = parse_inherit_env_at(toks, pos, stmt)? {
3431                return Ok(found);
3432            }
3433        }
3434        _ => {}
3435    }
3436    // Generic instruction: consumes the whole run; unknown heads
3437    // (LET/RETURN/FUNC/IF/...) fail in lowering.
3438    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
3439    Ok((kind, used))
3440}
3441
3442/// Parse an `INHERIT_ENV [...]` key list over a bracket group's
3443/// inner tokens, mirroring `inherit_list` strictly: comma-separated
3444/// keys, gaps/newlines only around keys and commas (never inside:
3445/// keys are atomic), each key a joint run validated against the
3446/// `guard_key_char` exclusions (`: = ! , | ( ) ] $`, plus the `//`
3447/// and `/*` comment opens). Groups and strings render raw (they read
3448/// as ordinary characters here); anything else misses
3449/// the shape (`None`: generic fails it in lowering).
3450/// Statement-level `INHERIT_ENV` stays generic (slice 5 directives);
3451/// this serves wrapper inners, where the nesting check (or the
3452/// isolated rewrite) consumes the result.
3453fn parse_inherit_keys(inner: &[Tok], stmt: usize) -> Result<Option<Vec<String>>, TokenError> {
3454    let mut parts: Vec<&[Tok]> = Vec::new();
3455    let mut start = 0;
3456    for (i, tok) in inner.iter().enumerate() {
3457        if matches!(&tok.kind, TokKind::Punct(',')) {
3458            parts.push(&inner[start..i]);
3459            start = i + 1;
3460        }
3461    }
3462    parts.push(&inner[start..]);
3463    let mut out = Vec::new();
3464    for part in parts {
3465        // Newlines skip at the edges only, like `ws?`.
3466        let mut part = part;
3467        while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
3468            part = &part[1..];
3469        }
3470        while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
3471            part = &part[..part.len() - 1];
3472        }
3473        let Some(key) = render_inherit_key(part, stmt)? else {
3474            return Ok(None);
3475        };
3476        out.push(key);
3477    }
3478    if out.is_empty() {
3479        return Ok(None);
3480    }
3481    Ok(Some(out))
3482}
3483
3484/// True when a `/` opens an inline comment: joint `//` or `/*`
3485/// (mirroring the grammar's comment literals, which need adjacency;
3486/// a gapped second char is payload text, like `a/ /b`). Used
3487/// everywhere `gap`/`gap_nl` admit comments.
3488fn is_comment_open(toks: &[Tok], pos: usize) -> bool {
3489    matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('/')))
3490        && matches!(
3491            toks.get(pos + 1).map(|t| (&t.kind, t.joint)),
3492            Some((TokKind::Punct('/'), true)) | Some((TokKind::Punct('*'), true))
3493        )
3494}
3495
3496/// Skip one inline comment starting at `pos` (which holds the `/`;
3497/// see [`is_comment_open`): `//` runs to a newline or the end,
3498/// `/* */` balances (nesting like the grammar) across newlines.
3499/// Returns the first position past the comment, or `None` when the
3500/// block never closes (the grammar fails unclosed comments too).
3501fn skip_inline_comment(toks: &[Tok], pos: usize) -> Option<usize> {
3502    let second = match toks.get(pos + 1).map(|t| &t.kind) {
3503        Some(TokKind::Punct('/')) => '/',
3504        Some(TokKind::Punct('*')) => '*',
3505        _ => return None,
3506    };
3507    if second == '/' {
3508        let mut p = pos + 2;
3509        while p < toks.len() && !matches!(&toks[p].kind, TokKind::Newline) {
3510            p += 1;
3511        }
3512        return Some(p);
3513    }
3514    let mut depth = 1usize;
3515    let mut p = pos + 2;
3516    while p < toks.len() {
3517        let is_open = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('/')))
3518            && matches!(
3519                toks.get(p + 1).map(|t| (&t.kind, t.joint)),
3520                Some((TokKind::Punct('*'), true))
3521            );
3522        let is_close = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('*')))
3523            && matches!(
3524                toks.get(p + 1).map(|t| (&t.kind, t.joint)),
3525                Some((TokKind::Punct('/'), true))
3526            );
3527        if is_open {
3528            depth += 1;
3529            p += 2;
3530        } else if is_close {
3531            depth -= 1;
3532            p += 2;
3533            if depth == 0 {
3534                return Some(p);
3535            }
3536        } else {
3537            p += 1;
3538        }
3539    }
3540    None
3541}
3542
3543/// Parse one inherit key: a maximal key-char run, then only
3544/// trailing gap content (`gap_nl`: newlines, comments, `#`). Key
3545/// chars exclude `: = ! , | ( ) ] $`, whitespace, and the `//` / `/*`
3546/// comment opens; a joint `#`
3547/// stays literal, a gapped one opens a trailing comment. Groups and
3548/// strings render raw for the exclusion check (they read as
3549/// ordinary characters here). `None` on shape miss.
3550fn render_inherit_key(part: &[Tok], stmt: usize) -> Result<Option<String>, TokenError> {
3551    let mut out = String::new();
3552    let mut i = 0;
3553    // Key run: words, puncts (except comment opens), groups and
3554    // strings rendered raw; ends at any gap, newline, comment, or
3555    // `//` / `/*` open.
3556    while i < part.len() {
3557        let tok = &part[i];
3558        if i > 0 && !tok.joint {
3559            break;
3560        }
3561        match &tok.kind {
3562            TokKind::Word(w) => {
3563                out.push_str(w);
3564                i += 1;
3565            }
3566            TokKind::Punct('/') if is_comment_open(part, i) => break,
3567            // `#` stays literal at key start (`#c`) or joint
3568            // (`a#b`); gapped mid-key it opens a trailing
3569            // comment like the grammar's `gap_nl`.
3570            TokKind::Punct('#') if tok.joint || out.is_empty() => {
3571                // `#` stays literal at key start (`#c`) or joint
3572                // (`a#b`).
3573                out.push('#');
3574                i += 1;
3575            }
3576            // Gapped mid-key `#` opens a trailing comment (handled
3577            // by the trailer check below, like `gap_nl`).
3578            TokKind::Punct('#') => break,
3579            TokKind::Punct(c) => {
3580                out.push(*c);
3581                i += 1;
3582            }
3583            TokKind::Semicolon => {
3584                out.push(';');
3585                i += 1;
3586            }
3587            TokKind::Str { text, quote } => {
3588                out.push(*quote);
3589                out.push_str(text);
3590                out.push(*quote);
3591                i += 1;
3592            }
3593            TokKind::BlockStr(full) => {
3594                out.push_str(full);
3595                i += 1;
3596            }
3597            TokKind::Group {
3598                delim,
3599                inner,
3600                open_joint,
3601                close_joint,
3602            } => {
3603                let (open, close) = match delim {
3604                    GroupDelim::Bracket => ('[', ']'),
3605                    GroupDelim::Paren => ('(', ')'),
3606                    GroupDelim::Brace => ('{', '}'),
3607                };
3608                out.push_str(&render_group(open, close, inner, *open_joint, *close_joint));
3609                i += 1;
3610            }
3611            // Newlines and comment markers end the key; the trailer
3612            // check below admits them.
3613            TokKind::Newline | TokKind::Comment(_) => break,
3614        }
3615    }
3616    if out.is_empty() {
3617        return Ok(None);
3618    }
3619    // Trailer: only gap content (`gap_nl`) may follow the key.
3620    let mut j = i;
3621    while j < part.len() {
3622        let tok = &part[j];
3623        match &tok.kind {
3624            TokKind::Newline | TokKind::Comment(_) => {
3625                j += 1;
3626            }
3627            TokKind::Punct('/') if is_comment_open(part, j) => {
3628                j = skip_inline_comment(part, j).ok_or(TokenError {
3629                    stmt,
3630                    msg: "unclosed block comment".to_string(),
3631                    line: 0,
3632                    col: 0,
3633                    kind: None,
3634                })?;
3635            }
3636            TokKind::Punct('#') => {
3637                // `#` comment runs to a newline or the part end.
3638                while j < part.len() && !matches!(&part[j].kind, TokKind::Newline) {
3639                    j += 1;
3640                }
3641            }
3642            _ => return Ok(None),
3643        }
3644    }
3645    // `guard_key_char` exclusions: the single-char set plus the
3646    // comment opens (`//`, `/*`); lone `/` stays legal.
3647    if out.contains("//") || out.contains("/*") {
3648        return Ok(None);
3649    }
3650    if out
3651        .chars()
3652        .any(|c| matches!(c, ':' | '=' | '!' | ',' | '|' | '(' | ')' | ']' | '$'))
3653    {
3654        return Ok(None);
3655    }
3656    Ok(Some(out))
3657}
3658
3659/// Strict `INHERIT_ENV [...]` at an element or single-inner
3660/// position: bracket riding gapped with valid keys yields the
3661/// directive (trailing elements loop on outside); anything else
3662/// misses (`None`) and generic fails it in lowering.
3663/// Serves both levels so keys stay exact everywhere; slice 5 adds
3664/// only the prelude-order validation.
3665fn parse_inherit_env_at(
3666    toks: &[Tok],
3667    pos: usize,
3668    stmt: usize,
3669) -> Result<Option<(StepKind, usize)>, TokenError> {
3670    // The bracket rides gapped (`sep`); anything else misses and
3671    // generic fails it in lowering.
3672    let bracket = match toks.get(pos + 1) {
3673        Some(t)
3674            if !t.joint
3675                && matches!(
3676                    &t.kind,
3677                    TokKind::Group {
3678                        delim: GroupDelim::Bracket,
3679                        ..
3680                    }
3681                ) =>
3682        {
3683            Some(t)
3684        }
3685        _ => None,
3686    };
3687    let Some(bracket) = bracket else {
3688        return Ok(None);
3689    };
3690    let inner = match &bracket.kind {
3691        TokKind::Group { inner, .. } => inner,
3692        _ => unreachable!(),
3693    };
3694    match parse_inherit_keys(inner, stmt)? {
3695        Some(keys) => Ok(Some((StepKind::InheritEnv { keys }, 2))),
3696        None => Ok(None),
3697    }
3698}
3699
3700/// Parse a brace block body into steps: statements split and lower
3701/// recursively, each keeping its own guard. `mark` selects scope
3702/// marking: top-level guard-block bodies mark (each nesting level
3703/// bumps first/last); wrapper bodies
3704/// (`IF`/`FOR`/`WHILE`/`FUNC`/`REMOTE`/wrappers/io-blocks) never mark
3705/// (block-element lowering pins 0/0).
3706fn parse_body_steps(
3707    inner: &[Tok],
3708    stmt: usize,
3709    ctx: &ParseCtx,
3710    mark: bool,
3711) -> Result<Vec<Step>, TokenError> {
3712    // One function/import scope per braced body (mirroring the
3713    // runtime push/pop boundary): same-block
3714    // `FUNC` redefinition errors, nested shadowing stays allowed.
3715    // Errors abort the whole parse (frames discarded with it), so no
3716    // exit runs on failure.
3717    ctx.funcs.borrow_mut().push(HashSet::new());
3718    ctx.imports.borrow_mut().push(Vec::new());
3719    ctx.forward.borrow_mut().push(HashSet::new());
3720    // Nested splits count lines from the enclosing statement's line
3721    // (headers are single-line, so the brace shares it). Save and
3722    // restore the discipline around the loop: sibling bodies after
3723    // this one must see the enclosing line, not the last inner one.
3724    // (On error the parse aborts and the context is discarded.)
3725    let saved = *ctx.current_line.borrow();
3726    let mut out = Vec::new();
3727    let stmts = split_statements(inner, saved)?;
3728    predeclare_forward_funcs(&stmts, ctx);
3729    for s in &stmts {
3730        // The innermost statement owns error positions: record it for
3731        // nested splits and stamp failures that have none yet (deeper
3732        // frames stamp first, so this never overwrites real positions).
3733        *ctx.current_line.borrow_mut() = s.line;
3734        out.extend(
3735            lower_stmt_steps(s, stmt, ctx, true, mark).map_err(|e| stamp_pos(e, s.line, s.col))?,
3736        );
3737    }
3738    *ctx.current_line.borrow_mut() = saved;
3739    ctx.funcs.borrow_mut().pop();
3740    ctx.imports.borrow_mut().pop();
3741    ctx.forward.borrow_mut().pop();
3742    Ok(out)
3743}
3744
3745/// Single (non-block) `WITH_IO`: bindings plus an optional inner
3746/// command. `None` on shape miss (no/gapped bracket: generic fails
3747/// it in lowering). A brace in single-inner position is
3748/// the grammar's pending-guard error, never an io-block; a bare
3749/// bracket leaks the transient `WithIoBlock` into the body (probed).
3750fn parse_with_io_single(
3751    toks: &[Tok],
3752    pos: usize,
3753    stmt: usize,
3754    ctx: &ParseCtx,
3755) -> Result<Option<(StepKind, usize)>, TokenError> {
3756    let bracket = match toks.get(pos + 1) {
3757        // The bracket rides gapped (`sep`); anything else misses the
3758        // shape and generic fails it in lowering.
3759        Some(t)
3760            if !t.joint
3761                && matches!(
3762                    &t.kind,
3763                    TokKind::Group {
3764                        delim: GroupDelim::Bracket,
3765                        ..
3766                    }
3767                ) =>
3768        {
3769            t
3770        }
3771        _ => return Ok(None),
3772    };
3773    let inner = match &bracket.kind {
3774        TokKind::Group { inner, .. } => inner.clone(),
3775        _ => unreachable!(),
3776    };
3777    let bindings = match parse_io_bindings(&inner, stmt)? {
3778        Some(bindings) => bindings,
3779        None => return Ok(None),
3780    };
3781    let rest = pos + 2;
3782    // A brace directly after the bracket is the pending-guard error
3783    // in single-inner position (probed); templates fall to generic.
3784    if let Some(next) = toks.get(rest)
3785        && matches!(
3786            &next.kind,
3787            TokKind::Group {
3788                delim: GroupDelim::Brace,
3789                ..
3790            }
3791        )
3792        && !is_template_brace(next)
3793    {
3794        return Err(TokenError {
3795            stmt,
3796            msg: "'{' without a pending guard".to_string(),
3797            line: 0,
3798            col: 0,
3799            kind: None,
3800        });
3801    }
3802    if rest >= toks.len() {
3803        // Bare bracket: the transient block node leaks into wrapper
3804        // bodies (statement level never reaches
3805        // here; the splitter holds it for `{`).
3806        return Ok(Some((StepKind::WithIoBlock { bindings }, 2)));
3807    }
3808    // A joint follower misses the inner `sep`: the bracket stands
3809    // bare (probed `TIMEOUT 10s WITH_IO [..]ECHO hi` yields the
3810    // transient node) and trailing elements loop on outside.
3811    if toks[rest].joint {
3812        return Ok(Some((StepKind::WithIoBlock { bindings }, 2)));
3813    }
3814    let (cmd, used) = parse_single_inner(
3815        toks,
3816        rest,
3817        stmt,
3818        ctx,
3819        InnerRules {
3820            allow_await: false,
3821            allow_with_io: true,
3822        },
3823    )?;
3824    let span = lowering_ctx(stmt);
3825    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| TokenError {
3826        stmt,
3827        msg: e.to_string(),
3828        line: 0,
3829        col: 0,
3830        kind: None,
3831    })?;
3832    let kind = StepKind::WithIo {
3833        bindings,
3834        cmd: Box::new(cmd),
3835    };
3836    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
3837        stmt,
3838        msg: e.to_string(),
3839        line: 0,
3840        col: 0,
3841        kind: None,
3842    })?;
3843    Ok(Some((kind, 2 + used)))
3844}
3845
3846/// Single (non-block) `TIMEOUT`: duration plus one inner command.
3847/// `None` on shape miss (bad duration, missing/joint inner: generic
3848/// fails it in lowering). Blocks parse inline; the body
3849/// holds one step for single inners.
3850fn parse_timeout_single(
3851    toks: &[Tok],
3852    pos: usize,
3853    stmt: usize,
3854    ctx: &ParseCtx,
3855) -> Result<Option<(StepKind, usize)>, TokenError> {
3856    let Some((duration, dused)) = parse_timeout_duration_at(toks, pos + 1, stmt)? else {
3857        return Ok(None);
3858    };
3859    let rest = pos + 1 + dused;
3860    let Some(next) = toks.get(rest) else {
3861        // `TIMEOUT 10s` alone is a generic instruction (lowering
3862        // fails it, probed), never a bare wrapper.
3863        return Ok(None);
3864    };
3865    if next.joint {
3866        return Ok(None);
3867    }
3868    let body = if matches!(
3869        &next.kind,
3870        TokKind::Group {
3871            delim: GroupDelim::Brace,
3872            ..
3873        }
3874    ) && !is_template_brace(next)
3875    {
3876        let inner = match &next.kind {
3877            TokKind::Group { inner, .. } => inner.clone(),
3878            _ => unreachable!(),
3879        };
3880        let steps = parse_body_steps(&inner, stmt, ctx, false)?;
3881        (steps, 1)
3882    } else {
3883        let (cmd, used) = parse_single_inner(
3884            toks,
3885            rest,
3886            stmt,
3887            ctx,
3888            InnerRules {
3889                allow_await: true,
3890                allow_with_io: true,
3891            },
3892        )?;
3893        (
3894            vec![Step {
3895                guard: None,
3896                kind: cmd,
3897                scope_enter: 0,
3898                scope_exit: 0,
3899                line: 0,
3900                col: 0,
3901            }],
3902            used,
3903        )
3904    };
3905    let kind = StepKind::Timeout {
3906        duration,
3907        body: body.0,
3908    };
3909    let span = lowering_ctx(stmt);
3910    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
3911        stmt,
3912        msg: e.to_string(),
3913        line: 0,
3914        col: 0,
3915        kind: None,
3916    })?;
3917    Ok(Some((kind, 1 + dused + body.1)))
3918}
3919
3920/// Single (non-block) `ISOLATED`: one inner command or block; the
3921/// body rewrites nested `INHERIT_ENV` through the shared pass.
3922/// `None` on shape miss (missing/joint inner: generic fails it).
3923fn parse_isolated_single(
3924    toks: &[Tok],
3925    pos: usize,
3926    stmt: usize,
3927    ctx: &ParseCtx,
3928) -> Result<Option<(StepKind, usize)>, TokenError> {
3929    let Some(next) = toks.get(pos + 1) else {
3930        return Ok(None);
3931    };
3932    if next.joint {
3933        return Ok(None);
3934    }
3935    let (mut body, used) = if matches!(
3936        &next.kind,
3937        TokKind::Group {
3938            delim: GroupDelim::Brace,
3939            ..
3940        }
3941    ) && !is_template_brace(next)
3942    {
3943        let inner = match &next.kind {
3944            TokKind::Group { inner, .. } => inner.clone(),
3945            _ => unreachable!(),
3946        };
3947        (parse_body_steps(&inner, stmt, ctx, false)?, 1)
3948    } else {
3949        let (cmd, used) = parse_single_inner(
3950            toks,
3951            pos + 1,
3952            stmt,
3953            ctx,
3954            InnerRules {
3955                allow_await: true,
3956                allow_with_io: true,
3957            },
3958        )?;
3959        (
3960            vec![Step {
3961                guard: None,
3962                kind: cmd,
3963                scope_enter: 0,
3964                scope_exit: 0,
3965                line: 0,
3966                col: 0,
3967            }],
3968            used,
3969        )
3970    };
3971    crate::commands::rewrite_isolated_inherit(&mut body);
3972    Ok(Some((StepKind::Isolated { body }, 1 + used)))
3973}
3974
3975/// Single (non-block) `ASYNC`: one inner command or block (blocks
3976/// admit a joint brace, like `async_statement_block`'s `sep?`).
3977/// Top-level `WITH_IO` steps fail through the shared reject; the
3978/// `LET` path never scans (probed: it accepts). `None` on shape
3979/// miss (missing/joint-single inner: generic fails it).
3980fn parse_async_single(
3981    toks: &[Tok],
3982    pos: usize,
3983    stmt: usize,
3984    ctx: &ParseCtx,
3985) -> Result<Option<(StepKind, usize)>, TokenError> {
3986    let Some(next) = toks.get(pos + 1) else {
3987        return Ok(None);
3988    };
3989    // Block form admits a joint brace (`ASYNC{...}`, probed); the
3990    // single form needs its `sep`.
3991    if matches!(
3992        &next.kind,
3993        TokKind::Group {
3994            delim: GroupDelim::Brace,
3995            ..
3996        }
3997    ) && !is_template_brace(next)
3998    {
3999        let inner = match &next.kind {
4000            TokKind::Group { inner, .. } => inner.clone(),
4001            _ => unreachable!(),
4002        };
4003        let body = parse_body_steps(&inner, stmt, ctx, false)?;
4004        let span = lowering_ctx(stmt);
4005        crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| TokenError {
4006            stmt,
4007            msg: e.to_string(),
4008            line: 0,
4009            col: 0,
4010            kind: None,
4011        })?;
4012        let kind = StepKind::AsyncBlock { body };
4013        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
4014            stmt,
4015            msg: e.to_string(),
4016            line: 0,
4017            col: 0,
4018            kind: None,
4019        })?;
4020        return Ok(Some((kind, 2)));
4021    }
4022    if next.joint {
4023        return Ok(None);
4024    }
4025    let (cmd, used) = parse_single_inner(
4026        toks,
4027        pos + 1,
4028        stmt,
4029        ctx,
4030        InnerRules {
4031            allow_await: false,
4032            allow_with_io: false,
4033        },
4034    )?;
4035    let body = vec![Step {
4036        guard: None,
4037        kind: cmd,
4038        scope_enter: 0,
4039        scope_exit: 0,
4040        line: 0,
4041        col: 0,
4042    }];
4043    let span = lowering_ctx(stmt);
4044    crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| TokenError {
4045        stmt,
4046        msg: e.to_string(),
4047        line: 0,
4048        col: 0,
4049        kind: None,
4050    })?;
4051    let kind = StepKind::AsyncBlock { body };
4052    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
4053        stmt,
4054        msg: e.to_string(),
4055        line: 0,
4056        col: 0,
4057        kind: None,
4058    })?;
4059    Ok(Some((kind, 1 + used)))
4060}
4061
4062// ---- Block statements, directives, REMOTE ----
4063// `IF`/`FOR`/`WHILE`/`FUNC` parse their headers token-natively with
4064// miss-to-generic fallback (the grammar's committed `instruction`
4065// path); bodies lower recursively with pushed scopes. `TYPE` builds
4066// aliases through a maximal type-shape match; `IMPORT`/`EXPORT` are
4067// zero-step frame/table directives; `REMOTE` validates targets,
4068// bindings, bodies, and outer-call containment through the shared
4069// validators. Guard blocks fold guards with scope markers at top
4070// level and mirror the nested quirk formula in bodies. A whole-script
4071// post-pass runs the shared validations (prelude order, COPY
4072// placement, EXPORT membership).
4073
4074/// Uppercase identifier mirror (`func_ident`, `type_name`,
4075/// `import_module`): ASCII upper start, upper/digit/`_` rest.
4076fn is_upper_ident(w: &str) -> bool {
4077    !w.is_empty()
4078        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
4079        && w.chars()
4080            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
4081}
4082
4083/// Lowercase identifier mirror (`field_name`): ASCII lower start,
4084/// lower/digit/`_` rest.
4085fn is_lower_ident(w: &str) -> bool {
4086    !w.is_empty()
4087        && w.chars().next().is_some_and(|c| c.is_ascii_lowercase())
4088        && w.chars()
4089            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
4090}
4091
4092/// `$name` with gapless adjacency (atomic `dollar_ident`); `None` on
4093/// shape miss (the caller falls back to generic, which fails in
4094/// lowering like the grammar's committed `instruction`).
4095fn peek_dollar_var(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
4096    match (toks.get(pos), toks.get(pos + 1)) {
4097        (Some(dollar), Some(name))
4098            if matches!(&dollar.kind, TokKind::Punct('$'))
4099                && name.joint
4100                && matches!(&name.kind, TokKind::Word(w) if is_ident_word(w)) =>
4101        {
4102            match &name.kind {
4103                TokKind::Word(w) => Some((w.clone(), 2)),
4104                _ => unreachable!(),
4105            }
4106        }
4107        _ => None,
4108    }
4109}
4110
4111/// Skip statement-level newlines (multi-line `<...>` shapes ride
4112/// them into the body) before the next type token. Narrower than
4113/// `gap_nl` on purpose: comments keep failing here exactly like
4114/// single-line shapes, so only the separator moves.
4115fn skip_type_nl(toks: &[Tok], mut p: usize) -> usize {
4116    while matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Newline)) {
4117        p += 1;
4118    }
4119    p
4120}
4121
4122/// Maximal `type_tag` match over toks (non-atomic: gaps free
4123/// everywhere): atoms with `<>` args, `|` unions, `name?:` fields.
4124/// Returns the exclusive end index, or `None` on shape miss.
4125fn parse_type_shape(toks: &[Tok], pos: usize) -> Option<usize> {
4126    let mut p = parse_type_atom(toks, skip_type_nl(toks, pos))?;
4127    loop {
4128        let q = skip_type_nl(toks, p);
4129        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('|'))) {
4130            return Some(p);
4131        }
4132        p = parse_type_atom(toks, skip_type_nl(toks, q + 1))?;
4133    }
4134}
4135
4136fn parse_type_atom(toks: &[Tok], pos: usize) -> Option<usize> {
4137    let pos = skip_type_nl(toks, pos);
4138    match toks.get(pos).map(|t| &t.kind) {
4139        Some(TokKind::Word(w)) if is_upper_ident(w) => {}
4140        _ => return None,
4141    }
4142    let mut p = skip_type_nl(toks, pos + 1);
4143    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('<'))) {
4144        p = parse_type_args(toks, skip_type_nl(toks, p + 1))?;
4145        p = skip_type_nl(toks, p);
4146        if !matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('>'))) {
4147            return None;
4148        }
4149        p += 1;
4150    }
4151    Some(p)
4152}
4153
4154fn parse_type_args(toks: &[Tok], pos: usize) -> Option<usize> {
4155    let mut p = parse_type_field(toks, skip_type_nl(toks, pos))?;
4156    loop {
4157        let q = skip_type_nl(toks, p);
4158        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(','))) {
4159            return Some(p);
4160        }
4161        p = parse_type_field(toks, skip_type_nl(toks, q + 1))?;
4162    }
4163}
4164
4165fn parse_type_field(toks: &[Tok], pos: usize) -> Option<usize> {
4166    let mut p = skip_type_nl(toks, pos);
4167    // Optional `name?:` prefix (lowercase names only, like the
4168    // grammar's `field_name`).
4169    if let Some(TokKind::Word(w)) = toks.get(p).map(|t| &t.kind)
4170        && is_lower_ident(w)
4171    {
4172        let mut q = skip_type_nl(toks, p + 1);
4173        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('?'))) {
4174            q = skip_type_nl(toks, q + 1);
4175        }
4176        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4177            p = skip_type_nl(toks, q + 1);
4178        }
4179    }
4180    parse_type_shape(toks, p)
4181}
4182
4183/// Single (non-block) `IF`: condition plus then-block with an
4184/// opportunistic `ELSE` chain (a malformed `ELSE` stays for the
4185/// element loop, which fails it in lowering exactly like the
4186/// grammar). `None` on shape miss (missing/joint-agnostic block or
4187/// unclassified bad condition: generic fails it); classified
4188/// expression failures (unknown/ambiguous callees) and inline-block
4189/// failures propagate (blocks lower here, so their errors surface
4190/// directly).
4191fn parse_if_at(
4192    toks: &[Tok],
4193    pos: usize,
4194    stmt: usize,
4195    ctx: &ParseCtx,
4196) -> Result<Option<(StepKind, usize)>, TokenError> {
4197    // Condition entry skips leading gap comments (`IF` uses `gap`).
4198    let mut lead = Cursor::expr(&toks[pos + 1..], stmt);
4199    lead.skip_gap();
4200    let mut cur = Cursor::expr(&toks[pos + 1 + lead.pos..], stmt);
4201    let cond = match parse_expr_checked(&mut cur, ctx) {
4202        Ok(expr) => expr,
4203        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4204        // Classified failures (unknown/ambiguous callees) name the
4205        // culprit instead of missing to the generic IF hint: the head
4206        // is unambiguously `IF`, so there is no alternative parse.
4207        Err(e) if e.kind.is_some() => return Err(e),
4208        Err(_) => return Ok(None),
4209    };
4210    let cond_end = pos + 1 + lead.pos + cur.pos;
4211    // Then-block: any gap (`gap` zero-width), never a template.
4212    let then_brace = match toks.get(cond_end) {
4213        Some(t)
4214            if matches!(
4215                &t.kind,
4216                TokKind::Group {
4217                    delim: GroupDelim::Brace,
4218                    ..
4219                }
4220            ) && !is_template_brace(t) =>
4221        {
4222            t
4223        }
4224        _ => return Ok(None),
4225    };
4226    let then_inner = match &then_brace.kind {
4227        TokKind::Group { inner, .. } => inner.clone(),
4228        _ => unreachable!(),
4229    };
4230    let then_body = parse_body_steps(&then_inner, stmt, ctx, false)?;
4231    let mut p = cond_end + 1;
4232    // Gap comments between the blocks and `ELSE` vanish (merge
4233    // junctions contribute newlines, crossed like `blank*`).
4234    {
4235        let mut gcur = Cursor::expr(&toks[p..], stmt);
4236        gcur.skip_gap_nl();
4237        p += gcur.pos;
4238    }
4239    let mut else_ifs = Vec::new();
4240    let mut else_body = None;
4241    loop {
4242        // `ELSE IF cond block`: any gaps (non-atomic chain).
4243        let is_else_if = matches!(
4244            toks.get(p).map(|t| &t.kind),
4245            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4246        ) && matches!(
4247            toks.get(p + 1).map(|t| &t.kind),
4248            Some(TokKind::Word(w)) if w == KEYWORD_IF
4249        );
4250        if is_else_if {
4251            let mut ecur = Cursor::expr(&toks[p + 2..], stmt);
4252            ecur.skip_gap();
4253            let econd = match parse_expr_checked(&mut ecur, ctx) {
4254                Ok(expr) => expr,
4255                Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4256                // Same classified-error rule as the `IF` head above:
4257                // an `ELSE IF` with a resolvable-but-unknown callee
4258                // names it instead of silently dropping the branch.
4259                Err(e) if e.kind.is_some() => return Err(e),
4260                Err(_) => break,
4261            };
4262            let ebrace = p + 2 + ecur.pos;
4263            let eblock_ok = matches!(
4264                toks.get(ebrace).map(|t| &t.kind),
4265                Some(TokKind::Group {
4266                    delim: GroupDelim::Brace,
4267                    ..
4268                })
4269            ) && toks.get(ebrace).is_some_and(|t| !is_template_brace(t));
4270            if !eblock_ok {
4271                break;
4272            }
4273            let einner = match &toks[ebrace].kind {
4274                TokKind::Group { inner, .. } => inner.clone(),
4275                _ => unreachable!(),
4276            };
4277            let ebody = parse_body_steps(&einner, stmt, ctx, false)?;
4278            else_ifs.push((Box::new(econd), ebody));
4279            p = ebrace + 1;
4280            // Gap comments before a further `ELSE` vanish too
4281            // (merge junctions contribute newlines).
4282            {
4283                let mut gcur = Cursor::expr(&toks[p..], stmt);
4284                gcur.skip_gap_nl();
4285                p += gcur.pos;
4286            }
4287            continue;
4288        }
4289        // `ELSE block`: same opportunism (a bare `ELSE` stays for
4290        // the loop, failing in lowering like the grammar).
4291        let is_else = matches!(
4292            toks.get(p).map(|t| &t.kind),
4293            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4294        ) && matches!(
4295            toks.get(p + 1).map(|t| &t.kind),
4296            Some(TokKind::Group {
4297                delim: GroupDelim::Brace,
4298                ..
4299            })
4300        ) && toks.get(p + 1).is_some_and(|t| !is_template_brace(t));
4301        if !is_else {
4302            break;
4303        }
4304        let einner = match &toks[p + 1].kind {
4305            TokKind::Group { inner, .. } => inner.clone(),
4306            _ => unreachable!(),
4307        };
4308        else_body = Some(parse_body_steps(&einner, stmt, ctx, false)?);
4309        p += 2;
4310        break;
4311    }
4312    let kind = StepKind::If {
4313        cond: Box::new(cond),
4314        then_body,
4315        else_ifs,
4316        else_body,
4317    };
4318    Ok(Some((kind, p - pos)))
4319}
4320
4321/// Single (non-block) `FOR`: `$var[: TYPE] (, $var[: TYPE])? IN
4322/// expr` plus block. Header shapes miss to generic (a third variable,
4323/// a missing block, a bad name all fail in lowering like the
4324/// grammar); completed headers validate counts and key types loudly.
4325/// Expression failures from inline blocks propagate (blocks lower
4326/// here); other expression failures miss (generic fails them like a
4327/// committed `instruction` would).
4328fn parse_for_at(
4329    toks: &[Tok],
4330    pos: usize,
4331    stmt: usize,
4332    ctx: &ParseCtx,
4333) -> Result<Option<(StepKind, usize)>, TokenError> {
4334    let mut p = pos + 1;
4335    let mut idents = Vec::new();
4336    let mut types = Vec::new();
4337    // First `$var[: TYPE]` (gapless `$var`; gaps free elsewhere).
4338    let Some((var1, _)) = peek_dollar_var(toks, p) else {
4339        return Ok(None);
4340    };
4341    idents.push(var1);
4342    p += 2;
4343    let mut cur = Cursor::expr(&toks[p..], stmt);
4344    cur.skip_gap();
4345    p += cur.pos;
4346    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4347        p += 1;
4348        let mut tcur = Cursor::expr(&toks[p..], stmt);
4349        tcur.skip_gap();
4350        let tstart = p + tcur.pos;
4351        let Some(tend) = parse_type_shape(toks, tstart) else {
4352            return Ok(None);
4353        };
4354        // `render_type_region` canonicalizes (shared spelling).
4355        types.push(render_type_region(&toks[tstart..tend], stmt)?);
4356        p = tend;
4357    }
4358    // Optional `, $var2[: TYPE2]`.
4359    {
4360        let mut ccur = Cursor::expr(&toks[p..], stmt);
4361        ccur.skip_gap();
4362        if matches!(
4363            ccur.toks.get(ccur.pos).map(|t| &t.kind),
4364            Some(TokKind::Punct(','))
4365        ) {
4366            ccur.pos += 1;
4367            ccur.skip_gap();
4368            let base = p + ccur.pos;
4369            let Some((var2, _)) = peek_dollar_var(toks, base) else {
4370                return Ok(None);
4371            };
4372            idents.push(var2);
4373            let mut q = base + 2;
4374            let mut qcur = Cursor::expr(&toks[q..], stmt);
4375            qcur.skip_gap();
4376            q += qcur.pos;
4377            if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4378                q += 1;
4379                let mut tcur = Cursor::expr(&toks[q..], stmt);
4380                tcur.skip_gap();
4381                let tstart = q + tcur.pos;
4382                let Some(tend) = parse_type_shape(toks, tstart) else {
4383                    return Ok(None);
4384                };
4385                types.push(render_type_region(&toks[tstart..tend], stmt)?);
4386                q = tend;
4387            }
4388            p = q;
4389        }
4390    }
4391    // `IN expr block`.
4392    {
4393        let mut icur = Cursor::expr(&toks[p..], stmt);
4394        icur.skip_gap();
4395        if !matches!(
4396            icur.toks.get(icur.pos).map(|t| &t.kind),
4397            Some(TokKind::Word(w)) if w == KEYWORD_IN
4398        ) {
4399            return Ok(None);
4400        }
4401        icur.pos += 1;
4402        p += icur.pos;
4403    }
4404    let mut ecur = Cursor::expr(&toks[p..], stmt);
4405    ecur.skip_gap();
4406    let in_expr = match parse_expr_checked(&mut ecur, ctx) {
4407        Ok(expr) => expr,
4408        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4409        // Classified failures name the callee: `FOR ... IN` is
4410        // committed once the header matched this far.
4411        Err(e) if e.kind.is_some() => return Err(e),
4412        Err(_) => return Ok(None),
4413    };
4414    p += ecur.pos;
4415    let block_ok = matches!(
4416        toks.get(p).map(|t| &t.kind),
4417        Some(TokKind::Group {
4418            delim: GroupDelim::Brace,
4419            ..
4420        })
4421    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4422    if !block_ok {
4423        return Ok(None);
4424    }
4425    let inner = match &toks[p].kind {
4426        TokKind::Group { inner, .. } => inner.clone(),
4427        _ => unreachable!(),
4428    };
4429    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4430    p += 1;
4431    if idents.len() != types.len() {
4432        return Err(TokenError {
4433            stmt,
4434            msg: format!(
4435                "FOR requires explicit types: FOR $item: TYPE IN <expr> (got {} vars, {} types)",
4436                idents.len(),
4437                types.len()
4438            ),
4439            line: 0,
4440            col: 0,
4441            kind: Some(ParseErrorKind::Validation {
4442                command: KEYWORD_FOR.to_string(),
4443            }),
4444        });
4445    }
4446    let (key_var, key_type, var, var_type) = match idents.len() {
4447        1 => (
4448            None,
4449            None,
4450            idents.into_iter().next().unwrap_or_default(),
4451            types.into_iter().next().unwrap_or_default(),
4452        ),
4453        2 => {
4454            let mut iv = idents.into_iter();
4455            let mut tv = types.into_iter();
4456            (
4457                Some(iv.next().unwrap_or_default()),
4458                Some(tv.next().unwrap_or_default()),
4459                iv.next().unwrap_or_default(),
4460                tv.next().unwrap_or_default(),
4461            )
4462        }
4463        _ => {
4464            return Err(TokenError {
4465                stmt,
4466                msg: "FOR requires one or two variables".to_string(),
4467                line: 0,
4468                col: 0,
4469                kind: Some(ParseErrorKind::Validation {
4470                    command: KEYWORD_FOR.to_string(),
4471                }),
4472            });
4473        }
4474    };
4475    if let Some(kt) = &key_type
4476        && kt != crate::TypeTag::String.name()
4477        && kt != crate::TypeTag::Int.name()
4478    {
4479        return Err(TokenError {
4480            stmt,
4481            msg: format!("FOR key variable must be INT or STRING, got {kt}"),
4482            line: 0,
4483            col: 0,
4484            kind: Some(ParseErrorKind::Validation {
4485                command: KEYWORD_FOR.to_string(),
4486            }),
4487        });
4488    }
4489    let kind = StepKind::For {
4490        key_var,
4491        key_type,
4492        var,
4493        var_type,
4494        in_expr,
4495        body,
4496    };
4497    Ok(Some((kind, p - pos)))
4498}
4499
4500/// Single (non-block) `WHILE`: condition plus block. `None` on
4501/// shape miss (missing block: generic fails it); classified
4502/// expression failures and inline-block failures propagate, other
4503/// expression failures miss (generic fails them like a committed
4504/// `instruction` would).
4505/// No leading gap-skip: `WHILE` takes `sep`, so a joint follower
4506/// never reaches here with a valid shape... (misses fall through
4507/// the same way regardless).
4508fn parse_while_single(
4509    toks: &[Tok],
4510    pos: usize,
4511    stmt: usize,
4512    ctx: &ParseCtx,
4513) -> Result<Option<(StepKind, usize)>, TokenError> {
4514    let mut cur = Cursor::expr(&toks[pos + 1..], stmt);
4515    let cond = match parse_expr_checked(&mut cur, ctx) {
4516        Ok(expr) => expr,
4517        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4518        // Same rule as `IF`: the head is unambiguous, so classified
4519        // failures name the culprit instead of the generic hint.
4520        Err(e) if e.kind.is_some() => return Err(e),
4521        Err(_) => return Ok(None),
4522    };
4523    let brace = pos + 1 + cur.pos;
4524    let block_ok = matches!(
4525        toks.get(brace).map(|t| &t.kind),
4526        Some(TokKind::Group {
4527            delim: GroupDelim::Brace,
4528            ..
4529        })
4530    ) && toks.get(brace).is_some_and(|t| !is_template_brace(t));
4531    if !block_ok {
4532        return Ok(None);
4533    }
4534    let inner = match &toks[brace].kind {
4535        TokKind::Group { inner, .. } => inner.clone(),
4536        _ => unreachable!(),
4537    };
4538    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4539    let kind = StepKind::While {
4540        cond: Box::new(cond),
4541        body,
4542    };
4543    Ok(Some((kind, brace + 1 - pos)))
4544}
4545
4546/// Validated `FUNC` header shape: name, parameter list, return type,
4547/// and body block. Single owner for the header grammar, shared by
4548/// `parse_func_at` and `predeclare_forward_funcs` so the hoist set can
4549/// never admit what the real path rejects (or reject what it admits).
4550/// Returns the header plus tokens consumed; `None` on shape miss
4551/// (lowercase names, missing paren/colon/block all miss to generic,
4552/// probed). Content failures (bad params, missing return type, bad
4553/// trailing tokens) carry the bare diagnostic: `parse_func_at`
4554/// adorns it, pre-declaration drops it (silent skip, letting the main
4555/// pass own the error).
4556struct FuncHeader {
4557    name: String,
4558    params: Vec<(String, String, bool)>,
4559    return_type: String,
4560    block: usize,
4561}
4562
4563#[allow(clippy::too_many_lines)]
4564fn parse_func_header(
4565    toks: &[Tok],
4566    pos: usize,
4567    stmt: usize,
4568    keyword: &str,
4569) -> Result<Option<(FuncHeader, usize)>, String> {
4570    // Head word: `FUNC` (callers normalize `ASYNC FUNC` to `pos`
4571    // first, so the header shape stays prefix-free).
4572    if !matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC) {
4573        return Ok(None);
4574    }
4575    // Name: UPPERCASE ident (lowercase misses to generic, probed).
4576    let def_name = match toks.get(pos + 1).map(|t| &t.kind) {
4577        Some(TokKind::Word(w))
4578            if crate::resolve::check_func_ident(&lowering_ctx(stmt), w).is_ok() =>
4579        {
4580            w.clone()
4581        }
4582        _ => return Ok(None),
4583    };
4584    // Paren group at any gap (`gap` zero-width): params live inside
4585    // its inner tokens, parsed with `gap_nl` discipline (newlines ride
4586    // free like call args and generics, via the shared helper).
4587    let mut p = pos + 2;
4588    let paren_inner = match toks.get(p).map(|t| &t.kind) {
4589        Some(TokKind::Group {
4590            delim: GroupDelim::Paren,
4591            inner,
4592            ..
4593        }) => inner.clone(),
4594        _ => return Ok(None),
4595    };
4596    p += 1;
4597    let mut params = Vec::new();
4598    let mut seen_optional = false;
4599    {
4600        let mut pcur = Cursor::expr(&paren_inner, stmt);
4601        pcur.skip_gap_nl();
4602        if !pcur.done() {
4603            loop {
4604                let base = pcur.pos;
4605                let Some((pname, _)) = peek_dollar_var(&paren_inner, base) else {
4606                    return Err(format!(
4607                        "FUNC {def_name} params must be `$name: TYPE` separated by commas"
4608                    ));
4609                };
4610                pcur.pos = base + 2;
4611                pcur.skip_gap_nl();
4612                // Optional params carry `?` before the colon
4613                // (`$flag?: BOOL`); all params are otherwise required.
4614                let optional = pcur.eat_punct('?');
4615                pcur.skip_gap_nl();
4616                if !pcur.eat_punct(':') {
4617                    return Err(format!(
4618                        "FUNC {def_name} param `${pname}` needs `: TYPE` after the name"
4619                    ));
4620                }
4621                pcur.skip_gap_nl();
4622                let tstart = pcur.pos;
4623                let Some(tend) = parse_type_shape(&paren_inner, tstart) else {
4624                    let got = match paren_inner.get(tstart).map(|tok| &tok.kind) {
4625                        Some(TokKind::Word(word)) => format!("; got `{word}`"),
4626                        _ => String::new(),
4627                    };
4628                    return Err(format!(
4629                        "FUNC {def_name} param `${pname}` needs an uppercase type after `:` (e.g. STRING, INT, BOOL){got}"
4630                    ));
4631                };
4632                // Post-match the span holds words/puncts only, so the
4633                // shared renderer cannot fail; stay failed regardless.
4634                let ptype =
4635                    render_type_region(&paren_inner[tstart..tend], stmt).unwrap_or_default();
4636                if optional {
4637                    seen_optional = true;
4638                } else if seen_optional {
4639                    return Err(format!(
4640                        "FUNC {def_name} optional ? params must be trailing: `${pname}` follows an optional param"
4641                    ));
4642                }
4643                params.push((pname, ptype, optional));
4644                pcur.pos = tend;
4645                pcur.skip_gap_nl();
4646                if pcur.eat_punct(',') {
4647                    pcur.skip_gap_nl();
4648                    // Trailing comma misses (a param must follow).
4649                    if pcur.done() {
4650                        return Err(format!(
4651                            "FUNC {def_name} params must not end with a trailing comma"
4652                        ));
4653                    }
4654                    continue;
4655                }
4656                break;
4657            }
4658            // Trailing junk (including newlines) misses to generic.
4659            pcur.skip_gap_nl();
4660            if !pcur.done() {
4661                return Err(format!(
4662                    "FUNC {def_name} params must be `$name: TYPE` separated by commas"
4663                ));
4664            }
4665        }
4666    }
4667    // Mandatory return annotation: FUNC NAME(...): RET { ... }.
4668    // After paren group, require gap-optional colon then type shape.
4669    // Missing colon after matched name+parens is a hard parse error
4670    // (no legacy fallback). Non-block tails (neither colon nor brace)
4671    // miss to generic (probed FUNC FOO() ECHO hi).
4672    let is_colon = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')));
4673    if !is_colon {
4674        let is_brace = matches!(
4675            toks.get(p).map(|t| &t.kind),
4676            Some(TokKind::Group {
4677                delim: GroupDelim::Brace,
4678                ..
4679            })
4680        ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4681        if is_brace {
4682            return Err(format!(
4683                "{keyword} {def_name} requires a return type : TYPE (e.g. : VOID, : STRING)"
4684            ));
4685        }
4686        return Ok(None);
4687    }
4688    let Some(ret_end) = parse_type_shape(toks, p + 1) else {
4689        return Err(format!(
4690            "{keyword} {def_name} requires a return type : TYPE after ':'"
4691        ));
4692    };
4693    let return_type = render_type_region(&toks[p + 1..ret_end], stmt)
4694        .map_err(|_| format!("{keyword} {def_name} requires a return type : TYPE after ':'"))?;
4695    let return_type = crate::canonicalize_spelling(&return_type);
4696    p = ret_end;
4697    // Block at any gap (never a template); missing blocks miss to
4698    // generic (probed FUNC FOO() ECHO hi).
4699    let block_ok = matches!(
4700        toks.get(p).map(|t| &t.kind),
4701        Some(TokKind::Group {
4702            delim: GroupDelim::Brace,
4703            ..
4704        })
4705    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4706    if !block_ok {
4707        return Ok(None);
4708    }
4709    Ok(Some((
4710        FuncHeader {
4711            name: def_name,
4712            params,
4713            return_type,
4714            block: p,
4715        },
4716        p + 1 - pos,
4717    )))
4718}
4719
4720/// Single (non-block) `FUNC`: name, parenthesized params, block. The
4721/// shape parses purely first (misses fall to generic, declaring
4722/// nothing — the grammar only lowers matched pairs); then the name
4723/// declares in the enclosing scope before the body lowers (so
4724/// recursion resolves), and the body pushes a fresh scope.
4725/// Duplicates, reserved shadows, and parameter dupes fail loudly.
4726fn parse_func_at(
4727    toks: &[Tok],
4728    pos: usize,
4729    stmt: usize,
4730    ctx: &ParseCtx,
4731    is_async: bool,
4732) -> Result<Option<(StepKind, usize)>, TokenError> {
4733    let keyword = if is_async { "ASYNC FUNC" } else { KEYWORD_FUNC };
4734    let fail = |msg: String| TokenError {
4735        stmt,
4736        msg,
4737        line: 0,
4738        col: 0,
4739        kind: Some(ParseErrorKind::Validation {
4740            command: KEYWORD_FUNC.to_string(),
4741        }),
4742    };
4743    // Phase 1 (pure shape) through the single header owner:
4744    // adorn content errors with the `FUNC` / `ASYNC FUNC` keyword,
4745    // miss to generic on shape miss exactly as before.
4746    let Some((header, used)) = parse_func_header(toks, pos, stmt, keyword).map_err(fail)? else {
4747        return Ok(None);
4748    };
4749    let FuncHeader {
4750        name: def_name,
4751        params,
4752        return_type,
4753        block: p,
4754    } = header;
4755    // Phase 2 (effects): reserved shadows and same-scope duplicates
4756    // fail at the definition line, verbatim.
4757    if ctx.reserved.contains(&def_name) || ctx.modules.reserved_base_names().contains(&def_name) {
4758        return Err(fail(format!(
4759            "FUNC {def_name} cannot shadow reserved function `{def_name}`"
4760        )));
4761    }
4762    if !ctx.declare_func(&def_name) {
4763        return Err(fail(format!(
4764            "duplicate function `{def_name}` in same scope"
4765        )));
4766    }
4767    let mut seen = HashSet::new();
4768    for (pname, _, _) in &params {
4769        if !seen.insert(pname.clone()) {
4770            return Err(fail(format!(
4771                "FUNC {def_name} declares duplicate parameter ${pname}"
4772            )));
4773        }
4774    }
4775    let inner = match &toks[p].kind {
4776        TokKind::Group { inner, .. } => inner.clone(),
4777        _ => unreachable!(),
4778    };
4779    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4780    let kind = StepKind::FuncDef {
4781        name: def_name,
4782        params,
4783        return_type,
4784        is_async,
4785        body,
4786        docs: None,
4787    };
4788    Ok(Some((kind, used)))
4789}
4790
4791/// `REMOTE` header bindings `[$var, env:KEY]` over a bracket
4792/// group's inner tokens: comma-separated, newlines and comments free
4793/// like `gap_nl`. `$`+name and `env`+`:`+key all ride gapless (the
4794/// enclosing rule is compound-atomic). Empty lists parse (probed);
4795/// anything else misses the shape (`None`: generic fails it like
4796/// the grammar's dropped optional).
4797#[allow(clippy::type_complexity)]
4798fn parse_remote_bindings(
4799    inner: &[Tok],
4800    stmt: usize,
4801) -> Result<Option<(Vec<String>, Vec<String>)>, TokenError> {
4802    let _ = stmt;
4803    let mut parts: Vec<&[Tok]> = Vec::new();
4804    let mut start = 0;
4805    for (i, tok) in inner.iter().enumerate() {
4806        if matches!(&tok.kind, TokKind::Punct(',')) {
4807            parts.push(&inner[start..i]);
4808            start = i + 1;
4809        }
4810    }
4811    parts.push(&inner[start..]);
4812    // An empty list (`[]`, whitespace/comment-only) holds no bindings.
4813    if parts.len() == 1
4814        && parts[0]
4815            .iter()
4816            .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
4817    {
4818        return Ok(Some((Vec::new(), Vec::new())));
4819    }
4820    let mut vars = Vec::new();
4821    let mut env = Vec::new();
4822    for part in parts {
4823        // Edges admit gaps, newlines, and comments, like `gap_nl`.
4824        let mut part = part;
4825        while matches!(
4826            part.first().map(|t| &t.kind),
4827            Some(TokKind::Newline | TokKind::Comment(_))
4828        ) {
4829            part = &part[1..];
4830        }
4831        while matches!(
4832            part.last().map(|t| &t.kind),
4833            Some(TokKind::Newline | TokKind::Comment(_))
4834        ) {
4835            part = &part[..part.len() - 1];
4836        }
4837        // `$var`: gapless `$` + ident.
4838        if matches!(part.first().map(|t| &t.kind), Some(TokKind::Punct('$'))) && part.len() == 2 {
4839            if part[1].joint
4840                && let TokKind::Word(w) = &part[1].kind
4841                && is_ident_word(w)
4842            {
4843                vars.push(w.clone());
4844                continue;
4845            }
4846            return Ok(None);
4847        }
4848        // `env:KEY`: gapless triple with an uppercase key.
4849        if part.len() == 3
4850            && matches!(&part[0].kind, TokKind::Word(w) if w == "env")
4851            && matches!(&part[1].kind, TokKind::Punct(':'))
4852            && part[1].joint
4853            && part[2].joint
4854        {
4855            if let TokKind::Word(k) = &part[2].kind
4856                && is_env_key(k)
4857            {
4858                env.push(k.clone());
4859                continue;
4860            }
4861            return Ok(None);
4862        }
4863        return Ok(None);
4864    }
4865    Ok(Some((vars, env)))
4866}
4867
4868/// `IMPORT` statement at `pos` (#115): module form (`IMPORT MOD`,
4869/// `IMPORT [A, B]`), file form (`IMPORT "p" AS A`,
4870/// `IMPORT ["p" AS A]`), mixed/multi forms
4871/// (`IMPORT [STD, "p" AS A, "q" AS B]`, multi-line included), and
4872/// selective harvests (`IMPORT [[F, G FROM "p" (AS A)?]]`).
4873/// Returns module names plus `ImportFile`/`ImportFuncs` steps in source
4874/// order, plus tokens consumed (relative to `pos`), or `None` on shape
4875/// miss (generic lowering fails it like the grammar). Validation is
4876/// hard: unknown modules, bad names, collisions, templates, and remote
4877/// URLs fail here, and validated entries register immediately
4878/// (modules, aliases, and bare harvest names share the innermost
4879/// frames).
4880type ImportEntries = (Vec<String>, Vec<StepKind>);
4881
4882fn parse_import_statement(
4883    toks: &[Tok],
4884    pos: usize,
4885    stmt: usize,
4886    ctx: &ParseCtx,
4887) -> Result<Option<(ImportEntries, usize)>, TokenError> {
4888    let fail = |msg: String| TokenError {
4889        stmt,
4890        msg,
4891        line: 0,
4892        col: 0,
4893        kind: Some(ParseErrorKind::Validation {
4894            command: KEYWORD_IMPORT.to_string(),
4895        }),
4896    };
4897    let next = match toks.get(pos + 1) {
4898        // `sep` after `IMPORT`: joint followers miss.
4899        Some(t) if !t.joint => t,
4900        _ => return Ok(None),
4901    };
4902    // Parse entries first, validate in source order after.
4903    enum RawEntry {
4904        Module(String),
4905        File {
4906            path: String,
4907            alias: String,
4908        },
4909        From {
4910            func_names: Vec<String>,
4911            type_names: Vec<String>,
4912            path: String,
4913            alias: Option<String>,
4914        },
4915    }
4916    let mut raw: Vec<RawEntry> = Vec::new();
4917    let used;
4918    if matches!(
4919        &next.kind,
4920        TokKind::Group {
4921            delim: GroupDelim::Brace,
4922            ..
4923        }
4924    ) {
4925        return Ok(None);
4926    }
4927    if let TokKind::Group {
4928        delim: GroupDelim::Bracket,
4929        inner,
4930        ..
4931    } = &next.kind
4932    {
4933        // Comma-separated entries, `ws` gaps (newlines ok inside and
4934        // around entries, comments MISS — `ws` admits neither).
4935        // Single-file multi-name harvests skip the split: in
4936        // `[TYPE A, TYPE B FROM "f"]` the first comma-part (`[TYPE A]`)
4937        // carries no FROM and is invalid alone, so the whole bracket
4938        // is one harvest (see `whole_file_harvest`).
4939        // Bare-multi hint: `[FOO, BAR FROM "f"]` reads FOO as a
4940        // module for back-compat (bare words stay modules in single
4941        // brackets). If that word is not a known module but a harvest
4942        // follows, fail fast naming the two valid spellings instead
4943        // of the misleading unknown-module error.
4944        let whole = whole_file_harvest(inner);
4945        if whole.is_none()
4946            && let Some(word) = single_bare_first_part(inner)
4947            && !ctx.modules.modules.contains_key(word)
4948            && has_top_level_from_after_comma(inner)
4949        {
4950            return Err(fail(format!(
4951                "unknown module `{word}`; to harvest multiple names qualify each kind (`IMPORT [FUNC FOO, FUNC BAR FROM \"f\"]`)"
4952            )));
4953        }
4954        let mut parts: Vec<&[Tok]> = Vec::new();
4955        if whole.is_some() {
4956            parts.push(inner);
4957        } else {
4958            let mut start = 0;
4959            for (i, tok) in inner.iter().enumerate() {
4960                if matches!(&tok.kind, TokKind::Punct(',')) {
4961                    parts.push(&inner[start..i]);
4962                    start = i + 1;
4963                }
4964            }
4965            parts.push(&inner[start..]);
4966        }
4967        for part in parts {
4968            let dense: Vec<&Tok> = part
4969                .iter()
4970                .filter(|t| !matches!(&t.kind, TokKind::Newline))
4971                .collect();
4972            // `[[F, G FROM "path" (AS ALIAS)?]]`: selective function
4973            // harvest. Anything else bracketed here misses.
4974            if let [bracket] = dense.as_slice()
4975                && let TokKind::Group {
4976                    delim: GroupDelim::Bracket,
4977                    inner,
4978                    ..
4979                } = &bracket.kind
4980            {
4981                let Some(HarvestImport {
4982                    func_names,
4983                    type_names,
4984                    path,
4985                    alias,
4986                }) = parse_from_entry(inner)
4987                else {
4988                    return Ok(None);
4989                };
4990                raw.push(RawEntry::From {
4991                    func_names,
4992                    type_names,
4993                    path,
4994                    alias,
4995                });
4996                continue;
4997            }
4998            // `[F FROM "path" (AS ALIAS)?]`: single harvest without
4999            // inner brackets. The `FROM` keyword is the discriminant
5000            // (module and file parts never contain a top-level one);
5001            // multi-name harvests keep `[[F, G FROM ...]]` so the comma
5002            // stays grouped inside its own scope.
5003            if dense.len() >= 3 {
5004                let owned: Vec<Tok> = dense.iter().map(|t| (*t).clone()).collect();
5005                if let Some(HarvestImport {
5006                    func_names,
5007                    type_names,
5008                    path,
5009                    alias,
5010                }) = parse_from_entry(&owned)
5011                {
5012                    raw.push(RawEntry::From {
5013                        func_names,
5014                        type_names,
5015                        path,
5016                        alias,
5017                    });
5018                    continue;
5019                }
5020            }
5021            match dense.as_slice() {
5022                [tok] => match &tok.kind {
5023                    TokKind::Word(w) if is_upper_ident(w) => {
5024                        raw.push(RawEntry::Module(w.clone()));
5025                    }
5026                    _ => return Ok(None),
5027                },
5028                [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5029                    let (
5030                        TokKind::Str { text, .. },
5031                        TokKind::Word(as_word),
5032                        TokKind::Word(alias_word),
5033                    ) = (&path_tok.kind, &as_tok.kind, &alias_tok.kind)
5034                    else {
5035                        return Ok(None);
5036                    };
5037                    if as_word != KEYWORD_AS {
5038                        return Ok(None);
5039                    }
5040                    raw.push(RawEntry::File {
5041                        path: text.clone(),
5042                        alias: alias_word.clone(),
5043                    });
5044                }
5045                _ => return Ok(None),
5046            }
5047        }
5048        if raw.is_empty() {
5049            return Ok(None);
5050        }
5051        used = 2;
5052    } else if let TokKind::Word(w) = &next.kind {
5053        // Bare `IMPORT MOD` (single module, probed).
5054        if !is_upper_ident(w) {
5055            return Ok(None);
5056        }
5057        raw.push(RawEntry::Module(w.clone()));
5058        used = 2;
5059    } else if let TokKind::Str { text, .. } = &next.kind {
5060        // Bare `IMPORT "path" AS ALIAS`.
5061        let (Some(as_tok), Some(alias_tok)) = (toks.get(pos + 2), toks.get(pos + 3)) else {
5062            return Ok(None);
5063        };
5064        if as_tok.joint || alias_tok.joint {
5065            return Ok(None);
5066        }
5067        let (TokKind::Word(as_word), TokKind::Word(alias_word)) = (&as_tok.kind, &alias_tok.kind)
5068        else {
5069            return Ok(None);
5070        };
5071        if as_word != KEYWORD_AS {
5072            return Ok(None);
5073        }
5074        raw.push(RawEntry::File {
5075            path: text.clone(),
5076            alias: alias_word.clone(),
5077        });
5078        used = 4;
5079    } else {
5080        return Ok(None);
5081    }
5082    // Validate in source order: unknown modules fail with the exact
5083    // backend message (sorted known list); file and harvest entries
5084    // validate hard (bad names, collisions, templates, remote URLs).
5085    let mut modules = Vec::new();
5086    let mut steps = Vec::new();
5087    for entry in raw {
5088        match entry {
5089            RawEntry::Module(module) => {
5090                if !ctx.modules.modules.contains_key(&module) {
5091                    let mut known: Vec<String> = ctx.modules.modules.keys().cloned().collect();
5092                    known.sort();
5093                    return Err(fail(format!(
5094                        "unknown module `{module}`; known modules: {}",
5095                        known.join(", ")
5096                    )));
5097                }
5098                ctx.import_into_frame(std::slice::from_ref(&module));
5099                modules.push(module);
5100            }
5101            RawEntry::File { path, alias } => {
5102                let (path, alias) = validate_file_import(&path, &alias, ctx).map_err(fail)?;
5103                steps.push(StepKind::ImportFile { path, alias });
5104            }
5105            RawEntry::From {
5106                func_names,
5107                type_names,
5108                path,
5109                alias,
5110            } => {
5111                let HarvestImport {
5112                    func_names,
5113                    type_names,
5114                    path,
5115                    alias,
5116                } = validate_from_import(&func_names, &type_names, &path, alias.as_deref(), ctx)
5117                    .map_err(fail)?;
5118                steps.push(StepKind::ImportFuncs {
5119                    path,
5120                    alias,
5121                    func_names,
5122                    type_names,
5123                });
5124            }
5125        }
5126    }
5127    Ok(Some(((modules, steps), used)))
5128}
5129
5130/// Single file import for value positions (#115): exactly one
5131/// `"path" AS ALIAS` entry and no modules. Anything else shaped like an
5132/// import is a hard error naming the restriction; shape misses return
5133/// `None` for the generic path.
5134fn parse_single_file_import(
5135    toks: &[Tok],
5136    pos: usize,
5137    stmt: usize,
5138    ctx: &ParseCtx,
5139) -> Result<Option<(String, String, usize)>, TokenError> {
5140    let Some(((modules, mut kinds), used)) = parse_import_statement(toks, pos, stmt, ctx)? else {
5141        return Ok(None);
5142    };
5143    if !modules.is_empty() || !matches!(kinds.as_slice(), [StepKind::ImportFile { .. }]) {
5144        return Err(TokenError {
5145            stmt,
5146            msg: if !modules.is_empty()
5147                || kinds
5148                    .iter()
5149                    .any(|k| matches!(k, StepKind::ImportFuncs { .. }))
5150            {
5151                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>]); modules and function harvests stay at statement level".to_string()
5152            } else {
5153                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>])"
5154                    .to_string()
5155            },
5156            line: 0,
5157            col: 0,
5158            kind: Some(ParseErrorKind::Validation {
5159                command: KEYWORD_IMPORT.to_string(),
5160            }),
5161        });
5162    }
5163    let Some(StepKind::ImportFile { path, alias }) = kinds.pop() else {
5164        unreachable!("length and variant checked above")
5165    };
5166    Ok(Some((path, alias, used)))
5167}
5168
5169/// One `EXPORT` name: an uppercase word with an optional joint
5170/// `::UPPER` tail. Returns the name and tokens consumed, or `None`
5171/// on shape miss.
5172fn parse_export_name(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
5173    let head = match toks.get(pos).map(|t| &t.kind) {
5174        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
5175        _ => return None,
5176    };
5177    let mut name = head;
5178    let mut used = 1;
5179    // Greedy-prefix `::tail` (atomic, like the grammar): a valid
5180    // tail joins, an invalid one stays trailing (failing downstream
5181    // exactly like the grammar's committed prefix).
5182    if matches!(
5183        toks.get(pos + 1).map(|t| &t.kind),
5184        Some(TokKind::Punct(':'))
5185    ) && toks.get(pos + 1).is_some_and(|t| t.joint)
5186        && matches!(
5187            toks.get(pos + 2).map(|t| &t.kind),
5188            Some(TokKind::Punct(':'))
5189        )
5190        && toks.get(pos + 2).is_some_and(|t| t.joint)
5191        && let Some(TokKind::Word(tail)) = toks.get(pos + 3).map(|t| &t.kind)
5192        && toks[pos + 3].joint
5193        && is_upper_ident(tail)
5194    {
5195        name.push_str(MODULE_SEPARATOR);
5196        name.push_str(tail);
5197        used = 4;
5198    }
5199    Some((name, used))
5200}
5201
5202/// One selective harvest (`[[F, G FROM "path" (AS ALIAS)?]]`): the
5203/// wanted function and type names plus the path and optional alias.
5204/// Bare names are functions; `TYPE`/`FUNC` prefixes select the kind
5205/// explicitly (`[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`).
5206struct HarvestImport {
5207    func_names: Vec<String>,
5208    type_names: Vec<String>,
5209    path: String,
5210    alias: Option<String>,
5211}
5212
5213/// One `[[F, G FROM "path" (AS ALIAS)?]]` entry: selective function
5214/// harvest with optional `TYPE`/`FUNC` qualifiers per name:
5215/// `[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`
5216/// (bare stays func for back-compat).
5217/// Returns the harvest, or `None` on shape miss (generic lowering fails
5218/// it). Name case is validated hard by the caller, like file aliases.
5219fn parse_from_entry(inner: &[Tok]) -> Option<HarvestImport> {
5220    let dense: Vec<&Tok> = inner
5221        .iter()
5222        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5223        .collect();
5224    let from = dense
5225        .iter()
5226        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5227    if from == 0 {
5228        return None;
5229    }
5230    // Names: comma-separated entries, each `NAME` (func) or
5231    // `TYPE NAME` / `FUNC NAME` (explicit kind for clarity).
5232    let mut func_names = Vec::new();
5233    let mut type_names = Vec::new();
5234    let mut start = 0;
5235    let head = &dense[..from];
5236    // Local helper: classify one comma-separated part.
5237    fn classify_part(part: &[&Tok]) -> Option<(bool, String)> {
5238        match part {
5239            [tok] => {
5240                let TokKind::Word(w) = &tok.kind else {
5241                    return None;
5242                };
5243                Some((false, w.clone()))
5244            }
5245            // `TYPE NAME` / `FUNC NAME`: the name must be `sep` (gapped
5246            // from the kind); the kind may be joint to a preceding `[`
5247            // or `,` (no space required there), so only the name's joint
5248            // flag matters.
5249            [kind_tok, name_tok] if !name_tok.joint => {
5250                let (TokKind::Word(kind), TokKind::Word(name)) = (&kind_tok.kind, &name_tok.kind)
5251                else {
5252                    return None;
5253                };
5254                if kind == KEYWORD_TYPE {
5255                    Some((true, name.clone()))
5256                } else if kind == KEYWORD_FUNC {
5257                    Some((false, name.clone()))
5258                } else {
5259                    None
5260                }
5261            }
5262            _ => None,
5263        }
5264    }
5265    for (i, tok) in head.iter().enumerate() {
5266        if matches!(&tok.kind, TokKind::Punct(',')) {
5267            let part = &head[start..i];
5268            let (is_type, name) = classify_part(part)?;
5269            if is_type {
5270                type_names.push(name);
5271            } else {
5272                func_names.push(name);
5273            }
5274            start = i + 1;
5275        }
5276    }
5277    let part = &head[start..];
5278    let (is_type, name) = classify_part(part)?;
5279    if is_type {
5280        type_names.push(name);
5281    } else {
5282        func_names.push(name);
5283    }
5284    // Tail: `"path"` or bare `MODULE` with an optional gapped `AS ALIAS`.
5285    // Quoted is a file path (module fallback only when no file matches);
5286    // bare is a host module (no file probe ambiguity).
5287    let tail = &dense[from + 1..];
5288    let path_text = |tok: &Tok| match &tok.kind {
5289        TokKind::Str { text, .. } => Some(text.clone()),
5290        TokKind::Word(w) if is_upper_ident(w) => Some(w.clone()),
5291        _ => None,
5292    };
5293    match tail {
5294        [path_tok] => {
5295            let text = path_text(path_tok)?;
5296            Some(HarvestImport {
5297                func_names,
5298                type_names,
5299                path: text,
5300                alias: None,
5301            })
5302        }
5303        [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5304            let text = path_text(path_tok)?;
5305            let (TokKind::Word(as_word), TokKind::Word(alias_word)) =
5306                (&as_tok.kind, &alias_tok.kind)
5307            else {
5308                return None;
5309            };
5310            if as_word != KEYWORD_AS {
5311                return None;
5312            }
5313            Some(HarvestImport {
5314                func_names,
5315                type_names,
5316                path: text,
5317                alias: Some(alias_word.clone()),
5318            })
5319        }
5320        _ => None,
5321    }
5322}
5323
5324/// First comma-part of a bracket when it is exactly one bare
5325/// uppercase word: the back-compat module reading. Anything else
5326/// (prefixed names, groups, multiple words) is not a bare module.
5327fn single_bare_first_part(inner: &[Tok]) -> Option<&str> {
5328    let end = inner
5329        .iter()
5330        .position(|t| matches!(&t.kind, TokKind::Punct(',')))
5331        .unwrap_or(inner.len());
5332    let mut words = inner[..end]
5333        .iter()
5334        .filter(|t| !matches!(&t.kind, TokKind::Newline));
5335    match (words.next(), words.next()) {
5336        (Some(tok), None) => match &tok.kind {
5337            TokKind::Word(w) if is_upper_ident(w) => Some(w.as_str()),
5338            _ => None,
5339        },
5340        _ => None,
5341    }
5342}
5343
5344/// Whether a top-level `FROM` follows the first top-level comma:
5345/// distinguishes a module-plus-harvest entry (`[STD, T FROM "f"]`)
5346/// from a bare word the author meant as a harvest name.
5347fn has_top_level_from_after_comma(inner: &[Tok]) -> bool {
5348    let mut seen_comma = false;
5349    for tok in inner {
5350        match &tok.kind {
5351            TokKind::Punct(',') => seen_comma = true,
5352            TokKind::Word(w) if seen_comma && w == KEYWORD_FROM => return true,
5353            _ => {}
5354        }
5355    }
5356    false
5357}
5358
5359/// Whole-bracket single-file harvest (`[TYPE A, TYPE B FROM "f"]`):
5360/// the comma-split would orphan `[TYPE A]` (no FROM, invalid alone),
5361/// so the entire bracket parses as one harvest. Only explicitly
5362/// prefixed names qualify: a bare word keeps its legacy module
5363/// reading, so `[STD, TYPE T FROM "f"]` still splits into a module
5364/// plus a harvest instead of harvesting STD as a function.
5365fn whole_file_harvest(inner: &[Tok]) -> Option<HarvestImport> {
5366    let owned: Vec<Tok> = inner.to_vec();
5367    let harvest = parse_from_entry(&owned)?;
5368    let dense: Vec<&Tok> = inner
5369        .iter()
5370        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5371        .collect();
5372    let from = dense
5373        .iter()
5374        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5375    let mut start = 0;
5376    for (i, tok) in dense[..from].iter().enumerate() {
5377        if matches!(&tok.kind, TokKind::Punct(',')) {
5378            if !is_prefixed_name(&dense[start..i]) {
5379                return None;
5380            }
5381            start = i + 1;
5382        }
5383    }
5384    if !is_prefixed_name(&dense[start..from]) {
5385        return None;
5386    }
5387    Some(harvest)
5388}
5389
5390/// One explicitly prefixed name (`TYPE NAME` / `FUNC NAME`): the name
5391/// stays gapped from its kind; the kind may joint to `[` or `,`.
5392fn is_prefixed_name(part: &[&Tok]) -> bool {
5393    match part {
5394        [kind_tok, name_tok] if !name_tok.joint => {
5395            matches!(
5396                (&kind_tok.kind, &name_tok.kind),
5397                (
5398                    TokKind::Word(kind),
5399                    TokKind::Word(_)
5400                ) if kind == KEYWORD_TYPE || kind == KEYWORD_FUNC
5401            )
5402        }
5403        _ => false,
5404    }
5405}
5406
5407/// Validate an `IMPORT` alias: hard errors (never shape misses) plus
5408/// registration into the innermost import frame.
5409fn validate_import_alias(alias: &str, ctx: &ParseCtx) -> Result<String, String> {
5410    if !is_upper_ident(alias) {
5411        return Err(format!(
5412            "IMPORT alias must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{alias}`"
5413        ));
5414    }
5415    if ctx.modules.modules.contains_key(alias) {
5416        return Err(format!(
5417            "IMPORT alias `{alias}` collides with module `{alias}`"
5418        ));
5419    }
5420    let (_, imports) = ctx.visible_snapshot();
5421    if imports.iter().any(|i| i == alias) {
5422        return Err(format!("duplicate IMPORT alias `{alias}`"));
5423    }
5424    ctx.import_into_frame(std::slice::from_ref(&alias.to_string()));
5425    Ok(alias.to_string())
5426}
5427
5428/// Validate an `IMPORT` path: hard errors, never shape misses.
5429fn validate_import_path(path: &str) -> Result<String, String> {
5430    if path.is_empty() {
5431        return Err("IMPORT path must not be empty".to_string());
5432    }
5433    if path.contains("{{") {
5434        return Err("IMPORT path must be a literal string (no {{ }} templates)".to_string());
5435    }
5436    if path.contains("://") {
5437        return Err(
5438            "remote imports are deferred to #270 (net: Run scripts from a remote URL)".to_string(),
5439        );
5440    }
5441    Ok(path.to_string())
5442}
5443
5444/// Validate a file-import path/alias pair: hard errors (never shape
5445/// misses) plus alias registration into the innermost import frame.
5446fn validate_file_import(
5447    path: &str,
5448    alias: &str,
5449    ctx: &ParseCtx,
5450) -> Result<(String, String), String> {
5451    let alias = validate_import_alias(alias, ctx)?;
5452    let path = validate_import_path(path)?;
5453    Ok((path, alias))
5454}
5455
5456/// Validate a `[[F, G FROM "path" (AS ALIAS)?]]` entry: hard errors
5457/// (never shape misses). Bare func names declare into the innermost
5458/// `FUNC` frame so calls resolve statically; the runtime defines them
5459/// (and fails unknown names there). Type names need no func-frame
5460/// declaration (types resolve through the global type directory);
5461/// the runtime validates them against the file's `EXPORT TYPE` list.
5462/// An alias registers like a file import.
5463fn validate_from_import(
5464    func_names: &[String],
5465    type_names: &[String],
5466    path: &str,
5467    alias: Option<&str>,
5468    ctx: &ParseCtx,
5469) -> Result<HarvestImport, String> {
5470    let path = validate_import_path(path)?;
5471    let mut out_func_names = Vec::with_capacity(func_names.len());
5472    for name in func_names {
5473        if !is_upper_ident(name) {
5474            return Err(format!(
5475                "IMPORT function names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
5476            ));
5477        }
5478        if ctx.reserved.contains(name) {
5479            return Err(format!("cannot shadow reserved function `{name}`"));
5480        }
5481        out_func_names.push(name.clone());
5482    }
5483    let mut out_type_names = Vec::with_capacity(type_names.len());
5484    for name in type_names {
5485        if !is_upper_ident(name) {
5486            return Err(format!(
5487                "IMPORT type names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
5488            ));
5489        }
5490        out_type_names.push(name.clone());
5491    }
5492    if out_func_names.is_empty() && out_type_names.is_empty() {
5493        return Err("IMPORT harvest needs at least one function or type name".to_string());
5494    }
5495    if let Some(alias) = alias {
5496        let alias = validate_import_alias(alias, ctx)?;
5497        Ok(HarvestImport {
5498            func_names: out_func_names,
5499            type_names: out_type_names,
5500            path,
5501            alias: Some(alias),
5502        })
5503    } else {
5504        for name in &out_func_names {
5505            if !ctx.declare_func(name) {
5506                return Err(format!("duplicate function `{name}` in same scope"));
5507            }
5508        }
5509        // Type harvests without alias land bare in the global type
5510        // directory: duplicates across files fail at import time
5511        // (different targets), not at parse time (targets need IO).
5512        Ok(HarvestImport {
5513            func_names: out_func_names,
5514            type_names: out_type_names,
5515            path,
5516            alias: None,
5517        })
5518    }
5519}
5520
5521/// One `EXPORT ...` name list: function names plus type names in
5522/// source order. Bare names are functions; explicit `TYPE`/`FUNC`
5523/// prefixes select the kind.
5524struct ExportNames {
5525    func_names: Vec<String>,
5526    type_names: Vec<String>,
5527}
5528
5529/// `EXPORT ...` names at `pos`: bracket list (strict, `ws` gaps:
5530/// newlines ok, comments miss) or a bare greedy-prefix name.
5531/// Supports explicit `TYPE`/`FUNC` qualifiers for clarity:
5532/// `EXPORT TYPE FOO`, `EXPORT TYPE [A, B]`, `EXPORT FUNC FOO`,
5533/// plus mixed `EXPORT [TYPE A, FUNC B, C]` (bare stays func).
5534/// Returns the name lists plus tokens consumed, or `None` on shape
5535/// miss (generic fails it in lowering like the grammar). Recording and
5536/// duplicate checks live with the caller (they need the guard and
5537/// level context).
5538fn parse_export_at(toks: &[Tok], pos: usize) -> Option<(ExportNames, usize)> {
5539    let next = match toks.get(pos + 1) {
5540        // `sep` after `EXPORT`: joint followers miss.
5541        Some(t) if !t.joint => t,
5542        _ => return None,
5543    };
5544    // Explicit `EXPORT TYPE ...` or `EXPORT FUNC ...` prefix.
5545    if let TokKind::Word(w) = &next.kind
5546        && (w == KEYWORD_TYPE || w == KEYWORD_FUNC)
5547    {
5548        let is_type = w == KEYWORD_TYPE;
5549        let after = match toks.get(pos + 2) {
5550            Some(t) if !t.joint => t,
5551            _ => return None,
5552        };
5553        if let TokKind::Group {
5554            delim: GroupDelim::Bracket,
5555            inner,
5556            ..
5557        } = &after.kind
5558        {
5559            let mut func_names = Vec::new();
5560            let mut type_names = Vec::new();
5561            for part in split_bracket_entries(inner) {
5562                let mut part = part;
5563                while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
5564                    part = &part[1..];
5565                }
5566                while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
5567                    part = &part[..part.len() - 1];
5568                }
5569                // A trailing comma leaves an empty final entry; it
5570                // carries no name and must not fail the list.
5571                if part.is_empty() {
5572                    continue;
5573                }
5574                let (name, used) = parse_export_name(part, 0)?;
5575                if used != part.len() {
5576                    return None;
5577                }
5578                if is_type {
5579                    type_names.push(name);
5580                } else {
5581                    func_names.push(name);
5582                }
5583            }
5584            if func_names.is_empty() && type_names.is_empty() {
5585                return None;
5586            }
5587            return Some((
5588                ExportNames {
5589                    func_names,
5590                    type_names,
5591                },
5592                3,
5593            ));
5594        }
5595        if matches!(&after.kind, TokKind::Group { .. }) {
5596            return None;
5597        }
5598        let (name, used) = parse_export_name(toks, pos + 2)?;
5599        // Bare name after TYPE/FUNC prefix must consume exactly one
5600        // name; trailing loops stay outside like the unprefixed case.
5601        // `used` counts from pos+2, so 1 name is valid.
5602        if used == 0 {
5603            return None;
5604        }
5605        if is_type {
5606            return Some((
5607                ExportNames {
5608                    func_names: Vec::new(),
5609                    type_names: vec![name],
5610                },
5611                2 + used,
5612            ));
5613        } else {
5614            return Some((
5615                ExportNames {
5616                    func_names: vec![name],
5617                    type_names: Vec::new(),
5618                },
5619                2 + used,
5620            ));
5621        }
5622    }
5623    if let TokKind::Group {
5624        delim: GroupDelim::Bracket,
5625        inner,
5626        ..
5627    } = &next.kind
5628    {
5629        let mut func_names = Vec::new();
5630        let mut type_names = Vec::new();
5631        for part in split_bracket_entries(inner) {
5632            let mut part = part;
5633            while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
5634                part = &part[1..];
5635            }
5636            while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
5637                part = &part[..part.len() - 1];
5638            }
5639            // A trailing comma leaves an empty final entry; it
5640            // carries no name and must not fail the list.
5641            if part.is_empty() {
5642                continue;
5643            }
5644            // Optional per-entry `TYPE`/`FUNC` prefix for mixed lists:
5645            // `EXPORT [TYPE A, FUNC B, C]` (bare stays func). The name
5646            // must be `sep` from the prefix; the prefix itself may be
5647            // joint to a preceding `[` or `,`, so only the name's joint
5648            // flag matters.
5649            let (is_type, rest) = match part {
5650                [first, second, ..]
5651                    if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_TYPE || w == KEYWORD_FUNC)
5652                        && !second.joint =>
5653                {
5654                    let is_t = matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_TYPE);
5655                    (is_t, &part[1..])
5656                }
5657                _ => (false, part),
5658            };
5659            // Exactly one name per entry (entries never trail).
5660            let (name, used) = parse_export_name(rest, 0)?;
5661            if used != rest.len() {
5662                return None;
5663            }
5664            if is_type {
5665                type_names.push(name);
5666            } else {
5667                func_names.push(name);
5668            }
5669        }
5670        if func_names.is_empty() && type_names.is_empty() {
5671            return None;
5672        }
5673        return Some((
5674            ExportNames {
5675                func_names,
5676                type_names,
5677            },
5678            2,
5679        ));
5680    }
5681    if matches!(&next.kind, TokKind::Group { .. }) {
5682        return None;
5683    }
5684    // Bare name (greedy `::` prefix; trailing loops outside). Bare
5685    // stays func for back-compat; `TYPE`/`FUNC` prefix selects above.
5686    parse_export_name(toks, pos + 1).map(|(name, used)| {
5687        (
5688            ExportNames {
5689                func_names: vec![name],
5690                type_names: Vec::new(),
5691            },
5692            1 + used,
5693        )
5694    })
5695}
5696
5697/// Split bracket inner tokens on top-level commas, preserving entries
5698/// for per-entry `TYPE`/`FUNC` handling. Newlines trim at the caller.
5699fn split_bracket_entries(inner: &[Tok]) -> Vec<&[Tok]> {
5700    let mut parts: Vec<&[Tok]> = Vec::new();
5701    let mut start = 0;
5702    for (i, tok) in inner.iter().enumerate() {
5703        if matches!(&tok.kind, TokKind::Punct(',')) {
5704            parts.push(&inner[start..i]);
5705            start = i + 1;
5706        }
5707    }
5708    parts.push(&inner[start..]);
5709    parts
5710}
5711
5712/// `TYPE NAME = SHAPE` at `pos`: uppercase name, single `=`, maximal
5713/// type-tag shape canonicalized through the shared spelling.
5714/// Returns the alias plus tokens consumed, or `None` on shape miss
5715/// (generic fails it in lowering like the grammar).
5716fn parse_type_stmt_at(
5717    toks: &[Tok],
5718    pos: usize,
5719    stmt: usize,
5720) -> Result<Option<(StepKind, usize)>, TokenError> {
5721    let name = match toks.get(pos + 1).map(|t| &t.kind) {
5722        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
5723        _ => return Ok(None),
5724    };
5725    // Single `=` at any gap (`gap` zero-width); `==` misses.
5726    if !matches!(
5727        toks.get(pos + 2).map(|t| &t.kind),
5728        Some(TokKind::Punct('='))
5729    ) {
5730        return Ok(None);
5731    }
5732    if matches!(
5733        toks.get(pos + 3).map(|t| &t.kind),
5734        Some(TokKind::Punct('='))
5735    ) {
5736        return Ok(None);
5737    }
5738    let Some(end) = parse_type_shape(toks, pos + 3) else {
5739        return Ok(None);
5740    };
5741    // Post-match the span holds words/puncts only, so the shared
5742    // renderer cannot fail; stay failed regardless.
5743    let target = render_type_region(&toks[pos + 3..end], stmt).unwrap_or_default();
5744    Ok(Some((StepKind::TypeAlias { name, target }, end - pos)))
5745}
5746
5747/// Single (non-block) `REMOTE`: target, optional bindings, block.
5748/// The target reads a maximal joint run in the grammar's superset
5749/// charset (misses fall to generic); strict validity fails loudly
5750/// with the exact backend message. Bindings miss to generic;
5751/// empty/missing bodies and nesting violations fail loudly.
5752fn parse_remote_single(
5753    toks: &[Tok],
5754    pos: usize,
5755    stmt: usize,
5756    ctx: &ParseCtx,
5757) -> Result<Option<(StepKind, usize)>, TokenError> {
5758    let fail = |msg: String| TokenError {
5759        stmt,
5760        msg,
5761        line: 0,
5762        col: 0,
5763        kind: Some(ParseErrorKind::Validation {
5764            command: KEYWORD_REMOTE.to_string(),
5765        }),
5766    };
5767    // Target: joint run in the superset charset (alnum/`_`/`-`/`.`/`:`).
5768    // Anything else (joint or not) ends the run; an empty run misses
5769    // to generic. (`sep` needs no explicit check: a joint `(` is a
5770    // call routed before this ever runs, and anything unparseable
5771    // misses the same way.)
5772    let mut target = String::new();
5773    let mut p = pos + 1;
5774    while let Some(t) = toks.get(p) {
5775        if !t.joint && !target.is_empty() {
5776            break;
5777        }
5778        match &t.kind {
5779            TokKind::Word(w)
5780                if w.chars().all(|c| {
5781                    c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' || c == ':'
5782                }) =>
5783            {
5784                // Words arrive whole from the lexer; a bad word ends
5785                // the run (never partially appends), like the grammar.
5786                target.push_str(w);
5787                p += 1;
5788            }
5789            TokKind::Punct(c)
5790                if matches!(c, '_' | '-' | '.' | ':') && (target.is_empty() || t.joint) =>
5791            {
5792                target.push(*c);
5793                p += 1;
5794            }
5795            _ => break,
5796        }
5797    }
5798    if target.is_empty() {
5799        return Ok(None);
5800    }
5801    if !crate::commands::is_valid_remote_target(&target) {
5802        return Err(fail(format!(
5803            "invalid REMOTE target `{target}`: start alphanumeric, then alphanumeric, `_`, or `-`, max 64 chars, never SNAPSHOT, LOCAL, CACHE, SYSTEM, or REMOTE"
5804        )));
5805    }
5806    // Optional bindings `[$var, env:KEY]` at any gap (even joint,
5807    // probed); malformed bindings miss the whole shape to generic.
5808    let mut vars = Vec::new();
5809    let mut env = Vec::new();
5810    if let Some(bracket) = toks.get(p)
5811        && matches!(
5812            &bracket.kind,
5813            TokKind::Group {
5814                delim: GroupDelim::Bracket,
5815                ..
5816            }
5817        )
5818    {
5819        let inner = match &bracket.kind {
5820            TokKind::Group { inner, .. } => inner.clone(),
5821            _ => unreachable!(),
5822        };
5823        match parse_remote_bindings(&inner, stmt)? {
5824            Some((v, e)) => {
5825                vars = v;
5826                env = e;
5827            }
5828            None => return Ok(None),
5829        }
5830        p += 1;
5831    }
5832    // Block required (any gap, never a template); missing blocks
5833    // miss to generic.
5834    let block_ok = matches!(
5835        toks.get(p).map(|t| &t.kind),
5836        Some(TokKind::Group {
5837            delim: GroupDelim::Brace,
5838            ..
5839        })
5840    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
5841    if !block_ok {
5842        return Ok(None);
5843    }
5844    let inner = match &toks[p].kind {
5845        TokKind::Group { inner, .. } => inner.clone(),
5846        _ => unreachable!(),
5847    };
5848    let body = parse_body_steps(&inner, stmt, ctx, false)?;
5849    p += 1;
5850    if body.is_empty() {
5851        return Err(fail("REMOTE requires a non-empty braced block".to_string()));
5852    }
5853    if crate::commands::contains_remote_block(&body) {
5854        return Err(fail(format!(
5855            "REMOTE blocks cannot nest (target `{target}` contains another REMOTE block)"
5856        )));
5857    }
5858    if body
5859        .iter()
5860        .any(|s| crate::commands::contains_inherit_env(&s.kind))
5861    {
5862        return Err(fail(
5863            "INHERIT_ENV cannot appear inside a REMOTE block: the guest inherits its own process environment".to_string(),
5864        ));
5865    }
5866    // Outer-function containment (same rule as the shared remote
5867    // validators): body calls resolving to visible
5868    // outer `SCRIPT` defs (without same-body definitions) fail.
5869    {
5870        let mut inner_defs = HashSet::new();
5871        let mut calls = Vec::new();
5872        crate::commands::collect_remote_body_symbols(&body, &mut inner_defs, &mut calls);
5873        let outer_defs: HashSet<String> = ctx.funcs.borrow().iter().flatten().cloned().collect();
5874        for call in &calls {
5875            let bare = crate::constants::base_name(call);
5876            let is_script_call = match crate::constants::split_qualified(call) {
5877                Some((module, _)) => module == crate::constants::SCRIPT_MODULE_NAME,
5878                None => true,
5879            };
5880            if is_script_call && outer_defs.contains(bare) && !inner_defs.contains(bare) {
5881                return Err(fail(format!(
5882                    "REMOTE '{target}' calls outer function '{bare}' (functions must be defined inside the block)"
5883                )));
5884            }
5885        }
5886    }
5887    Ok(Some((
5888        StepKind::RemoteBlock {
5889            target,
5890            vars,
5891            env,
5892            body,
5893        },
5894        p - pos,
5895    )))
5896}
5897// ---- LET/SET/RETURN + expressions ----
5898// Expression tiers over [`Tok`] implement the precedence chain
5899// (or > and > comparison > ordering > add > mul > unary > atom);
5900// arithmetic/comparison lowering runs through the shared constructors
5901// (`make_arith`, `make_compare`, `apply_unary_neg`), so folding, RPN
5902// compilation, and overflow behavior are identical by construction,
5903// never re-derived.
5904
5905/// Eat a one- or two-char operator: single puncts match directly;
5906/// pairs (`==`, `!=`, `<=`, `>=`, `&&`, `||`, `::`) require a joint
5907/// second punct. Newlines never skip here (expression mode).
5908fn eat_op(cur: &mut Cursor, first: char, second: Option<char>) -> bool {
5909    // Gaps (comments included) are skipped before every operator.
5910    cur.skip_gap();
5911    let (a, b) = match (cur.toks.get(cur.pos), cur.toks.get(cur.pos + 1)) {
5912        (Some(a), b) => (a, b),
5913        _ => return false,
5914    };
5915    if !matches!(&a.kind, TokKind::Punct(c) if *c == first) {
5916        return false;
5917    }
5918    match second {
5919        None => {
5920            cur.pos += 1;
5921            true
5922        }
5923        Some(c2) => match b {
5924            Some(t) if t.joint && matches!(&t.kind, TokKind::Punct(c) if *c == c2) => {
5925                cur.pos += 2;
5926                true
5927            }
5928            _ => false,
5929        },
5930    }
5931}
5932
5933/// Dummy span for the shared lowering constructors: v2 owns no source
5934/// positions yet, so only success values (span-free) participate in
5935/// parity; failures surface through [`TokenError`] text.
5936fn lowering_ctx(stmt: usize) -> SpanContext<'static> {
5937    let _ = stmt;
5938    SpanContext::line_only(0)
5939}
5940
5941fn parse_expr_or(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5942    let mut left = parse_expr_and(cur, ctx)?;
5943    while eat_op(cur, '|', Some('|')) {
5944        cur.skip_gap();
5945        let right = parse_expr_and(cur, ctx)?;
5946        // No folding, no boundary checks: unfused literal runs stay
5947        // literal here.
5948        left = Expr::Logical {
5949            op: LogicalOp::Or,
5950            left: Box::new(left),
5951            right: Box::new(right),
5952        };
5953    }
5954    Ok(left)
5955}
5956
5957fn parse_expr_and(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5958    let mut left = parse_expr_cmp(cur, ctx)?;
5959    while eat_op(cur, '&', Some('&')) {
5960        cur.skip_gap();
5961        let right = parse_expr_cmp(cur, ctx)?;
5962        reject_boundary(&lowering_ctx(cur.stmt), &left).map_err(|e| cur.err(e.to_string()))?;
5963        reject_boundary(&lowering_ctx(cur.stmt), &right).map_err(|e| cur.err(e.to_string()))?;
5964        left = Expr::Logical {
5965            op: LogicalOp::And,
5966            left: Box::new(left),
5967            right: Box::new(right),
5968        };
5969    }
5970    Ok(left)
5971}
5972
5973fn parse_expr_cmp(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
5974    let left = parse_expr_ord(cur, ctx)?;
5975    let op = if eat_op(cur, '=', Some('=')) {
5976        CompareOp::Eq
5977    } else if eat_op(cur, '!', Some('=')) {
5978        CompareOp::Ne
5979    } else {
5980        return Ok(left);
5981    };
5982    cur.skip_gap();
5983    let right = parse_expr_ord(cur, ctx)?;
5984    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
5985        .map_err(|e| cur.err(e.to_string()))?;
5986    reject_chained_compare(cur, false)?;
5987    Ok(expr)
5988}
5989
5990/// Reject a comparison operator trailing a complete comparison:
5991/// no grammar position continues with one, so the shape always fails —
5992/// loudly here instead of stranding text for a confusing downstream
5993/// error. The equality tier rejects all six (`$a == $b == $c`,
5994/// `$a == $b < $c < $d`); the ordering tier rejects ordering only
5995/// (`$a < $b < $c`), since `$a < $b == $c` is a legitimate equality
5996/// over an ordering result. Probes without consuming.
5997fn reject_chained_compare(cur: &mut Cursor, ordering_only: bool) -> Result<(), TokenError> {
5998    let mut probe = Cursor::expr(cur.toks, cur.stmt);
5999    probe.pos = cur.pos;
6000    probe.skip_gap();
6001    let chained = match probe.toks.get(probe.pos).map(|t| &t.kind) {
6002        Some(TokKind::Punct('<' | '>')) => true,
6003        Some(TokKind::Punct('=' | '!')) => !ordering_only,
6004        _ => false,
6005    };
6006    if chained {
6007        return Err(cur
6008            .err("chained comparison operators need explicit parentheses, e.g. `($a < $b) < $c`"));
6009    }
6010    Ok(())
6011}
6012
6013fn parse_expr_ord(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6014    let left = parse_expr_add(cur, ctx)?;
6015    let op = if eat_op(cur, '<', Some('=')) {
6016        CompareOp::Le
6017    } else if eat_op(cur, '>', Some('=')) {
6018        CompareOp::Ge
6019    } else if eat_op(cur, '<', None) {
6020        CompareOp::Lt
6021    } else if eat_op(cur, '>', None) {
6022        CompareOp::Gt
6023    } else {
6024        return Ok(left);
6025    };
6026    cur.skip_gap();
6027    let right = parse_expr_add(cur, ctx)?;
6028    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
6029        .map_err(|e| cur.err(e.to_string()))?;
6030    reject_chained_compare(cur, true)?;
6031    Ok(expr)
6032}
6033
6034fn parse_expr_add(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6035    let mut left = parse_expr_mul(cur, ctx)?;
6036    loop {
6037        let op = if eat_op(cur, '+', None) {
6038            ArithOp::Add
6039        } else if eat_op(cur, '-', None) {
6040            ArithOp::Sub
6041        } else {
6042            break;
6043        };
6044        cur.skip_gap();
6045        let right = parse_expr_mul(cur, ctx)?;
6046        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
6047            .map_err(|e| cur.err(e.to_string()))?;
6048    }
6049    Ok(left)
6050}
6051
6052fn parse_expr_mul(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6053    let mut left = parse_expr_unary(cur, ctx)?;
6054    loop {
6055        let op = if eat_op(cur, '*', None) {
6056            ArithOp::Mul
6057        } else if eat_op(cur, '/', None) {
6058            ArithOp::Div
6059        } else {
6060            break;
6061        };
6062        cur.skip_gap();
6063        let right = parse_expr_unary(cur, ctx)?;
6064        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
6065            .map_err(|e| cur.err(e.to_string()))?;
6066    }
6067    Ok(left)
6068}
6069
6070/// A `-` opens a bare word (never negation) when gaplessly followed by
6071/// a letter, `_`, or `/` — the `neg_op` lookahead, read off `joint`.
6072fn dash_is_bare(cur: &Cursor) -> bool {
6073    let next = cur.toks.get(cur.pos + 1);
6074    match next {
6075        Some(t) if t.joint => match &t.kind {
6076            TokKind::Word(w) => w
6077                .chars()
6078                .next()
6079                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_'),
6080            TokKind::Punct('/') => true,
6081            _ => false,
6082        },
6083        _ => false,
6084    }
6085}
6086
6087fn parse_expr_unary(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6088    let mut prefixes = Vec::new();
6089    loop {
6090        match cur.toks.get(cur.pos).map(|t| &t.kind) {
6091            Some(TokKind::Punct('!')) => {
6092                cur.pos += 1;
6093                // Each prefix is gap-separated.
6094                cur.skip_gap();
6095                prefixes.push(false);
6096            }
6097            Some(TokKind::Punct('-')) if !dash_is_bare(cur) => {
6098                cur.pos += 1;
6099                cur.skip_gap();
6100                prefixes.push(true);
6101            }
6102            _ => break,
6103        }
6104    }
6105    let mut expr = parse_expr_atom(cur, ctx)?;
6106    // Innermost prefix is closest to the atom: apply in reverse order.
6107    for is_neg in prefixes.into_iter().rev() {
6108        if is_neg {
6109            expr = apply_unary_neg(&lowering_ctx(cur.stmt), expr)
6110                .map_err(|e| cur.err(e.to_string()))?;
6111        } else {
6112            reject_boundary(&lowering_ctx(cur.stmt), &expr).map_err(|e| cur.err(e.to_string()))?;
6113            expr = Expr::Not(Box::new(expr));
6114        }
6115    }
6116    Ok(expr)
6117}
6118
6119/// Identifier charset for `$var` and `.segment` parts. Segments admit
6120/// digits-only too (`$a.0`); anything else ends the key path and errors
6121/// downstream, like the grammar's backtrack to `variable`.
6122fn is_ident_word(w: &str) -> bool {
6123    !w.is_empty() && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
6124}
6125
6126fn is_key_segment(w: &str) -> bool {
6127    !w.is_empty()
6128        && (w.chars().all(|c| c.is_ascii_digit())
6129            || (w
6130                .chars()
6131                .next()
6132                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
6133                && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')))
6134}
6135
6136fn is_env_key(w: &str) -> bool {
6137    !w.is_empty()
6138        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
6139        && w.chars()
6140            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
6141}
6142
6143/// Maximal joint run of words and `-/.'/'` puncts: the bare-word
6144/// shape (which admits `/` anywhere, so `//c`, `/a`, `a/b`, and the
6145/// `/`-`c`-`/` operands of `/*c*/` math all read literally here).
6146/// Callers classify (`true`/`false`/string); the numeric path
6147/// runs first and falls back here on shape/follower mismatch.
6148/// Backslash escapes are arg-position syntax: the bare-word shape admits
6149/// no `\`, so expression runs containing one fail here (never drift
6150/// into a string the grammar rejects).
6151fn expr_bare_run(cur: &mut Cursor, leading_dash: bool) -> Result<String, TokenError> {
6152    let mut out = String::new();
6153    if leading_dash {
6154        match cur.next() {
6155            Some(t) if matches!(&t.kind, TokKind::Punct('-')) => out.push('-'),
6156            _ => return Err(cur.err("missing expression operand")),
6157        }
6158    }
6159    match cur.next() {
6160        Some(t) => match &t.kind {
6161            TokKind::Word(w) => out.push_str(w),
6162            // Leading `/` (operand position only; operators are
6163            // consumed by the tiers before operands parse).
6164            TokKind::Punct('/') => out.push('/'),
6165            _ => return Err(cur.err("missing expression operand")),
6166        },
6167        None => return Err(cur.err("missing expression operand")),
6168    }
6169    loop {
6170        let next = match cur.toks.get(cur.pos) {
6171            Some(t) if t.joint => t,
6172            _ => break,
6173        };
6174        match &next.kind {
6175            TokKind::Word(w) => {
6176                // Abutting words only continue through an operator gap
6177                // the tiers own (`a -b` never fuses); without a joint
6178                // punct between, stop. Since this token IS joint, the
6179                // previous token must have been a bare punct.
6180                out.push_str(w);
6181                cur.pos += 1;
6182            }
6183            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
6184                out.push(*c);
6185                cur.pos += 1;
6186            }
6187            _ => break,
6188        }
6189    }
6190    if out.contains('\\') {
6191        return Err(cur.err("unexpected escape in expression"));
6192    }
6193    Ok(out)
6194}
6195
6196/// Numeric literal head: digit-led word plus joint `.digits` tails.
6197/// Callers apply the separator-shape gate and the follower rule, then
6198/// the shared classifier.
6199fn number_head(cur: &mut Cursor) -> Option<String> {
6200    let first = match cur.toks.get(cur.pos).map(|t| &t.kind) {
6201        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => w.clone(),
6202        _ => return None,
6203    };
6204    let mut text = first;
6205    let mut pos = cur.pos + 1;
6206    loop {
6207        let dot = matches!(
6208            cur.toks.get(pos).map(|t| &t.kind),
6209            Some(TokKind::Punct('.'))
6210        ) && cur.toks.get(pos).is_some_and(|t| t.joint);
6211        let digits = cur.toks.get(pos + 1);
6212        let digits_ok = dot
6213            && matches!(digits.map(|t| &t.kind), Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_'))
6214            && digits.is_some_and(|t| t.joint);
6215        if !digits_ok {
6216            break;
6217        }
6218        text.push('.');
6219        if let Some(TokKind::Word(w)) = digits.map(|t| &t.kind) {
6220            text.push_str(w);
6221        }
6222        pos += 2;
6223    }
6224    Some(text)
6225}
6226
6227/// `_`-separator shape gate mirroring the `numeric_literal` rule:
6228/// digits with single-underscore separators, at most one fraction.
6229fn numeric_shape_ok(text: &str) -> bool {
6230    let mut parts = text.split('.');
6231    let int_part = parts.next().unwrap_or("");
6232    let frac_part = parts.next();
6233    if parts.next().is_some() {
6234        return false;
6235    }
6236    fn run_ok(s: &str) -> bool {
6237        !s.is_empty()
6238            && s.chars().all(|c| c.is_ascii_digit() || c == '_')
6239            && !s.starts_with('_')
6240            && !s.ends_with('_')
6241            && !s.contains("__")
6242    }
6243    run_ok(int_part) && frac_part.is_none_or(run_ok)
6244}
6245
6246/// Follower rule mirroring the `numeric_literal` trailing guard
6247/// (`!(ALNUM | "_" | "." | "/")`): a joint word, `.`, or `/` continues
6248/// into a bare word (`30s`, `1.`, `4/2`); `-`/`+`/operators let the
6249/// number stand for the tiers (`1-2` is `Sub`, like the grammar).
6250fn number_falls_to_bare(cur: &Cursor, consumed: usize) -> bool {
6251    match cur.toks.get(cur.pos + consumed) {
6252        Some(t) if t.joint => matches!(
6253            &t.kind,
6254            TokKind::Word(_) | TokKind::Punct('.') | TokKind::Punct('/')
6255        ),
6256        _ => false,
6257    }
6258}
6259
6260fn parse_expr_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6261    match cur.toks.get(cur.pos).map(|t| &t.kind) {
6262        Some(TokKind::Group {
6263            delim: GroupDelim::Paren,
6264            inner,
6265            ..
6266        }) => {
6267            let inner = inner.clone();
6268            cur.pos += 1;
6269            let mut sub = Cursor::expr(&inner, cur.stmt);
6270            sub.skip_gap_nl();
6271            let expr = parse_expr_or(&mut sub, ctx)?;
6272            sub.skip_gap_nl();
6273            if !sub.done() {
6274                return Err(sub.err("unexpected text in parentheses"));
6275            }
6276            Ok(expr)
6277        }
6278        Some(TokKind::Word(_)) if call_shape_at(cur.toks, cur.pos, false).is_some() => {
6279            let (name, paren) =
6280                call_shape_at(cur.toks, cur.pos, false).ok_or_else(|| cur.err("unreachable"))?;
6281            let inner = match &cur.toks[paren].kind {
6282                TokKind::Group { inner, .. } => inner.clone(),
6283                _ => unreachable!(),
6284            };
6285            cur.pos = paren + 1;
6286            parse_expr_call(name, &inner, cur.stmt, ctx)
6287        }
6288        Some(TokKind::Punct('$')) => {
6289            cur.pos += 1;
6290            // Atomic `variable`: `$` and the name ride gapless (the
6291            // enclosing rules are compound-atomic).
6292            let base = match cur.next() {
6293                Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
6294                    match &t.kind {
6295                        TokKind::Word(w) => w.clone(),
6296                        _ => unreachable!(),
6297                    }
6298                }
6299                _ => return Err(cur.err("`$` requires a variable name")),
6300            };
6301            let mut keys = Vec::new();
6302            loop {
6303                // Key-path dots are gapless too (`~` without `gap`).
6304                let dot = matches!(
6305                    cur.toks.get(cur.pos).map(|t| &t.kind),
6306                    Some(TokKind::Punct('.'))
6307                ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
6308                let seg = cur.toks.get(cur.pos + 1);
6309                let seg_ok = dot
6310                    && matches!(seg.map(|t| &t.kind), Some(TokKind::Word(w)) if is_key_segment(w))
6311                    && seg.is_some_and(|t| t.joint);
6312                if !seg_ok {
6313                    break;
6314                }
6315                if let Some(TokKind::Word(w)) = seg.map(|t| &t.kind) {
6316                    keys.push(w.clone());
6317                }
6318                cur.pos += 2;
6319            }
6320            if keys.is_empty() {
6321                Ok(Expr::Var(base))
6322            } else {
6323                Ok(Expr::KeyPath { base, keys })
6324            }
6325        }
6326        Some(TokKind::Word(w)) if w == "env" => {
6327            // `env:KEY` read when the full shape matches gaplessly
6328            // (atomic `env_read`); otherwise a bare word (`env` alone,
6329            // `env:k` lowercase) for the error path, exactly like the
6330            // grammar's mismatch.
6331            let key_ok = matches!(
6332                cur.toks.get(cur.pos + 1).map(|t| &t.kind),
6333                Some(TokKind::Punct(':'))
6334            ) && cur.toks.get(cur.pos + 1).is_some_and(|t| t.joint)
6335                && matches!(
6336                    cur.toks.get(cur.pos + 2).map(|t| &t.kind),
6337                    Some(TokKind::Word(k)) if is_env_key(k)
6338                )
6339                && cur.toks.get(cur.pos + 2).is_some_and(|t| t.joint);
6340            if !key_ok {
6341                return parse_bare_atom(cur, ctx, false);
6342            }
6343            cur.pos += 1;
6344            cur.pos += 1;
6345            match cur.next() {
6346                Some(t) => match &t.kind {
6347                    TokKind::Word(k) => Ok(Expr::Env(k.clone())),
6348                    _ => Err(cur.err("unreachable")),
6349                },
6350                None => Err(cur.err("unreachable")),
6351            }
6352        }
6353        Some(TokKind::Group {
6354            delim: GroupDelim::Bracket,
6355            inner,
6356            ..
6357        }) => {
6358            let inner = inner.clone();
6359            cur.pos += 1;
6360            parse_list_literal(&inner, cur.stmt, ctx)
6361        }
6362        Some(TokKind::Group {
6363            delim: GroupDelim::Brace,
6364            inner,
6365            ..
6366        }) => {
6367            let inner = inner.clone();
6368            cur.pos += 1;
6369            parse_map_or_block(&inner, cur.stmt, ctx)
6370        }
6371        Some(TokKind::Str { text, .. }) => {
6372            let text = text.clone();
6373            cur.pos += 1;
6374            Ok(Expr::Literal(Value::string(text)))
6375        }
6376        Some(TokKind::BlockStr(full)) => {
6377            let full = full.clone();
6378            cur.pos += 1;
6379            Ok(Expr::Literal(Value::string(
6380                crate::command::lower_block_string(&full),
6381            )))
6382        }
6383        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => {
6384            parse_numeric_atom(cur, ctx)
6385        }
6386        Some(TokKind::Word(_)) => parse_bare_atom(cur, ctx, false),
6387        Some(TokKind::Punct('-')) => parse_bare_atom(cur, ctx, true),
6388        Some(TokKind::Punct('/')) => parse_bare_atom(cur, ctx, false),
6389        _ => Err(cur.err("missing expression operand")),
6390    }
6391}
6392
6393/// Bare-word atom with a `-` lead (the caller proved it is not
6394/// negation): consumes the joint `-/.'/'` run for the bare-word
6395/// shape.
6396fn parse_bare_atom(
6397    cur: &mut Cursor,
6398    _ctx: &ParseCtx,
6399    leading_dash: bool,
6400) -> Result<Expr, TokenError> {
6401    let text = expr_bare_run(cur, leading_dash)?;
6402    match text.as_str() {
6403        "true" => Ok(Expr::Literal(Value::bool(true))),
6404        "false" => Ok(Expr::Literal(Value::bool(false))),
6405        _ => Ok(Expr::Literal(Value::string(text))),
6406    }
6407}
6408
6409/// Numeric atom: rejoin dotted tails, apply the shape gate and the
6410/// follower rule, then the shared classifier. Anything failing the
6411/// gate or follower reparses as a bare word (durations, versions,
6412/// paths), exactly like the grammar's numeric-literal-or-bare-word
6413/// order.
6414fn parse_numeric_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6415    let start = cur.pos;
6416    let text = number_head(cur).ok_or_else(|| cur.err("missing expression operand"))?;
6417    let consumed = {
6418        let mut n = 1;
6419        let mut p = start + 1;
6420        while matches!(cur.toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('.')))
6421            && cur.toks.get(p).is_some_and(|t| t.joint)
6422            && matches!(
6423                cur.toks.get(p + 1).map(|t| &t.kind),
6424                Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_')
6425            )
6426            && cur.toks.get(p + 1).is_some_and(|t| t.joint)
6427        {
6428            n += 2;
6429            p += 2;
6430        }
6431        n
6432    };
6433    if !numeric_shape_ok(&text) || number_falls_to_bare(cur, consumed) {
6434        return parse_bare_atom(cur, ctx, false);
6435    }
6436    cur.pos += consumed;
6437    classify_numeric_text(&text).map_err(|msg| cur.err(msg))
6438}
6439
6440/// Full expression with the top-level boundary rejection (mirrors
6441/// `parse_expr`): a stray `UnsignedIntBoundary` that no unary `-`
6442/// consumed is an overflow error.
6443fn parse_expr_checked(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6444    let expr = parse_expr_or(cur, ctx)?;
6445    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
6446        return Err(cur.err("integer overflow: 9223372036854775808 exceeds i64::MAX"));
6447    }
6448    Ok(expr)
6449}
6450
6451/// List literal over a bracket group's contents: the shared bracket
6452/// core (see [`parse_bracket_list`]) in `Expr` mode. Expression
6453/// positions fail loudly instead of missing, so `None` is unreachable.
6454fn parse_list_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6455    parse_bracket_list(inner, stmt, ctx, BracketItems::Expr)
6456        .map(|list| list.expect("expression lists fail loudly, never miss"))
6457}
6458
6459/// Map literal attempt over a brace group's contents: comma-separated
6460/// `key: value` entries with `gap` (never newline) around the colon.
6461/// Any entry failing the shape is not a map: the caller reports the
6462/// deferred block slice (the grammar tries `block` next, which fails
6463/// the same inputs at this stage).
6464/// Marker message for a map entry run that ends without a comma
6465/// where another entry follows. Matched by exact equality in
6466/// [`parse_map_or_block`], never by prefix, so wording changes stay
6467/// local to this const and its one reader.
6468const MISSING_MAP_COMMA_MSG: &str = "missing comma between map entries";
6469
6470fn parse_map_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6471    let mut entries = Vec::new();
6472    // Empty (or blank/comment-only) braces are an empty map.
6473    if inner
6474        .iter()
6475        .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
6476    {
6477        return Ok(Expr::Map(vec![]));
6478    }
6479    for part in split_top_commas(inner) {
6480        let mut sub = Cursor::expr(part, stmt);
6481        sub.skip_gap_nl();
6482        let (key, val) = parse_map_entry(&mut sub, ctx, stmt)?;
6483        sub.skip_gap_nl();
6484        if !sub.done() {
6485            return Err(map_trailing_error(&sub, ctx, stmt));
6486        }
6487        entries.push((key, val));
6488    }
6489    Ok(Expr::Map(entries))
6490}
6491
6492/// One `key: value` map entry: string, block-string, or bare key,
6493/// a colon, then a full checked expression. Every failure reads
6494/// `not a map literal` exactly like the old inline loop, so only
6495/// the trailing rule changes the surface.
6496fn parse_map_entry(
6497    sub: &mut Cursor,
6498    ctx: &ParseCtx,
6499    stmt: usize,
6500) -> Result<(String, Expr), TokenError> {
6501    let key = match sub.toks.get(sub.pos).map(|t| &t.kind) {
6502        Some(TokKind::Str { text, .. }) => {
6503            let key = text.clone();
6504            sub.pos += 1;
6505            key
6506        }
6507        Some(TokKind::BlockStr(full)) => {
6508            let key = crate::command::lower_block_string(full);
6509            sub.pos += 1;
6510            key
6511        }
6512        Some(TokKind::Word(_)) | Some(TokKind::Punct('-')) | Some(TokKind::Punct('/')) => {
6513            map_bare_key(sub)?
6514        }
6515        _ => return Err(sub.err("not a map literal")),
6516    };
6517    sub.skip_gap();
6518    if !sub.eat_punct(':') {
6519        return Err(sub.err("not a map literal"));
6520    }
6521    let val = parse_expr_checked(sub, ctx)?;
6522    reject_boundary(&lowering_ctx(stmt), &val).map_err(|e| sub.err(e.to_string()))?;
6523    Ok((key, val))
6524}
6525
6526/// Trailing content after a complete map entry: stamps the
6527/// offending token and names the likely missing comma when the
6528/// remainder parses as another entry. Anything else keeps the old
6529/// `not a map literal` text. Error-path only.
6530fn map_trailing_error(sub: &Cursor, ctx: &ParseCtx, stmt: usize) -> TokenError {
6531    let (line, col) = sub
6532        .toks
6533        .get(sub.pos)
6534        .map(|t| (t.line, t.col))
6535        .unwrap_or((0, 0));
6536    let mut probe = Cursor::expr(&sub.toks[sub.pos.min(sub.toks.len())..], stmt);
6537    probe.skip_gap_nl();
6538    if parse_map_entry(&mut probe, ctx, stmt).is_ok() {
6539        return TokenError {
6540            stmt,
6541            line,
6542            col,
6543            msg: MISSING_MAP_COMMA_MSG.to_string(),
6544            kind: None,
6545        };
6546    }
6547    sub.err("not a map literal")
6548}
6549
6550/// Bare map key: joint `-/.'/'`-run, mirroring the bare-word charset
6551/// (no bool/numeric classification: keys are always strings).
6552fn map_bare_key(sub: &mut Cursor) -> Result<String, TokenError> {
6553    let mut out = String::new();
6554    if matches!(
6555        sub.toks.get(sub.pos).map(|t| &t.kind),
6556        Some(TokKind::Punct('-'))
6557    ) {
6558        out.push('-');
6559        sub.pos += 1;
6560    }
6561    // Leading `/` reads literally too (the bare-word shape admits `/`
6562    // anywhere: `{/a: 1}`, `{//c: 1}`); the joint loop below
6563    // continues the run.
6564    if matches!(
6565        sub.toks.get(sub.pos).map(|t| &t.kind),
6566        Some(TokKind::Punct('/'))
6567    ) {
6568        out.push('/');
6569        sub.pos += 1;
6570    }
6571    match sub.toks.get(sub.pos).map(|t| &t.kind) {
6572        Some(TokKind::Word(w)) => {
6573            out.push_str(w);
6574            sub.pos += 1;
6575        }
6576        // A leading `/` above already started the run; anything
6577        // else still needs a word head.
6578        _ if !out.is_empty() => {}
6579        _ => return Err(sub.err("not a map literal")),
6580    }
6581    while let Some(t) = sub.toks.get(sub.pos) {
6582        if !t.joint {
6583            break;
6584        }
6585        match &t.kind {
6586            TokKind::Word(w) => {
6587                out.push_str(w);
6588                sub.pos += 1;
6589            }
6590            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
6591                out.push(*c);
6592                sub.pos += 1;
6593            }
6594            _ => break,
6595        }
6596    }
6597    if out.contains('\\') {
6598        return Err(sub.err("unexpected escape in map key"));
6599    }
6600    Ok(out)
6601}
6602
6603/// Map-or-block over a brace group's contents: maps parse literally;
6604/// anything else is an inline block (`Expr::Block` over the body
6605/// steps, scopes unmarked like every braced body).
6606fn parse_map_or_block(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6607    match parse_map_literal(inner, stmt, ctx) {
6608        Ok(map) => Ok(map),
6609        // A detected missing comma is never a block: its `key:`
6610        // remainder cannot parse as a statement (a `name: "a"` line
6611        // fails as `unknown command`), so the block path can only
6612        // misreport it. Surface the map error instead; every other
6613        // map failure keeps the block fallback exactly as before.
6614        Err(e) if e.msg == MISSING_MAP_COMMA_MSG => Err(e),
6615        Err(_) => Ok(Expr::Block(parse_body_steps(inner, stmt, ctx, false)?)),
6616    }
6617}
6618
6619/// Parse one standalone expression from lexed tokens (the
6620/// `parse_expression_str` entry point): a full tier parse with
6621/// top-level boundary rejection and full consumption.
6622pub(crate) fn parse_single_expr(
6623    toks: &[Tok],
6624    stmt: usize,
6625    ctx: &ParseCtx,
6626) -> Result<Expr, TokenError> {
6627    let mut cur = Cursor::expr(toks, stmt);
6628    let expr = parse_expr_checked(&mut cur, ctx)?;
6629    if !cur.done() {
6630        return Err(cur.err("unexpected text in expression"));
6631    }
6632    Ok(expr)
6633}
6634
6635/// Assignment `=`: the first `=` neither glued to a following `=`
6636/// (`==`) nor glued after `!`/`<`/`>`/`=` (`!=`, `<=`, `>=`, second of
6637/// `==`). Glued-ness reads off the `=`'s own `joint` (gap before it)
6638/// and the follower's (gap after it). Anything else leaves the
6639/// statement bare (`LET $p: PIPE`), exactly where the grammar's `"="`
6640/// match fails.
6641fn find_assign_eq(body: &[Tok]) -> Option<usize> {
6642    for (i, tok) in body.iter().enumerate() {
6643        if !matches!(&tok.kind, TokKind::Punct('=')) {
6644            continue;
6645        }
6646        let next_eq = body
6647            .get(i + 1)
6648            .is_some_and(|t| t.joint && matches!(&t.kind, TokKind::Punct('=')));
6649        let prev_op = tok.joint
6650            && i > 0
6651            && matches!(&body[i - 1].kind, TokKind::Punct('!' | '<' | '>' | '='));
6652        if !next_eq && !prev_op {
6653            return Some(i);
6654        }
6655    }
6656    None
6657}
6658
6659/// Render a type region joint-aware (`LIST< MAP >` keeps its gaps for
6660/// the shared canonicalizer, exactly like `type_tag.as_str()`).
6661fn render_type_region(toks: &[Tok], stmt: usize) -> Result<String, TokenError> {
6662    let mut out = String::new();
6663    for tok in toks {
6664        // Ridden newlines from multi-line `<...>` shapes carry no
6665        // output, so the shape canonicalizes exactly like one line.
6666        if matches!(&tok.kind, TokKind::Newline) {
6667            continue;
6668        }
6669        if !tok.joint && !out.is_empty() {
6670            out.push(' ');
6671        }
6672        match &tok.kind {
6673            TokKind::Word(w) => out.push_str(w),
6674            TokKind::Punct(c) => out.push(*c),
6675            _ => {
6676                return Err(TokenError {
6677                    stmt,
6678                    msg: "malformed type in LET".to_string(),
6679                    line: 0,
6680                    col: 0,
6681                    kind: None,
6682                });
6683            }
6684        }
6685    }
6686    if out.is_empty() {
6687        return Err(TokenError {
6688            stmt,
6689            msg: "LET requires explicit type: LET $var: TYPE = <expr>".to_string(),
6690            line: 0,
6691            col: 0,
6692            kind: None,
6693        });
6694    }
6695    Ok(crate::canonicalize_spelling(&out))
6696}
6697
6698fn expect_dollar_var(cur: &mut Cursor, msg: &str) -> Result<String, TokenError> {
6699    // Atomic `dollar_ident`: no gap between `$` and the name (the
6700    // enclosing statements are compound-atomic, so implicit spacing is
6701    // off and only explicit `gap`s admit whitespace).
6702    match cur.next() {
6703        Some(t) if matches!(&t.kind, TokKind::Punct('$')) => {}
6704        _ => return Err(cur.err(msg)),
6705    }
6706    match cur.next() {
6707        Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
6708            match &t.kind {
6709                TokKind::Word(w) => Ok(w.clone()),
6710                _ => unreachable!(),
6711            }
6712        }
6713        _ => Err(cur.err(msg)),
6714    }
6715}
6716
6717/// `LET` body: `LET` is already matched. Returns `None` (miss to
6718/// generic, which fails in lowering like the grammar's committed
6719/// `instruction`) when the shape cannot match any `LET` form: no
6720/// gapless `$var`, or no `:` after it
6721/// (every form needs `: TYPE`). Past that the shape is committed and
6722/// malformed tails fail loudly.
6723fn parse_let_body(
6724    body: &[Tok],
6725    stmt: usize,
6726    ctx: &ParseCtx,
6727) -> Result<Option<(StepKind, usize)>, TokenError> {
6728    let mut cur = Cursor::expr(body, stmt);
6729    match cur.next() {
6730        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_LET) => {}
6731        _ => return Err(cur.err("unreachable")),
6732    }
6733    // No `$var`: no `LET` form can match (miss, never a hard fail).
6734    let var = match expect_dollar_var(&mut cur, "LET requires a variable") {
6735        Ok(var) => var,
6736        Err(_) => return Ok(None),
6737    };
6738    // The header allows gaps (comments, never newlines).
6739    cur.skip_gap();
6740    // No `:`: untyped LET is rejected outright. Every binding is
6741    // typed; the old miss-to-generic path only hid that behind a
6742    // rambling "invalid syntax" message. (FOR already does this.)
6743    if !cur.eat_punct(':') {
6744        return Err(TokenError {
6745            stmt,
6746            msg: "LET requires explicit types: LET $var: TYPE = <expr>".to_string(),
6747            line: 0,
6748            col: 0,
6749            kind: Some(ParseErrorKind::InvalidSyntax {
6750                command: "LET".to_string(),
6751            }),
6752        });
6753    }
6754    // Type region runs to the assignment `=`; it cannot contain one.
6755    let type_start = cur.pos;
6756    let assign = find_assign_eq(&body[type_start..]).map(|i| i + type_start);
6757    let Some(eq) = assign else {
6758        // Bare `LET $p: PIPE` mints a fresh pipe and ends with the
6759        // type word (trailing elements loop on, probed); every other
6760        // bare type is a validation error, mirroring the grammar.
6761        if matches!(
6762            body.get(type_start).map(|t| &t.kind),
6763            Some(TokKind::Word(w)) if w == crate::TypeTag::Pipe.name()
6764        ) {
6765            return Ok(Some((
6766                StepKind::Assign {
6767                    var,
6768                    decl_type: crate::TypeTag::Pipe.name().to_string(),
6769                    expr: Expr::FreshPipe,
6770                },
6771                type_start + 1,
6772            )));
6773        }
6774        return Err(cur.err(
6775            "LET requires an expression: LET $var: TYPE = <expr> (only LET $p: PIPE omits the initializer)",
6776        ));
6777    };
6778    let decl_type = render_type_region(&body[type_start..eq], stmt)?;
6779    let (kind, rhs_used) = parse_let_rhs(&body[eq + 1..], var, decl_type, stmt, ctx)?;
6780    Ok(Some((kind, eq + 1 + rhs_used)))
6781}
6782
6783/// LET right-hand side dispatch, mirroring the grammar order
6784/// (`let_async`, then `let_capture`, then `let_statement`):
6785/// `WITH_IO`-led lines branch async/sync like
6786/// `parse_let_async_statement_from_pair`, `ASYNC`-led lines spawn
6787/// tasks, `TIMEOUT`-led lines capture through the wrapper,
6788/// `AWAIT $v` captures, RUN exec-form captures, known commands
6789/// capture through the generic parser (lowering failures fatal,
6790/// exactly like the committed grammar alternative), and anything
6791/// else parses as an expression (unknown leads included). Returns
6792/// the kind and RHS tokens consumed: captures ending in structural
6793/// pairs leave trailing elements for the caller.
6794fn parse_let_rhs(
6795    rhs: &[Tok],
6796    var: String,
6797    decl_type: String,
6798    stmt: usize,
6799    ctx: &ParseCtx,
6800) -> Result<(StepKind, usize), TokenError> {
6801    // Leading gap comments vanish like the `=` gap (but a `//`/`#`
6802    // to end of input leaves no expression, failing).
6803    let mut lead = Cursor::expr(rhs, stmt);
6804    lead.skip_gap();
6805    let (rhs, skipped) = (&rhs[lead.pos..], lead.pos);
6806    let head_word = match rhs.first().map(|t| &t.kind) {
6807        Some(TokKind::Word(w)) => Some(w.clone()),
6808        _ => None,
6809    };
6810    // `WITH_IO`-led lines share `let_async_statement` with the
6811    // `ASYNC` forms (the grammar claims every WITH_IO-led LET
6812    // there); shape misses fall through to generic below.
6813    if head_word.as_deref() == Some(KEYWORD_WITH_IO)
6814        && let Some(found) = try_let_with_io_rhs(rhs, var.clone(), decl_type.clone(), stmt, ctx)?
6815    {
6816        let (kind, used) = found;
6817        return Ok((kind, skipped + used));
6818    }
6819    // `ASYNC`-led lines (with followers; alone they commit to the
6820    // generic path like the grammar, failing in lowering) spawn
6821    // background tasks. No `WITH_IO` scan here (probed: the LET
6822    // path accepts what statement `ASYNC` rejects).
6823    if head_word.as_deref() == Some(KEYWORD_ASYNC) && rhs.len() > 1 {
6824        let (kind, used) = parse_let_async_rhs(&rhs[1..], var, decl_type, stmt, ctx)?;
6825        return Ok((kind, skipped + 1 + used));
6826    }
6827    // `TIMEOUT`-led lines capture through the wrapper (shape misses
6828    // fall through to generic, which fails in lowering).
6829    if head_word.as_deref() == Some(KEYWORD_TIMEOUT)
6830        && let Some((kind, used)) = parse_timeout_single(rhs, 0, stmt, ctx)?
6831    {
6832        let span = lowering_ctx(stmt);
6833        crate::commands::reject_async_in_capture(&span, &kind).map_err(|e| TokenError {
6834            stmt,
6835            msg: e.to_string(),
6836            line: 0,
6837            col: 0,
6838            kind: None,
6839        })?;
6840        crate::commands::reject_pipe_stdout_in_capture(&span, &kind).map_err(|e| TokenError {
6841            stmt,
6842            msg: e.to_string(),
6843            line: 0,
6844            col: 0,
6845            kind: None,
6846        })?;
6847        return Ok((
6848            StepKind::AssignCapture {
6849                var,
6850                decl_type,
6851                cmd: Box::new(kind),
6852            },
6853            skipped + used,
6854        ));
6855    }
6856    // `AWAIT $v` captures the task output (`$`+name ride gapless in
6857    // this atomic position, like the grammar); anything else
6858    // `AWAIT`-led goes generic below (lowering fails it, probed).
6859    if head_word.as_deref() == Some(KEYWORD_AWAIT)
6860        && rhs.len() == 3
6861        && let (Some(dollar), Some(task)) = (rhs.get(1), rhs.get(2))
6862        && matches!(&dollar.kind, TokKind::Punct('$'))
6863        && task.joint
6864        && let TokKind::Word(task_var) = &task.kind
6865        && is_ident_word(task_var)
6866    {
6867        return Ok((
6868            StepKind::AwaitCapture {
6869                out_var: var,
6870                out_type: decl_type,
6871                task_var: task_var.clone(),
6872            },
6873            skipped + 3,
6874        ));
6875    }
6876    // RUN exec form captures the structured argv (gapped bracket;
6877    // a joint bracket falls through to generic, which fails it in
6878    // lowering).
6879    if head_word.as_deref() == Some(KEYWORD_RUN)
6880        && matches!(
6881            rhs.get(1).map(|t| (&t.kind, t.joint)),
6882            Some((
6883                TokKind::Group {
6884                    delim: GroupDelim::Bracket,
6885                    ..
6886                },
6887                false
6888            ))
6889        )
6890        && rhs.len() == 2
6891    {
6892        let inner = match &rhs[1].kind {
6893            TokKind::Group { inner, .. } => inner.clone(),
6894            _ => unreachable!(),
6895        };
6896        // Non-map blocks miss the exec shape; fall through below
6897        // (known-command capture, then expression), mirroring the
6898        // grammar's ordered alternatives.
6899        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
6900            let kind =
6901                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
6902            return Ok((
6903                StepKind::AssignCapture {
6904                    var,
6905                    decl_type,
6906                    cmd: Box::new(kind),
6907                },
6908                skipped + 2,
6909            ));
6910        }
6911    }
6912    // File `IMPORT ["path" AS ALIAS]` (#115) captures the imported
6913    // pipeline's `RETURN` value like a call (`LET $r: STRING = IMPORT ...`
6914    // lowers to `AssignCapture`): exactly one file entry, no modules.
6915    // Anything else shaped like an import is a hard error; shape misses
6916    // fall through to generic below, which fails them in lowering.
6917    if head_word.as_deref() == Some(KEYWORD_IMPORT)
6918        && let Some((path, alias, used)) = parse_single_file_import(rhs, 0, stmt, ctx)?
6919    {
6920        return Ok((
6921            StepKind::AssignCapture {
6922                var,
6923                decl_type,
6924                cmd: Box::new(StepKind::ImportFile { path, alias }),
6925            },
6926            skipped + used,
6927        ));
6928    }
6929    // Known-command leads capture through the generic parser
6930    // (lowering failures are fatal here, exactly like the committed
6931    // grammar alternative: probed wrapper-alone and `ISOLATED`-led
6932    // shapes error in lowering); unknown leads parse as expressions.
6933    match &head_word {
6934        Some(head) if is_known_command(head) => {
6935            let (cmd, used) = parse_inner_command(rhs, stmt, ctx)?;
6936            let span = lowering_ctx(stmt);
6937            crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| TokenError {
6938                stmt,
6939                msg: e.to_string(),
6940                line: 0,
6941                col: 0,
6942                kind: None,
6943            })?;
6944            crate::commands::reject_pipe_stdout_in_capture(&span, &cmd).map_err(|e| {
6945                TokenError {
6946                    stmt,
6947                    msg: e.to_string(),
6948                    line: 0,
6949                    col: 0,
6950                    kind: None,
6951                }
6952            })?;
6953            // `INHERIT_ENV`-led lines land here (generic): the
6954            // nesting check rejects them (probed).
6955            crate::commands::reject_nested_inherit_env(&span, &cmd).map_err(|e| TokenError {
6956                stmt,
6957                msg: e.to_string(),
6958                line: 0,
6959                col: 0,
6960                kind: None,
6961            })?;
6962            return Ok((
6963                StepKind::AssignCapture {
6964                    var,
6965                    decl_type,
6966                    cmd: Box::new(cmd),
6967                },
6968                skipped + used,
6969            ));
6970        }
6971        _ => {}
6972    }
6973    let mut cur = Cursor::expr(rhs, stmt);
6974    let expr = parse_expr_checked(&mut cur, ctx)?;
6975    let used = skipped + cur.pos;
6976    Ok((
6977        StepKind::Assign {
6978            var,
6979            decl_type,
6980            expr,
6981        },
6982        used,
6983    ))
6984}
6985
6986/// `WITH_IO`-led LET right-hand side, mirroring
6987/// `parse_let_async_statement_from_pair`'s `with_io_command` branch:
6988/// wrapping `ASYNC` binds a pipe-wired background task (multi-step
6989/// blocks fail loudly), wrapping a sync command captures its stdout
6990/// (async bodies and `stdout` pipes fail loudly), and a bare
6991/// bracket fails validation. `None` on shape miss (bad bracket:
6992/// the caller goes generic, which fails in lowering).
6993fn try_let_with_io_rhs(
6994    rhs: &[Tok],
6995    var: String,
6996    decl_type: String,
6997    stmt: usize,
6998    ctx: &ParseCtx,
6999) -> Result<Option<(StepKind, usize)>, TokenError> {
7000    let bracket = match rhs.get(1) {
7001        Some(t)
7002            if !t.joint
7003                && matches!(
7004                    &t.kind,
7005                    TokKind::Group {
7006                        delim: GroupDelim::Bracket,
7007                        ..
7008                    }
7009                ) =>
7010        {
7011            t
7012        }
7013        _ => return Ok(None),
7014    };
7015    let inner = match &bracket.kind {
7016        TokKind::Group { inner, .. } => inner.clone(),
7017        _ => unreachable!(),
7018    };
7019    let bindings = match parse_io_bindings(&inner, stmt)? {
7020        Some(bindings) => bindings,
7021        None => return Ok(None),
7022    };
7023    let fail = |msg: String| TokenError {
7024        stmt,
7025        msg,
7026        line: 0,
7027        col: 0,
7028        kind: None,
7029    };
7030    let rest = &rhs[2..];
7031    let Some(first) = rest.first() else {
7032        // Bare bracket: the grammar's committed validation error.
7033        return Err(fail(
7034            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7035                .to_string(),
7036        ));
7037    };
7038    if first.joint {
7039        // The inner rides after a `sep`: joint followers miss the
7040        // shape and fail validation like the grammar's bare bracket.
7041        return Err(fail(
7042            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7043                .to_string(),
7044        ));
7045    }
7046    if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_ASYNC) {
7047        // `WITH_IO [..] ASYNC <single|block>`: the bindings apply
7048        // inside the task thread (same shape as a one-step body
7049        // holding one `WITH_IO` step, which the runtime supports).
7050        // A bare `ASYNC` goes generic and fails in lowering
7051        // (`unknown command: ASYNC`, probed).
7052        let after = &rest[1..];
7053        if after.is_empty() {
7054            // Bare `ASYNC`: the grammar commits to `instruction`
7055            // and lowering fails it (`unknown command: ASYNC`,
7056            // probed); mirror by running generic, staying failed
7057            // even under a lenient dispatcher.
7058            match parse_inner_command(&rest[..1], stmt, ctx) {
7059                Err(e) => return Err(e),
7060                Ok(_) => {
7061                    return Err(fail(
7062                        "LET $var: HANDLE<T> = ASYNC requires a body".to_string(),
7063                    ));
7064                }
7065            }
7066        }
7067        if let Some(second) = after.first()
7068            && matches!(
7069                &second.kind,
7070                TokKind::Group {
7071                    delim: GroupDelim::Brace,
7072                    ..
7073                }
7074            )
7075            && !is_template_brace(second)
7076        {
7077            let brace_inner = match &second.kind {
7078                TokKind::Group { inner, .. } => inner.clone(),
7079                _ => unreachable!(),
7080            };
7081            let body = parse_body_steps(&brace_inner, stmt, ctx, false)?;
7082            if body.len() != 1 {
7083                return Err(fail(
7084                        "LET $var: TYPE = WITH_IO [..] ASYNC accepts a single command; use LET $var: HANDLE<T> = ASYNC {{ ... }} with WITH_IO inside the block for multi-step tasks"
7085                            .to_string(),
7086                    ));
7087            }
7088            let wrapped = Step {
7089                guard: None,
7090                kind: StepKind::WithIo {
7091                    bindings,
7092                    cmd: Box::new(
7093                        body.into_iter()
7094                            .next()
7095                            .ok_or_else(|| {
7096                                fail("LET $var: HANDLE<T> = ASYNC requires a body".to_string())
7097                            })?
7098                            .kind,
7099                    ),
7100                },
7101                scope_enter: 0,
7102                scope_exit: 0,
7103                line: 0,
7104                col: 0,
7105            };
7106            return Ok(Some((
7107                StepKind::AssignAsync {
7108                    var,
7109                    decl_type,
7110                    body: vec![wrapped],
7111                },
7112                2 + 2,
7113            )));
7114        }
7115        if after.first().is_some_and(|t| t.joint) {
7116            // Joint followers miss the inner `sep`: same validation
7117            // error as the bare bracket.
7118            return Err(fail(
7119                "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7120                    .to_string(),
7121            ));
7122        }
7123        let (cmd, used) = parse_single_inner(
7124            rest,
7125            1,
7126            stmt,
7127            ctx,
7128            InnerRules {
7129                allow_await: false,
7130                allow_with_io: false,
7131            },
7132        )?;
7133        let wrapped = Step {
7134            guard: None,
7135            kind: StepKind::WithIo {
7136                bindings,
7137                cmd: Box::new(cmd),
7138            },
7139            scope_enter: 0,
7140            scope_exit: 0,
7141            line: 0,
7142            col: 0,
7143        };
7144        let kind = StepKind::AssignAsync {
7145            var,
7146            decl_type,
7147            body: vec![wrapped],
7148        };
7149        let span = lowering_ctx(stmt);
7150        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7151            stmt,
7152            msg: e.to_string(),
7153            line: 0,
7154            col: 0,
7155            kind: None,
7156        })?;
7157        return Ok(Some((kind, 2 + 1 + used)));
7158    }
7159    if matches!(
7160        &first.kind,
7161        TokKind::Group {
7162            delim: GroupDelim::Brace,
7163            ..
7164        }
7165    ) {
7166        // A brace is no sync command: same validation error (probed).
7167        return Err(fail(
7168            "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7169                .to_string(),
7170        ));
7171    }
7172    // Sync inner: capture with the shared checks (the capture sink
7173    // owns stdout; async never runs inline).
7174    let (cmd, used) = parse_single_inner(
7175        rest,
7176        0,
7177        stmt,
7178        ctx,
7179        InnerRules {
7180            allow_await: false,
7181            allow_with_io: true,
7182        },
7183    )?;
7184    let span = lowering_ctx(stmt);
7185    if crate::commands::has_stdout_pipe(&bindings) {
7186        return Err(fail(
7187            "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
7188                .to_string(),
7189        ));
7190    }
7191    crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| TokenError {
7192        stmt,
7193        msg: e.to_string(),
7194        line: 0,
7195        col: 0,
7196        kind: None,
7197    })?;
7198    Ok(Some((
7199        StepKind::AssignCapture {
7200            var,
7201            decl_type,
7202            cmd: Box::new(StepKind::WithIo {
7203                bindings,
7204                cmd: Box::new(cmd),
7205            }),
7206        },
7207        2 + used,
7208    )))
7209}
7210
7211/// `ASYNC`-led LET right-hand side (the tokens after `ASYNC`):
7212/// a block or single command becomes the task body. No `WITH_IO`
7213/// scan (probed: this path accepts what statement `ASYNC`
7214/// rejects); nesting still fails loudly through the shared check.
7215fn parse_let_async_rhs(
7216    rest: &[Tok],
7217    var: String,
7218    decl_type: String,
7219    stmt: usize,
7220    ctx: &ParseCtx,
7221) -> Result<(StepKind, usize), TokenError> {
7222    let Some(first) = rest.first() else {
7223        return Err(TokenError {
7224            stmt,
7225            msg: "LET $var: HANDLE<T> = ASYNC requires a body".to_string(),
7226            line: 0,
7227            col: 0,
7228            kind: None,
7229        });
7230    };
7231    if matches!(
7232        &first.kind,
7233        TokKind::Group {
7234            delim: GroupDelim::Brace,
7235            ..
7236        }
7237    ) && !is_template_brace(first)
7238    {
7239        let inner = match &first.kind {
7240            TokKind::Group { inner, .. } => inner.clone(),
7241            _ => unreachable!(),
7242        };
7243        let body = parse_body_steps(&inner, stmt, ctx, false)?;
7244        let kind = StepKind::AssignAsync {
7245            var,
7246            decl_type,
7247            body,
7248        };
7249        let span = lowering_ctx(stmt);
7250        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7251            stmt,
7252            msg: e.to_string(),
7253            line: 0,
7254            col: 0,
7255            kind: None,
7256        })?;
7257        return Ok((kind, 1));
7258    }
7259    if first.joint {
7260        return Err(TokenError {
7261            stmt,
7262            msg: "LET $var: HANDLE<T> = ASYNC requires a body".to_string(),
7263            line: 0,
7264            col: 0,
7265            kind: None,
7266        });
7267    }
7268    let (cmd, used) = parse_single_inner(
7269        rest,
7270        0,
7271        stmt,
7272        ctx,
7273        InnerRules {
7274            allow_await: false,
7275            allow_with_io: false,
7276        },
7277    )?;
7278    let kind = StepKind::AssignAsync {
7279        var,
7280        decl_type,
7281        body: vec![Step {
7282            guard: None,
7283            kind: cmd,
7284            scope_enter: 0,
7285            scope_exit: 0,
7286            line: 0,
7287            col: 0,
7288        }],
7289    };
7290    let span = lowering_ctx(stmt);
7291    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
7292        stmt,
7293        msg: e.to_string(),
7294        line: 0,
7295        col: 0,
7296        kind: None,
7297    })?;
7298    Ok((kind, used))
7299}
7300
7301fn parse_set_body(
7302    body: &[Tok],
7303    stmt: usize,
7304    ctx: &ParseCtx,
7305) -> Result<(StepKind, usize), TokenError> {
7306    let mut cur = Cursor::expr(body, stmt);
7307    let var = expect_dollar_var(&mut cur, "mutation requires a variable: $var = <expr>")?;
7308    let assign = find_assign_eq(&body[cur.pos..]).map(|i| i + cur.pos);
7309    let eq = match assign {
7310        Some(eq) => eq,
7311        None => {
7312            return Err(cur.err("mutation requires a variable: $var = <expr>"));
7313        }
7314    };
7315    cur.pos = eq + 1;
7316    // Leading gap comments vanish like the `=` gap.
7317    cur.skip_gap();
7318    let expr = parse_expr_checked(&mut cur, ctx)?;
7319    Ok((StepKind::Set { var, expr }, cur.pos))
7320}
7321
7322fn parse_return_body(
7323    body: &[Tok],
7324    stmt: usize,
7325    ctx: &ParseCtx,
7326) -> Result<(StepKind, usize), TokenError> {
7327    let mut cur = Cursor::expr(body, stmt);
7328    match cur.next() {
7329        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_RETURN) => {}
7330        _ => return Err(cur.err("unreachable")),
7331    }
7332    if cur.done() {
7333        return Ok((
7334            StepKind::Return {
7335                expr: Box::new(Expr::Literal(Value::string(String::new()))),
7336                is_bare: true,
7337            },
7338            cur.pos,
7339        ));
7340    }
7341    let expr = parse_expr_checked(&mut cur, ctx)?;
7342    Ok((
7343        StepKind::Return {
7344            expr: Box::new(expr),
7345            is_bare: false,
7346        },
7347        cur.pos,
7348    ))
7349}
7350
7351/// Lower one statement to steps through the element loop: the
7352/// statement guard attaches to the first element only (trailing
7353/// elements ride guardless, probed): the pending guard clears after
7354/// the first command token.
7355fn lower_stmt_steps(
7356    stmt: &Stmt,
7357    idx: usize,
7358    ctx: &ParseCtx,
7359    in_block: bool,
7360    mark: bool,
7361) -> Result<Vec<Step>, TokenError> {
7362    let guard = parse_guard_groups(&stmt.guard, idx)?;
7363    // Statement-head braces route here (mid-run braces fail inside
7364    // the element loop): templates and guardless/bare blocks fail
7365    // loudly; guarded braces open guard blocks (top level) or the
7366    // nested quirk (in bodies).
7367    let mut steps = if starts_brace(&stmt.body) {
7368        parse_brace_head(stmt, guard, idx, ctx, in_block, mark)?
7369    } else {
7370        parse_elements(&stmt.body, idx, ctx, guard, in_block)?
7371    };
7372    // Stamp the statement's source position on every directly
7373    // produced step still missing one. Nested body steps were stamped
7374    // by their own statements during recursion, so only direct
7375    // products are claimed here; inner statements keep their own
7376    // lines and columns.
7377    for step in &mut steps {
7378        if step.line == 0 {
7379            step.line = stmt.line;
7380        }
7381        if step.col == 0 {
7382            step.col = stmt.col;
7383        }
7384    }
7385    // Qualify bare placeholder calls (`{{ NAME(args) }}`) through
7386    // the shared static resolver, so templates obey exactly the
7387    // statement-position scope rule. Nested bodies were already
7388    // qualified by their own recursive statements with their own
7389    // frames, so only direct products are visited here. Both
7390    // `Arg::String` fragments (via `walk_raw_strings_mut`) and
7391    // `Expr::Literal` strings (LET/SET/RETURN/call args/list/map
7392    // literals/parenthesized args) are qualified: expression
7393    // positions expand through the same `expand_string` at runtime,
7394    // so they must see the same parse-time rewrite. `WithIo` and
7395    // `AssignCapture` box their inner command directly (no recursive
7396    // statement pass), so the helper descends into them; all other
7397    // bodies were already qualified with their own frames.
7398    // `Step.guards` carry no template text (`Guard::Attr` triples
7399    // evaluated via `guard_allows`, never expanded), so there is
7400    // nothing to qualify there.
7401    let mut failed: Option<TokenError> = None;
7402    for step in &mut steps {
7403        qualify_step_templates(step, ctx, idx, &mut failed);
7404        if failed.is_some() {
7405            break;
7406        }
7407    }
7408    if let Some(err) = failed {
7409        return Err(err);
7410    }
7411    Ok(steps)
7412}
7413
7414/// Qualify one direct statement product plus any boxed `WithIo` /
7415/// `AssignCapture` inner command (same scope frame, never a
7416/// recursive statement pass). Body vectors are skipped: their steps
7417/// were qualified by their own recursive statements.
7418fn qualify_step_templates(
7419    step: &mut Step,
7420    ctx: &ParseCtx,
7421    stmt: usize,
7422    failed: &mut Option<TokenError>,
7423) {
7424    qualify_kind_templates(&mut step.kind, ctx, stmt, failed);
7425}
7426
7427/// Qualify one `StepKind` plus boxed inner commands sharing the
7428/// same scope frame.
7429fn qualify_kind_templates(
7430    kind: &mut StepKind,
7431    ctx: &ParseCtx,
7432    stmt: usize,
7433    failed: &mut Option<TokenError>,
7434) {
7435    kind.walk_raw_strings_mut(&mut |text| {
7436        if failed.is_none() {
7437            match qualify_template_calls(text, ctx, stmt) {
7438                Ok(Some(rewritten)) => *text = rewritten,
7439                Ok(None) => {}
7440                Err(err) => *failed = Some(err),
7441            }
7442        }
7443    });
7444    if failed.is_some() {
7445        return;
7446    }
7447    kind.walk_exprs_mut(&mut |expr| {
7448        if failed.is_some() {
7449            return;
7450        }
7451        expr.walk_mut(&mut |node| {
7452            if failed.is_some() {
7453                return;
7454            }
7455            if let Expr::Literal(value) = node
7456                && let Some(text) = value.as_str()
7457            {
7458                match qualify_template_calls(text, ctx, stmt) {
7459                    Ok(Some(rewritten)) => {
7460                        *value = Value::string(rewritten);
7461                    }
7462                    Ok(None) => {}
7463                    Err(err) => *failed = Some(err),
7464                }
7465            }
7466        });
7467    });
7468    if failed.is_some() {
7469        return;
7470    }
7471    // Boxed single commands share the outer scope frame (no recursive
7472    // statement pass built them): qualify the inner kind directly.
7473    match kind {
7474        StepKind::WithIo { cmd, .. } | StepKind::AssignCapture { cmd, .. } => {
7475            qualify_kind_templates(cmd, ctx, stmt, failed);
7476        }
7477        _ => {}
7478    }
7479    if failed.is_some() {
7480        return;
7481    }
7482    // Single-command synthetic bodies share the outer frame: `TIMEOUT 5s
7483    // <cmd>`, `ISOLATED <cmd>`, `ASYNC <cmd>`, and `AssignAsync` wrappers
7484    // build their `body` inline via `parse_single_inner` with no recursive
7485    // `lower_stmt_steps` pass, so their one synthetic step needs this one.
7486    // Brace-delimited bodies are NEVER re-walked here: they were already
7487    // lowered via `parse_body_steps` with their own frames and statement
7488    // indices (mirroring `Expr::walk_mut` skipping `Expr::Block`), and
7489    // re-resolving under the outer frame would corrupt scope isolation
7490    // and error attribution. The match names only the synthetic carriers;
7491    // any other body (If/For/While/FuncDef/RemoteBlock/WithIoBlock) stays
7492    // exactly as its own recursive pass left it.
7493    match kind {
7494        StepKind::Timeout { body, .. }
7495        | StepKind::Isolated { body }
7496        | StepKind::AsyncBlock { body }
7497        | StepKind::AssignAsync { body, .. } => {
7498            for step in body.iter_mut() {
7499                if failed.is_some() {
7500                    return;
7501                }
7502                qualify_step_templates(step, ctx, stmt, failed);
7503            }
7504        }
7505        _ => {}
7506    }
7507}
7508
7509/// Statement-head `{...}` dispatcher. Template braces fail (the
7510/// grammar strands them); guardless top-level braces fail; detached
7511/// or guardless in-body braces fail (no `block_start` in
7512/// `block_element`); guarded braces open a guard scope at top level
7513/// or mirror the nested quirk formula in bodies. Trailing elements
7514/// loop on guardless outside (like the grammar's continued line).
7515fn parse_brace_head(
7516    stmt: &Stmt,
7517    guard: Option<GuardExpr>,
7518    idx: usize,
7519    ctx: &ParseCtx,
7520    in_block: bool,
7521    mark: bool,
7522) -> Result<Vec<Step>, TokenError> {
7523    let brace = &stmt.body[0];
7524    if is_template_brace(brace) {
7525        return Err(TokenError {
7526            stmt: idx,
7527            msg: "'{' without a pending guard".to_string(),
7528            line: 0,
7529            col: 0,
7530            kind: None,
7531        });
7532    }
7533    let inner = match &brace.kind {
7534        TokKind::Group { inner, .. } => inner.clone(),
7535        _ => unreachable!(),
7536    };
7537    if in_block {
7538        // Attached guarded braces only: pending holds all groups but
7539        // the last (the block's own), mirroring the pair structure.
7540        if guard.is_none() || stmt.brace_detached || stmt.guard.is_empty() {
7541            return Err(TokenError {
7542                stmt: idx,
7543                msg: "unexpected '{' in block body".to_string(),
7544                line: 0,
7545                col: 0,
7546                kind: None,
7547            });
7548        }
7549        let n = stmt.guard.len();
7550        let mut pending = None;
7551        if n > 1 {
7552            pending = parse_guard_groups(&stmt.guard[..n - 1], idx)?;
7553        }
7554        let block_guard = parse_guard_groups(&stmt.guard[n - 1..n], idx)?.ok_or(TokenError {
7555            stmt: idx,
7556            msg: "unexpected '{' in block body".to_string(),
7557            line: 0,
7558            col: 0,
7559            kind: None,
7560        })?;
7561        let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
7562        // Guard-block bodies propagate the ambient marking context
7563        // (top-level nesting marks; wrapper bodies never mark).
7564        // Quirk formula verbatim (including the dropped block guard
7565        // with inner guards, probed).
7566        for s in &mut steps {
7567            let inner_guard = s.guard.take();
7568            s.guard = Some(match (pending.clone(), inner_guard) {
7569                (Some(p), Some(e)) => GuardExpr::all(vec![p, e]),
7570                (Some(p), None) => GuardExpr::all(vec![p, block_guard.clone()]),
7571                (None, Some(e)) => e,
7572                (None, None) => block_guard.clone(),
7573            });
7574        }
7575        // Marking contexts bump each nesting level (probed top-level
7576        // double-block 2/2); wrapper bodies stay 0/0.
7577        // Trailing elements ride outside, unmarked.
7578        if mark {
7579            if let Some(first) = steps.first_mut() {
7580                first.scope_enter += 1;
7581            }
7582            if let Some(last) = steps.last_mut() {
7583                last.scope_exit += 1;
7584            }
7585        }
7586        // Trailing elements loop on guardless outside.
7587        if stmt.body.len() > 1 {
7588            let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
7589            steps.append(&mut rest);
7590        }
7591        return Ok(steps);
7592    }
7593    // Top level: guardless braces fail; guarded braces open a guard
7594    // scope (each step folds outer-then-inner with markers).
7595    let Some(outer) = guard else {
7596        return Err(TokenError {
7597            stmt: idx,
7598            msg: "'{' without a pending guard".to_string(),
7599            line: 0,
7600            col: 0,
7601            kind: None,
7602        });
7603    };
7604    let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
7605    if steps.is_empty() {
7606        return Err(TokenError {
7607            stmt: idx,
7608            msg: "guard block must contain at least one command".to_string(),
7609            line: 0,
7610            col: 0,
7611            kind: None,
7612        });
7613    }
7614    for s in &mut steps {
7615        let inner_guard = s.guard.take();
7616        s.guard = Some(match inner_guard {
7617            Some(e) => GuardExpr::all(vec![outer.clone(), e]),
7618            None => outer.clone(),
7619        });
7620    }
7621    if let Some(first) = steps.first_mut() {
7622        first.scope_enter += 1;
7623    }
7624    if let Some(last) = steps.last_mut() {
7625        last.scope_exit += 1;
7626    }
7627    if stmt.body.len() > 1 {
7628        let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
7629        steps.append(&mut rest);
7630    }
7631    Ok(steps)
7632}
7633
7634/// Parse consecutive elements to end of run (the grammar's
7635/// `element*`): structural pairs (calls, RUN-exec, await/cancel,
7636/// wrapper blocks) end mid-run and trailing elements form following
7637/// steps; instructions and expressions consume greedily to the end.
7638fn parse_elements(
7639    toks: &[Tok],
7640    stmt: usize,
7641    ctx: &ParseCtx,
7642    guard: Option<GuardExpr>,
7643    in_block: bool,
7644) -> Result<Vec<Step>, TokenError> {
7645    let mut steps = Vec::new();
7646    let mut pos = 0;
7647    // Statement guard: consumed by the first element that yields a
7648    // step. `IMPORT` yields none, so the guard leaks to the next
7649    // element (probed).
7650    let mut pending_guard: Option<GuardExpr> = guard;
7651    while pos < toks.len() {
7652        // Trailing gap comments between elements (`} #c`, `F("a")
7653        // /*c*/ ECHO`, `LET $x: INT = 1 //c` — the pair ended, so the
7654        // comment is silent like the grammar, never payload):
7655        // `#` and lexer `Comment` markers run to the run end, `//`
7656        // likewise (line comments eat `;` too, and runs hold no
7657        // newlines), `/* */` balances. Mid-run `#`/`/*` stay payload
7658        // text inside the generic path, which consumes everything
7659        // and never loops back here.
7660        if matches!(&toks[pos].kind, TokKind::Punct('#'))
7661            || matches!(&toks[pos].kind, TokKind::Comment(_))
7662        {
7663            break;
7664        }
7665        if matches!(&toks[pos].kind, TokKind::Punct('/')) && is_comment_open(toks, pos) {
7666            if matches!(
7667                toks.get(pos + 1).map(|t| &t.kind),
7668                Some(TokKind::Punct('/'))
7669            ) {
7670                break;
7671            }
7672            match skip_inline_comment(toks, pos) {
7673                Some(past) => {
7674                    pos = past;
7675                    continue;
7676                }
7677                None => {
7678                    return Err(TokenError {
7679                        stmt,
7680                        msg: "unclosed block comment".to_string(),
7681                        line: 0,
7682                        col: 0,
7683                        kind: None,
7684                    });
7685                }
7686            }
7687        }
7688        // `IMPORT` statements update the import frames; module entries
7689        // emit no step (the guard leaks to the next element, probed,
7690        // unless this is top level, where a guarded module import
7691        // fails), while each file entry emits one `ImportFile` step
7692        // carrying the guard. Shape misses fall through to generic
7693        // (lowering fails them).
7694        if matches!(
7695            toks.get(pos).map(|t| &t.kind),
7696            Some(TokKind::Word(w)) if w == KEYWORD_IMPORT
7697        ) {
7698            // Unified statement form (#115): each entry validates hard
7699            // (unknown modules, bad aliases, templates, remote URLs);
7700            // module entries update the frame and emit no step, file
7701            // and harvest entries emit one step each, in source order.
7702            // A top-level guard on a statement with module entries fails
7703            // like the historical directive; file-only statements consume
7704            // the guard like any other element.
7705            if let Some(((modules, kinds), used)) = parse_import_statement(toks, pos, stmt, ctx)? {
7706                if !modules.is_empty() && !in_block && pending_guard.is_some() {
7707                    return Err(TokenError {
7708                        stmt,
7709                        msg: "IMPORT cannot be guarded".to_string(),
7710                        line: 0,
7711                        col: 0,
7712                        kind: None,
7713                    });
7714                }
7715                // Modules-only statements stay zero-step directives: the
7716                // guard leaks to the next element (probed). Anything with
7717                // file or harvest entries consumes it.
7718                let guard = if kinds.is_empty() {
7719                    None
7720                } else {
7721                    pending_guard.take()
7722                };
7723                for kind in kinds {
7724                    steps.push(Step {
7725                        guard: guard.clone(),
7726                        kind,
7727                        scope_enter: 0,
7728                        scope_exit: 0,
7729                        line: 0,
7730                        col: 0,
7731                    });
7732                }
7733                pos += used;
7734                continue;
7735            }
7736        }
7737        let guard = pending_guard.take();
7738        let (mut got, used) = parse_element_at(toks, pos, stmt, ctx, guard, in_block)?;
7739        if used == 0 {
7740            return Err(TokenError {
7741                stmt,
7742                msg: "element consumed no input".to_string(),
7743                line: 0,
7744                col: 0,
7745                kind: None,
7746            });
7747        }
7748        steps.append(&mut got);
7749        pos += used;
7750    }
7751    Ok(steps)
7752}
7753
7754/// Parse one element at `pos`, returning built steps (guard already
7755/// assigned: `first_guard` for the first, folded per io-block inner
7756/// step) and tokens consumed.
7757fn parse_element_at(
7758    toks: &[Tok],
7759    pos: usize,
7760    stmt: usize,
7761    ctx: &ParseCtx,
7762    first_guard: Option<GuardExpr>,
7763    in_block: bool,
7764) -> Result<(Vec<Step>, usize), TokenError> {
7765    let step = |kind: StepKind| Step {
7766        guard: first_guard.clone(),
7767        kind,
7768        scope_enter: 0,
7769        scope_exit: 0,
7770        line: 0,
7771        col: 0,
7772    };
7773    let head_word = match toks.get(pos).map(|t| &t.kind) {
7774        Some(TokKind::Word(w)) => Some(w.clone()),
7775        _ => None,
7776    };
7777    // Mid-run `{...}` (after a call, wrapper block, ...): the
7778    // grammar strands it (`block_start` needs a pending guard or
7779    // `WITH_IO` wait, both consumed), so fail loudly. Statement-head
7780    // braces route through `lower_stmt_steps`, never here.
7781    if starts_brace(&toks[pos..]) {
7782        return Err(TokenError {
7783            stmt,
7784            msg: "'{' without a pending guard".to_string(),
7785            line: 0,
7786            col: 0,
7787            kind: None,
7788        });
7789    }
7790    // LET/SET/RETURN heads parse with groups intact, then trailing
7791    // elements loop on (probed `LET $x: INT = 1 ECHO bye`). LET shape
7792    // misses fall to generic (lowering fails them like a committed
7793    // `instruction` would, e.g. `LET foo`).
7794    if head_word.as_deref() == Some(KEYWORD_LET)
7795        && let Some((kind, used)) = parse_let_body(&toks[pos..], stmt, ctx)?
7796    {
7797        return Ok((vec![step(kind)], used));
7798    }
7799    if matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('$'))) {
7800        let (kind, used) = parse_set_body(&toks[pos..], stmt, ctx)?;
7801        return Ok((vec![step(kind)], used));
7802    }
7803    if head_word.as_deref() == Some(KEYWORD_RETURN) {
7804        let (kind, used) = parse_return_body(&toks[pos..], stmt, ctx)?;
7805        return Ok((vec![step(kind)], used));
7806    }
7807    // Calls route before heads (even known commands take the call
7808    // path with a joint paren, probed `ECHO("hi")`); the call ends
7809    // mid-run and trailing elements loop on (fixes the slice-4a
7810    // divergence, probed).
7811    if call_shape_at(toks, pos, true).is_some() {
7812        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
7813        return Ok((vec![step(kind)], used));
7814    }
7815    // Block statements (shape misses fall to generic, which fails
7816    // them in lowering like the grammar's committed `instruction`).
7817    // `BREAK`/`CONTINUE` take no args (structural, like the grammar):
7818    // each consumes one token and trailing elements loop on (probed
7819    // `BREAK ECHO hi`); a lone trailing word fails downstream like
7820    // the grammar's committed mismatch.
7821    match head_word.as_deref() {
7822        Some(KEYWORD_BREAK) => {
7823            return Ok((vec![step(StepKind::Break)], 1));
7824        }
7825        Some(KEYWORD_CONTINUE) => {
7826            return Ok((vec![step(StepKind::Continue)], 1));
7827        }
7828        Some(KEYWORD_IF) => {
7829            if let Some((kind, used)) = parse_if_at(toks, pos, stmt, ctx)? {
7830                return Ok((vec![step(kind)], used));
7831            }
7832        }
7833        Some(KEYWORD_FOR) => {
7834            if let Some((kind, used)) = parse_for_at(toks, pos, stmt, ctx)? {
7835                return Ok((vec![step(kind)], used));
7836            }
7837        }
7838        Some(KEYWORD_WHILE) => {
7839            if let Some((kind, used)) = parse_while_single(toks, pos, stmt, ctx)? {
7840                return Ok((vec![step(kind)], used));
7841            }
7842        }
7843        Some(KEYWORD_FUNC) => {
7844            if let Some((kind, used)) = parse_func_at(toks, pos, stmt, ctx, false)? {
7845                return Ok((vec![step(kind)], used));
7846            }
7847        }
7848        Some(KEYWORD_REMOTE) => {
7849            if let Some((kind, used)) = parse_remote_single(toks, pos, stmt, ctx)? {
7850                return Ok((vec![step(kind)], used));
7851            }
7852        }
7853        _ => {}
7854    }
7855    // Wrappers (block or single); shape misses fall to generic.
7856    match head_word.as_deref() {
7857        Some(KEYWORD_WITH_IO) => {
7858            return parse_with_io_element(toks, pos, stmt, ctx, first_guard);
7859        }
7860        Some(KEYWORD_TIMEOUT) => {
7861            if let Some((kind, used)) = parse_timeout_single(toks, pos, stmt, ctx)? {
7862                return Ok((vec![step(kind)], used));
7863            }
7864        }
7865        Some(KEYWORD_ISOLATED) => {
7866            if let Some((kind, used)) = parse_isolated_single(toks, pos, stmt, ctx)? {
7867                return Ok((vec![step(kind)], used));
7868            }
7869        }
7870        Some(KEYWORD_ASYNC) => {
7871            // ASYNC FUNC definition form: prefix, parser records is_async
7872            // with no type-constraint validation (checker owns HANDLE rule).
7873            if matches!(toks.get(pos + 1).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC)
7874                && let Some((kind, used)) = parse_func_at(toks, pos + 1, stmt, ctx, true)?
7875            {
7876                return Ok((vec![step(kind)], 1 + used));
7877            }
7878            if let Some((kind, used)) = parse_async_single(toks, pos, stmt, ctx)? {
7879                return Ok((vec![step(kind)], used));
7880            }
7881        }
7882        _ => {}
7883    }
7884    // AWAIT/CANCEL statements (element level admits the `$` gap,
7885    // probed); heads without `$` go generic (lowering fails them).
7886    if matches!(
7887        head_word.as_deref(),
7888        Some(KEYWORD_AWAIT) | Some(KEYWORD_CANCEL)
7889    ) && let Some((kind, used)) = parse_await_cancel_at(toks, pos, stmt, false)?
7890    {
7891        return Ok((vec![step(kind)], used));
7892    }
7893    // `INHERIT_ENV [...]` parses strictly even at element level
7894    // (keys stay exact everywhere; slice 5 adds only the
7895    // prelude-order validation). Shape misses go generic.
7896    if head_word.as_deref() == Some(KEYWORD_INHERIT_ENV)
7897        && let Some((kind, used)) = parse_inherit_env_at(toks, pos, stmt)?
7898    {
7899        return Ok((vec![step(kind)], used));
7900    }
7901    // `EXPORT ...` records names (zero steps) or misses to generic;
7902    // level and guard violations fail loudly like the backend.
7903    if head_word.as_deref() == Some(KEYWORD_EXPORT) {
7904        if in_block {
7905            return Err(TokenError {
7906                stmt,
7907                msg: "EXPORT is only allowed at the top level".to_string(),
7908                line: 0,
7909                col: 0,
7910                kind: None,
7911            });
7912        }
7913        if first_guard.is_some() {
7914            return Err(TokenError {
7915                stmt,
7916                msg: "EXPORT cannot be guarded".to_string(),
7917                line: 0,
7918                col: 0,
7919                kind: None,
7920            });
7921        }
7922        if let Some((
7923            ExportNames {
7924                func_names,
7925                type_names,
7926            },
7927            used,
7928        )) = parse_export_at(toks, pos)
7929        {
7930            for name in &func_names {
7931                for part in name.split(MODULE_SEPARATOR) {
7932                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
7933                        .map_err(|e| lower_err(stmt, e))?;
7934                }
7935                if ctx.func_exports.borrow().contains(name)
7936                    || ctx.type_exports.borrow().contains(name)
7937                {
7938                    return Err(TokenError {
7939                        stmt,
7940                        msg: format!("duplicate EXPORT `{name}`"),
7941                        line: 0,
7942                        col: 0,
7943                        kind: Some(ParseErrorKind::Validation {
7944                            command: KEYWORD_EXPORT.to_string(),
7945                        }),
7946                    });
7947                }
7948                ctx.func_exports.borrow_mut().push(name.clone());
7949            }
7950            for name in &type_names {
7951                for part in name.split(MODULE_SEPARATOR) {
7952                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
7953                        .map_err(|e| lower_err(stmt, e))?;
7954                }
7955                if ctx.func_exports.borrow().contains(name)
7956                    || ctx.type_exports.borrow().contains(name)
7957                {
7958                    return Err(TokenError {
7959                        stmt,
7960                        msg: format!("duplicate EXPORT `{name}`"),
7961                        line: 0,
7962                        col: 0,
7963                        kind: Some(ParseErrorKind::Validation {
7964                            command: KEYWORD_EXPORT.to_string(),
7965                        }),
7966                    });
7967                }
7968                ctx.type_exports.borrow_mut().push(name.clone());
7969            }
7970            return Ok((Vec::new(), used));
7971        }
7972    }
7973    // `TYPE NAME = SHAPE` aliases (zero or one step); level and guard
7974    // violations fail loudly, shape misses fall to generic.
7975    if head_word.as_deref() == Some(KEYWORD_TYPE) {
7976        if in_block {
7977            return Err(TokenError {
7978                stmt,
7979                msg: "TYPE must appear at top level".to_string(),
7980                line: 0,
7981                col: 0,
7982                kind: None,
7983            });
7984        }
7985        if first_guard.is_some() {
7986            return Err(TokenError {
7987                stmt,
7988                msg: "TYPE cannot be guarded".to_string(),
7989                line: 0,
7990                col: 0,
7991                kind: None,
7992            });
7993        }
7994        if let Some((kind, used)) = parse_type_stmt_at(toks, pos, stmt)? {
7995            return Ok((vec![step(kind)], used));
7996        }
7997    }
7998    // Lowercase heads name their uppercase form (the grammar's
7999    // `command_name` mismatch): never a bare unknown-command.
8000    if let Some(head) = head_word.as_deref()
8001        && head.chars().all(|c| c.is_ascii_lowercase())
8002        && let upper = head.to_ascii_uppercase()
8003        && (is_known_command(&upper) || crate::STRUCTURAL_KEYWORDS.contains(&upper.as_str()))
8004    {
8005        return Err(TokenError {
8006            stmt,
8007            msg: format!("command must be uppercase: found `{head}`, expected `{upper}`"),
8008            line: 0,
8009            col: 0,
8010            kind: Some(ParseErrorKind::Syntax),
8011        });
8012    }
8013    // RUN-exec ends mid-run (trailing loops on, probed); generic
8014    // instructions consume everything.
8015    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8016    Ok((vec![step(kind)], used))
8017}
8018
8019/// Element-level `WITH_IO`: a same-run brace (any gap: `]{` works,
8020/// probed) opens the io-block form, wrapping every inner step with
8021/// scope markers; a joint non-brace follower is the pending-guard
8022/// error (the splitter only holds bare brackets); anything else is
8023/// the single form. Shape misses go generic.
8024fn parse_with_io_element(
8025    toks: &[Tok],
8026    pos: usize,
8027    stmt: usize,
8028    ctx: &ParseCtx,
8029    first_guard: Option<GuardExpr>,
8030) -> Result<(Vec<Step>, usize), TokenError> {
8031    // The bracket rides gapped (`sep`); anything else misses the
8032    // shape and generic fails it in lowering.
8033    let bracket = match toks.get(pos + 1) {
8034        Some(t)
8035            if !t.joint
8036                && matches!(
8037                    &t.kind,
8038                    TokKind::Group {
8039                        delim: GroupDelim::Bracket,
8040                        ..
8041                    }
8042                ) =>
8043        {
8044            Some(t)
8045        }
8046        _ => None,
8047    };
8048    let Some(bracket) = bracket else {
8049        // Shape miss: generic fails it in lowering.
8050        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8051        return Ok((
8052            vec![Step {
8053                guard: first_guard,
8054                kind,
8055                scope_enter: 0,
8056                scope_exit: 0,
8057                line: 0,
8058                col: 0,
8059            }],
8060            used,
8061        ));
8062    };
8063    let inner = match &bracket.kind {
8064        TokKind::Group { inner, .. } => inner.clone(),
8065        _ => unreachable!(),
8066    };
8067    let bindings = match parse_io_bindings(&inner, stmt)? {
8068        Some(bindings) => bindings,
8069        // Shape miss: generic fails it.
8070        None => {
8071            let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8072            return Ok((
8073                vec![Step {
8074                    guard: first_guard,
8075                    kind,
8076                    scope_enter: 0,
8077                    scope_exit: 0,
8078                    line: 0,
8079                    col: 0,
8080                }],
8081                used,
8082            ));
8083        }
8084    };
8085    let rest = pos + 2;
8086    // Same-run brace opens the io-block form (block-expanded
8087    // bindings skip the tty checks: the runtime repeats them).
8088    if let Some(next) = toks.get(rest)
8089        && matches!(
8090            &next.kind,
8091            TokKind::Group {
8092                delim: GroupDelim::Brace,
8093                ..
8094            }
8095        )
8096        && !is_template_brace(next)
8097    {
8098        let brace_inner = match &next.kind {
8099            TokKind::Group { inner, .. } => inner.clone(),
8100            _ => unreachable!(),
8101        };
8102        let mut steps = parse_body_steps(&brace_inner, stmt, ctx, false)?;
8103        if steps.is_empty() {
8104            return Err(TokenError {
8105                stmt,
8106                msg: "WITH_IO block must contain at least one command".to_string(),
8107                line: 0,
8108                col: 0,
8109                kind: None,
8110            });
8111        }
8112        // Every inner step wraps (merging when already wrapped,
8113        // like nested io scopes); the line guard folds into each
8114        // inner guard, inner-first (probed fold order).
8115        for s in &mut steps {
8116            let merged = match std::mem::replace(&mut s.kind, StepKind::Continue) {
8117                StepKind::WithIo {
8118                    bindings: inner_bindings,
8119                    cmd,
8120                } => StepKind::WithIo {
8121                    bindings: crate::commands::merge_bindings(&bindings, &inner_bindings),
8122                    cmd,
8123                },
8124                other => StepKind::WithIo {
8125                    bindings: bindings.clone(),
8126                    cmd: Box::new(other),
8127                },
8128            };
8129            s.kind = merged;
8130            s.guard = crate::commands::and_guard_exprs(s.guard.take(), first_guard.clone());
8131        }
8132        let span = lowering_ctx(stmt);
8133        for s in &steps {
8134            crate::commands::reject_nested_inherit_env(&span, &s.kind).map_err(|e| TokenError {
8135                stmt,
8136                msg: e.to_string(),
8137                line: 0,
8138                col: 0,
8139                kind: None,
8140            })?;
8141        }
8142        if let Some(first) = steps.first_mut() {
8143            first.scope_enter += 1;
8144        }
8145        if let Some(last) = steps.last_mut() {
8146            last.scope_exit += 1;
8147        }
8148        return Ok((steps, rest + 1 - pos));
8149    }
8150    if rest >= toks.len() {
8151        // Unreachable: the splitter holds bare brackets for `{`.
8152        // Kept for body-parsed runs, mirroring the transient node.
8153        return Ok((
8154            vec![Step {
8155                guard: first_guard,
8156                kind: StepKind::WithIoBlock { bindings },
8157                scope_enter: 0,
8158                scope_exit: 0,
8159                line: 0,
8160                col: 0,
8161            }],
8162            2,
8163        ));
8164    }
8165    // A joint follower misses the inner `sep`: the pending wait
8166    // fails exactly like the grammar.
8167    if toks[rest].joint {
8168        return Err(TokenError {
8169            stmt,
8170            msg: "WITH_IO block must be followed by '{'".to_string(),
8171            line: 0,
8172            col: 0,
8173            kind: None,
8174        });
8175    }
8176    // Single form, shared with single-inner (element guards the step).
8177    let (cmd, used) = parse_single_inner(
8178        toks,
8179        rest,
8180        stmt,
8181        ctx,
8182        InnerRules {
8183            allow_await: false,
8184            allow_with_io: true,
8185        },
8186    )?;
8187    let span = lowering_ctx(stmt);
8188    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| TokenError {
8189        stmt,
8190        msg: e.to_string(),
8191        line: 0,
8192        col: 0,
8193        kind: None,
8194    })?;
8195    let kind = StepKind::WithIo {
8196        bindings,
8197        cmd: Box::new(cmd),
8198    };
8199    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| TokenError {
8200        stmt,
8201        msg: e.to_string(),
8202        line: 0,
8203        col: 0,
8204        kind: None,
8205    })?;
8206    Ok((
8207        vec![Step {
8208            guard: first_guard,
8209            kind,
8210            scope_enter: 0,
8211            scope_exit: 0,
8212            line: 0,
8213            col: 0,
8214        }],
8215        2 + used,
8216    ))
8217}
8218
8219/// Shared inner-command parser: statement calls (joint paren, even on
8220/// known commands), RUN exec
8221/// form, and generic instructions. Returns the kind and tokens
8222/// consumed: calls and RUN-exec end mid-run (the caller continues
8223/// past them, like the grammar's `element*`); generic instructions
8224/// consume everything. Wrappers never route here (element and
8225/// single-inner dispatch own them); slice 4b reuses the call/RUN
8226/// arms for trailing elements.
8227fn parse_inner_command(
8228    body: &[Tok],
8229    stmt: usize,
8230    ctx: &ParseCtx,
8231) -> Result<(StepKind, usize), TokenError> {
8232    // Bare `NAME(...)` calls invoke functions with one syntax; the head
8233    // and `(` ride gapless or the shape stays an instruction (which
8234    // fails later as UnknownCommand), exactly like the grammar.
8235    if let Some((call_name, paren)) = call_shape_at(body, 0, true) {
8236        let inner = match &body[paren].kind {
8237            TokKind::Group { inner, .. } => inner.clone(),
8238            _ => unreachable!(),
8239        };
8240        let args = parse_call_args(&inner, stmt, ctx)?;
8241        // Statement-level `INSPECT(...)` resolves like any other call
8242        // (only expression position mints the node); unknown functions
8243        // fail in the shared resolver with identical messages.
8244        if !call_name.contains(MODULE_SEPARATOR) {
8245            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
8246                .map_err(|e| lower_err(stmt, e))?;
8247        }
8248        let qualified = resolve_name(ctx, stmt, &call_name)?;
8249        return Ok((
8250            StepKind::Call {
8251                name: qualified,
8252                args,
8253            },
8254            paren + 1,
8255        ));
8256    }
8257    let head = match body.first().map(|t| &t.kind) {
8258        Some(TokKind::Word(n)) => n.clone(),
8259        _ => {
8260            return Err(TokenError {
8261                stmt,
8262                msg: "statement must open with a command word".to_string(),
8263                line: 0,
8264                col: 0,
8265                kind: None,
8266            });
8267        }
8268    };
8269    // RUN exec form: the list routes structured through `lower` (the
8270    // mock wraps it in `Run`; production maps it to `RunExec`); the
8271    // caller continues past the list, like the grammar. The list
8272    // rides gapped (`sep`): a joint bracket is a hard error, never
8273    // a spliced arg (probed `RUN["a"]`).
8274    if head == KEYWORD_RUN
8275        && matches!(
8276            body.get(1).map(|t| &t.kind),
8277            Some(TokKind::Group {
8278                delim: GroupDelim::Bracket,
8279                ..
8280            })
8281        )
8282    {
8283        if body[1].joint {
8284            return Err(TokenError {
8285                stmt,
8286                msg: "RUN [...] requires a gap after RUN".to_string(),
8287                line: 0,
8288                col: 0,
8289                kind: None,
8290            });
8291        }
8292        let inner = match &body[1].kind {
8293            TokKind::Group { inner, .. } => inner.clone(),
8294            _ => unreachable!(),
8295        };
8296        // Non-map blocks miss the exec shape (the grammar has no
8297        // `block` alternative here); fall through to the shell path
8298        // below, which reads the bracket literally.
8299        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
8300            let kind =
8301                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
8302            return Ok((kind, 2));
8303        }
8304    }
8305    let (tokens, deferred) = build_arg_tokens(&body[1..], stmt, ctx)?;
8306    let lowered = lower_generic_args(&head, tokens, stmt, ctx);
8307    match lowered {
8308        Ok(kind) => {
8309            // Stashed call errors surface only for otherwise well-formed
8310            // statements: the command head owns its syntax, so a malformed
8311            // header keeps its tailored error instead of being masked by an
8312            // argument-position resolution failure.
8313            if let Some(err) = deferred {
8314                return Err(err);
8315            }
8316            Ok((kind, body.len()))
8317        }
8318        Err(lower_err) => {
8319            // Fallback raw strings (`NOPE()` rendered as text) can fail
8320            // argument-shape lowering with a misleading error. The
8321            // stashed unknown-callee error names the real culprit, so
8322            // it wins over every argument-level failure (`Validation`,
8323            // `Syntax`, `InvalidSyntax`, or the `None` classification
8324            // that `ENV`/`EXPAND` lowering uses). Heads owned by a
8325            // statement-header parser (`FUNC`, `LET`, `IF`, `FOR`,
8326            // `WHILE`, `TYPE`, `IMPORT`, `EXPORT`, `REMOTE`, `WITH_IO`)
8327            // keep their lowering `InvalidSyntax`: those parsers miss to
8328            // this path on shape miss (e.g. `FUNC FOO() ECHO hi` has no
8329            // body block), so the lowering error names the malformed
8330            // header while the stashed name is its definiendum, never an
8331            // argument-position call. Every other head is a plain
8332            // command, so a lowering `InvalidSyntax` there is an
8333            // argument-shape failure from the raw-text fallback, and
8334            // the stashed callee names the culprit. Only
8335            // head-identity errors (`UnknownCommand`, `Structural`)
8336            // keep their tailored diagnostic everywhere.
8337            let is_header_syntax = matches!(
8338                head.as_str(),
8339                KEYWORD_FUNC
8340                    | KEYWORD_LET
8341                    | KEYWORD_IF
8342                    | KEYWORD_FOR
8343                    | KEYWORD_WHILE
8344                    | KEYWORD_TYPE
8345                    | KEYWORD_IMPORT
8346                    | KEYWORD_EXPORT
8347                    | KEYWORD_REMOTE
8348                    | KEYWORD_WITH_IO
8349            ) && matches!(
8350                lower_err.kind,
8351                Some(crate::error::ParseErrorKind::InvalidSyntax { .. })
8352            );
8353            if let Some(deferred_err) = deferred
8354                && !is_header_syntax
8355                && matches!(
8356                    lower_err.kind,
8357                    Some(crate::error::ParseErrorKind::Validation { .. })
8358                        | Some(crate::error::ParseErrorKind::Syntax)
8359                        | Some(crate::error::ParseErrorKind::InvalidSyntax { .. })
8360                        | None
8361                )
8362            {
8363                return Err(deferred_err);
8364            }
8365            Err(lower_err)
8366        }
8367    }
8368}
8369
8370/// Parse a token stream (either lexer) into steps. Markers normalize to
8371/// 0/0 like the fuzz harness; scopes arrive with block slices.
8372pub fn parse_tokens(
8373    toks: &[Tok],
8374    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8375) -> Result<Vec<Step>, TokenError> {
8376    let modules = ModuleTable::default();
8377    let reserved = HashSet::new();
8378    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
8379    parse_tokens_with_ctx(toks, &ctx)
8380}
8381
8382/// Parse with an explicit context (module table for call resolution).
8383/// `parse_tokens` uses empty modules.
8384pub fn parse_tokens_with_ctx(toks: &[Tok], ctx: &ParseCtx) -> Result<Vec<Step>, TokenError> {
8385    let mut out = Vec::new();
8386    *ctx.current_line.borrow_mut() = 1;
8387    let stmts = split_statements(toks, 1)?;
8388    predeclare_forward_funcs(&stmts, ctx);
8389    for (i, s) in stmts.iter().enumerate() {
8390        *ctx.current_line.borrow_mut() = s.line;
8391        out.extend(
8392            lower_stmt_steps(s, i, ctx, false, true).map_err(|e| stamp_pos(e, s.line, s.col))?,
8393        );
8394    }
8395    // Whole-script validations through the shared validators.
8396    // `INHERIT_ENV` prelude order: only leading positions read.
8397    {
8398        let mut seen_non_prelude = false;
8399        for step in &out {
8400            match &step.kind {
8401                StepKind::InheritEnv { .. } => {
8402                    if seen_non_prelude {
8403                        return Err(TokenError {
8404                            stmt: out.len(),
8405                            msg: "INHERIT_ENV must appear before any other commands".to_string(),
8406                            line: 0,
8407                            col: 0,
8408                            kind: None,
8409                        });
8410                    }
8411                }
8412                kind => {
8413                    if crate::commands::contains_inherit_env(kind) {
8414                        return Err(TokenError {
8415                            stmt: out.len(),
8416                            msg: "INHERIT_ENV cannot be nested inside other commands".to_string(),
8417                            line: 0,
8418                            col: 0,
8419                            kind: None,
8420                        });
8421                    }
8422                    // Harvest imports stay prelude: they bind functions
8423                    // and types without executing module bodies, so they
8424                    // neither read nor disturb the inherited environment.
8425                    // File imports execute arbitrary top-level steps on
8426                    // import, so they end the prelude like any other
8427                    // side-effecting command. Host-only IMPORTs emit no
8428                    // step at all, which is why they never tripped this
8429                    // gate.
8430                    if !matches!(kind, StepKind::ImportFuncs { .. }) {
8431                        seen_non_prelude = true;
8432                    }
8433                }
8434            }
8435        }
8436    }
8437    crate::commands::validate_remote_copy_placement(&out, &lowering_ctx(out.len())).map_err(
8438        |e| TokenError {
8439            stmt: out.len(),
8440            msg: e.to_string(),
8441            line: 0,
8442            col: 0,
8443            kind: None,
8444        },
8445    )?;
8446    {
8447        let top: HashSet<String> = ctx.funcs.borrow().first().cloned().unwrap_or_default();
8448        let top_imports: Vec<String> = ctx.imports.borrow().first().cloned().unwrap_or_default();
8449        let mut top_types = HashSet::new();
8450        for step in &out {
8451            if let StepKind::TypeAlias { name, .. } = &step.kind {
8452                top_types.insert(name.clone());
8453            }
8454        }
8455        crate::commands::validate_exports(
8456            &lowering_ctx(out.len()),
8457            &ctx.func_exports.borrow(),
8458            &ctx.type_exports.borrow(),
8459            &top,
8460            &top_types,
8461            ctx.modules,
8462            &top_imports,
8463        )
8464        .map_err(|e| TokenError {
8465            stmt: out.len(),
8466            msg: e.to_string(),
8467            line: 0,
8468            col: 0,
8469            kind: None,
8470        })?;
8471    }
8472    Ok(out)
8473}
8474
8475// ---- String entry points: lex, lower, collect exports and docs ----
8476
8477/// Source text of a 1-based line. The line just past a trailing
8478/// newline (where unbalanced groups report) reads as empty text so
8479/// caret blocks still render.
8480fn source_line_of(input: &str, line: usize) -> Option<String> {
8481    let count = input.lines().count();
8482    let idx = line.checked_sub(1)?;
8483    if idx < count {
8484        input.lines().nth(idx).map(str::to_string)
8485    } else if idx == count {
8486        Some(String::new())
8487    } else {
8488        None
8489    }
8490}
8491
8492/// Last script line (end-of-script validations blame it).
8493fn last_line(input: &str) -> usize {
8494    input.lines().count().max(1)
8495}
8496
8497/// Convert a lexer failure: low-level syntax kind, exact lexer
8498/// position, and the source line for the caret block. Unclosed groups
8499/// name their opener (no grammar dumps); the closer expectation rides
8500/// along so `expected()` stays informative. A lexer-known kind (an
8501/// unclosed `WITH_IO` bracket) converts verbatim.
8502fn lex_error(input: &str, e: LexError) -> ParseError {
8503    let line = e.line.max(1);
8504    let ctx = match source_line_of(input, line) {
8505        Some(source_line) => SpanContext::full(line, e.col.max(1), e.col.max(1), source_line),
8506        None => SpanContext::line_only(line),
8507    };
8508    if let Some(ParseErrorKind::InvalidSyntax { command }) = e.kind {
8509        // Lexer-known command syntax (an unclosed `WITH_IO` bracket).
8510        return ParseError::invalid_syntax(
8511            &command,
8512            e.msg,
8513            None,
8514            vec!["`]`".to_string()],
8515            None,
8516            &ctx,
8517        );
8518    }
8519    let expected = if e.msg.starts_with("unclosed") {
8520        vec!["`}`".to_string()]
8521    } else {
8522        Vec::new()
8523    };
8524    ParseError::syntax(e.msg, expected, None, &ctx)
8525}
8526
8527/// Convert a backend failure, preserving the dispatcher's error kind
8528/// and completing line/source context the token stream knows. Spans
8529/// open at the statement's start column and cover its whole first line
8530/// (multi-line spans clamp to the start line), so caret blocks render
8531/// for every string-path error.
8532fn token_error(input: &str, e: TokenError) -> ParseError {
8533    let line = if e.line == 0 {
8534        last_line(input)
8535    } else {
8536        e.line
8537    };
8538    let start_col = e.col.max(1);
8539    let ctx = match source_line_of(input, line) {
8540        Some(source_line) => {
8541            let end = source_line.len().max(start_col);
8542            SpanContext::full(line, start_col, end, source_line)
8543        }
8544        None => SpanContext::line_only(line),
8545    };
8546    // Column spans are statement granularity (every error names its
8547    // statement's first column); the caret block still renders.
8548    match e.kind {
8549        Some(crate::error::ParseErrorKind::UnknownCommand { name }) => {
8550            ParseError::unknown_command(&name, e.msg, None, &ctx)
8551        }
8552        Some(crate::error::ParseErrorKind::InvalidSyntax { command }) => {
8553            ParseError::invalid_syntax(&command, e.msg, None, Vec::new(), None, &ctx)
8554        }
8555        Some(crate::error::ParseErrorKind::Validation { command }) => {
8556            ParseError::validation(&command, e.msg, &ctx)
8557        }
8558        Some(crate::error::ParseErrorKind::Syntax) => {
8559            ParseError::syntax(e.msg, Vec::new(), None, &ctx)
8560        }
8561        Some(crate::error::ParseErrorKind::Structural { rule }) => {
8562            ParseError::structural(&rule, e.msg, &ctx)
8563        }
8564        None => ParseError::structural("statement", e.msg, &ctx),
8565    }
8566}
8567
8568/// Shared parse driver: lex, lower with preseeded frames, and collect
8569/// `EXPORT` names (validated at end of parse, forward references
8570/// allowed).
8571fn parse_with_ctx(
8572    input: &str,
8573    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8574    reserved_names: HashSet<String>,
8575    modules: ModuleTable,
8576    preseed_funcs: HashSet<String>,
8577    preseed_imports: Vec<String>,
8578) -> ParseResult<ScriptWithExports> {
8579    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
8580    let ctx = ParseCtx::empty(&lower, &modules, &reserved_names);
8581    // Snippet re-parses seed their base frames so lookup behaves
8582    // identically; snippets never define, only read.
8583    ctx.funcs.borrow_mut()[0].extend(preseed_funcs);
8584    ctx.imports.borrow_mut()[0].extend(preseed_imports);
8585    let steps = parse_tokens_with_ctx(&toks, &ctx).map_err(|e| token_error(input, e))?;
8586    let mut steps = steps;
8587    stamp_func_docs(input, &mut steps);
8588    Ok(ScriptWithExports {
8589        steps,
8590        func_exports: ctx.func_exports.borrow().clone(),
8591        type_exports: ctx.type_exports.borrow().clone(),
8592    })
8593}
8594
8595/// Steps plus single-file `EXPORT` metadata, before `#` doc stamping.
8596/// Callers needing docs build a [`ParsedScript`] from this.
8597struct ScriptWithExports {
8598    steps: Vec<Step>,
8599    func_exports: Vec<String>,
8600    type_exports: Vec<String>,
8601}
8602
8603/// Parse a script with an unknown host environment.
8604pub fn parse_script(
8605    input: &str,
8606    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8607) -> ParseResult<Vec<Step>> {
8608    Ok(parse_with_ctx(
8609        input,
8610        lower,
8611        HashSet::new(),
8612        ModuleTable::default(),
8613        HashSet::new(),
8614        Vec::new(),
8615    )?
8616    .steps)
8617}
8618
8619/// Parse a snippet with an enclosing parse's visible scope state, so
8620/// re-parsed inner commands (async bodies) resolve calls identically.
8621/// The snippet never defines, only reads: seeds affect lookup alone.
8622pub fn parse_script_with_preseed(
8623    input: &str,
8624    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8625    reserved_names: HashSet<String>,
8626    modules: ModuleTable,
8627    preseed_funcs: HashSet<String>,
8628    preseed_imports: Vec<String>,
8629) -> ParseResult<Vec<Step>> {
8630    Ok(parse_with_ctx(
8631        input,
8632        lower,
8633        reserved_names,
8634        modules,
8635        preseed_funcs,
8636        preseed_imports,
8637    )?
8638    .steps)
8639}
8640
8641/// Parse with a module provenance table so calls resolve statically:
8642/// qualified `MODULE::NAME` checks membership, bare `NAME` resolves through
8643/// `SCRIPT` definitions and `IMPORT`ed modules, and anything else fails at
8644/// parse time instead of at runtime.
8645pub fn parse_script_with_modules(
8646    input: &str,
8647    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8648    reserved_names: HashSet<String>,
8649    modules: ModuleTable,
8650) -> ParseResult<Vec<Step>> {
8651    Ok(parse_script_with_modules_and_exports(input, lower, reserved_names, modules)?.steps)
8652}
8653
8654/// Parse with modules plus single-file `EXPORT` metadata and `#` doc
8655/// comments for top-level `FUNC`s. Used by the MCP host; the linear
8656/// runner keeps using `parse_script_with_modules` and ignores exports.
8657pub fn parse_script_with_modules_and_exports(
8658    input: &str,
8659    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8660    reserved_names: HashSet<String>,
8661    modules: ModuleTable,
8662) -> ParseResult<ParsedScript> {
8663    let ScriptWithExports {
8664        steps,
8665        func_exports,
8666        type_exports,
8667    } = parse_with_ctx(
8668        input,
8669        lower,
8670        reserved_names,
8671        modules,
8672        HashSet::new(),
8673        Vec::new(),
8674    )?;
8675    Ok(ParsedScript {
8676        func_docs: collect_func_docs(input, &steps),
8677        steps,
8678        func_exports,
8679        type_exports,
8680    })
8681}
8682
8683/// Parse without modules plus `EXPORT` metadata. Used by tests and
8684/// tooling that lower with the shared mock.
8685pub fn parse_script_with_exports(
8686    input: &str,
8687    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
8688) -> ParseResult<ParsedScript> {
8689    let ScriptWithExports {
8690        steps,
8691        func_exports,
8692        type_exports,
8693    } = parse_with_ctx(
8694        input,
8695        lower,
8696        HashSet::new(),
8697        ModuleTable::default(),
8698        HashSet::new(),
8699        Vec::new(),
8700    )?;
8701    Ok(ParsedScript {
8702        func_docs: collect_func_docs(input, &steps),
8703        steps,
8704        func_exports,
8705        type_exports,
8706    })
8707}
8708
8709/// Parse one expression from source text with an empty module scope, for
8710/// tooling that shows lowering without running (docs demos, explain output).
8711/// No imports exist here, so bare function calls fail and qualified calls
8712/// fail against the empty table; only `INSPECT` passes through untouched.
8713/// Arithmetic, comparison, variables, env reads, keypaths, and literals
8714/// lower normally, with literal only subtrees folded before flattening.
8715pub fn parse_expression_str(input: &str) -> ParseResult<Expr> {
8716    // Trailing whitespace lexes unconsumed, so lex the trimmed text:
8717    // otherwise padded but valid input fails the full consumption check.
8718    let trimmed = input.trim();
8719    let toks = lex_str(trimmed).map_err(|e| lex_error(trimmed, e))?;
8720    let modules = ModuleTable::default();
8721    let reserved = HashSet::new();
8722    let lower = crate::commands::lower_command as fn(&str, Vec<Arg>) -> ParseResult<StepKind>;
8723    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
8724    *ctx.current_line.borrow_mut() = 1;
8725    parse_single_expr(&toks, 0, &ctx).map_err(|e| token_error(trimmed, e))
8726}
8727
8728/// Parse one guard expression from source text (a bare `guard_seq`:
8729/// predicates, `not`/`any`/`all`, comma lists), for tooling and tests.
8730pub fn parse_guard_expr_str(input: &str) -> ParseResult<GuardExpr> {
8731    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
8732    parse_single_guard(&toks, 0).map_err(|e| token_error(input, e))
8733}
8734
8735/// Parsed script with single-file `EXPORT` metadata. `steps` is the
8736/// linear execution plan, `func_exports` the `EXPORT` func names in
8737/// source order, `type_exports` the `EXPORT TYPE` names in source order,
8738/// and `func_docs` maps top-level `FUNC` base names to (summary, docs)
8739/// collected from the immediately preceding `#` comment block.
8740#[derive(Debug, Clone, Default)]
8741pub struct ParsedScript {
8742    pub steps: Vec<Step>,
8743    pub func_exports: Vec<String>,
8744    pub type_exports: Vec<String>,
8745    pub func_docs: std::collections::HashMap<String, (String, String)>,
8746}
8747
8748fn collect_func_docs(
8749    input: &str,
8750    steps: &[Step],
8751) -> std::collections::HashMap<String, (String, String)> {
8752    use std::collections::{HashMap, HashSet};
8753    let lines: Vec<&str> = input.lines().collect();
8754    // Top-level FUNC definition lines keyed by base name. Brace depth
8755    // tracks nesting so only depth-0 `FUNC` lines count; the first
8756    // occurrence wins because same-scope duplicates fail at lowering.
8757    let mut def_lines: HashMap<String, usize> = HashMap::new();
8758    let mut seen: HashSet<String> = HashSet::new();
8759    let mut depth: usize = 0;
8760    for (idx, line) in lines.iter().enumerate() {
8761        let trimmed = line.trim_start();
8762        let is_comment = trimmed.starts_with('#');
8763        let is_guard_only = trimmed.starts_with('[');
8764        if !is_comment
8765            && !is_guard_only
8766            && let Some(rest) = strip_func_head(trimmed)
8767            && depth == 0
8768            && !seen.contains(&rest)
8769        {
8770            seen.insert(rest.clone());
8771            def_lines.insert(rest, idx + 1);
8772        }
8773        if !is_comment {
8774            for ch in line.chars() {
8775                if ch == '{' {
8776                    depth = depth.saturating_add(1);
8777                } else if ch == '}' {
8778                    depth = depth.saturating_sub(1);
8779                }
8780            }
8781        }
8782    }
8783    let mut out: HashMap<String, (String, String)> = HashMap::new();
8784    for step in steps {
8785        if let StepKind::FuncDef { name, .. } = &step.kind
8786            && !out.contains_key(name)
8787            && let Some(&line_no) = def_lines.get(name)
8788            && let Some((summary, docs)) = docs_above(&lines, line_no)
8789        {
8790            out.insert(name.clone(), (summary, docs));
8791        }
8792    }
8793    out
8794}
8795
8796/// Stamp `#` doc blocks onto top-level `FUNC` steps, from the same map
8797/// that feeds `func_docs`, so step-carried docs and the sidecar can
8798/// never disagree. Only top-level definitions qualify (same rule as
8799/// collection); nested shadowing keeps `docs: None`.
8800fn stamp_func_docs(input: &str, steps: &mut [Step]) {
8801    let docs = collect_func_docs(input, steps);
8802    for step in steps {
8803        if let StepKind::FuncDef {
8804            name, docs: slot, ..
8805        } = &mut step.kind
8806            && slot.is_none()
8807            && let Some(pair) = docs.get(name)
8808        {
8809            *slot = Some(pair.clone());
8810        }
8811    }
8812}
8813
8814fn strip_func_head(trimmed: &str) -> Option<String> {
8815    let rest = trimmed.strip_prefix(KEYWORD_FUNC)?;
8816    let after = rest.strip_prefix([' ', '\t'])?;
8817    if after.is_empty() {
8818        return None;
8819    }
8820    let name: String = after
8821        .chars()
8822        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
8823        .collect();
8824    if name.is_empty()
8825        || !name
8826            .bytes()
8827            .all(|b| b.is_ascii_uppercase() || b == b'_' || b.is_ascii_digit())
8828    {
8829        return None;
8830    }
8831    if name.starts_with(|c: char| c.is_ascii_digit()) {
8832        return None;
8833    }
8834    Some(name)
8835}
8836
8837fn docs_above(lines: &[&str], line_no: usize) -> Option<(String, String)> {
8838    if line_no <= 1 {
8839        return None;
8840    }
8841    let mut block: Vec<String> = Vec::new();
8842    let mut idx = line_no - 1;
8843    while idx > 0 {
8844        idx -= 1;
8845        let trimmed = lines[idx].trim_start();
8846        if trimmed.is_empty() {
8847            break;
8848        }
8849        if let Some(body) = trimmed.strip_prefix('#') {
8850            let text = body.strip_prefix(' ').unwrap_or(body);
8851            block.push(text.to_string());
8852        } else {
8853            break;
8854        }
8855        if idx == 0 {
8856            break;
8857        }
8858    }
8859    if block.is_empty() {
8860        return None;
8861    }
8862    block.reverse();
8863    let summary = block.first().cloned().unwrap_or_default();
8864    let docs = block.join("\n");
8865    Some((summary, docs))
8866}
8867
8868#[cfg(test)]
8869mod tests {
8870    use super::*;
8871    use crate::test_lower_mock;
8872    use indoc::indoc;
8873
8874    fn lower(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
8875        test_lower_mock::lower(name, args)
8876    }
8877
8878    /// Lexer-agreement oracle: both frontends must deliver identical
8879    /// steps through the single backend. `parse_script` is the string
8880    /// entry point; `parse_tokens` runs each lexer's output directly.
8881    fn assert_parity(text: &str) {
8882        let old = crate::parse_script(text, lower)
8883            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
8884        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
8885        let new = parse_tokens(&toks, lower)
8886            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
8887        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
8888        #[cfg(feature = "proc-macro-api")]
8889        {
8890            let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
8891            let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
8892            let new = parse_tokens(&toks, lower).expect("token path must parse token script");
8893            assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
8894        }
8895    }
8896
8897    /// String-path-only oracle for shapes `rustc` cannot carry at all
8898    /// (lifetime-like quotes). The backend must still agree there.
8899    fn assert_parity_string_only(text: &str) {
8900        let old = crate::parse_script(text, lower)
8901            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
8902        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
8903        let new = parse_tokens(&toks, lower)
8904            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
8905        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
8906    }
8907
8908    #[test]
8909    fn token_and_string_paths_agree_on_wrappers() {
8910        // Single-command wrappers, io-blocks, await/cancel,
8911        // LET wrapper forms — three-way agreement per script.
8912        for text in [
8913            "WITH_IO [stdout=$p] ECHO hi",
8914            "WITH_IO [stdin=$p] ECHO hi",
8915            "WITH_IO [stdin] ECHO hi",
8916            "WITH_IO [stdout] ECHO hi",
8917            "WITH_IO [stdin=$p, stdout=$q] ECHO hi",
8918            "WITH_IO [stdin=$p, stdin=$q] ECHO hi",
8919            "WITH_IO [tty] RUN echo hi",
8920            "WITH_IO [tty, rows=40, cols=100] RUN echo hi",
8921            "WITH_IO [rows=40, cols=100, tty] RUN echo hi",
8922            "WITH_IO [stdin =$p] ECHO hi",
8923            "WITH_IO [stdin= $p] ECHO hi",
8924            "WITH_IO [ stdin=$p ] ECHO hi",
8925            "WITH_IO [\nstdin=$p\n] ECHO hi",
8926            "WITH_IO [stdin=$p\n, stdout=$q] ECHO hi",
8927            "WITH_IO [stdout=$p] ASYNC ECHO hi",
8928            "WITH_IO [stdin=$p] WITH_IO [stderr=$e] ECHO hi",
8929            "WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
8930            "WITH_IO [stdin=$p] ISOLATED ECHO hi",
8931            "WITH_IO [stdin=$p] CANCEL $t",
8932            "WITH_IO [stdin=$p] CANCEL $t ECHO bye",
8933            "WITH_IO [stdin=$p] { ECHO hi }",
8934            "WITH_IO [stdin=$p]\n{ ECHO hi }",
8935            "WITH_IO [stdin=$p]; { ECHO hi }",
8936            "WITH_IO [stdin=$p]{ ECHO hi }",
8937            "WITH_IO [stdin=$p] { ECHO a\nECHO b }",
8938            "WITH_IO [stdin=$p] { ECHO hi } ECHO bye",
8939            "WITH_IO [rows=40] { ECHO hi }",
8940            "WITH_IO [tty] { ECHO hi }",
8941            "WITH_IO [stdin=$p] { WITH_IO [stderr=$e] ECHO hi }",
8942            "TIMEOUT 10s ECHO hi",
8943            "TIMEOUT 10 ECHO hi",
8944            "TIMEOUT 500ms ECHO hi",
8945            "TIMEOUT 5m ECHO hi",
8946            "TIMEOUT 2h ECHO hi",
8947            "TIMEOUT $d ECHO hi",
8948            "TIMEOUT \"10s\" ECHO hi",
8949            "TIMEOUT \"30 s\" ECHO hi",
8950            "TIMEOUT {{ $d }} ECHO hi",
8951            "TIMEOUT 10s AWAIT $t",
8952            "TIMEOUT 10s CANCEL $t",
8953            "TIMEOUT 10s AWAIT $t ECHO bye",
8954            "TIMEOUT 10s CANCEL $t ECHO bye",
8955            "TIMEOUT 10s { ECHO hi }",
8956            "TIMEOUT 10s {\nECHO hi\n}",
8957            "TIMEOUT 10s { ECHO hi } ECHO bye",
8958            "TIMEOUT 10s { ECHO hi } TIMEOUT 5s ECHO bye",
8959            "TIMEOUT 10s TIMEOUT 5s ECHO hi",
8960            "TIMEOUT 10s { ECHO a\nECHO b }",
8961            "TIMEOUT 10s ECHO hi extra",
8962            "ISOLATED ECHO hi",
8963            "ISOLATED { ECHO hi }",
8964            "ISOLATED { ECHO hi } ECHO bye",
8965            "ISOLATED AWAIT $t",
8966            "ISOLATED INHERIT_ENV [M]",
8967            "ISOLATED { INHERIT_ENV [M] }",
8968            "ISOLATED { INHERIT_ENV [MODE]\nECHO hi }",
8969            "ASYNC ECHO hi",
8970            "ASYNC { ECHO hi }",
8971            "ASYNC{ECHO hi}",
8972            "ASYNC { ECHO a\nECHO b }",
8973            "ASYNC { ECHO hi } ECHO bye",
8974            "ASYNC CANCEL $t",
8975            "ASYNC CANCEL $t ECHO bye",
8976            "AWAIT $t",
8977            "AWAIT$t",
8978            "AWAIT $ t",
8979            "AWAIT $T",
8980            "AWAIT $t2",
8981            "AWAIT $_t",
8982            "CANCEL $t",
8983            "CANCEL$t",
8984            "CANCEL $ t",
8985            "AWAIT $t ECHO bye",
8986            "CANCEL $t ECHO bye",
8987            "AWAIT $t AWAIT $u",
8988            "AWAIT $t\nECHO bye",
8989            "LET $t: HANDLE = ASYNC ECHO hi",
8990            "LET $t: HANDLE = ASYNC { ECHO hi }",
8991            "LET $t: HANDLE = ASYNC { ECHO hi } ECHO bye",
8992            "LET $a: STRING = ASYNC ECHO hi",
8993            "LET $t: HANDLE = ASYNC { WITH_IO [stdin=$p] ECHO hi }",
8994            "LET $w: STRING = WITH_IO [stdin=$p] ASYNC ECHO hi",
8995            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC ECHO hi",
8996            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi }",
8997            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi } ECHO bye",
8998            "LET $x: STRING = WITH_IO [stdin=$p] ECHO hi",
8999            "LET $x: STRING = WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
9000            "LET $x: STRING = TIMEOUT 10s ECHO hi",
9001            "LET $x: STRING = TIMEOUT 10s { ECHO hi }",
9002            "LET $x: STRING = TIMEOUT 10s ECHO hi ECHO bye",
9003            "LET $o: STRING = AWAIT $t",
9004            "LET $p: PIPE ECHO bye",
9005            "TIMEOUT 10s WITH_IO [stdin=$p]",
9006            "TIMEOUT 10s WITH_IO [stdin=$p]ECHO hi",
9007            "ISOLATED INHERIT_ENV [A, B]",
9008            "ISOLATED INHERIT_ENV [A-B]",
9009            "TIMEOUT 10s { [os:linux] ECHO hi }",
9010            "ASYNC { [os:linux] ECHO hi }",
9011            "ISOLATED { [os:linux] ECHO hi }",
9012            "[os:linux] WITH_IO [stdin=$p]\n{ ECHO hi }",
9013            "LET $x: INT = 1 ECHO bye",
9014            "CANCEL $t LET $x: INT = 1",
9015            "CANCEL $t $x = 1",
9016            "CANCEL $t RETURN \"hi\"",
9017            "TIMEOUT 10s { ECHO hi } LET $x: INT = 1",
9018            "RUN [\"a\"] ECHO bye",
9019            "[os:linux] AWAIT $t",
9020            "[os:linux] TIMEOUT 10s { ECHO hi } ECHO bye",
9021            "[os:linux] ASYNC CANCEL $t ECHO bye",
9022            "[os:linux] WITH_IO [stdin=$p] { [os:macos] ECHO hi }",
9023        ] {
9024            assert_parity(text);
9025        }
9026    }
9027
9028    #[test]
9029    fn token_and_string_paths_agree_on_blocks() {
9030        // Slice 5: `IF`/`FOR`/`WHILE`/`FUNC` with inline and
9031        // cross-newline `ELSE` chains, guard blocks (top-level and
9032        // nested quirk), and multi-element trailing — three-way
9033        // agreement per script.
9034        for text in [
9035            "IF true { ECHO hi }",
9036            "IF $x { ECHO hi } ELSE { ECHO bye }",
9037            "IF true { ECHO a } ELSE IF false { ECHO b } ELSE { ECHO c }",
9038            "IF true{ ECHO hi }",
9039            "IF true { ECHO hi } ECHO bye",
9040            "IF true { ECHO hi }\nELSE { ECHO bye }",
9041            "IF true { ECHO hi }\nELSE IF false { ECHO b }\nELSE { ECHO c }",
9042            "IF true { ECHO hi } //c\nELSE { ECHO bye }",
9043            "IF true { ECHO hi } #c\nELSE { ECHO bye }",
9044            "IF true { ECHO hi }//c\nELSE { ECHO bye }",
9045            "IF true { ECHO hi } /*c*/ ELSE { ECHO bye }",
9046            "IF true { ECHO hi } /*c1*/ /*c2*/\nELSE { ECHO bye }",
9047            "IF true { /*c*/ ECHO hi }",
9048            "IF true { [os:linux] ECHO hi }",
9049            "TIMEOUT 10s { IF true { ECHO hi } }",
9050            "TIMEOUT 10s { IF true { ECHO hi }\nELSE { ECHO bye } }",
9051            "FOR $x: INT IN [1] { ECHO hi }",
9052            "FOR $k: STRING, $v: INT IN $m { ECHO hi }",
9053            "FOR $k: INT IN [1] { ECHO hi }",
9054            "FOR $x: INT IN [1]{ ECHO hi }",
9055            "FOR $x: MAP<name: STRING> IN [1] { ECHO hi }",
9056            "FOR $x: INT IN [1] { ECHO hi } ECHO bye",
9057            "WHILE true { ECHO hi }",
9058            "WHILE $x { ECHO hi }",
9059            "WHILE true{ ECHO hi }",
9060            "TIMEOUT 10s WHILE true { ECHO hi }",
9061            "ASYNC WHILE true { ECHO hi }",
9062            "FUNC FOO(): INT { RETURN 1 }",
9063            "FUNC FOO(): INT { RETURN 1 }",
9064            "FUNC FOO($x: INT): INT { RETURN $x }",
9065            "FUNC FOO($x: INT, $y: STRING): INT { RETURN $x }",
9066            "FUNC FOO(): INT { FUNC FOO(): INT { RETURN 1 } }",
9067            "FUNC FOO(): INT { RETURN 1 }\nFUNC BAR(): VOID { FOO() }\nBAR()",
9068            "TYPE PERSON = MAP<name: STRING>",
9069            "TYPE A=B",
9070            "TYPE A = B | C",
9071            "TYPE A = B\nTYPE A = C",
9072            "INHERIT_ENV [A]\nECHO hi",
9073            "[os:linux] INHERIT_ENV [M]",
9074            "INHERIT_ENV [A]\nINHERIT_ENV [B]\nECHO hi",
9075            "ISOLATED INHERIT_ENV [M]",
9076            "ISOLATED { INHERIT_ENV [M] }",
9077            "ISOLATED INHERIT_ENV [A, B]",
9078            "ISOLATED INHERIT_ENV [A-B]",
9079            "REMOTE prod { ECHO hi }",
9080            "REMOTE prod [$v] { ECHO hi }",
9081            "REMOTE prod [$v, env:E] { ECHO hi }",
9082            "REMOTE prod [] { ECHO hi }",
9083            "REMOTE prod[$v] { ECHO hi }",
9084            "REMOTE prod [$v]{ ECHO hi }",
9085            "REMOTE prod{ ECHO hi }",
9086            "REMOTE  prod  { ECHO hi }",
9087            "REMOTE prod [$v, $v] { ECHO hi }",
9088            "REMOTE prod { ECHO hi } ECHO bye",
9089            "TIMEOUT 10s REMOTE prod { ECHO hi }",
9090            "ASYNC REMOTE prod [$v] { ECHO hi }",
9091            "[os:linux] { ECHO hi }",
9092            "[os:linux]\n{ ECHO hi }",
9093            "[os:linux] { [os:macos] ECHO hi }",
9094            "[os:linux] { [os:macos] ECHO hi\nECHO bye }",
9095            "[os:linux] { [os:macos] { ECHO hi } }",
9096            "TIMEOUT 10s { [os:linux] { [os:macos] ECHO hi } }",
9097            "TIMEOUT 10s { [os:linux] [os:windows] { ECHO hi } }",
9098            "TIMEOUT 10s { [os:linux] { ECHO hi } ECHO bye }",
9099            "LET $x: INT = 1 ECHO bye",
9100            KEYWORD_BREAK,
9101            KEYWORD_CONTINUE,
9102            "BREAK ECHO hi",
9103            "FOR $x: INT IN [1] { BREAK }",
9104            "LET $b: STRING = { RETURN \"hi\" }",
9105            "ECHO { RETURN \"hi\" }",
9106            "RUN [{ RETURN \"hi\" }]",
9107            "[not(env:FOO)] WRITE x",
9108            "[\nnot(env:FOO)\n] WRITE x",
9109            "WRITE env.txt \"{{ env:GREETING }}\"",
9110            "CANCEL $t LET $x: INT = 1",
9111            "RUN [\"a\"] ECHO bye",
9112        ] {
9113            assert_parity(text);
9114        }
9115    }
9116
9117    #[test]
9118    fn multi_line_generics_match_single_line_shape() {
9119        // Multi-line `<...>` shapes parse, and canonicalize exactly
9120        // like their single-line spelling.
9121        for (single, multi) in [
9122            (
9123                "TYPE R = MAP<name: STRING, value: INT>",
9124                "TYPE R = MAP<name: STRING,\nvalue: INT>",
9125            ),
9126            (
9127                "TYPE R = MAP<name: STRING, value: LIST<INT>>",
9128                "TYPE R = MAP<name: STRING,\nvalue: LIST<INT>>",
9129            ),
9130            (
9131                "TYPE R = MAP<name: STRING, value: INT>",
9132                "TYPE R = MAP<\nname: STRING,\nvalue: INT\n>",
9133            ),
9134            (
9135                "LET $m: MAP<name: STRING, value: INT> = {}",
9136                "LET $m: MAP<name: STRING,\nvalue: INT> = {}",
9137            ),
9138            (
9139                "FOR $x: LIST<INT> IN [1] { ECHO hi }",
9140                "FOR $x: LIST<\nINT> IN [1] { ECHO hi }",
9141            ),
9142            ("TYPE R = MAP<x: A | B>", "TYPE R = MAP<x: A |\nB>"),
9143        ] {
9144            assert_parity(multi);
9145            let want = crate::parse_script(single, lower)
9146                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
9147            let got = crate::parse_script(multi, lower)
9148                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
9149            assert_eq!(
9150                got, want,
9151                "multi-line must canonicalize like one line: {multi:?}"
9152            );
9153        }
9154    }
9155
9156    #[test]
9157    fn multi_line_run_exec_matches_single_line_shape() {
9158        // `RUN [...]` rides the shared bracket core, so a wrapped exec
9159        // list parses exactly like its single-line spelling (and agrees
9160        // across lexer frontends).
9161        for (single, multi) in [
9162            ("RUN [\"echo\", \"hi\"]", "RUN [\"echo\",\n\"hi\"]"),
9163            ("RUN [\"echo\", \"hi\"]", "RUN [\n\"echo\",\n\"hi\"\n]"),
9164            (
9165                "LET $o: STRING = RUN [\"echo\", \"hi\"]",
9166                "LET $o: STRING = RUN [\"echo\",\n\"hi\"]",
9167            ),
9168        ] {
9169            assert_parity(multi);
9170            let want = crate::parse_script(single, lower)
9171                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
9172            let got = crate::parse_script(multi, lower)
9173                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
9174            assert_eq!(
9175                got, want,
9176                "multi-line must canonicalize like one line: {multi:?}"
9177            );
9178        }
9179    }
9180
9181    #[test]
9182    fn untyped_let_fails_in_every_rhs_shape() {
9183        // The everything-typed rule: a missing `:` is a hard error
9184        // carrying the explicit-types message, regardless of what
9185        // follows the `=`. Every binding shape is covered, so no
9186        // untyped position can slip back in unnoticed.
9187        for text in [
9188            "LET $x = 1\n",
9189            "LET $x = \"hi\"\n",
9190            "LET $x = $y\n",
9191            "LET $x = [\"a\", \"b\"]\n",
9192            "LET $x = [\"a\",\n\"b\"]\n",
9193            "LET $x = ECHO hi\n",
9194            "LET $x = AWAIT $t\n",
9195            "LET $x = ASYNC ECHO hi\n",
9196            "LET $x = {\nRETURN 1\n}\n",
9197            "LET $x = WITH_IO [stdin=$p] ASYNC ECHO hi\n",
9198        ] {
9199            let err = crate::parse_script(text, lower).expect_err("untyped LET must fail");
9200            assert!(
9201                err.to_string().contains("LET requires explicit types"),
9202                "wrong error for {text:?}: {err}"
9203            );
9204        }
9205        // Typed spellings of the same shapes keep parsing through
9206        // every lexer frontend.
9207        for text in [
9208            "LET $x: INT = 1\n",
9209            "LET $x: STRING = \"hi\"\n",
9210            "LET $x: LIST<STRING> = [\"a\", \"b\"]\n",
9211            "LET $x: LIST<STRING> = [\"a\",\n\"b\"]\n",
9212            "LET $x: STRING = ECHO hi\n",
9213            "LET $x: STRING = AWAIT $t\n",
9214            "LET $x: HANDLE<VOID> = ASYNC ECHO hi\n",
9215            "LET $x: INT = {\nRETURN 1\n}\n",
9216        ] {
9217            assert_parity(text);
9218        }
9219    }
9220
9221    #[test]
9222    fn missing_comma_points_at_the_item() {
9223        // A forgotten comma between items names the missing
9224        // comma and points at the item's line, not the statement
9225        // head. Lists and call arguments share the rule.
9226        let text = indoc! {r#"
9227            LET $x: LIST<STRING> = [
9228            "a"
9229            "b",
9230            "c"
9231            ]
9232        "#};
9233        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
9234        assert!(
9235            err.to_string().contains("missing comma between list items"),
9236            "wrong error: {err}"
9237        );
9238        assert_eq!(err.line(), 3, "caret names the item line: {err}");
9239        // Same shape on one line.
9240        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" \"b\"]\n", lower)
9241            .expect_err("missing comma must fail");
9242        assert!(
9243            err.to_string().contains("missing comma between list items"),
9244            "wrong error: {err}"
9245        );
9246        assert_eq!(err.line(), 1, "single-line points at line 1: {err}");
9247        // Call arguments share the rule.
9248        let err = crate::parse_script("LET $x: STRING = FOO(\"a\" \"b\")\n", lower)
9249            .expect_err("missing comma must fail");
9250        assert!(
9251            err.to_string()
9252                .contains("missing comma between call arguments"),
9253            "wrong error: {err}"
9254        );
9255        // Genuine trailing garbage keeps the old message but still
9256        // points at the garbage instead of the statement head.
9257        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" : \"b\"]\n", lower)
9258            .expect_err("garbage must fail");
9259        assert!(
9260            err.to_string().contains("unexpected text in list"),
9261            "wrong error: {err}"
9262        );
9263        // Maps share the rule: a forgotten comma between entries
9264        // names it at the entry's line instead of misreporting the
9265        // key as an unknown command.
9266        let text = indoc! {r#"
9267            LET $m: MAP<name: STRING> = {
9268            name: "a"
9269            value: "b"
9270            }
9271        "#};
9272        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
9273        assert!(
9274            err.to_string()
9275                .contains("missing comma between map entries"),
9276            "wrong error: {err}"
9277        );
9278        assert_eq!(err.line(), 3, "caret names the entry line: {err}");
9279        let err = crate::parse_script(
9280            "LET $m: MAP<name: STRING> = {name: \"a\" value: \"b\"}\n",
9281            lower,
9282        )
9283        .expect_err("missing comma must fail");
9284        assert!(
9285            err.to_string()
9286                .contains("missing comma between map entries"),
9287            "wrong error: {err}"
9288        );
9289    }
9290
9291    #[test]
9292    fn spaced_comparisons_still_end_the_statement() {
9293        // A spaced `<` is a comparison, never a generic open: the
9294        // newline still ends the statement.
9295        let steps = crate::parse_script("LET $b: BOOL = $a < $b\nECHO hi", lower)
9296            .expect("comparison plus follower must parse");
9297        assert_eq!(steps.len(), 2, "newline ends the comparison statement");
9298    }
9299
9300    #[test]
9301    fn token_and_string_paths_agree_on_flat_commands() {
9302        for text in [
9303            "ECHO hi",
9304            "ECHO hi\nWRITE x out",
9305            "WRITE x",
9306            "ECHO \"quoted\" unquoted",
9307            "ENV COVERAGE=covered",
9308            "ECHO a; ECHO b",
9309            "// comment\nECHO hi",
9310            "ECHO 1.0.0 --flag a/b",
9311            "ECHO $x",
9312            "\n\nECHO hi\n\n",
9313        ] {
9314            assert_parity(text);
9315        }
9316    }
9317
9318    #[cfg(feature = "proc-macro-api")]
9319    #[test]
9320    fn backslash_outside_strings_is_string_only() {
9321        // `rustc` rejects a bare `\`, so unquoted backslash escapes
9322        // cannot cross `TokenStream` (same exclusion class as raw-`"`
9323        // blocks): the string lexer keeps them, the token path fails to
9324        // tokenize before v2 is ever reached.
9325        let toks = crate::tok::lex_str("ECHO a\\nb").expect("string lex keeps escapes");
9326        let old = crate::parse_script("ECHO a\\nb", lower).expect("string path parses it");
9327        assert_eq!(
9328            parse_tokens(&toks, lower).expect("token path parses it"),
9329            old
9330        );
9331        assert!("ECHO a\\nb".parse::<proc_macro2::TokenStream>().is_err());
9332    }
9333
9334    #[test]
9335    fn escaped_backslash_pair_is_atomic() {
9336        // `"a\\"` parses (one escape pair plus the closer): the pair
9337        // scans atomically, like the block-string arm and `lex_word`.
9338        // The value stays raw (`\\` verbatim for runtime
9339        // `expand_string`), so this pins parsing, not unescaping.
9340        assert_parity("ECHO \"a\\\\\"");
9341        let steps = crate::parse_script("ECHO \"a\\\\\"", lower).expect("escaped pair must parse");
9342        match &steps[..] {
9343            [s] => assert!(
9344                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a\\\\"),
9345                "escaped pair must survive raw: {s:?}"
9346            ),
9347            _ => panic!("one step: {steps:?}"),
9348        }
9349    }
9350
9351    #[test]
9352    fn joint_double_slash_stays_literal() {
9353        // `rustc` strips `//` before the macro ever runs, so these are
9354        // string-path-only by construction: joint `a//b` is one literal
9355        // arg, and `[a //c]` closes its group (the in-group `//` copy
9356        // stops at the closer).
9357        for text in ["ECHO a//b", "ECHO [a //c]"] {
9358            assert_parity_string_only(text);
9359        }
9360        let steps = crate::parse_script("ECHO a//b", lower).expect("joint slashes parse");
9361        match &steps[..] {
9362            [s] => assert!(
9363                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a//b"),
9364                "joint `//` must glue literally: {s:?}"
9365            ),
9366            _ => panic!("one step: {steps:?}"),
9367        }
9368        let steps = crate::parse_script("ECHO [a //c]", lower).expect("group must close");
9369        assert_eq!(steps.len(), 1, "one step: {steps:?}");
9370        // Full content survives literally: the mock joins WRITE args
9371        // with spaces, so the round trip is byte-exact here.
9372        let steps = crate::parse_script("WRITE f [a //c]", lower).expect("group must close");
9373        match &steps[..] {
9374            [s] => assert!(
9375                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a //c]"),
9376                "group content must survive literally: {s:?}"
9377            ),
9378            _ => panic!("one step: {steps:?}"),
9379        }
9380    }
9381
9382    #[test]
9383    fn block_comment_in_group_closes_like_line_comment() {
9384        // `[a /* c]` reads literally on the old backend (first arg
9385        // `[a`, joined `[a /* c]`), so the in-group `/*` copy breaks
9386        // at the depth-zero closer exactly like `//` does. The bare
9387        // `/*` reads literally too.
9388        for text in ["ECHO [a /* c]", "WRITE f [a /* c]", "ECHO /*"] {
9389            assert_parity_string_only(text);
9390        }
9391        let steps = crate::parse_script("ECHO /*", lower).expect("bare block open parses");
9392        match &steps[..] {
9393            [s] => assert!(
9394                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "/*"),
9395                "bare `/*` must stay literal: {s:?}"
9396            ),
9397            _ => panic!("one step: {steps:?}"),
9398        }
9399        let steps = crate::parse_script("WRITE f [a /* c]", lower).expect("group must close");
9400        match &steps[..] {
9401            [s] => assert!(
9402                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c]"),
9403                "group content must survive literally: {s:?}"
9404            ),
9405            _ => panic!("one step: {steps:?}"),
9406        }
9407        // Terminated spans keep working through the same path: the
9408        // run carries its closer, so math still gets first refusal.
9409        let steps = crate::parse_script("WRITE f [a /* c */ d]", lower).expect("group must close");
9410        match &steps[..] {
9411            [s] => assert!(
9412                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c */ d]"),
9413                "terminated group content must survive: {s:?}"
9414            ),
9415            _ => panic!("one step: {steps:?}"),
9416        }
9417    }
9418
9419    #[test]
9420    fn single_quoted_multiline_keeps_line_tracking() {
9421        // The `'` arm counts embedded newlines like the `"` arm, so the
9422        // statement after a multiline single-quoted string keeps its
9423        // own lines (func-docs stamping keys off them).
9424        let text = "ECHO 'a\nb'\nECHO c";
9425        assert_parity_string_only(text);
9426        let steps = crate::parse_script(text, lower).expect("must parse");
9427        assert_eq!(steps.len(), 2, "two steps: {steps:?}");
9428        assert_eq!((steps[0].line, steps[0].col), (1, 1));
9429        assert_eq!((steps[1].line, steps[1].col), (3, 1), "{steps:?}");
9430    }
9431
9432    #[test]
9433    fn token_and_string_paths_agree_on_guarded_commands() {
9434        for text in [
9435            "[env:X] ECHO hi",
9436            "[env:A] [os:linux] ECHO hi",
9437            "[os:macos] WRITE x",
9438            "[not(os:windows)] WRITE f x",
9439            "[any(os:macos, os:linux)] ECHO hi",
9440            "[all(env:A, os:linux)] ECHO hi",
9441            "[eq(env:K, v)] ECHO hi",
9442            "[ne(env:K, v)] ECHO hi",
9443            "[bool:true] ECHO hi",
9444            "[arch:arm] ECHO hi",
9445            "[family:unix] ECHO hi",
9446            "[(os:linux)] ECHO hi",
9447            "[env:A, os:linux] ECHO hi",
9448            "WRITE x\n[env:X] ECHO hi",
9449            "[env:K] ECHO $x",
9450            "[__OXDOCK_INJECT_1__] ECHO hi",
9451            "[eq(env:K, \"a b\")] ECHO hi",
9452            "[\nenv:X\n] ECHO hi",
9453            // In-body brackets are raw text split on whitespace (probed
9454            // parity: `[a, b]` is args `"[a,"` + `"b]"`, quotes kept).
9455            "ECHO [a, b] hi",
9456            "WRITE f [env:X]",
9457            "ECHO [env:X] hi",
9458            "WRITE f [\"a b\"]",
9459            "ECHO foo[bar]baz",
9460            "ECHO [a ]",
9461            "ECHO [ a]",
9462            "WRITE out x [env:X]",
9463        ] {
9464            assert_parity(text);
9465        }
9466        // `rustc` lexes `'a` as a lifetime start and rejects the
9467        // space: string-path-only by construction.
9468        assert_parity_string_only("ECHO ['a b']");
9469    }
9470
9471    #[test]
9472    fn token_and_string_paths_agree_on_calls_and_exact_args() {
9473        use crate::ast::{ModuleFuncs, ModuleTable};
9474        use std::collections::{HashMap, HashSet};
9475        let std_table = || ModuleTable {
9476            modules: HashMap::from([(
9477                crate::constants::STD_MODULE_NAME.to_string(),
9478                Some(ModuleFuncs {
9479                    func_names: HashSet::from(["LEN".to_string()]),
9480                }),
9481            )]),
9482        };
9483        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9484            test_lower_mock::lower(name, args)
9485        }
9486        // One table for both pathways: STD exports LEN.
9487        // Rebuilt per case (parse-time only, keeps borrows local).
9488        for text in [
9489            "LET $n: INT = STD::LEN(\"hi\")",
9490            "STD::LEN(\"hi\")",
9491            "LET $n: INT = STD::LEN(\"a\", \"b\")",
9492            "LET $s: STRING = INSPECT($x)",
9493            "INSPECT($x)",
9494            "LET $x: STRING = ECHO hi",
9495            "LET $t: STRING = WRITE x",
9496            "LET $o: STRING = RUN echo hi",
9497            "RUN [\"echo\", \"hi\"]",
9498            "RUN echo [a]",
9499            "LET $r: STRING = RUN [\"echo\"]",
9500            "ECHO K=v",
9501            "ECHO K = v",
9502            "ECHO K=a b",
9503            "ECHO K=a, b",
9504            "ECHO K=\"a b\"",
9505            "ECHO K=$x",
9506            "ECHO K=",
9507            "ECHO a = = b",
9508            "WRITE f K=v",
9509            "ECHO $a + $b",
9510            "ECHO $a==$b",
9511            "ECHO a $x b",
9512            "ECHO 5 + 3",
9513            "WRITE f ( \"hi\" )",
9514            "ECHO [a, b] hi",
9515            "ECHO {{x}}",
9516            "ECHO {{ $x }}",
9517            "ECHO $x=K",
9518            "ECHO a$x",
9519            "ECHO a$(x)",
9520            "ECHO K=$x tail",
9521            "EXPAND K1=$x K2=$y",
9522            "EXPAND a",
9523            "ENV K = v",
9524            "COPY a b",
9525            "ECHO foo[bar]baz",
9526            "LET $x: STRING = FOOBAR",
9527            "STD::LEN(\"hi\") ECHO bye",
9528            "LET $n: INT = STD::LEN(\"a\") ECHO bye",
9529            "TIMEOUT 10s STD::LEN(\"hi\")",
9530            "TIMEOUT 10s STD::LEN(\"hi\") ECHO bye",
9531            "LET $n: INT = STD::LEN(\"a\")STD::LEN(\"b\")",
9532        ] {
9533            let table = std_table();
9534            let old =
9535                crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
9536                    .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9537            let reserved = HashSet::new();
9538            let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
9539            let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9540            let new = parse_tokens_with_ctx(&toks, &ctx)
9541                .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9542            assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9543            #[cfg(feature = "proc-macro-api")]
9544            {
9545                let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
9546                let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
9547                let new = parse_tokens_with_ctx(&toks, &ctx)
9548                    .unwrap_or_else(|e| panic!("token path must parse token {text:?}: {e}"));
9549                assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
9550            }
9551        }
9552    }
9553
9554    #[test]
9555    fn placeholder_bare_calls_resolve_like_statements() {
9556        // `{{ NAME(args) }}` obeys exactly the statement-position
9557        // scope rule: `IMPORT [MOD]` brings the names into scope,
9558        // unimported names fail naming the fix, ambiguity fails
9559        // closed. The rewrite below is byte-identical past the
9560        // qualified head, so expansion sees the same args.
9561        use crate::ast::{ModuleFuncs, ModuleTable};
9562        use std::collections::{HashMap, HashSet};
9563        let table = || ModuleTable {
9564            modules: HashMap::from([
9565                (
9566                    crate::constants::STD_MODULE_NAME.to_string(),
9567                    Some(ModuleFuncs {
9568                        func_names: HashSet::from(["LEN".to_string()]),
9569                    }),
9570                ),
9571                (
9572                    "OTHER".to_string(),
9573                    Some(ModuleFuncs {
9574                        func_names: HashSet::from(["LEN".to_string()]),
9575                    }),
9576                ),
9577            ]),
9578        };
9579        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9580            test_lower_mock::lower(name, args)
9581        }
9582        fn echo_text(steps: &[crate::Step]) -> String {
9583            match steps {
9584                [s] => match &s.kind {
9585                    StepKind::Echo(Arg::String(text, _)) => text.clone(),
9586                    other => panic!("expected ECHO string, got {other:?}"),
9587                },
9588                _ => panic!("expected one step, got {steps:?}"),
9589            }
9590        }
9591        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
9592            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
9593        }
9594        // Imported bare names qualify; everything else rides through
9595        // byte-identical for the runtime to handle as before.
9596        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }}\"\n";
9597        let out = echo_text(&parse(text, table()).expect("imported bare call parses"));
9598        assert_eq!(out, "n: {{ STD::LEN($x) }}", "bare call qualifies: {out}");
9599        let text = "IMPORT [STD]\nECHO \"n: {{ STD::LEN($x) }}\"\n";
9600        let out = echo_text(&parse(text, table()).expect("qualified parses"));
9601        assert_eq!(
9602            out, "n: {{ STD::LEN($x) }}",
9603            "qualified keys stay untouched: {out}"
9604        );
9605        let text = "IMPORT [STD]\nECHO \"hi {{ $x }} and {{ bare }} and {{ env:K }}\"\n";
9606        let out = echo_text(&parse(text, table()).expect("non-calls parse"));
9607        assert_eq!(
9608            out, "hi {{ $x }} and {{ bare }} and {{ env:K }}",
9609            "non-call keys stay untouched: {out}"
9610        );
9611        let text = "IMPORT [STD]\nECHO \"lit \\{{ LEN($x) }}\"\n";
9612        let out = echo_text(&parse(text, table()).expect("escaped parses"));
9613        assert_eq!(
9614            out, "lit \\{{ LEN($x) }}",
9615            "escaped openers stay literal: {out}"
9616        );
9617        // Nested bodies resolve against the enclosing imports, exactly
9618        // like statement-position calls in the same body.
9619        let text = indoc! {r#"
9620            IMPORT [STD]
9621            FUNC F(): VOID {
9622            ECHO "n: {{ LEN($x) }}"
9623            }
9624        "#};
9625        let steps = parse(text, table()).expect("nested bare call parses");
9626        let body = steps.iter().find_map(|s| match &s.kind {
9627            StepKind::FuncDef { body, .. } => Some(body),
9628            _ => None,
9629        });
9630        match body.map(Vec::as_slice) {
9631            Some([inner]) => match &inner.kind {
9632                StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
9633                    echoed, "n: {{ STD::LEN($x) }}",
9634                    "nested body qualifies: {echoed}"
9635                ),
9636                other => panic!("expected nested ECHO, got {other:?}"),
9637            },
9638            _ => panic!("expected one FUNC with one body step, got {steps:?}"),
9639        };
9640        // Neighboring placeholders keep their exact bytes: only the
9641        // head span changes, so payloads never lose formatting.
9642        let text = "IMPORT [STD]\nECHO \"Call {{ LEN($x) }} and value {{ $y }}\"\n";
9643        let out = echo_text(&parse(text, table()).expect("mixed template parses"));
9644        assert_eq!(
9645            out, "Call {{ STD::LEN($x) }} and value {{ $y }}",
9646            "only the head span changes: {out}"
9647        );
9648        // Unimported bare names fail exactly like statement position:
9649        // qualify it or add the import.
9650        let err = parse("ECHO \"n: {{ LEN($x) }}\"\n", table()).expect_err("must fail");
9651        assert!(
9652            err.to_string().contains("unknown function `LEN`")
9653                && err.to_string().contains("or add `IMPORT"),
9654            "names the fix: {err}"
9655        );
9656        // Two exporters fail closed instead of picking one.
9657        let err = parse(
9658            "IMPORT [STD]\nIMPORT [OTHER]\nECHO \"n: {{ LEN($x) }}\"\n",
9659            table(),
9660        )
9661        .expect_err("must fail");
9662        assert!(
9663            err.to_string().contains("ambiguous function `LEN`"),
9664            "ambiguity fails closed: {err}"
9665        );
9666        // Both lexing pathways agree on rewritten templates.
9667        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }} and {{ $y }}\"\n";
9668        let table = table();
9669        let old = crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
9670            .expect("string path parses");
9671        let reserved = HashSet::new();
9672        let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
9673        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9674        let new = parse_tokens_with_ctx(&toks, &ctx).expect("token path parses");
9675        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9676    }
9677
9678    #[test]
9679    fn placeholder_bare_calls_qualify_in_expr_positions() {
9680        // Regression: `walk_raw_strings_mut` skips `Assign`/`Set`/
9681        // `Call`/`Return`/`If`/`For`/`While`, so `LET`/`RETURN`/call
9682        // args/list/map literals never qualified and failed at
9683        // runtime as undefined variables. Both carriers now qualify.
9684        use crate::ast::{ModuleFuncs, ModuleTable};
9685        use std::collections::{HashMap, HashSet};
9686        let table = || ModuleTable {
9687            modules: HashMap::from([(
9688                crate::constants::STD_MODULE_NAME.to_string(),
9689                Some(ModuleFuncs {
9690                    func_names: HashSet::from(["LEN".to_string()]),
9691                }),
9692            )]),
9693        };
9694        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9695            test_lower_mock::lower(name, args)
9696        }
9697        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
9698            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
9699        }
9700        // LET string literal qualifies.
9701        let steps = parse(
9702            "IMPORT [STD]\nLET $s: STRING = \"n: {{ LEN($x) }}\"\n",
9703            table(),
9704        )
9705        .expect("LET template parses");
9706        match &steps[0].kind {
9707            StepKind::Assign { expr, .. } => match expr {
9708                Expr::Literal(value) => assert_eq!(
9709                    value.as_str().unwrap_or_default(),
9710                    "n: {{ STD::LEN($x) }}",
9711                    "LET qualifies"
9712                ),
9713                other => panic!("expected literal, got {other:?}"),
9714            },
9715            other => panic!("expected Assign, got {other:?}"),
9716        }
9717        // RETURN string literal qualifies.
9718        let steps = parse(
9719            "IMPORT [STD]\nFUNC F(): STRING {\nRETURN \"n: {{ LEN($x) }}\"\n}\n",
9720            table(),
9721        )
9722        .expect("RETURN template parses");
9723        let body = steps.iter().find_map(|s| match &s.kind {
9724            StepKind::FuncDef { body, .. } => Some(body),
9725            _ => None,
9726        });
9727        match body.map(Vec::as_slice) {
9728            Some([inner]) => match &inner.kind {
9729                StepKind::Return { expr, .. } => match &**expr {
9730                    Expr::Literal(value) => assert_eq!(
9731                        value.as_str().unwrap_or_default(),
9732                        "n: {{ STD::LEN($x) }}",
9733                        "RETURN qualifies"
9734                    ),
9735                    other => panic!("expected literal, got {other:?}"),
9736                },
9737                other => panic!("expected RETURN, got {other:?}"),
9738            },
9739            _ => panic!("expected one FUNC, got {steps:?}"),
9740        }
9741        // Call args, list and map literals qualify.
9742        let steps = parse(
9743            "IMPORT [STD]\nLET $y: INT = LEN(\"b: {{ LEN($x) }}\")\n",
9744            table(),
9745        )
9746        .expect("call-arg template parses");
9747        let rendered = format!("{:?}", steps[0].kind);
9748        assert!(
9749            rendered.contains("STD::LEN"),
9750            "call arg qualifies: {rendered}"
9751        );
9752        let steps = parse(
9753            "IMPORT [STD]\nLET $l: LIST<STRING> = [\"{{ LEN($x) }}\"]\n",
9754            table(),
9755        )
9756        .expect("list template parses");
9757        let rendered = format!("{:?}", steps[0].kind);
9758        assert!(rendered.contains("STD::LEN"), "list qualifies: {rendered}");
9759        // Compound placeholders are not single calls: they pass
9760        // through untouched (no partial rewrite) for the runtime to
9761        // fail closed on the whole key.
9762        let text = "IMPORT [STD]\nECHO \"v: {{ LEN($a) + LEN($b) }}\"\n";
9763        let steps = parse(text, table()).expect("compound parses");
9764        match &steps[0].kind {
9765            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
9766                echoed, "v: {{ LEN($a) + LEN($b) }}",
9767                "compound untouched: {echoed}"
9768            ),
9769            other => panic!("expected ECHO string, got {other:?}"),
9770        }
9771        // Quoted parens inside args do not end the call early.
9772        let text = "IMPORT [STD]\nECHO 'v: {{ LEN(\"a(b\") }}'\n";
9773        let steps = parse(text, table()).expect("quoted paren parses");
9774        match &steps[0].kind {
9775            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
9776                echoed, "v: {{ STD::LEN(\"a(b\") }}",
9777                "quoted paren qualifies: {echoed}"
9778            ),
9779            other => panic!("expected ECHO string, got {other:?}"),
9780        }
9781        // Single-quoted args balance the same way.
9782        let text = "IMPORT [STD]\nECHO \"v: {{ LEN('a(b') }}\"\n";
9783        let steps = parse(text, table()).expect("single-quoted paren parses");
9784        match &steps[0].kind {
9785            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
9786                echoed, "v: {{ STD::LEN('a(b') }}",
9787                "single-quoted paren qualifies: {echoed}"
9788            ),
9789            other => panic!("expected ECHO string, got {other:?}"),
9790        }
9791        // `WithIo` boxes its inner command directly (no recursive
9792        // statement pass), so the qualifier must descend into it.
9793        // `LET $p: PIPE` plus bindings keep the shape realistic.
9794        let text = "IMPORT [STD]\nLET $p: PIPE\nWITH_IO [stdout=$p] ECHO 'v: {{ LEN($x) }}'\n";
9795        let steps = parse(text, table()).expect("with-io template parses");
9796        match &steps[1].kind {
9797            StepKind::WithIo { cmd, .. } => {
9798                let rendered = format!("{cmd:?}");
9799                assert!(
9800                    rendered.contains("STD::LEN"),
9801                    "with-io inner qualifies: {rendered}"
9802                );
9803            }
9804            other => panic!("expected WithIo, got {other:?}"),
9805        }
9806        // Single-command wrappers build synthetic body steps without a
9807        // recursive pass: `TIMEOUT 5s <cmd>` and `ASYNC <cmd>` share
9808        // the outer frame, so the qualifier must descend into bodies.
9809        let text = "IMPORT [STD]\nTIMEOUT 5s ECHO 't: {{ LEN($x) }}'\n";
9810        let steps = parse(text, table()).expect("timeout template parses");
9811        let rendered = format!("{:?}", steps[0].kind);
9812        assert!(
9813            rendered.contains("STD::LEN"),
9814            "timeout single qualifies: {rendered}"
9815        );
9816        let text = "IMPORT [STD]\nLET $h: HANDLE<ANY> = ASYNC ECHO 'a: {{ LEN($x) }}'\n";
9817        let steps = parse(text, table()).expect("async template parses");
9818        let rendered = format!("{:?}", steps[0].kind);
9819        assert!(
9820            rendered.contains("STD::LEN"),
9821            "async single qualifies: {rendered}"
9822        );
9823        // Brace bodies keep their own frames: the outer qualifier must
9824        // never re-walk them. A valid nested body qualifies via its own
9825        // recursive pass, and an unknown callee inside one fails with
9826        // the inner position, never re-resolved against the outer frame.
9827        let text = "IMPORT [STD]\nIF true {\nECHO 'v: {{ LEN($x) }}'\n}\n";
9828        let steps = parse(text, table()).expect("nested body qualifies");
9829        let rendered = format!("{:?}", steps[0].kind);
9830        assert!(
9831            rendered.contains("STD::LEN"),
9832            "nested IF body qualifies via its own frame: {rendered}"
9833        );
9834        let err = parse(
9835            "IMPORT [STD]\nIF true {\nECHO 'v: {{ NOPE($x) }}'\n}\n",
9836            table(),
9837        )
9838        .expect_err("nested unknown must fail");
9839        assert!(
9840            err.to_string().contains("unknown function `NOPE`"),
9841            "nested unknown names culprit: {err}"
9842        );
9843    }
9844
9845    #[test]
9846    fn block_conditions_name_unknown_callees() {
9847        // Regression: an unknown callee in a block header condition
9848        // used to miss to the generic `IF needs a condition and a
9849        // block` hint. Classified resolution failures now propagate
9850        // and name the culprit on all four speculative headers.
9851        use crate::ast::{ModuleFuncs, ModuleTable};
9852        use std::collections::{HashMap, HashSet};
9853        let table = || ModuleTable {
9854            modules: HashMap::from([(
9855                crate::constants::STD_MODULE_NAME.to_string(),
9856                Some(ModuleFuncs {
9857                    func_names: HashSet::from(["LEN".to_string()]),
9858                }),
9859            )]),
9860        };
9861        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9862            test_lower_mock::lower(name, args)
9863        }
9864        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
9865            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
9866        }
9867        for text in [
9868            "IMPORT [STD]\nIF NOPE($x) == 0 {\nECHO hi\n}\n",
9869            "IMPORT [STD]\nIF LEN($x) == 0 {\nECHO hi\n} ELSE IF NOPE($x) == 1 {\nECHO yo\n}\n",
9870            "IMPORT [STD]\nWHILE NOPE($x) > 0 {\nECHO hi\n}\n",
9871            "IMPORT [STD]\nFOR $i: STRING IN NOPE($x) {\nECHO $i\n}\n",
9872        ] {
9873            let err = parse(text, table()).expect_err("unknown callee must fail");
9874            assert!(
9875                err.to_string().contains("unknown function `NOPE`"),
9876                "names the culprit: {err}"
9877            );
9878        }
9879        // Unclassified shape misses still miss (the exact generic
9880        // hint comes from the real dispatcher, which the mock lacks).
9881        parse("IF {\nECHO hi\n}\n", table()).expect_err("empty condition must still fail");
9882    }
9883
9884    #[test]
9885    fn token_and_string_paths_agree_on_let_set_return() {
9886        for text in [
9887            "LET $x: INT = 1",
9888            "LET $s: STRING = \"hi\"",
9889            "LET $b: BOOL = true",
9890            "LET $f: FLOAT = 1.5",
9891            "LET $p: PIPE",
9892            "LET $l: LIST<STRING> = [\"a\", \"b\"]",
9893            "LET $e: LIST<STRING> = []",
9894            "LET $m: MAP = {k: 1}",
9895            "LET $m2: MAP = {\"a b\": 2, k: [1, 2]}",
9896            "LET $n: INT = $a + $b",
9897            "LET $c: BOOL = ($a == 3) && ($b == 4)",
9898            "LET $g: BOOL = !$ok",
9899            "LET $nn: BOOL = true && false",
9900            "LET $e2: STRING = env:HOME",
9901            "LET $k: STRING = $a.b.c",
9902            "LET $u: INT = -5",
9903            "LET $v: INT = 9223372036854775807",
9904            "LET $min: INT = -9223372036854775808",
9905            "LET $w: INT = 1_000",
9906            "LET $z: STRING = a/b",
9907            "LET $d: STRING = -f",
9908            "LET $t: STRING = 30s",
9909            "LET $q: STRING = \"\"\"hi\"\"\"",
9910            "LET $f2: FLOAT = 2 * -3",
9911            "LET $o: BOOL = 2 + 3 > 4",
9912            "LET $l2: LIST< MAP > = []",
9913            "LET $a1: INT = 1 + 2",
9914            "LET $s1: INT = 10 - 4 - 3",
9915            "LET $m1: INT = 2 * 3 + 4",
9916            "LET $x1: BOOL = 1 < 2 == true",
9917            "LET $or: BOOL = $a || $b",
9918            "LET $dbl: BOOL = !!$x",
9919            "LET $ver: STRING = 1.0.0",
9920            "LET $dash: STRING = a-b",
9921            "LET $div: INT = 4 / 2",
9922            "LET $bad: INT = 1__0 + 0",
9923            "LET $strdiv: STRING = 4/2",
9924            "LET $sp: INT = $a - $b",
9925            "$x = 1",
9926            "$x = $a + 1",
9927            "RETURN 1",
9928            KEYWORD_RETURN,
9929            "RETURN $x",
9930            "[env:X] LET $x: INT = 1",
9931            "[os:linux] $x = 2",
9932        ] {
9933            assert_parity(text);
9934        }
9935    }
9936
9937    #[test]
9938    fn malformed_shapes_fail_on_both_paths() {
9939        // Malformed shapes fail on both lexers (messages may differ;
9940        // success/failure must agree). Unbalanced groups fail even
9941        // earlier, at lex time: both layers reject, which is what the
9942        // oracle pins.
9943        for text in [
9944            "[a] ECHO hi",
9945            "[os:atari] ECHO hi",
9946            "[foo:bar] ECHO hi",
9947            "[any(os:linux)] ECHO hi",
9948            "[all()] ECHO hi",
9949            "[env:] ECHO hi",
9950            "[eq(env:K)] ECHO hi",
9951            "[not] ECHO hi",
9952            "ECHO [a;b]",
9953            "ECHO (a;b)",
9954            "ECHO a;b",
9955            "LET $x = 1",
9956            "LET $s: STRING",
9957            "LET $x: INT = 1 2",
9958            "LET $x: INT = (1",
9959            "LET $x: INT = 9223372036854775808",
9960            "$x =",
9961            "RETURN (",
9962            "[env:X]",
9963            "LET $x: INT = $a == $b == $c",
9964            "LET $x: BOOL = $a < $b < $c",
9965            "LET $bs: STRING = a\\nb",
9966            "FOO(\"a\")",
9967            "FOO (\"a\")",
9968            "ECHO FOO(\"a\")",
9969            "ECHO(\"hi\")",
9970            "RUN [a] extra",
9971            "RUN[\"a\"]",
9972            "TIMEOUT 10s RUN[\"a\"]",
9973            "LET $r: STRING = RUN[\"a\"]",
9974            "LET $e: STRING = ECHO",
9975            "ENV A=1 B=2",
9976            "EXPAND \"a b\" c",
9977            "ECHO {a}",
9978            "ECHO K=${x}",
9979            "[!env:A==1] RUN echo no",
9980            "run echo hi",
9981            "LET $x: STRING = AWAIT",
9982            "LET $o: STRING = CANCEL $t",
9983            "LET $x: STRING = ASYNC",
9984            "LET $x: STRING = WITH_IO",
9985            "LET $x: STRING = TIMEOUT",
9986            "LET $x: STRING = ISOLATED",
9987            "LET $x: STRING = ISOLATED ECHO hi",
9988            "COPY A=1",
9989            "WITH_IO [rows=40] RUN echo hi",
9990            "WITH_IO [tty] ECHO hi",
9991            "WITH_IO [tty, stderr=$p] RUN echo hi",
9992            "WITH_IO [tty=$p] RUN echo hi",
9993            "WITH_IO [cols=0] RUN echo hi",
9994            "WITH_IO [cols=65536] RUN echo hi",
9995            "WITH_IO [] ECHO hi",
9996            "WITH_IO [stdin=$p,] ECHO hi",
9997            "WITH_IO stdin=$p ECHO hi",
9998            "WITH_IO [STDIN=$p] ECHO hi",
9999            "WITH_IO [rows] RUN echo hi",
10000            KEYWORD_WITH_IO,
10001            "WITH_IO [stdout=$p]",
10002            "WITH_IO [stdin=$p]\n[os:linux] { ECHO hi }",
10003            "WITH_IO [stdin=$p] { }",
10004            "WITH_IO[stdin=$p] ECHO hi",
10005            "WITH_IO [stdin=$p]ECHO hi",
10006            "WITH_IO [stdin=$p] {{ $x }}",
10007            "ASYNC WITH_IO [stdout=$p] ECHO hi",
10008            "WITH_IO [stdin=$p] AWAIT $t",
10009            "ASYNC AWAIT $t",
10010            "WITH_IO [stdin=$p] RETURN \"hi\"",
10011            "ASYNC RETURN \"hi\"",
10012            "TIMEOUT 10s RETURN \"hi\"",
10013            "TIMEOUT banana ECHO hi",
10014            "TIMEOUT 10ss ECHO hi",
10015            "TIMEOUT 10 s ECHO hi",
10016            "TIMEOUT -5s ECHO hi",
10017            "TIMEOUT 0s ECHO hi",
10018            KEYWORD_TIMEOUT,
10019            "TIMEOUT 10s",
10020            "TIMEOUT { ECHO hi }",
10021            "TIMEOUT \"10s\"",
10022            "TIMEOUT 10s{ECHO hi}",
10023            "TIMEOUT 10sECHO hi",
10024            "TIMEOUT 10s {{ $d }}",
10025            "TIMEOUT 10s { $d }",
10026            "TIMEOUT { $d } ECHO hi",
10027            KEYWORD_ASYNC,
10028            KEYWORD_ISOLATED,
10029            "ISOLATED{ECHO hi}",
10030            KEYWORD_AWAIT,
10031            KEYWORD_CANCEL,
10032            "AWAIT t",
10033            "AWAIT $",
10034            "AWAIT $t extra",
10035            "CANCEL $t extra",
10036            "TIMEOUT 5s INHERIT_ENV [M]",
10037            "TIMEOUT 5s { INHERIT_ENV [M] }",
10038            "ASYNC { INHERIT_ENV [M] }",
10039            "LET $x: STRING = INHERIT_ENV [M]",
10040            "TIMEOUT 10s WITH_IO [stdin=$p] { ECHO hi }",
10041            "ISOLATED WITH_IO [stdin=$p] { ECHO hi }",
10042            "TIMEOUT 10s AWAIT $ t",
10043            "LET $o: STRING = AWAIT $ t",
10044            "ISOLATED AWAIT $ t",
10045            "WITH_IO [stdin=$p] CANCEL $ t",
10046            "LET $ x: INT = 1",
10047            "LET $x: STRING = WITH_IO [stdin=$p] { ECHO hi }",
10048            "LET $x: STRING = WITH_IO [stdin=$p] ASYNC",
10049            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO a\nECHO b }",
10050            "LET $x: STRING = WITH_IO [stdout=$p] ECHO hi",
10051            "LET $x: STRING = TIMEOUT 10s AWAIT $t",
10052            "LET $x: STRING = CANCEL $t",
10053            "LET $x: STRING = ASYNC",
10054            "LET $x: STRING = WITH_IO",
10055            "TIMEOUT 10s LET $x: INT = 1",
10056            "LET $x: STRING = FOO bar",
10057            "LET(\"a\")",
10058            "AWAIT($t)",
10059            "CANCEL($t)",
10060            "TIMEOUT(\"10s\") ECHO hi",
10061            "RETURN ECHO bye",
10062        ] {
10063            match crate::tok::lex_str(text) {
10064                Err(_) => {
10065                    assert!(
10066                        crate::parse_script(text, lower).is_err(),
10067                        "backend must also reject lex-broken input: {text:?}"
10068                    );
10069                    continue;
10070                }
10071                Ok(toks) => {
10072                    assert!(
10073                        parse_tokens(&toks, lower).is_err(),
10074                        "v2 must explicitly reject (not silently drift): {text:?}"
10075                    );
10076                }
10077            }
10078            assert!(
10079                crate::parse_script(text, lower).is_err(),
10080                "backend must also reject (oracle agreement): {text:?}"
10081            );
10082        }
10083        // No deferred shapes remain: every statement-level block and
10084        // inline-block expression parses natively.
10085    }
10086
10087    #[test]
10088    fn deferred_unknown_callee_beats_validation_arg_error() {
10089        // Directive 5: `WORKSPACE NOPE()` stashes `unknown function
10090        // NOPE` while the fallback raw string fails `WORKSPACE`
10091        // validation. On a well-formed header the stashed callee error
10092        // names the culprit instead of the misleading arg-shape error.
10093        let err =
10094            crate::parse_script("WORKSPACE NOPE()", lower).expect_err("unknown callee must fail");
10095        assert!(
10096            err.to_string().contains("unknown function `NOPE`"),
10097            "deferred must beat validation, got: {err}"
10098        );
10099    }
10100
10101    #[test]
10102    fn paren_line_break_reports_token_position() {
10103        // Directive 5: multiline paren breaks carry the offending
10104        // token's line/col, not a stamped 0/0. The break sits on line 2
10105        // while the statement opens on line 1.
10106        let err = crate::parse_script("ECHO (a\nb)", lower).expect_err("break must fail");
10107        let rendered = err.to_string();
10108        assert!(
10109            rendered.contains("unexpected line break"),
10110            "break must report, got: {rendered}"
10111        );
10112    }
10113
10114    #[test]
10115    fn deferred_unknown_callee_beats_invalid_syntax_arg_error() {
10116        // Fallback raw strings can trigger `InvalidSyntax` lowering
10117        // (for example `COPY NOPE()`). The stashed unknown-callee error
10118        // still names the culprit on a recognized head.
10119        for text in ["COPY NOPE()", "WRITE NOPE()"] {
10120            let err = crate::parse_script(text, lower).expect_err("unknown callee must fail");
10121            assert!(
10122                err.to_string().contains("unknown function `NOPE`"),
10123                "deferred must beat InvalidSyntax for {text:?}, got: {err}"
10124            );
10125        }
10126    }
10127
10128    #[test]
10129    fn deferred_beats_lowering_invalid_syntax_on_plain_heads() {
10130        // Plain command heads own no header grammar, so a lowering
10131        // `InvalidSyntax` there is an argument-shape failure from the
10132        // raw-text fallback: the stashed unknown-callee names the
10133        // culprit on every such head (no per-command allowlist).
10134        let lower_invalid =
10135            |name: &str, _args: Vec<crate::Arg>| -> crate::ParseResult<crate::StepKind> {
10136                Err(crate::ParseError::invalid_syntax(
10137                    name,
10138                    format!("{name} header is malformed"),
10139                    None,
10140                    Vec::new(),
10141                    None,
10142                    &crate::error::SpanContext::line_only(0),
10143                ))
10144            };
10145        for text in [
10146            "ASSERT_EQ $a NOSUCHFUNC()",
10147            "SYMLINK $a NOSUCHFUNC()",
10148            "COPY $a NOSUCHFUNC()",
10149            "WRITE $a NOSUCHFUNC()",
10150        ] {
10151            let err = crate::parse_script(text, lower_invalid).expect_err("arg error must fail");
10152            assert!(
10153                err.to_string().contains("unknown function `NOSUCHFUNC`"),
10154                "deferred must beat lowering InvalidSyntax for {text:?}, got: {err}"
10155            );
10156        }
10157        // Header-owned heads keep their lowering `InvalidSyntax`: the
10158        // native parser missed to the generic path on shape miss, so
10159        // the lowering error names the malformed header while the
10160        // stashed name is its definiendum, never a call.
10161        let err = crate::parse_script("FUNC $a NOSUCHFUNC()", lower_invalid)
10162            .expect_err("header syntax must fail");
10163        assert!(
10164            err.to_string().contains("header is malformed"),
10165            "header InvalidSyntax must stand on FUNC, got: {err}"
10166        );
10167    }
10168
10169    #[test]
10170    fn trailing_tokens_after_func_block_never_hoist() {
10171        // A `FUNC` header with trailing tokens after the body block is
10172        // malformed (the real path rejects it), so pre-declaration
10173        // must not hoist the name: the forward call fails instead of
10174        // resolving.
10175        let err = crate::parse_script(
10176            "LET $x: STRING = FOO()\nFUNC FOO(): STRING { RETURN \"a\" } TRAILING\n",
10177            lower,
10178        )
10179        .expect_err("trailing tokens must fail");
10180        assert!(
10181            err.to_string().contains("unknown function `FOO`"),
10182            "unhoisted forward call must fail, got: {err}"
10183        );
10184    }
10185
10186    #[test]
10187    fn forward_reference_resolves_regardless_of_order() {
10188        // `CALLER` calls `CALLEE` defined later. Top-level
10189        // pre-declaration hoists names before lowering, so order
10190        // does not matter. Runtime still executes sequentially;
10191        // the call below runs after both definitions.
10192        let steps = crate::parse_script(
10193            "FUNC CALLER(): STRING { RETURN CALLEE() }\nFUNC CALLEE(): STRING { RETURN \"forward-ok\" }\n",
10194            lower,
10195        )
10196        .expect("forward ref must parse");
10197        assert!(
10198            matches!(&steps[0].kind, crate::StepKind::FuncDef { name, .. } if name == "CALLER"),
10199            "first def kept, got: {:?}",
10200            steps[0].kind
10201        );
10202    }
10203
10204    #[test]
10205    fn forward_reference_to_guarded_func_resolves() {
10206        // Guarded definitions hoist like unguarded ones: `parse_func_at`
10207        // registers `[os:macos] FUNC FOO` unconditionally, so a forward
10208        // call before the definition must resolve identically to a
10209        // backward call after it.
10210        let steps = crate::parse_script(
10211            "LET $x: STRING = FOO()\n[os:macos] FUNC FOO(): STRING { RETURN \"guarded\" }\n",
10212            lower,
10213        )
10214        .expect("forward guarded ref must parse");
10215        assert!(
10216            matches!(&steps[1].kind, crate::StepKind::FuncDef { name, .. } if name == "FOO"),
10217            "guarded def kept, got: {:?}",
10218            steps[1].kind
10219        );
10220    }
10221}