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`/reassignment (`$var = <expr>`)/`RETURN`
18//! with the full 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    BindRhs, InsToken, apply_unary_neg, canonical_assignment_arg, check_tty_wrapping,
92    classify_numeric_text, is_known_command, lower_env_tokens, lower_expand_tokens, make_arith,
93    make_compare, reject_boundary,
94};
95use crate::constants::{
96    INJECT_PREFIX, INJECT_SUFFIX, KEY_PATH_SEPARATOR_CHAR, KEYWORD_AS, KEYWORD_ASYNC,
97    KEYWORD_AWAIT, KEYWORD_BREAK, KEYWORD_CANCEL, KEYWORD_CASE, KEYWORD_CONST, KEYWORD_CONTINUE,
98    KEYWORD_DEFAULT, KEYWORD_ECHO, KEYWORD_ELSE, KEYWORD_ENV, KEYWORD_EXPAND, KEYWORD_EXPORT,
99    KEYWORD_FAIL, KEYWORD_FOR, KEYWORD_FROM, KEYWORD_FUNC, KEYWORD_IF, KEYWORD_IMPORT, KEYWORD_IN,
100    KEYWORD_INHERIT_ENV, KEYWORD_INSPECT, KEYWORD_ISOLATED, KEYWORD_LET, KEYWORD_REMOTE,
101    KEYWORD_RETURN, KEYWORD_RUN, KEYWORD_SWITCH, KEYWORD_TIMEOUT, KEYWORD_TYPE, KEYWORD_WHILE,
102    KEYWORD_WITH_IO, MODULE_SEPARATOR, VAR_SIGIL_CHAR, qualify, sigil_qualified, sigil_var,
103};
104use crate::diagnostics as dsl_diag;
105use crate::error::{ParseError, ParseErrorKind, ParseResult, SpanContext};
106use crate::tag::{HANDLE_TYPE_NAME, INT_TYPE_NAME, STRING_TYPE_NAME};
107use oxdock_diagnostics::Diagnostic;
108
109use crate::resolve::resolve_call_name;
110use crate::tok::{GroupDelim, LexError, Tok, TokKind, lex_str};
111use std::cell::RefCell;
112use std::collections::HashSet;
113use std::fmt;
114
115/// Backend error. Carries the statement index and message; the string
116/// entry points below map it to [`crate::ParseError`]. Lowering
117/// failures from the shared `lower` dispatcher stringify through here
118/// so success paths compare exactly.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct TokenError {
121    pub stmt: usize,
122    /// 1-based source line, `0` when unknown (the split loops stamp the
123    /// enclosing statement's line on the way out, so only genuinely
124    /// position-less errors stay `0`).
125    pub line: usize,
126    /// 1-based start column of the enclosing statement, `0` when
127    /// unknown (stamped alongside `line`).
128    pub col: usize,
129    pub msg: String,
130    /// Lowering failures preserve the dispatcher's classification
131    /// (`UnknownCommand`, `InvalidSyntax`, `Validation`); `None` means
132    /// a parser-native structural failure.
133    pub kind: Option<ParseErrorKind>,
134    /// Owning keyed diagnostic, when this error wraps a dispatcher
135    /// [`ParseError`] built via `ParseError::from_diagnostic` or a
136    /// direct `check_arg` failure carrying its own diagnostic. The
137    /// entry points reattach it verbatim so stable keys survive the
138    /// token-stream round trip; other parser-native errors leave this
139    /// as `None` and rewrap from the message string as before. Boxed:
140    /// diagnostics are cold-path only and `TokenError` travels by
141    /// value in every `Result`.
142    pub diagnostic: Option<Box<Diagnostic>>,
143    /// Structured hint from the wrapped [`ParseError`], when the
144    /// dispatcher set one. Reattached alongside the diagnostic so
145    /// `hint()` survives the round trip; parser-native errors leave
146    /// this as `None`.
147    pub hint: Option<String>,
148}
149
150impl fmt::Display for TokenError {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        write!(
153            f,
154            "parse error in statement {}: {}",
155            self.stmt + 1,
156            self.msg
157        )
158    }
159}
160
161impl std::error::Error for TokenError {}
162
163/// Lift a dispatcher/resolver [`ParseError`] into a [`TokenError`],
164/// preserving its machine-readable classification (the entry points
165/// convert it back verbatim, so `UnknownCommand`/`InvalidSyntax`/
166/// `Validation` survive the round trip) and its owning diagnostic, so
167/// stable keys survive too. The message is the dispatcher's own
168/// display text; the split loops stamp the line.
169fn lower_err(stmt: usize, e: ParseError) -> TokenError {
170    TokenError {
171        stmt,
172        line: 0,
173        col: 0,
174        msg: e.to_string(),
175        kind: Some(e.kind().clone()),
176        diagnostic: e.diagnostic().cloned().map(Box::new),
177        hint: e.hint().map(str::to_string),
178    }
179}
180
181/// One split statement: leading bracket groups (guard region) plus
182/// the body tokens. `brace_detached` records a
183/// `Newline`/`Semicolon` between the guard region and a brace-headed
184/// body: in-body such statements are hard errors (a bare `{` is
185/// illegal inside blocks), while top level merges or parses guard
186/// blocks regardless.
187#[derive(Debug, Clone)]
188struct Stmt {
189    guard: Vec<Tok>,
190    body: Vec<Tok>,
191    brace_detached: bool,
192    /// 1-based source line where the body starts (guards ride on
193    /// earlier lines; errors report this).
194    line: usize,
195    /// 1-based column where the body starts (`0` when the head token
196    /// carries no coordinates: synthetic streams). Read off the first
197    /// body token, which always has the statement's own start.
198    col: usize,
199}
200
201impl PartialEq for Stmt {
202    fn eq(&self, other: &Self) -> bool {
203        // Coordinates are provenance (never rendered, never compared),
204        // like `Step`/`Tok`: two splits of one text compare equal.
205        self.guard == other.guard
206            && self.body == other.body
207            && self.brace_detached == other.brace_detached
208    }
209}
210
211impl Eq for Stmt {}
212
213/// True when a newline continues the statement for a multi-line
214/// generic: the body opens a type-carrying statement (TYPE/LET/CONST/FOR)
215/// and holds an unclosed `<...>` shape. Only a joint `<` after an
216/// uppercase word opens (never `<=`, never `$VAR<`), so spaced
217/// comparisons keep ending the statement as before. FUNC needs no
218/// gate: parameter types ride inside the atomic paren group, and the
219/// grammar defines no return-type position after the group.
220fn type_continuation_rides(body: &[Tok], next: Option<&Tok>) -> bool {
221    if !matches!(
222        body.first().map(|t| &t.kind),
223        Some(TokKind::Word(w)) if w == KEYWORD_TYPE || w == KEYWORD_LET || w == KEYWORD_CONST || w == KEYWORD_FOR
224    ) {
225        return false;
226    }
227    open_generic_depth(body, next) > 0
228}
229
230/// Unclosed `<...>` depth over a statement body: a joint `<` after
231/// an uppercase word opens (generic instantiation), `>` closes.
232fn open_generic_depth(body: &[Tok], next: Option<&Tok>) -> usize {
233    let mut depth = 0usize;
234    for (idx, tok) in body.iter().enumerate() {
235        if !matches!(&tok.kind, TokKind::Punct('<')) {
236            if matches!(&tok.kind, TokKind::Punct('>')) && depth > 0 {
237                depth -= 1;
238            }
239            continue;
240        }
241        if !tok.joint {
242            continue;
243        }
244        if idx == 0 {
245            continue;
246        }
247        if !matches!(
248            body.get(idx - 1).map(|t| &t.kind),
249            Some(TokKind::Word(w)) if is_upper_ident(w)
250        ) {
251            continue;
252        }
253        // `$VAR<` is a comparison, never a generic.
254        if idx >= 2
255            && body.get(idx - 1).is_some_and(|t| t.joint)
256            && matches!(
257                body.get(idx - 2).map(|t| &t.kind),
258                Some(TokKind::Punct(VAR_SIGIL_CHAR))
259            )
260        {
261            continue;
262        }
263        // `<=` is a comparison lead, never a generic open.
264        let followed_by_eq = matches!(
265            body.get(idx + 1).map(|t| &t.kind),
266            Some(TokKind::Punct('='))
267        ) || (idx + 1 == body.len()
268            && matches!(next.map(|t| &t.kind), Some(TokKind::Punct('='))));
269        if !followed_by_eq {
270            depth += 1;
271        }
272    }
273    depth
274}
275
276/// Grammar-state boundary decision: does this `Newline`/`Semicolon`
277/// end the statement? Groups are atomic, so every statement fits one
278/// logical token line; every keyword-headed statement (commands,
279/// wrappers, `LET`/`AWAIT`, block statements, directives) ends here.
280/// Only non-word heads fail, exactly like the grammar's element
281/// mismatch.
282fn boundary_ends_statement(body: &[Tok]) -> Result<bool, String> {
283    let head = match body.first() {
284        None => return Ok(true),
285        Some(t) => t,
286    };
287    match &head.kind {
288        TokKind::Word(_) | TokKind::Punct(VAR_SIGIL_CHAR) => Ok(true),
289        // A lone leading `{...}` ends here too: the splitter merges
290        // it into pending waits (`WITH_IO`, `IF`/`ELSE` chains) or
291        // emits it for block-statement lowering, never splitting
292        // inside.
293        TokKind::Group {
294            delim: GroupDelim::Brace,
295            ..
296        } => Ok(true),
297        _ => Err("statement must open with a command word".to_string()),
298    }
299}
300
301/// Bare `WITH_IO [..]` with no inner command: holds the line for a
302/// following `{...}` block (bare-bracket hold), which merges into one
303/// io-block statement. Anything else (or EOF) fails exactly like the
304/// grammar's `must be followed by '{'`.
305fn is_bare_with_io(body: &[Tok]) -> bool {
306    matches!(body.first().map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_WITH_IO)
307        && matches!(
308            body.get(1).map(|t| (&t.kind, t.joint)),
309            Some((
310                TokKind::Group {
311                    delim: GroupDelim::Bracket,
312                    ..
313                },
314                false
315            ))
316        )
317        && body.len() == 2
318}
319
320/// An if-tailed statement body: head `IF`, ends with a non-template
321/// brace (the then/else-if block), ignoring trailing gap comments.
322/// Trailing `//`/`#` runs and balanced `/* */` strip backward (the
323/// grammar's `gap` eats them before the `ELSE` chain, joint state
324/// irrelevant after a complete pair); anything else trailing (text,
325/// groups, strings) breaks the tail. Over-holding is safe: a merged
326/// non-`ELSE` follower releases, and a merged `ELSE` parses exactly
327/// where the grammar would.
328fn is_if_tail(body: &[Tok]) -> bool {
329    if !matches!(body.first().map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_IF) {
330        return false;
331    }
332    let mut end = body.len();
333    loop {
334        // Lexer comment markers.
335        while end > 0 && matches!(&body[end - 1].kind, TokKind::Comment(_)) {
336            end -= 1;
337        }
338        // Earliest comment opener (`//`-pair, `#`, `/*`-pair) starts
339        // trailing comment territory.
340        let mut cut = None;
341        let mut k = 0;
342        while k < end {
343            match &body[k].kind {
344                TokKind::Punct('#') => {
345                    cut = Some(k);
346                    break;
347                }
348                TokKind::Punct('/') if is_comment_open(&body[..end], k) => {
349                    cut = Some(k);
350                    break;
351                }
352                _ => k += 1,
353            }
354        }
355        match cut {
356            Some(k) => {
357                // A balanced `/* */` may be followed by more gap
358                // comments; anything else ends the strip for the
359                // brace check below.
360                if matches!(&body[k].kind, TokKind::Punct('/'))
361                    && !matches!(body.get(k + 1).map(|t| &t.kind), Some(TokKind::Punct('/')))
362                {
363                    match skip_inline_comment(&body[..end], k) {
364                        Some(past) if past < end => {
365                            end = past;
366                            continue;
367                        }
368                        _ => {}
369                    }
370                }
371                end = k;
372                continue;
373            }
374            None => break,
375        }
376    }
377    matches!(
378        body[..end].last().map(|t| &t.kind),
379        Some(TokKind::Group {
380            delim: GroupDelim::Brace,
381            ..
382        })
383    ) && body[..end].last().is_some_and(|t| !is_template_brace(t))
384}
385
386/// True when a body opens with a brace group (guard-block position
387/// or bare block).
388fn starts_brace(body: &[Tok]) -> bool {
389    matches!(
390        body.first().map(|t| &t.kind),
391        Some(TokKind::Group {
392            delim: GroupDelim::Brace,
393            ..
394        })
395    )
396}
397
398/// Source lines spanned by one token (for the splitter's line
399/// counter): newlines, `/* */` comment interiors, and nested group
400/// contents. Everything else occupies its own line.
401fn tok_newlines(tok: &Tok) -> usize {
402    match &tok.kind {
403        TokKind::Newline => 1,
404        TokKind::Comment(text) => text.matches('\n').count(),
405        TokKind::Group { inner, .. } => inner.iter().map(tok_newlines).sum(),
406        _ => 0,
407    }
408}
409
410/// Stamp an error with the innermost statement's position when it
411/// has none yet (deeper frames stamp first, so outer frames never
412/// overwrite real positions). Each component fills independently.
413fn stamp_pos(err: TokenError, line: usize, col: usize) -> TokenError {
414    TokenError {
415        line: if err.line == 0 { line } else { err.line },
416        col: if err.col == 0 { col } else { err.col },
417        ..err
418    }
419}
420
421/// Split top-level tokens into statements. Leading `[..]` groups attach
422/// to the following statement as its guard region; `Newline`/`Semicolon`
423/// end statements per [`boundary_ends_statement`]. Empty statements
424/// (blank lines, stray `;`) drop, matching the blank/semicolon
425/// grammar elements. Comment markers drop silently everywhere except
426/// pending `ELSE` waits, which a comment line breaks exactly like the
427/// grammar. Mid-line `//` runs and `#`/`/*` opens with an empty body
428/// skip as comments (statement position, like the grammar's silent
429/// elements); anywhere else they stay payload text for the arg engine.
430fn split_statements(toks: &[Tok], base: usize) -> Result<Vec<Stmt>, TokenError> {
431    let mut stmts = Vec::new();
432    let mut guard = Vec::new();
433    let mut body: Vec<Tok> = Vec::new();
434    let mut stmt_idx = 0;
435    // 1-based source line tracker: `base` is the line `toks[0]` starts
436    // on (1 at top level, the enclosing statement's line inside
437    // groups, where headers are single-line so the brace shares it).
438    // Groups and block comments advance past their inner newlines;
439    // every pushed statement records its body's start line for errors.
440    let mut line = base;
441    let mut start_line = base;
442    let mut start_col = 0;
443    // Bare `WITH_IO [..]` awaiting its `{...}` block (see
444    // `is_bare_with_io`): the guard and body hold across any
445    // separator until the brace arrives or the wait fails.
446    // Pending holds carry their body's start line with them.
447    let mut pending_io: Option<(Vec<Tok>, Vec<Tok>, usize, usize)> = None;
448    // If-tailed statement awaiting an `ELSE` continuation across
449    // newlines only (a `;` breaks the chain like the grammar).
450    let mut pending_if: Option<(Vec<Tok>, Vec<Tok>, usize, usize)> = None;
451    // Separator crossed between the guard region and the body start:
452    // only observed for brace-headed bodies (`brace_detached`).
453    let mut detached = false;
454    // Flush a statement, resolving pending waits first. `via_newline`
455    // records the separator kind: only newlines hold/merge `ELSE`
456    // chains; `;` and EOF release them. `line` is the current tracker
457    // for wait-failure errors; `start_line` is this body's start.
458    let flush_or_hold = |stmts: &mut Vec<Stmt>,
459                         guard: &mut Vec<Tok>,
460                         body: &mut Vec<Tok>,
461                         detached: &mut bool,
462                         stmt_idx: &mut usize,
463                         pending_io: &mut Option<(Vec<Tok>, Vec<Tok>, usize, usize)>,
464                         pending_if: &mut Option<(Vec<Tok>, Vec<Tok>, usize, usize)>,
465                         via_newline: bool,
466                         start_line: usize,
467                         start_col: usize,
468                         line: usize|
469     -> Result<(), TokenError> {
470        if body.is_empty() {
471            guard.clear();
472            *detached = false;
473            return Ok(());
474        }
475        // Pending `WITH_IO` wait takes precedence (the holds are
476        // mutually exclusive: setting either returns first).
477        if let Some((pending_guard, mut pending_body, pending_line, pending_col)) =
478            pending_io.take()
479        {
480            // Only a lone guard-less `{...}` group satisfies the wait;
481            // anything else (commands, guarded braces) fails like the
482            // grammar's `must be followed by '{'`.
483            let lone_brace = guard.is_empty()
484                && body.len() == 1
485                && matches!(
486                    body.first().map(|t| &t.kind),
487                    Some(TokKind::Group {
488                        delim: GroupDelim::Brace,
489                        ..
490                    })
491                );
492            if !lone_brace {
493                return Err(TokenError {
494                    diagnostic: None,
495                    hint: None,
496                    stmt: *stmt_idx,
497                    msg: format!("{KEYWORD_WITH_IO} block must be followed by '{{'"),
498                    line: pending_line,
499                    col: pending_col,
500                    kind: None,
501                });
502            }
503            pending_body.extend(std::mem::take(body));
504            guard.clear();
505            *detached = false;
506            stmts.push(Stmt {
507                guard: pending_guard,
508                body: pending_body,
509                brace_detached: false,
510                line: pending_line,
511                col: pending_col,
512            });
513            *stmt_idx += 1;
514            return Ok(());
515        }
516        // Pending `ELSE` wait: merge guard-less `ELSE`-led statements.
517        // The wait was set across a newline (only newlines hold), so
518        // the separator kind of *this* flush is irrelevant — `;` and
519        // EOF merge too; anything else releases the held IF.
520        if let Some((held_guard, mut held_body, held_line, held_col)) = pending_if.take() {
521            let else_start = guard.is_empty()
522                && matches!(
523                    body.first().map(|t| &t.kind),
524                    Some(TokKind::Word(w)) if w == KEYWORD_ELSE
525                );
526            if !else_start {
527                stmts.push(Stmt {
528                    guard: held_guard,
529                    body: held_body,
530                    brace_detached: false,
531                    line: held_line,
532                    col: held_col,
533                });
534                *stmt_idx += 1;
535            } else {
536                // The merged chain may hold again for a further
537                // `ELSE`, newlines only, like the grammar. A newline
538                // marker joins the parts: `#` comments end at it
539                // (their extent is unrecoverable post-merge), while
540                // `//`/`/*` carry their own extents.
541                held_body.push(Tok::fresh(TokKind::Newline, false));
542                held_body.extend(std::mem::take(body));
543                guard.clear();
544                *detached = false;
545                if via_newline && is_if_tail(&held_body) {
546                    *pending_if = Some((held_guard, held_body, held_line, held_col));
547                    return Ok(());
548                }
549                stmts.push(Stmt {
550                    guard: held_guard,
551                    body: held_body,
552                    brace_detached: false,
553                    line: held_line,
554                    col: held_col,
555                });
556                *stmt_idx += 1;
557                return Ok(());
558            }
559        }
560        if is_bare_with_io(body) {
561            if pending_io.is_some() {
562                return Err(TokenError {
563                    diagnostic: None,
564                    hint: None,
565                    stmt: *stmt_idx,
566                    msg: format!("previous {KEYWORD_WITH_IO} block is still waiting for '{{'"),
567                    line,
568                    col: start_col,
569                    kind: None,
570                });
571            }
572            *pending_io = Some((
573                std::mem::take(guard),
574                std::mem::take(body),
575                start_line,
576                start_col,
577            ));
578            *detached = false;
579            return Ok(());
580        }
581        // Ordinary statement: emit it, holding if-tailed bodies for
582        // an `ELSE` continuation across newlines only.
583        if via_newline && is_if_tail(body) {
584            *pending_if = Some((
585                std::mem::take(guard),
586                std::mem::take(body),
587                start_line,
588                start_col,
589            ));
590            *detached = false;
591            return Ok(());
592        }
593        let brace_detached = *detached && !guard.is_empty() && starts_brace(body);
594        stmts.push(Stmt {
595            guard: std::mem::take(guard),
596            body: std::mem::take(body),
597            brace_detached,
598            line: start_line,
599            col: start_col,
600        });
601        *detached = false;
602        *stmt_idx += 1;
603        Ok(())
604    };
605    // Release a pending `ELSE` wait by emitting the held IF as-is.
606    // (Inlined at use sites: a closure would collide with
607    // `flush_or_hold`'s borrow of the statement buffer.)
608    let mut i = 0;
609    // Open text-`/*` depth (line-start comments arrive as `Comment`
610    // toks; `//` never spans separators): newlines and semicolons
611    // inside never split, and `[` never guards (the closer, an
612    // error, or downstream rules resolve everything, exactly like
613    // the grammar).
614    let mut comment_depth = 0usize;
615    // True when `toks[i]` opens a text block comment (`/` plus a
616    // joint `*`; `//` is line-comment territory, handled elsewhere).
617    let block_open_at = |toks: &[Tok], i: usize| {
618        matches!(toks.get(i).map(|t| &t.kind), Some(TokKind::Punct('/')))
619            && matches!(
620                toks.get(i + 1).map(|t| (&t.kind, t.joint)),
621                Some((TokKind::Punct('*'), true))
622            )
623    };
624    // True when `toks[i]` closes one (`*` plus a joint `/`).
625    let block_close_at = |toks: &[Tok], i: usize| {
626        matches!(toks.get(i).map(|t| &t.kind), Some(TokKind::Punct('*')))
627            && matches!(
628                toks.get(i + 1).map(|t| (&t.kind, t.joint)),
629                Some((TokKind::Punct('/'), true))
630            )
631    };
632    while i < toks.len() {
633        let tok = &toks[i];
634        // Statement-start `/*` (silent gap position): skip balanced,
635        // failing unclosed like the grammar; mid-body opens only
636        // deepen the tracker below and ride into args as payload.
637        if body.is_empty() && comment_depth == 0 && block_open_at(toks, i) {
638            match skip_inline_comment(toks, i) {
639                Some(past) => {
640                    // The skipped span may cross lines (`/*a\nb*/`).
641                    line += toks[i..past].iter().map(tok_newlines).sum::<usize>();
642                    i = past;
643                    continue;
644                }
645                None => {
646                    return Err(TokenError {
647                        diagnostic: None,
648                        hint: None,
649                        stmt: stmt_idx,
650                        msg: "unclosed block comment".to_string(),
651                        line,
652                        col: tok.col,
653                        kind: None,
654                    });
655                }
656            }
657        }
658        // Nesting transitions on text pairs (mid-body opens deepen;
659        // closers pop when nested).
660        if block_open_at(toks, i) && (comment_depth > 0 || !body.is_empty()) {
661            comment_depth += 1;
662        } else if block_close_at(toks, i) && comment_depth > 0 {
663            comment_depth -= 1;
664        }
665        // Inside a block comment everything rides into the current
666        // body (never splits, never guards, never releases waits,
667        // never skips): gap positions swallow it downstream, arg
668        // positions fail or math over it, exactly like the grammar.
669        if comment_depth > 0 {
670            if body.is_empty() {
671                // Head-token coordinates are authoritative: the line
672                // tracker lags content stripped before lexing (comments
673                // vanish on the token path, leaving no newline behind).
674                // Zero coordinates (synthetic streams) keep the tracker.
675                if tok.line > 0 {
676                    start_line = tok.line;
677                } else {
678                    start_line = line;
679                }
680                if tok.col > 0 {
681                    start_col = tok.col;
682                }
683            }
684            line += tok_newlines(tok);
685            body.push(tok.clone());
686            detached = false;
687            i += 1;
688            continue;
689        }
690        match &tok.kind {
691            TokKind::Newline => {
692                if body.is_empty() {
693                    // A separator between the guard region and a
694                    // following brace matters (see `brace_detached`).
695                    detached = true;
696                    line += 1;
697                    i += 1;
698                    continue;
699                }
700                // Multi-line generics: a newline inside an unclosed
701                // `<...>` rides into the body, so `MAP<...>` shapes may
702                // span lines. Anything else ends here as before.
703                if type_continuation_rides(&body, toks.get(i + 1)) {
704                    line += 1;
705                    body.push(tok.clone());
706                    detached = false;
707                    i += 1;
708                    continue;
709                }
710                match boundary_ends_statement(&body) {
711                    Ok(true) => flush_or_hold(
712                        &mut stmts,
713                        &mut guard,
714                        &mut body,
715                        &mut detached,
716                        &mut stmt_idx,
717                        &mut pending_io,
718                        &mut pending_if,
719                        true,
720                        start_line,
721                        start_col,
722                        line,
723                    )?,
724                    Ok(false) => {}
725                    Err(msg) => {
726                        return Err(TokenError {
727                            diagnostic: None,
728                            hint: None,
729                            stmt: stmt_idx,
730                            msg,
731                            line: start_line,
732                            col: start_col,
733                            kind: None,
734                        });
735                    }
736                }
737                line += 1;
738                i += 1;
739            }
740            TokKind::Semicolon => {
741                if body.is_empty() {
742                    // A `;` breaks `ELSE` chains (release the hold)
743                    // but not `WITH_IO` waits (probed `;` merge).
744                    if let Some((held_guard, held_body, held_line, held_col)) = pending_if.take() {
745                        stmts.push(Stmt {
746                            guard: held_guard,
747                            body: held_body,
748                            brace_detached: false,
749                            line: held_line,
750                            col: held_col,
751                        });
752                        stmt_idx += 1;
753                    }
754                    detached = true;
755                    i += 1;
756                    continue;
757                }
758                match boundary_ends_statement(&body) {
759                    Ok(true) => flush_or_hold(
760                        &mut stmts,
761                        &mut guard,
762                        &mut body,
763                        &mut detached,
764                        &mut stmt_idx,
765                        &mut pending_io,
766                        &mut pending_if,
767                        false,
768                        start_line,
769                        start_col,
770                        line,
771                    )?,
772                    Ok(false) => {}
773                    Err(msg) => {
774                        return Err(TokenError {
775                            diagnostic: None,
776                            hint: None,
777                            stmt: stmt_idx,
778                            msg,
779                            line: start_line,
780                            col: start_col,
781                            kind: None,
782                        });
783                    }
784                }
785                i += 1;
786            }
787            // Lexer comment markers drop silently, but release a
788            // pending `ELSE` wait (a comment line breaks the chain
789            // like the grammar); `WITH_IO` waits survive comments.
790            TokKind::Comment(text) => {
791                if let Some((held_guard, held_body, held_line, held_col)) = pending_if.take() {
792                    stmts.push(Stmt {
793                        guard: held_guard,
794                        body: held_body,
795                        brace_detached: false,
796                        line: held_line,
797                        col: held_col,
798                    });
799                    stmt_idx += 1;
800                }
801                // A joint marker (`a//b`) is payload, not trivia: it
802                // rides into the body so arg assembly glues it
803                // literally, exactly like the grammar. Gapped and
804                // line-start markers drop.
805                if tok.joint && !body.is_empty() {
806                    line += text.matches('\n').count();
807                    body.push(tok.clone());
808                    detached = false;
809                    i += 1;
810                    continue;
811                }
812                // Block markers may span lines (`/*a\nb*/`).
813                line += text.matches('\n').count();
814                i += 1;
815            }
816            // A `//` run with an empty body (mid-line, e.g. after
817            // `;`) is a comment to the line end; with a non-empty
818            // body the slash-run rule owns it as payload text.
819            TokKind::Punct('/') if body.is_empty() && is_comment_open(toks, i) => {
820                if matches!(toks.get(i + 1).map(|t| &t.kind), Some(TokKind::Punct('/'))) {
821                    while i < toks.len() && !matches!(&toks[i].kind, TokKind::Newline) {
822                        i += 1;
823                    }
824                } else {
825                    match skip_inline_comment(toks, i) {
826                        Some(past) => i = past,
827                        None => {
828                            return Err(TokenError {
829                                diagnostic: None,
830                                hint: None,
831                                stmt: stmt_idx,
832                                msg: "unclosed block comment".to_string(),
833                                line,
834                                col: tok.col,
835                                kind: None,
836                            });
837                        }
838                    }
839                }
840            }
841            // `#` with an empty body (e.g. after `;`) is a comment
842            // to the line end; mid-body it stays arg text.
843            TokKind::Punct('#') if body.is_empty() => {
844                while i < toks.len() && !matches!(&toks[i].kind, TokKind::Newline) {
845                    i += 1;
846                }
847            }
848            TokKind::Group { delim, .. } if body.is_empty() && *delim == GroupDelim::Bracket => {
849                // Guard groups may span lines; the body starts after.
850                line += tok_newlines(tok);
851                guard.push(tok.clone());
852                detached = false;
853                i += 1;
854            }
855            _ => {
856                if body.is_empty() {
857                    // Head-token coordinates are authoritative (see
858                    // above); the tracker is the fallback.
859                    if tok.line > 0 {
860                        start_line = tok.line;
861                    } else {
862                        start_line = line;
863                    }
864                    if tok.col > 0 {
865                        start_col = tok.col;
866                    }
867                }
868                line += tok_newlines(tok);
869                body.push(tok.clone());
870                i += 1;
871            }
872        }
873    }
874    if !body.is_empty() {
875        match boundary_ends_statement(&body) {
876            Ok(_) => flush_or_hold(
877                &mut stmts,
878                &mut guard,
879                &mut body,
880                &mut detached,
881                &mut stmt_idx,
882                &mut pending_io,
883                &mut pending_if,
884                false,
885                start_line,
886                start_col,
887                line,
888            )?,
889            Err(msg) => {
890                return Err(TokenError {
891                    diagnostic: None,
892                    hint: None,
893                    stmt: stmt_idx,
894                    msg,
895                    line: start_line,
896                    col: start_col,
897                    kind: None,
898                });
899            }
900        }
901    } else if !guard.is_empty() {
902        // Trailing guards with no following command error (probed: a
903        // lone `[env:X]` is an error), never drop silently.
904        return Err(TokenError {
905            diagnostic: None,
906            hint: None,
907            stmt: stmt_idx,
908            msg: "guard declared without a following command".to_string(),
909            line,
910            col: 0,
911            kind: None,
912        });
913    }
914    // Release a trailing `ELSE` wait; a trailing `WITH_IO` wait fails.
915    if let Some((held_guard, held_body, held_line, held_col)) = pending_if.take() {
916        stmts.push(Stmt {
917            guard: held_guard,
918            body: held_body,
919            brace_detached: false,
920            line: held_line,
921            col: held_col,
922        });
923    }
924    if let Some((_, _, pending_line, pending_col)) = pending_io.take() {
925        return Err(TokenError {
926            diagnostic: None,
927            hint: None,
928            stmt: stmt_idx,
929            msg: format!("{KEYWORD_WITH_IO} block must be followed by '{{'"),
930            line: pending_line,
931            col: pending_col,
932            kind: None,
933        });
934    }
935    Ok(stmts)
936}
937
938/// Splice in-body bracket/paren groups to flat raw text: arg-position
939/// brackets read as ordinary characters split purely on whitespace
940/// (`ECHO [a, b]` is args `"[a,"` + `"b]"`), so the parser expands
941/// each group to open-punct + inner + close-punct and lets the normal
942/// gap-split/render reproduce the bytes exactly (probed parity).
943/// Recursion handles nesting; edge joints ride along untouched. Brace
944/// groups stay put (blocks, never args). Newlines/semicolons spliced
945/// from multi-line groups fail loudly in assembly.
946fn splice_arg_groups(body: &[Tok], stmt: usize) -> Result<Vec<Tok>, TokenError> {
947    let _ = stmt;
948    let mut out = Vec::new();
949    for tok in body.iter() {
950        match &tok.kind {
951            TokKind::Group {
952                delim: GroupDelim::Brace,
953                ..
954            } => out.push(tok.clone()),
955            // Call parens stay structural: exploding them to puncts
956            // would strand full-region calls (`MAKE()` in arg position)
957            // as raw text, disagreeing with assignment values and
958            // RUN-exec items, which both parse calls. Brackets keep
959            // the raw-text splicing below (whitespace splits inside
960            // them, strings de-quote to words).
961            TokKind::Group {
962                delim: GroupDelim::Paren,
963                ..
964            } => out.push(tok.clone()),
965            TokKind::Group {
966                delim: GroupDelim::Bracket,
967                inner,
968                close_joint,
969                ..
970            } => {
971                out.push(Tok::fresh(TokKind::Punct('['), tok.joint));
972                // Inside brackets raw-text rules apply: quotes are
973                // characters, blocks never dedent, and whitespace splits
974                // runs (`['a b']` is args `"['a"` + `"b']"`). Convert
975                // spliced strings back to word text (splitting it like
976                // raw text); top-level strings stay structural.
977                for t in splice_arg_groups(inner, stmt)? {
978                    match &t.kind {
979                        TokKind::Str { text, quote } => {
980                            out.extend(split_word_text(&format!("{quote}{text}{quote}"), t.joint));
981                        }
982                        TokKind::BlockStr(full) => {
983                            out.extend(split_word_text(full, t.joint));
984                        }
985                        _ => out.push(t),
986                    }
987                }
988                out.push(Tok::fresh(TokKind::Punct(']'), *close_joint));
989            }
990            _ => out.push(tok.clone()),
991        }
992    }
993    Ok(out)
994}
995
996/// Split re-quoted raw text on whitespace runs. The first piece keeps the source joint flag; the rest break
997/// (whitespace separates args). Multi-space gaps normalize to one
998/// (documented edge, same class as group rendering).
999fn split_word_text(text: &str, joint: bool) -> Vec<Tok> {
1000    let mut out = Vec::new();
1001    let mut first = true;
1002    for piece in text.split_whitespace() {
1003        out.push(Tok::fresh(
1004            TokKind::Word(piece.to_string()),
1005            if first { joint } else { false },
1006        ));
1007        first = false;
1008    }
1009    if out.is_empty() {
1010        out.push(Tok::fresh(TokKind::Word(text.to_string()), joint));
1011    }
1012    out
1013}
1014
1015/// Assignment key charset, minus the `=` the
1016/// classifier handles separately. Words are pre-filtered by the same
1017/// set; `$`, quotes, and groups never start a key.
1018fn is_assign_key_char(c: char) -> bool {
1019    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':')
1020}
1021
1022/// Match an assignment key run at an argument start: joint
1023/// word/punct run in the key charset, non-empty, not `--`-led
1024/// (flags keep their literal reading). Returns the key and end index.
1025fn match_assign_key(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
1026    let mut out = String::new();
1027    let mut p = pos;
1028    loop {
1029        let t = toks.get(p)?;
1030        if !out.is_empty() && !t.joint {
1031            break;
1032        }
1033        match &t.kind {
1034            TokKind::Word(w) => out.push_str(w),
1035            TokKind::Punct(c) if is_assign_key_char(*c) => out.push(*c),
1036            _ => break,
1037        }
1038        p += 1;
1039    }
1040    if out.is_empty() || out.starts_with("--") {
1041        return None;
1042    }
1043    if !out
1044        .chars()
1045        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':'))
1046    {
1047        return None;
1048    }
1049    Some((out, p))
1050}
1051
1052/// Assignment boundary ahead (for value scanning): an argument start
1053/// holding `KEY=` (key run plus `=` at any gap).
1054/// Groups and strings are opaque: a `=` inside them never counts.
1055fn at_assign_boundary(toks: &[Tok], pos: usize) -> bool {
1056    match match_assign_key(toks, pos) {
1057        Some((_, end)) => matches!(toks.get(end).map(|t| &t.kind), Some(TokKind::Punct('='))),
1058        None => false,
1059    }
1060}
1061
1062/// Line breaks nested in a raw paren run fail like flat ones did
1063/// before parens stayed structural: splicing used to surface every
1064/// `;`/newline to `render_raw_text`'s reject arm. Brace contents are
1065/// skipped (templates and blocks render whole, then and now);
1066/// brackets nested in parens were spliced before, so their breaks
1067/// fail here too. Single owner for the rule; both raw fallbacks
1068/// (positional args, assignment values) ride `render_raw_text`.
1069fn reject_paren_line_breaks(inner: &[Tok], stmt: usize) -> Result<(), TokenError> {
1070    for tok in inner {
1071        match &tok.kind {
1072            TokKind::Newline | TokKind::Semicolon => {
1073                return Err(TokenError {
1074                    diagnostic: None,
1075                    hint: None,
1076                    stmt,
1077                    msg: "unexpected line break in argument".to_string(),
1078                    line: tok.line,
1079                    col: tok.col,
1080                    kind: None,
1081                });
1082            }
1083            TokKind::Group {
1084                delim: GroupDelim::Brace,
1085                ..
1086            } => {}
1087            TokKind::Group { inner, .. } => reject_paren_line_breaks(inner, stmt)?,
1088            _ => {}
1089        }
1090    }
1091    Ok(())
1092}
1093
1094/// Raw-text render of one gap-run (or value span): words/puncts
1095/// literally (`$`+word literally, `$` elsewhere errors), strings by
1096/// their inner bytes, blocks lowered, groups spliced. Gaps collapse
1097/// to one space like `collapse_ws`; newlines/semicolons fail (the
1098/// grammar's raw span excludes them).
1099fn render_raw_text(toks: &[Tok], stmt: usize) -> Result<String, TokenError> {
1100    let mut out = String::new();
1101    let mut i = 0;
1102    while i < toks.len() {
1103        let tok = &toks[i];
1104        if !tok.joint && !out.is_empty() {
1105            out.push(' ');
1106        }
1107        match &tok.kind {
1108            TokKind::Word(w) => out.push_str(w),
1109            TokKind::Punct(c) => {
1110                if *c == VAR_SIGIL_CHAR {
1111                    // Lone-`$` runs never reach here (expression
1112                    // extension claims them first and fails loudly).
1113                    // Elsewhere `$` renders literally (probed `a$(x)`
1114                    // reads raw) except before a brace group, where
1115                    // the grammar strands it (probed `K=${x}` fails).
1116                    let next = toks.get(i + 1);
1117                    let brace_next = next.is_some_and(|t| {
1118                        matches!(
1119                            &t.kind,
1120                            TokKind::Group {
1121                                delim: GroupDelim::Brace,
1122                                ..
1123                            }
1124                        )
1125                    });
1126                    if brace_next {
1127                        return Err(TokenError {
1128                            diagnostic: None,
1129                            hint: None,
1130                            stmt,
1131                            msg: "unexpected `$` in argument".to_string(),
1132                            line: 0,
1133                            col: 0,
1134                            kind: None,
1135                        });
1136                    }
1137                    out.push(VAR_SIGIL_CHAR);
1138                } else {
1139                    out.push(*c);
1140                }
1141            }
1142            // Standalone quotes strip (the caller handles single-tok
1143            // runs); glued quotes keep their marks, like the grammar's
1144            // mixed fragments (`>"a"` stays quoted, `"a"` strips).
1145            TokKind::Str { text: s, quote } => {
1146                let glued = tok.joint || toks.get(i + 1).is_some_and(|t| t.joint);
1147                if toks.len() > 1 && glued {
1148                    out.push(*quote);
1149                    out.push_str(s);
1150                    out.push(*quote);
1151                } else {
1152                    out.push_str(s);
1153                }
1154            }
1155            // Comments reproduce verbatim (templates keep comment
1156            // text like the atomic grammar span); gaps collapse
1157            // around them like other fragments per the documented
1158            // single-space normalization.
1159            TokKind::Comment(text) => out.push_str(text),
1160            TokKind::BlockStr(full) => {
1161                // Glued blocks keep their delimiters, like quotes.
1162                let glued = tok.joint || toks.get(i + 1).is_some_and(|t| t.joint);
1163                if toks.len() > 1 && glued {
1164                    out.push_str(full);
1165                } else {
1166                    out.push_str(&crate::command::lower_block_string(full));
1167                }
1168            }
1169            TokKind::Group {
1170                delim: GroupDelim::Brace,
1171                inner,
1172                open_joint,
1173                close_joint,
1174                ..
1175            } => out.push_str(&render_brace_run_text(inner, *open_joint, *close_joint)),
1176            TokKind::Group {
1177                delim: GroupDelim::Bracket,
1178                inner,
1179                open_joint,
1180                close_joint,
1181                ..
1182            } => out.push_str(&render_group('[', ']', inner, *open_joint, *close_joint)),
1183            TokKind::Group {
1184                delim: GroupDelim::Paren,
1185                inner,
1186                open_joint,
1187                close_joint,
1188                ..
1189            } => {
1190                // Parens stayed structural (call shapes need them), so
1191                // surface the breaks splicing used to expose: a `;` or
1192                // newline anywhere inside fails exactly like a flat one
1193                // did. Brace contents keep the verbatim whole-render
1194                // below; brackets nested in parens were spliced before,
1195                // so their breaks fail here too.
1196                reject_paren_line_breaks(inner, stmt)?;
1197                out.push_str(&render_group('(', ')', inner, *open_joint, *close_joint))
1198            }
1199            TokKind::Newline | TokKind::Semicolon => {
1200                return Err(TokenError {
1201                    diagnostic: None,
1202                    hint: None,
1203                    stmt,
1204                    msg: "unexpected line break in argument".to_string(),
1205                    line: 0,
1206                    col: 0,
1207                    kind: None,
1208                });
1209            }
1210        }
1211        i += 1;
1212    }
1213    Ok(out)
1214}
1215
1216/// Build an assignment value `Arg` over a region that runs to the next
1217/// boundary or end. Single quoted/block strings keep `quoted=true`; a
1218/// region that is exactly one lone `$var`/keypath/`env:`/call shape
1219/// stays typed (calls resolve through the shared resolver, matching
1220/// `assign_expr`); everything else renders raw. A quoted unit followed
1221/// by joint content errors (probed: `K="a"b` fails), like the grammar.
1222/// Lone-shape failures stash into `deferred` and render raw: the
1223/// command's own lowering error (if any) takes precedence, and the
1224/// stashed call error surfaces only when lowering succeeds.
1225fn build_value_arg(
1226    region: &[Tok],
1227    stmt: usize,
1228    ctx: &ParseCtx,
1229    lone_ok: bool,
1230    deferred: &mut Option<TokenError>,
1231) -> Result<Arg, TokenError> {
1232    if region.is_empty() {
1233        return Ok(Arg::String(String::new(), false));
1234    }
1235    if region.len() == 1 {
1236        match &region[0].kind {
1237            TokKind::Str { text: s, .. } => return Ok(Arg::String(s.clone(), true)),
1238            TokKind::BlockStr(full) => {
1239                return Ok(Arg::String(crate::command::lower_block_string(full), true));
1240            }
1241            _ => {}
1242        }
1243    }
1244    if region.len() > 1
1245        && matches!(&region[0].kind, TokKind::Str { .. } | TokKind::BlockStr(_))
1246        && region[1].joint
1247    {
1248        return Err(TokenError {
1249            diagnostic: None,
1250            hint: None,
1251            stmt,
1252            msg: "unexpected text after quoted value".to_string(),
1253            line: 0,
1254            col: 0,
1255            kind: None,
1256        });
1257    }
1258    // Single-quoted values mid-line (`K='a b'`): the string lexer only
1259    // opens `'` gapped, so these arrive as fragments; the grammar's
1260    // `quoted_string` admits them anywhere. Reassemble a region that
1261    // opens with `'` and closes at its end, stripping exactly like a
1262    // structural string (escapes intact for runtime, like `Str`).
1263    if matches!(&region[0].kind, TokKind::Punct('\''))
1264        && let Some(text) = try_squote_value(region)
1265    {
1266        return Ok(Arg::String(text, true));
1267    }
1268    // Lone typed values apply only at a true end/boundary, never
1269    // past a comment (the grammar's `!assign_expr_cont` guard).
1270    // Failures stash (see above) so command syntax owns precedence.
1271    if lone_ok {
1272        match try_lone_value_expr(region, stmt, ctx) {
1273            Ok(Some(expr)) => return Ok(expr),
1274            Ok(None) => {}
1275            Err(err) => {
1276                deferred.get_or_insert(err);
1277            }
1278        }
1279    }
1280    Ok(Arg::String(render_raw_text(region, stmt)?, false))
1281}
1282
1283/// Reassemble a single-quoted assignment value (`K='a b'`) from its
1284/// lexer fragments: the opener must close at the region end (a
1285/// trailing fragment falls back to raw text, which fails downstream
1286/// like the grammar). Inner gaps join with one space and nested
1287/// double quotes re-quote (the atomic span keeps them); `\'` escapes
1288/// pass through intact for runtime, like structural strings. `None`
1289/// on shape miss.
1290fn try_squote_value(region: &[Tok]) -> Option<String> {
1291    // Closing `'`: first unescaped quote past the opener.
1292    let mut close = None;
1293    let mut i = 1;
1294    while i < region.len() {
1295        match &region[i].kind {
1296            TokKind::Punct('\\') => i += 2,
1297            TokKind::Punct('\'') => {
1298                close = Some(i);
1299                break;
1300            }
1301            _ => i += 1,
1302        }
1303    }
1304    if close != Some(region.len() - 1) {
1305        return None;
1306    }
1307    let mut out = String::new();
1308    for tok in &region[1..region.len() - 1] {
1309        if !tok.joint && !out.is_empty() {
1310            out.push(' ');
1311        }
1312        match &tok.kind {
1313            TokKind::Word(w) => out.push_str(w),
1314            TokKind::Punct(c) => out.push(*c),
1315            TokKind::Semicolon => out.push(';'),
1316            // Nested double quotes keep their marks (the atomic span
1317            // never strips them); triple quotes pass through whole.
1318            TokKind::Str { text, quote } => {
1319                out.push(*quote);
1320                out.push_str(text);
1321                out.push(*quote);
1322            }
1323            TokKind::BlockStr(full) => out.push_str(full),
1324            // Groups and newlines never occur in value regions (the
1325            // splitter owns them); anything else breaks the shape.
1326            _ => return None,
1327        }
1328    }
1329    Some(out)
1330}
1331
1332/// Lone assignable shapes (`assign_expr` without continuation): `$var`,
1333/// key paths, `env:KEY`, `$`-sigiled `CONST` reads (`$NAME`,
1334/// `$ALIAS::NAME`), and full-region calls
1335/// (resolved). Anything longer renders raw; the caller decides
1336/// strictness.
1337fn try_lone_value_expr(
1338    region: &[Tok],
1339    stmt: usize,
1340    ctx: &ParseCtx,
1341) -> Result<Option<Arg>, TokenError> {
1342    // `$` shapes: exactly Punct+Word or dotted runs, all joint past
1343    // the first (the region starts at an argument start by construction).
1344    if matches!(
1345        region.first().map(|t| &t.kind),
1346        Some(TokKind::Punct(VAR_SIGIL_CHAR))
1347    ) {
1348        let mut cur = Cursor::expr(region, stmt);
1349        cur.pos += 1;
1350        let base = match cur.next() {
1351            Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
1352                match &t.kind {
1353                    TokKind::Word(w) => w.clone(),
1354                    _ => unreachable!(),
1355                }
1356            }
1357            _ => return Ok(None),
1358        };
1359        // Qualified immutable read (`$ALIAS::NAME[.key]`): key paths
1360        // traverse the resolved CONST exactly like `$base.key`. Any
1361        // trailing text after the full path fails closed: there is no
1362        // grammar where trailing tokens fall back to word parsing.
1363        if let Some(name) = match_joint_qualified(cur.toks, cur.pos) {
1364            cur.pos += 3;
1365            let root = sigil_qualified(&base, &name);
1366            let keys = parse_joint_key_segments(&mut cur, &root)?;
1367            if cur.pos != region.len() {
1368                let mut display = root;
1369                for key in &keys {
1370                    display.push(KEY_PATH_SEPARATOR_CHAR);
1371                    display.push_str(key);
1372                }
1373                return Err(cur.err(format!("unexpected text after {display}")));
1374            }
1375            return Ok(Some(Arg::Expr(Expr::ConstRef {
1376                alias: base,
1377                name,
1378                keys,
1379            })));
1380        }
1381        let root = sigil_var(&base);
1382        let keys = parse_joint_key_segments(&mut cur, &root)?;
1383        if cur.pos != region.len() {
1384            return Ok(None);
1385        }
1386        return Ok(Some(Arg::Expr(if keys.is_empty() {
1387            Expr::Var { name: base }
1388        } else {
1389            Expr::KeyPath { base, keys }
1390        })));
1391    }
1392    // `env:KEY` read, gapless and exact.
1393    if region.len() == 3
1394        && matches!(&region[0].kind, TokKind::Word(w) if w == "env")
1395        && matches!(&region[1].kind, TokKind::Punct(':'))
1396        && region[1].joint
1397        && let TokKind::Word(k) = &region[2].kind
1398        && is_env_key(k)
1399        && region[2].joint
1400    {
1401        return Ok(Some(Arg::Expr(Expr::Env(k.clone()))));
1402    }
1403    // Full-region call: resolve and keep typed (canonical rendering
1404    // happens per command: verbatim for ENV/EXPAND, `K=`-joined text
1405    // elsewhere, all from the same `Arg::Expr`). Single owner for the
1406    // call tail; positional args share it (see `build_arg_tokens`).
1407    if let Some(arg) = try_lone_call_expr(region, stmt, ctx)? {
1408        return Ok(Some(arg));
1409    }
1410    Ok(None)
1411}
1412
1413/// Full-region call shape (`NAME(...)`, `MOD::NAME(...)`) over one
1414/// argument run: parse args through the shared call owner and resolve
1415/// through the shared resolver, so assignment values, RUN-exec items,
1416/// and generic positional args can never disagree on what a call is.
1417/// `None` on shape miss (caller renders raw); errors propagate, so a
1418/// misspelled callee fails loud instead of going literal.
1419fn try_lone_call_expr(
1420    region: &[Tok],
1421    stmt: usize,
1422    ctx: &ParseCtx,
1423) -> Result<Option<Arg>, TokenError> {
1424    if let Some((name, paren)) = call_shape_at(region, 0, false)
1425        && paren + 1 == region.len()
1426        && let TokKind::Group { inner, .. } = &region[paren].kind
1427    {
1428        let inner = inner.clone();
1429        let args = parse_call_args(&inner, stmt, ctx)?;
1430        if name == KEYWORD_INSPECT {
1431            let [arg] = args.as_slice() else {
1432                return Err(TokenError {
1433                    diagnostic: None,
1434                    hint: None,
1435                    stmt,
1436                    msg: format!(
1437                        "{KEYWORD_INSPECT} requires exactly one argument: {KEYWORD_INSPECT}($var)"
1438                    ),
1439                    line: 0,
1440                    col: 0,
1441                    kind: None,
1442                });
1443            };
1444            if let Expr::Var { name } = arg {
1445                return Ok(Some(Arg::Expr(Expr::Inspect { name: name.clone() })));
1446            }
1447            return Err(TokenError {
1448                diagnostic: None,
1449                hint: None,
1450                stmt,
1451                msg: format!("{KEYWORD_INSPECT} requires a $variable argument, found {arg:?}"),
1452                line: 0,
1453                col: 0,
1454                kind: None,
1455            });
1456        }
1457        let qualified = resolve_name(ctx, stmt, &name)?;
1458        return Ok(Some(Arg::Expr(Expr::Call {
1459            name: qualified,
1460            args,
1461        })));
1462    }
1463    Ok(None)
1464}
1465
1466/// Expression extension for `$`/`env:`-led argument starts: parse a
1467/// full expression (operators reach across gaps exactly like the
1468/// grammar's inner `gap`s). Ending at a gap/end yields a typed single
1469/// group; ending mid-run falls back to raw text of the run (`$x=K`);
1470/// parse failure is fatal (every fragment alternative failed).
1471/// Returns the arg and tokens consumed.
1472fn try_expr_arg(
1473    toks: &[Tok],
1474    pos: usize,
1475    stmt: usize,
1476    ctx: &ParseCtx,
1477) -> Result<Option<(Arg, usize)>, TokenError> {
1478    let extend = matches!(
1479        toks.get(pos).map(|t| &t.kind),
1480        Some(TokKind::Punct(VAR_SIGIL_CHAR))
1481    ) || matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == "env");
1482    if !extend {
1483        return Ok(None);
1484    }
1485    // A bare `env` head only extends into a real `env:KEY` read (joint
1486    // `:`); dotted bare words (`env.txt`) stay raw strings like the
1487    // grammar's `unquoted_arg`, which precedes `expr`.
1488    if matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == "env")
1489        && !matches!(
1490            (
1491                toks.get(pos + 1).map(|t| &t.kind),
1492                toks.get(pos + 1).map(|t| t.joint)
1493            ),
1494            (Some(TokKind::Punct(':')), Some(true))
1495        )
1496    {
1497        return Ok(None);
1498    }
1499    let mut cur = Cursor::expr(&toks[pos..], stmt);
1500    let expr = parse_expr_or(&mut cur, ctx)?;
1501    let end = pos + cur.pos;
1502    // Mid-run stop (joint follower): the whole run renders raw
1503    // (`$x=K`, `$a$b`); the run always ends the fallback span here
1504    // because extension starts groups.
1505    if toks.get(end).is_some_and(|t| t.joint) {
1506        let mut run_end = end;
1507        while toks.get(run_end).is_some_and(|t| t.joint) {
1508            run_end += 1;
1509        }
1510        let text = render_raw_text(&toks[pos..run_end], stmt)?;
1511        return Ok(Some((Arg::String(text, false), run_end - pos)));
1512    }
1513    Ok(Some((Arg::Expr(expr), end - pos)))
1514}
1515
1516/// Render a brace group inside raw text (`{{..}}` templates and
1517/// mid-run `{..}` shapes): verbatim bytes, single-space-normalized
1518/// gaps. Run-start non-template braces never reach here (they parse
1519/// as maps/blocks in `build_arg_tokens`).
1520fn render_brace_run_text(inner: &[Tok], open_joint: bool, close_joint: bool) -> String {
1521    render_group('{', '}', inner, open_joint, close_joint)
1522}
1523
1524/// Inner bytes of a fully-quoted word (`"hi"`, `'a'`): the re-quoted
1525/// standalone strings spliced from groups strip exactly like
1526/// structural ones. Triple-quote pieces never qualify (block lowering
1527/// owns them); glued quotes (`['a`) never reach here as sole runs.
1528fn quoted_word_inner(w: &str) -> Option<String> {
1529    if w.len() >= 2 && !w.starts_with("\"\"\"") {
1530        let q = w.as_bytes()[0] as char;
1531        if (q == '"' || q == '\'') && w.ends_with(q) {
1532            return Some(w[1..w.len() - 1].to_string());
1533        }
1534    }
1535    None
1536}
1537
1538/// Build instruction tokens over generic args, mirroring
1539/// `assignment | argument` order at every argument start: assignments
1540/// merge across gaps to the next boundary, `$`/`env:`-led runs extend
1541/// as expressions, brace-led runs try templates then maps/blocks, and
1542/// everything else renders raw. Single quoted strings keep their flag.
1543fn build_arg_tokens(
1544    toks: &[Tok],
1545    stmt: usize,
1546    ctx: &ParseCtx,
1547) -> Result<(Vec<InsToken>, Option<TokenError>), TokenError> {
1548    // Splice bracket groups first: they read as ordinary
1549    // characters (whitespace splits inside them), with strings
1550    // re-quoted back to word text. Paren groups stay structural (see
1551    // `splice_arg_groups`); brace groups stay structural
1552    // (templates render whole; blocks parse as expressions).
1553    let flat = splice_arg_groups(toks, stmt)?;
1554    let mut deferred: Option<TokenError> = None;
1555    let mut out = Vec::new();
1556    let mut pos = 0;
1557    while pos < flat.len() {
1558        // 1. Assignment: key run plus `=` at any gap.
1559        if let Some((key, key_end)) = match_assign_key(&flat, pos)
1560            && let Some(tok) = flat.get(key_end)
1561            && matches!(&tok.kind, TokKind::Punct('='))
1562        {
1563            // Value runs to the next boundary, but raw text also
1564            // stops at `//` / `/*` (raw-text rule):
1565            // a line comment swallows the rest silently, a block
1566            // comment must be followed by nothing or a boundary
1567            // (anything else strands text and fails the line, like
1568            // the grammar). Lone typed values (`$x`, calls) apply
1569            // only at a true end/boundary, never past a comment
1570            // (the grammar's `!assign_expr_cont` guard).
1571            let mut vend = key_end + 1;
1572            let mut lone_ok = true;
1573            let mut failed: Option<String> = None;
1574            'scan: while vend < flat.len() {
1575                if !flat[vend].joint && at_assign_boundary(&flat, vend) {
1576                    break;
1577                }
1578                // Lexer comment markers end the raw span like `//`
1579                // (they run to end of line by construction).
1580                if matches!(&flat[vend].kind, TokKind::Comment(_)) {
1581                    lone_ok = false;
1582                    vend = flat.len();
1583                    break;
1584                }
1585                if matches!(&flat[vend].kind, TokKind::Punct('/')) && is_comment_open(&flat, vend) {
1586                    // Comments end the raw span: line comments eat
1587                    // the rest silently, block comments must be
1588                    // followed by nothing, a boundary, or more
1589                    // comments (stranded text fails the line, like
1590                    // the grammar).
1591                    lone_ok = false;
1592                    loop {
1593                        if vend >= flat.len()
1594                            || (!flat[vend].joint && at_assign_boundary(&flat, vend))
1595                        {
1596                            break 'scan;
1597                        }
1598                        if !matches!(&flat[vend].kind, TokKind::Punct('/'))
1599                            || !is_comment_open(&flat, vend)
1600                        {
1601                            failed = Some("unexpected text after assignment value".to_string());
1602                            break 'scan;
1603                        }
1604                        if matches!(
1605                            flat.get(vend + 1).map(|t| &t.kind),
1606                            Some(TokKind::Punct('/'))
1607                        ) {
1608                            vend = flat.len();
1609                            break 'scan;
1610                        }
1611                        match skip_inline_comment(&flat, vend) {
1612                            None => {
1613                                failed = Some("unclosed block comment".to_string());
1614                                break 'scan;
1615                            }
1616                            Some(past) => vend = past,
1617                        }
1618                    }
1619                }
1620                vend += 1;
1621            }
1622            if let Some(msg) = failed {
1623                return Err(TokenError {
1624                    diagnostic: None,
1625                    hint: None,
1626                    stmt,
1627                    msg,
1628                    line: 0,
1629                    col: 0,
1630                    kind: None,
1631                });
1632            }
1633            let value =
1634                build_value_arg(&flat[key_end + 1..vend], stmt, ctx, lone_ok, &mut deferred)?;
1635            out.push(InsToken::Assign(key, value));
1636            pos = vend;
1637            continue;
1638        }
1639        // 2. Brace-led run: template text, else map/block expression.
1640        if matches!(
1641            flat.get(pos).map(|t| &t.kind),
1642            Some(TokKind::Group {
1643                delim: GroupDelim::Brace,
1644                ..
1645            })
1646        ) {
1647            let mut run_end = pos + 1;
1648            while flat.get(run_end).is_some_and(|t| t.joint) {
1649                run_end += 1;
1650            }
1651            let run = &flat[pos..run_end];
1652            let is_template = is_template_brace(&run[0]);
1653            if is_template {
1654                out.push(InsToken::Pos(Arg::String(
1655                    render_raw_text(run, stmt)?,
1656                    false,
1657                )));
1658            } else {
1659                let inner = match &run[0].kind {
1660                    TokKind::Group { inner, .. } => inner.clone(),
1661                    _ => unreachable!(),
1662                };
1663                // Map success alone stays typed; map success with a
1664                // joint tail renders raw (`{k:1}x`, like the grammar's
1665                // mixed fragments); map failure defers/errors exactly
1666                // like the expression path.
1667                match parse_map_or_block(&inner, stmt, ctx) {
1668                    Ok(expr) if run.len() == 1 => {
1669                        out.push(InsToken::Pos(Arg::Expr(expr)));
1670                    }
1671                    Ok(_) => out.push(InsToken::Pos(Arg::String(
1672                        render_raw_text(run, stmt)?,
1673                        false,
1674                    ))),
1675                    Err(e) => return Err(e),
1676                }
1677            }
1678            pos = run_end;
1679            continue;
1680        }
1681        // 3. `$`/`env:`-led expression extension.
1682        if let Some((arg, used)) = try_expr_arg(&flat, pos, stmt, ctx)? {
1683            // A lone expression group stays typed; the fallback
1684            // already rendered text above.
1685            out.push(InsToken::Pos(arg));
1686            pos += used;
1687            continue;
1688        }
1689        // 4. Raw text run to the next gap.
1690        let mut run_end = pos + 1;
1691        while flat.get(run_end).is_some_and(|t| t.joint) {
1692            run_end += 1;
1693        }
1694        let run = &flat[pos..run_end];
1695        // Slash-pair-led runs (`/*c*/`; `//` arrives as `Comment`
1696        // toks) parse as expression fragments (typed when single,
1697        // glued verbatim otherwise).
1698        if is_slash_run(run) {
1699            out.push(InsToken::Pos(parse_slash_run(run, stmt, ctx)?));
1700            pos = run_end;
1701            continue;
1702        }
1703        // Trailing `Comment` (`//` to end of line) glues as a
1704        // literal fragment (typed when alone, verbatim otherwise),
1705        // exactly like the grammar's expression fragments.
1706        if let Some(TokKind::Comment(text)) = run.last().map(|t| &t.kind) {
1707            if run.len() == 1 {
1708                out.push(InsToken::Pos(Arg::Expr(Expr::Literal(Value::string(
1709                    text.clone(),
1710                )))));
1711            } else {
1712                let mut bytes = render_raw_text(&run[..run.len() - 1], stmt)?;
1713                bytes.push_str(text);
1714                out.push(InsToken::Pos(Arg::String(bytes, false)));
1715            }
1716            pos = run_end;
1717            continue;
1718        }
1719        if run.len() == 1 {
1720            match &run[0].kind {
1721                TokKind::Str { text: s, .. } => {
1722                    out.push(InsToken::Pos(Arg::String(s.clone(), true)));
1723                    pos = run_end;
1724                    continue;
1725                }
1726                TokKind::BlockStr(full) => {
1727                    out.push(InsToken::Pos(Arg::String(
1728                        crate::command::lower_block_string(full),
1729                        true,
1730                    )));
1731                    pos = run_end;
1732                    continue;
1733                }
1734                // Re-quoted standalone strings (spliced from groups)
1735                // strip exactly like structural ones (`["hi"]` gives
1736                // `hi`); glued quotes stay literal (`['a` keeps its
1737                // mark). Triple-quote pieces never qualify.
1738                TokKind::Word(w) if quoted_word_inner(w).is_some() => {
1739                    out.push(InsToken::Pos(Arg::String(
1740                        quoted_word_inner(w).unwrap(),
1741                        true,
1742                    )));
1743                    pos = run_end;
1744                    continue;
1745                }
1746                _ => {}
1747            }
1748        }
1749        // Bare full-region calls stay typed like assignment values and
1750        // RUN-exec items (same owner, `try_lone_call_expr`), so every
1751        // argument position evaluates them instead of one silently
1752        // appending the source text. Failures stash: the command's own
1753        // lowering error (if any) takes precedence, and the stashed
1754        // call error surfaces only when lowering succeeds.
1755        match try_lone_call_expr(run, stmt, ctx) {
1756            Ok(Some(arg)) => {
1757                out.push(InsToken::Pos(arg));
1758                pos = run_end;
1759                continue;
1760            }
1761            Ok(None) => {}
1762            Err(err) => {
1763                deferred.get_or_insert(err);
1764            }
1765        }
1766        out.push(InsToken::Pos(Arg::String(
1767            render_raw_text(run, stmt)?,
1768            false,
1769        )));
1770        pos = run_end;
1771    }
1772    Ok((out, deferred))
1773}
1774
1775/// A raw run starting with `//` or `/*` (a slash-pair: `/` plus a
1776/// joint `/` or `*`) parses as expression fragments: both route to
1777/// `expr` there (so `//c` types as a literal and `/*c*/` as math). A single
1778/// fully-consuming expression stays typed; anything longer glues to
1779/// verbatim text exactly like the grammar's mixed fragments (byte
1780/// for byte, since joint runs admit no span gaps). An unparseable
1781/// unterminated block open (`/*` with no `*/` in the run) reads
1782/// literally like the old backend (`ECHO /*`, `[a /* c]`); a
1783/// terminated span keeps the loud failure.
1784fn parse_slash_run(run: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Arg, TokenError> {
1785    let mut cur = Cursor::expr(run, stmt);
1786    match parse_expr_checked(&mut cur, ctx) {
1787        Ok(expr) if cur.done() => Ok(Arg::Expr(expr)),
1788        Ok(_) => Ok(Arg::String(render_raw_text(run, stmt)?, false)),
1789        Err(_) if !run_has_block_close(run) => Ok(Arg::String(render_raw_text(run, stmt)?, false)),
1790        Err(e) => Err(e),
1791    }
1792}
1793
1794/// True when the run holds a `*/` close pair (`*` plus a joint `/`),
1795/// mirroring [`skip_inline_comment`]'s terminator: only unterminated
1796/// block opens read literally.
1797fn run_has_block_close(run: &[Tok]) -> bool {
1798    run.windows(2).any(|w| {
1799        matches!(&w[0].kind, TokKind::Punct('*'))
1800            && matches!(&w[1].kind, TokKind::Punct('/'))
1801            && w[1].joint
1802    })
1803}
1804
1805/// True when a raw run opens with a slash-pair (`/` plus a joint
1806/// `/` or `*`), routing it to expression fragments (see
1807/// [`parse_slash_run`]). A lone `/` (`/a`, `/`) stays raw text.
1808fn is_slash_run(run: &[Tok]) -> bool {
1809    matches!(run.first().map(|t| &t.kind), Some(TokKind::Punct('/')))
1810        && matches!(
1811            run.get(1).map(|t| (&t.kind, t.joint)),
1812            Some((TokKind::Punct('/'), true)) | Some((TokKind::Punct('*'), true))
1813        )
1814}
1815
1816/// Lower generic args through the shared cores: `ENV`/`EXPAND` bypass
1817/// the injected dispatcher; everything else
1818/// canonicalizes assignments and calls it.
1819fn lower_generic_args(
1820    name: &str,
1821    tokens: Vec<InsToken>,
1822    stmt: usize,
1823    ctx: &ParseCtx,
1824) -> Result<StepKind, TokenError> {
1825    if name == KEYWORD_ENV {
1826        return lower_env_tokens(&lowering_ctx(stmt), tokens).map_err(|e| lower_err(stmt, e));
1827    }
1828    if name == KEYWORD_EXPAND {
1829        return lower_expand_tokens(&lowering_ctx(stmt), tokens).map_err(|e| lower_err(stmt, e));
1830    }
1831    let args = tokens
1832        .into_iter()
1833        .map(|token| match token {
1834            InsToken::Pos(arg) => arg,
1835            InsToken::Assign(key, value) => canonical_assignment_arg(&key, &value),
1836        })
1837        .collect();
1838    (ctx.lower)(name, args).map_err(|e| lower_err(stmt, e))
1839}
1840
1841/// Render a bracket/paren/brace group back to source text for raw-text
1842/// positions (in-body groups are args, template braces render whole).
1843/// Fragments join with a space on gaps and glue on `joint`, so both
1844/// lexers render the same source identically; quote styles round-trip
1845/// exactly. Known normalization (documented, not silent): multi-space
1846/// gaps collapse to one.
1847fn render_group(
1848    open: char,
1849    close: char,
1850    inner: &[Tok],
1851    open_joint: bool,
1852    close_joint: bool,
1853) -> String {
1854    let mut out = String::from(open);
1855    if !open_joint && !inner.is_empty() {
1856        out.push(' ');
1857    }
1858    let mut first = true;
1859    for tok in inner {
1860        match &tok.kind {
1861            TokKind::Newline => out.push('\n'),
1862            TokKind::Semicolon => out.push(';'),
1863            // Comments reproduce verbatim (templates keep comment
1864            // text like the atomic grammar span); like newlines they
1865            // carry their own separation, never a synthetic space.
1866            TokKind::Comment(text) => out.push_str(text),
1867            _ => {
1868                if !first && !tok.joint {
1869                    out.push(' ');
1870                }
1871                match &tok.kind {
1872                    TokKind::Word(w) => out.push_str(w),
1873                    TokKind::Punct(c) => out.push(*c),
1874                    TokKind::Str { text, quote } => {
1875                        out.push(*quote);
1876                        out.push_str(text);
1877                        out.push(*quote);
1878                    }
1879                    TokKind::BlockStr(full) => out.push_str(full),
1880                    TokKind::Group {
1881                        delim: GroupDelim::Bracket,
1882                        inner,
1883                        open_joint,
1884                        close_joint,
1885                        ..
1886                    } => out.push_str(&render_group('[', ']', inner, *open_joint, *close_joint)),
1887                    TokKind::Group {
1888                        delim: GroupDelim::Paren,
1889                        inner,
1890                        open_joint,
1891                        close_joint,
1892                        ..
1893                    } => out.push_str(&render_group('(', ')', inner, *open_joint, *close_joint)),
1894                    TokKind::Group {
1895                        delim: GroupDelim::Brace,
1896                        inner,
1897                        open_joint,
1898                        close_joint,
1899                        ..
1900                    } => out.push_str(&render_group('{', '}', inner, *open_joint, *close_joint)),
1901                    // Comments reproduce verbatim (nested groups keep
1902                    // comment text like the atomic grammar span).
1903                    TokKind::Comment(text) => out.push_str(text),
1904                    TokKind::Newline | TokKind::Semicolon => unreachable!(),
1905                }
1906            }
1907        }
1908        first = false;
1909    }
1910    if !close_joint && !inner.is_empty() {
1911        out.push(' ');
1912    }
1913    out.push(close);
1914    out
1915}
1916
1917/// Positional cursor over guard/group token slices. Newlines skip
1918/// freely between tokens (`ws` admits linebreaks in the grammar);
1919/// bare key/value runs never cross them (the grammar excludes
1920/// linebreaks there), so runs read raw.
1921///
1922/// Expression parsing reuses this cursor with `nl_skip = false`:
1923/// expressions are single-line (`gap`, never `gap_nl`, between
1924/// operands), so a newline terminates instead of vanishing. Newlines
1925/// inside group inners (call args, lists, maps) skip via explicit
1926/// `skip_newlines` calls at the grammar's `gap_nl` junctures.
1927struct Cursor<'t> {
1928    toks: &'t [Tok],
1929    pos: usize,
1930    stmt: usize,
1931    nl_skip: bool,
1932}
1933
1934impl<'t> Cursor<'t> {
1935    fn new(toks: &'t [Tok], stmt: usize) -> Self {
1936        Self {
1937            toks,
1938            pos: 0,
1939            stmt,
1940            nl_skip: true,
1941        }
1942    }
1943
1944    /// Expression-mode cursor: newlines stop, never skip.
1945    fn expr(toks: &'t [Tok], stmt: usize) -> Self {
1946        Self {
1947            toks,
1948            pos: 0,
1949            stmt,
1950            nl_skip: false,
1951        }
1952    }
1953
1954    fn err(&self, msg: impl Into<String>) -> TokenError {
1955        TokenError {
1956            diagnostic: None,
1957            hint: None,
1958            stmt: self.stmt,
1959            line: 0,
1960            col: 0,
1961            msg: msg.into(),
1962            kind: None,
1963        }
1964    }
1965
1966    fn skip_newlines(&mut self) {
1967        while matches!(
1968            self.toks.get(self.pos).map(|t| &t.kind),
1969            Some(TokKind::Newline)
1970        ) {
1971            self.pos += 1;
1972        }
1973    }
1974
1975    fn peek(&mut self) -> Option<&'t Tok> {
1976        if self.nl_skip {
1977            self.skip_newlines();
1978        }
1979        self.toks.get(self.pos)
1980    }
1981
1982    fn next(&mut self) -> Option<&'t Tok> {
1983        if self.nl_skip {
1984            self.skip_newlines();
1985        }
1986        let t = self.toks.get(self.pos)?;
1987        self.pos += 1;
1988        Some(t)
1989    }
1990
1991    fn done(&mut self) -> bool {
1992        if self.nl_skip {
1993            self.skip_newlines();
1994        }
1995        self.pos >= self.toks.len()
1996    }
1997
1998    fn eat_punct(&mut self, c: char) -> bool {
1999        if self.nl_skip {
2000            self.skip_newlines();
2001        }
2002        match self.peek() {
2003            Some(t) if matches!(&t.kind, TokKind::Punct(p) if *p == c) => {
2004                self.pos += 1;
2005                true
2006            }
2007            _ => false,
2008        }
2009    }
2010
2011    /// Skip one gap's worth of comments (`gap`: `//`-to-newline,
2012    /// balanced `/* */` even across newlines, `#`-to-newline —
2013    /// never a standalone newline, which ends single-line
2014    /// expressions. Greedy gap before operators and operands; whitespace itself is
2015    /// already invisible in the token stream.
2016    fn skip_gap(&mut self) {
2017        loop {
2018            match self.toks.get(self.pos).map(|t| &t.kind) {
2019                Some(TokKind::Comment(_)) => {
2020                    self.pos += 1;
2021                }
2022                Some(TokKind::Punct('/')) if is_comment_open(self.toks, self.pos) => {
2023                    match skip_inline_comment(self.toks, self.pos) {
2024                        Some(next) => self.pos = next,
2025                        // Unclosed block comments fail the gap (and
2026                        // the enclosing rule) like the grammar.
2027                        None => break,
2028                    }
2029                }
2030                Some(TokKind::Punct('#')) => {
2031                    while self.pos < self.toks.len()
2032                        && !matches!(&self.toks[self.pos].kind, TokKind::Newline)
2033                    {
2034                        self.pos += 1;
2035                    }
2036                }
2037                _ => break,
2038            }
2039        }
2040    }
2041
2042    /// Skip gap comments plus standalone newlines (`gap_nl`: call
2043    /// args, list items, maps, parenthesized expressions).
2044    fn skip_gap_nl(&mut self) {
2045        loop {
2046            match self.toks.get(self.pos).map(|t| &t.kind) {
2047                Some(TokKind::Newline) => {
2048                    self.pos += 1;
2049                }
2050                _ => {
2051                    let before = self.pos;
2052                    self.skip_gap();
2053                    if self.pos == before {
2054                        break;
2055                    }
2056                }
2057            }
2058        }
2059    }
2060
2061    /// Consume the parenthesized group following a call word (`not`,
2062    /// `any`, `all`, `eq`, `ne`), ignoring gap width exactly like the
2063    /// grammar's implicit whitespace.
2064    fn eat_paren_group(&mut self) -> Option<Vec<Tok>> {
2065        match self.peek() {
2066            Some(t) => match &t.kind {
2067                TokKind::Group {
2068                    delim: GroupDelim::Paren,
2069                    inner,
2070                    ..
2071                } => {
2072                    let inner = inner.clone();
2073                    self.pos += 1;
2074                    Some(inner)
2075                }
2076                _ => None,
2077            },
2078            None => None,
2079        }
2080    }
2081}
2082
2083/// Split a flat token slice on top-level commas (nesting lives inside
2084/// atomic groups, so a flat scan is exact).
2085fn split_top_commas(toks: &[Tok]) -> Vec<&[Tok]> {
2086    let mut parts = Vec::new();
2087    let mut start = 0;
2088    for (i, t) in toks.iter().enumerate() {
2089        if matches!(&t.kind, TokKind::Punct(',')) {
2090            parts.push(&toks[start..i]);
2091            start = i + 1;
2092        }
2093    }
2094    parts.push(&toks[start..]);
2095    parts
2096}
2097
2098/// Punctuation admissible inside bare guard key runs: everything but
2099/// the terminators the parser enforces separately. `;` arrives as its
2100/// own token kind; the key charset admits it, so runs accept it literally.
2101fn key_char(c: char) -> bool {
2102    !matches!(
2103        c,
2104        ':' | '=' | '!' | ',' | '|' | '(' | ')' | ']' | VAR_SIGIL_CHAR
2105    )
2106}
2107
2108/// Consume a joint run of words/punctuation as one bare key or value.
2109/// Gaps end the run; terminators and groups end or fail it per `extra`.
2110fn bare_run(cur: &mut Cursor, extra: fn(char) -> bool, what: &str) -> Result<String, TokenError> {
2111    let mut out = String::new();
2112    loop {
2113        let tok = match cur.toks.get(cur.pos) {
2114            Some(t) if matches!(&t.kind, TokKind::Newline) => break,
2115            Some(t) => t,
2116            None => break,
2117        };
2118        // First element may follow a gap; continuations must be gapless.
2119        if !out.is_empty() && !tok.joint {
2120            break;
2121        }
2122        match &tok.kind {
2123            TokKind::Word(w) => out.push_str(w),
2124            TokKind::Punct(c) if key_char(*c) && extra(*c) => out.push(*c),
2125            TokKind::Semicolon if extra(';') => out.push(';'),
2126            _ => break,
2127        }
2128        cur.pos += 1;
2129    }
2130    if out.is_empty() {
2131        return Err(cur.err(format!("missing {what}")));
2132    }
2133    Ok(out)
2134}
2135
2136/// The `guard_term` negative lookahead: a complete term followed by
2137/// `(`, `:`, `=`, or `!` is malformed, never a longer form.
2138fn check_term_end(cur: &mut Cursor) -> Result<(), TokenError> {
2139    cur.skip_newlines();
2140    match cur.toks.get(cur.pos) {
2141        Some(t) => match &t.kind {
2142            TokKind::Group {
2143                delim: GroupDelim::Paren,
2144                ..
2145            } => Err(cur.err("unexpected `(` after guard term")),
2146            TokKind::Punct(c) if matches!(c, ':' | '=' | '!') => {
2147                Err(cur.err(format!("unexpected `{c}` after guard term")))
2148            }
2149            _ => Ok(()),
2150        },
2151        None => Ok(()),
2152    }
2153}
2154
2155fn os_guard(value: &str) -> GuardExpr {
2156    GuardExpr::Predicate(Guard::Attr {
2157        ns: Ns::Os,
2158        key: None,
2159        val: Some(value.to_string()),
2160    })
2161}
2162
2163/// Namespace validation for guard predicates with closed domains
2164/// (`family`, `os`, `arch`); open namespaces pass through.
2165fn ns_guard(ns: &str, val: &str, cur: &Cursor) -> Result<GuardExpr, TokenError> {
2166    match ns {
2167        "family" => match val {
2168            "unix" => Ok(GuardExpr::or(vec![os_guard("macos"), os_guard("linux")])),
2169            "windows" => Ok(os_guard("windows")),
2170            _ => Err(cur.err(format!(
2171                "unknown family '{val}'; known values: unix, windows"
2172            ))),
2173        },
2174        "os" => match val {
2175            "macos" | "linux" | "windows" => Ok(os_guard(val)),
2176            _ => Err(cur.err(format!(
2177                "unknown os '{val}'; known values: macos, linux, windows"
2178            ))),
2179        },
2180        "arch" => {
2181            if crate::ARCH_VALUES.contains(&val) {
2182                Ok(GuardExpr::Predicate(Guard::Attr {
2183                    ns: Ns::Arch,
2184                    key: None,
2185                    val: Some(val.to_string()),
2186                }))
2187            } else {
2188                Err(cur.err(format!(
2189                    "unknown arch '{val}'; known values: {}",
2190                    crate::ARCH_VALUES.join(", ")
2191                )))
2192            }
2193        }
2194        _ => Err(cur.err(format!(
2195            "unknown guard namespace '{ns}'; known namespaces: family, os, arch, env, bool"
2196        ))),
2197    }
2198}
2199
2200fn parse_guard_term(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2201    let tok = cur
2202        .next()
2203        .ok_or_else(|| cur.err("missing guard predicate"))?;
2204    // A `!` prefix is never negation in guards (only `not(...)` negates).
2205    if matches!(&tok.kind, TokKind::Punct('!')) {
2206        return Err(cur.err("unexpected `!` in guard; negation uses `not(...)`"));
2207    }
2208    let word = match &tok.kind {
2209        TokKind::Word(w) => w.clone(),
2210        _ => return Err(cur.err("missing guard predicate")),
2211    };
2212    // `__OXDOCK_INJECT_N__` interpolation placeholder: env-key shape.
2213    if let Some(rest) = word.strip_prefix(INJECT_PREFIX) {
2214        if !rest.is_empty()
2215            && rest
2216                .strip_suffix(INJECT_SUFFIX)
2217                .is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()))
2218        {
2219            return Ok(GuardExpr::Predicate(Guard::Attr {
2220                ns: Ns::Env,
2221                key: Some(word),
2222                val: None,
2223            }));
2224        }
2225        return Err(cur.err("missing guard predicate"));
2226    }
2227    match word.as_str() {
2228        "eq" | "ne" => {
2229            let inner = cur
2230                .eat_paren_group()
2231                .ok_or_else(|| cur.err(format!("`{word}` requires `(env:KEY, value)`")))?;
2232            let mut arg = Cursor::new(&inner, cur.stmt);
2233            if arg.next().map(|t| &t.kind) != Some(&TokKind::Word("env".to_string())) {
2234                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2235            }
2236            if !arg.eat_punct(':') {
2237                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2238            }
2239            let key = bare_run(&mut arg, |_| true, "guard key")?;
2240            if !arg.eat_punct(',') {
2241                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2242            }
2243            arg.skip_newlines();
2244            let value = match arg.next() {
2245                Some(t) => match &t.kind {
2246                    TokKind::Str { text, .. } => text.clone(),
2247                    TokKind::BlockStr(full) => crate::command::lower_block_string(full),
2248                    _ => {
2249                        // Bare value: runs to the region end (commas and
2250                        // groups terminate it with an error, matching the
2251                        // bare-value exclusions).
2252                        arg.pos -= 1;
2253                        value_run(&mut arg)?
2254                    }
2255                },
2256                None => return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`"))),
2257            };
2258            if !arg.done() {
2259                return Err(arg.err(format!("unexpected text after `{word}` value")));
2260            }
2261            let pred = GuardExpr::Predicate(Guard::Attr {
2262                ns: Ns::Env,
2263                key: Some(key),
2264                val: Some(value),
2265            });
2266            if word == "ne" {
2267                Ok(GuardExpr::Not(Box::new(pred)))
2268            } else {
2269                Ok(pred)
2270            }
2271        }
2272        "bool" => {
2273            if !cur.eat_punct(':') {
2274                return Err(cur.err("`bool` requires `:value`"));
2275            }
2276            let val = bare_run(cur, |_| true, "bool value")?;
2277            check_term_end(cur)?;
2278            Ok(GuardExpr::Predicate(Guard::Attr {
2279                ns: Ns::Bool,
2280                key: None,
2281                val: Some(val),
2282            }))
2283        }
2284        "env" => {
2285            if !cur.eat_punct(':') {
2286                return Err(cur.err("`env` requires `:KEY`"));
2287            }
2288            let key = bare_run(cur, |_| true, "guard key")?;
2289            check_term_end(cur)?;
2290            Ok(GuardExpr::Predicate(Guard::Attr {
2291                ns: Ns::Env,
2292                key: Some(key),
2293                val: None,
2294            }))
2295        }
2296        _ => {
2297            if !cur.eat_punct(':') {
2298                return Err(cur.err("missing guard predicate"));
2299            }
2300            let val = bare_run(cur, |_| true, "guard value")?;
2301            check_term_end(cur)?;
2302            ns_guard(&word, &val, cur)
2303        }
2304    }
2305}
2306
2307/// Bare `eq`/`ne` value run: key charset plus `:`/`=`/`!` (the grammar
2308/// admits them in values, never in keys), with nested groups rendered
2309/// for the pathological `(`-in-value shape. `$`, `|`, `,` terminate
2310/// with an error downstream.
2311/// Bare `eq`/`ne` value with atomic bare-value semantics:
2312/// everything except `, | ) ] $`, linebreaks, and comment opens —
2313/// gaps included (joined with one space; the token stream cannot
2314/// preserve gap width). Quotes ride literally mid-run (the atomic
2315/// span keeps them); a *leading* quote never reaches here (the
2316/// caller strips it as the `quoted_string` alternative, which then
2317/// requires end-of-region like the grammar's committed choice).
2318fn value_run(arg: &mut Cursor) -> Result<String, TokenError> {
2319    let mut out = String::new();
2320    while let Some(tok) = arg.toks.get(arg.pos) {
2321        // Terminators: the grammar's negative-lookahead set.
2322        match &tok.kind {
2323            TokKind::Newline | TokKind::Comment(_) => break,
2324            TokKind::Punct(',')
2325            | TokKind::Punct('|')
2326            | TokKind::Punct(']')
2327            | TokKind::Punct(')') => break,
2328            TokKind::Punct(VAR_SIGIL_CHAR) => break,
2329            TokKind::Punct('/') if is_comment_open(arg.toks, arg.pos) => break,
2330            TokKind::Group { .. } => break,
2331            _ => {}
2332        }
2333        if !out.is_empty() && !tok.joint {
2334            out.push(' ');
2335        }
2336        match &tok.kind {
2337            TokKind::Word(w) => out.push_str(w),
2338            TokKind::Punct(c) => out.push(*c),
2339            TokKind::Semicolon => out.push(';'),
2340            // Mid-run quotes keep their marks, like the atomic span.
2341            TokKind::Str { text, quote } => {
2342                out.push(*quote);
2343                out.push_str(text);
2344                out.push(*quote);
2345            }
2346            TokKind::BlockStr(full) => out.push_str(full),
2347            _ => break,
2348        }
2349        arg.pos += 1;
2350    }
2351    if out.is_empty() {
2352        return Err(arg.err("missing guard value"));
2353    }
2354    Ok(out)
2355}
2356
2357/// True when the cursor sits on `name` followed (over newlines,
2358/// like the grammar's implicit whitespace) by a paren group.
2359fn at_call(cur: &Cursor, name: &str) -> bool {
2360    let mut pos = cur.pos;
2361    // Leading newlines skip (the grammar's implicit whitespace gaps
2362    // multi-line guards, e.g. `[\nnot(env:K)\n]`).
2363    while matches!(cur.toks.get(pos).map(|t| &t.kind), Some(TokKind::Newline)) {
2364        pos += 1;
2365    }
2366    match cur.toks.get(pos) {
2367        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == name) => pos += 1,
2368        _ => return false,
2369    }
2370    while matches!(cur.toks.get(pos).map(|t| &t.kind), Some(TokKind::Newline)) {
2371        pos += 1;
2372    }
2373    matches!(
2374        cur.toks.get(pos).map(|t| &t.kind),
2375        Some(TokKind::Group {
2376            delim: GroupDelim::Paren,
2377            ..
2378        })
2379    )
2380}
2381
2382fn parse_guard_primary(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2383    // Call shapes dispatch on word + paren group regardless of gap
2384    // width (the grammar's implicit whitespace); anything else is a term.
2385    for name in ["not", "any", "all"] {
2386        if at_call(cur, name) {
2387            cur.next();
2388            let inner = cur
2389                .eat_paren_group()
2390                .ok_or_else(|| cur.err("unreachable"))?;
2391            let parts = split_top_commas(&inner);
2392            match name {
2393                "not" => {
2394                    if parts.len() != 1 {
2395                        return Err(cur.err("`not` takes exactly one guard expression"));
2396                    }
2397                    let mut sub = Cursor::new(parts[0], cur.stmt);
2398                    let expr = parse_guard_seq(&mut sub)?;
2399                    if !sub.done() {
2400                        return Err(sub.err("unexpected text in `not`"));
2401                    }
2402                    return Ok(GuardExpr::Not(Box::new(expr)));
2403                }
2404                "any" => {
2405                    if parts.len() < 2 {
2406                        return Err(cur.err("any(...) requires at least two guard expressions"));
2407                    }
2408                    let mut exprs = Vec::new();
2409                    for part in parts {
2410                        let mut sub = Cursor::new(part, cur.stmt);
2411                        exprs.push(parse_guard_seq(&mut sub)?);
2412                        if !sub.done() {
2413                            return Err(sub.err("unexpected text in `any`"));
2414                        }
2415                    }
2416                    return Ok(GuardExpr::or(exprs));
2417                }
2418                _ => {
2419                    if parts.is_empty() {
2420                        return Err(cur.err("all(...) requires at least one guard expression"));
2421                    }
2422                    let mut exprs = Vec::new();
2423                    for part in parts {
2424                        if part.iter().all(|t| matches!(&t.kind, TokKind::Newline)) {
2425                            return Err(cur.err("all(...) requires at least one guard expression"));
2426                        }
2427                        let mut sub = Cursor::new(part, cur.stmt);
2428                        exprs.push(parse_guard_seq(&mut sub)?);
2429                        if !sub.done() {
2430                            return Err(sub.err("unexpected text in `all`"));
2431                        }
2432                    }
2433                    return Ok(GuardExpr::all(exprs));
2434                }
2435            }
2436        }
2437    }
2438    match cur.peek() {
2439        Some(t) => match &t.kind {
2440            TokKind::Group {
2441                delim: GroupDelim::Paren,
2442                inner,
2443                ..
2444            } => {
2445                let inner = inner.clone();
2446                cur.next();
2447                let mut sub = Cursor::new(&inner, cur.stmt);
2448                let expr = parse_guard_seq(&mut sub)?;
2449                if !sub.done() {
2450                    return Err(sub.err("unexpected text in guard group"));
2451                }
2452                Ok(expr)
2453            }
2454            _ => parse_guard_term(cur),
2455        },
2456        None => Err(cur.err("missing guard expression")),
2457    }
2458}
2459
2460fn parse_guard_seq(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2461    let first = parse_guard_primary(cur)?;
2462    let mut rest = vec![first];
2463    while cur.eat_punct(',') {
2464        rest.push(parse_guard_primary(cur)?);
2465    }
2466    if rest.len() == 1 {
2467        Ok(rest.pop().unwrap())
2468    } else {
2469        Ok(GuardExpr::all(rest))
2470    }
2471}
2472
2473/// Parse one bracket group's contents as a guard expression.
2474fn parse_guard_inner(inner: &[Tok], stmt: usize) -> Result<GuardExpr, TokenError> {
2475    let mut cur = Cursor::new(inner, stmt);
2476    let expr = parse_guard_seq(&mut cur)?;
2477    if !cur.done() {
2478        return Err(cur.err("unexpected text in guard"));
2479    }
2480    Ok(expr)
2481}
2482
2483/// Parse one standalone guard expression from lexed tokens (the
2484/// `parse_guard_expr_str` entry point): a bare `guard_seq` with full
2485/// consumption.
2486pub(crate) fn parse_single_guard(toks: &[Tok], stmt: usize) -> Result<GuardExpr, TokenError> {
2487    let mut cur = Cursor::new(toks, stmt);
2488    if cur.done() {
2489        return Err(cur.err("empty guard"));
2490    }
2491    let expr = parse_guard_seq(&mut cur)?;
2492    if !cur.done() {
2493        return Err(cur.err("unexpected text in guard"));
2494    }
2495    Ok(expr)
2496}
2497
2498/// Combine a statement's leading guard groups: stacked brackets `All`
2499/// together, a single bracket stands alone.
2500fn parse_guard_groups(guard: &[Tok], stmt: usize) -> Result<Option<GuardExpr>, TokenError> {
2501    let mut acc: Option<GuardExpr> = None;
2502    for tok in guard {
2503        let inner = match &tok.kind {
2504            TokKind::Group {
2505                delim: GroupDelim::Bracket,
2506                inner,
2507                ..
2508            } => inner.clone(),
2509            _ => {
2510                return Err(TokenError {
2511                    diagnostic: None,
2512                    hint: None,
2513                    stmt,
2514                    msg: "unsupported non-bracket guard".to_string(),
2515                    line: 0,
2516                    col: 0,
2517                    kind: None,
2518                });
2519            }
2520        };
2521        let expr = parse_guard_inner(&inner, stmt)?;
2522        acc = Some(match acc {
2523            None => expr,
2524            Some(prev) => GuardExpr::all(vec![prev, expr]),
2525        });
2526    }
2527    Ok(acc)
2528}
2529
2530// ---- Calls, RUN-exec, instruction exactness ----
2531// Static call resolution runs through the shared `resolve_call_name`
2532// (same module table, same messages); only the token-level call-shape
2533// detector is v2-native. Generic arguments classify like the
2534// `assignment | argument` grammar order (assignments merge across
2535// gaps, `$`/`env:`-led runs extend as expressions, everything else
2536// renders raw), and `ENV`/`EXPAND` lower through the shared direct
2537// cores instead of the injected dispatcher.
2538
2539/// Parse context: shared lowering dispatcher plus module table for
2540/// static call resolution, with `FUNC`/import frames per braced body.
2541pub struct ParseCtx<'a> {
2542    pub lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
2543    pub modules: &'a ModuleTable,
2544    /// Host-registered function names for the `FUNC` shadow check
2545    /// (empty when hosts are unknown).
2546    pub reserved: &'a HashSet<String>,
2547    /// `FUNC` scopes (innermost last) and import frames, pushed per
2548    /// braced body; short borrows only,
2549    /// never held across recursive parses.
2550    pub funcs: RefCell<Vec<HashSet<String>>>,
2551    pub imports: RefCell<Vec<Vec<(String, bool)>>>,
2552    /// Single-file `EXPORT` metadata in source order, validated at end
2553    /// of parse (forward references allowed). One struct for all three
2554    /// kinds so holders never thread parallel lists.
2555    pub exports: RefCell<Exports>,
2556    /// Top-level `FUNC` names pre-declared before lowering, so forward
2557    /// references resolve regardless of order. Separate from `funcs`
2558    /// frames so duplicate detection in `declare_func` stays intact;
2559    /// `visible_snapshot` unions this set.
2560    pub forward: RefCell<Vec<HashSet<String>>>,
2561    /// 1-based source line of the statement currently lowering (the
2562    /// innermost split statement; updated per statement by the body
2563    /// loops, read as the base for nested splits). Lets every error
2564    /// carry its statement's line without threading it through every
2565    /// header function by hand.
2566    pub current_line: RefCell<usize>,
2567}
2568
2569impl<'a> ParseCtx<'a> {
2570    /// Context with empty tables.
2571    pub fn empty(
2572        lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
2573        modules: &'a ModuleTable,
2574        reserved: &'a HashSet<String>,
2575    ) -> Self {
2576        Self {
2577            lower,
2578            modules,
2579            reserved,
2580            funcs: RefCell::new(vec![HashSet::new()]),
2581            imports: RefCell::new(vec![Vec::new()]),
2582            exports: RefCell::new(Exports::default()),
2583            forward: RefCell::new(vec![HashSet::new()]),
2584            current_line: RefCell::new(0),
2585        }
2586    }
2587
2588    /// Snapshot of everything visible at this point: `FUNC` names
2589    /// unioned across frames plus imports flattened outer-to-inner
2590    /// (unions `FUNC` names across frames, flattens imports outer-to-inner,
2591    /// dropping guardedness: call resolution only needs names).
2592    fn visible_snapshot(&self) -> (HashSet<String>, Vec<String>) {
2593        let mut funcs = HashSet::new();
2594        for scope in self.funcs.borrow().iter() {
2595            funcs.extend(scope.iter().cloned());
2596        }
2597        funcs.extend(
2598            self.forward
2599                .borrow()
2600                .iter()
2601                .flat_map(|frame| frame.iter().cloned()),
2602        );
2603        let mut imports = Vec::new();
2604        for frame in self.imports.borrow().iter() {
2605            for (module, _) in frame {
2606                if !imports.contains(module) {
2607                    imports.push(module.clone());
2608                }
2609            }
2610        }
2611        (funcs, imports)
2612    }
2613
2614    /// Record a `FUNC` name in the innermost scope. Returns false when
2615    /// already defined in that same scope (nested shadowing stays
2616    /// allowed (nested shadowing stays permitted).
2617    fn declare_func(&self, name: &str) -> bool {
2618        match self.funcs.borrow_mut().last_mut() {
2619            Some(current) => current.insert(name.to_string()),
2620            None => true,
2621        }
2622    }
2623
2624    /// Record `IMPORT`ed modules in the innermost frame (deduped,
2625    /// (deduped; the unknown-module table check lives at the import site),
2626    /// which lives at the import site. `guarded` marks guard-gated
2627    /// imports so the same-frame duplicate gate can tell a probable
2628    /// typo (unguarded, always collides) from a platform branch
2629    /// (guarded, disjointness decided by the static pass).
2630    fn import_into_frame(&self, modules: &[String], guarded: bool) {
2631        match self.imports.borrow_mut().last_mut() {
2632            Some(frame) => {
2633                for module in modules {
2634                    if !frame.iter().any(|(known, _)| known == module) {
2635                        frame.push((module.clone(), guarded));
2636                    }
2637                }
2638            }
2639            None => {
2640                self.imports
2641                    .borrow_mut()
2642                    .push(modules.iter().map(|m| (m.clone(), guarded)).collect());
2643            }
2644        }
2645    }
2646
2647    /// Guardedness of every visible entry for `alias`, outer to inner.
2648    /// Single owner for the duplicate-gate input, so the gate never
2649    /// restates the frame walk.
2650    fn import_guard_flags(&self, alias: &str) -> Vec<bool> {
2651        let mut out = Vec::new();
2652        for frame in self.imports.borrow().iter() {
2653            for (known, guarded) in frame {
2654                if known == alias {
2655                    out.push(*guarded);
2656                }
2657            }
2658        }
2659        out
2660    }
2661}
2662
2663fn resolve_name(ctx: &ParseCtx, stmt: usize, name: &str) -> Result<String, TokenError> {
2664    let (funcs, imports) = ctx.visible_snapshot();
2665    resolve_call_name(ctx.modules, &funcs, &imports, &lowering_ctx(stmt), name)
2666        .map_err(|e| lower_err(stmt, e))
2667}
2668
2669/// Pre-declare `FUNC` names before lowering, so forward references
2670/// resolve regardless of order. Only valid non-reserved headers hoist:
2671/// the head (`FUNC NAME`, `ASYNC FUNC NAME`), a parameter Paren group,
2672/// a `:` return-type shape (via the shared `parse_type_shape` owner),
2673/// and a trailing non-template Brace body. Malformed headers
2674/// (`FUNC FOO() ECHO hi`) and reserved names (`FUNC LEN`) stay silent
2675/// here so the main pass owns their diagnostics. Runs per scope: the
2676/// caller pre-declares each statement list into its own frame, so
2677/// nested blocks resolve forward without leaking outward.
2678fn predeclare_forward_funcs(stmts: &[Stmt], ctx: &ParseCtx) {
2679    // Guarded definitions hoist like unguarded ones: `parse_func_at`
2680    // registers the name in `ctx.funcs` unconditionally, so the
2681    // forward set must see the same statement regardless of its
2682    // guard, or forward calls to `[os:macos] FUNC FOO` would fail
2683    // while backward calls resolve.
2684    for stmt in stmts {
2685        let body = &stmt.body;
2686        // `ASYNC FUNC` carries the prefix; the shared header owner
2687        // takes `pos` at `FUNC` in both cases.
2688        let pos = match body.first().map(|t| &t.kind) {
2689            Some(TokKind::Word(w)) if w == KEYWORD_FUNC => 0,
2690            Some(TokKind::Word(w)) if w == KEYWORD_ASYNC => match body.get(1).map(|t| &t.kind) {
2691                Some(TokKind::Word(next)) if next == KEYWORD_FUNC => 1,
2692                _ => continue,
2693            },
2694            _ => continue,
2695        };
2696        // Header grammar lives in the single owner: parameter lists,
2697        // return types, and trailing tokens validate exactly like the
2698        // real path, so malformed headers never hoist. Diagnostics
2699        // drop here (silent skip); the main pass owns the error.
2700        let Ok(Some((header, _))) = parse_func_header(body, pos, 0, KEYWORD_FUNC) else {
2701            continue;
2702        };
2703        if ctx.reserved.contains(&header.name)
2704            || ctx.modules.reserved_base_names().contains(&header.name)
2705        {
2706            continue;
2707        }
2708        // Trailing tokens after the body block are malformed (the real
2709        // path consumes the header exactly, leaving them to fail as the
2710        // next element), so such headers never hoist into `forward`:
2711        // only gap trivia may follow.
2712        if body.len() != header.block + 1
2713            && !body[header.block + 1..]
2714                .iter()
2715                .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
2716        {
2717            continue;
2718        }
2719        if let Some(frame) = ctx.forward.borrow_mut().last_mut() {
2720            frame.insert(header.name.clone());
2721        }
2722    }
2723}
2724
2725/// Qualify bare placeholder calls in template text through the
2726/// shared static resolver, so `{{ NAME(args) }}` obeys exactly the
2727/// same scope rule as statement-position calls: `IMPORT [MOD]`
2728/// brings the names into scope, unimported names fail naming the
2729/// fix, ambiguity fails closed. Qualified (`MOD::FUNC`), variable
2730/// (`$x`, `bare_key`), env (`env:K`), and non-call keys pass
2731/// through untouched for the runtime to handle exactly as before;
2732/// only keys that are entirely one bare call shape are rewritten,
2733/// and only the head identifier's bytes change: surrounding
2734/// spacing and neighboring placeholders stay byte-identical, so
2735/// string payloads never lose formatting. Returns `None` when
2736/// nothing qualified, leaving the text completely untouched.
2737/// Shape detection is the shared `template::parse_placeholder_call`
2738/// grammar (also behind runtime dispatch), so parse and runtime
2739/// can never disagree on what counts as one call.
2740fn qualify_template_calls(
2741    text: &str,
2742    ctx: &ParseCtx,
2743    stmt: usize,
2744) -> Result<Option<String>, TokenError> {
2745    use crate::template::{TemplateSegment, TemplateSegments, parse_placeholder_call};
2746    let mut out = String::with_capacity(text.len());
2747    let mut changed = false;
2748    for segment in TemplateSegments::new(text) {
2749        match segment {
2750            TemplateSegment::Text(raw) => out.push_str(raw),
2751            TemplateSegment::Placeholder { key, raw } => {
2752                let call = match parse_placeholder_call(key) {
2753                    Some(call) if call.module.is_none() => call,
2754                    _ => {
2755                        out.push_str(raw);
2756                        continue;
2757                    }
2758                };
2759                let head = call.name;
2760                let resolved = resolve_name(ctx, stmt, head)?;
2761                if !resolved.contains(MODULE_SEPARATOR) {
2762                    // Unqualified resolutions (`INSPECT`) keep today's
2763                    // runtime handling untouched.
2764                    out.push_str(raw);
2765                    continue;
2766                }
2767                changed = true;
2768                // Splice only the head span: `name_span` is the byte
2769                // range of the head inside `key`, and `key` is the
2770                // trimmed interior of `raw`, so the raw offset is the
2771                // interior start plus the span start.
2772                let key_off = raw.find(key).expect("key is trimmed interior");
2773                let off = key_off + call.name_span.start;
2774                out.push_str(&raw[..off]);
2775                out.push_str(&resolved);
2776                out.push_str(&raw[off + head.len()..]);
2777            }
2778        }
2779    }
2780    if changed { Ok(Some(out)) } else { Ok(None) }
2781}
2782
2783/// Call shape at `pos`: UPPERCASE head plus joint `::` segments and a
2784/// paren group (joint iff required: statements forbid the gap;
2785/// expressions allow it).
2786/// Peek-only; anything else falls through (not a call shape).
2787/// Returns the dotted name and paren index.
2788fn call_shape_at(toks: &[Tok], pos: usize, joint_paren: bool) -> Option<(String, usize)> {
2789    let head = match toks.get(pos).map(|t| &t.kind) {
2790        Some(TokKind::Word(w))
2791            if !w.is_empty()
2792                && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
2793                && w.chars()
2794                    .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') =>
2795        {
2796            w.clone()
2797        }
2798        _ => return None,
2799    };
2800    let mut name = head;
2801    let mut p = pos + 1;
2802    loop {
2803        let colons = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')))
2804            && toks.get(p).is_some_and(|t| t.joint)
2805            && matches!(toks.get(p + 1).map(|t| &t.kind), Some(TokKind::Punct(':')))
2806            && toks.get(p + 1).is_some_and(|t| t.joint)
2807            && matches!(toks.get(p + 2).map(|t| &t.kind), Some(TokKind::Word(_)))
2808            && toks.get(p + 2).is_some_and(|t| t.joint);
2809        if !colons {
2810            break;
2811        }
2812        if let Some(TokKind::Word(seg)) = toks.get(p + 2).map(|t| &t.kind) {
2813            name.push_str(MODULE_SEPARATOR);
2814            name.push_str(seg);
2815        }
2816        p += 3;
2817    }
2818    match toks.get(p).map(|t| &t.kind) {
2819        Some(TokKind::Group {
2820            delim: GroupDelim::Paren,
2821            ..
2822        }) => {
2823            if joint_paren && !toks[p].joint {
2824                return None;
2825            }
2826            Some((name, p))
2827        }
2828        _ => None,
2829    }
2830}
2831
2832/// Call arguments over a paren group's contents: comma-separated full
2833/// expressions with `gap_nl` newlines at the edges (each arg rejects
2834/// a stray boundary).
2835fn parse_call_args(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Vec<Expr>, TokenError> {
2836    let mut cur = Cursor::expr(inner, stmt);
2837    cur.skip_gap_nl();
2838    if cur.done() {
2839        return Ok(vec![]);
2840    }
2841    let mut args = Vec::new();
2842    loop {
2843        let arg = parse_expr_or(&mut cur, ctx)?;
2844        reject_boundary(&lowering_ctx(stmt), &arg).map_err(|e| cur.err(e.to_string()))?;
2845        args.push(arg);
2846        cur.skip_gap_nl();
2847        if cur.eat_punct(',') {
2848            cur.skip_gap_nl();
2849            continue;
2850        }
2851        break;
2852    }
2853    if !cur.done() {
2854        return Err(trailing_items_error(
2855            &cur,
2856            ctx,
2857            stmt,
2858            "call arguments",
2859            "unexpected text in call",
2860        ));
2861    }
2862    Ok(args)
2863}
2864
2865/// Lower a call-shape to `Expr`: `INSPECT` keeps its variable
2866/// unevaluated (`INSPECT($var)` for `LET` and `$`-sigiled `CONST`
2867/// reads); everything else resolves statically through the shared
2868/// resolver.
2869fn parse_expr_call(
2870    name: String,
2871    inner: &[Tok],
2872    stmt: usize,
2873    ctx: &ParseCtx,
2874) -> Result<Expr, TokenError> {
2875    let args = parse_call_args(inner, stmt, ctx)?;
2876    if name == KEYWORD_INSPECT {
2877        let [arg] = args.as_slice() else {
2878            return Err(TokenError {
2879                diagnostic: None,
2880                hint: None,
2881                stmt,
2882                msg: format!(
2883                    "{KEYWORD_INSPECT} requires exactly one argument: {KEYWORD_INSPECT}($var)"
2884                ),
2885                line: 0,
2886                col: 0,
2887                kind: None,
2888            });
2889        };
2890        if let Expr::Var { name } = arg {
2891            return Ok(Expr::Inspect { name: name.clone() });
2892        }
2893        return Err(TokenError {
2894            diagnostic: None,
2895            hint: None,
2896            stmt,
2897            msg: format!("{KEYWORD_INSPECT} requires a $variable argument, found {arg:?}"),
2898            line: 0,
2899            col: 0,
2900            kind: None,
2901        });
2902    }
2903    let qualified = resolve_name(ctx, stmt, &name)?;
2904    Ok(Expr::Call {
2905        name: qualified,
2906        args,
2907    })
2908}
2909
2910/// Item rule selecting which `[...]` position the shared list core
2911/// parses for. The loop, comma rule, empty rule, trailing-content rule,
2912/// and newline tolerance are identical for every position (see
2913/// [`parse_bracket_list`]); only items and miss handling differ.
2914#[derive(Clone, Copy)]
2915enum BracketItems {
2916    /// Full checked expressions; a miss fails loudly.
2917    Expr,
2918    /// RUN-exec restricted atoms (brace groups try maps only, so blocks
2919    /// miss); a miss is shell fallthrough (`None`), never an error, so
2920    /// POSIX `[ -f ... ]` and malformed shapes stay shell.
2921    Exec,
2922}
2923
2924/// Trailing-content error for comma-separated positions (list
2925/// items, call arguments): stamps the offending token's position so
2926/// the caret names the line that actually fails instead of the
2927/// statement head, and names the likely missing comma when the
2928/// remainder parses as another item. Genuine trailing garbage keeps
2929/// the previous message verbatim. Error-path only, so the probe
2930/// parse costs nothing on success.
2931fn trailing_items_error(
2932    cur: &Cursor,
2933    ctx: &ParseCtx,
2934    stmt: usize,
2935    missing_what: &str,
2936    fallback: &str,
2937) -> TokenError {
2938    let (line, col) = cur
2939        .toks
2940        .get(cur.pos)
2941        .map(|t| (t.line, t.col))
2942        .unwrap_or((0, 0));
2943    let mut probe = Cursor::expr(&cur.toks[cur.pos.min(cur.toks.len())..], stmt);
2944    let msg = if parse_expr_checked(&mut probe, ctx).is_ok() {
2945        format!("missing comma between {missing_what}")
2946    } else {
2947        fallback.to_string()
2948    };
2949    TokenError {
2950        diagnostic: None,
2951        hint: None,
2952        stmt,
2953        line,
2954        col,
2955        msg,
2956        kind: None,
2957    }
2958}
2959
2960/// Shared comma-separated `[...]` core behind every bracket position.
2961/// There is exactly one list loop: one empty rule, one comma rule, one
2962/// trailing-content rule, newlines riding every gap. A bracket group
2963/// already lexes across lines, so rejecting newlines here only strands
2964/// the statement in raw-text rendering.
2965fn parse_bracket_list(
2966    inner: &[Tok],
2967    stmt: usize,
2968    ctx: &ParseCtx,
2969    items: BracketItems,
2970) -> Result<Option<Expr>, TokenError> {
2971    let mut cur = Cursor::expr(inner, stmt);
2972    cur.skip_gap_nl();
2973    if cur.done() {
2974        return Ok(Some(Expr::List(vec![])));
2975    }
2976    let mut list = Vec::new();
2977    loop {
2978        let item = match items {
2979            BracketItems::Expr => parse_expr_checked(&mut cur, ctx),
2980            BracketItems::Exec => match parse_run_exec_atom(&mut cur, ctx) {
2981                Ok(Some(atom)) => Ok(atom),
2982                // Not an exec shape at all: shell fallthrough.
2983                Ok(None) | Err(_) => return Ok(None),
2984            },
2985        };
2986        // Only expression positions can fail here: exec misses
2987        // return `None` above.
2988        let item = item?;
2989        match reject_boundary(&lowering_ctx(stmt), &item) {
2990            Ok(()) => {}
2991            Err(e) if matches!(items, BracketItems::Expr) => {
2992                return Err(cur.err(e.to_string()));
2993            }
2994            Err(_) => return Ok(None),
2995        }
2996        list.push(item);
2997        cur.skip_gap_nl();
2998        if cur.eat_punct(',') {
2999            cur.skip_gap_nl();
3000            continue;
3001        }
3002        break;
3003    }
3004    if !cur.done() {
3005        return match items {
3006            BracketItems::Expr => Err(trailing_items_error(
3007                &cur,
3008                ctx,
3009                stmt,
3010                "list items",
3011                "unexpected text in list",
3012            )),
3013            BracketItems::Exec => Ok(None),
3014        };
3015    }
3016    Ok(Some(Expr::List(list)))
3017}
3018
3019/// RUN exec-form list: the shared bracket core in `Exec` mode (atoms
3020/// only, except parenthesized/calls/lists/maps which recurse fully).
3021/// Anything that is not a clean comma-separated list misses the whole
3022/// exec shape (`None`): the grammar falls through to the shell path,
3023/// which reads the bracket literally and lets the shared lowering
3024/// decide (POSIX `[ -f ... ]` stays shell; non-map blocks and malformed
3025/// shapes behave exactly like the grammar's fallthrough).
3026/// (`instruction`), which reads the bracket literally and lets the
3027/// shared lowering decide (POSIX `[ -f ... ]` stays shell, malformed
3028/// shapes fail there exactly like the grammar). Only the
3029/// joint-bracket gate stays a hard error (it precedes this function).
3030fn parse_run_exec_list(
3031    inner: &[Tok],
3032    stmt: usize,
3033    ctx: &ParseCtx,
3034) -> Result<Option<Expr>, TokenError> {
3035    parse_bracket_list(inner, stmt, ctx, BracketItems::Exec)
3036}
3037
3038/// One RUN-exec item: brace groups try maps only (blocks miss);
3039/// everything else parses as a full atom (nested lists and map
3040/// values still admit blocks, like the grammar).
3041fn parse_run_exec_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Option<Expr>, TokenError> {
3042    if matches!(
3043        cur.toks.get(cur.pos).map(|t| &t.kind),
3044        Some(TokKind::Group {
3045            delim: GroupDelim::Brace,
3046            ..
3047        })
3048    ) {
3049        let inner = match &cur.toks[cur.pos].kind {
3050            TokKind::Group { inner, .. } => inner.clone(),
3051            _ => unreachable!(),
3052        };
3053        return match parse_map_literal(&inner, cur.stmt, ctx) {
3054            Ok(map) => {
3055                cur.pos += 1;
3056                Ok(Some(map))
3057            }
3058            Err(_) => Ok(None),
3059        };
3060    }
3061    parse_expr_atom(cur, ctx).map(Some)
3062}
3063
3064// ---- Single-command wrappers + AWAIT/CANCEL ----
3065// Wrappers parse through the shared validators (`check_tty_wrapping`,
3066// capture rejects, isolated rewrite, nesting reject, binding merge,
3067// guard `and`) promoted verbatim to `commands.rs`; only the
3068// token-level shape classifiers (duration gate, binding splitter,
3069// await/cancel shapes, block-vs-template) are v2-native. Statements
3070// lower to step VECTORS: structural pairs (calls, RUN-exec,
3071// await/cancel, wrapper blocks) end mid-line and trailing elements
3072// form following steps, exactly like the grammar's `element*`.
3073//
3074// Deferred: block STATEMENTS (slice 5: top-level `IF`/`FOR`/`WHILE`
3075// bodies, guard blocks, `REMOTE`, directives).
3076
3077/// Static duration shape mirror (`timeout_literal`, atomic): ASCII
3078/// digits plus one optional unit, full-match only. Anything else
3079/// (`10ss`, `banana`, `-5s`) misses the wrapper shape and falls back
3080/// to the generic instruction path, which fails in lowering exactly
3081/// like the grammar's committed `instruction`.
3082fn is_timeout_literal(text: &str) -> bool {
3083    let digits = text.len() - text.trim_start_matches(|c: char| c.is_ascii_digit()).len();
3084    if digits == 0 {
3085        return false;
3086    }
3087    matches!(&text[digits..], "" | "ms" | "s" | "m" | "h")
3088}
3089
3090/// Template-brace test: a brace group whose first inner token opens
3091/// another brace (`{{...}}`); anything else braced is a block body.
3092/// Same shape the arg engine uses; single source from here.
3093fn is_template_brace(tok: &Tok) -> bool {
3094    matches!(
3095        &tok.kind,
3096        TokKind::Group {
3097            delim: GroupDelim::Brace,
3098            inner,
3099            ..
3100        } if matches!(
3101            inner.first().map(|t| &t.kind),
3102            Some(TokKind::Group {
3103                delim: GroupDelim::Brace,
3104                ..
3105            })
3106        )
3107    )
3108}
3109
3110/// Parse one TIMEOUT duration unit at `pos` (the token after the
3111/// head, gapped like the grammar's `sep`). Returns the arg and
3112/// tokens consumed, or `None` on shape miss (caller falls back to
3113/// generic, which fails in lowering). Static
3114/// literals validate now through the shared Duration check
3115/// (`TIMEOUT 0s` fails here, probed); dynamics defer to runtime.
3116fn parse_timeout_duration_at(
3117    toks: &[Tok],
3118    pos: usize,
3119    stmt: usize,
3120) -> Result<Option<(Arg, usize)>, TokenError> {
3121    let Some(head) = toks.get(pos) else {
3122        return Ok(None);
3123    };
3124    if head.joint {
3125        return Ok(None);
3126    }
3127    let arg = match &head.kind {
3128        TokKind::Word(w) if is_timeout_literal(w) => Arg::String(w.clone(), false),
3129        TokKind::Punct(VAR_SIGIL_CHAR) => match toks.get(pos + 1) {
3130            Some(var) if var.joint && matches!(&var.kind, TokKind::Word(w) if is_ident_word(w)) => {
3131                match &var.kind {
3132                    TokKind::Word(w) => Arg::Expr(Expr::Var { name: w.clone() }),
3133                    _ => unreachable!(),
3134                }
3135            }
3136            _ => return Ok(None),
3137        },
3138        TokKind::Str { text, .. } => Arg::String(text.clone(), true),
3139        TokKind::BlockStr(full) => Arg::String(crate::command::lower_block_string(full), true),
3140        TokKind::Group {
3141            delim: GroupDelim::Brace,
3142            inner,
3143            open_joint,
3144            close_joint,
3145        } if is_template_brace(&toks[pos]) => Arg::String(
3146            render_group('{', '}', inner, *open_joint, *close_joint),
3147            false,
3148        ),
3149        _ => return Ok(None),
3150    };
3151    let used = match &head.kind {
3152        TokKind::Punct(VAR_SIGIL_CHAR) => 2,
3153        _ => 1,
3154    };
3155    ArgType::Duration.check_arg(&arg).map_err(|e| TokenError {
3156        hint: None,
3157        stmt,
3158        msg: e.to_string(),
3159        line: 0,
3160        col: 0,
3161        kind: None,
3162        diagnostic: Some(Box::new(e)),
3163    })?;
3164    Ok(Some((arg, used)))
3165}
3166
3167/// Parse `WITH_IO [...]` bindings over a bracket group's inner
3168/// tokens: comma-separated `stream[=$var]` / `rows|cols=int`
3169/// bindings, newlines skipping freely like `ws`. Returns `None` on
3170/// shape miss (empty flags, bad stream words, missing commas or
3171/// values: the caller falls back to generic, which fails in lowering).
3172/// Grammar-matched but invalid bindings (tty
3173/// values, out-of-range geometry) fail loudly, mirroring
3174/// `parse_io_binding`'s messages one by one.
3175fn parse_io_bindings(
3176    inner: &[Tok],
3177    stmt: usize,
3178    ctx: &ParseCtx,
3179) -> Result<Option<Vec<IoBinding>>, TokenError> {
3180    let mut parts: Vec<&[Tok]> = Vec::new();
3181    let mut start = 0;
3182    for (i, tok) in inner.iter().enumerate() {
3183        // Newlines skip freely like `ws` (filtered per part below);
3184        // commas split bindings; everything else is content.
3185        if matches!(&tok.kind, TokKind::Punct(',')) {
3186            parts.push(&inner[start..i]);
3187            start = i + 1;
3188        }
3189    }
3190    parts.push(&inner[start..]);
3191    // An empty flag list (`[]`, `[,]`) misses the shape.
3192    if parts.len() == 1 && parts[0].iter().all(|t| matches!(&t.kind, TokKind::Newline)) {
3193        return Ok(None);
3194    }
3195    let mut out = Vec::new();
3196    for part in parts {
3197        let part: Vec<&Tok> = part
3198            .iter()
3199            .filter(|t| !matches!(&t.kind, TokKind::Newline))
3200            .collect();
3201        match parse_io_binding_part(&part, stmt, ctx)? {
3202            Some(binding) => out.push(binding),
3203            None => return Ok(None),
3204        }
3205    }
3206    if out.is_empty() {
3207        return Ok(None);
3208    }
3209    Ok(Some(out))
3210}
3211
3212/// One `stream[=$var]` / `rows|cols=int` binding.
3213/// Gaps ride free around `=`/`,`/names like `ws?`; only `$`+name
3214/// stays gapless (atomic `dollar_ident`), covering `LET` and
3215/// `$`-sigiled `CONST` pipes alike. Streams and size names outside the grammar's words
3216/// miss the shape; a valued `tty` and out-of-range geometry fail
3217/// loudly with exact messages.
3218fn parse_io_binding_part(
3219    part: &[&Tok],
3220    stmt: usize,
3221    _ctx: &ParseCtx,
3222) -> Result<Option<IoBinding>, TokenError> {
3223    let fail = |msg: String| TokenError {
3224        diagnostic: None,
3225        hint: None,
3226        stmt,
3227        msg,
3228        line: 0,
3229        col: 0,
3230        kind: None,
3231    };
3232    let Some(first) = part.first() else {
3233        return Ok(None);
3234    };
3235    let TokKind::Word(stream) = &first.kind else {
3236        return Ok(None);
3237    };
3238    let is_stream = matches!(stream.as_str(), "stdin" | "stdout" | "stderr" | "tty");
3239    let is_size = matches!(stream.as_str(), "rows" | "cols");
3240    if !is_stream && !is_size {
3241        return Ok(None);
3242    }
3243    let rest = &part[1..];
3244    if rest.is_empty() {
3245        if is_size {
3246            // Bare `rows` misses `io_size` (`=` + digits required).
3247            return Ok(None);
3248        }
3249        return Ok(Some(IoBinding {
3250            stream: io_stream_of(stream),
3251            pipe: None,
3252        }));
3253    }
3254    // `= value` at any gap.
3255    if !matches!(rest.first().map(|t| &t.kind), Some(TokKind::Punct('='))) {
3256        return Ok(None);
3257    }
3258    let value = &rest[1..];
3259    if is_size {
3260        // Geometry: one all-digit word, 1-65535 (mirrors `parse_io_size`).
3261        if value.len() != 1 {
3262            return Ok(None);
3263        }
3264        let TokKind::Word(digits) = &value[0].kind else {
3265            return Ok(None);
3266        };
3267        if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
3268            return Ok(None);
3269        }
3270        let dim = digits
3271            .parse::<u64>()
3272            .ok()
3273            .filter(|v| (1..=u64::from(u16::MAX)).contains(v))
3274            .ok_or_else(|| {
3275                fail(
3276                    "WITH_IO terminal geometry needs a positive integer 1-65535 (e.g. `rows=40`)"
3277                        .to_string(),
3278                )
3279            })?;
3280        let dim = dim as u16;
3281        return Ok(Some(IoBinding {
3282            stream: if stream == "rows" {
3283                IoStream::Rows(dim)
3284            } else {
3285                IoStream::Cols(dim)
3286            },
3287            pipe: None,
3288        }));
3289    }
3290    // Stream pipe: `= $var` with a gapless name.
3291    if value.len() == 2
3292        && matches!(&value[0].kind, TokKind::Punct(VAR_SIGIL_CHAR))
3293        && let TokKind::Word(var) = &value[1].kind
3294        && value[1].joint
3295        && is_ident_word(var)
3296    {
3297        if stream == "tty" {
3298            return Err(fail(
3299                "WITH_IO [tty] takes no value: use bare `tty`, with `rows = <int>` / `cols = <int>` for geometry (e.g. `[tty, rows=40, cols=100]`)"
3300                    .to_string(),
3301            ));
3302        }
3303        return Ok(Some(IoBinding {
3304            stream: io_stream_of(stream),
3305            pipe: Some(crate::ast::PipeTarget::Var { name: var.clone() }),
3306        }));
3307    }
3308    Ok(None)
3309}
3310
3311/// Stream word to [`IoStream`]: only grammar words reach here, so
3312/// the mapping is total (mirrors `parse_io_stream`).
3313fn io_stream_of(name: &str) -> IoStream {
3314    match name {
3315        "stdin" => IoStream::Stdin,
3316        "stdout" => IoStream::Stdout,
3317        "stderr" => IoStream::Stderr,
3318        _ => IoStream::Tty,
3319    }
3320}
3321
3322/// `AWAIT`/`CANCEL $var` shape at `pos` (`$`-sigiled, covering `LET`
3323/// and `CONST` handles alike). A head without `$` misses
3324/// (`None`: generic fails it in lowering); once `$` commits, the
3325/// name must follow and parse errors stay loud. `var_joint`
3326/// enforces atomic adjacency inside compound parents.
3327fn parse_await_cancel_at(
3328    toks: &[Tok],
3329    pos: usize,
3330    stmt: usize,
3331    var_joint: bool,
3332    _ctx: &ParseCtx,
3333) -> Result<Option<(StepKind, usize)>, TokenError> {
3334    let head = match toks.get(pos).map(|t| &t.kind) {
3335        Some(TokKind::Word(w)) if w == KEYWORD_AWAIT || w == KEYWORD_CANCEL => w.clone(),
3336        _ => return Ok(None),
3337    };
3338    if matches!(
3339        toks.get(pos + 1).map(|t| &t.kind),
3340        Some(TokKind::Punct(VAR_SIGIL_CHAR))
3341    ) {
3342        let var = match toks.get(pos + 2) {
3343            Some(t)
3344                if matches!(&t.kind, TokKind::Word(w) if is_ident_word(w))
3345                    && (!var_joint || t.joint) =>
3346            {
3347                match &t.kind {
3348                    TokKind::Word(w) => w.clone(),
3349                    _ => unreachable!(),
3350                }
3351            }
3352            _ => {
3353                return Err(TokenError {
3354                    diagnostic: None,
3355                    hint: None,
3356                    stmt,
3357                    msg: format!("{head} requires a variable"),
3358                    line: 0,
3359                    col: 0,
3360                    kind: None,
3361                });
3362            }
3363        };
3364        return Ok(Some((
3365            if head == KEYWORD_AWAIT {
3366                StepKind::Await { var }
3367            } else {
3368                StepKind::Cancel { var }
3369            },
3370            3,
3371        )));
3372    }
3373    Ok(None)
3374}
3375
3376/// Wrapper strictness for one single-command inner: `AWAIT` parses
3377/// dedicated in `TIMEOUT`/`ISOLATED` inners but falls to generic in
3378/// `WITH_IO`/`ASYNC` inners (where lowering fails it, probed), and
3379/// `WITH_IO` recurses everywhere but directly under `ASYNC` (where
3380/// lowering fails it, probed). Shared predicates, never restated.
3381#[derive(Clone, Copy)]
3382struct InnerRules {
3383    allow_await: bool,
3384    allow_with_io: bool,
3385}
3386
3387/// Parse one single (non-block) inner command, returning the kind
3388/// and tokens consumed: dedicated await/cancel, while/remote, calls,
3389/// RUN-exec, nested wrappers, strict `INHERIT_ENV` (the caller
3390/// rejects the nesting or rewrites it), or the generic instruction
3391/// path (which consumes everything and fails unknown heads in
3392/// lowering, exactly like the grammar's committed `instruction`).
3393fn parse_single_inner(
3394    toks: &[Tok],
3395    pos: usize,
3396    stmt: usize,
3397    ctx: &ParseCtx,
3398    rules: InnerRules,
3399) -> Result<(StepKind, usize), TokenError> {
3400    let head_word = match toks.get(pos).map(|t| &t.kind) {
3401        Some(TokKind::Word(w)) => Some(w.clone()),
3402        _ => None,
3403    };
3404    // Nested `WHILE`/`REMOTE` recurse structurally (both ride every
3405    // inner-command set in the grammar); misses fall through to
3406    // generic below.
3407    if head_word.as_deref() == Some(KEYWORD_WHILE) {
3408        match parse_while_single(toks, pos, stmt, ctx) {
3409            Ok(Some((kind, used))) => return Ok((kind, used)),
3410            Ok(None) => {}
3411            Err(e) => return Err(e),
3412        }
3413    }
3414    if head_word.as_deref() == Some(KEYWORD_REMOTE) {
3415        match parse_remote_single(toks, pos, stmt, ctx) {
3416            Ok(Some((kind, used))) => return Ok((kind, used)),
3417            Ok(None) => {}
3418            Err(e) => return Err(e),
3419        }
3420    }
3421    // File `IMPORT "path" AS ALIAS` (#115) rides every single-inner
3422    // set (TIMEOUT/ISOLATED/WITH_IO/ASYNC, LET ASYNC): exactly one file
3423    // entry and no modules, else a hard error; shape misses fall through
3424    // to generic below, which fails them in lowering.
3425    if head_word.as_deref() == Some(KEYWORD_IMPORT)
3426        && let Some((path, alias, used)) = parse_single_file_import(toks, pos, stmt, ctx)?
3427    {
3428        return Ok((StepKind::ImportFile { path, alias }, used));
3429    }
3430    // Dedicated await/cancel first (await gated by parent); anything
3431    // they decline falls through to generic below.
3432    if head_word.as_deref() == Some(KEYWORD_AWAIT)
3433        && rules.allow_await
3434        && let Some(found) = parse_await_cancel_at(toks, pos, stmt, true, ctx)?
3435    {
3436        return Ok(found);
3437    }
3438    if head_word.as_deref() == Some(KEYWORD_CANCEL)
3439        && let Some(found) = parse_await_cancel_at(toks, pos, stmt, true, ctx)?
3440    {
3441        return Ok(found);
3442    }
3443    // Calls and RUN-exec end mid-run; the caller continues past them.
3444    if let Some((call_name, paren)) = call_shape_at(toks, pos, true) {
3445        let inner = match &toks[paren].kind {
3446            TokKind::Group { inner, .. } => inner.clone(),
3447            _ => unreachable!(),
3448        };
3449        let args = parse_call_args(&inner, stmt, ctx)?;
3450        if !call_name.contains(MODULE_SEPARATOR) {
3451            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
3452                .map_err(|e| lower_err(stmt, e))?;
3453        }
3454        let qualified = resolve_name(ctx, stmt, &call_name)?;
3455        return Ok((
3456            StepKind::Call {
3457                name: qualified,
3458                args,
3459            },
3460            paren + 1 - pos,
3461        ));
3462    }
3463    if head_word.as_deref() == Some(KEYWORD_RUN)
3464        && matches!(
3465            toks.get(pos + 1).map(|t| &t.kind),
3466            Some(TokKind::Group {
3467                delim: GroupDelim::Bracket,
3468                ..
3469            })
3470        )
3471    {
3472        // Gapped like the grammar's `sep`; a joint bracket is a
3473        // hard error, never a spliced arg (probed `RUN["a"]`).
3474        if toks[pos + 1].joint {
3475            return Err(TokenError {
3476                diagnostic: None,
3477                hint: None,
3478                stmt,
3479                msg: format!("{KEYWORD_RUN} [...] requires a gap after {KEYWORD_RUN}"),
3480                line: 0,
3481                col: 0,
3482                kind: None,
3483            });
3484        }
3485        let inner = match &toks[pos + 1].kind {
3486            TokKind::Group { inner, .. } => inner.clone(),
3487            _ => unreachable!(),
3488        };
3489        let exec_list = parse_run_exec_list(&inner, stmt, ctx)?;
3490        // Non-map blocks miss the exec shape (the grammar has no
3491        // `block` alternative here); fall through to generic below,
3492        // which reads the shell path literally.
3493        if let Some(list) = exec_list {
3494            let kind =
3495                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
3496            return Ok((kind, 2));
3497        }
3498    }
3499    // Nested wrappers recurse structurally; a `WITH_IO` directly
3500    // under `ASYNC` goes generic instead (lowering fails it, probed).
3501    match head_word.as_deref() {
3502        Some(KEYWORD_WITH_IO) if rules.allow_with_io => {
3503            match parse_with_io_single(toks, pos, stmt, ctx) {
3504                Ok(Some((kind, used))) => return Ok((kind, used)),
3505                Ok(None) => {}
3506                Err(e) => return Err(e),
3507            }
3508        }
3509        Some(KEYWORD_TIMEOUT) => match parse_timeout_single(toks, pos, stmt, ctx) {
3510            Ok(Some((kind, used))) => return Ok((kind, used)),
3511            Ok(None) => {}
3512            Err(e) => return Err(e),
3513        },
3514        Some(KEYWORD_ISOLATED) => match parse_isolated_single(toks, pos, stmt, ctx) {
3515            Ok(Some((kind, used))) => return Ok((kind, used)),
3516            Ok(None) => {}
3517            Err(e) => return Err(e),
3518        },
3519        Some(KEYWORD_ASYNC) => match parse_async_single(toks, pos, stmt, ctx) {
3520            Ok(Some((kind, used))) => return Ok((kind, used)),
3521            Ok(None) => {}
3522            Err(e) => return Err(e),
3523        },
3524        // `INHERIT_ENV [...]` parses strictly here (shared with
3525        // element level); the caller either rejects the nesting or
3526        // rewrites it, same as the shared validator. Trailing
3527        // elements loop on outside (a bad follower fails there, like
3528        // the grammar's line end).
3529        Some(KEYWORD_INHERIT_ENV) => {
3530            if let Some(found) = parse_inherit_env_at(toks, pos, stmt)? {
3531                return Ok(found);
3532            }
3533        }
3534        _ => {}
3535    }
3536    // Generic instruction: consumes the whole run; unknown heads
3537    // (LET/RETURN/FUNC/IF/...) fail in lowering.
3538    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
3539    Ok((kind, used))
3540}
3541
3542/// Parse an `INHERIT_ENV [...]` key list over a bracket group's
3543/// inner tokens, mirroring `inherit_list` strictly: comma-separated
3544/// keys, gaps/newlines only around keys and commas (never inside:
3545/// keys are atomic), each key a joint run validated against the
3546/// `guard_key_char` exclusions (`: = ! , | ( ) ] $`, plus the `//`
3547/// and `/*` comment opens). Groups and strings render raw (they read
3548/// as ordinary characters here); anything else misses
3549/// the shape (`None`: generic fails it in lowering).
3550/// Statement-level `INHERIT_ENV` stays generic (slice 5 directives);
3551/// this serves wrapper inners, where the nesting check (or the
3552/// isolated rewrite) consumes the result.
3553fn parse_inherit_keys(inner: &[Tok], stmt: usize) -> Result<Option<Vec<String>>, TokenError> {
3554    let mut parts: Vec<&[Tok]> = Vec::new();
3555    let mut start = 0;
3556    for (i, tok) in inner.iter().enumerate() {
3557        if matches!(&tok.kind, TokKind::Punct(',')) {
3558            parts.push(&inner[start..i]);
3559            start = i + 1;
3560        }
3561    }
3562    parts.push(&inner[start..]);
3563    let mut out = Vec::new();
3564    for part in parts {
3565        // Newlines skip at the edges only, like `ws?`.
3566        let mut part = part;
3567        while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
3568            part = &part[1..];
3569        }
3570        while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
3571            part = &part[..part.len() - 1];
3572        }
3573        let Some(key) = render_inherit_key(part, stmt)? else {
3574            return Ok(None);
3575        };
3576        out.push(key);
3577    }
3578    if out.is_empty() {
3579        return Ok(None);
3580    }
3581    Ok(Some(out))
3582}
3583
3584/// True when a `/` opens an inline comment: joint `//` or `/*`
3585/// (mirroring the grammar's comment literals, which need adjacency;
3586/// a gapped second char is payload text, like `a/ /b`). Used
3587/// everywhere `gap`/`gap_nl` admit comments.
3588fn is_comment_open(toks: &[Tok], pos: usize) -> bool {
3589    matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('/')))
3590        && matches!(
3591            toks.get(pos + 1).map(|t| (&t.kind, t.joint)),
3592            Some((TokKind::Punct('/'), true)) | Some((TokKind::Punct('*'), true))
3593        )
3594}
3595
3596/// Skip one inline comment starting at `pos` (which holds the `/`;
3597/// see [`is_comment_open`): `//` runs to a newline or the end,
3598/// `/* */` balances (nesting like the grammar) across newlines.
3599/// Returns the first position past the comment, or `None` when the
3600/// block never closes (the grammar fails unclosed comments too).
3601fn skip_inline_comment(toks: &[Tok], pos: usize) -> Option<usize> {
3602    let second = match toks.get(pos + 1).map(|t| &t.kind) {
3603        Some(TokKind::Punct('/')) => '/',
3604        Some(TokKind::Punct('*')) => '*',
3605        _ => return None,
3606    };
3607    if second == '/' {
3608        let mut p = pos + 2;
3609        while p < toks.len() && !matches!(&toks[p].kind, TokKind::Newline) {
3610            p += 1;
3611        }
3612        return Some(p);
3613    }
3614    let mut depth = 1usize;
3615    let mut p = pos + 2;
3616    while p < toks.len() {
3617        let is_open = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('/')))
3618            && matches!(
3619                toks.get(p + 1).map(|t| (&t.kind, t.joint)),
3620                Some((TokKind::Punct('*'), true))
3621            );
3622        let is_close = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('*')))
3623            && matches!(
3624                toks.get(p + 1).map(|t| (&t.kind, t.joint)),
3625                Some((TokKind::Punct('/'), true))
3626            );
3627        if is_open {
3628            depth += 1;
3629            p += 2;
3630        } else if is_close {
3631            depth -= 1;
3632            p += 2;
3633            if depth == 0 {
3634                return Some(p);
3635            }
3636        } else {
3637            p += 1;
3638        }
3639    }
3640    None
3641}
3642
3643/// Parse one inherit key: a maximal key-char run, then only
3644/// trailing gap content (`gap_nl`: newlines, comments, `#`). Key
3645/// chars exclude `: = ! , | ( ) ] $`, whitespace, and the `//` / `/*`
3646/// comment opens; a joint `#`
3647/// stays literal, a gapped one opens a trailing comment. Groups and
3648/// strings render raw for the exclusion check (they read as
3649/// ordinary characters here). `None` on shape miss.
3650fn render_inherit_key(part: &[Tok], stmt: usize) -> Result<Option<String>, TokenError> {
3651    let mut out = String::new();
3652    let mut i = 0;
3653    // Key run: words, puncts (except comment opens), groups and
3654    // strings rendered raw; ends at any gap, newline, comment, or
3655    // `//` / `/*` open.
3656    while i < part.len() {
3657        let tok = &part[i];
3658        if i > 0 && !tok.joint {
3659            break;
3660        }
3661        match &tok.kind {
3662            TokKind::Word(w) => {
3663                out.push_str(w);
3664                i += 1;
3665            }
3666            TokKind::Punct('/') if is_comment_open(part, i) => break,
3667            // `#` stays literal at key start (`#c`) or joint
3668            // (`a#b`); gapped mid-key it opens a trailing
3669            // comment like the grammar's `gap_nl`.
3670            TokKind::Punct('#') if tok.joint || out.is_empty() => {
3671                // `#` stays literal at key start (`#c`) or joint
3672                // (`a#b`).
3673                out.push('#');
3674                i += 1;
3675            }
3676            // Gapped mid-key `#` opens a trailing comment (handled
3677            // by the trailer check below, like `gap_nl`).
3678            TokKind::Punct('#') => break,
3679            TokKind::Punct(c) => {
3680                out.push(*c);
3681                i += 1;
3682            }
3683            TokKind::Semicolon => {
3684                out.push(';');
3685                i += 1;
3686            }
3687            TokKind::Str { text, quote } => {
3688                out.push(*quote);
3689                out.push_str(text);
3690                out.push(*quote);
3691                i += 1;
3692            }
3693            TokKind::BlockStr(full) => {
3694                out.push_str(full);
3695                i += 1;
3696            }
3697            TokKind::Group {
3698                delim,
3699                inner,
3700                open_joint,
3701                close_joint,
3702            } => {
3703                let (open, close) = match delim {
3704                    GroupDelim::Bracket => ('[', ']'),
3705                    GroupDelim::Paren => ('(', ')'),
3706                    GroupDelim::Brace => ('{', '}'),
3707                };
3708                out.push_str(&render_group(open, close, inner, *open_joint, *close_joint));
3709                i += 1;
3710            }
3711            // Newlines and comment markers end the key; the trailer
3712            // check below admits them.
3713            TokKind::Newline | TokKind::Comment(_) => break,
3714        }
3715    }
3716    if out.is_empty() {
3717        return Ok(None);
3718    }
3719    // Trailer: only gap content (`gap_nl`) may follow the key.
3720    let mut j = i;
3721    while j < part.len() {
3722        let tok = &part[j];
3723        match &tok.kind {
3724            TokKind::Newline | TokKind::Comment(_) => {
3725                j += 1;
3726            }
3727            TokKind::Punct('/') if is_comment_open(part, j) => {
3728                j = skip_inline_comment(part, j).ok_or(TokenError {
3729                    diagnostic: None,
3730                    hint: None,
3731                    stmt,
3732                    msg: "unclosed block comment".to_string(),
3733                    line: 0,
3734                    col: 0,
3735                    kind: None,
3736                })?;
3737            }
3738            TokKind::Punct('#') => {
3739                // `#` comment runs to a newline or the part end.
3740                while j < part.len() && !matches!(&part[j].kind, TokKind::Newline) {
3741                    j += 1;
3742                }
3743            }
3744            _ => return Ok(None),
3745        }
3746    }
3747    // `guard_key_char` exclusions: the single-char set plus the
3748    // comment opens (`//`, `/*`); lone `/` stays legal.
3749    if out.contains("//") || out.contains("/*") {
3750        return Ok(None);
3751    }
3752    if out.chars().any(|c| {
3753        matches!(
3754            c,
3755            ':' | '=' | '!' | ',' | '|' | '(' | ')' | ']' | VAR_SIGIL_CHAR
3756        )
3757    }) {
3758        return Ok(None);
3759    }
3760    Ok(Some(out))
3761}
3762
3763/// Strict `INHERIT_ENV [...]` at an element or single-inner
3764/// position: bracket riding gapped with valid keys yields the
3765/// directive (trailing elements loop on outside); anything else
3766/// misses (`None`) and generic fails it in lowering.
3767/// Serves both levels so keys stay exact everywhere; slice 5 adds
3768/// only the prelude-order validation.
3769fn parse_inherit_env_at(
3770    toks: &[Tok],
3771    pos: usize,
3772    stmt: usize,
3773) -> Result<Option<(StepKind, usize)>, TokenError> {
3774    // The bracket rides gapped (`sep`); anything else misses and
3775    // generic fails it in lowering.
3776    let bracket = match toks.get(pos + 1) {
3777        Some(t)
3778            if !t.joint
3779                && matches!(
3780                    &t.kind,
3781                    TokKind::Group {
3782                        delim: GroupDelim::Bracket,
3783                        ..
3784                    }
3785                ) =>
3786        {
3787            Some(t)
3788        }
3789        _ => None,
3790    };
3791    let Some(bracket) = bracket else {
3792        return Ok(None);
3793    };
3794    let inner = match &bracket.kind {
3795        TokKind::Group { inner, .. } => inner,
3796        _ => unreachable!(),
3797    };
3798    match parse_inherit_keys(inner, stmt)? {
3799        Some(keys) => Ok(Some((StepKind::InheritEnv { keys }, 2))),
3800        None => Ok(None),
3801    }
3802}
3803
3804/// Parse a brace block body into steps: statements split and lower
3805/// recursively, each keeping its own guard. `mark` selects scope
3806/// marking: top-level guard-block bodies mark (each nesting level
3807/// bumps first/last); wrapper bodies
3808/// (`IF`/`FOR`/`WHILE`/`FUNC`/`REMOTE`/wrappers/io-blocks) never mark
3809/// (block-element lowering pins 0/0).
3810fn parse_body_steps(
3811    inner: &[Tok],
3812    stmt: usize,
3813    ctx: &ParseCtx,
3814    mark: bool,
3815) -> Result<Vec<Step>, TokenError> {
3816    // One function/import scope per braced body (mirroring the
3817    // runtime push/pop boundary): same-block
3818    // `FUNC` redefinition errors, nested shadowing stays allowed.
3819    // Errors abort the whole parse (frames discarded with it), so no
3820    // exit runs on failure.
3821    ctx.funcs.borrow_mut().push(HashSet::new());
3822    ctx.imports.borrow_mut().push(Vec::new());
3823    ctx.forward.borrow_mut().push(HashSet::new());
3824    // Nested splits count lines from the enclosing statement's line
3825    // (headers are single-line, so the brace shares it). Save and
3826    // restore the discipline around the loop: sibling bodies after
3827    // this one must see the enclosing line, not the last inner one.
3828    // (On error the parse aborts and the context is discarded.)
3829    let saved = *ctx.current_line.borrow();
3830    let mut out = Vec::new();
3831    let stmts = split_statements(inner, saved)?;
3832    predeclare_forward_funcs(&stmts, ctx);
3833
3834    for s in &stmts {
3835        // The innermost statement owns error positions: record it for
3836        // nested splits and stamp failures that have none yet (deeper
3837        // frames stamp first, so this never overwrites real positions).
3838        *ctx.current_line.borrow_mut() = s.line;
3839        out.extend(
3840            lower_stmt_steps(s, stmt, ctx, true, mark).map_err(|e| stamp_pos(e, s.line, s.col))?,
3841        );
3842    }
3843    *ctx.current_line.borrow_mut() = saved;
3844    ctx.funcs.borrow_mut().pop();
3845    ctx.imports.borrow_mut().pop();
3846    ctx.forward.borrow_mut().pop();
3847    Ok(out)
3848}
3849
3850/// Single (non-block) `WITH_IO`: bindings plus an optional inner
3851/// command. `None` on shape miss (no/gapped bracket: generic fails
3852/// it in lowering). A brace in single-inner position is
3853/// the grammar's pending-guard error, never an io-block; a bare
3854/// bracket leaks the transient `WithIoBlock` into the body (probed).
3855fn parse_with_io_single(
3856    toks: &[Tok],
3857    pos: usize,
3858    stmt: usize,
3859    ctx: &ParseCtx,
3860) -> Result<Option<(StepKind, usize)>, TokenError> {
3861    let bracket = match toks.get(pos + 1) {
3862        // The bracket rides gapped (`sep`); anything else misses the
3863        // shape and generic fails it in lowering.
3864        Some(t)
3865            if !t.joint
3866                && matches!(
3867                    &t.kind,
3868                    TokKind::Group {
3869                        delim: GroupDelim::Bracket,
3870                        ..
3871                    }
3872                ) =>
3873        {
3874            t
3875        }
3876        _ => return Ok(None),
3877    };
3878    let inner = match &bracket.kind {
3879        TokKind::Group { inner, .. } => inner.clone(),
3880        _ => unreachable!(),
3881    };
3882    let bindings = match parse_io_bindings(&inner, stmt, ctx)? {
3883        Some(bindings) => bindings,
3884        None => return Ok(None),
3885    };
3886    let rest = pos + 2;
3887    // A brace directly after the bracket is the pending-guard error
3888    // in single-inner position (probed); templates fall to generic.
3889    if let Some(next) = toks.get(rest)
3890        && matches!(
3891            &next.kind,
3892            TokKind::Group {
3893                delim: GroupDelim::Brace,
3894                ..
3895            }
3896        )
3897        && !is_template_brace(next)
3898    {
3899        return Err(TokenError {
3900            diagnostic: None,
3901            hint: None,
3902            stmt,
3903            msg: "'{' without a pending guard".to_string(),
3904            line: 0,
3905            col: 0,
3906            kind: None,
3907        });
3908    }
3909    if rest >= toks.len() {
3910        // Bare bracket: the transient block node leaks into wrapper
3911        // bodies (statement level never reaches
3912        // here; the splitter holds it for `{`).
3913        return Ok(Some((StepKind::WithIoBlock { bindings }, 2)));
3914    }
3915    // A joint follower misses the inner `sep`: the bracket stands
3916    // bare (probed `TIMEOUT 10s WITH_IO [..]ECHO hi` yields the
3917    // transient node) and trailing elements loop on outside.
3918    if toks[rest].joint {
3919        return Ok(Some((StepKind::WithIoBlock { bindings }, 2)));
3920    }
3921    let (cmd, used) = parse_single_inner(
3922        toks,
3923        rest,
3924        stmt,
3925        ctx,
3926        InnerRules {
3927            allow_await: false,
3928            allow_with_io: true,
3929        },
3930    )?;
3931    let span = lowering_ctx(stmt);
3932    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| lower_err(stmt, e))?;
3933    let kind = StepKind::WithIo {
3934        bindings,
3935        cmd: Box::new(cmd),
3936    };
3937    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
3938    Ok(Some((kind, 2 + used)))
3939}
3940
3941/// Single (non-block) `TIMEOUT`: duration plus one inner command.
3942/// `None` on shape miss (bad duration, missing/joint inner: generic
3943/// fails it in lowering). Blocks parse inline; the body
3944/// holds one step for single inners.
3945fn parse_timeout_single(
3946    toks: &[Tok],
3947    pos: usize,
3948    stmt: usize,
3949    ctx: &ParseCtx,
3950) -> Result<Option<(StepKind, usize)>, TokenError> {
3951    let Some((duration, dused)) = parse_timeout_duration_at(toks, pos + 1, stmt)? else {
3952        return Ok(None);
3953    };
3954    let rest = pos + 1 + dused;
3955    let Some(next) = toks.get(rest) else {
3956        // `TIMEOUT 10s` alone is a generic instruction (lowering
3957        // fails it, probed), never a bare wrapper.
3958        return Ok(None);
3959    };
3960    if next.joint {
3961        return Ok(None);
3962    }
3963    let body = if matches!(
3964        &next.kind,
3965        TokKind::Group {
3966            delim: GroupDelim::Brace,
3967            ..
3968        }
3969    ) && !is_template_brace(next)
3970    {
3971        let inner = match &next.kind {
3972            TokKind::Group { inner, .. } => inner.clone(),
3973            _ => unreachable!(),
3974        };
3975        let steps = parse_body_steps(&inner, stmt, ctx, false)?;
3976        (steps, 1)
3977    } else {
3978        let (cmd, used) = parse_single_inner(
3979            toks,
3980            rest,
3981            stmt,
3982            ctx,
3983            InnerRules {
3984                allow_await: true,
3985                allow_with_io: true,
3986            },
3987        )?;
3988        (
3989            vec![Step {
3990                guard: None,
3991                kind: cmd,
3992                scope_enter: 0,
3993                scope_exit: 0,
3994                line: 0,
3995                col: 0,
3996            }],
3997            used,
3998        )
3999    };
4000    let kind = StepKind::Timeout {
4001        duration,
4002        body: body.0,
4003    };
4004    let span = lowering_ctx(stmt);
4005    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
4006    Ok(Some((kind, 1 + dused + body.1)))
4007}
4008
4009/// Single (non-block) `ISOLATED`: one inner command or block; the
4010/// body rewrites nested `INHERIT_ENV` through the shared pass.
4011/// `None` on shape miss (missing/joint inner: generic fails it).
4012fn parse_isolated_single(
4013    toks: &[Tok],
4014    pos: usize,
4015    stmt: usize,
4016    ctx: &ParseCtx,
4017) -> Result<Option<(StepKind, usize)>, TokenError> {
4018    let Some(next) = toks.get(pos + 1) else {
4019        return Ok(None);
4020    };
4021    if next.joint {
4022        return Ok(None);
4023    }
4024    let (mut body, used) = if matches!(
4025        &next.kind,
4026        TokKind::Group {
4027            delim: GroupDelim::Brace,
4028            ..
4029        }
4030    ) && !is_template_brace(next)
4031    {
4032        let inner = match &next.kind {
4033            TokKind::Group { inner, .. } => inner.clone(),
4034            _ => unreachable!(),
4035        };
4036        (parse_body_steps(&inner, stmt, ctx, false)?, 1)
4037    } else {
4038        let (cmd, used) = parse_single_inner(
4039            toks,
4040            pos + 1,
4041            stmt,
4042            ctx,
4043            InnerRules {
4044                allow_await: true,
4045                allow_with_io: true,
4046            },
4047        )?;
4048        (
4049            vec![Step {
4050                guard: None,
4051                kind: cmd,
4052                scope_enter: 0,
4053                scope_exit: 0,
4054                line: 0,
4055                col: 0,
4056            }],
4057            used,
4058        )
4059    };
4060    crate::commands::rewrite_isolated_inherit(&mut body);
4061    Ok(Some((StepKind::Isolated { body }, 1 + used)))
4062}
4063
4064/// `FAIL [<code>] [<message>] [{ <block> }]`: message and/or block
4065/// required, code optional. The trailing brace (when present and not
4066/// a `{{ }}` template) parses as a child-scope body that reads
4067/// caller locals; the remaining tokens lower as 0-2 plain args (no `KEY=VAL`). One arg
4068/// is the message unless it is a bare int literal, which is the
4069/// code (`FAIL 2` exits silently, `FAIL "2"` prints); two args are
4070/// code plus message with the code statically int-checked like
4071/// `EXIT`. `None` on shape miss (joint head, `KEY=VAL`, >2 args fall
4072/// to generic, which fails with the `FAIL` hint).
4073fn parse_fail_single(
4074    toks: &[Tok],
4075    pos: usize,
4076    stmt: usize,
4077    ctx: &ParseCtx,
4078) -> Result<Option<(StepKind, usize)>, TokenError> {
4079    let head_ok =
4080        matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FAIL);
4081    if !head_ok {
4082        return Ok(None);
4083    }
4084    let next_joint = toks.get(pos + 1).is_some_and(|t| t.joint);
4085    if next_joint {
4086        return Ok(None);
4087    }
4088    let end = toks.len();
4089    let mut arg_end = end;
4090    let mut body: Vec<Step> = Vec::new();
4091    // Brace presence is tracked apart from body length: `FAIL {}`
4092    // is a valid empty block, while a missing block leaves no
4093    // braces at all.
4094    let mut has_block = false;
4095    if let Some(last) = toks.last()
4096        && matches!(
4097            &last.kind,
4098            TokKind::Group {
4099                delim: GroupDelim::Brace,
4100                ..
4101            }
4102        )
4103        && !is_template_brace(last)
4104        && end > pos + 1
4105    {
4106        let inner = match &last.kind {
4107            TokKind::Group { inner, .. } => inner.clone(),
4108            _ => unreachable!(),
4109        };
4110        body = parse_body_steps(&inner, stmt, ctx, false)?;
4111        arg_end = end - 1;
4112        has_block = true;
4113    }
4114    let arg_toks = if arg_end > pos + 1 {
4115        &toks[pos + 1..arg_end]
4116    } else {
4117        &[]
4118    };
4119    if !arg_toks.is_empty() && arg_toks.first().is_some_and(|t| t.joint) {
4120        return Ok(None);
4121    }
4122    let (tokens, deferred) = build_arg_tokens(arg_toks, stmt, ctx)?;
4123    let mut args: Vec<Arg> = Vec::with_capacity(tokens.len());
4124    for token in tokens {
4125        match token {
4126            InsToken::Pos(arg) => args.push(arg),
4127            InsToken::Assign(..) => return Ok(None),
4128        }
4129    }
4130    if args.len() > 2 {
4131        return Ok(None);
4132    }
4133    if args.is_empty() && !has_block {
4134        return Ok(None);
4135    }
4136    if let Some(err) = deferred {
4137        return Err(err);
4138    }
4139    let (code, message) = match args.len() {
4140        0 => (None, None),
4141        1 => {
4142            let mut it = args.into_iter();
4143            let only = it.next();
4144            // A lone bare int is a silent code (`FAIL 2`); anything
4145            // else (quoted text, `$var`, templates) is the message.
4146            // Quoting decides: `FAIL "2"` prints `2` and exits 1.
4147            match &only {
4148                Some(Arg::String(s, false))
4149                    if crate::command::strip_digit_separators(s)
4150                        .parse::<i64>()
4151                        .is_ok() =>
4152                {
4153                    (only, None)
4154                }
4155                _ => (None, only),
4156            }
4157        }
4158        _ => {
4159            let mut it = args.into_iter();
4160            let code = it.next();
4161            let message = it.next();
4162            // The code position is statically int-checked like
4163            // `EXIT`: a non-int literal fails here, while `$var`
4164            // and templates defer to runtime resolution.
4165            if let Some(arg) = &code {
4166                crate::command::ArgType::Int
4167                    .check_arg(arg)
4168                    .map_err(|e| TokenError {
4169                        hint: None,
4170                        stmt,
4171                        msg: e.to_string(),
4172                        line: 0,
4173                        col: 0,
4174                        kind: Some(ParseErrorKind::Validation {
4175                            command: KEYWORD_FAIL.to_string(),
4176                        }),
4177                        diagnostic: Some(Box::new(e)),
4178                    })?;
4179            }
4180            (code, message)
4181        }
4182    };
4183    crate::commands::rewrite_isolated_inherit(&mut body);
4184    let kind = StepKind::Fail {
4185        code,
4186        message,
4187        body,
4188    };
4189    let span = lowering_ctx(stmt);
4190    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
4191    Ok(Some((kind, end - pos)))
4192}
4193
4194/// Single (non-block) `ASYNC`: one inner command or block (blocks
4195/// admit a joint brace, like `async_statement_block`'s `sep?`).
4196/// Top-level `WITH_IO` steps fail through the shared reject; the
4197/// `LET` path never scans (probed: it accepts). `None` on shape
4198/// miss (missing/joint-single inner: generic fails it).
4199fn parse_async_single(
4200    toks: &[Tok],
4201    pos: usize,
4202    stmt: usize,
4203    ctx: &ParseCtx,
4204) -> Result<Option<(StepKind, usize)>, TokenError> {
4205    let Some(next) = toks.get(pos + 1) else {
4206        return Ok(None);
4207    };
4208    // Block form admits a joint brace (`ASYNC{...}`, probed); the
4209    // single form needs its `sep`.
4210    if matches!(
4211        &next.kind,
4212        TokKind::Group {
4213            delim: GroupDelim::Brace,
4214            ..
4215        }
4216    ) && !is_template_brace(next)
4217    {
4218        let inner = match &next.kind {
4219            TokKind::Group { inner, .. } => inner.clone(),
4220            _ => unreachable!(),
4221        };
4222        let body = parse_body_steps(&inner, stmt, ctx, false)?;
4223        let span = lowering_ctx(stmt);
4224        crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| lower_err(stmt, e))?;
4225        let kind = StepKind::AsyncBlock { body };
4226        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
4227        return Ok(Some((kind, 2)));
4228    }
4229    if next.joint {
4230        return Ok(None);
4231    }
4232    let (cmd, used) = parse_single_inner(
4233        toks,
4234        pos + 1,
4235        stmt,
4236        ctx,
4237        InnerRules {
4238            allow_await: false,
4239            allow_with_io: false,
4240        },
4241    )?;
4242    let body = vec![Step {
4243        guard: None,
4244        kind: cmd,
4245        scope_enter: 0,
4246        scope_exit: 0,
4247        line: 0,
4248        col: 0,
4249    }];
4250    let span = lowering_ctx(stmt);
4251    crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| lower_err(stmt, e))?;
4252    let kind = StepKind::AsyncBlock { body };
4253    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
4254    Ok(Some((kind, 1 + used)))
4255}
4256
4257// ---- Block statements, directives, REMOTE ----
4258// `IF`/`FOR`/`WHILE`/`FUNC` parse their headers token-natively with
4259// miss-to-generic fallback (the grammar's committed `instruction`
4260// path); bodies lower recursively with pushed scopes. `TYPE` builds
4261// aliases through a maximal type-shape match; `IMPORT`/`EXPORT` are
4262// zero-step frame/table directives; `REMOTE` validates targets,
4263// bindings, bodies, and outer-call containment through the shared
4264// validators. Guard blocks fold guards with scope markers at top
4265// level and mirror the nested quirk formula in bodies. A whole-script
4266// post-pass runs the shared validations (prelude order, COPY
4267// placement, EXPORT membership).
4268
4269/// Uppercase identifier mirror (`func_ident`, `type_name`,
4270/// `import_module`): ASCII upper start, upper/digit/`_` rest.
4271fn is_upper_ident(w: &str) -> bool {
4272    !w.is_empty()
4273        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
4274        && w.chars()
4275            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
4276}
4277
4278/// Lowercase identifier mirror (`field_name`): ASCII lower start,
4279/// lower/digit/`_` rest.
4280fn is_lower_ident(w: &str) -> bool {
4281    !w.is_empty()
4282        && w.chars().next().is_some_and(|c| c.is_ascii_lowercase())
4283        && w.chars()
4284            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
4285}
4286
4287/// `$name` with gapless adjacency (atomic `dollar_ident`); `None` on
4288/// shape miss (the caller falls back to generic, which fails in
4289/// lowering like the grammar's committed `instruction`).
4290fn peek_dollar_var(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
4291    match (toks.get(pos), toks.get(pos + 1)) {
4292        (Some(dollar), Some(name))
4293            if matches!(&dollar.kind, TokKind::Punct(VAR_SIGIL_CHAR))
4294                && name.joint
4295                && matches!(&name.kind, TokKind::Word(w) if is_ident_word(w)) =>
4296        {
4297            match &name.kind {
4298                TokKind::Word(w) => Some((w.clone(), 2)),
4299                _ => unreachable!(),
4300            }
4301        }
4302        _ => None,
4303    }
4304}
4305
4306/// Skip statement-level newlines (multi-line `<...>` shapes ride
4307/// them into the body) before the next type token. Narrower than
4308/// `gap_nl` on purpose: comments keep failing here exactly like
4309/// single-line shapes, so only the separator moves.
4310fn skip_type_nl(toks: &[Tok], mut p: usize) -> usize {
4311    while matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Newline)) {
4312        p += 1;
4313    }
4314    p
4315}
4316
4317/// Maximal `type_tag` match over toks (non-atomic: gaps free
4318/// everywhere): atoms with `<>` args, `|` unions, `name?:` fields,
4319/// and one `= literal` default tail per field.
4320/// Returns the exclusive end index, or `None` on shape miss.
4321fn parse_type_shape(toks: &[Tok], pos: usize) -> Option<usize> {
4322    let mut p = parse_type_atom(toks, skip_type_nl(toks, pos))?;
4323    loop {
4324        let q = skip_type_nl(toks, p);
4325        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('|'))) {
4326            return Some(p);
4327        }
4328        p = parse_type_atom(toks, skip_type_nl(toks, q + 1))?;
4329    }
4330}
4331
4332fn parse_type_atom(toks: &[Tok], pos: usize) -> Option<usize> {
4333    let pos = skip_type_nl(toks, pos);
4334    match toks.get(pos).map(|t| &t.kind) {
4335        Some(TokKind::Word(w)) if is_upper_ident(w) => {}
4336        _ => return None,
4337    }
4338    let mut p = skip_type_nl(toks, pos + 1);
4339    // Qualified `ALIAS::NAME`: two colons plus a second uppercase word.
4340    // The renderer joins tokens joint-aware so the spelling keeps `::`.
4341    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')))
4342        && matches!(toks.get(p + 1).map(|t| &t.kind), Some(TokKind::Punct(':')))
4343        && matches!(toks.get(p + 2).map(|t| &t.kind), Some(TokKind::Word(w)) if is_upper_ident(w))
4344    {
4345        p = skip_type_nl(toks, p + 3);
4346    }
4347    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('<'))) {
4348        p = parse_type_args(toks, skip_type_nl(toks, p + 1))?;
4349        p = skip_type_nl(toks, p);
4350        if !matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('>'))) {
4351            return None;
4352        }
4353        p += 1;
4354    }
4355    Some(p)
4356}
4357
4358fn parse_type_args(toks: &[Tok], pos: usize) -> Option<usize> {
4359    let mut p = parse_type_field(toks, skip_type_nl(toks, pos))?;
4360    loop {
4361        let q = skip_type_nl(toks, p);
4362        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(','))) {
4363            return Some(p);
4364        }
4365        p = parse_type_field(toks, skip_type_nl(toks, q + 1))?;
4366    }
4367}
4368
4369fn parse_type_field(toks: &[Tok], pos: usize) -> Option<usize> {
4370    let mut p = skip_type_nl(toks, pos);
4371    // Optional `name?:` prefix (lowercase names only, like the
4372    // grammar's `field_name`).
4373    if let Some(TokKind::Word(w)) = toks.get(p).map(|t| &t.kind)
4374        && is_lower_ident(w)
4375    {
4376        let mut q = skip_type_nl(toks, p + 1);
4377        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('?'))) {
4378            q = skip_type_nl(toks, q + 1);
4379        }
4380        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4381            p = skip_type_nl(toks, q + 1);
4382        }
4383    }
4384    let mut p = parse_type_shape(toks, p)?;
4385    // Optional `ALIAS name` clauses (#310.5): one alternate CLI spelling
4386    // per field, but the matcher covers every consecutive clause so the
4387    // spelling parser owns arity (second ALIAS fails there naming both
4388    // names, never here as shape miss). The renderer carries raw tokens
4389    // through. Order is fixed: `TYPE [ALIAS alias]* [= default]`.
4390    loop {
4391        let q = skip_type_nl(toks, p);
4392        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Word(w)) if w == crate::tag::ALIAS_KEYWORD)
4393        {
4394            break;
4395        }
4396        p = skip_type_nl(toks, q + 1);
4397        if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Word(_))) {
4398            p = skip_type_nl(toks, p + 1);
4399        } else {
4400            break;
4401        }
4402    }
4403    // Optional `= ...` default tail: consume to the next field
4404    // delimiter (`,`, `>`, `|` at angle depth zero), tracking `<>`
4405    // so nested shapes ride along. Any spacing, any tokens:
4406    // literals, `$vars`, `env:` reads, calls. The spelling parser
4407    // owns literal validation, so non-literals fail there naming
4408    // the alias instead of missing here as unknown-command noise.
4409    let q = skip_type_nl(toks, p);
4410    if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('=')))
4411        && !matches!(toks.get(q + 1).map(|t| &t.kind), Some(TokKind::Punct('=')))
4412    {
4413        let mut r = skip_type_nl(toks, q + 1);
4414        let mut depth = 0usize;
4415        loop {
4416            match toks.get(r).map(|t| &t.kind) {
4417                Some(TokKind::Punct('<')) => {
4418                    depth += 1;
4419                    r = skip_type_nl(toks, r + 1);
4420                }
4421                Some(TokKind::Punct('>')) => {
4422                    if depth == 0 {
4423                        break;
4424                    }
4425                    depth -= 1;
4426                    r = skip_type_nl(toks, r + 1);
4427                }
4428                Some(TokKind::Punct(',' | '|')) if depth == 0 => break,
4429                Some(_) => {
4430                    r += 1;
4431                }
4432                None => break,
4433            }
4434        }
4435        p = r;
4436    }
4437    Some(p)
4438}
4439
4440/// Single (non-block) `IF`: condition plus then-block with an
4441/// opportunistic `ELSE` chain (a malformed `ELSE` stays for the
4442/// element loop, which fails it in lowering exactly like the
4443/// grammar). `None` on shape miss (missing/joint-agnostic block or
4444/// unclassified bad condition: generic fails it); classified
4445/// expression failures (unknown/ambiguous callees) and inline-block
4446/// failures propagate (blocks lower here, so their errors surface
4447/// directly).
4448fn parse_if_at(
4449    toks: &[Tok],
4450    pos: usize,
4451    stmt: usize,
4452    ctx: &ParseCtx,
4453) -> Result<Option<(StepKind, usize)>, TokenError> {
4454    // Condition entry skips leading gap comments (`IF` uses `gap`).
4455    let mut lead = Cursor::expr(&toks[pos + 1..], stmt);
4456    lead.skip_gap();
4457    let mut cur = Cursor::expr(&toks[pos + 1 + lead.pos..], stmt);
4458    let cond = match parse_expr_checked(&mut cur, ctx) {
4459        Ok(expr) => expr,
4460        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4461        // Classified failures (unknown/ambiguous callees) name the
4462        // culprit instead of missing to the generic IF hint: the head
4463        // is unambiguously `IF`, so there is no alternative parse.
4464        Err(e) if e.kind.is_some() => return Err(e),
4465        Err(_) => return Ok(None),
4466    };
4467    let cond_end = pos + 1 + lead.pos + cur.pos;
4468    // Then-block: any gap (`gap` zero-width), never a template.
4469    let then_brace = match toks.get(cond_end) {
4470        Some(t)
4471            if matches!(
4472                &t.kind,
4473                TokKind::Group {
4474                    delim: GroupDelim::Brace,
4475                    ..
4476                }
4477            ) && !is_template_brace(t) =>
4478        {
4479            t
4480        }
4481        _ => return Ok(None),
4482    };
4483    let then_inner = match &then_brace.kind {
4484        TokKind::Group { inner, .. } => inner.clone(),
4485        _ => unreachable!(),
4486    };
4487    let then_body = parse_body_steps(&then_inner, stmt, ctx, false)?;
4488    let mut p = cond_end + 1;
4489    // Gap comments between the blocks and `ELSE` vanish (merge
4490    // junctions contribute newlines, crossed like `blank*`).
4491    {
4492        let mut gcur = Cursor::expr(&toks[p..], stmt);
4493        gcur.skip_gap_nl();
4494        p += gcur.pos;
4495    }
4496    let mut else_ifs = Vec::new();
4497    let mut else_body = None;
4498    loop {
4499        // `ELSE IF cond block`: any gaps (non-atomic chain).
4500        let is_else_if = matches!(
4501            toks.get(p).map(|t| &t.kind),
4502            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4503        ) && matches!(
4504            toks.get(p + 1).map(|t| &t.kind),
4505            Some(TokKind::Word(w)) if w == KEYWORD_IF
4506        );
4507        if is_else_if {
4508            let mut ecur = Cursor::expr(&toks[p + 2..], stmt);
4509            ecur.skip_gap();
4510            let econd = match parse_expr_checked(&mut ecur, ctx) {
4511                Ok(expr) => expr,
4512                Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4513                // Same classified-error rule as the `IF` head above:
4514                // an `ELSE IF` with a resolvable-but-unknown callee
4515                // names it instead of silently dropping the branch.
4516                Err(e) if e.kind.is_some() => return Err(e),
4517                Err(_) => break,
4518            };
4519            let ebrace = p + 2 + ecur.pos;
4520            let eblock_ok = matches!(
4521                toks.get(ebrace).map(|t| &t.kind),
4522                Some(TokKind::Group {
4523                    delim: GroupDelim::Brace,
4524                    ..
4525                })
4526            ) && toks.get(ebrace).is_some_and(|t| !is_template_brace(t));
4527            if !eblock_ok {
4528                break;
4529            }
4530            let einner = match &toks[ebrace].kind {
4531                TokKind::Group { inner, .. } => inner.clone(),
4532                _ => unreachable!(),
4533            };
4534            let ebody = parse_body_steps(&einner, stmt, ctx, false)?;
4535            else_ifs.push((Box::new(econd), ebody));
4536            p = ebrace + 1;
4537            // Gap comments before a further `ELSE` vanish too
4538            // (merge junctions contribute newlines).
4539            {
4540                let mut gcur = Cursor::expr(&toks[p..], stmt);
4541                gcur.skip_gap_nl();
4542                p += gcur.pos;
4543            }
4544            continue;
4545        }
4546        // `ELSE block`: same opportunism (a bare `ELSE` stays for
4547        // the loop, failing in lowering like the grammar).
4548        let is_else = matches!(
4549            toks.get(p).map(|t| &t.kind),
4550            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4551        ) && matches!(
4552            toks.get(p + 1).map(|t| &t.kind),
4553            Some(TokKind::Group {
4554                delim: GroupDelim::Brace,
4555                ..
4556            })
4557        ) && toks.get(p + 1).is_some_and(|t| !is_template_brace(t));
4558        if !is_else {
4559            break;
4560        }
4561        let einner = match &toks[p + 1].kind {
4562            TokKind::Group { inner, .. } => inner.clone(),
4563            _ => unreachable!(),
4564        };
4565        else_body = Some(parse_body_steps(&einner, stmt, ctx, false)?);
4566        p += 2;
4567        break;
4568    }
4569    let kind = StepKind::If {
4570        cond: Box::new(cond),
4571        then_body,
4572        else_ifs,
4573        else_body,
4574    };
4575    Ok(Some((kind, p - pos)))
4576}
4577
4578/// Parse one `CASE` value list: comma-separated expressions up to (not
4579/// including) the arm body brace. Groups are atomic tokens, so commas
4580/// inside calls, lists, and maps never split. Returns the values plus
4581/// the token count consumed past the `CASE` word.
4582fn parse_case_values(
4583    toks: &[Tok],
4584    stmt: usize,
4585    ctx: &ParseCtx,
4586) -> Result<(Vec<Expr>, usize), TokenError> {
4587    let mut values = Vec::new();
4588    let mut p = 0;
4589    loop {
4590        let mut gcur = Cursor::expr(&toks[p..], stmt);
4591        gcur.skip_gap_nl();
4592        let start = p + gcur.pos;
4593        let mut vcur = Cursor::expr(&toks[start..], stmt);
4594        let value = match parse_expr_checked(&mut vcur, ctx) {
4595            Ok(expr) => expr,
4596            Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4597            Err(e) => return Err(e),
4598        };
4599        // A `{ ... }` block is never a case value: without this, a
4600        // missing `CASE` value consumes the arm body as a block
4601        // expression and fails downstream instead of naming the miss.
4602        if matches!(value, Expr::Block(_)) {
4603            return Err(TokenError {
4604                diagnostic: None,
4605                hint: None,
4606                stmt,
4607                line: 0,
4608                col: 0,
4609                msg: format!(
4610                    "{KEYWORD_SWITCH} {KEYWORD_CASE} requires a value or condition before '{{'"
4611                ),
4612                kind: None,
4613            });
4614        }
4615        values.push(value);
4616        p = start + vcur.pos;
4617        let mut gcur = Cursor::expr(&toks[p..], stmt);
4618        gcur.skip_gap_nl();
4619        p += gcur.pos;
4620        if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(','))) {
4621            p += 1;
4622            continue;
4623        }
4624        break;
4625    }
4626    Ok((values, p))
4627}
4628
4629/// Parsed `SWITCH` arms: one value list plus body per `CASE`, with
4630/// an optional trailing `DEFAULT` body.
4631type SwitchArms = (Vec<(Vec<Expr>, Vec<Step>)>, Option<Vec<Step>>);
4632
4633/// Parse the arms inside a `SWITCH` body brace: `CASE <values> { ... }`
4634/// arms plus an optional trailing `DEFAULT { ... }`. Hard errors once
4635/// committed (the `SWITCH` head is unambiguous): unknown words, empty
4636/// bodies, missing blocks, duplicate or non-trailing `DEFAULT`.
4637fn parse_switch_body(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<SwitchArms, TokenError> {
4638    let err = |msg: String| TokenError {
4639        diagnostic: None,
4640        hint: None,
4641        stmt,
4642        line: 0,
4643        col: 0,
4644        msg,
4645        kind: None,
4646    };
4647    let mut cases: Vec<(Vec<Expr>, Vec<Step>)> = Vec::new();
4648    let mut default_body: Option<Vec<Step>> = None;
4649    let mut p = 0;
4650    loop {
4651        let mut gcur = Cursor::expr(&inner[p..], stmt);
4652        gcur.skip_gap_nl();
4653        p += gcur.pos;
4654        if p >= inner.len() {
4655            break;
4656        }
4657        let word = match &inner[p].kind {
4658            TokKind::Word(w) => w.clone(),
4659            _ => {
4660                return Err(err(format!(
4661                    "{KEYWORD_SWITCH} body must hold {KEYWORD_CASE} or {KEYWORD_DEFAULT} arms, e.g. `{KEYWORD_SWITCH} $cmd {{ {KEYWORD_CASE} \"a\" {{ {KEYWORD_ECHO} yes }} {KEYWORD_DEFAULT} {{ {KEYWORD_ECHO} no }} }}`"
4662                )));
4663            }
4664        };
4665        if word == KEYWORD_CASE {
4666            if default_body.is_some() {
4667                return Err(err(format!(
4668                    "{KEYWORD_SWITCH} {KEYWORD_DEFAULT} must be the last arm; no {KEYWORD_CASE} may follow it"
4669                )));
4670            }
4671            let (values, used) = parse_case_values(&inner[p + 1..], stmt, ctx)?;
4672            p += 1 + used;
4673            let mut bcur = Cursor::expr(&inner[p..], stmt);
4674            bcur.skip_gap_nl();
4675            p += bcur.pos;
4676            let arm_ok = matches!(
4677                inner.get(p).map(|t| &t.kind),
4678                Some(TokKind::Group {
4679                    delim: GroupDelim::Brace,
4680                    ..
4681                })
4682            ) && inner.get(p).is_some_and(|t| !is_template_brace(t));
4683            if !arm_ok {
4684                return Err(err(
4685                    "SWITCH CASE needs a braced block, e.g. `CASE \"a\", \"b\" { ECHO yes }`"
4686                        .to_string(),
4687                ));
4688            }
4689            let arm_inner = match &inner[p].kind {
4690                TokKind::Group { inner, .. } => inner.clone(),
4691                _ => unreachable!(),
4692            };
4693            let body = parse_body_steps(&arm_inner, stmt, ctx, false)?;
4694            cases.push((values, body));
4695            p += 1;
4696        } else if word == KEYWORD_DEFAULT {
4697            if default_body.is_some() {
4698                return Err(err(format!(
4699                    "{KEYWORD_SWITCH} allows only one {KEYWORD_DEFAULT} arm"
4700                )));
4701            }
4702            p += 1;
4703            let mut bcur = Cursor::expr(&inner[p..], stmt);
4704            bcur.skip_gap_nl();
4705            p += bcur.pos;
4706            let arm_ok = matches!(
4707                inner.get(p).map(|t| &t.kind),
4708                Some(TokKind::Group {
4709                    delim: GroupDelim::Brace,
4710                    ..
4711                })
4712            ) && inner.get(p).is_some_and(|t| !is_template_brace(t));
4713            if !arm_ok {
4714                return Err(err(
4715                    "SWITCH DEFAULT needs a braced block, e.g. `DEFAULT { ECHO fallback }`"
4716                        .to_string(),
4717                ));
4718            }
4719            let arm_inner = match &inner[p].kind {
4720                TokKind::Group { inner, .. } => inner.clone(),
4721                _ => unreachable!(),
4722            };
4723            default_body = Some(parse_body_steps(&arm_inner, stmt, ctx, false)?);
4724            p += 1;
4725        } else {
4726            return Err(err(format!(
4727                "{KEYWORD_SWITCH} body must hold {KEYWORD_CASE} or {KEYWORD_DEFAULT} arms, e.g. `{KEYWORD_SWITCH} $cmd {{ {KEYWORD_CASE} \"a\" {{ {KEYWORD_ECHO} yes }} {KEYWORD_DEFAULT} {{ {KEYWORD_ECHO} no }} }}`"
4728            )));
4729        }
4730    }
4731    if cases.is_empty() && default_body.is_none() {
4732        return Err(err(format!(
4733            "{KEYWORD_SWITCH} needs at least one {KEYWORD_CASE} or {KEYWORD_DEFAULT} arm"
4734        )));
4735    }
4736    Ok((cases, default_body))
4737}
4738
4739/// `SWITCH [disc] { CASE v, ... { ... } ... [DEFAULT { ... }] }` or
4740/// bare `SWITCH { CASE <bool> { ... } ... }`. `None` on shape miss (no
4741/// outer brace: falls to generic, which fails it with the SWITCH hint);
4742/// classified expression failures propagate like `IF`, and arm errors
4743/// are hard (the head commits the shape).
4744fn parse_switch_at(
4745    toks: &[Tok],
4746    pos: usize,
4747    stmt: usize,
4748    ctx: &ParseCtx,
4749) -> Result<Option<(StepKind, usize)>, TokenError> {
4750    // Bare head: gaps skipped like the discriminant entry below; the
4751    // token then opens the body brace, so no discriminant is parsed
4752    // (every `CASE` carries its own condition).
4753    let mut gap = Cursor::expr(&toks[pos + 1..], stmt);
4754    gap.skip_gap();
4755    let brace_pos = pos + 1 + gap.pos;
4756    let bare_head = matches!(
4757        toks.get(brace_pos).map(|t| &t.kind),
4758        Some(TokKind::Group {
4759            delim: GroupDelim::Brace,
4760            ..
4761        })
4762    ) && toks.get(brace_pos).is_some_and(|t| !is_template_brace(t));
4763    let p: usize;
4764    let discriminant = if bare_head {
4765        p = brace_pos;
4766        None
4767    } else {
4768        // Discriminant entry reuses the skipped gaps above (`IF` uses
4769        // the same gap rule).
4770        let mut cur = Cursor::expr(&toks[brace_pos..], stmt);
4771        let disc = match parse_expr_checked(&mut cur, ctx) {
4772            Ok(expr) => expr,
4773            Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4774            // Same classified-error rule as the `IF` head above: the
4775            // head is unambiguous, so resolvable-but-unknown callees
4776            // name the culprit instead of the generic hint.
4777            Err(e) if e.kind.is_some() => return Err(e),
4778            Err(_) => return Ok(None),
4779        };
4780        p = brace_pos + cur.pos;
4781        Some(Box::new(disc))
4782    };
4783    let body_ok = matches!(
4784        toks.get(p).map(|t| &t.kind),
4785        Some(TokKind::Group {
4786            delim: GroupDelim::Brace,
4787            ..
4788        })
4789    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4790    if !body_ok {
4791        return Ok(None);
4792    }
4793    let inner = match &toks[p].kind {
4794        TokKind::Group { inner, .. } => inner.clone(),
4795        _ => unreachable!(),
4796    };
4797    let (cases, default_body) = parse_switch_body(&inner, stmt, ctx)?;
4798    let kind = StepKind::Switch {
4799        discriminant,
4800        cases,
4801        default_body,
4802    };
4803    Ok(Some((kind, p + 1 - pos)))
4804}
4805
4806/// Single (non-block) `FOR`: `$var[: TYPE] (, $var[: TYPE])? IN
4807/// expr` plus block. Header shapes miss to generic (a third variable,
4808/// a missing block, a bad name all fail in lowering like the
4809/// grammar); completed headers validate counts and key types loudly.
4810/// Expression failures from inline blocks propagate (blocks lower
4811/// here); other expression failures miss (generic fails them like a
4812/// committed `instruction` would).
4813fn parse_for_at(
4814    toks: &[Tok],
4815    pos: usize,
4816    stmt: usize,
4817    ctx: &ParseCtx,
4818) -> Result<Option<(StepKind, usize)>, TokenError> {
4819    let mut p = pos + 1;
4820    let mut idents = Vec::new();
4821    let mut types = Vec::new();
4822    // First `$var[: TYPE]` (gapless `$var`; gaps free elsewhere).
4823    let Some((var1, _)) = peek_dollar_var(toks, p) else {
4824        return Ok(None);
4825    };
4826    idents.push(var1);
4827    p += 2;
4828    let mut cur = Cursor::expr(&toks[p..], stmt);
4829    cur.skip_gap();
4830    p += cur.pos;
4831    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4832        p += 1;
4833        let mut tcur = Cursor::expr(&toks[p..], stmt);
4834        tcur.skip_gap();
4835        let tstart = p + tcur.pos;
4836        let Some(tend) = parse_type_shape(toks, tstart) else {
4837            return Ok(None);
4838        };
4839        // `render_type_region` canonicalizes (shared spelling).
4840        types.push(render_type_region(&toks[tstart..tend], stmt)?);
4841        p = tend;
4842    }
4843    // Optional `, $var2[: TYPE2]`.
4844    {
4845        let mut ccur = Cursor::expr(&toks[p..], stmt);
4846        ccur.skip_gap();
4847        if matches!(
4848            ccur.toks.get(ccur.pos).map(|t| &t.kind),
4849            Some(TokKind::Punct(','))
4850        ) {
4851            ccur.pos += 1;
4852            ccur.skip_gap();
4853            let base = p + ccur.pos;
4854            let Some((var2, _)) = peek_dollar_var(toks, base) else {
4855                return Ok(None);
4856            };
4857            idents.push(var2);
4858            let mut q = base + 2;
4859            let mut qcur = Cursor::expr(&toks[q..], stmt);
4860            qcur.skip_gap();
4861            q += qcur.pos;
4862            if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4863                q += 1;
4864                let mut tcur = Cursor::expr(&toks[q..], stmt);
4865                tcur.skip_gap();
4866                let tstart = q + tcur.pos;
4867                let Some(tend) = parse_type_shape(toks, tstart) else {
4868                    return Ok(None);
4869                };
4870                types.push(render_type_region(&toks[tstart..tend], stmt)?);
4871                q = tend;
4872            }
4873            p = q;
4874        }
4875    }
4876    // `IN expr block`.
4877    {
4878        let mut icur = Cursor::expr(&toks[p..], stmt);
4879        icur.skip_gap();
4880        if !matches!(
4881            icur.toks.get(icur.pos).map(|t| &t.kind),
4882            Some(TokKind::Word(w)) if w == KEYWORD_IN
4883        ) {
4884            return Ok(None);
4885        }
4886        icur.pos += 1;
4887        p += icur.pos;
4888    }
4889    let mut ecur = Cursor::expr(&toks[p..], stmt);
4890    ecur.skip_gap();
4891    let in_expr = match parse_expr_checked(&mut ecur, ctx) {
4892        Ok(expr) => expr,
4893        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4894        // Classified failures name the callee: `FOR ... IN` is
4895        // committed once the header matched this far.
4896        Err(e) if e.kind.is_some() => return Err(e),
4897        Err(_) => return Ok(None),
4898    };
4899    p += ecur.pos;
4900    let block_ok = matches!(
4901        toks.get(p).map(|t| &t.kind),
4902        Some(TokKind::Group {
4903            delim: GroupDelim::Brace,
4904            ..
4905        })
4906    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4907    if !block_ok {
4908        return Ok(None);
4909    }
4910    let inner = match &toks[p].kind {
4911        TokKind::Group { inner, .. } => inner.clone(),
4912        _ => unreachable!(),
4913    };
4914    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4915    p += 1;
4916    if idents.len() != types.len() {
4917        return Err(TokenError {
4918            diagnostic: None,
4919            hint: None,
4920            stmt,
4921            msg: format!(
4922                "FOR requires explicit types: FOR $item: TYPE IN <expr> (got {} vars, {} types)",
4923                idents.len(),
4924                types.len()
4925            ),
4926            line: 0,
4927            col: 0,
4928            kind: Some(ParseErrorKind::Validation {
4929                command: KEYWORD_FOR.to_string(),
4930            }),
4931        });
4932    }
4933    let (key_var, key_type, var, var_type) = match idents.len() {
4934        1 => (
4935            None,
4936            None,
4937            idents.into_iter().next().unwrap_or_default(),
4938            types.into_iter().next().unwrap_or_default(),
4939        ),
4940        2 => {
4941            let mut iv = idents.into_iter();
4942            let mut tv = types.into_iter();
4943            (
4944                Some(iv.next().unwrap_or_default()),
4945                Some(tv.next().unwrap_or_default()),
4946                iv.next().unwrap_or_default(),
4947                tv.next().unwrap_or_default(),
4948            )
4949        }
4950        _ => {
4951            return Err(TokenError {
4952                diagnostic: None,
4953                hint: None,
4954                stmt,
4955                msg: format!("{KEYWORD_FOR} requires one or two variables"),
4956                line: 0,
4957                col: 0,
4958                kind: Some(ParseErrorKind::Validation {
4959                    command: KEYWORD_FOR.to_string(),
4960                }),
4961            });
4962        }
4963    };
4964    if let Some(kt) = &key_type
4965        && kt != crate::TypeTag::String.name()
4966        && kt != crate::TypeTag::Int.name()
4967    {
4968        return Err(TokenError {
4969            diagnostic: None,
4970            hint: None,
4971            stmt,
4972            msg: format!(
4973                "{KEYWORD_FOR} key variable must be {INT_TYPE_NAME} or {STRING_TYPE_NAME}, got {kt}"
4974            ),
4975            line: 0,
4976            col: 0,
4977            kind: Some(ParseErrorKind::Validation {
4978                command: KEYWORD_FOR.to_string(),
4979            }),
4980        });
4981    }
4982    let kind = StepKind::For {
4983        key_var,
4984        key_type,
4985        var,
4986        var_type,
4987        in_expr,
4988        body,
4989    };
4990    Ok(Some((kind, p - pos)))
4991}
4992
4993/// Single (non-block) `WHILE`: condition plus block. `None` on
4994/// shape miss (missing block: generic fails it); classified
4995/// expression failures and inline-block failures propagate, other
4996/// expression failures miss (generic fails them like a committed
4997/// `instruction` would).
4998/// No leading gap-skip: `WHILE` takes `sep`, so a joint follower
4999/// never reaches here with a valid shape... (misses fall through
5000/// the same way regardless).
5001fn parse_while_single(
5002    toks: &[Tok],
5003    pos: usize,
5004    stmt: usize,
5005    ctx: &ParseCtx,
5006) -> Result<Option<(StepKind, usize)>, TokenError> {
5007    let mut cur = Cursor::expr(&toks[pos + 1..], stmt);
5008    let cond = match parse_expr_checked(&mut cur, ctx) {
5009        Ok(expr) => expr,
5010        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
5011        // Same rule as `IF`: the head is unambiguous, so classified
5012        // failures name the culprit instead of the generic hint.
5013        Err(e) if e.kind.is_some() => return Err(e),
5014        Err(_) => return Ok(None),
5015    };
5016    let brace = pos + 1 + cur.pos;
5017    let block_ok = matches!(
5018        toks.get(brace).map(|t| &t.kind),
5019        Some(TokKind::Group {
5020            delim: GroupDelim::Brace,
5021            ..
5022        })
5023    ) && toks.get(brace).is_some_and(|t| !is_template_brace(t));
5024    if !block_ok {
5025        return Ok(None);
5026    }
5027    let inner = match &toks[brace].kind {
5028        TokKind::Group { inner, .. } => inner.clone(),
5029        _ => unreachable!(),
5030    };
5031    let body = parse_body_steps(&inner, stmt, ctx, false)?;
5032    let kind = StepKind::While {
5033        cond: Box::new(cond),
5034        body,
5035    };
5036    Ok(Some((kind, brace + 1 - pos)))
5037}
5038
5039/// Validated `FUNC` header shape: name, parameter list, return type,
5040/// and body block. Single owner for the header grammar, shared by
5041/// `parse_func_at` and `predeclare_forward_funcs` so the hoist set can
5042/// never admit what the real path rejects (or reject what it admits).
5043/// Returns the header plus tokens consumed; `None` on shape miss
5044/// (lowercase names, missing paren/colon/block all miss to generic,
5045/// probed). Content failures (bad params, missing return type, bad
5046/// trailing tokens) carry the bare diagnostic: `parse_func_at`
5047/// adorns it, pre-declaration drops it (silent skip, letting the main
5048/// pass own the error).
5049struct FuncHeader {
5050    name: String,
5051    params: Vec<(String, String, bool)>,
5052    return_type: String,
5053    block: usize,
5054}
5055
5056#[allow(clippy::too_many_lines)]
5057fn parse_func_header(
5058    toks: &[Tok],
5059    pos: usize,
5060    stmt: usize,
5061    keyword: &str,
5062) -> Result<Option<(FuncHeader, usize)>, String> {
5063    // Head word: `FUNC` (callers normalize `ASYNC FUNC` to `pos`
5064    // first, so the header shape stays prefix-free).
5065    if !matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC) {
5066        return Ok(None);
5067    }
5068    // Name: UPPERCASE ident (lowercase misses to generic, probed).
5069    let def_name = match toks.get(pos + 1).map(|t| &t.kind) {
5070        Some(TokKind::Word(w))
5071            if crate::resolve::check_func_ident(&lowering_ctx(stmt), w).is_ok() =>
5072        {
5073            w.clone()
5074        }
5075        _ => return Ok(None),
5076    };
5077    // Paren group at any gap (`gap` zero-width): params live inside
5078    // its inner tokens, parsed with `gap_nl` discipline (newlines ride
5079    // free like call args and generics, via the shared helper).
5080    let mut p = pos + 2;
5081    let paren_inner = match toks.get(p).map(|t| &t.kind) {
5082        Some(TokKind::Group {
5083            delim: GroupDelim::Paren,
5084            inner,
5085            ..
5086        }) => inner.clone(),
5087        _ => return Ok(None),
5088    };
5089    p += 1;
5090    let mut params = Vec::new();
5091    let mut seen_optional = false;
5092    {
5093        let mut pcur = Cursor::expr(&paren_inner, stmt);
5094        pcur.skip_gap_nl();
5095        if !pcur.done() {
5096            loop {
5097                let base = pcur.pos;
5098                let Some((pname, _)) = peek_dollar_var(&paren_inner, base) else {
5099                    return Err(format!(
5100                        "FUNC {def_name} params must be `$name: TYPE` separated by commas"
5101                    ));
5102                };
5103                pcur.pos = base + 2;
5104                pcur.skip_gap_nl();
5105                // Optional params carry `?` before the colon
5106                // (`$flag?: BOOL`); all params are otherwise required.
5107                let optional = pcur.eat_punct('?');
5108                pcur.skip_gap_nl();
5109                if !pcur.eat_punct(':') {
5110                    return Err(format!(
5111                        "FUNC {def_name} param `${pname}` needs `: TYPE` after the name"
5112                    ));
5113                }
5114                pcur.skip_gap_nl();
5115                let tstart = pcur.pos;
5116                let Some(tend) = parse_type_shape(&paren_inner, tstart) else {
5117                    let got = match paren_inner.get(tstart).map(|tok| &tok.kind) {
5118                        Some(TokKind::Word(word)) => format!("; got `{word}`"),
5119                        _ => String::new(),
5120                    };
5121                    return Err(format!(
5122                        "FUNC {def_name} param `${pname}` needs an uppercase type after `:` (e.g. STRING, INT, BOOL){got}"
5123                    ));
5124                };
5125                // Post-match the span holds words/puncts only, so the
5126                // shared renderer cannot fail; stay failed regardless.
5127                let ptype =
5128                    render_type_region(&paren_inner[tstart..tend], stmt).unwrap_or_default();
5129                if optional {
5130                    seen_optional = true;
5131                } else if seen_optional {
5132                    return Err(format!(
5133                        "FUNC {def_name} optional ? params must be trailing: `${pname}` follows an optional param"
5134                    ));
5135                }
5136                params.push((pname, ptype, optional));
5137                pcur.pos = tend;
5138                pcur.skip_gap_nl();
5139                if pcur.eat_punct(',') {
5140                    pcur.skip_gap_nl();
5141                    // Trailing comma misses (a param must follow).
5142                    if pcur.done() {
5143                        return Err(format!(
5144                            "FUNC {def_name} params must not end with a trailing comma"
5145                        ));
5146                    }
5147                    continue;
5148                }
5149                break;
5150            }
5151            // Trailing junk (including newlines) misses to generic.
5152            pcur.skip_gap_nl();
5153            if !pcur.done() {
5154                return Err(format!(
5155                    "FUNC {def_name} params must be `$name: TYPE` separated by commas"
5156                ));
5157            }
5158        }
5159    }
5160    // Mandatory return annotation: FUNC NAME(...): RET { ... }.
5161    // After paren group, require gap-optional colon then type shape.
5162    // Missing colon after matched name+parens is a hard parse error
5163    // (no legacy fallback). Non-block tails (neither colon nor brace)
5164    // miss to generic (probed FUNC FOO() ECHO hi).
5165    let is_colon = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')));
5166    if !is_colon {
5167        let is_brace = matches!(
5168            toks.get(p).map(|t| &t.kind),
5169            Some(TokKind::Group {
5170                delim: GroupDelim::Brace,
5171                ..
5172            })
5173        ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
5174        if is_brace {
5175            return Err(format!(
5176                "{keyword} {def_name} requires a return type : TYPE (e.g. : VOID, : STRING)"
5177            ));
5178        }
5179        return Ok(None);
5180    }
5181    let Some(ret_end) = parse_type_shape(toks, p + 1) else {
5182        return Err(format!(
5183            "{keyword} {def_name} requires a return type : TYPE after ':'"
5184        ));
5185    };
5186    let return_type = render_type_region(&toks[p + 1..ret_end], stmt).map_err(|_| {
5187        format!("{keyword} {def_name} requires a return type : {KEYWORD_TYPE} after ':'")
5188    })?;
5189    let return_type = crate::canonicalize_spelling(&return_type);
5190    p = ret_end;
5191    // Block at any gap (never a template); missing blocks miss to
5192    // generic (probed FUNC FOO() ECHO hi).
5193    let block_ok = matches!(
5194        toks.get(p).map(|t| &t.kind),
5195        Some(TokKind::Group {
5196            delim: GroupDelim::Brace,
5197            ..
5198        })
5199    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
5200    if !block_ok {
5201        return Ok(None);
5202    }
5203    Ok(Some((
5204        FuncHeader {
5205            name: def_name,
5206            params,
5207            return_type,
5208            block: p,
5209        },
5210        p + 1 - pos,
5211    )))
5212}
5213
5214/// Single (non-block) `FUNC`: name, parenthesized params, block. The
5215/// shape parses purely first (misses fall to generic, declaring
5216/// nothing — the grammar only lowers matched pairs); then the name
5217/// declares in the enclosing scope before the body lowers (so
5218/// recursion resolves), and the body pushes a fresh scope.
5219/// Duplicates, reserved shadows, and parameter dupes fail loudly.
5220fn parse_func_at(
5221    toks: &[Tok],
5222    pos: usize,
5223    stmt: usize,
5224    ctx: &ParseCtx,
5225    is_async: bool,
5226) -> Result<Option<(StepKind, usize)>, TokenError> {
5227    let keyword = if is_async { "ASYNC FUNC" } else { KEYWORD_FUNC };
5228    let fail = |msg: String| TokenError {
5229        diagnostic: None,
5230        hint: None,
5231        stmt,
5232        msg,
5233        line: 0,
5234        col: 0,
5235        kind: Some(ParseErrorKind::Validation {
5236            command: KEYWORD_FUNC.to_string(),
5237        }),
5238    };
5239    // Phase 1 (pure shape) through the single header owner:
5240    // adorn content errors with the `FUNC` / `ASYNC FUNC` keyword,
5241    // miss to generic on shape miss exactly as before.
5242    let Some((header, used)) = parse_func_header(toks, pos, stmt, keyword).map_err(fail)? else {
5243        return Ok(None);
5244    };
5245    let FuncHeader {
5246        name: def_name,
5247        params,
5248        return_type,
5249        block: p,
5250    } = header;
5251    // Phase 2 (effects): reserved shadows and same-scope duplicates
5252    // fail at the definition line, verbatim.
5253    if ctx.reserved.contains(&def_name) || ctx.modules.reserved_base_names().contains(&def_name) {
5254        return Err(fail(format!(
5255            "FUNC {def_name} cannot shadow reserved function `{def_name}`"
5256        )));
5257    }
5258    if !ctx.declare_func(&def_name) {
5259        return Err(fail(format!(
5260            "duplicate function `{def_name}` in same scope"
5261        )));
5262    }
5263    let mut seen = HashSet::new();
5264    for (pname, _, _) in &params {
5265        if !seen.insert(pname.clone()) {
5266            return Err(fail(format!(
5267                "FUNC {def_name} declares duplicate parameter ${pname}"
5268            )));
5269        }
5270    }
5271    let inner = match &toks[p].kind {
5272        TokKind::Group { inner, .. } => inner.clone(),
5273        _ => unreachable!(),
5274    };
5275    let body = parse_body_steps(&inner, stmt, ctx, false)?;
5276    let kind = StepKind::FuncDef {
5277        name: def_name,
5278        params,
5279        return_type,
5280        is_async,
5281        body,
5282        docs: None,
5283    };
5284    Ok(Some((kind, used)))
5285}
5286
5287/// `REMOTE` header bindings `[$var, env:KEY]` over a bracket
5288/// group's inner tokens: comma-separated, newlines and comments free
5289/// like `gap_nl`. `$`+name and `env`+`:`+key all ride gapless (the
5290/// enclosing rule is compound-atomic). Empty lists parse (probed);
5291/// anything else misses the shape (`None`: generic fails it like
5292/// the grammar's dropped optional).
5293#[allow(clippy::type_complexity)]
5294fn parse_remote_bindings(
5295    inner: &[Tok],
5296    stmt: usize,
5297    _ctx: &ParseCtx,
5298) -> Result<Option<(Vec<String>, Vec<String>)>, TokenError> {
5299    let _ = stmt;
5300    let mut parts: Vec<&[Tok]> = Vec::new();
5301    let mut start = 0;
5302    for (i, tok) in inner.iter().enumerate() {
5303        if matches!(&tok.kind, TokKind::Punct(',')) {
5304            parts.push(&inner[start..i]);
5305            start = i + 1;
5306        }
5307    }
5308    parts.push(&inner[start..]);
5309    // An empty list (`[]`, whitespace/comment-only) holds no bindings.
5310    if parts.len() == 1
5311        && parts[0]
5312            .iter()
5313            .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
5314    {
5315        return Ok(Some((Vec::new(), Vec::new())));
5316    }
5317    let mut vars = Vec::new();
5318    let mut env = Vec::new();
5319    for part in parts {
5320        // Edges admit gaps, newlines, and comments, like `gap_nl`.
5321        let mut part = part;
5322        while matches!(
5323            part.first().map(|t| &t.kind),
5324            Some(TokKind::Newline | TokKind::Comment(_))
5325        ) {
5326            part = &part[1..];
5327        }
5328        while matches!(
5329            part.last().map(|t| &t.kind),
5330            Some(TokKind::Newline | TokKind::Comment(_))
5331        ) {
5332            part = &part[..part.len() - 1];
5333        }
5334        // `$var` entries only: bare words are literal text, never
5335        // bindings.
5336        if matches!(
5337            part.first().map(|t| &t.kind),
5338            Some(TokKind::Punct(VAR_SIGIL_CHAR))
5339        ) && part.len() == 2
5340        {
5341            if part[1].joint
5342                && let TokKind::Word(w) = &part[1].kind
5343                && is_ident_word(w)
5344            {
5345                vars.push(w.clone());
5346                continue;
5347            }
5348            return Ok(None);
5349        }
5350        // `env:KEY`: gapless triple with an uppercase key.
5351        if part.len() == 3
5352            && matches!(&part[0].kind, TokKind::Word(w) if w == "env")
5353            && matches!(&part[1].kind, TokKind::Punct(':'))
5354            && part[1].joint
5355            && part[2].joint
5356        {
5357            if let TokKind::Word(k) = &part[2].kind
5358                && is_env_key(k)
5359            {
5360                env.push(k.clone());
5361                continue;
5362            }
5363            return Ok(None);
5364        }
5365        return Ok(None);
5366    }
5367    Ok(Some((vars, env)))
5368}
5369
5370/// `IMPORT` statement at `pos` (#115): module form (`IMPORT MOD`,
5371/// `IMPORT [A, B]`), file form (`IMPORT "p" AS A`,
5372/// `IMPORT ["p" AS A]`), mixed/multi forms
5373/// (`IMPORT [STD, "p" AS A, "q" AS B]`, multi-line included), and
5374/// selective harvests (`IMPORT [[F, G FROM "p" (AS A)?]]`).
5375/// Returns module names plus `ImportFile`/`ImportFuncs` steps in source
5376/// order, plus tokens consumed (relative to `pos`), or `None` on shape
5377/// miss (generic lowering fails it like the grammar). Validation is
5378/// hard: unknown modules, bad names, collisions, templates, and remote
5379/// URLs fail here, and validated entries register immediately
5380/// (modules, aliases, and bare harvest names share the innermost
5381/// frames).
5382type ImportEntries = (Vec<String>, Vec<StepKind>);
5383
5384fn parse_import_statement(
5385    toks: &[Tok],
5386    pos: usize,
5387    stmt: usize,
5388    ctx: &ParseCtx,
5389    guarded: bool,
5390) -> Result<Option<(ImportEntries, usize)>, TokenError> {
5391    let fail = |msg: String| TokenError {
5392        diagnostic: None,
5393        hint: None,
5394        stmt,
5395        msg,
5396        line: 0,
5397        col: 0,
5398        kind: Some(ParseErrorKind::Validation {
5399            command: KEYWORD_IMPORT.to_string(),
5400        }),
5401    };
5402    let next = match toks.get(pos + 1) {
5403        // `sep` after `IMPORT`: joint followers miss.
5404        Some(t) if !t.joint => t,
5405        _ => return Ok(None),
5406    };
5407    // Parse entries first, validate in source order after.
5408    enum RawEntry {
5409        Module(String),
5410        File {
5411            path: String,
5412            alias: String,
5413        },
5414        From {
5415            func_names: Vec<String>,
5416            type_names: Vec<String>,
5417            path: String,
5418            alias: Option<String>,
5419        },
5420    }
5421    let mut raw: Vec<RawEntry> = Vec::new();
5422    let used;
5423    if matches!(
5424        &next.kind,
5425        TokKind::Group {
5426            delim: GroupDelim::Brace,
5427            ..
5428        }
5429    ) {
5430        return Ok(None);
5431    }
5432    if let TokKind::Group {
5433        delim: GroupDelim::Bracket,
5434        inner,
5435        ..
5436    } = &next.kind
5437    {
5438        // Comma-separated entries, `ws` gaps (newlines ok inside and
5439        // around entries, comments MISS — `ws` admits neither).
5440        // Single-file multi-name harvests skip the split: in
5441        // `[TYPE A, TYPE B FROM "f"]` the first comma-part (`[TYPE A]`)
5442        // carries no FROM and is invalid alone, so the whole bracket
5443        // is one harvest (see `whole_file_harvest`).
5444        // Bare-multi hint: `[FOO, BAR FROM "f"]` reads FOO as a
5445        // module for back-compat (bare words stay modules in single
5446        // brackets). If that word is not a known module but a harvest
5447        // follows, fail fast naming the two valid spellings instead
5448        // of the misleading unknown-module error.
5449        if let Some(comment) = find_bracket_comment(inner) {
5450            let mut err = lower_err(
5451                stmt,
5452                ParseError::from_diagnostic(
5453                    ParseErrorKind::InvalidSyntax {
5454                        command: KEYWORD_IMPORT.to_string(),
5455                    },
5456                    dsl_diag::spelling_bracket_list_comment(KEYWORD_IMPORT),
5457                    &lowering_ctx(stmt),
5458                ),
5459            );
5460            err.line = comment.line;
5461            err.col = comment.col;
5462            return Err(err);
5463        }
5464        let whole = whole_file_harvest(inner);
5465        if whole.is_none()
5466            && let Some(word) = single_bare_first_part(inner)
5467            && !ctx.modules.modules.contains_key(word)
5468            && has_top_level_from_after_comma(inner)
5469        {
5470            return Err(fail(format!(
5471                "unknown module `{word}`; to harvest multiple names qualify each kind (`IMPORT [FUNC FOO, FUNC BAR FROM \"f\"]`)"
5472            )));
5473        }
5474        let mut parts: Vec<&[Tok]> = Vec::new();
5475        if whole.is_some() {
5476            parts.push(inner);
5477        } else {
5478            let mut start = 0;
5479            for (i, tok) in inner.iter().enumerate() {
5480                if matches!(&tok.kind, TokKind::Punct(',')) {
5481                    parts.push(&inner[start..i]);
5482                    start = i + 1;
5483                }
5484            }
5485            parts.push(&inner[start..]);
5486        }
5487        for part in parts {
5488            let dense: Vec<&Tok> = part
5489                .iter()
5490                .filter(|t| !matches!(&t.kind, TokKind::Newline))
5491                .collect();
5492            // `[[F, G FROM "path" (AS ALIAS)?]]`: selective function
5493            // harvest. Anything else bracketed here misses.
5494            if let [bracket] = dense.as_slice()
5495                && let TokKind::Group {
5496                    delim: GroupDelim::Bracket,
5497                    inner,
5498                    ..
5499                } = &bracket.kind
5500            {
5501                let Some(HarvestImport {
5502                    func_names,
5503                    type_names,
5504                    path,
5505                    alias,
5506                }) = parse_from_entry(inner)
5507                else {
5508                    return Ok(None);
5509                };
5510                raw.push(RawEntry::From {
5511                    func_names,
5512                    type_names,
5513                    path,
5514                    alias,
5515                });
5516                continue;
5517            }
5518            // `[F FROM "path" (AS ALIAS)?]`: single harvest without
5519            // inner brackets. The `FROM` keyword is the discriminant
5520            // (module and file parts never contain a top-level one);
5521            // multi-name harvests keep `[[F, G FROM ...]]` so the comma
5522            // stays grouped inside its own scope.
5523            if dense.len() >= 3 {
5524                let owned: Vec<Tok> = dense.iter().map(|t| (*t).clone()).collect();
5525                if let Some(HarvestImport {
5526                    func_names,
5527                    type_names,
5528                    path,
5529                    alias,
5530                }) = parse_from_entry(&owned)
5531                {
5532                    raw.push(RawEntry::From {
5533                        func_names,
5534                        type_names,
5535                        path,
5536                        alias,
5537                    });
5538                    continue;
5539                }
5540            }
5541            match dense.as_slice() {
5542                [tok] => match &tok.kind {
5543                    TokKind::Word(w) if is_upper_ident(w) => {
5544                        raw.push(RawEntry::Module(w.clone()));
5545                    }
5546                    _ => return Ok(None),
5547                },
5548                [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5549                    let (
5550                        TokKind::Str { text, .. },
5551                        TokKind::Word(as_word),
5552                        TokKind::Word(alias_word),
5553                    ) = (&path_tok.kind, &as_tok.kind, &alias_tok.kind)
5554                    else {
5555                        return Ok(None);
5556                    };
5557                    if as_word != KEYWORD_AS {
5558                        return Ok(None);
5559                    }
5560                    raw.push(RawEntry::File {
5561                        path: text.clone(),
5562                        alias: alias_word.clone(),
5563                    });
5564                }
5565                _ => return Ok(None),
5566            }
5567        }
5568        if raw.is_empty() {
5569            return Ok(None);
5570        }
5571        used = 2;
5572    } else if let TokKind::Word(w) = &next.kind {
5573        // Bare `IMPORT MOD` (single module, probed).
5574        if !is_upper_ident(w) {
5575            return Ok(None);
5576        }
5577        raw.push(RawEntry::Module(w.clone()));
5578        used = 2;
5579    } else if let TokKind::Str { text, .. } = &next.kind {
5580        // Bare `IMPORT "path" AS ALIAS`.
5581        let (Some(as_tok), Some(alias_tok)) = (toks.get(pos + 2), toks.get(pos + 3)) else {
5582            return Ok(None);
5583        };
5584        if as_tok.joint || alias_tok.joint {
5585            return Ok(None);
5586        }
5587        let (TokKind::Word(as_word), TokKind::Word(alias_word)) = (&as_tok.kind, &alias_tok.kind)
5588        else {
5589            return Ok(None);
5590        };
5591        if as_word != KEYWORD_AS {
5592            return Ok(None);
5593        }
5594        raw.push(RawEntry::File {
5595            path: text.clone(),
5596            alias: alias_word.clone(),
5597        });
5598        used = 4;
5599    } else {
5600        return Ok(None);
5601    }
5602    // Validate in source order: unknown modules fail with the exact
5603    // backend message (sorted known list); file and harvest entries
5604    // validate hard (bad names, collisions, templates, remote URLs).
5605    let mut modules = Vec::new();
5606    let mut steps = Vec::new();
5607    for entry in raw {
5608        match entry {
5609            RawEntry::Module(module) => {
5610                if !ctx.modules.modules.contains_key(&module) {
5611                    let mut known: Vec<String> = ctx.modules.modules.keys().cloned().collect();
5612                    known.sort();
5613                    return Err(fail(format!(
5614                        "unknown module `{module}`; known modules: {}",
5615                        known.join(", ")
5616                    )));
5617                }
5618                ctx.import_into_frame(std::slice::from_ref(&module), false);
5619                modules.push(module);
5620            }
5621            RawEntry::File { path, alias } => {
5622                let (path, alias) =
5623                    validate_file_import(&path, &alias, ctx, guarded).map_err(fail)?;
5624                steps.push(StepKind::ImportFile { path, alias });
5625            }
5626            RawEntry::From {
5627                func_names,
5628                type_names,
5629                path,
5630                alias,
5631            } => {
5632                let HarvestImport {
5633                    func_names,
5634                    type_names,
5635                    path,
5636                    alias,
5637                } = validate_from_import(
5638                    &func_names,
5639                    &type_names,
5640                    &path,
5641                    alias.as_deref(),
5642                    ctx,
5643                    guarded,
5644                )
5645                .map_err(fail)?;
5646                steps.push(StepKind::ImportFuncs {
5647                    path,
5648                    alias,
5649                    func_names,
5650                    type_names,
5651                });
5652            }
5653        }
5654    }
5655    Ok(Some(((modules, steps), used)))
5656}
5657
5658/// Single file import for value positions (#115): exactly one
5659/// `"path" AS ALIAS` entry and no modules. Anything else shaped like an
5660/// import is a hard error naming the restriction; shape misses return
5661/// `None` for the generic path.
5662fn parse_single_file_import(
5663    toks: &[Tok],
5664    pos: usize,
5665    stmt: usize,
5666    ctx: &ParseCtx,
5667) -> Result<Option<(String, String, usize)>, TokenError> {
5668    let Some(((modules, mut kinds), used)) = parse_import_statement(toks, pos, stmt, ctx, false)?
5669    else {
5670        return Ok(None);
5671    };
5672    if !modules.is_empty() || !matches!(kinds.as_slice(), [StepKind::ImportFile { .. }]) {
5673        return Err(TokenError {
5674            diagnostic: None,
5675            hint: None,
5676            stmt,
5677            msg: if !modules.is_empty()
5678                || kinds
5679                    .iter()
5680                    .any(|k| matches!(k, StepKind::ImportFuncs { .. }))
5681            {
5682                format!(
5683                    "{KEYWORD_IMPORT} here takes a single file import ({KEYWORD_IMPORT} [\"<path>\" AS <ALIAS>]); modules and function harvests stay at statement level"
5684                )
5685            } else {
5686                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>])"
5687                    .to_string()
5688            },
5689            line: 0,
5690            col: 0,
5691            kind: Some(ParseErrorKind::Validation {
5692                command: KEYWORD_IMPORT.to_string(),
5693            }),
5694        });
5695    }
5696    let Some(StepKind::ImportFile { path, alias }) = kinds.pop() else {
5697        unreachable!("length and variant checked above")
5698    };
5699    Ok(Some((path, alias, used)))
5700}
5701
5702/// One `EXPORT` name: an uppercase word with an optional joint
5703/// `::UPPER` tail. Returns the name and tokens consumed, `Ok(None)`
5704/// on shape miss, or `Err` when a recognizable identifier carries
5705/// the wrong sigil (`CONST` requires `$`, `FUNC`/`TYPE` forbid it).
5706fn parse_export_name(
5707    toks: &[Tok],
5708    pos: usize,
5709    require_sigil: bool,
5710    stmt: usize,
5711) -> Result<Option<(String, usize)>, TokenError> {
5712    // Sigil rule: `EXPORT CONST $N` and `EXPORT CONST $LIB::V` require
5713    // the `$`, exactly like every other `CONST` read; `EXPORT FOO`,
5714    // `EXPORT TYPE T`, and qualified func forwards never take one.
5715    // Stored without the sigil; downstream matching (top-level tables,
5716    // harvest maps) is unchanged. `$` must ride gapless onto the
5717    // name, like every `$` read.
5718    let fail = |msg: String| TokenError {
5719        diagnostic: None,
5720        hint: None,
5721        stmt,
5722        line: 0,
5723        col: 0,
5724        kind: None,
5725        msg,
5726    };
5727    let offset = match toks.get(pos).map(|t| &t.kind) {
5728        Some(TokKind::Punct(VAR_SIGIL_CHAR)) if toks.get(pos + 1).is_some_and(|t| t.joint) => 1,
5729        Some(TokKind::Punct(VAR_SIGIL_CHAR)) => return Ok(None),
5730        _ => 0,
5731    };
5732    if require_sigil != (offset == 1) {
5733        let head = toks.get(pos + offset).map(|t| &t.kind);
5734        let recognizable = matches!(head, Some(TokKind::Word(w)) if is_upper_ident(w));
5735        if !recognizable {
5736            return Ok(None);
5737        }
5738        if require_sigil {
5739            return Err(fail(format!(
5740                "{KEYWORD_EXPORT} {KEYWORD_CONST} requires `$`: write {KEYWORD_EXPORT} {KEYWORD_CONST} $NAME (never bare)"
5741            )));
5742        } else {
5743            return Err(fail(format!(
5744                "{KEYWORD_EXPORT} {KEYWORD_FUNC} and {KEYWORD_EXPORT} {KEYWORD_TYPE} names never take `$`: write {KEYWORD_EXPORT} FOO"
5745            )));
5746        }
5747    }
5748    let head = match toks.get(pos + offset).map(|t| &t.kind) {
5749        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
5750        _ => return Ok(None),
5751    };
5752    let mut name = head;
5753    let mut used = 1 + offset;
5754    // Greedy-prefix `::tail` (atomic, like the grammar): a valid
5755    // tail joins, an invalid one stays trailing (failing downstream
5756    // exactly like the grammar's committed prefix).
5757    if matches!(
5758        toks.get(pos + offset + 1).map(|t| &t.kind),
5759        Some(TokKind::Punct(':'))
5760    ) && toks.get(pos + offset + 1).is_some_and(|t| t.joint)
5761        && matches!(
5762            toks.get(pos + offset + 2).map(|t| &t.kind),
5763            Some(TokKind::Punct(':'))
5764        )
5765        && toks.get(pos + offset + 2).is_some_and(|t| t.joint)
5766        && let Some(TokKind::Word(tail)) = toks.get(pos + offset + 3).map(|t| &t.kind)
5767        && toks[pos + offset + 3].joint
5768        && is_upper_ident(tail)
5769    {
5770        name.push_str(MODULE_SEPARATOR);
5771        name.push_str(tail);
5772        used = 4 + offset;
5773    }
5774    Ok(Some((name, used)))
5775}
5776
5777/// One selective harvest (`[[F, G FROM "path" (AS ALIAS)?]]`): the
5778/// wanted function and type names plus the path and optional alias.
5779/// Bare names are functions; `TYPE`/`FUNC` prefixes select the kind
5780/// explicitly (`[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`).
5781struct HarvestImport {
5782    func_names: Vec<String>,
5783    type_names: Vec<String>,
5784    path: String,
5785    alias: Option<String>,
5786}
5787
5788/// One `[[F, G FROM "path" (AS ALIAS)?]]` entry: selective function
5789/// harvest with optional `TYPE`/`FUNC` qualifiers per name:
5790/// `[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`
5791/// (bare stays func for back-compat).
5792/// Returns the harvest, or `None` on shape miss (generic lowering fails
5793/// it). Name case is validated hard by the caller, like file aliases.
5794fn parse_from_entry(inner: &[Tok]) -> Option<HarvestImport> {
5795    let dense: Vec<&Tok> = inner
5796        .iter()
5797        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5798        .collect();
5799    let from = dense
5800        .iter()
5801        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5802    if from == 0 {
5803        return None;
5804    }
5805    // Names: comma-separated entries, each `NAME` (func) or
5806    // `TYPE NAME` / `FUNC NAME` (explicit kind for clarity).
5807    let mut func_names = Vec::new();
5808    let mut type_names = Vec::new();
5809    let mut start = 0;
5810    let head = &dense[..from];
5811    // Local helper: classify one comma-separated part.
5812    fn classify_part(part: &[&Tok]) -> Option<(bool, String)> {
5813        match part {
5814            [tok] => {
5815                let TokKind::Word(w) = &tok.kind else {
5816                    return None;
5817                };
5818                Some((false, w.clone()))
5819            }
5820            // `TYPE NAME` / `FUNC NAME`: the name must be `sep` (gapped
5821            // from the kind); the kind may be joint to a preceding `[`
5822            // or `,` (no space required there), so only the name's joint
5823            // flag matters.
5824            [kind_tok, name_tok] if !name_tok.joint => {
5825                let (TokKind::Word(kind), TokKind::Word(name)) = (&kind_tok.kind, &name_tok.kind)
5826                else {
5827                    return None;
5828                };
5829                if kind == KEYWORD_TYPE {
5830                    Some((true, name.clone()))
5831                } else if kind == KEYWORD_FUNC {
5832                    Some((false, name.clone()))
5833                } else {
5834                    None
5835                }
5836            }
5837            _ => None,
5838        }
5839    }
5840    for (i, tok) in head.iter().enumerate() {
5841        if matches!(&tok.kind, TokKind::Punct(',')) {
5842            let part = &head[start..i];
5843            let (is_type, name) = classify_part(part)?;
5844            if is_type {
5845                type_names.push(name);
5846            } else {
5847                func_names.push(name);
5848            }
5849            start = i + 1;
5850        }
5851    }
5852    let part = &head[start..];
5853    let (is_type, name) = classify_part(part)?;
5854    if is_type {
5855        type_names.push(name);
5856    } else {
5857        func_names.push(name);
5858    }
5859    // Tail: `"path"` or bare `MODULE` with an optional gapped `AS ALIAS`.
5860    // Quoted is a file path (module fallback only when no file matches);
5861    // bare is a host module (no file probe ambiguity).
5862    let tail = &dense[from + 1..];
5863    let path_text = |tok: &Tok| match &tok.kind {
5864        TokKind::Str { text, .. } => Some(text.clone()),
5865        TokKind::Word(w) if is_upper_ident(w) => Some(w.clone()),
5866        _ => None,
5867    };
5868    match tail {
5869        [path_tok] => {
5870            let text = path_text(path_tok)?;
5871            Some(HarvestImport {
5872                func_names,
5873                type_names,
5874                path: text,
5875                alias: None,
5876            })
5877        }
5878        [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5879            let text = path_text(path_tok)?;
5880            let (TokKind::Word(as_word), TokKind::Word(alias_word)) =
5881                (&as_tok.kind, &alias_tok.kind)
5882            else {
5883                return None;
5884            };
5885            if as_word != KEYWORD_AS {
5886                return None;
5887            }
5888            Some(HarvestImport {
5889                func_names,
5890                type_names,
5891                path: text,
5892                alias: Some(alias_word.clone()),
5893            })
5894        }
5895        _ => None,
5896    }
5897}
5898
5899/// First comma-part of a bracket when it is exactly one bare
5900/// uppercase word: the back-compat module reading. Anything else
5901/// (prefixed names, groups, multiple words) is not a bare module.
5902fn single_bare_first_part(inner: &[Tok]) -> Option<&str> {
5903    let end = inner
5904        .iter()
5905        .position(|t| matches!(&t.kind, TokKind::Punct(',')))
5906        .unwrap_or(inner.len());
5907    let mut words = inner[..end]
5908        .iter()
5909        .filter(|t| !matches!(&t.kind, TokKind::Newline));
5910    match (words.next(), words.next()) {
5911        (Some(tok), None) => match &tok.kind {
5912            TokKind::Word(w) if is_upper_ident(w) => Some(w.as_str()),
5913            _ => None,
5914        },
5915        _ => None,
5916    }
5917}
5918
5919/// Whether a top-level `FROM` follows the first top-level comma:
5920/// distinguishes a module-plus-harvest entry (`[STD, T FROM "f"]`)
5921/// from a bare word the author meant as a harvest name.
5922fn has_top_level_from_after_comma(inner: &[Tok]) -> bool {
5923    let mut seen_comma = false;
5924    for tok in inner {
5925        match &tok.kind {
5926            TokKind::Punct(',') => seen_comma = true,
5927            TokKind::Word(w) if seen_comma && w == KEYWORD_FROM => return true,
5928            _ => {}
5929        }
5930    }
5931    false
5932}
5933
5934/// Whole-bracket single-file harvest (`[TYPE A, TYPE B FROM "f"]`):
5935/// the comma-split would orphan `[TYPE A]` (no FROM, invalid alone),
5936/// so the entire bracket parses as one harvest. Only explicitly
5937/// prefixed names qualify: a bare word keeps its legacy module
5938/// reading, so `[STD, TYPE T FROM "f"]` still splits into a module
5939/// plus a harvest instead of harvesting STD as a function.
5940fn whole_file_harvest(inner: &[Tok]) -> Option<HarvestImport> {
5941    let owned: Vec<Tok> = inner.to_vec();
5942    let harvest = parse_from_entry(&owned)?;
5943    let dense: Vec<&Tok> = inner
5944        .iter()
5945        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5946        .collect();
5947    let from = dense
5948        .iter()
5949        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5950    let mut start = 0;
5951    for (i, tok) in dense[..from].iter().enumerate() {
5952        if matches!(&tok.kind, TokKind::Punct(',')) {
5953            if !is_prefixed_name(&dense[start..i]) {
5954                return None;
5955            }
5956            start = i + 1;
5957        }
5958    }
5959    if !is_prefixed_name(&dense[start..from]) {
5960        return None;
5961    }
5962    Some(harvest)
5963}
5964
5965/// One explicitly prefixed name (`TYPE NAME` / `FUNC NAME`): the name
5966/// stays gapped from its kind; the kind may joint to `[` or `,`.
5967fn is_prefixed_name(part: &[&Tok]) -> bool {
5968    match part {
5969        [kind_tok, name_tok] if !name_tok.joint => {
5970            matches!(
5971                (&kind_tok.kind, &name_tok.kind),
5972                (
5973                    TokKind::Word(kind),
5974                    TokKind::Word(_)
5975                ) if kind == KEYWORD_TYPE || kind == KEYWORD_FUNC
5976            )
5977        }
5978        _ => false,
5979    }
5980}
5981
5982/// Validate an `IMPORT` alias: hard errors (never shape misses) plus
5983/// registration into the innermost import frame. Same-frame duplicates
5984/// reject, unless the new import and every visible same-alias entry
5985/// are guard-gated: an unguarded duplicate always collides at runtime
5986/// (probable typo, fail fast), while guarded duplicates may be
5987/// platform branches whose disjointness the static pass decides.
5988fn validate_import_alias(alias: &str, ctx: &ParseCtx, guarded: bool) -> Result<String, String> {
5989    if !is_upper_ident(alias) {
5990        return Err(format!(
5991            "IMPORT alias must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{alias}`"
5992        ));
5993    }
5994    if ctx.modules.modules.contains_key(alias) {
5995        return Err(format!(
5996            "IMPORT alias `{alias}` collides with module `{alias}`"
5997        ));
5998    }
5999    let flags = ctx.import_guard_flags(alias);
6000    if !flags.is_empty() && (!guarded || flags.iter().any(|g| !g)) {
6001        return Err(format!("duplicate {KEYWORD_IMPORT} alias `{alias}`"));
6002    }
6003    ctx.import_into_frame(std::slice::from_ref(&alias.to_string()), guarded);
6004    Ok(alias.to_string())
6005}
6006
6007/// Validate an `IMPORT` path: hard errors, never shape misses.
6008fn validate_import_path(path: &str) -> Result<String, String> {
6009    if path.is_empty() {
6010        return Err(format!("{KEYWORD_IMPORT} path must not be empty"));
6011    }
6012    if path.contains("{{") {
6013        return Err(format!(
6014            "{KEYWORD_IMPORT} path must be a literal string (no {{{{ }}}} templates)"
6015        ));
6016    }
6017    if path.contains("://") {
6018        return Err(
6019            "remote imports are deferred to #270 (net: Run scripts from a remote URL)".to_string(),
6020        );
6021    }
6022    Ok(path.to_string())
6023}
6024
6025/// Validate a file-import path/alias pair: hard errors (never shape
6026/// misses) plus alias registration into the innermost import frame.
6027/// `guarded` marks a guard-gated statement, relaxing the same-frame
6028/// duplicate gate for platform branches (see `validate_import_alias`).
6029fn validate_file_import(
6030    path: &str,
6031    alias: &str,
6032    ctx: &ParseCtx,
6033    guarded: bool,
6034) -> Result<(String, String), String> {
6035    let alias = validate_import_alias(alias, ctx, guarded)?;
6036    let path = validate_import_path(path)?;
6037    Ok((path, alias))
6038}
6039
6040/// Validate a `[[F, G FROM "path" (AS ALIAS)?]]` entry: hard errors
6041/// (never shape misses). Bare func names declare into the innermost
6042/// `FUNC` frame so calls resolve statically; the runtime defines them
6043/// (and fails unknown names there). Type names need no func-frame
6044/// declaration (types resolve through the global type directory);
6045/// the runtime validates them against the file's `EXPORT TYPE` list.
6046/// An alias registers like a file import.
6047fn validate_from_import(
6048    func_names: &[String],
6049    type_names: &[String],
6050    path: &str,
6051    alias: Option<&str>,
6052    ctx: &ParseCtx,
6053    guarded: bool,
6054) -> Result<HarvestImport, String> {
6055    let path = validate_import_path(path)?;
6056    let mut out_func_names = Vec::with_capacity(func_names.len());
6057    for name in func_names {
6058        if !is_upper_ident(name) {
6059            return Err(format!(
6060                "IMPORT function names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
6061            ));
6062        }
6063        if ctx.reserved.contains(name) {
6064            return Err(format!("cannot shadow reserved function `{name}`"));
6065        }
6066        out_func_names.push(name.clone());
6067    }
6068    let mut out_type_names = Vec::with_capacity(type_names.len());
6069    for name in type_names {
6070        if !is_upper_ident(name) {
6071            return Err(format!(
6072                "IMPORT type names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
6073            ));
6074        }
6075        out_type_names.push(name.clone());
6076    }
6077    if out_func_names.is_empty() && out_type_names.is_empty() {
6078        return Err(format!(
6079            "{KEYWORD_IMPORT} harvest needs at least one function or type name"
6080        ));
6081    }
6082    if let Some(alias) = alias {
6083        let alias = validate_import_alias(alias, ctx, guarded)?;
6084        Ok(HarvestImport {
6085            func_names: out_func_names,
6086            type_names: out_type_names,
6087            path,
6088            alias: Some(alias),
6089        })
6090    } else {
6091        for name in &out_func_names {
6092            if !ctx.declare_func(name) {
6093                return Err(format!("duplicate function `{name}` in same scope"));
6094            }
6095        }
6096        // Type harvests without alias land bare in the global type
6097        // directory: duplicates across files fail at import time
6098        // (different targets), not at parse time (targets need IO).
6099        Ok(HarvestImport {
6100            func_names: out_func_names,
6101            type_names: out_type_names,
6102            path,
6103            alias: None,
6104        })
6105    }
6106}
6107
6108/// One `EXPORT ...` name list: function, type, and const names in
6109/// source order. Bare names are functions; explicit `TYPE`/`FUNC`/
6110/// `CONST` prefixes select the kind.
6111struct ExportNames {
6112    func_names: Vec<String>,
6113    type_names: Vec<String>,
6114    const_names: Vec<String>,
6115}
6116
6117/// `EXPORT ...` names at `pos`: bracket list (strict, `ws` gaps:
6118/// newlines ok, comments miss) or a bare greedy-prefix name.
6119/// Supports explicit `TYPE`/`FUNC`/`CONST` qualifiers for clarity:
6120/// `EXPORT TYPE FOO`, `EXPORT FUNC FOO`, `EXPORT CONST $FOO`,
6121/// plus mixed `EXPORT [TYPE A, FUNC B, CONST $C, D]` (bare stays func).
6122/// Returns the name lists plus tokens consumed, `Ok(None)` on shape
6123/// miss (generic fails it in lowering like the grammar), or `Err`
6124/// when a recognizable name carries the wrong sigil. Recording and
6125/// duplicate checks live with the caller (they need the guard and
6126/// level context).
6127fn parse_export_at(
6128    toks: &[Tok],
6129    pos: usize,
6130    stmt: usize,
6131) -> Result<Option<(ExportNames, usize)>, TokenError> {
6132    let next = match toks.get(pos + 1) {
6133        // `sep` after `EXPORT`: joint followers miss.
6134        Some(t) if !t.joint => t,
6135        _ => return Ok(None),
6136    };
6137    // Explicit `EXPORT TYPE ...`, `EXPORT FUNC ...`, or
6138    // `EXPORT CONST ...` prefix.
6139    if let TokKind::Word(w) = &next.kind
6140        && (w == KEYWORD_TYPE || w == KEYWORD_FUNC || w == KEYWORD_CONST)
6141    {
6142        let kind = w.as_str();
6143        let after = match toks.get(pos + 2) {
6144            Some(t) if !t.joint => t,
6145            _ => return Ok(None),
6146        };
6147        if let TokKind::Group {
6148            delim: GroupDelim::Bracket,
6149            inner,
6150            ..
6151        } = &after.kind
6152        {
6153            if let Some(comment) = find_bracket_comment(inner) {
6154                let mut err = lower_err(
6155                    stmt,
6156                    ParseError::from_diagnostic(
6157                        ParseErrorKind::InvalidSyntax {
6158                            command: KEYWORD_EXPORT.to_string(),
6159                        },
6160                        dsl_diag::spelling_bracket_list_comment(KEYWORD_EXPORT),
6161                        &lowering_ctx(stmt),
6162                    ),
6163                );
6164                err.line = comment.line;
6165                err.col = comment.col;
6166                return Err(err);
6167            }
6168            let mut func_names = Vec::new();
6169            let mut type_names = Vec::new();
6170            let mut const_names = Vec::new();
6171            for part in split_bracket_entries(inner) {
6172                let part = trim_export_part(part);
6173                // A trailing comma leaves an empty final entry; it
6174                // carries no name and must not fail the list.
6175                if part.is_empty() {
6176                    continue;
6177                }
6178                let require_sigil = kind == KEYWORD_CONST;
6179                let Some((name, used)) = parse_export_name(part, 0, require_sigil, stmt)? else {
6180                    return Ok(None);
6181                };
6182                if used != part.len() {
6183                    return Ok(None);
6184                }
6185                match kind {
6186                    k if k == KEYWORD_TYPE => type_names.push(name),
6187                    k if k == KEYWORD_CONST => const_names.push(name),
6188                    _ => func_names.push(name),
6189                }
6190            }
6191            if func_names.is_empty() && type_names.is_empty() && const_names.is_empty() {
6192                return Ok(None);
6193            }
6194            return Ok(Some((
6195                ExportNames {
6196                    func_names,
6197                    type_names,
6198                    const_names,
6199                },
6200                3,
6201            )));
6202        }
6203        if matches!(&after.kind, TokKind::Group { .. }) {
6204            return Ok(None);
6205        }
6206        let require_sigil = kind == KEYWORD_CONST;
6207        let Some((name, used)) = parse_export_name(toks, pos + 2, require_sigil, stmt)? else {
6208            return Ok(None);
6209        };
6210        // Bare name after TYPE/FUNC/CONST prefix must consume exactly
6211        // one name; trailing loops stay outside like the unprefixed
6212        // case. `used` counts from pos+2, so 1 name is valid.
6213        if used == 0 {
6214            return Ok(None);
6215        }
6216        return Ok(Some((
6217            match kind {
6218                k if k == KEYWORD_TYPE => ExportNames {
6219                    func_names: Vec::new(),
6220                    type_names: vec![name],
6221                    const_names: Vec::new(),
6222                },
6223                k if k == KEYWORD_CONST => ExportNames {
6224                    func_names: Vec::new(),
6225                    type_names: Vec::new(),
6226                    const_names: vec![name],
6227                },
6228                _ => ExportNames {
6229                    func_names: vec![name],
6230                    type_names: Vec::new(),
6231                    const_names: Vec::new(),
6232                },
6233            },
6234            2 + used,
6235        )));
6236    }
6237    if let TokKind::Group {
6238        delim: GroupDelim::Bracket,
6239        inner,
6240        ..
6241    } = &next.kind
6242    {
6243        if let Some(comment) = find_bracket_comment(inner) {
6244            let mut err = lower_err(
6245                stmt,
6246                ParseError::from_diagnostic(
6247                    ParseErrorKind::InvalidSyntax {
6248                        command: KEYWORD_EXPORT.to_string(),
6249                    },
6250                    dsl_diag::spelling_bracket_list_comment(KEYWORD_EXPORT),
6251                    &lowering_ctx(stmt),
6252                ),
6253            );
6254            err.line = comment.line;
6255            err.col = comment.col;
6256            return Err(err);
6257        }
6258        let mut func_names = Vec::new();
6259        let mut type_names = Vec::new();
6260        let mut const_names = Vec::new();
6261        for part in split_bracket_entries(inner) {
6262            let part = trim_export_part(part);
6263            // A trailing comma leaves an empty final entry; it
6264            // carries no name and must not fail the list.
6265            if part.is_empty() {
6266                continue;
6267            }
6268            let (kind, rest) = split_export_prefix(part);
6269            let is_const = matches!(&kind, TokKind::Word(w) if w == KEYWORD_CONST);
6270            let is_type = matches!(&kind, TokKind::Word(w) if w == KEYWORD_TYPE);
6271            // Exactly one name per entry (entries never trail).
6272            let Some((name, used)) = parse_export_name(rest, 0, is_const, stmt)? else {
6273                return Ok(None);
6274            };
6275            if used != rest.len() {
6276                return Ok(None);
6277            }
6278            if is_const {
6279                const_names.push(name);
6280            } else if is_type {
6281                type_names.push(name);
6282            } else {
6283                func_names.push(name);
6284            }
6285        }
6286        if func_names.is_empty() && type_names.is_empty() && const_names.is_empty() {
6287            return Ok(None);
6288        }
6289        return Ok(Some((
6290            ExportNames {
6291                func_names,
6292                type_names,
6293                const_names,
6294            },
6295            2,
6296        )));
6297    }
6298    if matches!(&next.kind, TokKind::Group { .. }) {
6299        return Ok(None);
6300    }
6301    // Bare name (greedy `::` prefix; trailing loops outside). Bare
6302    // stays func for back-compat; `TYPE`/`FUNC` prefix selects above.
6303    // Func names never take `$`: `EXPORT $X` errors inside
6304    // `parse_export_name`, exactly like a `$`-less read elsewhere.
6305    match parse_export_name(toks, pos + 1, false, stmt)? {
6306        Some((name, used)) => Ok(Some((
6307            ExportNames {
6308                func_names: vec![name],
6309                type_names: Vec::new(),
6310                const_names: Vec::new(),
6311            },
6312            1 + used,
6313        ))),
6314        None => Ok(None),
6315    }
6316}
6317
6318/// Trim leading/trailing newlines around one `EXPORT` bracket entry.
6319/// Single owner so the explicit-prefix and mixed-list loops cannot
6320/// drift on trailing-comma handling.
6321fn trim_export_part(part: &[Tok]) -> &[Tok] {
6322    let mut part = part;
6323    while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
6324        part = &part[1..];
6325    }
6326    while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
6327        part = &part[..part.len() - 1];
6328    }
6329    part
6330}
6331
6332/// Split one mixed-list `EXPORT` entry into its kind prefix and name
6333/// slice. `TYPE`/`FUNC`/`CONST` plus a gapped name selects the kind;
6334/// anything else defaults to `FUNC`. Single owner so both bracket
6335/// loops agree on prefix parsing.
6336fn split_export_prefix(part: &[Tok]) -> (TokKind, &[Tok]) {
6337    // Optional per-entry `TYPE`/`FUNC`/`CONST` prefix for mixed
6338    // lists: `EXPORT [TYPE A, FUNC B, CONST $C, D]` (bare stays
6339    // func, `CONST` entries require `$`). The name must be `sep`
6340    // from the prefix; the prefix itself may be joint to a
6341    // preceding `[` or `,`, so only the name's joint flag matters.
6342    match part {
6343        [first, second, ..]
6344            if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_TYPE || w == KEYWORD_FUNC || w == KEYWORD_CONST)
6345                && !second.joint =>
6346        {
6347            (first.kind.clone(), &part[1..])
6348        }
6349        _ => (TokKind::Word(KEYWORD_FUNC.to_string()), part),
6350    }
6351}
6352
6353/// Split bracket inner tokens on top-level commas, preserving entries
6354/// for per-entry `TYPE`/`FUNC` handling. Newlines trim at the caller.
6355fn split_bracket_entries(inner: &[Tok]) -> Vec<&[Tok]> {
6356    let mut parts: Vec<&[Tok]> = Vec::new();
6357    let mut start = 0;
6358    for (i, tok) in inner.iter().enumerate() {
6359        if matches!(&tok.kind, TokKind::Punct(',')) {
6360            parts.push(&inner[start..i]);
6361            start = i + 1;
6362        }
6363    }
6364    parts.push(&inner[start..]);
6365    parts
6366}
6367
6368/// First comment token inside a bracket name list, if any. Single
6369/// owner for the shared `IMPORT`/`EXPORT` bracket rule (newlines ok,
6370/// comments miss): every bracket-list entry loop consults this
6371/// before treating the list as a shape miss, so the failure names
6372/// and points at the comment instead of falling through to the
6373/// generic statement error. Recurses into nested groups so
6374/// selective-harvest `[[...]]` entries report the same way through
6375/// the one key. Callers stamp the returned token's coordinates onto
6376/// the error (`stamp_pos` never overwrites real positions).
6377fn find_bracket_comment(inner: &[Tok]) -> Option<&Tok> {
6378    inner.iter().find_map(|t| match &t.kind {
6379        TokKind::Comment(_) => Some(t),
6380        TokKind::Group { inner, .. } => find_bracket_comment(inner),
6381        _ => None,
6382    })
6383}
6384
6385/// `TYPE NAME = SHAPE` at `pos`: uppercase name, single `=`, maximal
6386/// type-tag shape canonicalized through the shared spelling.
6387/// Returns the alias plus tokens consumed, or `None` on shape miss
6388/// (generic fails it in lowering like the grammar).
6389fn parse_type_stmt_at(
6390    toks: &[Tok],
6391    pos: usize,
6392    stmt: usize,
6393) -> Result<Option<(StepKind, usize)>, TokenError> {
6394    let name = match toks.get(pos + 1).map(|t| &t.kind) {
6395        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
6396        _ => return Ok(None),
6397    };
6398    // Single `=` at any gap (`gap` zero-width); `==` misses.
6399    if !matches!(
6400        toks.get(pos + 2).map(|t| &t.kind),
6401        Some(TokKind::Punct('='))
6402    ) {
6403        return Ok(None);
6404    }
6405    if matches!(
6406        toks.get(pos + 3).map(|t| &t.kind),
6407        Some(TokKind::Punct('='))
6408    ) {
6409        return Ok(None);
6410    }
6411    let Some(end) = parse_type_shape(toks, pos + 3) else {
6412        return Ok(None);
6413    };
6414    // Post-match the span holds words, puncts, and default literals
6415    // only, so the shared renderer cannot fail; stay failed regardless.
6416    let target = render_type_region(&toks[pos + 3..end], stmt).unwrap_or_default();
6417    Ok(Some((StepKind::TypeAlias { name, target }, end - pos)))
6418}
6419
6420/// Single (non-block) `REMOTE`: target, optional bindings, block.
6421/// The target reads a maximal joint run in the grammar's superset
6422/// charset (misses fall to generic); strict validity fails loudly
6423/// with the exact backend message. Bindings miss to generic;
6424/// empty/missing bodies and nesting violations fail loudly.
6425fn parse_remote_single(
6426    toks: &[Tok],
6427    pos: usize,
6428    stmt: usize,
6429    ctx: &ParseCtx,
6430) -> Result<Option<(StepKind, usize)>, TokenError> {
6431    let fail = |msg: String| TokenError {
6432        diagnostic: None,
6433        hint: None,
6434        stmt,
6435        msg,
6436        line: 0,
6437        col: 0,
6438        kind: Some(ParseErrorKind::Validation {
6439            command: KEYWORD_REMOTE.to_string(),
6440        }),
6441    };
6442    // Target: joint run in the superset charset (alnum/`_`/`-`/`.`/`:`).
6443    // Anything else (joint or not) ends the run; an empty run misses
6444    // to generic. (`sep` needs no explicit check: a joint `(` is a
6445    // call routed before this ever runs, and anything unparseable
6446    // misses the same way.)
6447    let mut target = String::new();
6448    let mut p = pos + 1;
6449    while let Some(t) = toks.get(p) {
6450        if !t.joint && !target.is_empty() {
6451            break;
6452        }
6453        match &t.kind {
6454            TokKind::Word(w)
6455                if w.chars().all(|c| {
6456                    c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' || c == ':'
6457                }) =>
6458            {
6459                // Words arrive whole from the lexer; a bad word ends
6460                // the run (never partially appends), like the grammar.
6461                target.push_str(w);
6462                p += 1;
6463            }
6464            TokKind::Punct(c)
6465                if matches!(c, '_' | '-' | '.' | ':') && (target.is_empty() || t.joint) =>
6466            {
6467                target.push(*c);
6468                p += 1;
6469            }
6470            _ => break,
6471        }
6472    }
6473    if target.is_empty() {
6474        return Ok(None);
6475    }
6476    if !crate::commands::is_valid_remote_target(&target) {
6477        return Err(fail(format!(
6478            "invalid REMOTE target `{target}`: start alphanumeric, then alphanumeric, `_`, or `-`, max 64 chars, never SNAPSHOT, LOCAL, CACHE, SYSTEM, or REMOTE"
6479        )));
6480    }
6481    // Optional bindings `[$var, env:KEY]` at any gap (even joint,
6482    // probed); malformed bindings miss the whole shape to generic.
6483    let mut vars = Vec::new();
6484    let mut env = Vec::new();
6485    if let Some(bracket) = toks.get(p)
6486        && matches!(
6487            &bracket.kind,
6488            TokKind::Group {
6489                delim: GroupDelim::Bracket,
6490                ..
6491            }
6492        )
6493    {
6494        let inner = match &bracket.kind {
6495            TokKind::Group { inner, .. } => inner.clone(),
6496            _ => unreachable!(),
6497        };
6498        match parse_remote_bindings(&inner, stmt, ctx)? {
6499            Some((v, e)) => {
6500                vars = v;
6501                env = e;
6502            }
6503            None => return Ok(None),
6504        }
6505        p += 1;
6506    }
6507    // Block required (any gap, never a template); missing blocks
6508    // miss to generic.
6509    let block_ok = matches!(
6510        toks.get(p).map(|t| &t.kind),
6511        Some(TokKind::Group {
6512            delim: GroupDelim::Brace,
6513            ..
6514        })
6515    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
6516    if !block_ok {
6517        return Ok(None);
6518    }
6519    let inner = match &toks[p].kind {
6520        TokKind::Group { inner, .. } => inner.clone(),
6521        _ => unreachable!(),
6522    };
6523    let body = parse_body_steps(&inner, stmt, ctx, false)?;
6524    p += 1;
6525    if body.is_empty() {
6526        return Err(fail(format!(
6527            "{KEYWORD_REMOTE} requires a non-empty braced block"
6528        )));
6529    }
6530    if crate::commands::contains_remote_block(&body) {
6531        return Err(fail(format!(
6532            "REMOTE blocks cannot nest (target `{target}` contains another REMOTE block)"
6533        )));
6534    }
6535    if body
6536        .iter()
6537        .any(|s| crate::commands::contains_inherit_env(&s.kind))
6538    {
6539        return Err(fail(format!(
6540            "{KEYWORD_INHERIT_ENV} cannot appear inside a {KEYWORD_REMOTE} block: the guest inherits its own process environment"
6541        )));
6542    }
6543    // Outer-function containment (same rule as the shared remote
6544    // validators): body calls resolving to visible
6545    // outer `SCRIPT` defs (without same-body definitions) fail.
6546    {
6547        let mut inner_defs = HashSet::new();
6548        let mut calls = Vec::new();
6549        crate::commands::collect_remote_body_symbols(&body, &mut inner_defs, &mut calls);
6550        let outer_defs: HashSet<String> = ctx.funcs.borrow().iter().flatten().cloned().collect();
6551        for call in &calls {
6552            let bare = crate::constants::base_name(call);
6553            let is_script_call = match crate::constants::split_qualified(call) {
6554                Some((module, _)) => module == crate::constants::SCRIPT_MODULE_NAME,
6555                None => true,
6556            };
6557            if is_script_call && outer_defs.contains(bare) && !inner_defs.contains(bare) {
6558                return Err(fail(format!(
6559                    "REMOTE '{target}' calls outer function '{bare}' (functions must be defined inside the block)"
6560                )));
6561            }
6562        }
6563    }
6564    Ok(Some((
6565        StepKind::RemoteBlock {
6566            target,
6567            vars,
6568            env,
6569            body,
6570        },
6571        p - pos,
6572    )))
6573}
6574// ---- LET/SET/RETURN + expressions ----
6575// Expression tiers over [`Tok`] implement the precedence chain
6576// (or > and > comparison > ordering > add > mul > unary > atom);
6577// arithmetic/comparison lowering runs through the shared constructors
6578// (`make_arith`, `make_compare`, `apply_unary_neg`), so folding, RPN
6579// compilation, and overflow behavior are identical by construction,
6580// never re-derived.
6581
6582/// Eat a one- or two-char operator: single puncts match directly;
6583/// pairs (`==`, `!=`, `<=`, `>=`, `&&`, `||`, `::`) require a joint
6584/// second punct. Newlines never skip here (expression mode).
6585fn eat_op(cur: &mut Cursor, first: char, second: Option<char>) -> bool {
6586    // Gaps (comments included) are skipped before every operator.
6587    cur.skip_gap();
6588    let (a, b) = match (cur.toks.get(cur.pos), cur.toks.get(cur.pos + 1)) {
6589        (Some(a), b) => (a, b),
6590        _ => return false,
6591    };
6592    if !matches!(&a.kind, TokKind::Punct(c) if *c == first) {
6593        return false;
6594    }
6595    match second {
6596        None => {
6597            cur.pos += 1;
6598            true
6599        }
6600        Some(c2) => match b {
6601            Some(t) if t.joint && matches!(&t.kind, TokKind::Punct(c) if *c == c2) => {
6602                cur.pos += 2;
6603                true
6604            }
6605            _ => false,
6606        },
6607    }
6608}
6609
6610/// Dummy span for the shared lowering constructors: v2 owns no source
6611/// positions yet, so only success values (span-free) participate in
6612/// parity; failures surface through [`TokenError`] text.
6613fn lowering_ctx(stmt: usize) -> SpanContext<'static> {
6614    let _ = stmt;
6615    SpanContext::line_only(0)
6616}
6617
6618fn parse_expr_or(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6619    let mut left = parse_expr_and(cur, ctx)?;
6620    while eat_op(cur, '|', Some('|')) {
6621        cur.skip_gap();
6622        let right = parse_expr_and(cur, ctx)?;
6623        // No folding, no boundary checks: unfused literal runs stay
6624        // literal here.
6625        left = Expr::Logical {
6626            op: LogicalOp::Or,
6627            left: Box::new(left),
6628            right: Box::new(right),
6629        };
6630    }
6631    Ok(left)
6632}
6633
6634fn parse_expr_and(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6635    let mut left = parse_expr_cmp(cur, ctx)?;
6636    while eat_op(cur, '&', Some('&')) {
6637        cur.skip_gap();
6638        let right = parse_expr_cmp(cur, ctx)?;
6639        reject_boundary(&lowering_ctx(cur.stmt), &left).map_err(|e| cur.err(e.to_string()))?;
6640        reject_boundary(&lowering_ctx(cur.stmt), &right).map_err(|e| cur.err(e.to_string()))?;
6641        left = Expr::Logical {
6642            op: LogicalOp::And,
6643            left: Box::new(left),
6644            right: Box::new(right),
6645        };
6646    }
6647    Ok(left)
6648}
6649
6650fn parse_expr_cmp(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6651    let left = parse_expr_ord(cur, ctx)?;
6652    let op = if eat_op(cur, '=', Some('=')) {
6653        CompareOp::Eq
6654    } else if eat_op(cur, '!', Some('=')) {
6655        CompareOp::Ne
6656    } else {
6657        return Ok(left);
6658    };
6659    cur.skip_gap();
6660    let right = parse_expr_ord(cur, ctx)?;
6661    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
6662        .map_err(|e| cur.err(e.to_string()))?;
6663    reject_chained_compare(cur, false)?;
6664    Ok(expr)
6665}
6666
6667/// Reject a comparison operator trailing a complete comparison:
6668/// no grammar position continues with one, so the shape always fails —
6669/// loudly here instead of stranding text for a confusing downstream
6670/// error. The equality tier rejects all six (`$a == $b == $c`,
6671/// `$a == $b < $c < $d`); the ordering tier rejects ordering only
6672/// (`$a < $b < $c`), since `$a < $b == $c` is a legitimate equality
6673/// over an ordering result. Probes without consuming.
6674fn reject_chained_compare(cur: &mut Cursor, ordering_only: bool) -> Result<(), TokenError> {
6675    let mut probe = Cursor::expr(cur.toks, cur.stmt);
6676    probe.pos = cur.pos;
6677    probe.skip_gap();
6678    let chained = match probe.toks.get(probe.pos).map(|t| &t.kind) {
6679        Some(TokKind::Punct('<' | '>')) => true,
6680        Some(TokKind::Punct('=' | '!')) => !ordering_only,
6681        _ => false,
6682    };
6683    if chained {
6684        return Err(cur
6685            .err("chained comparison operators need explicit parentheses, e.g. `($a < $b) < $c`"));
6686    }
6687    Ok(())
6688}
6689
6690fn parse_expr_ord(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6691    let left = parse_expr_add(cur, ctx)?;
6692    let op = if eat_op(cur, '<', Some('=')) {
6693        CompareOp::Le
6694    } else if eat_op(cur, '>', Some('=')) {
6695        CompareOp::Ge
6696    } else if eat_op(cur, '<', None) {
6697        CompareOp::Lt
6698    } else if eat_op(cur, '>', None) {
6699        CompareOp::Gt
6700    } else {
6701        return Ok(left);
6702    };
6703    cur.skip_gap();
6704    let right = parse_expr_add(cur, ctx)?;
6705    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
6706        .map_err(|e| cur.err(e.to_string()))?;
6707    reject_chained_compare(cur, true)?;
6708    Ok(expr)
6709}
6710
6711fn parse_expr_add(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6712    let mut left = parse_expr_mul(cur, ctx)?;
6713    loop {
6714        let op = if eat_op(cur, '+', None) {
6715            ArithOp::Add
6716        } else if eat_op(cur, '-', None) {
6717            ArithOp::Sub
6718        } else {
6719            break;
6720        };
6721        cur.skip_gap();
6722        let right = parse_expr_mul(cur, ctx)?;
6723        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
6724            .map_err(|e| cur.err(e.to_string()))?;
6725    }
6726    Ok(left)
6727}
6728
6729fn parse_expr_mul(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6730    let mut left = parse_expr_unary(cur, ctx)?;
6731    loop {
6732        let op = if eat_op(cur, '*', None) {
6733            ArithOp::Mul
6734        } else if eat_op(cur, '/', None) {
6735            ArithOp::Div
6736        } else {
6737            break;
6738        };
6739        cur.skip_gap();
6740        let right = parse_expr_unary(cur, ctx)?;
6741        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
6742            .map_err(|e| cur.err(e.to_string()))?;
6743    }
6744    Ok(left)
6745}
6746
6747/// A `-` opens a bare word (never negation) when gaplessly followed by
6748/// a letter, `_`, or `/` — the `neg_op` lookahead, read off `joint`.
6749fn dash_is_bare(cur: &Cursor) -> bool {
6750    let next = cur.toks.get(cur.pos + 1);
6751    match next {
6752        Some(t) if t.joint => match &t.kind {
6753            TokKind::Word(w) => w
6754                .chars()
6755                .next()
6756                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_'),
6757            TokKind::Punct('/') => true,
6758            _ => false,
6759        },
6760        _ => false,
6761    }
6762}
6763
6764fn parse_expr_unary(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6765    let mut prefixes = Vec::new();
6766    loop {
6767        match cur.toks.get(cur.pos).map(|t| &t.kind) {
6768            Some(TokKind::Punct('!')) => {
6769                cur.pos += 1;
6770                // Each prefix is gap-separated.
6771                cur.skip_gap();
6772                prefixes.push(false);
6773            }
6774            Some(TokKind::Punct('-')) if !dash_is_bare(cur) => {
6775                cur.pos += 1;
6776                cur.skip_gap();
6777                prefixes.push(true);
6778            }
6779            _ => break,
6780        }
6781    }
6782    let mut expr = parse_expr_atom(cur, ctx)?;
6783    // Innermost prefix is closest to the atom: apply in reverse order.
6784    for is_neg in prefixes.into_iter().rev() {
6785        if is_neg {
6786            expr = apply_unary_neg(&lowering_ctx(cur.stmt), expr)
6787                .map_err(|e| cur.err(e.to_string()))?;
6788        } else {
6789            reject_boundary(&lowering_ctx(cur.stmt), &expr).map_err(|e| cur.err(e.to_string()))?;
6790            expr = Expr::Not(Box::new(expr));
6791        }
6792    }
6793    Ok(expr)
6794}
6795
6796/// Identifier charset for `$var` and `.segment` parts. Segments admit
6797/// digits-only too (`$a.0`); anything else ends the key path and errors
6798/// downstream, like the grammar's backtrack to `variable`.
6799fn is_ident_word(w: &str) -> bool {
6800    !w.is_empty() && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
6801}
6802
6803/// One joint `::NAME` tail at `pos` (the first `:`): both colons and
6804/// the name ride gapless, and the name matches [`is_ident_word`].
6805/// Single owner for qualified-`$ALIAS::NAME` matching, so `$` arms
6806/// and bare-word diagnostics cannot drift on jointness or charset.
6807fn match_joint_qualified(toks: &[Tok], pos: usize) -> Option<String> {
6808    let first = matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct(':')))
6809        && toks.get(pos).is_some_and(|t| t.joint);
6810    let second = matches!(
6811        toks.get(pos + 1).map(|t| &t.kind),
6812        Some(TokKind::Punct(':'))
6813    ) && toks.get(pos + 1).is_some_and(|t| t.joint);
6814    let name_tok = toks.get(pos + 2);
6815    let ok = first
6816        && second
6817        && matches!(name_tok.map(|t| &t.kind), Some(TokKind::Word(w)) if is_ident_word(w))
6818        && name_tok.is_some_and(|t| t.joint);
6819    if !ok {
6820        return None;
6821    }
6822    match &name_tok.expect("checked").kind {
6823        TokKind::Word(w) => Some(w.clone()),
6824        _ => unreachable!(),
6825    }
6826}
6827
6828fn is_key_segment(w: &str) -> bool {
6829    crate::template::is_key_segment_str(w)
6830}
6831
6832/// Single owner for gapless `.key` segment consumption after a `$`
6833/// read (qualified `$ALIAS::NAME` or bare `$base`): advances `cur`
6834/// past every joint `.segment` pair. A joint dot with no valid joint
6835/// key segment after it fails closed instead of leaking the raw `.`
6836/// into surrounding parsing. `root` names the consumed read for the
6837/// error (the full `$ALIAS::NAME[.keys]` or `$base[.keys]` path built
6838/// so far, extended with each consumed key).
6839fn parse_joint_key_segments(cur: &mut Cursor, root: &str) -> Result<Vec<String>, TokenError> {
6840    let mut keys: Vec<String> = Vec::new();
6841    loop {
6842        let dot = matches!(
6843            cur.toks.get(cur.pos).map(|t| &t.kind),
6844            Some(TokKind::Punct(KEY_PATH_SEPARATOR_CHAR))
6845        ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
6846        if !dot {
6847            break;
6848        }
6849        let seg = cur.toks.get(cur.pos + 1);
6850        let seg_ok = matches!(seg.map(|t| &t.kind), Some(TokKind::Word(w)) if is_key_segment(w))
6851            && seg.is_some_and(|t| t.joint);
6852        if !seg_ok {
6853            let mut display = root.to_string();
6854            for key in &keys {
6855                display.push(KEY_PATH_SEPARATOR_CHAR);
6856                display.push_str(key);
6857            }
6858            return Err(cur.err(format!("invalid key segment after {display}")));
6859        }
6860        if let Some(TokKind::Word(w)) = seg.map(|t| &t.kind) {
6861            keys.push(w.clone());
6862        }
6863        cur.pos += 2;
6864    }
6865    Ok(keys)
6866}
6867
6868fn is_env_key(w: &str) -> bool {
6869    !w.is_empty()
6870        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
6871        && w.chars()
6872            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
6873}
6874
6875/// Maximal joint run of words and `-/.'/'` puncts: the bare-word
6876/// shape (which admits `/` anywhere, so `//c`, `/a`, `a/b`, and the
6877/// `/`-`c`-`/` operands of `/*c*/` math all read literally here).
6878/// Callers classify (`true`/`false`/string); the numeric path
6879/// runs first and falls back here on shape/follower mismatch.
6880/// Backslash escapes are arg-position syntax: the bare-word shape admits
6881/// no `\`, so expression runs containing one fail here (never drift
6882/// into a string the grammar rejects).
6883fn expr_bare_run(cur: &mut Cursor, leading_dash: bool) -> Result<String, TokenError> {
6884    let mut out = String::new();
6885    if leading_dash {
6886        match cur.next() {
6887            Some(t) if matches!(&t.kind, TokKind::Punct('-')) => out.push('-'),
6888            _ => return Err(cur.err("missing expression operand")),
6889        }
6890    }
6891    match cur.next() {
6892        Some(t) => match &t.kind {
6893            TokKind::Word(w) => out.push_str(w),
6894            // Leading `/` (operand position only; operators are
6895            // consumed by the tiers before operands parse).
6896            TokKind::Punct('/') => out.push('/'),
6897            _ => return Err(cur.err("missing expression operand")),
6898        },
6899        None => return Err(cur.err("missing expression operand")),
6900    }
6901    loop {
6902        let next = match cur.toks.get(cur.pos) {
6903            Some(t) if t.joint => t,
6904            _ => break,
6905        };
6906        match &next.kind {
6907            TokKind::Word(w) => {
6908                // Abutting words only continue through an operator gap
6909                // the tiers own (`a -b` never fuses); without a joint
6910                // punct between, stop. Since this token IS joint, the
6911                // previous token must have been a bare punct.
6912                out.push_str(w);
6913                cur.pos += 1;
6914            }
6915            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
6916                out.push(*c);
6917                cur.pos += 1;
6918            }
6919            _ => break,
6920        }
6921    }
6922    if out.contains('\\') {
6923        return Err(cur.err("unexpected escape in expression"));
6924    }
6925    Ok(out)
6926}
6927
6928/// Numeric literal head: digit-led word plus joint `.digits` tails.
6929/// Callers apply the separator-shape gate and the follower rule, then
6930/// the shared classifier.
6931fn number_head(cur: &mut Cursor) -> Option<String> {
6932    let first = match cur.toks.get(cur.pos).map(|t| &t.kind) {
6933        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => w.clone(),
6934        _ => return None,
6935    };
6936    let mut text = first;
6937    let mut pos = cur.pos + 1;
6938    loop {
6939        let dot = matches!(
6940            cur.toks.get(pos).map(|t| &t.kind),
6941            Some(TokKind::Punct('.'))
6942        ) && cur.toks.get(pos).is_some_and(|t| t.joint);
6943        let digits = cur.toks.get(pos + 1);
6944        let digits_ok = dot
6945            && matches!(digits.map(|t| &t.kind), Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_'))
6946            && digits.is_some_and(|t| t.joint);
6947        if !digits_ok {
6948            break;
6949        }
6950        text.push('.');
6951        if let Some(TokKind::Word(w)) = digits.map(|t| &t.kind) {
6952            text.push_str(w);
6953        }
6954        pos += 2;
6955    }
6956    Some(text)
6957}
6958
6959/// `_`-separator shape gate mirroring the `numeric_literal` rule:
6960/// digits with single-underscore separators, at most one fraction.
6961fn numeric_shape_ok(text: &str) -> bool {
6962    let mut parts = text.split('.');
6963    let int_part = parts.next().unwrap_or("");
6964    let frac_part = parts.next();
6965    if parts.next().is_some() {
6966        return false;
6967    }
6968    fn run_ok(s: &str) -> bool {
6969        !s.is_empty()
6970            && s.chars().all(|c| c.is_ascii_digit() || c == '_')
6971            && !s.starts_with('_')
6972            && !s.ends_with('_')
6973            && !s.contains("__")
6974    }
6975    run_ok(int_part) && frac_part.is_none_or(run_ok)
6976}
6977
6978/// Follower rule mirroring the `numeric_literal` trailing guard
6979/// (`!(ALNUM | "_" | "." | "/")`): a joint word, `.`, or `/` continues
6980/// into a bare word (`30s`, `1.`, `4/2`); `-`/`+`/operators let the
6981/// number stand for the tiers (`1-2` is `Sub`, like the grammar).
6982fn number_falls_to_bare(cur: &Cursor, consumed: usize) -> bool {
6983    match cur.toks.get(cur.pos + consumed) {
6984        Some(t) if t.joint => matches!(
6985            &t.kind,
6986            TokKind::Word(_) | TokKind::Punct('.') | TokKind::Punct('/')
6987        ),
6988        _ => false,
6989    }
6990}
6991
6992fn parse_expr_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6993    match cur.toks.get(cur.pos).map(|t| &t.kind) {
6994        Some(TokKind::Group {
6995            delim: GroupDelim::Paren,
6996            inner,
6997            ..
6998        }) => {
6999            let inner = inner.clone();
7000            cur.pos += 1;
7001            let mut sub = Cursor::expr(&inner, cur.stmt);
7002            sub.skip_gap_nl();
7003            let expr = parse_expr_or(&mut sub, ctx)?;
7004            sub.skip_gap_nl();
7005            if !sub.done() {
7006                return Err(sub.err("unexpected text in parentheses"));
7007            }
7008            Ok(expr)
7009        }
7010        Some(TokKind::Word(_)) if call_shape_at(cur.toks, cur.pos, false).is_some() => {
7011            let (name, paren) =
7012                call_shape_at(cur.toks, cur.pos, false).ok_or_else(|| cur.err("unreachable"))?;
7013            let inner = match &cur.toks[paren].kind {
7014                TokKind::Group { inner, .. } => inner.clone(),
7015                _ => unreachable!(),
7016            };
7017            cur.pos = paren + 1;
7018            parse_expr_call(name, &inner, cur.stmt, ctx)
7019        }
7020        Some(TokKind::Punct(VAR_SIGIL_CHAR)) => {
7021            cur.pos += 1;
7022            // Atomic `variable`: `$` and the name ride gapless (the
7023            // enclosing rules are compound-atomic).
7024            let base = match cur.next() {
7025                Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
7026                    match &t.kind {
7027                        TokKind::Word(w) => w.clone(),
7028                        _ => unreachable!(),
7029                    }
7030                }
7031                _ => return Err(cur.err("`$` requires a variable name")),
7032            };
7033            // Qualified immutable read (`$ALIAS::NAME[.key]`): key paths
7034            // traverse the resolved CONST exactly like `$base.key`.
7035            if let Some(name) = match_joint_qualified(cur.toks, cur.pos) {
7036                cur.pos += 3;
7037                let root = sigil_qualified(&base, &name);
7038                let keys = parse_joint_key_segments(&mut *cur, &root)?;
7039                return Ok(Expr::ConstRef {
7040                    alias: base,
7041                    name,
7042                    keys,
7043                });
7044            }
7045            let root = sigil_var(&base);
7046            let keys = parse_joint_key_segments(&mut *cur, &root)?;
7047            if keys.is_empty() {
7048                Ok(Expr::Var { name: base })
7049            } else {
7050                Ok(Expr::KeyPath { base, keys })
7051            }
7052        }
7053        Some(TokKind::Word(w)) if w == "env" => {
7054            // `env:KEY` read when the full shape matches gaplessly
7055            // (atomic `env_read`); otherwise a bare word (`env` alone,
7056            // `env:k` lowercase) for the error path, exactly like the
7057            // grammar's mismatch.
7058            let key_ok = matches!(
7059                cur.toks.get(cur.pos + 1).map(|t| &t.kind),
7060                Some(TokKind::Punct(':'))
7061            ) && cur.toks.get(cur.pos + 1).is_some_and(|t| t.joint)
7062                && matches!(
7063                    cur.toks.get(cur.pos + 2).map(|t| &t.kind),
7064                    Some(TokKind::Word(k)) if is_env_key(k)
7065                )
7066                && cur.toks.get(cur.pos + 2).is_some_and(|t| t.joint);
7067            if !key_ok {
7068                return parse_bare_atom(cur, ctx, false);
7069            }
7070            cur.pos += 1;
7071            cur.pos += 1;
7072            match cur.next() {
7073                Some(t) => match &t.kind {
7074                    TokKind::Word(k) => Ok(Expr::Env(k.clone())),
7075                    _ => Err(cur.err("unreachable")),
7076                },
7077                None => Err(cur.err("unreachable")),
7078            }
7079        }
7080        Some(TokKind::Group {
7081            delim: GroupDelim::Bracket,
7082            inner,
7083            ..
7084        }) => {
7085            let inner = inner.clone();
7086            cur.pos += 1;
7087            parse_list_literal(&inner, cur.stmt, ctx)
7088        }
7089        Some(TokKind::Group {
7090            delim: GroupDelim::Brace,
7091            inner,
7092            ..
7093        }) => {
7094            let inner = inner.clone();
7095            cur.pos += 1;
7096            parse_map_or_block(&inner, cur.stmt, ctx)
7097        }
7098        Some(TokKind::Str { text, .. }) => {
7099            let text = text.clone();
7100            cur.pos += 1;
7101            Ok(Expr::Literal(Value::string(text)))
7102        }
7103        Some(TokKind::BlockStr(full)) => {
7104            let full = full.clone();
7105            cur.pos += 1;
7106            Ok(Expr::Literal(Value::string(
7107                crate::command::lower_block_string(&full),
7108            )))
7109        }
7110        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => {
7111            parse_numeric_atom(cur, ctx)
7112        }
7113        Some(TokKind::Word(_)) => {
7114            // Bare `ALIAS::NAME` never reads: without the `$` sigil
7115            // there is no qualified shape, only a bare word followed
7116            // by stray punctuation. Name the `$` form instead of
7117            // stranding the reader on the colons.
7118            if let Some(TokKind::Word(base)) = cur.toks.get(cur.pos).map(|t| &t.kind)
7119                && is_ident_word(base)
7120                && let Some(name) = match_joint_qualified(cur.toks, cur.pos + 1)
7121            {
7122                let base = base.clone();
7123                return Err(cur.err(crate::template::bare_sigil_error(&qualify(&base, &name))));
7124            }
7125            parse_bare_atom(cur, ctx, false)
7126        }
7127        Some(TokKind::Punct('-')) => parse_bare_atom(cur, ctx, true),
7128        Some(TokKind::Punct('/')) => parse_bare_atom(cur, ctx, false),
7129        _ => Err(cur.err("missing expression operand")),
7130    }
7131}
7132
7133/// Bare-word atom with a `-` lead (the caller proved it is not
7134/// negation): consumes the joint `-/.'/'` run for the bare-word
7135/// shape.
7136fn parse_bare_atom(
7137    cur: &mut Cursor,
7138    _ctx: &ParseCtx,
7139    leading_dash: bool,
7140) -> Result<Expr, TokenError> {
7141    let text = expr_bare_run(cur, leading_dash)?;
7142    match text.as_str() {
7143        "true" => Ok(Expr::Literal(Value::bool(true))),
7144        "false" => Ok(Expr::Literal(Value::bool(false))),
7145        _ => Ok(Expr::Literal(Value::string(text))),
7146    }
7147}
7148
7149/// Numeric atom: rejoin dotted tails, apply the shape gate and the
7150/// follower rule, then the shared classifier. Anything failing the
7151/// gate or follower reparses as a bare word (durations, versions,
7152/// paths), exactly like the grammar's numeric-literal-or-bare-word
7153/// order.
7154fn parse_numeric_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7155    let start = cur.pos;
7156    let text = number_head(cur).ok_or_else(|| cur.err("missing expression operand"))?;
7157    let consumed = {
7158        let mut n = 1;
7159        let mut p = start + 1;
7160        while matches!(cur.toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('.')))
7161            && cur.toks.get(p).is_some_and(|t| t.joint)
7162            && matches!(
7163                cur.toks.get(p + 1).map(|t| &t.kind),
7164                Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_')
7165            )
7166            && cur.toks.get(p + 1).is_some_and(|t| t.joint)
7167        {
7168            n += 2;
7169            p += 2;
7170        }
7171        n
7172    };
7173    if !numeric_shape_ok(&text) || number_falls_to_bare(cur, consumed) {
7174        return parse_bare_atom(cur, ctx, false);
7175    }
7176    cur.pos += consumed;
7177    classify_numeric_text(&text).map_err(|msg| cur.err(msg))
7178}
7179
7180/// Full expression with the top-level boundary rejection (mirrors
7181/// `parse_expr`): a stray `UnsignedIntBoundary` that no unary `-`
7182/// consumed is an overflow error.
7183fn parse_expr_checked(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7184    let expr = parse_expr_or(cur, ctx)?;
7185    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
7186        return Err(cur.err("integer overflow: 9223372036854775808 exceeds i64::MAX"));
7187    }
7188    Ok(expr)
7189}
7190
7191/// List literal over a bracket group's contents: the shared bracket
7192/// core (see [`parse_bracket_list`]) in `Expr` mode. Expression
7193/// positions fail loudly instead of missing, so `None` is unreachable.
7194fn parse_list_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7195    parse_bracket_list(inner, stmt, ctx, BracketItems::Expr)
7196        .map(|list| list.expect("expression lists fail loudly, never miss"))
7197}
7198
7199/// Map literal attempt over a brace group's contents: comma-separated
7200/// `key: value` entries with `gap` (never newline) around the colon.
7201/// Any entry failing the shape is not a map: the caller reports the
7202/// deferred block slice (the grammar tries `block` next, which fails
7203/// the same inputs at this stage).
7204/// Marker message for a map entry run that ends without a comma
7205/// where another entry follows. Matched by exact equality in
7206/// [`parse_map_or_block`], never by prefix, so wording changes stay
7207/// local to this const and its one reader.
7208const MISSING_MAP_COMMA_MSG: &str = "missing comma between map entries";
7209
7210fn parse_map_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7211    let mut entries = Vec::new();
7212    // Empty (or blank/comment-only) braces are an empty map.
7213    if inner
7214        .iter()
7215        .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
7216    {
7217        return Ok(Expr::Map(vec![]));
7218    }
7219    for part in split_top_commas(inner) {
7220        let mut sub = Cursor::expr(part, stmt);
7221        sub.skip_gap_nl();
7222        let (key, val) = parse_map_entry(&mut sub, ctx, stmt)?;
7223        sub.skip_gap_nl();
7224        if !sub.done() {
7225            return Err(map_trailing_error(&sub, ctx, stmt));
7226        }
7227        entries.push((key, val));
7228    }
7229    Ok(Expr::Map(entries))
7230}
7231
7232/// One `key: value` map entry: string, block-string, or bare key,
7233/// a colon, then a full checked expression. Every failure reads
7234/// `not a map literal` exactly like the old inline loop, so only
7235/// the trailing rule changes the surface.
7236fn parse_map_entry(
7237    sub: &mut Cursor,
7238    ctx: &ParseCtx,
7239    stmt: usize,
7240) -> Result<(String, Expr), TokenError> {
7241    let key = match sub.toks.get(sub.pos).map(|t| &t.kind) {
7242        Some(TokKind::Str { text, .. }) => {
7243            let key = text.clone();
7244            sub.pos += 1;
7245            key
7246        }
7247        Some(TokKind::BlockStr(full)) => {
7248            let key = crate::command::lower_block_string(full);
7249            sub.pos += 1;
7250            key
7251        }
7252        Some(TokKind::Word(_)) | Some(TokKind::Punct('-')) | Some(TokKind::Punct('/')) => {
7253            map_bare_key(sub)?
7254        }
7255        _ => return Err(sub.err("not a map literal")),
7256    };
7257    sub.skip_gap();
7258    if !sub.eat_punct(':') {
7259        return Err(sub.err("not a map literal"));
7260    }
7261    let val = parse_expr_checked(sub, ctx)?;
7262    reject_boundary(&lowering_ctx(stmt), &val).map_err(|e| sub.err(e.to_string()))?;
7263    Ok((key, val))
7264}
7265
7266/// Trailing content after a complete map entry: stamps the
7267/// offending token and names the likely missing comma when the
7268/// remainder parses as another entry. Anything else keeps the old
7269/// `not a map literal` text. Error-path only.
7270fn map_trailing_error(sub: &Cursor, ctx: &ParseCtx, stmt: usize) -> TokenError {
7271    let (line, col) = sub
7272        .toks
7273        .get(sub.pos)
7274        .map(|t| (t.line, t.col))
7275        .unwrap_or((0, 0));
7276    let mut probe = Cursor::expr(&sub.toks[sub.pos.min(sub.toks.len())..], stmt);
7277    probe.skip_gap_nl();
7278    if parse_map_entry(&mut probe, ctx, stmt).is_ok() {
7279        return TokenError {
7280            diagnostic: None,
7281            hint: None,
7282            stmt,
7283            line,
7284            col,
7285            msg: MISSING_MAP_COMMA_MSG.to_string(),
7286            kind: None,
7287        };
7288    }
7289    sub.err("not a map literal")
7290}
7291
7292/// Bare map key: joint `-/.'/'`-run, mirroring the bare-word charset
7293/// (no bool/numeric classification: keys are always strings).
7294fn map_bare_key(sub: &mut Cursor) -> Result<String, TokenError> {
7295    let mut out = String::new();
7296    if matches!(
7297        sub.toks.get(sub.pos).map(|t| &t.kind),
7298        Some(TokKind::Punct('-'))
7299    ) {
7300        out.push('-');
7301        sub.pos += 1;
7302    }
7303    // Leading `/` reads literally too (the bare-word shape admits `/`
7304    // anywhere: `{/a: 1}`, `{//c: 1}`); the joint loop below
7305    // continues the run.
7306    if matches!(
7307        sub.toks.get(sub.pos).map(|t| &t.kind),
7308        Some(TokKind::Punct('/'))
7309    ) {
7310        out.push('/');
7311        sub.pos += 1;
7312    }
7313    match sub.toks.get(sub.pos).map(|t| &t.kind) {
7314        Some(TokKind::Word(w)) => {
7315            out.push_str(w);
7316            sub.pos += 1;
7317        }
7318        // A leading `/` above already started the run; anything
7319        // else still needs a word head.
7320        _ if !out.is_empty() => {}
7321        _ => return Err(sub.err("not a map literal")),
7322    }
7323    while let Some(t) = sub.toks.get(sub.pos) {
7324        if !t.joint {
7325            break;
7326        }
7327        match &t.kind {
7328            TokKind::Word(w) => {
7329                out.push_str(w);
7330                sub.pos += 1;
7331            }
7332            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
7333                out.push(*c);
7334                sub.pos += 1;
7335            }
7336            _ => break,
7337        }
7338    }
7339    if out.contains('\\') {
7340        return Err(sub.err("unexpected escape in map key"));
7341    }
7342    Ok(out)
7343}
7344
7345/// Map-or-block over a brace group's contents: maps parse literally;
7346/// anything else is an inline block (`Expr::Block` over the body
7347/// steps, scopes unmarked like every braced body).
7348fn parse_map_or_block(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7349    match parse_map_literal(inner, stmt, ctx) {
7350        Ok(map) => Ok(map),
7351        // A detected missing comma is never a block: its `key:`
7352        // remainder cannot parse as a statement (a `name: "a"` line
7353        // fails as `unknown command`), so the block path can only
7354        // misreport it. Surface the map error instead; every other
7355        // map failure keeps the block fallback exactly as before.
7356        Err(e) if e.msg == MISSING_MAP_COMMA_MSG => Err(e),
7357        Err(_) => Ok(Expr::Block(parse_body_steps(inner, stmt, ctx, false)?)),
7358    }
7359}
7360
7361/// Parse one standalone expression from lexed tokens (the
7362/// `parse_expression_str` entry point): a full tier parse with
7363/// top-level boundary rejection and full consumption.
7364pub(crate) fn parse_single_expr(
7365    toks: &[Tok],
7366    stmt: usize,
7367    ctx: &ParseCtx,
7368) -> Result<Expr, TokenError> {
7369    let mut cur = Cursor::expr(toks, stmt);
7370    let expr = parse_expr_checked(&mut cur, ctx)?;
7371    if !cur.done() {
7372        return Err(cur.err("unexpected text in expression"));
7373    }
7374    Ok(expr)
7375}
7376
7377/// Assignment `=`: the first depth-zero `=` neither glued to a
7378/// following `=` (`==`) nor glued after `!`/`<`/`>`/`=` (`!=`, `<=`,
7379/// `>=`, second of `==`). `<>` shape brackets own any `=` inside
7380/// them (field defaults), so LET annotations with defaults find the
7381/// real assignment. Glued-ness reads off the `=`'s own `joint` (gap
7382/// before it) and the follower's (gap after it). Anything else leaves
7383/// the statement bare (`LET $p: PIPE`), exactly where the grammar's
7384/// `"="` match fails.
7385fn find_assign_eq(body: &[Tok]) -> Option<usize> {
7386    let mut depth = 0usize;
7387    for (i, tok) in body.iter().enumerate() {
7388        match &tok.kind {
7389            TokKind::Punct('<') => depth += 1,
7390            TokKind::Punct('>') if depth > 0 => depth -= 1,
7391            TokKind::Punct('=') if depth == 0 => {
7392                let next_eq = body
7393                    .get(i + 1)
7394                    .is_some_and(|t| t.joint && matches!(&t.kind, TokKind::Punct('=')));
7395                let prev_op = tok.joint
7396                    && i > 0
7397                    && matches!(&body[i - 1].kind, TokKind::Punct('!' | '<' | '>' | '='));
7398                if !next_eq && !prev_op {
7399                    return Some(i);
7400                }
7401            }
7402            _ => {}
7403        }
7404    }
7405    None
7406}
7407
7408/// Render a type region joint-aware (`LIST< MAP >` keeps its gaps for
7409/// the shared canonicalizer, exactly like `type_tag.as_str()`).
7410fn render_type_region(toks: &[Tok], stmt: usize) -> Result<String, TokenError> {
7411    let mut out = String::new();
7412    for tok in toks {
7413        // Ridden newlines from multi-line `<...>` shapes carry no
7414        // output, so the shape canonicalizes exactly like one line.
7415        if matches!(&tok.kind, TokKind::Newline) {
7416            continue;
7417        }
7418        if !tok.joint && !out.is_empty() {
7419            out.push(' ');
7420        }
7421        match &tok.kind {
7422            TokKind::Word(w) => out.push_str(w),
7423            TokKind::Punct(c) => out.push(*c),
7424            TokKind::Str { text, quote } => {
7425                out.push(*quote);
7426                out.push_str(text);
7427                out.push(*quote);
7428            }
7429            TokKind::BlockStr(full) => out.push_str(full),
7430            _ => {
7431                return Err(TokenError {
7432                    diagnostic: None,
7433                    hint: None,
7434                    stmt,
7435                    msg: format!("malformed type in {KEYWORD_LET}"),
7436                    line: 0,
7437                    col: 0,
7438                    kind: None,
7439                });
7440            }
7441        }
7442    }
7443    if out.is_empty() {
7444        return Err(TokenError {
7445            diagnostic: None,
7446            hint: None,
7447            stmt,
7448            msg: format!(
7449                "{KEYWORD_LET} requires explicit type: {KEYWORD_LET} $var: {KEYWORD_TYPE} = <expr>"
7450            ),
7451            line: 0,
7452            col: 0,
7453            kind: None,
7454        });
7455    }
7456    Ok(crate::canonicalize_spelling(&out))
7457}
7458
7459fn expect_dollar_var(cur: &mut Cursor, msg: &str) -> Result<String, TokenError> {
7460    // Atomic `dollar_ident`: no gap between `$` and the name (the
7461    // enclosing statements are compound-atomic, so implicit spacing is
7462    // off and only explicit `gap`s admit whitespace).
7463    match cur.next() {
7464        Some(t) if matches!(&t.kind, TokKind::Punct(VAR_SIGIL_CHAR)) => {}
7465        _ => return Err(cur.err(msg)),
7466    }
7467    match cur.next() {
7468        Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
7469            match &t.kind {
7470                TokKind::Word(w) => Ok(w.clone()),
7471                _ => unreachable!(),
7472            }
7473        }
7474        _ => Err(cur.err(msg)),
7475    }
7476}
7477
7478/// Reject a qualified `$ALIAS::NAME` where a declaration or mutation
7479/// target stands: bindings declare plain locals, and module `CONST`s
7480/// are immutable (reads use `$ALIAS::NAME` in expressions).
7481/// Single owner for the qualified-target gate, shared by the binding
7482/// (`LET`/`CONST`) and reassignment (`$var = <expr>`) heads so all fail
7483/// with one message shape.
7484fn reject_qualified_target(cur: &Cursor, base: &str) -> Result<(), TokenError> {
7485    let first = matches!(
7486        cur.toks.get(cur.pos).map(|t| &t.kind),
7487        Some(TokKind::Punct(':'))
7488    ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
7489    let second = matches!(
7490        cur.toks.get(cur.pos + 1).map(|t| &t.kind),
7491        Some(TokKind::Punct(':'))
7492    ) && cur.toks.get(cur.pos + 1).is_some_and(|t| t.joint);
7493    if first && second {
7494        return Err(cur.err(format!(
7495            "cannot declare or assign ${base}::...: module values read as $ALIAS::NAME in expressions and are never binding targets"
7496        )));
7497    }
7498    Ok(())
7499}
7500
7501/// `LET`/`CONST` body: the keyword is already matched. Returns `None`
7502/// (miss to generic, which fails in lowering like the grammar's
7503/// committed `instruction`) when the shape cannot match any binding
7504/// form: no gapless `$var`, or no `:` after it
7505/// (every form needs `: TYPE`). Past that the shape is committed and
7506/// malformed tails fail loudly. `kw` selects the produced StepKind
7507/// family (`LET` or `CONST`) and the diagnostic spellings.
7508fn parse_let_body(
7509    body: &[Tok],
7510    stmt: usize,
7511    ctx: &ParseCtx,
7512) -> Result<Option<(StepKind, usize)>, TokenError> {
7513    parse_binding_body(body, stmt, ctx, KEYWORD_LET)
7514}
7515
7516/// `CONST` body: same shapes as `LET`, producing the `Const` family.
7517/// Miss semantics mirror [`parse_let_body`].
7518fn parse_const_body(
7519    body: &[Tok],
7520    stmt: usize,
7521    ctx: &ParseCtx,
7522) -> Result<Option<(StepKind, usize)>, TokenError> {
7523    parse_binding_body(body, stmt, ctx, KEYWORD_CONST)
7524}
7525
7526/// Shared `LET`/`CONST` body: the head keyword is already matched.
7527/// `kw` must be `KEYWORD_LET` or `KEYWORD_CONST`. Both take a `$var`
7528/// head; `CONST` additionally requires an uppercase name.
7529/// Single owner for the binding header: the `is_const` flag rides
7530/// straight into [`StepKind::Bind`], so no post-pass flips per form.
7531fn parse_binding_body(
7532    body: &[Tok],
7533    stmt: usize,
7534    ctx: &ParseCtx,
7535    kw: &'static str,
7536) -> Result<Option<(StepKind, usize)>, TokenError> {
7537    use crate::commands::BindRhs;
7538    let is_const = kw == KEYWORD_CONST;
7539    let mut cur = Cursor::expr(body, stmt);
7540    match cur.next() {
7541        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == kw) => {}
7542        _ => return Err(cur.err("unreachable")),
7543    }
7544    // Head: `$var` for both `LET` and `CONST`. `CONST` additionally
7545    // requires an uppercase name (see `validate_const_name`). The
7546    // keyword already committed to a binding, so a malformed head
7547    // fails loudly; only a non-name head misses to generic.
7548    let var = if is_const {
7549        cur.skip_gap();
7550        match cur.toks.get(cur.pos).map(|t| &t.kind) {
7551            Some(TokKind::Punct(VAR_SIGIL_CHAR)) => {
7552                let var = expect_dollar_var(
7553                    &mut cur,
7554                    "CONST requires a `$NAME` head: CONST $NAME: TYPE = ...",
7555                )?;
7556                reject_qualified_target(&cur, &var)?;
7557                validate_const_name(ctx, &cur, &var)?;
7558                var
7559            }
7560            Some(TokKind::Word(_)) => {
7561                return Err(
7562                    cur.err(format!("{KEYWORD_CONST} requires `$`: write {KEYWORD_CONST} $NAME: {KEYWORD_TYPE} = ... (never bare)"))
7563                );
7564            }
7565            _ => return Ok(None),
7566        }
7567    } else {
7568        // No `$var`: no binding form can match (miss, never a hard fail).
7569        let var = match expect_dollar_var(&mut cur, &format!("{kw} requires a variable")) {
7570            Ok(var) => var,
7571            Err(_) => return Ok(None),
7572        };
7573        reject_qualified_target(&cur, &var)?;
7574        var
7575    };
7576    // The header allows gaps (comments, never newlines).
7577    cur.skip_gap();
7578    // No `:`: untyped bindings are rejected outright. Every binding is
7579    // typed; the old miss-to-generic path only hid that behind a
7580    // rambling "invalid syntax" message. (FOR already does this.)
7581    let head_example = if is_const { "$NAME" } else { "$var" };
7582    if !cur.eat_punct(':') {
7583        return Err(TokenError {
7584            diagnostic: None,
7585            hint: None,
7586            stmt,
7587            msg: format!(
7588                "{kw} requires explicit types: {kw} {head_example}: {KEYWORD_TYPE} = <expr>"
7589            ),
7590            line: 0,
7591            col: 0,
7592            kind: Some(ParseErrorKind::InvalidSyntax {
7593                command: kw.to_string(),
7594            }),
7595        });
7596    }
7597    // Type region runs to the depth-zero assignment `=`; `<>`
7598    // shapes own any `=` inside them (field defaults).
7599    let type_start = cur.pos;
7600    let assign = find_assign_eq(&body[type_start..]).map(|i| i + type_start);
7601    let Some(eq) = assign else {
7602        // Bare `$p: PIPE` mints a fresh pipe and ends with the
7603        // type word (trailing elements loop on, probed); every other
7604        // bare type is a validation error, mirroring the grammar.
7605        if matches!(
7606            body.get(type_start).map(|t| &t.kind),
7607            Some(TokKind::Word(w)) if w == crate::TypeTag::Pipe.name()
7608        ) {
7609            let kind = StepKind::Bind {
7610                var: var.clone(),
7611                decl_type: crate::TypeTag::Pipe.name().to_string(),
7612                is_const,
7613                rhs: BindRhs::Expr(Expr::FreshPipe),
7614            };
7615            return Ok(Some((kind, type_start + 1)));
7616        }
7617        return Err(cur.err(format!(
7618            "{kw} requires an expression: {kw} {head_example}: TYPE = <expr> (only {kw} {head_example}: PIPE omits the initializer)"
7619        )));
7620    };
7621    let decl_type = render_type_region(&body[type_start..eq], stmt)?;
7622    let (kind, rhs_used) = parse_let_rhs(&body[eq + 1..], var, decl_type, stmt, ctx, is_const)?;
7623    Ok(Some((kind, eq + 1 + rhs_used)))
7624}
7625
7626/// Collision gate for `CONST` names: uppercase plus keywords,
7627/// commands, types, and workspace targets. `FUNC` names and host
7628/// functions live in separate namespaces and may share a spelling
7629/// with a private `CONST`.
7630/// Same-scope `LET`/`CONST` duplicates rely on the static gate so
7631/// guard-disjoint declarations stay legal.
7632fn validate_const_name(ctx: &ParseCtx, cur: &Cursor, name: &str) -> Result<(), TokenError> {
7633    let _ = ctx;
7634    // Single gate for the declaration spelling: uppercase plus
7635    // freedom from reserved words (see [`crate::constants`]).
7636    if !crate::constants::is_const_name(name) {
7637        return Err(cur.err(format!(
7638            "{KEYWORD_CONST} names must be UPPERCASE: got `{name}`"
7639        )));
7640    }
7641    if crate::commands::is_reserved_const_name(name) {
7642        return Err(cur.err(format!(
7643            "CONST {name} collides with reserved keyword `{name}`"
7644        )));
7645    }
7646    Ok(())
7647}
7648
7649/// LET right-hand side dispatch, mirroring the grammar order
7650/// (`let_async`, then `let_capture`, then `let_statement`):
7651/// `WITH_IO`-led lines branch async/sync like
7652/// `parse_let_async_statement_from_pair`, `ASYNC`-led lines spawn
7653/// tasks, `TIMEOUT`-led lines capture through the wrapper,
7654/// `AWAIT $v` captures, RUN exec-form captures, known commands
7655/// capture through the generic parser (lowering failures fatal,
7656/// exactly like the committed grammar alternative), and anything
7657/// else parses as an expression (unknown leads included). Returns
7658/// the kind and RHS tokens consumed: captures ending in structural
7659/// pairs leave trailing elements for the caller.
7660fn parse_let_rhs(
7661    rhs: &[Tok],
7662    var: String,
7663    decl_type: String,
7664    stmt: usize,
7665    ctx: &ParseCtx,
7666    is_const: bool,
7667) -> Result<(StepKind, usize), TokenError> {
7668    // Leading gap comments vanish like the `=` gap (but a `//`/`#`
7669    // to end of input leaves no expression, failing).
7670    let mut lead = Cursor::expr(rhs, stmt);
7671    lead.skip_gap();
7672    let (rhs, skipped) = (&rhs[lead.pos..], lead.pos);
7673    let head_word = match rhs.first().map(|t| &t.kind) {
7674        Some(TokKind::Word(w)) => Some(w.clone()),
7675        _ => None,
7676    };
7677    // `WITH_IO`-led lines share `let_async_statement` with the
7678    // `ASYNC` forms (the grammar claims every WITH_IO-led LET
7679    // there); shape misses fall through to generic below.
7680    if head_word.as_deref() == Some(KEYWORD_WITH_IO)
7681        && let Some(found) =
7682            try_let_with_io_rhs(rhs, var.clone(), decl_type.clone(), stmt, ctx, is_const)?
7683    {
7684        let (kind, used) = found;
7685        return Ok((kind, skipped + used));
7686    }
7687    // `ASYNC`-led lines (with followers; alone they commit to the
7688    // generic path like the grammar, failing in lowering) spawn
7689    // background tasks. No `WITH_IO` scan here (probed: the LET
7690    // path accepts what statement `ASYNC` rejects).
7691    if head_word.as_deref() == Some(KEYWORD_ASYNC) && rhs.len() > 1 {
7692        let (kind, used) = parse_let_async_rhs(&rhs[1..], var, decl_type, stmt, ctx, is_const)?;
7693        return Ok((kind, skipped + 1 + used));
7694    }
7695    // `TIMEOUT`-led lines capture through the wrapper (shape misses
7696    // fall through to generic, which fails in lowering).
7697    if head_word.as_deref() == Some(KEYWORD_TIMEOUT)
7698        && let Some((kind, used)) = parse_timeout_single(rhs, 0, stmt, ctx)?
7699    {
7700        let span = lowering_ctx(stmt);
7701        crate::commands::reject_async_in_capture(&span, &kind).map_err(|e| lower_err(stmt, e))?;
7702        crate::commands::reject_pipe_stdout_in_capture(&span, &kind)
7703            .map_err(|e| lower_err(stmt, e))?;
7704        return Ok((
7705            StepKind::Bind {
7706                var,
7707                decl_type,
7708                is_const,
7709                rhs: BindRhs::Capture(Box::new(kind)),
7710            },
7711            skipped + used,
7712        ));
7713    }
7714    // `AWAIT $v` captures the task output (`$`+name ride gapless in
7715    // this atomic position, like the grammar). Anything else
7716    // `AWAIT`-led goes generic below (lowering fails it, probed).
7717    if head_word.as_deref() == Some(KEYWORD_AWAIT)
7718        && rhs.len() == 3
7719        && let (Some(dollar), Some(task)) = (rhs.get(1), rhs.get(2))
7720        && matches!(&dollar.kind, TokKind::Punct(VAR_SIGIL_CHAR))
7721        && task.joint
7722        && let TokKind::Word(task_var) = &task.kind
7723        && is_ident_word(task_var)
7724    {
7725        return Ok((
7726            StepKind::Bind {
7727                var,
7728                decl_type,
7729                is_const,
7730                rhs: BindRhs::Await {
7731                    task_var: task_var.clone(),
7732                },
7733            },
7734            skipped + 3,
7735        ));
7736    }
7737    // RUN exec form captures the structured argv (gapped bracket;
7738    // a joint bracket falls through to generic, which fails it in
7739    // lowering).
7740    if head_word.as_deref() == Some(KEYWORD_RUN)
7741        && matches!(
7742            rhs.get(1).map(|t| (&t.kind, t.joint)),
7743            Some((
7744                TokKind::Group {
7745                    delim: GroupDelim::Bracket,
7746                    ..
7747                },
7748                false
7749            ))
7750        )
7751        && rhs.len() == 2
7752    {
7753        let inner = match &rhs[1].kind {
7754            TokKind::Group { inner, .. } => inner.clone(),
7755            _ => unreachable!(),
7756        };
7757        // Non-map blocks miss the exec shape; fall through below
7758        // (known-command capture, then expression), mirroring the
7759        // grammar's ordered alternatives.
7760        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
7761            let kind =
7762                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
7763            return Ok((
7764                StepKind::Bind {
7765                    var,
7766                    decl_type,
7767                    is_const,
7768                    rhs: BindRhs::Capture(Box::new(kind)),
7769                },
7770                skipped + 2,
7771            ));
7772        }
7773    }
7774    // File `IMPORT ["path" AS ALIAS]` (#115) captures the imported
7775    // pipeline's `RETURN` value like a call (`LET $r: STRING = IMPORT ...`
7776    // lowers to `AssignCapture`): exactly one file entry, no modules.
7777    // Anything else shaped like an import is a hard error; shape misses
7778    // fall through to generic below, which fails them in lowering.
7779    if head_word.as_deref() == Some(KEYWORD_IMPORT)
7780        && let Some((path, alias, used)) = parse_single_file_import(rhs, 0, stmt, ctx)?
7781    {
7782        return Ok((
7783            StepKind::Bind {
7784                var,
7785                decl_type,
7786                is_const,
7787                rhs: BindRhs::Capture(Box::new(StepKind::ImportFile { path, alias })),
7788            },
7789            skipped + used,
7790        ));
7791    }
7792    // Known-command leads capture through the generic parser
7793    // (lowering failures are fatal here, exactly like the committed
7794    // grammar alternative: probed wrapper-alone and `ISOLATED`-led
7795    // shapes error in lowering); unknown leads parse as expressions.
7796    match &head_word {
7797        Some(head) if is_known_command(head) => {
7798            let (cmd, used) = parse_inner_command(rhs, stmt, ctx)?;
7799            let span = lowering_ctx(stmt);
7800            crate::commands::reject_async_in_capture(&span, &cmd)
7801                .map_err(|e| lower_err(stmt, e))?;
7802            crate::commands::reject_pipe_stdout_in_capture(&span, &cmd)
7803                .map_err(|e| lower_err(stmt, e))?;
7804            // `INHERIT_ENV`-led lines land here (generic): the
7805            // nesting check rejects them (probed).
7806            crate::commands::reject_nested_inherit_env(&span, &cmd)
7807                .map_err(|e| lower_err(stmt, e))?;
7808            return Ok((
7809                StepKind::Bind {
7810                    var,
7811                    decl_type,
7812                    is_const,
7813                    rhs: BindRhs::Capture(Box::new(cmd)),
7814                },
7815                skipped + used,
7816            ));
7817        }
7818        _ => {}
7819    }
7820    let mut cur = Cursor::expr(rhs, stmt);
7821    let expr = parse_expr_checked(&mut cur, ctx)?;
7822    let used = skipped + cur.pos;
7823    Ok((
7824        StepKind::Bind {
7825            var,
7826            decl_type,
7827            is_const,
7828            rhs: BindRhs::Expr(expr),
7829        },
7830        used,
7831    ))
7832}
7833
7834/// `WITH_IO`-led LET right-hand side, mirroring
7835/// `parse_let_async_statement_from_pair`'s `with_io_command` branch:
7836/// wrapping `ASYNC` binds a pipe-wired background task (multi-step
7837/// blocks fail loudly), wrapping a sync command captures its stdout
7838/// (async bodies and `stdout` pipes fail loudly), and a bare
7839/// bracket fails validation. `None` on shape miss (bad bracket:
7840/// the caller goes generic, which fails in lowering).
7841fn try_let_with_io_rhs(
7842    rhs: &[Tok],
7843    var: String,
7844    decl_type: String,
7845    stmt: usize,
7846    ctx: &ParseCtx,
7847    is_const: bool,
7848) -> Result<Option<(StepKind, usize)>, TokenError> {
7849    let kw = if is_const { KEYWORD_CONST } else { KEYWORD_LET };
7850    let bracket = match rhs.get(1) {
7851        Some(t)
7852            if !t.joint
7853                && matches!(
7854                    &t.kind,
7855                    TokKind::Group {
7856                        delim: GroupDelim::Bracket,
7857                        ..
7858                    }
7859                ) =>
7860        {
7861            t
7862        }
7863        _ => return Ok(None),
7864    };
7865    let inner = match &bracket.kind {
7866        TokKind::Group { inner, .. } => inner.clone(),
7867        _ => unreachable!(),
7868    };
7869    let bindings = match parse_io_bindings(&inner, stmt, ctx)? {
7870        Some(bindings) => bindings,
7871        None => return Ok(None),
7872    };
7873    let fail = |msg: String| TokenError {
7874        diagnostic: None,
7875        hint: None,
7876        stmt,
7877        msg,
7878        line: 0,
7879        col: 0,
7880        kind: None,
7881    };
7882    let rest = &rhs[2..];
7883    let Some(first) = rest.first() else {
7884        // Bare bracket: the grammar's committed validation error.
7885        return Err(fail(format!(
7886            "{kw} $var: TYPE = WITH_IO requires an ASYNC command (e.g. {kw} $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7887        )));
7888    };
7889    if first.joint {
7890        // The inner rides after a `sep`: joint followers miss the
7891        // shape and fail validation like the grammar's bare bracket.
7892        return Err(fail(format!(
7893            "{kw} $var: TYPE = WITH_IO requires an ASYNC command (e.g. {kw} $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7894        )));
7895    }
7896    if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_ASYNC) {
7897        // `WITH_IO [..] ASYNC <single|block>`: the bindings apply
7898        // inside the task thread (same shape as a one-step body
7899        // holding one `WITH_IO` step, which the runtime supports).
7900        // A bare `ASYNC` goes generic and fails in lowering
7901        // (`unknown command: ASYNC`, probed).
7902        let after = &rest[1..];
7903        if after.is_empty() {
7904            // Bare `ASYNC`: the grammar commits to `instruction`
7905            // and lowering fails it (`unknown command: ASYNC`,
7906            // probed); mirror by running generic, staying failed
7907            // even under a lenient dispatcher.
7908            match parse_inner_command(&rest[..1], stmt, ctx) {
7909                Err(e) => return Err(e),
7910                Ok(_) => {
7911                    return Err(fail(format!(
7912                        "{kw} $var: HANDLE<T> = ASYNC requires a body"
7913                    )));
7914                }
7915            }
7916        }
7917        if let Some(second) = after.first()
7918            && matches!(
7919                &second.kind,
7920                TokKind::Group {
7921                    delim: GroupDelim::Brace,
7922                    ..
7923                }
7924            )
7925            && !is_template_brace(second)
7926        {
7927            let brace_inner = match &second.kind {
7928                TokKind::Group { inner, .. } => inner.clone(),
7929                _ => unreachable!(),
7930            };
7931            let body = parse_body_steps(&brace_inner, stmt, ctx, false)?;
7932            if body.len() != 1 {
7933                return Err(fail(format!(
7934                    "{kw} $var: TYPE = WITH_IO [..] ASYNC accepts a single command; use {kw} $var: HANDLE<T> = ASYNC {{ ... }} with WITH_IO inside the block for multi-step tasks"
7935                )));
7936            }
7937            let wrapped = Step {
7938                guard: None,
7939                kind: StepKind::WithIo {
7940                    bindings,
7941                    cmd: Box::new(
7942                        body.into_iter()
7943                            .next()
7944                            .ok_or_else(|| {
7945                                fail(format!("{KEYWORD_LET} $var: {HANDLE_TYPE_NAME}<T> = {KEYWORD_ASYNC} requires a body"))
7946                            })?
7947                            .kind,
7948                    ),
7949                },
7950                scope_enter: 0,
7951                scope_exit: 0,
7952                line: 0,
7953                col: 0,
7954            };
7955            return Ok(Some((
7956                StepKind::Bind {
7957                    var,
7958                    decl_type,
7959                    is_const,
7960                    rhs: BindRhs::Async(vec![wrapped]),
7961                },
7962                2 + 2,
7963            )));
7964        }
7965        if after.first().is_some_and(|t| t.joint) {
7966            // Joint followers miss the inner `sep`: same validation
7967            // error as the bare bracket.
7968            return Err(fail(
7969                "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7970                    .to_string(),
7971            ));
7972        }
7973        let (cmd, used) = parse_single_inner(
7974            rest,
7975            1,
7976            stmt,
7977            ctx,
7978            InnerRules {
7979                allow_await: false,
7980                allow_with_io: false,
7981            },
7982        )?;
7983        let wrapped = Step {
7984            guard: None,
7985            kind: StepKind::WithIo {
7986                bindings,
7987                cmd: Box::new(cmd),
7988            },
7989            scope_enter: 0,
7990            scope_exit: 0,
7991            line: 0,
7992            col: 0,
7993        };
7994        let kind = StepKind::Bind {
7995            var,
7996            decl_type,
7997            is_const,
7998            rhs: BindRhs::Async(vec![wrapped]),
7999        };
8000        let span = lowering_ctx(stmt);
8001        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
8002        return Ok(Some((kind, 2 + 1 + used)));
8003    }
8004    if matches!(
8005        &first.kind,
8006        TokKind::Group {
8007            delim: GroupDelim::Brace,
8008            ..
8009        }
8010    ) {
8011        // A brace is no sync command: same validation error (probed).
8012        return Err(fail(format!(
8013            "{kw} $var: TYPE = WITH_IO requires an ASYNC command (e.g. {kw} $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
8014        )));
8015    }
8016    // Sync inner: capture with the shared checks (the capture sink
8017    // owns stdout; async never runs inline).
8018    let (cmd, used) = parse_single_inner(
8019        rest,
8020        0,
8021        stmt,
8022        ctx,
8023        InnerRules {
8024            allow_await: false,
8025            allow_with_io: true,
8026        },
8027    )?;
8028    let span = lowering_ctx(stmt);
8029    if crate::commands::has_stdout_pipe(&bindings) {
8030        return Err(fail(format!(
8031            "{kw} capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
8032        )));
8033    }
8034    crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| lower_err(stmt, e))?;
8035    Ok(Some((
8036        StepKind::Bind {
8037            var,
8038            decl_type,
8039            is_const,
8040            rhs: BindRhs::Capture(Box::new(StepKind::WithIo {
8041                bindings,
8042                cmd: Box::new(cmd),
8043            })),
8044        },
8045        2 + used,
8046    )))
8047}
8048
8049/// `ASYNC`-led LET right-hand side (the tokens after `ASYNC`):
8050/// a block or single command becomes the task body. No `WITH_IO`
8051/// scan (probed: this path accepts what statement `ASYNC`
8052/// rejects); nesting still fails loudly through the shared check.
8053fn parse_let_async_rhs(
8054    rest: &[Tok],
8055    var: String,
8056    decl_type: String,
8057    stmt: usize,
8058    ctx: &ParseCtx,
8059    is_const: bool,
8060) -> Result<(StepKind, usize), TokenError> {
8061    let Some(first) = rest.first() else {
8062        return Err(TokenError {
8063            diagnostic: None,
8064            hint: None,
8065            stmt,
8066            msg: format!("binding $var: {HANDLE_TYPE_NAME}<T> = {KEYWORD_ASYNC} requires a body"),
8067            line: 0,
8068            col: 0,
8069            kind: None,
8070        });
8071    };
8072    if matches!(
8073        &first.kind,
8074        TokKind::Group {
8075            delim: GroupDelim::Brace,
8076            ..
8077        }
8078    ) && !is_template_brace(first)
8079    {
8080        let inner = match &first.kind {
8081            TokKind::Group { inner, .. } => inner.clone(),
8082            _ => unreachable!(),
8083        };
8084        let body = parse_body_steps(&inner, stmt, ctx, false)?;
8085        let kind = StepKind::Bind {
8086            var,
8087            decl_type,
8088            is_const,
8089            rhs: BindRhs::Async(body),
8090        };
8091        let span = lowering_ctx(stmt);
8092        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
8093        return Ok((kind, 1));
8094    }
8095    if first.joint {
8096        return Err(TokenError {
8097            diagnostic: None,
8098            hint: None,
8099            stmt,
8100            msg: format!("binding $var: {HANDLE_TYPE_NAME}<T> = {KEYWORD_ASYNC} requires a body"),
8101            line: 0,
8102            col: 0,
8103            kind: None,
8104        });
8105    }
8106    let (cmd, used) = parse_single_inner(
8107        rest,
8108        0,
8109        stmt,
8110        ctx,
8111        InnerRules {
8112            allow_await: false,
8113            allow_with_io: false,
8114        },
8115    )?;
8116    let kind = StepKind::Bind {
8117        var,
8118        decl_type,
8119        is_const,
8120        rhs: BindRhs::Async(vec![Step {
8121            guard: None,
8122            kind: cmd,
8123            scope_enter: 0,
8124            scope_exit: 0,
8125            line: 0,
8126            col: 0,
8127        }]),
8128    };
8129    let span = lowering_ctx(stmt);
8130    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
8131    Ok((kind, used))
8132}
8133
8134fn parse_set_body(
8135    body: &[Tok],
8136    stmt: usize,
8137    ctx: &ParseCtx,
8138) -> Result<(StepKind, usize), TokenError> {
8139    let mut cur = Cursor::expr(body, stmt);
8140    if matches!(
8141        cur.toks.get(cur.pos).map(|t| &t.kind),
8142        Some(TokKind::Punct(VAR_SIGIL_CHAR))
8143    ) {
8144        let var = expect_dollar_var(&mut cur, "mutation requires a variable: $var = <expr>")?;
8145        reject_qualified_target(&cur, &var)?;
8146        // Key paths never serve as mutation targets: without this,
8147        // `$M.a = ...` would drop `.a` when the head jumps to `=`
8148        // below and silently rebind the whole `$M`. Reads use key
8149        // paths in expressions; writes rebind the variable
8150        // (e.g. `$M = MAP_SET($M, "a", 2)`).
8151        if matches!(
8152            cur.toks.get(cur.pos).map(|t| &t.kind),
8153            Some(TokKind::Punct(KEY_PATH_SEPARATOR_CHAR))
8154        ) {
8155            let mut target = sigil_var(&var);
8156            let mut p = cur.pos;
8157            loop {
8158                let dot = matches!(
8159                    cur.toks.get(p).map(|t| &t.kind),
8160                    Some(TokKind::Punct(KEY_PATH_SEPARATOR_CHAR))
8161                );
8162                let word = match cur.toks.get(p + 1).map(|t| &t.kind) {
8163                    Some(TokKind::Word(w)) if is_key_segment(w) => w.clone(),
8164                    _ => break,
8165                };
8166                if !dot {
8167                    break;
8168                }
8169                target.push(KEY_PATH_SEPARATOR_CHAR);
8170                target.push_str(&word);
8171                p += 2;
8172            }
8173            return Err(cur.err(format!(
8174                "cannot assign to {target}: key paths read in expressions but are never mutation targets; rebind the variable instead (e.g. {example} = MAP_SET({example}, \"a\", 2))",
8175                example = sigil_var(&var),
8176            )));
8177        }
8178        let assign = find_assign_eq(&body[cur.pos..]).map(|i| i + cur.pos);
8179        let eq = match assign {
8180            Some(eq) => eq,
8181            None => {
8182                return Err(cur.err("mutation requires a variable: $var = <expr>"));
8183            }
8184        };
8185        cur.pos = eq + 1;
8186        cur.skip_gap();
8187        let expr = parse_expr_checked(&mut cur, ctx)?;
8188        return Ok((StepKind::Set { var, expr }, cur.pos));
8189    }
8190    // Bare words are literal text, never variable targets: only
8191    // `$var = <expr>` mutates.
8192    Err(cur.err("mutation requires a variable: $var = <expr>"))
8193}
8194
8195fn parse_return_body(
8196    body: &[Tok],
8197    stmt: usize,
8198    ctx: &ParseCtx,
8199) -> Result<(StepKind, usize), TokenError> {
8200    let mut cur = Cursor::expr(body, stmt);
8201    match cur.next() {
8202        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_RETURN) => {}
8203        _ => return Err(cur.err("unreachable")),
8204    }
8205    if cur.done() {
8206        return Ok((
8207            StepKind::Return {
8208                expr: Box::new(Expr::Literal(Value::string(String::new()))),
8209                is_bare: true,
8210            },
8211            cur.pos,
8212        ));
8213    }
8214    let expr = parse_expr_checked(&mut cur, ctx)?;
8215    Ok((
8216        StepKind::Return {
8217            expr: Box::new(expr),
8218            is_bare: false,
8219        },
8220        cur.pos,
8221    ))
8222}
8223
8224/// Lower one statement to steps through the element loop: the
8225/// statement guard attaches to the first element only (trailing
8226/// elements ride guardless, probed): the pending guard clears after
8227/// the first command token.
8228fn lower_stmt_steps(
8229    stmt: &Stmt,
8230    idx: usize,
8231    ctx: &ParseCtx,
8232    in_block: bool,
8233    mark: bool,
8234) -> Result<Vec<Step>, TokenError> {
8235    let guard = parse_guard_groups(&stmt.guard, idx)?;
8236    // Statement-head braces route here (mid-run braces fail inside
8237    // the element loop): templates and guardless/bare blocks fail
8238    // loudly; guarded braces open guard blocks (top level) or the
8239    // nested quirk (in bodies).
8240    let mut steps = if starts_brace(&stmt.body) {
8241        parse_brace_head(stmt, guard, idx, ctx, in_block, mark)?
8242    } else {
8243        parse_elements(&stmt.body, idx, ctx, guard, in_block)?
8244    };
8245    // Stamp the statement's source position on every directly
8246    // produced step still missing one. Nested body steps were stamped
8247    // by their own statements during recursion, so only direct
8248    // products are claimed here; inner statements keep their own
8249    // lines and columns.
8250    for step in &mut steps {
8251        if step.line == 0 {
8252            step.line = stmt.line;
8253        }
8254        if step.col == 0 {
8255            step.col = stmt.col;
8256        }
8257    }
8258    // Qualify bare placeholder calls (`{{ NAME(args) }}`) through
8259    // the shared static resolver, so templates obey exactly the
8260    // statement-position scope rule. Nested bodies were already
8261    // qualified by their own recursive statements with their own
8262    // frames, so only direct products are visited here. Both
8263    // `Arg::String` fragments (via `walk_raw_strings_mut`) and
8264    // `Expr::Literal` strings (LET/SET/RETURN/call args/list/map
8265    // literals/parenthesized args) are qualified: expression
8266    // positions expand through the same `expand_string` at runtime,
8267    // so they must see the same parse-time rewrite. `WithIo` and
8268    // `AssignCapture` box their inner command directly (no recursive
8269    // statement pass), so the helper descends into them; all other
8270    // bodies were already qualified with their own frames.
8271    // `Step.guards` carry no template text (`Guard::Attr` triples
8272    // evaluated via `guard_allows`, never expanded), so there is
8273    // nothing to qualify there.
8274    let mut failed: Option<TokenError> = None;
8275    for step in &mut steps {
8276        qualify_step_templates(step, ctx, idx, &mut failed);
8277        if failed.is_some() {
8278            break;
8279        }
8280    }
8281    if let Some(err) = failed {
8282        return Err(err);
8283    }
8284    Ok(steps)
8285}
8286
8287/// Qualify one direct statement product plus any boxed `WithIo` /
8288/// `AssignCapture` inner command (same scope frame, never a
8289/// recursive statement pass). Body vectors are skipped: their steps
8290/// were qualified by their own recursive statements.
8291fn qualify_step_templates(
8292    step: &mut Step,
8293    ctx: &ParseCtx,
8294    stmt: usize,
8295    failed: &mut Option<TokenError>,
8296) {
8297    qualify_kind_templates(&mut step.kind, ctx, stmt, failed);
8298}
8299
8300/// Qualify one `StepKind` plus boxed inner commands sharing the
8301/// same scope frame.
8302fn qualify_kind_templates(
8303    kind: &mut StepKind,
8304    ctx: &ParseCtx,
8305    stmt: usize,
8306    failed: &mut Option<TokenError>,
8307) {
8308    kind.walk_raw_strings_mut(&mut |text| {
8309        if failed.is_none() {
8310            match qualify_template_calls(text, ctx, stmt) {
8311                Ok(Some(rewritten)) => *text = rewritten,
8312                Ok(None) => {}
8313                Err(err) => *failed = Some(err),
8314            }
8315        }
8316    });
8317    if failed.is_some() {
8318        return;
8319    }
8320    kind.walk_exprs_mut(&mut |expr| {
8321        if failed.is_some() {
8322            return;
8323        }
8324        expr.walk_mut(&mut |node| {
8325            if failed.is_some() {
8326                return;
8327            }
8328            if let Expr::Literal(value) = node
8329                && let Some(text) = value.as_str()
8330            {
8331                match qualify_template_calls(text, ctx, stmt) {
8332                    Ok(Some(rewritten)) => {
8333                        *value = Value::string(rewritten);
8334                    }
8335                    Ok(None) => {}
8336                    Err(err) => *failed = Some(err),
8337                }
8338            }
8339        });
8340    });
8341    if failed.is_some() {
8342        return;
8343    }
8344    // Boxed single commands share the outer scope frame (no recursive
8345    // statement pass built them): qualify the inner kind directly.
8346    match kind {
8347        StepKind::WithIo { cmd, .. } => {
8348            qualify_kind_templates(cmd, ctx, stmt, failed);
8349        }
8350        StepKind::Bind {
8351            rhs: BindRhs::Capture(cmd),
8352            ..
8353        } => {
8354            qualify_kind_templates(cmd, ctx, stmt, failed);
8355        }
8356        _ => {}
8357    }
8358    if failed.is_some() {
8359        return;
8360    }
8361    // Single-command synthetic bodies share the outer frame: `TIMEOUT 5s
8362    // <cmd>`, `ISOLATED <cmd>`, `ASYNC <cmd>`, and `AssignAsync` wrappers
8363    // build their `body` inline via `parse_single_inner` with no recursive
8364    // `lower_stmt_steps` pass, so their one synthetic step needs this one.
8365    // Brace-delimited bodies are NEVER re-walked here: they were already
8366    // lowered via `parse_body_steps` with their own frames and statement
8367    // indices (mirroring `Expr::walk_mut` skipping `Expr::Block`), and
8368    // re-resolving under the outer frame would corrupt scope isolation
8369    // and error attribution. The match names only the synthetic carriers;
8370    // any other body (If/For/While/FuncDef/RemoteBlock/WithIoBlock) stays
8371    // exactly as its own recursive pass left it.
8372    match kind {
8373        StepKind::Timeout { body, .. }
8374        | StepKind::Isolated { body }
8375        | StepKind::AsyncBlock { body } => {
8376            for step in body.iter_mut() {
8377                if failed.is_some() {
8378                    return;
8379                }
8380                qualify_step_templates(step, ctx, stmt, failed);
8381            }
8382        }
8383        StepKind::Bind { rhs, .. } => match rhs {
8384            BindRhs::Async(body) => {
8385                for step in body.iter_mut() {
8386                    if failed.is_some() {
8387                        return;
8388                    }
8389                    qualify_step_templates(step, ctx, stmt, failed);
8390                }
8391            }
8392            BindRhs::Capture(_) | BindRhs::Expr(_) | BindRhs::Await { .. } => {}
8393        },
8394        _ => {}
8395    }
8396}
8397
8398/// Statement-head `{...}` dispatcher. Template braces fail (the
8399/// grammar strands them); guardless top-level braces fail; detached
8400/// or guardless in-body braces fail (no `block_start` in
8401/// `block_element`); guarded braces open a guard scope at top level
8402/// or mirror the nested quirk formula in bodies. Trailing elements
8403/// loop on guardless outside (like the grammar's continued line).
8404fn parse_brace_head(
8405    stmt: &Stmt,
8406    guard: Option<GuardExpr>,
8407    idx: usize,
8408    ctx: &ParseCtx,
8409    in_block: bool,
8410    mark: bool,
8411) -> Result<Vec<Step>, TokenError> {
8412    let brace = &stmt.body[0];
8413    if is_template_brace(brace) {
8414        return Err(TokenError {
8415            diagnostic: None,
8416            hint: None,
8417            stmt: idx,
8418            msg: "'{' without a pending guard".to_string(),
8419            line: 0,
8420            col: 0,
8421            kind: None,
8422        });
8423    }
8424    let inner = match &brace.kind {
8425        TokKind::Group { inner, .. } => inner.clone(),
8426        _ => unreachable!(),
8427    };
8428    if in_block {
8429        // Attached guarded braces only: pending holds all groups but
8430        // the last (the block's own), mirroring the pair structure.
8431        if guard.is_none() || stmt.brace_detached || stmt.guard.is_empty() {
8432            return Err(TokenError {
8433                diagnostic: None,
8434                hint: None,
8435                stmt: idx,
8436                msg: "unexpected '{' in block body".to_string(),
8437                line: 0,
8438                col: 0,
8439                kind: None,
8440            });
8441        }
8442        let n = stmt.guard.len();
8443        let mut pending = None;
8444        if n > 1 {
8445            pending = parse_guard_groups(&stmt.guard[..n - 1], idx)?;
8446        }
8447        let block_guard = parse_guard_groups(&stmt.guard[n - 1..n], idx)?.ok_or(TokenError {
8448            diagnostic: None,
8449            hint: None,
8450            stmt: idx,
8451            msg: "unexpected '{' in block body".to_string(),
8452            line: 0,
8453            col: 0,
8454            kind: None,
8455        })?;
8456        let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
8457        // Guard-block bodies propagate the ambient marking context
8458        // (top-level nesting marks; wrapper bodies never mark).
8459        // Quirk formula verbatim (including the dropped block guard
8460        // with inner guards, probed).
8461        for s in &mut steps {
8462            let inner_guard = s.guard.take();
8463            s.guard = Some(match (pending.clone(), inner_guard) {
8464                (Some(p), Some(e)) => GuardExpr::all(vec![p, e]),
8465                (Some(p), None) => GuardExpr::all(vec![p, block_guard.clone()]),
8466                (None, Some(e)) => e,
8467                (None, None) => block_guard.clone(),
8468            });
8469        }
8470        // Marking contexts bump each nesting level (probed top-level
8471        // double-block 2/2); wrapper bodies stay 0/0.
8472        // Trailing elements ride outside, unmarked.
8473        if mark {
8474            if let Some(first) = steps.first_mut() {
8475                first.scope_enter += 1;
8476            }
8477            if let Some(last) = steps.last_mut() {
8478                last.scope_exit += 1;
8479            }
8480        }
8481        // Trailing elements loop on guardless outside.
8482        if stmt.body.len() > 1 {
8483            let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
8484            steps.append(&mut rest);
8485        }
8486        return Ok(steps);
8487    }
8488    // Top level: guardless braces fail; guarded braces open a guard
8489    // scope (each step folds outer-then-inner with markers).
8490    let Some(outer) = guard else {
8491        return Err(TokenError {
8492            diagnostic: None,
8493            hint: None,
8494            stmt: idx,
8495            msg: "'{' without a pending guard".to_string(),
8496            line: 0,
8497            col: 0,
8498            kind: None,
8499        });
8500    };
8501    let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
8502    if steps.is_empty() {
8503        return Err(TokenError {
8504            diagnostic: None,
8505            hint: None,
8506            stmt: idx,
8507            msg: "guard block must contain at least one command".to_string(),
8508            line: 0,
8509            col: 0,
8510            kind: None,
8511        });
8512    }
8513    for s in &mut steps {
8514        let inner_guard = s.guard.take();
8515        s.guard = Some(match inner_guard {
8516            Some(e) => GuardExpr::all(vec![outer.clone(), e]),
8517            None => outer.clone(),
8518        });
8519    }
8520    if let Some(first) = steps.first_mut() {
8521        first.scope_enter += 1;
8522    }
8523    if let Some(last) = steps.last_mut() {
8524        last.scope_exit += 1;
8525    }
8526    if stmt.body.len() > 1 {
8527        let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
8528        steps.append(&mut rest);
8529    }
8530    Ok(steps)
8531}
8532
8533/// Parse consecutive elements to end of run (the grammar's
8534/// `element*`): structural pairs (calls, RUN-exec, await/cancel,
8535/// wrapper blocks) end mid-run and trailing elements form following
8536/// steps; instructions and expressions consume greedily to the end.
8537fn parse_elements(
8538    toks: &[Tok],
8539    stmt: usize,
8540    ctx: &ParseCtx,
8541    guard: Option<GuardExpr>,
8542    in_block: bool,
8543) -> Result<Vec<Step>, TokenError> {
8544    let mut steps = Vec::new();
8545    let mut pos = 0;
8546    // Statement guard: consumed by the first element that yields a
8547    // step. `IMPORT` yields none, so the guard leaks to the next
8548    // element (probed).
8549    let mut pending_guard: Option<GuardExpr> = guard;
8550    while pos < toks.len() {
8551        // Trailing gap comments between elements (`} #c`, `F("a")
8552        // /*c*/ ECHO`, `LET $x: INT = 1 //c` — the pair ended, so the
8553        // comment is silent like the grammar, never payload):
8554        // `#` and lexer `Comment` markers run to the run end, `//`
8555        // likewise (line comments eat `;` too, and runs hold no
8556        // newlines), `/* */` balances. Mid-run `#`/`/*` stay payload
8557        // text inside the generic path, which consumes everything
8558        // and never loops back here.
8559        if matches!(&toks[pos].kind, TokKind::Punct('#'))
8560            || matches!(&toks[pos].kind, TokKind::Comment(_))
8561        {
8562            break;
8563        }
8564        if matches!(&toks[pos].kind, TokKind::Punct('/')) && is_comment_open(toks, pos) {
8565            if matches!(
8566                toks.get(pos + 1).map(|t| &t.kind),
8567                Some(TokKind::Punct('/'))
8568            ) {
8569                break;
8570            }
8571            match skip_inline_comment(toks, pos) {
8572                Some(past) => {
8573                    pos = past;
8574                    continue;
8575                }
8576                None => {
8577                    return Err(TokenError {
8578                        diagnostic: None,
8579                        hint: None,
8580                        stmt,
8581                        msg: "unclosed block comment".to_string(),
8582                        line: 0,
8583                        col: 0,
8584                        kind: None,
8585                    });
8586                }
8587            }
8588        }
8589        // `IMPORT` statements update the import frames; module entries
8590        // emit no step (the guard leaks to the next element, probed,
8591        // unless this is top level, where a guarded module import
8592        // fails), while each file entry emits one `ImportFile` step
8593        // carrying the guard. Shape misses fall through to generic
8594        // (lowering fails them).
8595        if matches!(
8596            toks.get(pos).map(|t| &t.kind),
8597            Some(TokKind::Word(w)) if w == KEYWORD_IMPORT
8598        ) {
8599            // Unified statement form (#115): each entry validates hard
8600            // (unknown modules, bad aliases, templates, remote URLs);
8601            // module entries update the frame and emit no step, file
8602            // and harvest entries emit one step each, in source order.
8603            // A top-level guard on a statement with module entries fails
8604            // like the historical directive; file-only statements consume
8605            // the guard like any other element.
8606            if let Some(((modules, kinds), used)) =
8607                parse_import_statement(toks, pos, stmt, ctx, pending_guard.is_some())?
8608            {
8609                if !modules.is_empty() && !in_block && pending_guard.is_some() {
8610                    return Err(TokenError {
8611                        diagnostic: None,
8612                        hint: None,
8613                        stmt,
8614                        msg: format!("{KEYWORD_IMPORT} cannot be guarded"),
8615                        line: 0,
8616                        col: 0,
8617                        kind: None,
8618                    });
8619                }
8620                // Modules-only statements stay zero-step directives: the
8621                // guard leaks to the next element (probed). Anything with
8622                // file or harvest entries consumes it.
8623                let guard = if kinds.is_empty() {
8624                    None
8625                } else {
8626                    pending_guard.take()
8627                };
8628                for kind in kinds {
8629                    steps.push(Step {
8630                        guard: guard.clone(),
8631                        kind,
8632                        scope_enter: 0,
8633                        scope_exit: 0,
8634                        line: 0,
8635                        col: 0,
8636                    });
8637                }
8638                pos += used;
8639                continue;
8640            }
8641        }
8642        let guard = pending_guard.take();
8643        let (mut got, used) = parse_element_at(toks, pos, stmt, ctx, guard, in_block)?;
8644        if used == 0 {
8645            return Err(TokenError {
8646                diagnostic: None,
8647                hint: None,
8648                stmt,
8649                msg: "element consumed no input".to_string(),
8650                line: 0,
8651                col: 0,
8652                kind: None,
8653            });
8654        }
8655        steps.append(&mut got);
8656        pos += used;
8657    }
8658    Ok(steps)
8659}
8660
8661/// Parse one element at `pos`, returning built steps (guard already
8662/// assigned: `first_guard` for the first, folded per io-block inner
8663/// step) and tokens consumed.
8664fn parse_element_at(
8665    toks: &[Tok],
8666    pos: usize,
8667    stmt: usize,
8668    ctx: &ParseCtx,
8669    first_guard: Option<GuardExpr>,
8670    in_block: bool,
8671) -> Result<(Vec<Step>, usize), TokenError> {
8672    let step = |kind: StepKind| Step {
8673        guard: first_guard.clone(),
8674        kind,
8675        scope_enter: 0,
8676        scope_exit: 0,
8677        line: 0,
8678        col: 0,
8679    };
8680    let head_word = match toks.get(pos).map(|t| &t.kind) {
8681        Some(TokKind::Word(w)) => Some(w.clone()),
8682        _ => None,
8683    };
8684    // Mid-run `{...}` (after a call, wrapper block, ...): the
8685    // grammar strands it (`block_start` needs a pending guard or
8686    // `WITH_IO` wait, both consumed), so fail loudly. Statement-head
8687    // braces route through `lower_stmt_steps`, never here.
8688    if starts_brace(&toks[pos..]) {
8689        return Err(TokenError {
8690            diagnostic: None,
8691            hint: None,
8692            stmt,
8693            msg: "'{' without a pending guard".to_string(),
8694            line: 0,
8695            col: 0,
8696            kind: None,
8697        });
8698    }
8699    // LET/CONST/SET/RETURN heads parse with groups intact, then trailing
8700    // elements loop on (probed `LET $x: INT = 1 ECHO bye`). Binding shape
8701    // misses fall to generic (lowering fails them like a committed
8702    // `instruction` would, e.g. `LET foo`).
8703    if head_word.as_deref() == Some(KEYWORD_LET)
8704        && let Some((kind, used)) = parse_let_body(&toks[pos..], stmt, ctx)?
8705    {
8706        return Ok((vec![step(kind)], used));
8707    }
8708    if head_word.as_deref() == Some(KEYWORD_CONST)
8709        && let Some((kind, used)) = parse_const_body(&toks[pos..], stmt, ctx)?
8710    {
8711        return Ok((vec![step(kind)], used));
8712    }
8713    if matches!(
8714        toks.get(pos).map(|t| &t.kind),
8715        Some(TokKind::Punct(VAR_SIGIL_CHAR))
8716    ) {
8717        let (kind, used) = parse_set_body(&toks[pos..], stmt, ctx)?;
8718        return Ok((vec![step(kind)], used));
8719    }
8720    if head_word.as_deref() == Some(KEYWORD_RETURN) {
8721        let (kind, used) = parse_return_body(&toks[pos..], stmt, ctx)?;
8722        return Ok((vec![step(kind)], used));
8723    }
8724    // Calls route before heads (even known commands take the call
8725    // path with a joint paren, probed `ECHO("hi")`); the call ends
8726    // mid-run and trailing elements loop on (fixes the slice-4a
8727    // divergence, probed).
8728    if call_shape_at(toks, pos, true).is_some() {
8729        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8730        return Ok((vec![step(kind)], used));
8731    }
8732    if let Some(TokKind::Word(base)) = toks.get(pos).map(|t| &t.kind)
8733        && is_ident_word(base)
8734        && match_joint_qualified(toks, pos + 1).is_some()
8735    {
8736        // Qualified calls already returned above; anything else
8737        // starting `ALIAS::NAME` is a binding-target misuse.
8738        return Err(TokenError {
8739            diagnostic: None,
8740            hint: None,
8741            stmt,
8742            msg: "cannot declare or assign ALIAS::NAME: module values read as $ALIAS::NAME in expressions and are never binding targets".to_string(),
8743            line: 0,
8744            col: 0,
8745            kind: None,
8746        });
8747    }
8748    // Block statements (shape misses fall to generic, which fails
8749    // them in lowering like the grammar's committed `instruction`).
8750    // `BREAK`/`CONTINUE` take no args (structural, like the grammar):
8751    // each consumes one token and trailing elements loop on (probed
8752    // `BREAK ECHO hi`); a lone trailing word fails downstream like
8753    // the grammar's committed mismatch.
8754    match head_word.as_deref() {
8755        Some(KEYWORD_BREAK) => {
8756            return Ok((vec![step(StepKind::Break)], 1));
8757        }
8758        Some(KEYWORD_CONTINUE) => {
8759            return Ok((vec![step(StepKind::Continue)], 1));
8760        }
8761        Some(KEYWORD_IF) => {
8762            if let Some((kind, used)) = parse_if_at(toks, pos, stmt, ctx)? {
8763                return Ok((vec![step(kind)], used));
8764            }
8765        }
8766        Some(KEYWORD_SWITCH) => {
8767            if let Some((kind, used)) = parse_switch_at(toks, pos, stmt, ctx)? {
8768                return Ok((vec![step(kind)], used));
8769            }
8770        }
8771        Some(KEYWORD_FOR) => {
8772            if let Some((kind, used)) = parse_for_at(toks, pos, stmt, ctx)? {
8773                return Ok((vec![step(kind)], used));
8774            }
8775        }
8776        Some(KEYWORD_WHILE) => {
8777            if let Some((kind, used)) = parse_while_single(toks, pos, stmt, ctx)? {
8778                return Ok((vec![step(kind)], used));
8779            }
8780        }
8781        Some(KEYWORD_FUNC) => {
8782            if let Some((kind, used)) = parse_func_at(toks, pos, stmt, ctx, false)? {
8783                return Ok((vec![step(kind)], used));
8784            }
8785        }
8786        Some(KEYWORD_REMOTE) => {
8787            if let Some((kind, used)) = parse_remote_single(toks, pos, stmt, ctx)? {
8788                return Ok((vec![step(kind)], used));
8789            }
8790        }
8791        _ => {}
8792    }
8793    // Wrappers (block or single); shape misses fall to generic.
8794    match head_word.as_deref() {
8795        Some(KEYWORD_WITH_IO) => {
8796            return parse_with_io_element(toks, pos, stmt, ctx, first_guard);
8797        }
8798        Some(KEYWORD_TIMEOUT) => {
8799            if let Some((kind, used)) = parse_timeout_single(toks, pos, stmt, ctx)? {
8800                return Ok((vec![step(kind)], used));
8801            }
8802        }
8803        Some(KEYWORD_ISOLATED) => {
8804            if let Some((kind, used)) = parse_isolated_single(toks, pos, stmt, ctx)? {
8805                return Ok((vec![step(kind)], used));
8806            }
8807        }
8808        Some(KEYWORD_FAIL) => {
8809            if let Some((kind, used)) = parse_fail_single(toks, pos, stmt, ctx)? {
8810                return Ok((vec![step(kind)], used));
8811            }
8812        }
8813        Some(KEYWORD_ASYNC) => {
8814            // ASYNC FUNC definition form: prefix, parser records is_async
8815            // with no type-constraint validation (checker owns HANDLE rule).
8816            if matches!(toks.get(pos + 1).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC)
8817                && let Some((kind, used)) = parse_func_at(toks, pos + 1, stmt, ctx, true)?
8818            {
8819                return Ok((vec![step(kind)], 1 + used));
8820            }
8821            if let Some((kind, used)) = parse_async_single(toks, pos, stmt, ctx)? {
8822                return Ok((vec![step(kind)], used));
8823            }
8824        }
8825        _ => {}
8826    }
8827    // AWAIT/CANCEL statements (element level admits the `$` gap,
8828    // probed); heads without `$` go generic (lowering fails the
8829    // rest).
8830    if matches!(
8831        head_word.as_deref(),
8832        Some(KEYWORD_AWAIT) | Some(KEYWORD_CANCEL)
8833    ) && let Some((kind, used)) = parse_await_cancel_at(toks, pos, stmt, false, ctx)?
8834    {
8835        return Ok((vec![step(kind)], used));
8836    }
8837    // `INHERIT_ENV [...]` parses strictly even at element level
8838    // (keys stay exact everywhere; slice 5 adds only the
8839    // prelude-order validation). Shape misses go generic.
8840    if head_word.as_deref() == Some(KEYWORD_INHERIT_ENV)
8841        && let Some((kind, used)) = parse_inherit_env_at(toks, pos, stmt)?
8842    {
8843        return Ok((vec![step(kind)], used));
8844    }
8845    // `EXPORT ...` records names (zero steps) or misses to generic;
8846    // level, guard, and sigil violations fail loudly like the backend.
8847    if head_word.as_deref() == Some(KEYWORD_EXPORT) {
8848        if in_block {
8849            return Err(TokenError {
8850                diagnostic: None,
8851                hint: None,
8852                stmt,
8853                msg: format!("{KEYWORD_EXPORT} is only allowed at the top level"),
8854                line: 0,
8855                col: 0,
8856                kind: None,
8857            });
8858        }
8859        if first_guard.is_some() {
8860            return Err(TokenError {
8861                diagnostic: None,
8862                hint: None,
8863                stmt,
8864                msg: format!("{KEYWORD_EXPORT} cannot be guarded"),
8865                line: 0,
8866                col: 0,
8867                kind: None,
8868            });
8869        }
8870        if let Some((
8871            ExportNames {
8872                func_names,
8873                type_names,
8874                const_names,
8875            },
8876            used,
8877        )) = parse_export_at(toks, pos, stmt)?
8878        {
8879            for name in &func_names {
8880                for part in name.split(MODULE_SEPARATOR) {
8881                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8882                        .map_err(|e| lower_err(stmt, e))?;
8883                }
8884                // Recording and the duplicate rule live in
8885                // `Exports::insert` (single owner); this loop only
8886                // validates identifier shapes.
8887                if let Err(msg) = ctx
8888                    .exports
8889                    .borrow_mut()
8890                    .insert(ExportKind::Func, name.clone())
8891                {
8892                    return Err(TokenError {
8893                        diagnostic: None,
8894                        hint: None,
8895                        stmt,
8896                        msg,
8897                        line: 0,
8898                        col: 0,
8899                        kind: Some(ParseErrorKind::Validation {
8900                            command: KEYWORD_EXPORT.to_string(),
8901                        }),
8902                    });
8903                }
8904            }
8905            for name in &type_names {
8906                for part in name.split(MODULE_SEPARATOR) {
8907                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8908                        .map_err(|e| lower_err(stmt, e))?;
8909                }
8910                if let Err(msg) = ctx
8911                    .exports
8912                    .borrow_mut()
8913                    .insert(ExportKind::Type, name.clone())
8914                {
8915                    return Err(TokenError {
8916                        diagnostic: None,
8917                        hint: None,
8918                        stmt,
8919                        msg,
8920                        line: 0,
8921                        col: 0,
8922                        kind: Some(ParseErrorKind::Validation {
8923                            command: KEYWORD_EXPORT.to_string(),
8924                        }),
8925                    });
8926                }
8927            }
8928            for name in &const_names {
8929                for part in name.split(MODULE_SEPARATOR) {
8930                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8931                        .map_err(|e| lower_err(stmt, e))?;
8932                }
8933                if let Err(msg) = ctx
8934                    .exports
8935                    .borrow_mut()
8936                    .insert(ExportKind::Const, name.clone())
8937                {
8938                    return Err(TokenError {
8939                        diagnostic: None,
8940                        hint: None,
8941                        stmt,
8942                        msg,
8943                        line: 0,
8944                        col: 0,
8945                        kind: Some(ParseErrorKind::Validation {
8946                            command: KEYWORD_EXPORT.to_string(),
8947                        }),
8948                    });
8949                }
8950            }
8951            return Ok((Vec::new(), used));
8952        }
8953    }
8954    // `TYPE NAME = SHAPE` aliases (zero or one step); level and guard
8955    // violations fail loudly, shape misses fall to generic.
8956    if head_word.as_deref() == Some(KEYWORD_TYPE) {
8957        if in_block {
8958            return Err(TokenError {
8959                diagnostic: None,
8960                hint: None,
8961                stmt,
8962                msg: format!("{KEYWORD_TYPE} must appear at top level"),
8963                line: 0,
8964                col: 0,
8965                kind: None,
8966            });
8967        }
8968        if first_guard.is_some() {
8969            return Err(TokenError {
8970                diagnostic: None,
8971                hint: None,
8972                stmt,
8973                msg: format!("{KEYWORD_TYPE} cannot be guarded"),
8974                line: 0,
8975                col: 0,
8976                kind: None,
8977            });
8978        }
8979        if let Some((kind, used)) = parse_type_stmt_at(toks, pos, stmt)? {
8980            return Ok((vec![step(kind)], used));
8981        }
8982    }
8983    // Lowercase heads name their uppercase form (the grammar's
8984    // `command_name` mismatch): never a bare unknown-command.
8985    if let Some(head) = head_word.as_deref()
8986        && head.chars().all(|c| c.is_ascii_lowercase())
8987        && let upper = head.to_ascii_uppercase()
8988        && (is_known_command(&upper) || crate::STRUCTURAL_KEYWORDS.contains(&upper.as_str()))
8989    {
8990        return Err(TokenError {
8991            diagnostic: None,
8992            hint: None,
8993            stmt,
8994            msg: format!("command must be uppercase: found `{head}`, expected `{upper}`"),
8995            line: 0,
8996            col: 0,
8997            kind: Some(ParseErrorKind::Syntax),
8998        });
8999    }
9000    // RUN-exec ends mid-run (trailing loops on, probed); generic
9001    // instructions consume everything.
9002    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
9003    Ok((vec![step(kind)], used))
9004}
9005
9006/// Element-level `WITH_IO`: a same-run brace (any gap: `]{` works,
9007/// probed) opens the io-block form, wrapping every inner step with
9008/// scope markers; a joint non-brace follower is the pending-guard
9009/// error (the splitter only holds bare brackets); anything else is
9010/// the single form. Shape misses go generic.
9011fn parse_with_io_element(
9012    toks: &[Tok],
9013    pos: usize,
9014    stmt: usize,
9015    ctx: &ParseCtx,
9016    first_guard: Option<GuardExpr>,
9017) -> Result<(Vec<Step>, usize), TokenError> {
9018    // The bracket rides gapped (`sep`); anything else misses the
9019    // shape and generic fails it in lowering.
9020    let bracket = match toks.get(pos + 1) {
9021        Some(t)
9022            if !t.joint
9023                && matches!(
9024                    &t.kind,
9025                    TokKind::Group {
9026                        delim: GroupDelim::Bracket,
9027                        ..
9028                    }
9029                ) =>
9030        {
9031            Some(t)
9032        }
9033        _ => None,
9034    };
9035    let Some(bracket) = bracket else {
9036        // Shape miss: generic fails it in lowering.
9037        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
9038        return Ok((
9039            vec![Step {
9040                guard: first_guard,
9041                kind,
9042                scope_enter: 0,
9043                scope_exit: 0,
9044                line: 0,
9045                col: 0,
9046            }],
9047            used,
9048        ));
9049    };
9050    let inner = match &bracket.kind {
9051        TokKind::Group { inner, .. } => inner.clone(),
9052        _ => unreachable!(),
9053    };
9054    let bindings = match parse_io_bindings(&inner, stmt, ctx)? {
9055        Some(bindings) => bindings,
9056        // Shape miss: generic fails it.
9057        None => {
9058            let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
9059            return Ok((
9060                vec![Step {
9061                    guard: first_guard,
9062                    kind,
9063                    scope_enter: 0,
9064                    scope_exit: 0,
9065                    line: 0,
9066                    col: 0,
9067                }],
9068                used,
9069            ));
9070        }
9071    };
9072    let rest = pos + 2;
9073    // Same-run brace opens the io-block form (block-expanded
9074    // bindings skip the tty checks: the runtime repeats them).
9075    if let Some(next) = toks.get(rest)
9076        && matches!(
9077            &next.kind,
9078            TokKind::Group {
9079                delim: GroupDelim::Brace,
9080                ..
9081            }
9082        )
9083        && !is_template_brace(next)
9084    {
9085        let brace_inner = match &next.kind {
9086            TokKind::Group { inner, .. } => inner.clone(),
9087            _ => unreachable!(),
9088        };
9089        let mut steps = parse_body_steps(&brace_inner, stmt, ctx, false)?;
9090        if steps.is_empty() {
9091            return Err(TokenError {
9092                diagnostic: None,
9093                hint: None,
9094                stmt,
9095                msg: format!("{KEYWORD_WITH_IO} block must contain at least one command"),
9096                line: 0,
9097                col: 0,
9098                kind: None,
9099            });
9100        }
9101        // Every inner step wraps (merging when already wrapped,
9102        // like nested io scopes); the line guard folds into each
9103        // inner guard, inner-first (probed fold order).
9104        for s in &mut steps {
9105            let merged = match std::mem::replace(&mut s.kind, StepKind::Continue) {
9106                StepKind::WithIo {
9107                    bindings: inner_bindings,
9108                    cmd,
9109                } => StepKind::WithIo {
9110                    bindings: crate::commands::merge_bindings(&bindings, &inner_bindings),
9111                    cmd,
9112                },
9113                other => StepKind::WithIo {
9114                    bindings: bindings.clone(),
9115                    cmd: Box::new(other),
9116                },
9117            };
9118            s.kind = merged;
9119            s.guard = crate::commands::and_guard_exprs(s.guard.take(), first_guard.clone());
9120        }
9121        let span = lowering_ctx(stmt);
9122        for s in &steps {
9123            crate::commands::reject_nested_inherit_env(&span, &s.kind)
9124                .map_err(|e| lower_err(stmt, e))?;
9125        }
9126        if let Some(first) = steps.first_mut() {
9127            first.scope_enter += 1;
9128        }
9129        if let Some(last) = steps.last_mut() {
9130            last.scope_exit += 1;
9131        }
9132        return Ok((steps, rest + 1 - pos));
9133    }
9134    if rest >= toks.len() {
9135        // Unreachable: the splitter holds bare brackets for `{`.
9136        // Kept for body-parsed runs, mirroring the transient node.
9137        return Ok((
9138            vec![Step {
9139                guard: first_guard,
9140                kind: StepKind::WithIoBlock { bindings },
9141                scope_enter: 0,
9142                scope_exit: 0,
9143                line: 0,
9144                col: 0,
9145            }],
9146            2,
9147        ));
9148    }
9149    // A joint follower misses the inner `sep`: the pending wait
9150    // fails exactly like the grammar.
9151    if toks[rest].joint {
9152        return Err(TokenError {
9153            diagnostic: None,
9154            hint: None,
9155            stmt,
9156            msg: format!("{KEYWORD_WITH_IO} block must be followed by '{{'"),
9157            line: 0,
9158            col: 0,
9159            kind: None,
9160        });
9161    }
9162    // Single form, shared with single-inner (element guards the step).
9163    let (cmd, used) = parse_single_inner(
9164        toks,
9165        rest,
9166        stmt,
9167        ctx,
9168        InnerRules {
9169            allow_await: false,
9170            allow_with_io: true,
9171        },
9172    )?;
9173    let span = lowering_ctx(stmt);
9174    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| lower_err(stmt, e))?;
9175    let kind = StepKind::WithIo {
9176        bindings,
9177        cmd: Box::new(cmd),
9178    };
9179    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
9180    Ok((
9181        vec![Step {
9182            guard: first_guard,
9183            kind,
9184            scope_enter: 0,
9185            scope_exit: 0,
9186            line: 0,
9187            col: 0,
9188        }],
9189        2 + used,
9190    ))
9191}
9192
9193/// Shared inner-command parser: statement calls (joint paren, even on
9194/// known commands), RUN exec
9195/// form, and generic instructions. Returns the kind and tokens
9196/// consumed: calls and RUN-exec end mid-run (the caller continues
9197/// past them, like the grammar's `element*`); generic instructions
9198/// consume everything. Wrappers never route here (element and
9199/// single-inner dispatch own them); slice 4b reuses the call/RUN
9200/// arms for trailing elements.
9201fn parse_inner_command(
9202    body: &[Tok],
9203    stmt: usize,
9204    ctx: &ParseCtx,
9205) -> Result<(StepKind, usize), TokenError> {
9206    // Bare `NAME(...)` calls invoke functions with one syntax; the head
9207    // and `(` ride gapless or the shape stays an instruction (which
9208    // fails later as UnknownCommand), exactly like the grammar.
9209    if let Some((call_name, paren)) = call_shape_at(body, 0, true) {
9210        let inner = match &body[paren].kind {
9211            TokKind::Group { inner, .. } => inner.clone(),
9212            _ => unreachable!(),
9213        };
9214        let args = parse_call_args(&inner, stmt, ctx)?;
9215        // Statement-level `INSPECT(...)` resolves like any other call
9216        // (only expression position mints the node); unknown functions
9217        // fail in the shared resolver with identical messages.
9218        if !call_name.contains(MODULE_SEPARATOR) {
9219            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
9220                .map_err(|e| lower_err(stmt, e))?;
9221        }
9222        let qualified = resolve_name(ctx, stmt, &call_name)?;
9223        return Ok((
9224            StepKind::Call {
9225                name: qualified,
9226                args,
9227            },
9228            paren + 1,
9229        ));
9230    }
9231    let head = match body.first().map(|t| &t.kind) {
9232        Some(TokKind::Word(n)) => n.clone(),
9233        _ => {
9234            return Err(TokenError {
9235                diagnostic: None,
9236                hint: None,
9237                stmt,
9238                msg: "statement must open with a command word".to_string(),
9239                line: 0,
9240                col: 0,
9241                kind: None,
9242            });
9243        }
9244    };
9245    // RUN exec form: the list routes structured through `lower` (the
9246    // mock wraps it in `Run`; production maps it to `RunExec`); the
9247    // caller continues past the list, like the grammar. The list
9248    // rides gapped (`sep`): a joint bracket is a hard error, never
9249    // a spliced arg (probed `RUN["a"]`).
9250    if head == KEYWORD_RUN
9251        && matches!(
9252            body.get(1).map(|t| &t.kind),
9253            Some(TokKind::Group {
9254                delim: GroupDelim::Bracket,
9255                ..
9256            })
9257        )
9258    {
9259        if body[1].joint {
9260            return Err(TokenError {
9261                diagnostic: None,
9262                hint: None,
9263                stmt,
9264                msg: format!("{KEYWORD_RUN} [...] requires a gap after {KEYWORD_RUN}"),
9265                line: 0,
9266                col: 0,
9267                kind: None,
9268            });
9269        }
9270        let inner = match &body[1].kind {
9271            TokKind::Group { inner, .. } => inner.clone(),
9272            _ => unreachable!(),
9273        };
9274        // Non-map blocks miss the exec shape (the grammar has no
9275        // `block` alternative here); fall through to the shell path
9276        // below, which reads the bracket literally.
9277        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
9278            let kind =
9279                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
9280            return Ok((kind, 2));
9281        }
9282    }
9283    let (tokens, deferred) = build_arg_tokens(&body[1..], stmt, ctx)?;
9284    let lowered = lower_generic_args(&head, tokens, stmt, ctx);
9285    match lowered {
9286        Ok(kind) => {
9287            // Stashed call errors surface only for otherwise well-formed
9288            // statements: the command head owns its syntax, so a malformed
9289            // header keeps its tailored error instead of being masked by an
9290            // argument-position resolution failure.
9291            if let Some(err) = deferred {
9292                return Err(err);
9293            }
9294            Ok((kind, body.len()))
9295        }
9296        Err(lower_err) => {
9297            // Fallback raw strings (`NOPE()` rendered as text) can fail
9298            // argument-shape lowering with a misleading error. The
9299            // stashed unknown-callee error names the real culprit, so
9300            // it wins over every argument-level failure (`Validation`,
9301            // `Syntax`, `InvalidSyntax`, or the `None` classification
9302            // that `ENV`/`EXPAND` lowering uses). Heads owned by a
9303            // statement-header parser (`FUNC`, `LET`, `IF`, `FOR`,
9304            // `WHILE`, `TYPE`, `IMPORT`, `EXPORT`, `REMOTE`, `WITH_IO`)
9305            // keep their lowering `InvalidSyntax`: those parsers miss to
9306            // this path on shape miss (e.g. `FUNC FOO() ECHO hi` has no
9307            // body block), so the lowering error names the malformed
9308            // header while the stashed name is its definiendum, never an
9309            // argument-position call. Every other head is a plain
9310            // command, so a lowering `InvalidSyntax` there is an
9311            // argument-shape failure from the raw-text fallback, and
9312            // the stashed callee names the culprit. Only
9313            // head-identity errors (`UnknownCommand`, `Structural`)
9314            // keep their tailored diagnostic everywhere.
9315            let is_header_syntax = matches!(
9316                head.as_str(),
9317                KEYWORD_FUNC
9318                    | KEYWORD_LET
9319                    | KEYWORD_CONST
9320                    | KEYWORD_IF
9321                    | KEYWORD_SWITCH
9322                    | KEYWORD_FOR
9323                    | KEYWORD_WHILE
9324                    | KEYWORD_TYPE
9325                    | KEYWORD_IMPORT
9326                    | KEYWORD_EXPORT
9327                    | KEYWORD_REMOTE
9328                    | KEYWORD_WITH_IO
9329            ) && matches!(
9330                lower_err.kind,
9331                Some(crate::error::ParseErrorKind::InvalidSyntax { .. })
9332            );
9333            if let Some(deferred_err) = deferred
9334                && !is_header_syntax
9335                && matches!(
9336                    lower_err.kind,
9337                    Some(crate::error::ParseErrorKind::Validation { .. })
9338                        | Some(crate::error::ParseErrorKind::Syntax)
9339                        | Some(crate::error::ParseErrorKind::InvalidSyntax { .. })
9340                        | None
9341                )
9342            {
9343                return Err(deferred_err);
9344            }
9345            Err(lower_err)
9346        }
9347    }
9348}
9349
9350/// Parse a token stream (either lexer) into steps. Markers normalize to
9351/// 0/0 like the fuzz harness; scopes arrive with block slices.
9352pub fn parse_tokens(
9353    toks: &[Tok],
9354    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9355) -> Result<Vec<Step>, TokenError> {
9356    let modules = ModuleTable::default();
9357    let reserved = HashSet::new();
9358    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
9359    parse_tokens_with_ctx(toks, &ctx)
9360}
9361
9362/// Parse with an explicit context (module table for call resolution).
9363/// `parse_tokens` uses empty modules.
9364pub fn parse_tokens_with_ctx(toks: &[Tok], ctx: &ParseCtx) -> Result<Vec<Step>, TokenError> {
9365    let mut out = Vec::new();
9366    *ctx.current_line.borrow_mut() = 1;
9367    let stmts = split_statements(toks, 1)?;
9368    predeclare_forward_funcs(&stmts, ctx);
9369    for (i, s) in stmts.iter().enumerate() {
9370        *ctx.current_line.borrow_mut() = s.line;
9371        out.extend(
9372            lower_stmt_steps(s, i, ctx, false, true).map_err(|e| stamp_pos(e, s.line, s.col))?,
9373        );
9374    }
9375    // Whole-script validations through the shared validators.
9376    // `INHERIT_ENV` prelude order: only leading positions read.
9377    {
9378        let mut seen_non_prelude = false;
9379        for step in &out {
9380            match &step.kind {
9381                StepKind::InheritEnv { .. } => {
9382                    if seen_non_prelude {
9383                        return Err(TokenError {
9384                            diagnostic: None,
9385                            hint: None,
9386                            stmt: out.len(),
9387                            msg: format!(
9388                                "{KEYWORD_INHERIT_ENV} must appear before any other commands"
9389                            ),
9390                            line: 0,
9391                            col: 0,
9392                            kind: None,
9393                        });
9394                    }
9395                }
9396                kind => {
9397                    if crate::commands::contains_inherit_env(kind) {
9398                        return Err(TokenError {
9399                            diagnostic: None,
9400                            hint: None,
9401                            stmt: out.len(),
9402                            msg: format!(
9403                                "{KEYWORD_INHERIT_ENV} cannot be nested inside other commands"
9404                            ),
9405                            line: 0,
9406                            col: 0,
9407                            kind: None,
9408                        });
9409                    }
9410                    // Harvest imports stay prelude: they bind functions
9411                    // and types without executing module bodies, so they
9412                    // neither read nor disturb the inherited environment.
9413                    // File imports execute arbitrary top-level steps on
9414                    // import, so they end the prelude like any other
9415                    // side-effecting command. Host-only IMPORTs emit no
9416                    // step at all, which is why they never tripped this
9417                    // gate.
9418                    if !matches!(kind, StepKind::ImportFuncs { .. }) {
9419                        seen_non_prelude = true;
9420                    }
9421                }
9422            }
9423        }
9424    }
9425    crate::commands::validate_remote_copy_placement(&out, &lowering_ctx(out.len()))
9426        .map_err(|e| lower_err(out.len(), e))?;
9427    {
9428        let top: HashSet<String> = ctx.funcs.borrow().first().cloned().unwrap_or_default();
9429        let top_imports: Vec<String> = ctx
9430            .imports
9431            .borrow()
9432            .first()
9433            .cloned()
9434            .unwrap_or_default()
9435            .into_iter()
9436            .map(|(name, _)| name)
9437            .collect();
9438        let mut top_types = HashSet::new();
9439        let mut top_consts = HashSet::new();
9440        for step in &out {
9441            if let StepKind::TypeAlias { name, .. } = &step.kind {
9442                top_types.insert(name.clone());
9443            }
9444            match &step.kind {
9445                StepKind::Bind { var, is_const, .. } if *is_const => {
9446                    top_consts.insert(var.clone());
9447                }
9448                _ => {}
9449            }
9450        }
9451        crate::commands::validate_exports(
9452            &lowering_ctx(out.len()),
9453            &ctx.exports.borrow(),
9454            &top,
9455            &top_types,
9456            &top_consts,
9457            ctx.modules,
9458            &top_imports,
9459        )
9460        .map_err(|e| lower_err(out.len(), e))?;
9461    }
9462    Ok(out)
9463}
9464
9465// ---- String entry points: lex, lower, collect exports and docs ----
9466
9467/// Source text of a 1-based line. The line just past a trailing
9468/// newline (where unbalanced groups report) reads as empty text so
9469/// caret blocks still render.
9470fn source_line_of(input: &str, line: usize) -> Option<String> {
9471    let count = input.lines().count();
9472    let idx = line.checked_sub(1)?;
9473    if idx < count {
9474        input.lines().nth(idx).map(str::to_string)
9475    } else if idx == count {
9476        Some(String::new())
9477    } else {
9478        None
9479    }
9480}
9481
9482/// Last script line (end-of-script validations blame it).
9483fn last_line(input: &str) -> usize {
9484    input.lines().count().max(1)
9485}
9486
9487/// Convert a lexer failure: low-level syntax kind, exact lexer
9488/// position, and the source line for the caret block. Unclosed groups
9489/// name their opener (no grammar dumps); the closer expectation rides
9490/// along so `expected()` stays informative. A lexer-known kind (an
9491/// unclosed `WITH_IO` bracket) converts verbatim.
9492fn lex_error(input: &str, e: LexError) -> ParseError {
9493    let line = e.line.max(1);
9494    let ctx = match source_line_of(input, line) {
9495        Some(source_line) => SpanContext::full(line, e.col.max(1), e.col.max(1), source_line),
9496        None => SpanContext::line_only(line),
9497    };
9498    if let Some(ParseErrorKind::InvalidSyntax { command }) = e.kind {
9499        // Lexer-known command syntax (an unclosed `WITH_IO` bracket).
9500        return ParseError::invalid_syntax(
9501            &command,
9502            e.msg,
9503            None,
9504            vec!["`]`".to_string()],
9505            None,
9506            &ctx,
9507        );
9508    }
9509    let expected = if e.msg.starts_with("unclosed") {
9510        vec!["`}`".to_string()]
9511    } else {
9512        Vec::new()
9513    };
9514    ParseError::syntax(e.msg, expected, None, &ctx)
9515}
9516
9517/// Convert a backend failure, preserving the dispatcher's error kind
9518/// and completing line/source context the token stream knows. Spans
9519/// open at the statement's start column and cover its whole first line
9520/// (multi-line spans clamp to the start line), so caret blocks render
9521/// for every string-path error.
9522fn token_error(input: &str, e: TokenError) -> ParseError {
9523    let line = if e.line == 0 {
9524        last_line(input)
9525    } else {
9526        e.line
9527    };
9528    let start_col = e.col.max(1);
9529    let ctx = match source_line_of(input, line) {
9530        Some(source_line) => {
9531            let end = source_line.len().max(start_col);
9532            SpanContext::full(line, start_col, end, source_line)
9533        }
9534        None => SpanContext::line_only(line),
9535    };
9536    // Column spans are statement granularity (every error names its
9537    // statement's first column); the caret block still renders.
9538    // A carried diagnostic reattaches verbatim (key and fields
9539    // survive); only parser-native errors rewrap from the message
9540    // string as before. A carried hint reattaches alongside, so
9541    // `hint()` survives the round trip on every path.
9542    if let Some(diagnostic) = e.diagnostic {
9543        let kind = e.kind.unwrap_or(ParseErrorKind::Structural {
9544            rule: "statement".to_string(),
9545        });
9546        return ParseError::from_diagnostic(kind, *diagnostic, &ctx).with_hint(e.hint);
9547    }
9548    let hint = e.hint;
9549    match e.kind {
9550        Some(crate::error::ParseErrorKind::UnknownCommand { name }) => {
9551            ParseError::unknown_command(&name, e.msg, hint, &ctx)
9552        }
9553        Some(crate::error::ParseErrorKind::InvalidSyntax { command }) => {
9554            ParseError::invalid_syntax(&command, e.msg, None, Vec::new(), hint, &ctx)
9555        }
9556        Some(crate::error::ParseErrorKind::Validation { command }) => {
9557            ParseError::validation(&command, e.msg, &ctx)
9558        }
9559        Some(crate::error::ParseErrorKind::Syntax) => {
9560            ParseError::syntax(e.msg, Vec::new(), hint, &ctx)
9561        }
9562        Some(crate::error::ParseErrorKind::Structural { rule }) => {
9563            ParseError::structural(&rule, e.msg, &ctx)
9564        }
9565        None => ParseError::structural("statement", e.msg, &ctx),
9566    }
9567}
9568
9569/// Shared parse driver: lex, lower with preseeded frames, and collect
9570/// `EXPORT` names (validated at end of parse, forward references
9571/// allowed).
9572fn parse_with_ctx(
9573    input: &str,
9574    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9575    reserved_names: HashSet<String>,
9576    modules: ModuleTable,
9577    preseed_funcs: HashSet<String>,
9578    preseed_imports: Vec<String>,
9579) -> ParseResult<ScriptWithExports> {
9580    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
9581    let ctx = ParseCtx::empty(&lower, &modules, &reserved_names);
9582    // Snippet re-parses seed their base frames so lookup behaves
9583    // identically; snippets never define, only read.
9584    ctx.funcs.borrow_mut()[0].extend(preseed_funcs);
9585    ctx.imports.borrow_mut()[0].extend(preseed_imports.into_iter().map(|name| (name, false)));
9586    let steps = parse_tokens_with_ctx(&toks, &ctx).map_err(|e| token_error(input, e))?;
9587    let mut steps = steps;
9588    stamp_func_docs(input, &mut steps);
9589    Ok(ScriptWithExports {
9590        steps,
9591        exports: ctx.exports.borrow().clone(),
9592    })
9593}
9594
9595/// Steps plus single-file `EXPORT` metadata, before `#` doc stamping.
9596/// Callers needing docs build a [`ParsedScript`] from this.
9597struct ScriptWithExports {
9598    steps: Vec<Step>,
9599    exports: Exports,
9600}
9601
9602/// Parse a script with an unknown host environment.
9603pub fn parse_script(
9604    input: &str,
9605    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9606) -> ParseResult<Vec<Step>> {
9607    Ok(parse_with_ctx(
9608        input,
9609        lower,
9610        HashSet::new(),
9611        ModuleTable::default(),
9612        HashSet::new(),
9613        Vec::new(),
9614    )?
9615    .steps)
9616}
9617
9618/// Parse a snippet with an enclosing parse's visible scope state, so
9619/// re-parsed inner commands (async bodies) resolve calls identically.
9620/// The snippet never defines, only reads: seeds affect lookup alone.
9621pub fn parse_script_with_preseed(
9622    input: &str,
9623    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9624    reserved_names: HashSet<String>,
9625    modules: ModuleTable,
9626    preseed_funcs: HashSet<String>,
9627    preseed_imports: Vec<String>,
9628) -> ParseResult<Vec<Step>> {
9629    Ok(parse_with_ctx(
9630        input,
9631        lower,
9632        reserved_names,
9633        modules,
9634        preseed_funcs,
9635        preseed_imports,
9636    )?
9637    .steps)
9638}
9639
9640/// Parse with a module provenance table so calls resolve statically:
9641/// qualified `MODULE::NAME` checks membership, bare `NAME` resolves through
9642/// `SCRIPT` definitions and `IMPORT`ed modules, and anything else fails at
9643/// parse time instead of at runtime.
9644pub fn parse_script_with_modules(
9645    input: &str,
9646    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9647    reserved_names: HashSet<String>,
9648    modules: ModuleTable,
9649) -> ParseResult<Vec<Step>> {
9650    Ok(parse_script_with_modules_and_exports(input, lower, reserved_names, modules)?.steps)
9651}
9652
9653/// Parse with modules plus single-file `EXPORT` metadata and `#` doc
9654/// comments for top-level `FUNC`s. Used by the MCP host; the linear
9655/// runner keeps using `parse_script_with_modules` and ignores exports.
9656pub fn parse_script_with_modules_and_exports(
9657    input: &str,
9658    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9659    reserved_names: HashSet<String>,
9660    modules: ModuleTable,
9661) -> ParseResult<ParsedScript> {
9662    let ScriptWithExports { steps, exports } = parse_with_ctx(
9663        input,
9664        lower,
9665        reserved_names,
9666        modules,
9667        HashSet::new(),
9668        Vec::new(),
9669    )?;
9670    Ok(ParsedScript {
9671        func_docs: collect_func_docs(input, &steps),
9672        steps,
9673        exports,
9674    })
9675}
9676
9677/// Parse without modules plus `EXPORT` metadata. Used by tests and
9678/// tooling that lower with the shared mock.
9679pub fn parse_script_with_exports(
9680    input: &str,
9681    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9682) -> ParseResult<ParsedScript> {
9683    let ScriptWithExports { steps, exports } = parse_with_ctx(
9684        input,
9685        lower,
9686        HashSet::new(),
9687        ModuleTable::default(),
9688        HashSet::new(),
9689        Vec::new(),
9690    )?;
9691    Ok(ParsedScript {
9692        func_docs: collect_func_docs(input, &steps),
9693        steps,
9694        exports,
9695    })
9696}
9697
9698/// Parse one expression from source text with an empty module scope, for
9699/// tooling that shows lowering without running (docs demos, explain output).
9700/// No imports exist here, so bare function calls fail and qualified calls
9701/// fail against the empty table; only `INSPECT` passes through untouched.
9702/// Arithmetic, comparison, variables, env reads, keypaths, and literals
9703/// lower normally, with literal only subtrees folded before flattening.
9704pub fn parse_expression_str(input: &str) -> ParseResult<Expr> {
9705    // Trailing whitespace lexes unconsumed, so lex the trimmed text:
9706    // otherwise padded but valid input fails the full consumption check.
9707    let trimmed = input.trim();
9708    let toks = lex_str(trimmed).map_err(|e| lex_error(trimmed, e))?;
9709    let modules = ModuleTable::default();
9710    let reserved = HashSet::new();
9711    let lower = crate::commands::lower_command as fn(&str, Vec<Arg>) -> ParseResult<StepKind>;
9712    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
9713    *ctx.current_line.borrow_mut() = 1;
9714    parse_single_expr(&toks, 0, &ctx).map_err(|e| token_error(trimmed, e))
9715}
9716
9717/// Parse one guard expression from source text (a bare `guard_seq`:
9718/// predicates, `not`/`any`/`all`, comma lists), for tooling and tests.
9719pub fn parse_guard_expr_str(input: &str) -> ParseResult<GuardExpr> {
9720    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
9721    parse_single_guard(&toks, 0).map_err(|e| token_error(input, e))
9722}
9723
9724/// Parsed script with single-file `EXPORT` metadata. `steps` is the
9725/// linear execution plan, `exports` the `EXPORT` names in source order
9726/// per kind, and `func_docs` maps top-level `FUNC` base names to
9727/// (summary, docs) collected from the immediately preceding `#`
9728/// comment block.
9729#[derive(Debug, Clone, Default)]
9730pub struct ParsedScript {
9731    pub steps: Vec<Step>,
9732    pub exports: Exports,
9733    pub func_docs: std::collections::HashMap<String, (String, String)>,
9734}
9735
9736/// One `EXPORT` list kind. Single owner for the func/type/const
9737/// distinction, so the duplicate rule and every holder never restate
9738/// the three-way split.
9739#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9740pub enum ExportKind {
9741    Func,
9742    Type,
9743    Const,
9744}
9745
9746/// Single-file `EXPORT` metadata: per-kind names in source order.
9747/// Separate lists (never one mixed vec) so the MCP server never
9748/// confuses a type for a tool, and reads stay kind-addressed.
9749#[derive(Debug, Clone, Default)]
9750pub struct Exports {
9751    pub funcs: Vec<String>,
9752    pub types: Vec<String>,
9753    pub consts: Vec<String>,
9754}
9755
9756impl Exports {
9757    /// Record one `EXPORT` name, enforcing the duplicate rule.
9758    /// Uniqueness is by exported base name for every kind: `EXPORT FOO`
9759    /// and `EXPORT LIB::FOO` name one servable tool, `EXPORT CONST $N`
9760    /// and `EXPORT CONST $A::N` name one read, so the second spelling
9761    /// shapes the same `duplicate EXPORT` instead of silently
9762    /// shadowing. One base name rides exactly one export kind.
9763    /// `Err` carries the `duplicate EXPORT` message unchanged.
9764    pub fn insert(&mut self, kind: ExportKind, name: String) -> Result<(), String> {
9765        let base = crate::base_name(&name);
9766        let clash = [&self.funcs, &self.types, &self.consts]
9767            .iter()
9768            .any(|list| list.iter().any(|e| crate::base_name(e) == base));
9769        if clash {
9770            return Err(format!("duplicate {KEYWORD_EXPORT} `{name}`"));
9771        }
9772        match kind {
9773            ExportKind::Func => self.funcs.push(name),
9774            ExportKind::Type => self.types.push(name),
9775            ExportKind::Const => self.consts.push(name),
9776        }
9777        Ok(())
9778    }
9779}
9780
9781fn collect_func_docs(
9782    input: &str,
9783    steps: &[Step],
9784) -> std::collections::HashMap<String, (String, String)> {
9785    use std::collections::{HashMap, HashSet};
9786    let lines: Vec<&str> = input.lines().collect();
9787    // Top-level FUNC definition lines keyed by base name. Brace depth
9788    // tracks nesting so only depth-0 `FUNC` lines count; the first
9789    // occurrence wins because same-scope duplicates fail at lowering.
9790    let mut def_lines: HashMap<String, usize> = HashMap::new();
9791    let mut seen: HashSet<String> = HashSet::new();
9792    let mut depth: usize = 0;
9793    for (idx, line) in lines.iter().enumerate() {
9794        let trimmed = line.trim_start();
9795        let is_comment = trimmed.starts_with('#');
9796        let is_guard_only = trimmed.starts_with('[');
9797        if !is_comment
9798            && !is_guard_only
9799            && let Some(rest) = strip_func_head(trimmed)
9800            && depth == 0
9801            && !seen.contains(&rest)
9802        {
9803            seen.insert(rest.clone());
9804            def_lines.insert(rest, idx + 1);
9805        }
9806        if !is_comment {
9807            for ch in line.chars() {
9808                if ch == '{' {
9809                    depth = depth.saturating_add(1);
9810                } else if ch == '}' {
9811                    depth = depth.saturating_sub(1);
9812                }
9813            }
9814        }
9815    }
9816    let mut out: HashMap<String, (String, String)> = HashMap::new();
9817    for step in steps {
9818        if let StepKind::FuncDef { name, .. } = &step.kind
9819            && !out.contains_key(name)
9820            && let Some(&line_no) = def_lines.get(name)
9821            && let Some((summary, docs)) = docs_above(&lines, line_no)
9822        {
9823            out.insert(name.clone(), (summary, docs));
9824        }
9825    }
9826    out
9827}
9828
9829/// Stamp `#` doc blocks onto top-level `FUNC` steps, from the same map
9830/// that feeds `func_docs`, so step-carried docs and the sidecar can
9831/// never disagree. Only top-level definitions qualify (same rule as
9832/// collection); nested shadowing keeps `docs: None`.
9833fn stamp_func_docs(input: &str, steps: &mut [Step]) {
9834    let docs = collect_func_docs(input, steps);
9835    for step in steps {
9836        if let StepKind::FuncDef {
9837            name, docs: slot, ..
9838        } = &mut step.kind
9839            && slot.is_none()
9840            && let Some(pair) = docs.get(name)
9841        {
9842            *slot = Some(pair.clone());
9843        }
9844    }
9845}
9846
9847fn strip_func_head(trimmed: &str) -> Option<String> {
9848    let rest = trimmed.strip_prefix(KEYWORD_FUNC)?;
9849    let after = rest.strip_prefix([' ', '\t'])?;
9850    if after.is_empty() {
9851        return None;
9852    }
9853    let name: String = after
9854        .chars()
9855        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
9856        .collect();
9857    if name.is_empty()
9858        || !name
9859            .bytes()
9860            .all(|b| b.is_ascii_uppercase() || b == b'_' || b.is_ascii_digit())
9861    {
9862        return None;
9863    }
9864    if name.starts_with(|c: char| c.is_ascii_digit()) {
9865        return None;
9866    }
9867    Some(name)
9868}
9869
9870fn docs_above(lines: &[&str], line_no: usize) -> Option<(String, String)> {
9871    if line_no <= 1 {
9872        return None;
9873    }
9874    let mut block: Vec<String> = Vec::new();
9875    let mut idx = line_no - 1;
9876    while idx > 0 {
9877        idx -= 1;
9878        let trimmed = lines[idx].trim_start();
9879        if trimmed.is_empty() {
9880            break;
9881        }
9882        if let Some(body) = trimmed.strip_prefix('#') {
9883            let text = body.strip_prefix(' ').unwrap_or(body);
9884            block.push(text.to_string());
9885        } else {
9886            break;
9887        }
9888        if idx == 0 {
9889            break;
9890        }
9891    }
9892    if block.is_empty() {
9893        return None;
9894    }
9895    block.reverse();
9896    let summary = block.first().cloned().unwrap_or_default();
9897    let docs = block.join("\n");
9898    Some((summary, docs))
9899}
9900
9901#[cfg(test)]
9902mod tests {
9903    use super::*;
9904    use crate::test_lower_mock;
9905    use indoc::indoc;
9906
9907    fn lower(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9908        test_lower_mock::lower(name, args)
9909    }
9910
9911    /// Lexer-agreement oracle: both frontends must deliver identical
9912    /// steps through the single backend. `parse_script` is the string
9913    /// entry point; `parse_tokens` runs each lexer's output directly.
9914    fn assert_parity(text: &str) {
9915        let old = crate::parse_script(text, lower)
9916            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9917        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9918        let new = parse_tokens(&toks, lower)
9919            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9920        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9921        #[cfg(feature = "proc-macro-api")]
9922        {
9923            let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
9924            let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
9925            let new = parse_tokens(&toks, lower).expect("token path must parse token script");
9926            assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
9927        }
9928    }
9929
9930    /// String-path-only oracle for shapes `rustc` cannot carry at all
9931    /// (lifetime-like quotes). The backend must still agree there.
9932    fn assert_parity_string_only(text: &str) {
9933        let old = crate::parse_script(text, lower)
9934            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9935        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9936        let new = parse_tokens(&toks, lower)
9937            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9938        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9939    }
9940
9941    #[test]
9942    fn token_and_string_paths_agree_on_wrappers() {
9943        // Single-command wrappers, io-blocks, await/cancel,
9944        // LET wrapper forms — three-way agreement per script.
9945        for text in [
9946            "WITH_IO [stdout=$p] ECHO hi",
9947            "WITH_IO [stdin=$p] ECHO hi",
9948            "WITH_IO [stdin] ECHO hi",
9949            "WITH_IO [stdout] ECHO hi",
9950            "WITH_IO [stdin=$p, stdout=$q] ECHO hi",
9951            "WITH_IO [stdin=$p, stdin=$q] ECHO hi",
9952            "WITH_IO [tty] RUN echo hi",
9953            "WITH_IO [tty, rows=40, cols=100] RUN echo hi",
9954            "WITH_IO [rows=40, cols=100, tty] RUN echo hi",
9955            "WITH_IO [stdin =$p] ECHO hi",
9956            "WITH_IO [stdin= $p] ECHO hi",
9957            "WITH_IO [ stdin=$p ] ECHO hi",
9958            "WITH_IO [\nstdin=$p\n] ECHO hi",
9959            "WITH_IO [stdin=$p\n, stdout=$q] ECHO hi",
9960            "WITH_IO [stdout=$p] ASYNC ECHO hi",
9961            "WITH_IO [stdin=$p] WITH_IO [stderr=$e] ECHO hi",
9962            "WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
9963            "WITH_IO [stdin=$p] ISOLATED ECHO hi",
9964            "WITH_IO [stdin=$p] CANCEL $t",
9965            "WITH_IO [stdin=$p] CANCEL $t ECHO bye",
9966            "WITH_IO [stdin=$p] { ECHO hi }",
9967            "WITH_IO [stdin=$p]\n{ ECHO hi }",
9968            "WITH_IO [stdin=$p]; { ECHO hi }",
9969            "WITH_IO [stdin=$p]{ ECHO hi }",
9970            "WITH_IO [stdin=$p] { ECHO a\nECHO b }",
9971            "WITH_IO [stdin=$p] { ECHO hi } ECHO bye",
9972            "WITH_IO [rows=40] { ECHO hi }",
9973            "WITH_IO [tty] { ECHO hi }",
9974            "WITH_IO [stdin=$p] { WITH_IO [stderr=$e] ECHO hi }",
9975            "TIMEOUT 10s ECHO hi",
9976            "TIMEOUT 10 ECHO hi",
9977            "TIMEOUT 500ms ECHO hi",
9978            "TIMEOUT 5m ECHO hi",
9979            "TIMEOUT 2h ECHO hi",
9980            "TIMEOUT $d ECHO hi",
9981            "TIMEOUT \"10s\" ECHO hi",
9982            "TIMEOUT \"30 s\" ECHO hi",
9983            "TIMEOUT {{ $d }} ECHO hi",
9984            "TIMEOUT 10s AWAIT $t",
9985            "TIMEOUT 10s CANCEL $t",
9986            "TIMEOUT 10s AWAIT $t ECHO bye",
9987            "TIMEOUT 10s CANCEL $t ECHO bye",
9988            "TIMEOUT 10s { ECHO hi }",
9989            "TIMEOUT 10s {\nECHO hi\n}",
9990            "TIMEOUT 10s { ECHO hi } ECHO bye",
9991            "TIMEOUT 10s { ECHO hi } TIMEOUT 5s ECHO bye",
9992            "TIMEOUT 10s TIMEOUT 5s ECHO hi",
9993            "TIMEOUT 10s { ECHO a\nECHO b }",
9994            "TIMEOUT 10s ECHO hi extra",
9995            "ISOLATED ECHO hi",
9996            "ISOLATED { ECHO hi }",
9997            "ISOLATED { ECHO hi } ECHO bye",
9998            "ISOLATED AWAIT $t",
9999            "ISOLATED INHERIT_ENV [M]",
10000            "ISOLATED { INHERIT_ENV [M] }",
10001            "ISOLATED { INHERIT_ENV [MODE]\nECHO hi }",
10002            "ASYNC ECHO hi",
10003            "ASYNC { ECHO hi }",
10004            "ASYNC{ECHO hi}",
10005            "ASYNC { ECHO a\nECHO b }",
10006            "ASYNC { ECHO hi } ECHO bye",
10007            "ASYNC CANCEL $t",
10008            "ASYNC CANCEL $t ECHO bye",
10009            "AWAIT $t",
10010            "AWAIT$t",
10011            "AWAIT $ t",
10012            "AWAIT $T",
10013            "AWAIT $t2",
10014            "AWAIT $_t",
10015            "CANCEL $t",
10016            "CANCEL$t",
10017            "CANCEL $ t",
10018            "AWAIT $t ECHO bye",
10019            "CANCEL $t ECHO bye",
10020            "AWAIT $t AWAIT $u",
10021            "AWAIT $t\nECHO bye",
10022            "LET $t: HANDLE = ASYNC ECHO hi",
10023            "LET $t: HANDLE = ASYNC { ECHO hi }",
10024            "LET $t: HANDLE = ASYNC { ECHO hi } ECHO bye",
10025            "LET $a: STRING = ASYNC ECHO hi",
10026            "LET $t: HANDLE = ASYNC { WITH_IO [stdin=$p] ECHO hi }",
10027            "LET $w: STRING = WITH_IO [stdin=$p] ASYNC ECHO hi",
10028            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC ECHO hi",
10029            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi }",
10030            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi } ECHO bye",
10031            "LET $x: STRING = WITH_IO [stdin=$p] ECHO hi",
10032            "LET $x: STRING = WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
10033            "LET $x: STRING = TIMEOUT 10s ECHO hi",
10034            "LET $x: STRING = TIMEOUT 10s { ECHO hi }",
10035            "LET $x: STRING = TIMEOUT 10s ECHO hi ECHO bye",
10036            "LET $o: STRING = AWAIT $t",
10037            "LET $p: PIPE ECHO bye",
10038            "TIMEOUT 10s WITH_IO [stdin=$p]",
10039            "TIMEOUT 10s WITH_IO [stdin=$p]ECHO hi",
10040            "ISOLATED INHERIT_ENV [A, B]",
10041            "ISOLATED INHERIT_ENV [A-B]",
10042            "TIMEOUT 10s { [os:linux] ECHO hi }",
10043            "ASYNC { [os:linux] ECHO hi }",
10044            "ISOLATED { [os:linux] ECHO hi }",
10045            "[os:linux] WITH_IO [stdin=$p]\n{ ECHO hi }",
10046            "LET $x: INT = 1 ECHO bye",
10047            "CANCEL $t LET $x: INT = 1",
10048            "CANCEL $t $x = 1",
10049            "CANCEL $t RETURN \"hi\"",
10050            "TIMEOUT 10s { ECHO hi } LET $x: INT = 1",
10051            "RUN [\"a\"] ECHO bye",
10052            "[os:linux] AWAIT $t",
10053            "[os:linux] TIMEOUT 10s { ECHO hi } ECHO bye",
10054            "[os:linux] ASYNC CANCEL $t ECHO bye",
10055            "[os:linux] WITH_IO [stdin=$p] { [os:macos] ECHO hi }",
10056        ] {
10057            assert_parity(text);
10058        }
10059    }
10060
10061    #[test]
10062    fn token_and_string_paths_agree_on_blocks() {
10063        // Slice 5: `IF`/`FOR`/`WHILE`/`FUNC` with inline and
10064        // cross-newline `ELSE` chains, guard blocks (top-level and
10065        // nested quirk), and multi-element trailing — three-way
10066        // agreement per script.
10067        for text in [
10068            "IF true { ECHO hi }",
10069            "IF $x { ECHO hi } ELSE { ECHO bye }",
10070            "IF true { ECHO a } ELSE IF false { ECHO b } ELSE { ECHO c }",
10071            "IF true{ ECHO hi }",
10072            "IF true { ECHO hi } ECHO bye",
10073            "IF true { ECHO hi }\nELSE { ECHO bye }",
10074            "IF true { ECHO hi }\nELSE IF false { ECHO b }\nELSE { ECHO c }",
10075            "IF true { ECHO hi } //c\nELSE { ECHO bye }",
10076            "IF true { ECHO hi } #c\nELSE { ECHO bye }",
10077            "IF true { ECHO hi }//c\nELSE { ECHO bye }",
10078            "IF true { ECHO hi } /*c*/ ELSE { ECHO bye }",
10079            "IF true { ECHO hi } /*c1*/ /*c2*/\nELSE { ECHO bye }",
10080            "IF true { /*c*/ ECHO hi }",
10081            "IF true { [os:linux] ECHO hi }",
10082            "TIMEOUT 10s { IF true { ECHO hi } }",
10083            "TIMEOUT 10s { IF true { ECHO hi }\nELSE { ECHO bye } }",
10084            "FOR $x: INT IN [1] { ECHO hi }",
10085            "FOR $k: STRING, $v: INT IN $m { ECHO hi }",
10086            "FOR $k: INT IN [1] { ECHO hi }",
10087            "FOR $x: INT IN [1]{ ECHO hi }",
10088            "FOR $x: MAP<name: STRING> IN [1] { ECHO hi }",
10089            "FOR $x: INT IN [1] { ECHO hi } ECHO bye",
10090            "WHILE true { ECHO hi }",
10091            "WHILE $x { ECHO hi }",
10092            "WHILE true{ ECHO hi }",
10093            "TIMEOUT 10s WHILE true { ECHO hi }",
10094            "ASYNC WHILE true { ECHO hi }",
10095            "FUNC FOO(): INT { RETURN 1 }",
10096            "FUNC FOO(): INT { RETURN 1 }",
10097            "FUNC FOO($x: INT): INT { RETURN $x }",
10098            "FUNC FOO($x: INT, $y: STRING): INT { RETURN $x }",
10099            "FUNC FOO(): INT { FUNC FOO(): INT { RETURN 1 } }",
10100            "FUNC FOO(): INT { RETURN 1 }\nFUNC BAR(): VOID { FOO() }\nBAR()",
10101            "TYPE PERSON = MAP<name: STRING>",
10102            "TYPE A=B",
10103            "TYPE A = B | C",
10104            "TYPE A = B\nTYPE A = C",
10105            "INHERIT_ENV [A]\nECHO hi",
10106            "[os:linux] INHERIT_ENV [M]",
10107            "INHERIT_ENV [A]\nINHERIT_ENV [B]\nECHO hi",
10108            "ISOLATED INHERIT_ENV [M]",
10109            "ISOLATED { INHERIT_ENV [M] }",
10110            "ISOLATED INHERIT_ENV [A, B]",
10111            "ISOLATED INHERIT_ENV [A-B]",
10112            "REMOTE prod { ECHO hi }",
10113            "REMOTE prod [$v] { ECHO hi }",
10114            "REMOTE prod [$v, env:E] { ECHO hi }",
10115            "REMOTE prod [] { ECHO hi }",
10116            "REMOTE prod[$v] { ECHO hi }",
10117            "REMOTE prod [$v]{ ECHO hi }",
10118            "REMOTE prod{ ECHO hi }",
10119            "REMOTE  prod  { ECHO hi }",
10120            "REMOTE prod [$v, $v] { ECHO hi }",
10121            "REMOTE prod { ECHO hi } ECHO bye",
10122            "TIMEOUT 10s REMOTE prod { ECHO hi }",
10123            "ASYNC REMOTE prod [$v] { ECHO hi }",
10124            "[os:linux] { ECHO hi }",
10125            "[os:linux]\n{ ECHO hi }",
10126            "[os:linux] { [os:macos] ECHO hi }",
10127            "[os:linux] { [os:macos] ECHO hi\nECHO bye }",
10128            "[os:linux] { [os:macos] { ECHO hi } }",
10129            "TIMEOUT 10s { [os:linux] { [os:macos] ECHO hi } }",
10130            "TIMEOUT 10s { [os:linux] [os:windows] { ECHO hi } }",
10131            "TIMEOUT 10s { [os:linux] { ECHO hi } ECHO bye }",
10132            "LET $x: INT = 1 ECHO bye",
10133            KEYWORD_BREAK,
10134            KEYWORD_CONTINUE,
10135            "BREAK ECHO hi",
10136            "FOR $x: INT IN [1] { BREAK }",
10137            "LET $b: STRING = { RETURN \"hi\" }",
10138            "ECHO { RETURN \"hi\" }",
10139            "RUN [{ RETURN \"hi\" }]",
10140            "[not(env:FOO)] WRITE x",
10141            "[\nnot(env:FOO)\n] WRITE x",
10142            "WRITE env.txt \"{{ env:GREETING }}\"",
10143            "CANCEL $t LET $x: INT = 1",
10144            "RUN [\"a\"] ECHO bye",
10145        ] {
10146            assert_parity(text);
10147        }
10148    }
10149
10150    #[test]
10151    fn multi_line_generics_match_single_line_shape() {
10152        // Multi-line `<...>` shapes parse, and canonicalize exactly
10153        // like their single-line spelling.
10154        for (single, multi) in [
10155            (
10156                "TYPE R = MAP<name: STRING, value: INT>",
10157                "TYPE R = MAP<name: STRING,\nvalue: INT>",
10158            ),
10159            (
10160                "TYPE R = MAP<name: STRING, value: LIST<INT>>",
10161                "TYPE R = MAP<name: STRING,\nvalue: LIST<INT>>",
10162            ),
10163            (
10164                "TYPE R = MAP<name: STRING, value: INT>",
10165                "TYPE R = MAP<\nname: STRING,\nvalue: INT\n>",
10166            ),
10167            (
10168                "LET $m: MAP<name: STRING, value: INT> = {}",
10169                "LET $m: MAP<name: STRING,\nvalue: INT> = {}",
10170            ),
10171            (
10172                "FOR $x: LIST<INT> IN [1] { ECHO hi }",
10173                "FOR $x: LIST<\nINT> IN [1] { ECHO hi }",
10174            ),
10175            ("TYPE R = MAP<x: A | B>", "TYPE R = MAP<x: A |\nB>"),
10176        ] {
10177            assert_parity(multi);
10178            let want = crate::parse_script(single, lower)
10179                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
10180            let got = crate::parse_script(multi, lower)
10181                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
10182            assert_eq!(
10183                got, want,
10184                "multi-line must canonicalize like one line: {multi:?}"
10185            );
10186        }
10187    }
10188
10189    #[test]
10190    fn type_field_defaults_parse_to_canonical_targets() {
10191        // Token-level regression: `= literal` tails belong to the
10192        // field (floats lex as three tokens), and the statement
10193        // target canonicalizes exactly like the spelling parser.
10194        for (text, want) in [
10195            ("TYPE F = MAP<retries: INT = 2>", "MAP<retries: INT = 2>"),
10196            ("TYPE F = MAP<retries: INT=-2>", "MAP<retries: INT = -2>"),
10197            (
10198                "TYPE F = MAP<ratio: FLOAT = 2.5>",
10199                "MAP<ratio: FLOAT = 2.5>",
10200            ),
10201            ("TYPE F = MAP<on: BOOL = true>", "MAP<on: BOOL = true>"),
10202            (
10203                "TYPE F = MAP<model: STRING = \"gpt-4\">",
10204                "MAP<model: STRING = \"gpt-4\">",
10205            ),
10206            (
10207                "TYPE F = MAP<k: STRING = \"d\", n: INT = 3>",
10208                "MAP<k: STRING = \"d\", n: INT = 3>",
10209            ),
10210        ] {
10211            assert_parity(text);
10212            let steps = crate::parse_script(text, lower)
10213                .unwrap_or_else(|e| panic!("default spelling must parse {text:?}: {e}"));
10214            let target = steps
10215                .iter()
10216                .find_map(|s| match &s.kind {
10217                    StepKind::TypeAlias { target, .. } => Some(target.clone()),
10218                    _ => None,
10219                })
10220                .expect("TYPE alias step");
10221            assert_eq!(target, want, "canonical target for {text:?}");
10222        }
10223    }
10224
10225    #[test]
10226    fn multi_line_run_exec_matches_single_line_shape() {
10227        // `RUN [...]` rides the shared bracket core, so a wrapped exec
10228        // list parses exactly like its single-line spelling (and agrees
10229        // across lexer frontends).
10230        for (single, multi) in [
10231            ("RUN [\"echo\", \"hi\"]", "RUN [\"echo\",\n\"hi\"]"),
10232            ("RUN [\"echo\", \"hi\"]", "RUN [\n\"echo\",\n\"hi\"\n]"),
10233            (
10234                "LET $o: STRING = RUN [\"echo\", \"hi\"]",
10235                "LET $o: STRING = RUN [\"echo\",\n\"hi\"]",
10236            ),
10237        ] {
10238            assert_parity(multi);
10239            let want = crate::parse_script(single, lower)
10240                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
10241            let got = crate::parse_script(multi, lower)
10242                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
10243            assert_eq!(
10244                got, want,
10245                "multi-line must canonicalize like one line: {multi:?}"
10246            );
10247        }
10248    }
10249
10250    #[test]
10251    fn untyped_let_fails_in_every_rhs_shape() {
10252        // The everything-typed rule: a missing `:` is a hard error
10253        // carrying the explicit-types message, regardless of what
10254        // follows the `=`. Every binding shape is covered, so no
10255        // untyped position can slip back in unnoticed.
10256        for text in [
10257            "LET $x = 1\n",
10258            "LET $x = \"hi\"\n",
10259            "LET $x = $y\n",
10260            "LET $x = [\"a\", \"b\"]\n",
10261            "LET $x = [\"a\",\n\"b\"]\n",
10262            "LET $x = ECHO hi\n",
10263            "LET $x = AWAIT $t\n",
10264            "LET $x = ASYNC ECHO hi\n",
10265            "LET $x = {\nRETURN 1\n}\n",
10266            "LET $x = WITH_IO [stdin=$p] ASYNC ECHO hi\n",
10267        ] {
10268            let err = crate::parse_script(text, lower).expect_err("untyped LET must fail");
10269            assert!(
10270                err.to_string().contains("LET requires explicit types"),
10271                "wrong error for {text:?}: {err}"
10272            );
10273        }
10274        // Typed spellings of the same shapes keep parsing through
10275        // every lexer frontend.
10276        for text in [
10277            "LET $x: INT = 1\n",
10278            "LET $x: STRING = \"hi\"\n",
10279            "LET $x: LIST<STRING> = [\"a\", \"b\"]\n",
10280            "LET $x: LIST<STRING> = [\"a\",\n\"b\"]\n",
10281            "LET $x: STRING = ECHO hi\n",
10282            "LET $x: STRING = AWAIT $t\n",
10283            "LET $x: HANDLE<VOID> = ASYNC ECHO hi\n",
10284            "LET $x: INT = {\nRETURN 1\n}\n",
10285        ] {
10286            assert_parity(text);
10287        }
10288    }
10289
10290    #[test]
10291    fn missing_comma_points_at_the_item() {
10292        // A forgotten comma between items names the missing
10293        // comma and points at the item's line, not the statement
10294        // head. Lists and call arguments share the rule.
10295        let text = indoc! {r#"
10296            LET $x: LIST<STRING> = [
10297            "a"
10298            "b",
10299            "c"
10300            ]
10301        "#};
10302        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
10303        assert!(
10304            err.to_string().contains("missing comma between list items"),
10305            "wrong error: {err}"
10306        );
10307        assert_eq!(err.line(), 3, "caret names the item line: {err}");
10308        // Same shape on one line.
10309        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" \"b\"]\n", lower)
10310            .expect_err("missing comma must fail");
10311        assert!(
10312            err.to_string().contains("missing comma between list items"),
10313            "wrong error: {err}"
10314        );
10315        assert_eq!(err.line(), 1, "single-line points at line 1: {err}");
10316        // Call arguments share the rule.
10317        let err = crate::parse_script("LET $x: STRING = FOO(\"a\" \"b\")\n", lower)
10318            .expect_err("missing comma must fail");
10319        assert!(
10320            err.to_string()
10321                .contains("missing comma between call arguments"),
10322            "wrong error: {err}"
10323        );
10324        // Genuine trailing garbage keeps the old message but still
10325        // points at the garbage instead of the statement head.
10326        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" : \"b\"]\n", lower)
10327            .expect_err("garbage must fail");
10328        assert!(
10329            err.to_string().contains("unexpected text in list"),
10330            "wrong error: {err}"
10331        );
10332        // Maps share the rule: a forgotten comma between entries
10333        // names it at the entry's line instead of misreporting the
10334        // key as an unknown command.
10335        let text = indoc! {r#"
10336            LET $m: MAP<name: STRING> = {
10337            name: "a"
10338            value: "b"
10339            }
10340        "#};
10341        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
10342        assert!(
10343            err.to_string()
10344                .contains("missing comma between map entries"),
10345            "wrong error: {err}"
10346        );
10347        assert_eq!(err.line(), 3, "caret names the entry line: {err}");
10348        let err = crate::parse_script(
10349            "LET $m: MAP<name: STRING> = {name: \"a\" value: \"b\"}\n",
10350            lower,
10351        )
10352        .expect_err("missing comma must fail");
10353        assert!(
10354            err.to_string()
10355                .contains("missing comma between map entries"),
10356            "wrong error: {err}"
10357        );
10358    }
10359
10360    #[test]
10361    fn spaced_comparisons_still_end_the_statement() {
10362        // A spaced `<` is a comparison, never a generic open: the
10363        // newline still ends the statement.
10364        let steps = crate::parse_script("LET $b: BOOL = $a < $b\nECHO hi", lower)
10365            .expect("comparison plus follower must parse");
10366        assert_eq!(steps.len(), 2, "newline ends the comparison statement");
10367    }
10368
10369    #[test]
10370    fn token_and_string_paths_agree_on_flat_commands() {
10371        for text in [
10372            "ECHO hi",
10373            "ECHO hi\nWRITE x out",
10374            "WRITE x",
10375            "ECHO \"quoted\" unquoted",
10376            "ENV COVERAGE=covered",
10377            "ECHO a; ECHO b",
10378            "// comment\nECHO hi",
10379            "ECHO 1.0.0 --flag a/b",
10380            "ECHO $x",
10381            "\n\nECHO hi\n\n",
10382        ] {
10383            assert_parity(text);
10384        }
10385    }
10386
10387    #[cfg(feature = "proc-macro-api")]
10388    #[test]
10389    fn backslash_outside_strings_is_string_only() {
10390        // `rustc` rejects a bare `\`, so unquoted backslash escapes
10391        // cannot cross `TokenStream` (same exclusion class as raw-`"`
10392        // blocks): the string lexer keeps them, the token path fails to
10393        // tokenize before v2 is ever reached.
10394        let toks = crate::tok::lex_str("ECHO a\\nb").expect("string lex keeps escapes");
10395        let old = crate::parse_script("ECHO a\\nb", lower).expect("string path parses it");
10396        assert_eq!(
10397            parse_tokens(&toks, lower).expect("token path parses it"),
10398            old
10399        );
10400        assert!("ECHO a\\nb".parse::<proc_macro2::TokenStream>().is_err());
10401    }
10402
10403    #[test]
10404    fn escaped_backslash_pair_is_atomic() {
10405        // `"a\\"` parses (one escape pair plus the closer): the pair
10406        // scans atomically, like the block-string arm and `lex_word`.
10407        // The value stays raw (`\\` verbatim for runtime
10408        // `expand_string`), so this pins parsing, not unescaping.
10409        assert_parity("ECHO \"a\\\\\"");
10410        let steps = crate::parse_script("ECHO \"a\\\\\"", lower).expect("escaped pair must parse");
10411        match &steps[..] {
10412            [s] => assert!(
10413                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a\\\\"),
10414                "escaped pair must survive raw: {s:?}"
10415            ),
10416            _ => panic!("one step: {steps:?}"),
10417        }
10418    }
10419
10420    #[test]
10421    fn joint_double_slash_stays_literal() {
10422        // `rustc` strips `//` before the macro ever runs, so these are
10423        // string-path-only by construction: joint `a//b` is one literal
10424        // arg, and `[a //c]` closes its group (the in-group `//` copy
10425        // stops at the closer).
10426        for text in ["ECHO a//b", "ECHO [a //c]"] {
10427            assert_parity_string_only(text);
10428        }
10429        let steps = crate::parse_script("ECHO a//b", lower).expect("joint slashes parse");
10430        match &steps[..] {
10431            [s] => assert!(
10432                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a//b"),
10433                "joint `//` must glue literally: {s:?}"
10434            ),
10435            _ => panic!("one step: {steps:?}"),
10436        }
10437        let steps = crate::parse_script("ECHO [a //c]", lower).expect("group must close");
10438        assert_eq!(steps.len(), 1, "one step: {steps:?}");
10439        // Full content survives literally: the mock joins WRITE args
10440        // with spaces, so the round trip is byte-exact here.
10441        let steps = crate::parse_script("WRITE f [a //c]", lower).expect("group must close");
10442        match &steps[..] {
10443            [s] => assert!(
10444                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a //c]"),
10445                "group content must survive literally: {s:?}"
10446            ),
10447            _ => panic!("one step: {steps:?}"),
10448        }
10449    }
10450
10451    #[test]
10452    fn block_comment_in_group_closes_like_line_comment() {
10453        // `[a /* c]` reads literally on the old backend (first arg
10454        // `[a`, joined `[a /* c]`), so the in-group `/*` copy breaks
10455        // at the depth-zero closer exactly like `//` does. The bare
10456        // `/*` reads literally too.
10457        for text in ["ECHO [a /* c]", "WRITE f [a /* c]", "ECHO /*"] {
10458            assert_parity_string_only(text);
10459        }
10460        let steps = crate::parse_script("ECHO /*", lower).expect("bare block open parses");
10461        match &steps[..] {
10462            [s] => assert!(
10463                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "/*"),
10464                "bare `/*` must stay literal: {s:?}"
10465            ),
10466            _ => panic!("one step: {steps:?}"),
10467        }
10468        let steps = crate::parse_script("WRITE f [a /* c]", lower).expect("group must close");
10469        match &steps[..] {
10470            [s] => assert!(
10471                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c]"),
10472                "group content must survive literally: {s:?}"
10473            ),
10474            _ => panic!("one step: {steps:?}"),
10475        }
10476        // Terminated spans keep working through the same path: the
10477        // run carries its closer, so math still gets first refusal.
10478        let steps = crate::parse_script("WRITE f [a /* c */ d]", lower).expect("group must close");
10479        match &steps[..] {
10480            [s] => assert!(
10481                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c */ d]"),
10482                "terminated group content must survive: {s:?}"
10483            ),
10484            _ => panic!("one step: {steps:?}"),
10485        }
10486    }
10487
10488    #[test]
10489    fn single_quoted_multiline_keeps_line_tracking() {
10490        // The `'` arm counts embedded newlines like the `"` arm, so the
10491        // statement after a multiline single-quoted string keeps its
10492        // own lines (func-docs stamping keys off them).
10493        let text = "ECHO 'a\nb'\nECHO c";
10494        assert_parity_string_only(text);
10495        let steps = crate::parse_script(text, lower).expect("must parse");
10496        assert_eq!(steps.len(), 2, "two steps: {steps:?}");
10497        assert_eq!((steps[0].line, steps[0].col), (1, 1));
10498        assert_eq!((steps[1].line, steps[1].col), (3, 1), "{steps:?}");
10499    }
10500
10501    #[test]
10502    fn token_and_string_paths_agree_on_guarded_commands() {
10503        for text in [
10504            "[env:X] ECHO hi",
10505            "[env:A] [os:linux] ECHO hi",
10506            "[os:macos] WRITE x",
10507            "[not(os:windows)] WRITE f x",
10508            "[any(os:macos, os:linux)] ECHO hi",
10509            "[all(env:A, os:linux)] ECHO hi",
10510            "[eq(env:K, v)] ECHO hi",
10511            "[ne(env:K, v)] ECHO hi",
10512            "[bool:true] ECHO hi",
10513            "[arch:arm] ECHO hi",
10514            "[family:unix] ECHO hi",
10515            "[(os:linux)] ECHO hi",
10516            "[env:A, os:linux] ECHO hi",
10517            "WRITE x\n[env:X] ECHO hi",
10518            "[env:K] ECHO $x",
10519            "[__OXDOCK_INJECT_1__] ECHO hi",
10520            "[eq(env:K, \"a b\")] ECHO hi",
10521            "[\nenv:X\n] ECHO hi",
10522            // In-body brackets are raw text split on whitespace (probed
10523            // parity: `[a, b]` is args `"[a,"` + `"b]"`, quotes kept).
10524            "ECHO [a, b] hi",
10525            "WRITE f [env:X]",
10526            "ECHO [env:X] hi",
10527            "WRITE f [\"a b\"]",
10528            "ECHO foo[bar]baz",
10529            "ECHO [a ]",
10530            "ECHO [ a]",
10531            "WRITE out x [env:X]",
10532        ] {
10533            assert_parity(text);
10534        }
10535        // `rustc` lexes `'a` as a lifetime start and rejects the
10536        // space: string-path-only by construction.
10537        assert_parity_string_only("ECHO ['a b']");
10538    }
10539
10540    #[test]
10541    fn token_and_string_paths_agree_on_calls_and_exact_args() {
10542        use crate::ast::{ModuleFuncs, ModuleTable};
10543        use std::collections::{HashMap, HashSet};
10544        let std_table = || ModuleTable {
10545            modules: HashMap::from([(
10546                crate::constants::STD_MODULE_NAME.to_string(),
10547                Some(ModuleFuncs {
10548                    func_names: HashSet::from(["LEN".to_string()]),
10549                }),
10550            )]),
10551        };
10552        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10553            test_lower_mock::lower(name, args)
10554        }
10555        // One table for both pathways: STD exports LEN.
10556        // Rebuilt per case (parse-time only, keeps borrows local).
10557        for text in [
10558            "LET $n: INT = STD::LEN(\"hi\")",
10559            "STD::LEN(\"hi\")",
10560            "LET $n: INT = STD::LEN(\"a\", \"b\")",
10561            "LET $s: STRING = INSPECT($x)",
10562            "INSPECT($x)",
10563            "LET $x: STRING = ECHO hi",
10564            "LET $t: STRING = WRITE x",
10565            "LET $o: STRING = RUN echo hi",
10566            "RUN [\"echo\", \"hi\"]",
10567            "RUN echo [a]",
10568            "LET $r: STRING = RUN [\"echo\"]",
10569            "ECHO K=v",
10570            "ECHO K = v",
10571            "ECHO K=a b",
10572            "ECHO K=a, b",
10573            "ECHO K=\"a b\"",
10574            "ECHO K=$x",
10575            "ECHO K=",
10576            "ECHO a = = b",
10577            "WRITE f K=v",
10578            "ECHO $a + $b",
10579            "ECHO $a==$b",
10580            "ECHO a $x b",
10581            "ECHO 5 + 3",
10582            "WRITE f ( \"hi\" )",
10583            "ECHO [a, b] hi",
10584            "ECHO {{x}}",
10585            "ECHO {{ $x }}",
10586            "ECHO $x=K",
10587            "ECHO a$x",
10588            "ECHO a$(x)",
10589            "ECHO K=$x tail",
10590            "EXPAND K1=$x K2=$y",
10591            "EXPAND a",
10592            "ENV K = v",
10593            "COPY a b",
10594            "ECHO foo[bar]baz",
10595            "LET $x: STRING = FOOBAR",
10596            "STD::LEN(\"hi\") ECHO bye",
10597            "LET $n: INT = STD::LEN(\"a\") ECHO bye",
10598            "TIMEOUT 10s STD::LEN(\"hi\")",
10599            "TIMEOUT 10s STD::LEN(\"hi\") ECHO bye",
10600            "LET $n: INT = STD::LEN(\"a\")STD::LEN(\"b\")",
10601        ] {
10602            let table = std_table();
10603            let old =
10604                crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
10605                    .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
10606            let reserved = HashSet::new();
10607            let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
10608            let toks = crate::tok::lex_str(text).expect("string lex must succeed");
10609            let new = parse_tokens_with_ctx(&toks, &ctx)
10610                .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
10611            assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
10612            #[cfg(feature = "proc-macro-api")]
10613            {
10614                let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
10615                let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
10616                let new = parse_tokens_with_ctx(&toks, &ctx)
10617                    .unwrap_or_else(|e| panic!("token path must parse token {text:?}: {e}"));
10618                assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
10619            }
10620        }
10621    }
10622
10623    #[test]
10624    fn placeholder_bare_calls_resolve_like_statements() {
10625        // `{{ NAME(args) }}` obeys exactly the statement-position
10626        // scope rule: `IMPORT [MOD]` brings the names into scope,
10627        // unimported names fail naming the fix, ambiguity fails
10628        // closed. The rewrite below is byte-identical past the
10629        // qualified head, so expansion sees the same args.
10630        use crate::ast::{ModuleFuncs, ModuleTable};
10631        use std::collections::{HashMap, HashSet};
10632        let table = || ModuleTable {
10633            modules: HashMap::from([
10634                (
10635                    crate::constants::STD_MODULE_NAME.to_string(),
10636                    Some(ModuleFuncs {
10637                        func_names: HashSet::from(["LEN".to_string()]),
10638                    }),
10639                ),
10640                (
10641                    "OTHER".to_string(),
10642                    Some(ModuleFuncs {
10643                        func_names: HashSet::from(["LEN".to_string()]),
10644                    }),
10645                ),
10646            ]),
10647        };
10648        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10649            test_lower_mock::lower(name, args)
10650        }
10651        fn echo_text(steps: &[crate::Step]) -> String {
10652            match steps {
10653                [s] => match &s.kind {
10654                    StepKind::Echo(Arg::String(text, _)) => text.clone(),
10655                    other => panic!("expected ECHO string, got {other:?}"),
10656                },
10657                _ => panic!("expected one step, got {steps:?}"),
10658            }
10659        }
10660        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10661            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10662        }
10663        // Imported bare names qualify; everything else rides through
10664        // byte-identical for the runtime to handle as before.
10665        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }}\"\n";
10666        let out = echo_text(&parse(text, table()).expect("imported bare call parses"));
10667        assert_eq!(out, "n: {{ STD::LEN($x) }}", "bare call qualifies: {out}");
10668        let text = "IMPORT [STD]\nECHO \"n: {{ STD::LEN($x) }}\"\n";
10669        let out = echo_text(&parse(text, table()).expect("qualified parses"));
10670        assert_eq!(
10671            out, "n: {{ STD::LEN($x) }}",
10672            "qualified keys stay untouched: {out}"
10673        );
10674        let text = "IMPORT [STD]\nECHO \"hi {{ $x }} and {{ bare }} and {{ env:K }}\"\n";
10675        let out = echo_text(&parse(text, table()).expect("non-calls parse"));
10676        assert_eq!(
10677            out, "hi {{ $x }} and {{ bare }} and {{ env:K }}",
10678            "non-call keys stay untouched: {out}"
10679        );
10680        let text = "IMPORT [STD]\nECHO \"lit \\{{ LEN($x) }}\"\n";
10681        let out = echo_text(&parse(text, table()).expect("escaped parses"));
10682        assert_eq!(
10683            out, "lit \\{{ LEN($x) }}",
10684            "escaped openers stay literal: {out}"
10685        );
10686        // Nested bodies resolve against the enclosing imports, exactly
10687        // like statement-position calls in the same body.
10688        let text = indoc! {r#"
10689            IMPORT [STD]
10690            FUNC F(): VOID {
10691            ECHO "n: {{ LEN($x) }}"
10692            }
10693        "#};
10694        let steps = parse(text, table()).expect("nested bare call parses");
10695        let body = steps.iter().find_map(|s| match &s.kind {
10696            StepKind::FuncDef { body, .. } => Some(body),
10697            _ => None,
10698        });
10699        match body.map(Vec::as_slice) {
10700            Some([inner]) => match &inner.kind {
10701                StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10702                    echoed, "n: {{ STD::LEN($x) }}",
10703                    "nested body qualifies: {echoed}"
10704                ),
10705                other => panic!("expected nested ECHO, got {other:?}"),
10706            },
10707            _ => panic!("expected one FUNC with one body step, got {steps:?}"),
10708        };
10709        // Neighboring placeholders keep their exact bytes: only the
10710        // head span changes, so payloads never lose formatting.
10711        let text = "IMPORT [STD]\nECHO \"Call {{ LEN($x) }} and value {{ $y }}\"\n";
10712        let out = echo_text(&parse(text, table()).expect("mixed template parses"));
10713        assert_eq!(
10714            out, "Call {{ STD::LEN($x) }} and value {{ $y }}",
10715            "only the head span changes: {out}"
10716        );
10717        // Unimported bare names fail exactly like statement position:
10718        // qualify it or add the import.
10719        let err = parse("ECHO \"n: {{ LEN($x) }}\"\n", table()).expect_err("must fail");
10720        assert!(
10721            err.to_string().contains("unknown function `LEN`")
10722                && err.to_string().contains("or add `IMPORT"),
10723            "names the fix: {err}"
10724        );
10725        // Two exporters fail closed instead of picking one.
10726        let err = parse(
10727            "IMPORT [STD]\nIMPORT [OTHER]\nECHO \"n: {{ LEN($x) }}\"\n",
10728            table(),
10729        )
10730        .expect_err("must fail");
10731        assert!(
10732            err.to_string().contains("ambiguous function `LEN`"),
10733            "ambiguity fails closed: {err}"
10734        );
10735        // Both lexing pathways agree on rewritten templates.
10736        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }} and {{ $y }}\"\n";
10737        let table = table();
10738        let old = crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
10739            .expect("string path parses");
10740        let reserved = HashSet::new();
10741        let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
10742        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
10743        let new = parse_tokens_with_ctx(&toks, &ctx).expect("token path parses");
10744        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
10745    }
10746
10747    #[test]
10748    fn placeholder_bare_calls_qualify_in_expr_positions() {
10749        // Regression: `walk_raw_strings_mut` skips `Assign`/`Set`/
10750        // `Call`/`Return`/`If`/`For`/`While`, so `LET`/`RETURN`/call
10751        // args/list/map literals never qualified and failed at
10752        // runtime as undefined variables. Both carriers now qualify.
10753        use crate::ast::{ModuleFuncs, ModuleTable};
10754        use std::collections::{HashMap, HashSet};
10755        let table = || ModuleTable {
10756            modules: HashMap::from([(
10757                crate::constants::STD_MODULE_NAME.to_string(),
10758                Some(ModuleFuncs {
10759                    func_names: HashSet::from(["LEN".to_string()]),
10760                }),
10761            )]),
10762        };
10763        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10764            test_lower_mock::lower(name, args)
10765        }
10766        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10767            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10768        }
10769        // LET string literal qualifies.
10770        let steps = parse(
10771            "IMPORT [STD]\nLET $s: STRING = \"n: {{ LEN($x) }}\"\n",
10772            table(),
10773        )
10774        .expect("LET template parses");
10775        match &steps[0].kind {
10776            StepKind::Bind {
10777                rhs: BindRhs::Expr(expr),
10778                ..
10779            } => match expr {
10780                Expr::Literal(value) => assert_eq!(
10781                    value.as_str().unwrap_or_default(),
10782                    "n: {{ STD::LEN($x) }}",
10783                    "LET qualifies"
10784                ),
10785                other => panic!("expected literal, got {other:?}"),
10786            },
10787            other => panic!("expected Bind, got {other:?}"),
10788        }
10789        // RETURN string literal qualifies.
10790        let steps = parse(
10791            "IMPORT [STD]\nFUNC F(): STRING {\nRETURN \"n: {{ LEN($x) }}\"\n}\n",
10792            table(),
10793        )
10794        .expect("RETURN template parses");
10795        let body = steps.iter().find_map(|s| match &s.kind {
10796            StepKind::FuncDef { body, .. } => Some(body),
10797            _ => None,
10798        });
10799        match body.map(Vec::as_slice) {
10800            Some([inner]) => match &inner.kind {
10801                StepKind::Return { expr, .. } => match &**expr {
10802                    Expr::Literal(value) => assert_eq!(
10803                        value.as_str().unwrap_or_default(),
10804                        "n: {{ STD::LEN($x) }}",
10805                        "RETURN qualifies"
10806                    ),
10807                    other => panic!("expected literal, got {other:?}"),
10808                },
10809                other => panic!("expected RETURN, got {other:?}"),
10810            },
10811            _ => panic!("expected one FUNC, got {steps:?}"),
10812        }
10813        // Call args, list and map literals qualify.
10814        let steps = parse(
10815            "IMPORT [STD]\nLET $y: INT = LEN(\"b: {{ LEN($x) }}\")\n",
10816            table(),
10817        )
10818        .expect("call-arg template parses");
10819        let rendered = format!("{:?}", steps[0].kind);
10820        assert!(
10821            rendered.contains("STD::LEN"),
10822            "call arg qualifies: {rendered}"
10823        );
10824        let steps = parse(
10825            "IMPORT [STD]\nLET $l: LIST<STRING> = [\"{{ LEN($x) }}\"]\n",
10826            table(),
10827        )
10828        .expect("list template parses");
10829        let rendered = format!("{:?}", steps[0].kind);
10830        assert!(rendered.contains("STD::LEN"), "list qualifies: {rendered}");
10831        // Compound placeholders are not single calls: they pass
10832        // through untouched (no partial rewrite) for the runtime to
10833        // fail closed on the whole key.
10834        let text = "IMPORT [STD]\nECHO \"v: {{ LEN($a) + LEN($b) }}\"\n";
10835        let steps = parse(text, table()).expect("compound parses");
10836        match &steps[0].kind {
10837            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10838                echoed, "v: {{ LEN($a) + LEN($b) }}",
10839                "compound untouched: {echoed}"
10840            ),
10841            other => panic!("expected ECHO string, got {other:?}"),
10842        }
10843        // Quoted parens inside args do not end the call early.
10844        let text = "IMPORT [STD]\nECHO 'v: {{ LEN(\"a(b\") }}'\n";
10845        let steps = parse(text, table()).expect("quoted paren parses");
10846        match &steps[0].kind {
10847            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10848                echoed, "v: {{ STD::LEN(\"a(b\") }}",
10849                "quoted paren qualifies: {echoed}"
10850            ),
10851            other => panic!("expected ECHO string, got {other:?}"),
10852        }
10853        // Single-quoted args balance the same way.
10854        let text = "IMPORT [STD]\nECHO \"v: {{ LEN('a(b') }}\"\n";
10855        let steps = parse(text, table()).expect("single-quoted paren parses");
10856        match &steps[0].kind {
10857            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10858                echoed, "v: {{ STD::LEN('a(b') }}",
10859                "single-quoted paren qualifies: {echoed}"
10860            ),
10861            other => panic!("expected ECHO string, got {other:?}"),
10862        }
10863        // `WithIo` boxes its inner command directly (no recursive
10864        // statement pass), so the qualifier must descend into it.
10865        // `LET $p: PIPE` plus bindings keep the shape realistic.
10866        let text = "IMPORT [STD]\nLET $p: PIPE\nWITH_IO [stdout=$p] ECHO 'v: {{ LEN($x) }}'\n";
10867        let steps = parse(text, table()).expect("with-io template parses");
10868        match &steps[1].kind {
10869            StepKind::WithIo { cmd, .. } => {
10870                let rendered = format!("{cmd:?}");
10871                assert!(
10872                    rendered.contains("STD::LEN"),
10873                    "with-io inner qualifies: {rendered}"
10874                );
10875            }
10876            other => panic!("expected WithIo, got {other:?}"),
10877        }
10878        // Single-command wrappers build synthetic body steps without a
10879        // recursive pass: `TIMEOUT 5s <cmd>` and `ASYNC <cmd>` share
10880        // the outer frame, so the qualifier must descend into bodies.
10881        let text = "IMPORT [STD]\nTIMEOUT 5s ECHO 't: {{ LEN($x) }}'\n";
10882        let steps = parse(text, table()).expect("timeout template parses");
10883        let rendered = format!("{:?}", steps[0].kind);
10884        assert!(
10885            rendered.contains("STD::LEN"),
10886            "timeout single qualifies: {rendered}"
10887        );
10888        let text = "IMPORT [STD]\nLET $h: HANDLE<ANY> = ASYNC ECHO 'a: {{ LEN($x) }}'\n";
10889        let steps = parse(text, table()).expect("async template parses");
10890        let rendered = format!("{:?}", steps[0].kind);
10891        assert!(
10892            rendered.contains("STD::LEN"),
10893            "async single qualifies: {rendered}"
10894        );
10895        // Brace bodies keep their own frames: the outer qualifier must
10896        // never re-walk them. A valid nested body qualifies via its own
10897        // recursive pass, and an unknown callee inside one fails with
10898        // the inner position, never re-resolved against the outer frame.
10899        let text = "IMPORT [STD]\nIF true {\nECHO 'v: {{ LEN($x) }}'\n}\n";
10900        let steps = parse(text, table()).expect("nested body qualifies");
10901        let rendered = format!("{:?}", steps[0].kind);
10902        assert!(
10903            rendered.contains("STD::LEN"),
10904            "nested IF body qualifies via its own frame: {rendered}"
10905        );
10906        let err = parse(
10907            "IMPORT [STD]\nIF true {\nECHO 'v: {{ NOPE($x) }}'\n}\n",
10908            table(),
10909        )
10910        .expect_err("nested unknown must fail");
10911        assert!(
10912            err.to_string().contains("unknown function `NOPE`"),
10913            "nested unknown names culprit: {err}"
10914        );
10915    }
10916
10917    #[test]
10918    fn block_conditions_name_unknown_callees() {
10919        // Regression: an unknown callee in a block header condition
10920        // used to miss to the generic `IF needs a condition and a
10921        // block` hint. Classified resolution failures now propagate
10922        // and name the culprit on all four speculative headers.
10923        use crate::ast::{ModuleFuncs, ModuleTable};
10924        use std::collections::{HashMap, HashSet};
10925        let table = || ModuleTable {
10926            modules: HashMap::from([(
10927                crate::constants::STD_MODULE_NAME.to_string(),
10928                Some(ModuleFuncs {
10929                    func_names: HashSet::from(["LEN".to_string()]),
10930                }),
10931            )]),
10932        };
10933        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10934            test_lower_mock::lower(name, args)
10935        }
10936        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10937            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10938        }
10939        for text in [
10940            "IMPORT [STD]\nIF NOPE($x) == 0 {\nECHO hi\n}\n",
10941            "IMPORT [STD]\nIF LEN($x) == 0 {\nECHO hi\n} ELSE IF NOPE($x) == 1 {\nECHO yo\n}\n",
10942            "IMPORT [STD]\nWHILE NOPE($x) > 0 {\nECHO hi\n}\n",
10943            "IMPORT [STD]\nFOR $i: STRING IN NOPE($x) {\nECHO $i\n}\n",
10944        ] {
10945            let err = parse(text, table()).expect_err("unknown callee must fail");
10946            assert!(
10947                err.to_string().contains("unknown function `NOPE`"),
10948                "names the culprit: {err}"
10949            );
10950        }
10951        // Unclassified shape misses still miss (the exact generic
10952        // hint comes from the real dispatcher, which the mock lacks).
10953        parse("IF {\nECHO hi\n}\n", table()).expect_err("empty condition must still fail");
10954    }
10955
10956    #[test]
10957    fn token_and_string_paths_agree_on_let_set_return() {
10958        for text in [
10959            "LET $x: INT = 1",
10960            "LET $s: STRING = \"hi\"",
10961            "LET $b: BOOL = true",
10962            "LET $f: FLOAT = 1.5",
10963            "LET $p: PIPE",
10964            "LET $l: LIST<STRING> = [\"a\", \"b\"]",
10965            "LET $e: LIST<STRING> = []",
10966            "LET $m: MAP = {k: 1}",
10967            "LET $m2: MAP = {\"a b\": 2, k: [1, 2]}",
10968            "LET $n: INT = $a + $b",
10969            "LET $c: BOOL = ($a == 3) && ($b == 4)",
10970            "LET $g: BOOL = !$ok",
10971            "LET $nn: BOOL = true && false",
10972            "LET $e2: STRING = env:HOME",
10973            "LET $k: STRING = $a.b.c",
10974            "LET $u: INT = -5",
10975            "LET $v: INT = 9223372036854775807",
10976            "LET $min: INT = -9223372036854775808",
10977            "LET $w: INT = 1_000",
10978            "LET $z: STRING = a/b",
10979            "LET $d: STRING = -f",
10980            "LET $t: STRING = 30s",
10981            "LET $q: STRING = \"\"\"hi\"\"\"",
10982            "LET $f2: FLOAT = 2 * -3",
10983            "LET $o: BOOL = 2 + 3 > 4",
10984            "LET $l2: LIST< MAP > = []",
10985            "LET $a1: INT = 1 + 2",
10986            "LET $s1: INT = 10 - 4 - 3",
10987            "LET $m1: INT = 2 * 3 + 4",
10988            "LET $x1: BOOL = 1 < 2 == true",
10989            "LET $or: BOOL = $a || $b",
10990            "LET $dbl: BOOL = !!$x",
10991            "LET $ver: STRING = 1.0.0",
10992            "LET $dash: STRING = a-b",
10993            "LET $div: INT = 4 / 2",
10994            "LET $bad: INT = 1__0 + 0",
10995            "LET $strdiv: STRING = 4/2",
10996            "LET $sp: INT = $a - $b",
10997            "$x = 1",
10998            "$x = $a + 1",
10999            "RETURN 1",
11000            KEYWORD_RETURN,
11001            "RETURN $x",
11002            "[env:X] LET $x: INT = 1",
11003            "[os:linux] $x = 2",
11004        ] {
11005            assert_parity(text);
11006        }
11007    }
11008
11009    #[test]
11010    fn malformed_shapes_fail_on_both_paths() {
11011        // Malformed shapes fail on both lexers (messages may differ;
11012        // success/failure must agree). Unbalanced groups fail even
11013        // earlier, at lex time: both layers reject, which is what the
11014        // oracle pins.
11015        for text in [
11016            "[a] ECHO hi",
11017            "[os:atari] ECHO hi",
11018            "[foo:bar] ECHO hi",
11019            "[any(os:linux)] ECHO hi",
11020            "[all()] ECHO hi",
11021            "[env:] ECHO hi",
11022            "[eq(env:K)] ECHO hi",
11023            "[not] ECHO hi",
11024            "ECHO [a;b]",
11025            "ECHO (a;b)",
11026            "ECHO a;b",
11027            "LET $x = 1",
11028            "LET $s: STRING",
11029            "LET $x: INT = 1 2",
11030            "LET $x: INT = (1",
11031            "LET $x: INT = 9223372036854775808",
11032            "$x =",
11033            "RETURN (",
11034            "[env:X]",
11035            "LET $x: INT = $a == $b == $c",
11036            "LET $x: BOOL = $a < $b < $c",
11037            "LET $bs: STRING = a\\nb",
11038            "FOO(\"a\")",
11039            "FOO (\"a\")",
11040            "ECHO FOO(\"a\")",
11041            "ECHO(\"hi\")",
11042            "RUN [a] extra",
11043            "RUN[\"a\"]",
11044            "TIMEOUT 10s RUN[\"a\"]",
11045            "LET $r: STRING = RUN[\"a\"]",
11046            "LET $e: STRING = ECHO",
11047            "ENV A=1 B=2",
11048            "EXPAND \"a b\" c",
11049            "ECHO {a}",
11050            "ECHO K=${x}",
11051            "[!env:A==1] RUN echo no",
11052            "run echo hi",
11053            "LET $x: STRING = AWAIT",
11054            "LET $o: STRING = CANCEL $t",
11055            "LET $x: STRING = ASYNC",
11056            "LET $x: STRING = WITH_IO",
11057            "LET $x: STRING = TIMEOUT",
11058            "LET $x: STRING = ISOLATED",
11059            "LET $x: STRING = ISOLATED ECHO hi",
11060            "COPY A=1",
11061            "WITH_IO [rows=40] RUN echo hi",
11062            "WITH_IO [tty] ECHO hi",
11063            "WITH_IO [tty, stderr=$p] RUN echo hi",
11064            "WITH_IO [tty=$p] RUN echo hi",
11065            "WITH_IO [cols=0] RUN echo hi",
11066            "WITH_IO [cols=65536] RUN echo hi",
11067            "WITH_IO [] ECHO hi",
11068            "WITH_IO [stdin=$p,] ECHO hi",
11069            "WITH_IO stdin=$p ECHO hi",
11070            "WITH_IO [STDIN=$p] ECHO hi",
11071            "WITH_IO [rows] RUN echo hi",
11072            KEYWORD_WITH_IO,
11073            "WITH_IO [stdout=$p]",
11074            "WITH_IO [stdin=$p]\n[os:linux] { ECHO hi }",
11075            "WITH_IO [stdin=$p] { }",
11076            "WITH_IO[stdin=$p] ECHO hi",
11077            "WITH_IO [stdin=$p]ECHO hi",
11078            "WITH_IO [stdin=$p] {{ $x }}",
11079            "ASYNC WITH_IO [stdout=$p] ECHO hi",
11080            "WITH_IO [stdin=$p] AWAIT $t",
11081            "ASYNC AWAIT $t",
11082            "WITH_IO [stdin=$p] RETURN \"hi\"",
11083            "ASYNC RETURN \"hi\"",
11084            "TIMEOUT 10s RETURN \"hi\"",
11085            "TIMEOUT banana ECHO hi",
11086            "TIMEOUT 10ss ECHO hi",
11087            "TIMEOUT 10 s ECHO hi",
11088            "TIMEOUT -5s ECHO hi",
11089            "TIMEOUT 0s ECHO hi",
11090            KEYWORD_TIMEOUT,
11091            "TIMEOUT 10s",
11092            "TIMEOUT { ECHO hi }",
11093            "TIMEOUT \"10s\"",
11094            "TIMEOUT 10s{ECHO hi}",
11095            "TIMEOUT 10sECHO hi",
11096            "TIMEOUT 10s {{ $d }}",
11097            "TIMEOUT 10s { $d }",
11098            "TIMEOUT { $d } ECHO hi",
11099            KEYWORD_ASYNC,
11100            KEYWORD_ISOLATED,
11101            "ISOLATED{ECHO hi}",
11102            KEYWORD_AWAIT,
11103            KEYWORD_CANCEL,
11104            "AWAIT t",
11105            "AWAIT $",
11106            "AWAIT $t extra",
11107            "CANCEL $t extra",
11108            "TIMEOUT 5s INHERIT_ENV [M]",
11109            "TIMEOUT 5s { INHERIT_ENV [M] }",
11110            "ASYNC { INHERIT_ENV [M] }",
11111            "LET $x: STRING = INHERIT_ENV [M]",
11112            "TIMEOUT 10s WITH_IO [stdin=$p] { ECHO hi }",
11113            "ISOLATED WITH_IO [stdin=$p] { ECHO hi }",
11114            "TIMEOUT 10s AWAIT $ t",
11115            "LET $o: STRING = AWAIT $ t",
11116            "ISOLATED AWAIT $ t",
11117            "WITH_IO [stdin=$p] CANCEL $ t",
11118            "LET $ x: INT = 1",
11119            "LET $x: STRING = WITH_IO [stdin=$p] { ECHO hi }",
11120            "LET $x: STRING = WITH_IO [stdin=$p] ASYNC",
11121            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO a\nECHO b }",
11122            "LET $x: STRING = WITH_IO [stdout=$p] ECHO hi",
11123            "LET $x: STRING = TIMEOUT 10s AWAIT $t",
11124            "LET $x: STRING = CANCEL $t",
11125            "LET $x: STRING = ASYNC",
11126            "LET $x: STRING = WITH_IO",
11127            "TIMEOUT 10s LET $x: INT = 1",
11128            "LET $x: STRING = FOO bar",
11129            "LET(\"a\")",
11130            "AWAIT($t)",
11131            "CANCEL($t)",
11132            "TIMEOUT(\"10s\") ECHO hi",
11133            "RETURN ECHO bye",
11134        ] {
11135            match crate::tok::lex_str(text) {
11136                Err(_) => {
11137                    assert!(
11138                        crate::parse_script(text, lower).is_err(),
11139                        "backend must also reject lex-broken input: {text:?}"
11140                    );
11141                    continue;
11142                }
11143                Ok(toks) => {
11144                    assert!(
11145                        parse_tokens(&toks, lower).is_err(),
11146                        "v2 must explicitly reject (not silently drift): {text:?}"
11147                    );
11148                }
11149            }
11150            assert!(
11151                crate::parse_script(text, lower).is_err(),
11152                "backend must also reject (oracle agreement): {text:?}"
11153            );
11154        }
11155        // No deferred shapes remain: every statement-level block and
11156        // inline-block expression parses natively.
11157    }
11158
11159    #[test]
11160    fn deferred_unknown_callee_beats_validation_arg_error() {
11161        // Directive 5: `WORKSPACE NOPE()` stashes `unknown function
11162        // NOPE` while the fallback raw string fails `WORKSPACE`
11163        // validation. On a well-formed header the stashed callee error
11164        // names the culprit instead of the misleading arg-shape error.
11165        let err =
11166            crate::parse_script("WORKSPACE NOPE()", lower).expect_err("unknown callee must fail");
11167        assert!(
11168            err.to_string().contains("unknown function `NOPE`"),
11169            "deferred must beat validation, got: {err}"
11170        );
11171    }
11172
11173    #[test]
11174    fn paren_line_break_reports_token_position() {
11175        // Directive 5: multiline paren breaks carry the offending
11176        // token's line/col, not a stamped 0/0. The break sits on line 2
11177        // while the statement opens on line 1.
11178        let err = crate::parse_script("ECHO (a\nb)", lower).expect_err("break must fail");
11179        let rendered = err.to_string();
11180        assert!(
11181            rendered.contains("unexpected line break"),
11182            "break must report, got: {rendered}"
11183        );
11184    }
11185
11186    #[test]
11187    fn deferred_unknown_callee_beats_invalid_syntax_arg_error() {
11188        // Fallback raw strings can trigger `InvalidSyntax` lowering
11189        // (for example `COPY NOPE()`). The stashed unknown-callee error
11190        // still names the culprit on a recognized head.
11191        for text in ["COPY NOPE()", "WRITE NOPE()"] {
11192            let err = crate::parse_script(text, lower).expect_err("unknown callee must fail");
11193            assert!(
11194                err.to_string().contains("unknown function `NOPE`"),
11195                "deferred must beat InvalidSyntax for {text:?}, got: {err}"
11196            );
11197        }
11198    }
11199
11200    #[test]
11201    fn deferred_beats_lowering_invalid_syntax_on_plain_heads() {
11202        // Plain command heads own no header grammar, so a lowering
11203        // `InvalidSyntax` there is an argument-shape failure from the
11204        // raw-text fallback: the stashed unknown-callee names the
11205        // culprit on every such head (no per-command allowlist).
11206        let lower_invalid =
11207            |name: &str, _args: Vec<crate::Arg>| -> crate::ParseResult<crate::StepKind> {
11208                Err(crate::ParseError::invalid_syntax(
11209                    name,
11210                    format!("{name} header is malformed"),
11211                    None,
11212                    Vec::new(),
11213                    None,
11214                    &crate::error::SpanContext::line_only(0),
11215                ))
11216            };
11217        for text in [
11218            "ASSERT_EQ $a NOSUCHFUNC()",
11219            "SYMLINK $a NOSUCHFUNC()",
11220            "COPY $a NOSUCHFUNC()",
11221            "WRITE $a NOSUCHFUNC()",
11222        ] {
11223            let err = crate::parse_script(text, lower_invalid).expect_err("arg error must fail");
11224            assert!(
11225                err.to_string().contains("unknown function `NOSUCHFUNC`"),
11226                "deferred must beat lowering InvalidSyntax for {text:?}, got: {err}"
11227            );
11228        }
11229        // Header-owned heads keep their lowering `InvalidSyntax`: the
11230        // native parser missed to the generic path on shape miss, so
11231        // the lowering error names the malformed header while the
11232        // stashed name is its definiendum, never a call.
11233        let err = crate::parse_script("FUNC $a NOSUCHFUNC()", lower_invalid)
11234            .expect_err("header syntax must fail");
11235        assert!(
11236            err.to_string().contains("header is malformed"),
11237            "header InvalidSyntax must stand on FUNC, got: {err}"
11238        );
11239    }
11240
11241    #[test]
11242    fn trailing_tokens_after_func_block_never_hoist() {
11243        // A `FUNC` header with trailing tokens after the body block is
11244        // malformed (the real path rejects it), so pre-declaration
11245        // must not hoist the name: the forward call fails instead of
11246        // resolving.
11247        let err = crate::parse_script(
11248            "LET $x: STRING = FOO()\nFUNC FOO(): STRING { RETURN \"a\" } TRAILING\n",
11249            lower,
11250        )
11251        .expect_err("trailing tokens must fail");
11252        assert!(
11253            err.to_string().contains("unknown function `FOO`"),
11254            "unhoisted forward call must fail, got: {err}"
11255        );
11256    }
11257
11258    #[test]
11259    fn forward_reference_resolves_regardless_of_order() {
11260        // `CALLER` calls `CALLEE` defined later. Top-level
11261        // pre-declaration hoists names before lowering, so order
11262        // does not matter. Runtime still executes sequentially;
11263        // the call below runs after both definitions.
11264        let steps = crate::parse_script(
11265            "FUNC CALLER(): STRING { RETURN CALLEE() }\nFUNC CALLEE(): STRING { RETURN \"forward-ok\" }\n",
11266            lower,
11267        )
11268        .expect("forward ref must parse");
11269        assert!(
11270            matches!(&steps[0].kind, crate::StepKind::FuncDef { name, .. } if name == "CALLER"),
11271            "first def kept, got: {:?}",
11272            steps[0].kind
11273        );
11274    }
11275
11276    #[test]
11277    fn lone_qualified_value_rejects_trailing_text_and_bad_dots() {
11278        // `try_lone_value_expr` is the lone-shape gate for unquoted
11279        // command arguments: trailing text after a full
11280        // `$ALIAS::NAME[.key...]` path fails closed with the whole
11281        // path named, keys or not, and dangling dots fail naming the
11282        // valid prefix. Both sides route through the shared
11283        // `parse_joint_key_segments` helper, so no call site restates
11284        // the loop.
11285        use crate::ast::ModuleTable;
11286        use std::collections::{HashMap, HashSet};
11287        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
11288            test_lower_mock::lower(name, args)
11289        }
11290        let table = ModuleTable {
11291            modules: HashMap::new(),
11292        };
11293        let reserved = HashSet::new();
11294        let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
11295        for (text, message) in [
11296            ("$LIB::LIMITS::X", "unexpected text after $LIB::LIMITS"),
11297            (
11298                "$LIB::LIMITS.nested::X",
11299                "unexpected text after $LIB::LIMITS.nested",
11300            ),
11301            ("$LIB::LIMITS.", "invalid key segment after $LIB::LIMITS"),
11302            (
11303                "$LIB::LIMITS.nested.",
11304                "invalid key segment after $LIB::LIMITS.nested",
11305            ),
11306            ("$LIB::LIMITS..x", "invalid key segment after $LIB::LIMITS"),
11307        ] {
11308            let toks = crate::tok::lex_str(text).expect("must lex");
11309            match try_lone_value_expr(&toks, 0, &ctx) {
11310                Err(err) => assert!(
11311                    err.msg.contains(message),
11312                    "{text} must fail naming the path, got: {}",
11313                    err.msg
11314                ),
11315                Ok(shape) => panic!("{text} must fail, got: {shape:?}"),
11316            }
11317        }
11318        // Bare reads keep their fallthrough: trailing text that is not
11319        // a joint key path misses the lone shape and renders raw
11320        // downstream instead of failing here.
11321        let toks = crate::tok::lex_str("$m/foo").expect("must lex");
11322        assert!(
11323            matches!(try_lone_value_expr(&toks, 0, &ctx), Ok(None)),
11324            "bare trailing text must miss the lone shape"
11325        );
11326    }
11327
11328    #[test]
11329    fn forward_reference_to_guarded_func_resolves() {
11330        // Guarded definitions hoist like unguarded ones: `parse_func_at`
11331        // registers `[os:macos] FUNC FOO` unconditionally, so a forward
11332        // call before the definition must resolve identically to a
11333        // backward call after it.
11334        let steps = crate::parse_script(
11335            "LET $x: STRING = FOO()\n[os:macos] FUNC FOO(): STRING { RETURN \"guarded\" }\n",
11336            lower,
11337        )
11338        .expect("forward guarded ref must parse");
11339        assert!(
11340            matches!(&steps[1].kind, crate::StepKind::FuncDef { name, .. } if name == "FOO"),
11341            "guarded def kept, got: {:?}",
11342            steps[1].kind
11343        );
11344    }
11345}