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, KEYWORD_AS, KEYWORD_ASYNC, KEYWORD_AWAIT, KEYWORD_BREAK,
97    KEYWORD_CANCEL, KEYWORD_CASE, KEYWORD_CONST, KEYWORD_CONTINUE, KEYWORD_DEFAULT, KEYWORD_ECHO,
98    KEYWORD_ELSE, KEYWORD_ENV, KEYWORD_EXPAND, KEYWORD_EXPORT, KEYWORD_FAIL, KEYWORD_FOR,
99    KEYWORD_FROM, KEYWORD_FUNC, KEYWORD_IF, KEYWORD_IMPORT, KEYWORD_IN, KEYWORD_INHERIT_ENV,
100    KEYWORD_INSPECT, KEYWORD_ISOLATED, KEYWORD_LET, KEYWORD_REMOTE, KEYWORD_RETURN, KEYWORD_RUN,
101    KEYWORD_SWITCH, KEYWORD_TIMEOUT, KEYWORD_TYPE, KEYWORD_WHILE, KEYWORD_WITH_IO,
102    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 paths
1360        // never ride qualified names: copy to a local first.
1361        if let Some(name) = match_joint_qualified(cur.toks, cur.pos) {
1362            if cur.toks.get(cur.pos + 3).is_some() {
1363                if matches!(
1364                    cur.toks.get(cur.pos + 3).map(|t| &t.kind),
1365                    Some(TokKind::Punct('.'))
1366                ) && cur.toks.get(cur.pos + 3).is_some_and(|t| t.joint)
1367                {
1368                    return Err(TokenError {
1369                        diagnostic: None,
1370                        hint: None,
1371                        stmt,
1372                        msg: crate::template::qualified_keypath_error(),
1373                        line: 0,
1374                        col: 0,
1375                        kind: None,
1376                    });
1377                }
1378                return Err(TokenError {
1379                    diagnostic: None,
1380                    hint: None,
1381                    stmt,
1382                    msg: format!("unexpected text after {}", sigil_qualified(&base, &name)),
1383                    line: 0,
1384                    col: 0,
1385                    kind: None,
1386                });
1387            }
1388            return Ok(Some(Arg::Expr(Expr::ConstRef { alias: base, name })));
1389        }
1390        let mut keys = Vec::new();
1391        loop {
1392            let dot = matches!(
1393                cur.toks.get(cur.pos).map(|t| &t.kind),
1394                Some(TokKind::Punct('.'))
1395            ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
1396            let seg = cur.toks.get(cur.pos + 1);
1397            let seg_ok = dot
1398                && matches!(seg.map(|t| &t.kind), Some(TokKind::Word(w)) if is_key_segment(w))
1399                && seg.is_some_and(|t| t.joint);
1400            if !seg_ok {
1401                break;
1402            }
1403            if let Some(TokKind::Word(w)) = seg.map(|t| &t.kind) {
1404                keys.push(w.clone());
1405            }
1406            cur.pos += 2;
1407        }
1408        if cur.pos != region.len() {
1409            return Ok(None);
1410        }
1411        return Ok(Some(Arg::Expr(if keys.is_empty() {
1412            Expr::Var { name: base }
1413        } else {
1414            Expr::KeyPath { base, keys }
1415        })));
1416    }
1417    // `env:KEY` read, gapless and exact.
1418    if region.len() == 3
1419        && matches!(&region[0].kind, TokKind::Word(w) if w == "env")
1420        && matches!(&region[1].kind, TokKind::Punct(':'))
1421        && region[1].joint
1422        && let TokKind::Word(k) = &region[2].kind
1423        && is_env_key(k)
1424        && region[2].joint
1425    {
1426        return Ok(Some(Arg::Expr(Expr::Env(k.clone()))));
1427    }
1428    // Full-region call: resolve and keep typed (canonical rendering
1429    // happens per command: verbatim for ENV/EXPAND, `K=`-joined text
1430    // elsewhere, all from the same `Arg::Expr`). Single owner for the
1431    // call tail; positional args share it (see `build_arg_tokens`).
1432    if let Some(arg) = try_lone_call_expr(region, stmt, ctx)? {
1433        return Ok(Some(arg));
1434    }
1435    Ok(None)
1436}
1437
1438/// Full-region call shape (`NAME(...)`, `MOD::NAME(...)`) over one
1439/// argument run: parse args through the shared call owner and resolve
1440/// through the shared resolver, so assignment values, RUN-exec items,
1441/// and generic positional args can never disagree on what a call is.
1442/// `None` on shape miss (caller renders raw); errors propagate, so a
1443/// misspelled callee fails loud instead of going literal.
1444fn try_lone_call_expr(
1445    region: &[Tok],
1446    stmt: usize,
1447    ctx: &ParseCtx,
1448) -> Result<Option<Arg>, TokenError> {
1449    if let Some((name, paren)) = call_shape_at(region, 0, false)
1450        && paren + 1 == region.len()
1451        && let TokKind::Group { inner, .. } = &region[paren].kind
1452    {
1453        let inner = inner.clone();
1454        let args = parse_call_args(&inner, stmt, ctx)?;
1455        if name == KEYWORD_INSPECT {
1456            let [arg] = args.as_slice() else {
1457                return Err(TokenError {
1458                    diagnostic: None,
1459                    hint: None,
1460                    stmt,
1461                    msg: format!(
1462                        "{KEYWORD_INSPECT} requires exactly one argument: {KEYWORD_INSPECT}($var)"
1463                    ),
1464                    line: 0,
1465                    col: 0,
1466                    kind: None,
1467                });
1468            };
1469            if let Expr::Var { name } = arg {
1470                return Ok(Some(Arg::Expr(Expr::Inspect { name: name.clone() })));
1471            }
1472            return Err(TokenError {
1473                diagnostic: None,
1474                hint: None,
1475                stmt,
1476                msg: format!("{KEYWORD_INSPECT} requires a $variable argument, found {arg:?}"),
1477                line: 0,
1478                col: 0,
1479                kind: None,
1480            });
1481        }
1482        let qualified = resolve_name(ctx, stmt, &name)?;
1483        return Ok(Some(Arg::Expr(Expr::Call {
1484            name: qualified,
1485            args,
1486        })));
1487    }
1488    Ok(None)
1489}
1490
1491/// Expression extension for `$`/`env:`-led argument starts: parse a
1492/// full expression (operators reach across gaps exactly like the
1493/// grammar's inner `gap`s). Ending at a gap/end yields a typed single
1494/// group; ending mid-run falls back to raw text of the run (`$x=K`);
1495/// parse failure is fatal (every fragment alternative failed).
1496/// Returns the arg and tokens consumed.
1497fn try_expr_arg(
1498    toks: &[Tok],
1499    pos: usize,
1500    stmt: usize,
1501    ctx: &ParseCtx,
1502) -> Result<Option<(Arg, usize)>, TokenError> {
1503    let extend = matches!(
1504        toks.get(pos).map(|t| &t.kind),
1505        Some(TokKind::Punct(VAR_SIGIL_CHAR))
1506    ) || matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == "env");
1507    if !extend {
1508        return Ok(None);
1509    }
1510    // A bare `env` head only extends into a real `env:KEY` read (joint
1511    // `:`); dotted bare words (`env.txt`) stay raw strings like the
1512    // grammar's `unquoted_arg`, which precedes `expr`.
1513    if matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == "env")
1514        && !matches!(
1515            (
1516                toks.get(pos + 1).map(|t| &t.kind),
1517                toks.get(pos + 1).map(|t| t.joint)
1518            ),
1519            (Some(TokKind::Punct(':')), Some(true))
1520        )
1521    {
1522        return Ok(None);
1523    }
1524    let mut cur = Cursor::expr(&toks[pos..], stmt);
1525    let expr = parse_expr_or(&mut cur, ctx)?;
1526    let end = pos + cur.pos;
1527    // Mid-run stop (joint follower): the whole run renders raw
1528    // (`$x=K`, `$a$b`); the run always ends the fallback span here
1529    // because extension starts groups.
1530    if toks.get(end).is_some_and(|t| t.joint) {
1531        let mut run_end = end;
1532        while toks.get(run_end).is_some_and(|t| t.joint) {
1533            run_end += 1;
1534        }
1535        let text = render_raw_text(&toks[pos..run_end], stmt)?;
1536        return Ok(Some((Arg::String(text, false), run_end - pos)));
1537    }
1538    Ok(Some((Arg::Expr(expr), end - pos)))
1539}
1540
1541/// Render a brace group inside raw text (`{{..}}` templates and
1542/// mid-run `{..}` shapes): verbatim bytes, single-space-normalized
1543/// gaps. Run-start non-template braces never reach here (they parse
1544/// as maps/blocks in `build_arg_tokens`).
1545fn render_brace_run_text(inner: &[Tok], open_joint: bool, close_joint: bool) -> String {
1546    render_group('{', '}', inner, open_joint, close_joint)
1547}
1548
1549/// Inner bytes of a fully-quoted word (`"hi"`, `'a'`): the re-quoted
1550/// standalone strings spliced from groups strip exactly like
1551/// structural ones. Triple-quote pieces never qualify (block lowering
1552/// owns them); glued quotes (`['a`) never reach here as sole runs.
1553fn quoted_word_inner(w: &str) -> Option<String> {
1554    if w.len() >= 2 && !w.starts_with("\"\"\"") {
1555        let q = w.as_bytes()[0] as char;
1556        if (q == '"' || q == '\'') && w.ends_with(q) {
1557            return Some(w[1..w.len() - 1].to_string());
1558        }
1559    }
1560    None
1561}
1562
1563/// Build instruction tokens over generic args, mirroring
1564/// `assignment | argument` order at every argument start: assignments
1565/// merge across gaps to the next boundary, `$`/`env:`-led runs extend
1566/// as expressions, brace-led runs try templates then maps/blocks, and
1567/// everything else renders raw. Single quoted strings keep their flag.
1568fn build_arg_tokens(
1569    toks: &[Tok],
1570    stmt: usize,
1571    ctx: &ParseCtx,
1572) -> Result<(Vec<InsToken>, Option<TokenError>), TokenError> {
1573    // Splice bracket groups first: they read as ordinary
1574    // characters (whitespace splits inside them), with strings
1575    // re-quoted back to word text. Paren groups stay structural (see
1576    // `splice_arg_groups`); brace groups stay structural
1577    // (templates render whole; blocks parse as expressions).
1578    let flat = splice_arg_groups(toks, stmt)?;
1579    let mut deferred: Option<TokenError> = None;
1580    let mut out = Vec::new();
1581    let mut pos = 0;
1582    while pos < flat.len() {
1583        // 1. Assignment: key run plus `=` at any gap.
1584        if let Some((key, key_end)) = match_assign_key(&flat, pos)
1585            && let Some(tok) = flat.get(key_end)
1586            && matches!(&tok.kind, TokKind::Punct('='))
1587        {
1588            // Value runs to the next boundary, but raw text also
1589            // stops at `//` / `/*` (raw-text rule):
1590            // a line comment swallows the rest silently, a block
1591            // comment must be followed by nothing or a boundary
1592            // (anything else strands text and fails the line, like
1593            // the grammar). Lone typed values (`$x`, calls) apply
1594            // only at a true end/boundary, never past a comment
1595            // (the grammar's `!assign_expr_cont` guard).
1596            let mut vend = key_end + 1;
1597            let mut lone_ok = true;
1598            let mut failed: Option<String> = None;
1599            'scan: while vend < flat.len() {
1600                if !flat[vend].joint && at_assign_boundary(&flat, vend) {
1601                    break;
1602                }
1603                // Lexer comment markers end the raw span like `//`
1604                // (they run to end of line by construction).
1605                if matches!(&flat[vend].kind, TokKind::Comment(_)) {
1606                    lone_ok = false;
1607                    vend = flat.len();
1608                    break;
1609                }
1610                if matches!(&flat[vend].kind, TokKind::Punct('/')) && is_comment_open(&flat, vend) {
1611                    // Comments end the raw span: line comments eat
1612                    // the rest silently, block comments must be
1613                    // followed by nothing, a boundary, or more
1614                    // comments (stranded text fails the line, like
1615                    // the grammar).
1616                    lone_ok = false;
1617                    loop {
1618                        if vend >= flat.len()
1619                            || (!flat[vend].joint && at_assign_boundary(&flat, vend))
1620                        {
1621                            break 'scan;
1622                        }
1623                        if !matches!(&flat[vend].kind, TokKind::Punct('/'))
1624                            || !is_comment_open(&flat, vend)
1625                        {
1626                            failed = Some("unexpected text after assignment value".to_string());
1627                            break 'scan;
1628                        }
1629                        if matches!(
1630                            flat.get(vend + 1).map(|t| &t.kind),
1631                            Some(TokKind::Punct('/'))
1632                        ) {
1633                            vend = flat.len();
1634                            break 'scan;
1635                        }
1636                        match skip_inline_comment(&flat, vend) {
1637                            None => {
1638                                failed = Some("unclosed block comment".to_string());
1639                                break 'scan;
1640                            }
1641                            Some(past) => vend = past,
1642                        }
1643                    }
1644                }
1645                vend += 1;
1646            }
1647            if let Some(msg) = failed {
1648                return Err(TokenError {
1649                    diagnostic: None,
1650                    hint: None,
1651                    stmt,
1652                    msg,
1653                    line: 0,
1654                    col: 0,
1655                    kind: None,
1656                });
1657            }
1658            let value =
1659                build_value_arg(&flat[key_end + 1..vend], stmt, ctx, lone_ok, &mut deferred)?;
1660            out.push(InsToken::Assign(key, value));
1661            pos = vend;
1662            continue;
1663        }
1664        // 2. Brace-led run: template text, else map/block expression.
1665        if matches!(
1666            flat.get(pos).map(|t| &t.kind),
1667            Some(TokKind::Group {
1668                delim: GroupDelim::Brace,
1669                ..
1670            })
1671        ) {
1672            let mut run_end = pos + 1;
1673            while flat.get(run_end).is_some_and(|t| t.joint) {
1674                run_end += 1;
1675            }
1676            let run = &flat[pos..run_end];
1677            let is_template = is_template_brace(&run[0]);
1678            if is_template {
1679                out.push(InsToken::Pos(Arg::String(
1680                    render_raw_text(run, stmt)?,
1681                    false,
1682                )));
1683            } else {
1684                let inner = match &run[0].kind {
1685                    TokKind::Group { inner, .. } => inner.clone(),
1686                    _ => unreachable!(),
1687                };
1688                // Map success alone stays typed; map success with a
1689                // joint tail renders raw (`{k:1}x`, like the grammar's
1690                // mixed fragments); map failure defers/errors exactly
1691                // like the expression path.
1692                match parse_map_or_block(&inner, stmt, ctx) {
1693                    Ok(expr) if run.len() == 1 => {
1694                        out.push(InsToken::Pos(Arg::Expr(expr)));
1695                    }
1696                    Ok(_) => out.push(InsToken::Pos(Arg::String(
1697                        render_raw_text(run, stmt)?,
1698                        false,
1699                    ))),
1700                    Err(e) => return Err(e),
1701                }
1702            }
1703            pos = run_end;
1704            continue;
1705        }
1706        // 3. `$`/`env:`-led expression extension.
1707        if let Some((arg, used)) = try_expr_arg(&flat, pos, stmt, ctx)? {
1708            // A lone expression group stays typed; the fallback
1709            // already rendered text above.
1710            out.push(InsToken::Pos(arg));
1711            pos += used;
1712            continue;
1713        }
1714        // 4. Raw text run to the next gap.
1715        let mut run_end = pos + 1;
1716        while flat.get(run_end).is_some_and(|t| t.joint) {
1717            run_end += 1;
1718        }
1719        let run = &flat[pos..run_end];
1720        // Slash-pair-led runs (`/*c*/`; `//` arrives as `Comment`
1721        // toks) parse as expression fragments (typed when single,
1722        // glued verbatim otherwise).
1723        if is_slash_run(run) {
1724            out.push(InsToken::Pos(parse_slash_run(run, stmt, ctx)?));
1725            pos = run_end;
1726            continue;
1727        }
1728        // Trailing `Comment` (`//` to end of line) glues as a
1729        // literal fragment (typed when alone, verbatim otherwise),
1730        // exactly like the grammar's expression fragments.
1731        if let Some(TokKind::Comment(text)) = run.last().map(|t| &t.kind) {
1732            if run.len() == 1 {
1733                out.push(InsToken::Pos(Arg::Expr(Expr::Literal(Value::string(
1734                    text.clone(),
1735                )))));
1736            } else {
1737                let mut bytes = render_raw_text(&run[..run.len() - 1], stmt)?;
1738                bytes.push_str(text);
1739                out.push(InsToken::Pos(Arg::String(bytes, false)));
1740            }
1741            pos = run_end;
1742            continue;
1743        }
1744        if run.len() == 1 {
1745            match &run[0].kind {
1746                TokKind::Str { text: s, .. } => {
1747                    out.push(InsToken::Pos(Arg::String(s.clone(), true)));
1748                    pos = run_end;
1749                    continue;
1750                }
1751                TokKind::BlockStr(full) => {
1752                    out.push(InsToken::Pos(Arg::String(
1753                        crate::command::lower_block_string(full),
1754                        true,
1755                    )));
1756                    pos = run_end;
1757                    continue;
1758                }
1759                // Re-quoted standalone strings (spliced from groups)
1760                // strip exactly like structural ones (`["hi"]` gives
1761                // `hi`); glued quotes stay literal (`['a` keeps its
1762                // mark). Triple-quote pieces never qualify.
1763                TokKind::Word(w) if quoted_word_inner(w).is_some() => {
1764                    out.push(InsToken::Pos(Arg::String(
1765                        quoted_word_inner(w).unwrap(),
1766                        true,
1767                    )));
1768                    pos = run_end;
1769                    continue;
1770                }
1771                _ => {}
1772            }
1773        }
1774        // Bare full-region calls stay typed like assignment values and
1775        // RUN-exec items (same owner, `try_lone_call_expr`), so every
1776        // argument position evaluates them instead of one silently
1777        // appending the source text. Failures stash: the command's own
1778        // lowering error (if any) takes precedence, and the stashed
1779        // call error surfaces only when lowering succeeds.
1780        match try_lone_call_expr(run, stmt, ctx) {
1781            Ok(Some(arg)) => {
1782                out.push(InsToken::Pos(arg));
1783                pos = run_end;
1784                continue;
1785            }
1786            Ok(None) => {}
1787            Err(err) => {
1788                deferred.get_or_insert(err);
1789            }
1790        }
1791        out.push(InsToken::Pos(Arg::String(
1792            render_raw_text(run, stmt)?,
1793            false,
1794        )));
1795        pos = run_end;
1796    }
1797    Ok((out, deferred))
1798}
1799
1800/// A raw run starting with `//` or `/*` (a slash-pair: `/` plus a
1801/// joint `/` or `*`) parses as expression fragments: both route to
1802/// `expr` there (so `//c` types as a literal and `/*c*/` as math). A single
1803/// fully-consuming expression stays typed; anything longer glues to
1804/// verbatim text exactly like the grammar's mixed fragments (byte
1805/// for byte, since joint runs admit no span gaps). An unparseable
1806/// unterminated block open (`/*` with no `*/` in the run) reads
1807/// literally like the old backend (`ECHO /*`, `[a /* c]`); a
1808/// terminated span keeps the loud failure.
1809fn parse_slash_run(run: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Arg, TokenError> {
1810    let mut cur = Cursor::expr(run, stmt);
1811    match parse_expr_checked(&mut cur, ctx) {
1812        Ok(expr) if cur.done() => Ok(Arg::Expr(expr)),
1813        Ok(_) => Ok(Arg::String(render_raw_text(run, stmt)?, false)),
1814        Err(_) if !run_has_block_close(run) => Ok(Arg::String(render_raw_text(run, stmt)?, false)),
1815        Err(e) => Err(e),
1816    }
1817}
1818
1819/// True when the run holds a `*/` close pair (`*` plus a joint `/`),
1820/// mirroring [`skip_inline_comment`]'s terminator: only unterminated
1821/// block opens read literally.
1822fn run_has_block_close(run: &[Tok]) -> bool {
1823    run.windows(2).any(|w| {
1824        matches!(&w[0].kind, TokKind::Punct('*'))
1825            && matches!(&w[1].kind, TokKind::Punct('/'))
1826            && w[1].joint
1827    })
1828}
1829
1830/// True when a raw run opens with a slash-pair (`/` plus a joint
1831/// `/` or `*`), routing it to expression fragments (see
1832/// [`parse_slash_run`]). A lone `/` (`/a`, `/`) stays raw text.
1833fn is_slash_run(run: &[Tok]) -> bool {
1834    matches!(run.first().map(|t| &t.kind), Some(TokKind::Punct('/')))
1835        && matches!(
1836            run.get(1).map(|t| (&t.kind, t.joint)),
1837            Some((TokKind::Punct('/'), true)) | Some((TokKind::Punct('*'), true))
1838        )
1839}
1840
1841/// Lower generic args through the shared cores: `ENV`/`EXPAND` bypass
1842/// the injected dispatcher; everything else
1843/// canonicalizes assignments and calls it.
1844fn lower_generic_args(
1845    name: &str,
1846    tokens: Vec<InsToken>,
1847    stmt: usize,
1848    ctx: &ParseCtx,
1849) -> Result<StepKind, TokenError> {
1850    if name == KEYWORD_ENV {
1851        return lower_env_tokens(&lowering_ctx(stmt), tokens).map_err(|e| lower_err(stmt, e));
1852    }
1853    if name == KEYWORD_EXPAND {
1854        return lower_expand_tokens(&lowering_ctx(stmt), tokens).map_err(|e| lower_err(stmt, e));
1855    }
1856    let args = tokens
1857        .into_iter()
1858        .map(|token| match token {
1859            InsToken::Pos(arg) => arg,
1860            InsToken::Assign(key, value) => canonical_assignment_arg(&key, &value),
1861        })
1862        .collect();
1863    (ctx.lower)(name, args).map_err(|e| lower_err(stmt, e))
1864}
1865
1866/// Render a bracket/paren/brace group back to source text for raw-text
1867/// positions (in-body groups are args, template braces render whole).
1868/// Fragments join with a space on gaps and glue on `joint`, so both
1869/// lexers render the same source identically; quote styles round-trip
1870/// exactly. Known normalization (documented, not silent): multi-space
1871/// gaps collapse to one.
1872fn render_group(
1873    open: char,
1874    close: char,
1875    inner: &[Tok],
1876    open_joint: bool,
1877    close_joint: bool,
1878) -> String {
1879    let mut out = String::from(open);
1880    if !open_joint && !inner.is_empty() {
1881        out.push(' ');
1882    }
1883    let mut first = true;
1884    for tok in inner {
1885        match &tok.kind {
1886            TokKind::Newline => out.push('\n'),
1887            TokKind::Semicolon => out.push(';'),
1888            // Comments reproduce verbatim (templates keep comment
1889            // text like the atomic grammar span); like newlines they
1890            // carry their own separation, never a synthetic space.
1891            TokKind::Comment(text) => out.push_str(text),
1892            _ => {
1893                if !first && !tok.joint {
1894                    out.push(' ');
1895                }
1896                match &tok.kind {
1897                    TokKind::Word(w) => out.push_str(w),
1898                    TokKind::Punct(c) => out.push(*c),
1899                    TokKind::Str { text, quote } => {
1900                        out.push(*quote);
1901                        out.push_str(text);
1902                        out.push(*quote);
1903                    }
1904                    TokKind::BlockStr(full) => out.push_str(full),
1905                    TokKind::Group {
1906                        delim: GroupDelim::Bracket,
1907                        inner,
1908                        open_joint,
1909                        close_joint,
1910                        ..
1911                    } => out.push_str(&render_group('[', ']', inner, *open_joint, *close_joint)),
1912                    TokKind::Group {
1913                        delim: GroupDelim::Paren,
1914                        inner,
1915                        open_joint,
1916                        close_joint,
1917                        ..
1918                    } => out.push_str(&render_group('(', ')', inner, *open_joint, *close_joint)),
1919                    TokKind::Group {
1920                        delim: GroupDelim::Brace,
1921                        inner,
1922                        open_joint,
1923                        close_joint,
1924                        ..
1925                    } => out.push_str(&render_group('{', '}', inner, *open_joint, *close_joint)),
1926                    // Comments reproduce verbatim (nested groups keep
1927                    // comment text like the atomic grammar span).
1928                    TokKind::Comment(text) => out.push_str(text),
1929                    TokKind::Newline | TokKind::Semicolon => unreachable!(),
1930                }
1931            }
1932        }
1933        first = false;
1934    }
1935    if !close_joint && !inner.is_empty() {
1936        out.push(' ');
1937    }
1938    out.push(close);
1939    out
1940}
1941
1942/// Positional cursor over guard/group token slices. Newlines skip
1943/// freely between tokens (`ws` admits linebreaks in the grammar);
1944/// bare key/value runs never cross them (the grammar excludes
1945/// linebreaks there), so runs read raw.
1946///
1947/// Expression parsing reuses this cursor with `nl_skip = false`:
1948/// expressions are single-line (`gap`, never `gap_nl`, between
1949/// operands), so a newline terminates instead of vanishing. Newlines
1950/// inside group inners (call args, lists, maps) skip via explicit
1951/// `skip_newlines` calls at the grammar's `gap_nl` junctures.
1952struct Cursor<'t> {
1953    toks: &'t [Tok],
1954    pos: usize,
1955    stmt: usize,
1956    nl_skip: bool,
1957}
1958
1959impl<'t> Cursor<'t> {
1960    fn new(toks: &'t [Tok], stmt: usize) -> Self {
1961        Self {
1962            toks,
1963            pos: 0,
1964            stmt,
1965            nl_skip: true,
1966        }
1967    }
1968
1969    /// Expression-mode cursor: newlines stop, never skip.
1970    fn expr(toks: &'t [Tok], stmt: usize) -> Self {
1971        Self {
1972            toks,
1973            pos: 0,
1974            stmt,
1975            nl_skip: false,
1976        }
1977    }
1978
1979    fn err(&self, msg: impl Into<String>) -> TokenError {
1980        TokenError {
1981            diagnostic: None,
1982            hint: None,
1983            stmt: self.stmt,
1984            line: 0,
1985            col: 0,
1986            msg: msg.into(),
1987            kind: None,
1988        }
1989    }
1990
1991    fn skip_newlines(&mut self) {
1992        while matches!(
1993            self.toks.get(self.pos).map(|t| &t.kind),
1994            Some(TokKind::Newline)
1995        ) {
1996            self.pos += 1;
1997        }
1998    }
1999
2000    fn peek(&mut self) -> Option<&'t Tok> {
2001        if self.nl_skip {
2002            self.skip_newlines();
2003        }
2004        self.toks.get(self.pos)
2005    }
2006
2007    fn next(&mut self) -> Option<&'t Tok> {
2008        if self.nl_skip {
2009            self.skip_newlines();
2010        }
2011        let t = self.toks.get(self.pos)?;
2012        self.pos += 1;
2013        Some(t)
2014    }
2015
2016    fn done(&mut self) -> bool {
2017        if self.nl_skip {
2018            self.skip_newlines();
2019        }
2020        self.pos >= self.toks.len()
2021    }
2022
2023    fn eat_punct(&mut self, c: char) -> bool {
2024        if self.nl_skip {
2025            self.skip_newlines();
2026        }
2027        match self.peek() {
2028            Some(t) if matches!(&t.kind, TokKind::Punct(p) if *p == c) => {
2029                self.pos += 1;
2030                true
2031            }
2032            _ => false,
2033        }
2034    }
2035
2036    /// Skip one gap's worth of comments (`gap`: `//`-to-newline,
2037    /// balanced `/* */` even across newlines, `#`-to-newline —
2038    /// never a standalone newline, which ends single-line
2039    /// expressions. Greedy gap before operators and operands; whitespace itself is
2040    /// already invisible in the token stream.
2041    fn skip_gap(&mut self) {
2042        loop {
2043            match self.toks.get(self.pos).map(|t| &t.kind) {
2044                Some(TokKind::Comment(_)) => {
2045                    self.pos += 1;
2046                }
2047                Some(TokKind::Punct('/')) if is_comment_open(self.toks, self.pos) => {
2048                    match skip_inline_comment(self.toks, self.pos) {
2049                        Some(next) => self.pos = next,
2050                        // Unclosed block comments fail the gap (and
2051                        // the enclosing rule) like the grammar.
2052                        None => break,
2053                    }
2054                }
2055                Some(TokKind::Punct('#')) => {
2056                    while self.pos < self.toks.len()
2057                        && !matches!(&self.toks[self.pos].kind, TokKind::Newline)
2058                    {
2059                        self.pos += 1;
2060                    }
2061                }
2062                _ => break,
2063            }
2064        }
2065    }
2066
2067    /// Skip gap comments plus standalone newlines (`gap_nl`: call
2068    /// args, list items, maps, parenthesized expressions).
2069    fn skip_gap_nl(&mut self) {
2070        loop {
2071            match self.toks.get(self.pos).map(|t| &t.kind) {
2072                Some(TokKind::Newline) => {
2073                    self.pos += 1;
2074                }
2075                _ => {
2076                    let before = self.pos;
2077                    self.skip_gap();
2078                    if self.pos == before {
2079                        break;
2080                    }
2081                }
2082            }
2083        }
2084    }
2085
2086    /// Consume the parenthesized group following a call word (`not`,
2087    /// `any`, `all`, `eq`, `ne`), ignoring gap width exactly like the
2088    /// grammar's implicit whitespace.
2089    fn eat_paren_group(&mut self) -> Option<Vec<Tok>> {
2090        match self.peek() {
2091            Some(t) => match &t.kind {
2092                TokKind::Group {
2093                    delim: GroupDelim::Paren,
2094                    inner,
2095                    ..
2096                } => {
2097                    let inner = inner.clone();
2098                    self.pos += 1;
2099                    Some(inner)
2100                }
2101                _ => None,
2102            },
2103            None => None,
2104        }
2105    }
2106}
2107
2108/// Split a flat token slice on top-level commas (nesting lives inside
2109/// atomic groups, so a flat scan is exact).
2110fn split_top_commas(toks: &[Tok]) -> Vec<&[Tok]> {
2111    let mut parts = Vec::new();
2112    let mut start = 0;
2113    for (i, t) in toks.iter().enumerate() {
2114        if matches!(&t.kind, TokKind::Punct(',')) {
2115            parts.push(&toks[start..i]);
2116            start = i + 1;
2117        }
2118    }
2119    parts.push(&toks[start..]);
2120    parts
2121}
2122
2123/// Punctuation admissible inside bare guard key runs: everything but
2124/// the terminators the parser enforces separately. `;` arrives as its
2125/// own token kind; the key charset admits it, so runs accept it literally.
2126fn key_char(c: char) -> bool {
2127    !matches!(
2128        c,
2129        ':' | '=' | '!' | ',' | '|' | '(' | ')' | ']' | VAR_SIGIL_CHAR
2130    )
2131}
2132
2133/// Consume a joint run of words/punctuation as one bare key or value.
2134/// Gaps end the run; terminators and groups end or fail it per `extra`.
2135fn bare_run(cur: &mut Cursor, extra: fn(char) -> bool, what: &str) -> Result<String, TokenError> {
2136    let mut out = String::new();
2137    loop {
2138        let tok = match cur.toks.get(cur.pos) {
2139            Some(t) if matches!(&t.kind, TokKind::Newline) => break,
2140            Some(t) => t,
2141            None => break,
2142        };
2143        // First element may follow a gap; continuations must be gapless.
2144        if !out.is_empty() && !tok.joint {
2145            break;
2146        }
2147        match &tok.kind {
2148            TokKind::Word(w) => out.push_str(w),
2149            TokKind::Punct(c) if key_char(*c) && extra(*c) => out.push(*c),
2150            TokKind::Semicolon if extra(';') => out.push(';'),
2151            _ => break,
2152        }
2153        cur.pos += 1;
2154    }
2155    if out.is_empty() {
2156        return Err(cur.err(format!("missing {what}")));
2157    }
2158    Ok(out)
2159}
2160
2161/// The `guard_term` negative lookahead: a complete term followed by
2162/// `(`, `:`, `=`, or `!` is malformed, never a longer form.
2163fn check_term_end(cur: &mut Cursor) -> Result<(), TokenError> {
2164    cur.skip_newlines();
2165    match cur.toks.get(cur.pos) {
2166        Some(t) => match &t.kind {
2167            TokKind::Group {
2168                delim: GroupDelim::Paren,
2169                ..
2170            } => Err(cur.err("unexpected `(` after guard term")),
2171            TokKind::Punct(c) if matches!(c, ':' | '=' | '!') => {
2172                Err(cur.err(format!("unexpected `{c}` after guard term")))
2173            }
2174            _ => Ok(()),
2175        },
2176        None => Ok(()),
2177    }
2178}
2179
2180fn os_guard(value: &str) -> GuardExpr {
2181    GuardExpr::Predicate(Guard::Attr {
2182        ns: Ns::Os,
2183        key: None,
2184        val: Some(value.to_string()),
2185    })
2186}
2187
2188/// Namespace validation for guard predicates with closed domains
2189/// (`family`, `os`, `arch`); open namespaces pass through.
2190fn ns_guard(ns: &str, val: &str, cur: &Cursor) -> Result<GuardExpr, TokenError> {
2191    match ns {
2192        "family" => match val {
2193            "unix" => Ok(GuardExpr::or(vec![os_guard("macos"), os_guard("linux")])),
2194            "windows" => Ok(os_guard("windows")),
2195            _ => Err(cur.err(format!(
2196                "unknown family '{val}'; known values: unix, windows"
2197            ))),
2198        },
2199        "os" => match val {
2200            "macos" | "linux" | "windows" => Ok(os_guard(val)),
2201            _ => Err(cur.err(format!(
2202                "unknown os '{val}'; known values: macos, linux, windows"
2203            ))),
2204        },
2205        "arch" => {
2206            if crate::ARCH_VALUES.contains(&val) {
2207                Ok(GuardExpr::Predicate(Guard::Attr {
2208                    ns: Ns::Arch,
2209                    key: None,
2210                    val: Some(val.to_string()),
2211                }))
2212            } else {
2213                Err(cur.err(format!(
2214                    "unknown arch '{val}'; known values: {}",
2215                    crate::ARCH_VALUES.join(", ")
2216                )))
2217            }
2218        }
2219        _ => Err(cur.err(format!(
2220            "unknown guard namespace '{ns}'; known namespaces: family, os, arch, env, bool"
2221        ))),
2222    }
2223}
2224
2225fn parse_guard_term(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2226    let tok = cur
2227        .next()
2228        .ok_or_else(|| cur.err("missing guard predicate"))?;
2229    // A `!` prefix is never negation in guards (only `not(...)` negates).
2230    if matches!(&tok.kind, TokKind::Punct('!')) {
2231        return Err(cur.err("unexpected `!` in guard; negation uses `not(...)`"));
2232    }
2233    let word = match &tok.kind {
2234        TokKind::Word(w) => w.clone(),
2235        _ => return Err(cur.err("missing guard predicate")),
2236    };
2237    // `__OXDOCK_INJECT_N__` interpolation placeholder: env-key shape.
2238    if let Some(rest) = word.strip_prefix(INJECT_PREFIX) {
2239        if !rest.is_empty()
2240            && rest
2241                .strip_suffix(INJECT_SUFFIX)
2242                .is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()))
2243        {
2244            return Ok(GuardExpr::Predicate(Guard::Attr {
2245                ns: Ns::Env,
2246                key: Some(word),
2247                val: None,
2248            }));
2249        }
2250        return Err(cur.err("missing guard predicate"));
2251    }
2252    match word.as_str() {
2253        "eq" | "ne" => {
2254            let inner = cur
2255                .eat_paren_group()
2256                .ok_or_else(|| cur.err(format!("`{word}` requires `(env:KEY, value)`")))?;
2257            let mut arg = Cursor::new(&inner, cur.stmt);
2258            if arg.next().map(|t| &t.kind) != Some(&TokKind::Word("env".to_string())) {
2259                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2260            }
2261            if !arg.eat_punct(':') {
2262                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2263            }
2264            let key = bare_run(&mut arg, |_| true, "guard key")?;
2265            if !arg.eat_punct(',') {
2266                return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`")));
2267            }
2268            arg.skip_newlines();
2269            let value = match arg.next() {
2270                Some(t) => match &t.kind {
2271                    TokKind::Str { text, .. } => text.clone(),
2272                    TokKind::BlockStr(full) => crate::command::lower_block_string(full),
2273                    _ => {
2274                        // Bare value: runs to the region end (commas and
2275                        // groups terminate it with an error, matching the
2276                        // bare-value exclusions).
2277                        arg.pos -= 1;
2278                        value_run(&mut arg)?
2279                    }
2280                },
2281                None => return Err(arg.err(format!("`{word}` requires `(env:KEY, value)`"))),
2282            };
2283            if !arg.done() {
2284                return Err(arg.err(format!("unexpected text after `{word}` value")));
2285            }
2286            let pred = GuardExpr::Predicate(Guard::Attr {
2287                ns: Ns::Env,
2288                key: Some(key),
2289                val: Some(value),
2290            });
2291            if word == "ne" {
2292                Ok(GuardExpr::Not(Box::new(pred)))
2293            } else {
2294                Ok(pred)
2295            }
2296        }
2297        "bool" => {
2298            if !cur.eat_punct(':') {
2299                return Err(cur.err("`bool` requires `:value`"));
2300            }
2301            let val = bare_run(cur, |_| true, "bool value")?;
2302            check_term_end(cur)?;
2303            Ok(GuardExpr::Predicate(Guard::Attr {
2304                ns: Ns::Bool,
2305                key: None,
2306                val: Some(val),
2307            }))
2308        }
2309        "env" => {
2310            if !cur.eat_punct(':') {
2311                return Err(cur.err("`env` requires `:KEY`"));
2312            }
2313            let key = bare_run(cur, |_| true, "guard key")?;
2314            check_term_end(cur)?;
2315            Ok(GuardExpr::Predicate(Guard::Attr {
2316                ns: Ns::Env,
2317                key: Some(key),
2318                val: None,
2319            }))
2320        }
2321        _ => {
2322            if !cur.eat_punct(':') {
2323                return Err(cur.err("missing guard predicate"));
2324            }
2325            let val = bare_run(cur, |_| true, "guard value")?;
2326            check_term_end(cur)?;
2327            ns_guard(&word, &val, cur)
2328        }
2329    }
2330}
2331
2332/// Bare `eq`/`ne` value run: key charset plus `:`/`=`/`!` (the grammar
2333/// admits them in values, never in keys), with nested groups rendered
2334/// for the pathological `(`-in-value shape. `$`, `|`, `,` terminate
2335/// with an error downstream.
2336/// Bare `eq`/`ne` value with atomic bare-value semantics:
2337/// everything except `, | ) ] $`, linebreaks, and comment opens —
2338/// gaps included (joined with one space; the token stream cannot
2339/// preserve gap width). Quotes ride literally mid-run (the atomic
2340/// span keeps them); a *leading* quote never reaches here (the
2341/// caller strips it as the `quoted_string` alternative, which then
2342/// requires end-of-region like the grammar's committed choice).
2343fn value_run(arg: &mut Cursor) -> Result<String, TokenError> {
2344    let mut out = String::new();
2345    while let Some(tok) = arg.toks.get(arg.pos) {
2346        // Terminators: the grammar's negative-lookahead set.
2347        match &tok.kind {
2348            TokKind::Newline | TokKind::Comment(_) => break,
2349            TokKind::Punct(',')
2350            | TokKind::Punct('|')
2351            | TokKind::Punct(']')
2352            | TokKind::Punct(')') => break,
2353            TokKind::Punct(VAR_SIGIL_CHAR) => break,
2354            TokKind::Punct('/') if is_comment_open(arg.toks, arg.pos) => break,
2355            TokKind::Group { .. } => break,
2356            _ => {}
2357        }
2358        if !out.is_empty() && !tok.joint {
2359            out.push(' ');
2360        }
2361        match &tok.kind {
2362            TokKind::Word(w) => out.push_str(w),
2363            TokKind::Punct(c) => out.push(*c),
2364            TokKind::Semicolon => out.push(';'),
2365            // Mid-run quotes keep their marks, like the atomic span.
2366            TokKind::Str { text, quote } => {
2367                out.push(*quote);
2368                out.push_str(text);
2369                out.push(*quote);
2370            }
2371            TokKind::BlockStr(full) => out.push_str(full),
2372            _ => break,
2373        }
2374        arg.pos += 1;
2375    }
2376    if out.is_empty() {
2377        return Err(arg.err("missing guard value"));
2378    }
2379    Ok(out)
2380}
2381
2382/// True when the cursor sits on `name` followed (over newlines,
2383/// like the grammar's implicit whitespace) by a paren group.
2384fn at_call(cur: &Cursor, name: &str) -> bool {
2385    let mut pos = cur.pos;
2386    // Leading newlines skip (the grammar's implicit whitespace gaps
2387    // multi-line guards, e.g. `[\nnot(env:K)\n]`).
2388    while matches!(cur.toks.get(pos).map(|t| &t.kind), Some(TokKind::Newline)) {
2389        pos += 1;
2390    }
2391    match cur.toks.get(pos) {
2392        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == name) => pos += 1,
2393        _ => return false,
2394    }
2395    while matches!(cur.toks.get(pos).map(|t| &t.kind), Some(TokKind::Newline)) {
2396        pos += 1;
2397    }
2398    matches!(
2399        cur.toks.get(pos).map(|t| &t.kind),
2400        Some(TokKind::Group {
2401            delim: GroupDelim::Paren,
2402            ..
2403        })
2404    )
2405}
2406
2407fn parse_guard_primary(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2408    // Call shapes dispatch on word + paren group regardless of gap
2409    // width (the grammar's implicit whitespace); anything else is a term.
2410    for name in ["not", "any", "all"] {
2411        if at_call(cur, name) {
2412            cur.next();
2413            let inner = cur
2414                .eat_paren_group()
2415                .ok_or_else(|| cur.err("unreachable"))?;
2416            let parts = split_top_commas(&inner);
2417            match name {
2418                "not" => {
2419                    if parts.len() != 1 {
2420                        return Err(cur.err("`not` takes exactly one guard expression"));
2421                    }
2422                    let mut sub = Cursor::new(parts[0], cur.stmt);
2423                    let expr = parse_guard_seq(&mut sub)?;
2424                    if !sub.done() {
2425                        return Err(sub.err("unexpected text in `not`"));
2426                    }
2427                    return Ok(GuardExpr::Not(Box::new(expr)));
2428                }
2429                "any" => {
2430                    if parts.len() < 2 {
2431                        return Err(cur.err("any(...) requires at least two guard expressions"));
2432                    }
2433                    let mut exprs = Vec::new();
2434                    for part in parts {
2435                        let mut sub = Cursor::new(part, cur.stmt);
2436                        exprs.push(parse_guard_seq(&mut sub)?);
2437                        if !sub.done() {
2438                            return Err(sub.err("unexpected text in `any`"));
2439                        }
2440                    }
2441                    return Ok(GuardExpr::or(exprs));
2442                }
2443                _ => {
2444                    if parts.is_empty() {
2445                        return Err(cur.err("all(...) requires at least one guard expression"));
2446                    }
2447                    let mut exprs = Vec::new();
2448                    for part in parts {
2449                        if part.iter().all(|t| matches!(&t.kind, TokKind::Newline)) {
2450                            return Err(cur.err("all(...) requires at least one guard expression"));
2451                        }
2452                        let mut sub = Cursor::new(part, cur.stmt);
2453                        exprs.push(parse_guard_seq(&mut sub)?);
2454                        if !sub.done() {
2455                            return Err(sub.err("unexpected text in `all`"));
2456                        }
2457                    }
2458                    return Ok(GuardExpr::all(exprs));
2459                }
2460            }
2461        }
2462    }
2463    match cur.peek() {
2464        Some(t) => match &t.kind {
2465            TokKind::Group {
2466                delim: GroupDelim::Paren,
2467                inner,
2468                ..
2469            } => {
2470                let inner = inner.clone();
2471                cur.next();
2472                let mut sub = Cursor::new(&inner, cur.stmt);
2473                let expr = parse_guard_seq(&mut sub)?;
2474                if !sub.done() {
2475                    return Err(sub.err("unexpected text in guard group"));
2476                }
2477                Ok(expr)
2478            }
2479            _ => parse_guard_term(cur),
2480        },
2481        None => Err(cur.err("missing guard expression")),
2482    }
2483}
2484
2485fn parse_guard_seq(cur: &mut Cursor) -> Result<GuardExpr, TokenError> {
2486    let first = parse_guard_primary(cur)?;
2487    let mut rest = vec![first];
2488    while cur.eat_punct(',') {
2489        rest.push(parse_guard_primary(cur)?);
2490    }
2491    if rest.len() == 1 {
2492        Ok(rest.pop().unwrap())
2493    } else {
2494        Ok(GuardExpr::all(rest))
2495    }
2496}
2497
2498/// Parse one bracket group's contents as a guard expression.
2499fn parse_guard_inner(inner: &[Tok], stmt: usize) -> Result<GuardExpr, TokenError> {
2500    let mut cur = Cursor::new(inner, stmt);
2501    let expr = parse_guard_seq(&mut cur)?;
2502    if !cur.done() {
2503        return Err(cur.err("unexpected text in guard"));
2504    }
2505    Ok(expr)
2506}
2507
2508/// Parse one standalone guard expression from lexed tokens (the
2509/// `parse_guard_expr_str` entry point): a bare `guard_seq` with full
2510/// consumption.
2511pub(crate) fn parse_single_guard(toks: &[Tok], stmt: usize) -> Result<GuardExpr, TokenError> {
2512    let mut cur = Cursor::new(toks, stmt);
2513    if cur.done() {
2514        return Err(cur.err("empty guard"));
2515    }
2516    let expr = parse_guard_seq(&mut cur)?;
2517    if !cur.done() {
2518        return Err(cur.err("unexpected text in guard"));
2519    }
2520    Ok(expr)
2521}
2522
2523/// Combine a statement's leading guard groups: stacked brackets `All`
2524/// together, a single bracket stands alone.
2525fn parse_guard_groups(guard: &[Tok], stmt: usize) -> Result<Option<GuardExpr>, TokenError> {
2526    let mut acc: Option<GuardExpr> = None;
2527    for tok in guard {
2528        let inner = match &tok.kind {
2529            TokKind::Group {
2530                delim: GroupDelim::Bracket,
2531                inner,
2532                ..
2533            } => inner.clone(),
2534            _ => {
2535                return Err(TokenError {
2536                    diagnostic: None,
2537                    hint: None,
2538                    stmt,
2539                    msg: "unsupported non-bracket guard".to_string(),
2540                    line: 0,
2541                    col: 0,
2542                    kind: None,
2543                });
2544            }
2545        };
2546        let expr = parse_guard_inner(&inner, stmt)?;
2547        acc = Some(match acc {
2548            None => expr,
2549            Some(prev) => GuardExpr::all(vec![prev, expr]),
2550        });
2551    }
2552    Ok(acc)
2553}
2554
2555// ---- Calls, RUN-exec, instruction exactness ----
2556// Static call resolution runs through the shared `resolve_call_name`
2557// (same module table, same messages); only the token-level call-shape
2558// detector is v2-native. Generic arguments classify like the
2559// `assignment | argument` grammar order (assignments merge across
2560// gaps, `$`/`env:`-led runs extend as expressions, everything else
2561// renders raw), and `ENV`/`EXPAND` lower through the shared direct
2562// cores instead of the injected dispatcher.
2563
2564/// Parse context: shared lowering dispatcher plus module table for
2565/// static call resolution, with `FUNC`/import frames per braced body.
2566pub struct ParseCtx<'a> {
2567    pub lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
2568    pub modules: &'a ModuleTable,
2569    /// Host-registered function names for the `FUNC` shadow check
2570    /// (empty when hosts are unknown).
2571    pub reserved: &'a HashSet<String>,
2572    /// `FUNC` scopes (innermost last) and import frames, pushed per
2573    /// braced body; short borrows only,
2574    /// never held across recursive parses.
2575    pub funcs: RefCell<Vec<HashSet<String>>>,
2576    pub imports: RefCell<Vec<Vec<(String, bool)>>>,
2577    /// Single-file `EXPORT` metadata in source order, validated at end
2578    /// of parse (forward references allowed). One struct for all three
2579    /// kinds so holders never thread parallel lists.
2580    pub exports: RefCell<Exports>,
2581    /// Top-level `FUNC` names pre-declared before lowering, so forward
2582    /// references resolve regardless of order. Separate from `funcs`
2583    /// frames so duplicate detection in `declare_func` stays intact;
2584    /// `visible_snapshot` unions this set.
2585    pub forward: RefCell<Vec<HashSet<String>>>,
2586    /// 1-based source line of the statement currently lowering (the
2587    /// innermost split statement; updated per statement by the body
2588    /// loops, read as the base for nested splits). Lets every error
2589    /// carry its statement's line without threading it through every
2590    /// header function by hand.
2591    pub current_line: RefCell<usize>,
2592}
2593
2594impl<'a> ParseCtx<'a> {
2595    /// Context with empty tables.
2596    pub fn empty(
2597        lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
2598        modules: &'a ModuleTable,
2599        reserved: &'a HashSet<String>,
2600    ) -> Self {
2601        Self {
2602            lower,
2603            modules,
2604            reserved,
2605            funcs: RefCell::new(vec![HashSet::new()]),
2606            imports: RefCell::new(vec![Vec::new()]),
2607            exports: RefCell::new(Exports::default()),
2608            forward: RefCell::new(vec![HashSet::new()]),
2609            current_line: RefCell::new(0),
2610        }
2611    }
2612
2613    /// Snapshot of everything visible at this point: `FUNC` names
2614    /// unioned across frames plus imports flattened outer-to-inner
2615    /// (unions `FUNC` names across frames, flattens imports outer-to-inner,
2616    /// dropping guardedness: call resolution only needs names).
2617    fn visible_snapshot(&self) -> (HashSet<String>, Vec<String>) {
2618        let mut funcs = HashSet::new();
2619        for scope in self.funcs.borrow().iter() {
2620            funcs.extend(scope.iter().cloned());
2621        }
2622        funcs.extend(
2623            self.forward
2624                .borrow()
2625                .iter()
2626                .flat_map(|frame| frame.iter().cloned()),
2627        );
2628        let mut imports = Vec::new();
2629        for frame in self.imports.borrow().iter() {
2630            for (module, _) in frame {
2631                if !imports.contains(module) {
2632                    imports.push(module.clone());
2633                }
2634            }
2635        }
2636        (funcs, imports)
2637    }
2638
2639    /// Record a `FUNC` name in the innermost scope. Returns false when
2640    /// already defined in that same scope (nested shadowing stays
2641    /// allowed (nested shadowing stays permitted).
2642    fn declare_func(&self, name: &str) -> bool {
2643        match self.funcs.borrow_mut().last_mut() {
2644            Some(current) => current.insert(name.to_string()),
2645            None => true,
2646        }
2647    }
2648
2649    /// Record `IMPORT`ed modules in the innermost frame (deduped,
2650    /// (deduped; the unknown-module table check lives at the import site),
2651    /// which lives at the import site. `guarded` marks guard-gated
2652    /// imports so the same-frame duplicate gate can tell a probable
2653    /// typo (unguarded, always collides) from a platform branch
2654    /// (guarded, disjointness decided by the static pass).
2655    fn import_into_frame(&self, modules: &[String], guarded: bool) {
2656        match self.imports.borrow_mut().last_mut() {
2657            Some(frame) => {
2658                for module in modules {
2659                    if !frame.iter().any(|(known, _)| known == module) {
2660                        frame.push((module.clone(), guarded));
2661                    }
2662                }
2663            }
2664            None => {
2665                self.imports
2666                    .borrow_mut()
2667                    .push(modules.iter().map(|m| (m.clone(), guarded)).collect());
2668            }
2669        }
2670    }
2671
2672    /// Guardedness of every visible entry for `alias`, outer to inner.
2673    /// Single owner for the duplicate-gate input, so the gate never
2674    /// restates the frame walk.
2675    fn import_guard_flags(&self, alias: &str) -> Vec<bool> {
2676        let mut out = Vec::new();
2677        for frame in self.imports.borrow().iter() {
2678            for (known, guarded) in frame {
2679                if known == alias {
2680                    out.push(*guarded);
2681                }
2682            }
2683        }
2684        out
2685    }
2686}
2687
2688fn resolve_name(ctx: &ParseCtx, stmt: usize, name: &str) -> Result<String, TokenError> {
2689    let (funcs, imports) = ctx.visible_snapshot();
2690    resolve_call_name(ctx.modules, &funcs, &imports, &lowering_ctx(stmt), name)
2691        .map_err(|e| lower_err(stmt, e))
2692}
2693
2694/// Pre-declare `FUNC` names before lowering, so forward references
2695/// resolve regardless of order. Only valid non-reserved headers hoist:
2696/// the head (`FUNC NAME`, `ASYNC FUNC NAME`), a parameter Paren group,
2697/// a `:` return-type shape (via the shared `parse_type_shape` owner),
2698/// and a trailing non-template Brace body. Malformed headers
2699/// (`FUNC FOO() ECHO hi`) and reserved names (`FUNC LEN`) stay silent
2700/// here so the main pass owns their diagnostics. Runs per scope: the
2701/// caller pre-declares each statement list into its own frame, so
2702/// nested blocks resolve forward without leaking outward.
2703fn predeclare_forward_funcs(stmts: &[Stmt], ctx: &ParseCtx) {
2704    // Guarded definitions hoist like unguarded ones: `parse_func_at`
2705    // registers the name in `ctx.funcs` unconditionally, so the
2706    // forward set must see the same statement regardless of its
2707    // guard, or forward calls to `[os:macos] FUNC FOO` would fail
2708    // while backward calls resolve.
2709    for stmt in stmts {
2710        let body = &stmt.body;
2711        // `ASYNC FUNC` carries the prefix; the shared header owner
2712        // takes `pos` at `FUNC` in both cases.
2713        let pos = match body.first().map(|t| &t.kind) {
2714            Some(TokKind::Word(w)) if w == KEYWORD_FUNC => 0,
2715            Some(TokKind::Word(w)) if w == KEYWORD_ASYNC => match body.get(1).map(|t| &t.kind) {
2716                Some(TokKind::Word(next)) if next == KEYWORD_FUNC => 1,
2717                _ => continue,
2718            },
2719            _ => continue,
2720        };
2721        // Header grammar lives in the single owner: parameter lists,
2722        // return types, and trailing tokens validate exactly like the
2723        // real path, so malformed headers never hoist. Diagnostics
2724        // drop here (silent skip); the main pass owns the error.
2725        let Ok(Some((header, _))) = parse_func_header(body, pos, 0, KEYWORD_FUNC) else {
2726            continue;
2727        };
2728        if ctx.reserved.contains(&header.name)
2729            || ctx.modules.reserved_base_names().contains(&header.name)
2730        {
2731            continue;
2732        }
2733        // Trailing tokens after the body block are malformed (the real
2734        // path consumes the header exactly, leaving them to fail as the
2735        // next element), so such headers never hoist into `forward`:
2736        // only gap trivia may follow.
2737        if body.len() != header.block + 1
2738            && !body[header.block + 1..]
2739                .iter()
2740                .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
2741        {
2742            continue;
2743        }
2744        if let Some(frame) = ctx.forward.borrow_mut().last_mut() {
2745            frame.insert(header.name.clone());
2746        }
2747    }
2748}
2749
2750/// Qualify bare placeholder calls in template text through the
2751/// shared static resolver, so `{{ NAME(args) }}` obeys exactly the
2752/// same scope rule as statement-position calls: `IMPORT [MOD]`
2753/// brings the names into scope, unimported names fail naming the
2754/// fix, ambiguity fails closed. Qualified (`MOD::FUNC`), variable
2755/// (`$x`, `bare_key`), env (`env:K`), and non-call keys pass
2756/// through untouched for the runtime to handle exactly as before;
2757/// only keys that are entirely one bare call shape are rewritten,
2758/// and only the head identifier's bytes change: surrounding
2759/// spacing and neighboring placeholders stay byte-identical, so
2760/// string payloads never lose formatting. Returns `None` when
2761/// nothing qualified, leaving the text completely untouched.
2762/// Shape detection is the shared `template::parse_placeholder_call`
2763/// grammar (also behind runtime dispatch), so parse and runtime
2764/// can never disagree on what counts as one call.
2765fn qualify_template_calls(
2766    text: &str,
2767    ctx: &ParseCtx,
2768    stmt: usize,
2769) -> Result<Option<String>, TokenError> {
2770    use crate::template::{TemplateSegment, TemplateSegments, parse_placeholder_call};
2771    let mut out = String::with_capacity(text.len());
2772    let mut changed = false;
2773    for segment in TemplateSegments::new(text) {
2774        match segment {
2775            TemplateSegment::Text(raw) => out.push_str(raw),
2776            TemplateSegment::Placeholder { key, raw } => {
2777                let call = match parse_placeholder_call(key) {
2778                    Some(call) if call.module.is_none() => call,
2779                    _ => {
2780                        out.push_str(raw);
2781                        continue;
2782                    }
2783                };
2784                let head = call.name;
2785                let resolved = resolve_name(ctx, stmt, head)?;
2786                if !resolved.contains(MODULE_SEPARATOR) {
2787                    // Unqualified resolutions (`INSPECT`) keep today's
2788                    // runtime handling untouched.
2789                    out.push_str(raw);
2790                    continue;
2791                }
2792                changed = true;
2793                // Splice only the head span: `name_span` is the byte
2794                // range of the head inside `key`, and `key` is the
2795                // trimmed interior of `raw`, so the raw offset is the
2796                // interior start plus the span start.
2797                let key_off = raw.find(key).expect("key is trimmed interior");
2798                let off = key_off + call.name_span.start;
2799                out.push_str(&raw[..off]);
2800                out.push_str(&resolved);
2801                out.push_str(&raw[off + head.len()..]);
2802            }
2803        }
2804    }
2805    if changed { Ok(Some(out)) } else { Ok(None) }
2806}
2807
2808/// Call shape at `pos`: UPPERCASE head plus joint `::` segments and a
2809/// paren group (joint iff required: statements forbid the gap;
2810/// expressions allow it).
2811/// Peek-only; anything else falls through (not a call shape).
2812/// Returns the dotted name and paren index.
2813fn call_shape_at(toks: &[Tok], pos: usize, joint_paren: bool) -> Option<(String, usize)> {
2814    let head = match toks.get(pos).map(|t| &t.kind) {
2815        Some(TokKind::Word(w))
2816            if !w.is_empty()
2817                && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
2818                && w.chars()
2819                    .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') =>
2820        {
2821            w.clone()
2822        }
2823        _ => return None,
2824    };
2825    let mut name = head;
2826    let mut p = pos + 1;
2827    loop {
2828        let colons = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')))
2829            && toks.get(p).is_some_and(|t| t.joint)
2830            && matches!(toks.get(p + 1).map(|t| &t.kind), Some(TokKind::Punct(':')))
2831            && toks.get(p + 1).is_some_and(|t| t.joint)
2832            && matches!(toks.get(p + 2).map(|t| &t.kind), Some(TokKind::Word(_)))
2833            && toks.get(p + 2).is_some_and(|t| t.joint);
2834        if !colons {
2835            break;
2836        }
2837        if let Some(TokKind::Word(seg)) = toks.get(p + 2).map(|t| &t.kind) {
2838            name.push_str(MODULE_SEPARATOR);
2839            name.push_str(seg);
2840        }
2841        p += 3;
2842    }
2843    match toks.get(p).map(|t| &t.kind) {
2844        Some(TokKind::Group {
2845            delim: GroupDelim::Paren,
2846            ..
2847        }) => {
2848            if joint_paren && !toks[p].joint {
2849                return None;
2850            }
2851            Some((name, p))
2852        }
2853        _ => None,
2854    }
2855}
2856
2857/// Call arguments over a paren group's contents: comma-separated full
2858/// expressions with `gap_nl` newlines at the edges (each arg rejects
2859/// a stray boundary).
2860fn parse_call_args(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Vec<Expr>, TokenError> {
2861    let mut cur = Cursor::expr(inner, stmt);
2862    cur.skip_gap_nl();
2863    if cur.done() {
2864        return Ok(vec![]);
2865    }
2866    let mut args = Vec::new();
2867    loop {
2868        let arg = parse_expr_or(&mut cur, ctx)?;
2869        reject_boundary(&lowering_ctx(stmt), &arg).map_err(|e| cur.err(e.to_string()))?;
2870        args.push(arg);
2871        cur.skip_gap_nl();
2872        if cur.eat_punct(',') {
2873            cur.skip_gap_nl();
2874            continue;
2875        }
2876        break;
2877    }
2878    if !cur.done() {
2879        return Err(trailing_items_error(
2880            &cur,
2881            ctx,
2882            stmt,
2883            "call arguments",
2884            "unexpected text in call",
2885        ));
2886    }
2887    Ok(args)
2888}
2889
2890/// Lower a call-shape to `Expr`: `INSPECT` keeps its variable
2891/// unevaluated (`INSPECT($var)` for `LET` and `$`-sigiled `CONST`
2892/// reads); everything else resolves statically through the shared
2893/// resolver.
2894fn parse_expr_call(
2895    name: String,
2896    inner: &[Tok],
2897    stmt: usize,
2898    ctx: &ParseCtx,
2899) -> Result<Expr, TokenError> {
2900    let args = parse_call_args(inner, stmt, ctx)?;
2901    if name == KEYWORD_INSPECT {
2902        let [arg] = args.as_slice() else {
2903            return Err(TokenError {
2904                diagnostic: None,
2905                hint: None,
2906                stmt,
2907                msg: format!(
2908                    "{KEYWORD_INSPECT} requires exactly one argument: {KEYWORD_INSPECT}($var)"
2909                ),
2910                line: 0,
2911                col: 0,
2912                kind: None,
2913            });
2914        };
2915        if let Expr::Var { name } = arg {
2916            return Ok(Expr::Inspect { name: name.clone() });
2917        }
2918        return Err(TokenError {
2919            diagnostic: None,
2920            hint: None,
2921            stmt,
2922            msg: format!("{KEYWORD_INSPECT} requires a $variable argument, found {arg:?}"),
2923            line: 0,
2924            col: 0,
2925            kind: None,
2926        });
2927    }
2928    let qualified = resolve_name(ctx, stmt, &name)?;
2929    Ok(Expr::Call {
2930        name: qualified,
2931        args,
2932    })
2933}
2934
2935/// Item rule selecting which `[...]` position the shared list core
2936/// parses for. The loop, comma rule, empty rule, trailing-content rule,
2937/// and newline tolerance are identical for every position (see
2938/// [`parse_bracket_list`]); only items and miss handling differ.
2939#[derive(Clone, Copy)]
2940enum BracketItems {
2941    /// Full checked expressions; a miss fails loudly.
2942    Expr,
2943    /// RUN-exec restricted atoms (brace groups try maps only, so blocks
2944    /// miss); a miss is shell fallthrough (`None`), never an error, so
2945    /// POSIX `[ -f ... ]` and malformed shapes stay shell.
2946    Exec,
2947}
2948
2949/// Trailing-content error for comma-separated positions (list
2950/// items, call arguments): stamps the offending token's position so
2951/// the caret names the line that actually fails instead of the
2952/// statement head, and names the likely missing comma when the
2953/// remainder parses as another item. Genuine trailing garbage keeps
2954/// the previous message verbatim. Error-path only, so the probe
2955/// parse costs nothing on success.
2956fn trailing_items_error(
2957    cur: &Cursor,
2958    ctx: &ParseCtx,
2959    stmt: usize,
2960    missing_what: &str,
2961    fallback: &str,
2962) -> TokenError {
2963    let (line, col) = cur
2964        .toks
2965        .get(cur.pos)
2966        .map(|t| (t.line, t.col))
2967        .unwrap_or((0, 0));
2968    let mut probe = Cursor::expr(&cur.toks[cur.pos.min(cur.toks.len())..], stmt);
2969    let msg = if parse_expr_checked(&mut probe, ctx).is_ok() {
2970        format!("missing comma between {missing_what}")
2971    } else {
2972        fallback.to_string()
2973    };
2974    TokenError {
2975        diagnostic: None,
2976        hint: None,
2977        stmt,
2978        line,
2979        col,
2980        msg,
2981        kind: None,
2982    }
2983}
2984
2985/// Shared comma-separated `[...]` core behind every bracket position.
2986/// There is exactly one list loop: one empty rule, one comma rule, one
2987/// trailing-content rule, newlines riding every gap. A bracket group
2988/// already lexes across lines, so rejecting newlines here only strands
2989/// the statement in raw-text rendering.
2990fn parse_bracket_list(
2991    inner: &[Tok],
2992    stmt: usize,
2993    ctx: &ParseCtx,
2994    items: BracketItems,
2995) -> Result<Option<Expr>, TokenError> {
2996    let mut cur = Cursor::expr(inner, stmt);
2997    cur.skip_gap_nl();
2998    if cur.done() {
2999        return Ok(Some(Expr::List(vec![])));
3000    }
3001    let mut list = Vec::new();
3002    loop {
3003        let item = match items {
3004            BracketItems::Expr => parse_expr_checked(&mut cur, ctx),
3005            BracketItems::Exec => match parse_run_exec_atom(&mut cur, ctx) {
3006                Ok(Some(atom)) => Ok(atom),
3007                // Not an exec shape at all: shell fallthrough.
3008                Ok(None) | Err(_) => return Ok(None),
3009            },
3010        };
3011        // Only expression positions can fail here: exec misses
3012        // return `None` above.
3013        let item = item?;
3014        match reject_boundary(&lowering_ctx(stmt), &item) {
3015            Ok(()) => {}
3016            Err(e) if matches!(items, BracketItems::Expr) => {
3017                return Err(cur.err(e.to_string()));
3018            }
3019            Err(_) => return Ok(None),
3020        }
3021        list.push(item);
3022        cur.skip_gap_nl();
3023        if cur.eat_punct(',') {
3024            cur.skip_gap_nl();
3025            continue;
3026        }
3027        break;
3028    }
3029    if !cur.done() {
3030        return match items {
3031            BracketItems::Expr => Err(trailing_items_error(
3032                &cur,
3033                ctx,
3034                stmt,
3035                "list items",
3036                "unexpected text in list",
3037            )),
3038            BracketItems::Exec => Ok(None),
3039        };
3040    }
3041    Ok(Some(Expr::List(list)))
3042}
3043
3044/// RUN exec-form list: the shared bracket core in `Exec` mode (atoms
3045/// only, except parenthesized/calls/lists/maps which recurse fully).
3046/// Anything that is not a clean comma-separated list misses the whole
3047/// exec shape (`None`): the grammar falls through to the shell path,
3048/// which reads the bracket literally and lets the shared lowering
3049/// decide (POSIX `[ -f ... ]` stays shell; non-map blocks and malformed
3050/// shapes behave exactly like the grammar's fallthrough).
3051/// (`instruction`), which reads the bracket literally and lets the
3052/// shared lowering decide (POSIX `[ -f ... ]` stays shell, malformed
3053/// shapes fail there exactly like the grammar). Only the
3054/// joint-bracket gate stays a hard error (it precedes this function).
3055fn parse_run_exec_list(
3056    inner: &[Tok],
3057    stmt: usize,
3058    ctx: &ParseCtx,
3059) -> Result<Option<Expr>, TokenError> {
3060    parse_bracket_list(inner, stmt, ctx, BracketItems::Exec)
3061}
3062
3063/// One RUN-exec item: brace groups try maps only (blocks miss);
3064/// everything else parses as a full atom (nested lists and map
3065/// values still admit blocks, like the grammar).
3066fn parse_run_exec_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Option<Expr>, TokenError> {
3067    if matches!(
3068        cur.toks.get(cur.pos).map(|t| &t.kind),
3069        Some(TokKind::Group {
3070            delim: GroupDelim::Brace,
3071            ..
3072        })
3073    ) {
3074        let inner = match &cur.toks[cur.pos].kind {
3075            TokKind::Group { inner, .. } => inner.clone(),
3076            _ => unreachable!(),
3077        };
3078        return match parse_map_literal(&inner, cur.stmt, ctx) {
3079            Ok(map) => {
3080                cur.pos += 1;
3081                Ok(Some(map))
3082            }
3083            Err(_) => Ok(None),
3084        };
3085    }
3086    parse_expr_atom(cur, ctx).map(Some)
3087}
3088
3089// ---- Single-command wrappers + AWAIT/CANCEL ----
3090// Wrappers parse through the shared validators (`check_tty_wrapping`,
3091// capture rejects, isolated rewrite, nesting reject, binding merge,
3092// guard `and`) promoted verbatim to `commands.rs`; only the
3093// token-level shape classifiers (duration gate, binding splitter,
3094// await/cancel shapes, block-vs-template) are v2-native. Statements
3095// lower to step VECTORS: structural pairs (calls, RUN-exec,
3096// await/cancel, wrapper blocks) end mid-line and trailing elements
3097// form following steps, exactly like the grammar's `element*`.
3098//
3099// Deferred: block STATEMENTS (slice 5: top-level `IF`/`FOR`/`WHILE`
3100// bodies, guard blocks, `REMOTE`, directives).
3101
3102/// Static duration shape mirror (`timeout_literal`, atomic): ASCII
3103/// digits plus one optional unit, full-match only. Anything else
3104/// (`10ss`, `banana`, `-5s`) misses the wrapper shape and falls back
3105/// to the generic instruction path, which fails in lowering exactly
3106/// like the grammar's committed `instruction`.
3107fn is_timeout_literal(text: &str) -> bool {
3108    let digits = text.len() - text.trim_start_matches(|c: char| c.is_ascii_digit()).len();
3109    if digits == 0 {
3110        return false;
3111    }
3112    matches!(&text[digits..], "" | "ms" | "s" | "m" | "h")
3113}
3114
3115/// Template-brace test: a brace group whose first inner token opens
3116/// another brace (`{{...}}`); anything else braced is a block body.
3117/// Same shape the arg engine uses; single source from here.
3118fn is_template_brace(tok: &Tok) -> bool {
3119    matches!(
3120        &tok.kind,
3121        TokKind::Group {
3122            delim: GroupDelim::Brace,
3123            inner,
3124            ..
3125        } if matches!(
3126            inner.first().map(|t| &t.kind),
3127            Some(TokKind::Group {
3128                delim: GroupDelim::Brace,
3129                ..
3130            })
3131        )
3132    )
3133}
3134
3135/// Parse one TIMEOUT duration unit at `pos` (the token after the
3136/// head, gapped like the grammar's `sep`). Returns the arg and
3137/// tokens consumed, or `None` on shape miss (caller falls back to
3138/// generic, which fails in lowering). Static
3139/// literals validate now through the shared Duration check
3140/// (`TIMEOUT 0s` fails here, probed); dynamics defer to runtime.
3141fn parse_timeout_duration_at(
3142    toks: &[Tok],
3143    pos: usize,
3144    stmt: usize,
3145) -> Result<Option<(Arg, usize)>, TokenError> {
3146    let Some(head) = toks.get(pos) else {
3147        return Ok(None);
3148    };
3149    if head.joint {
3150        return Ok(None);
3151    }
3152    let arg = match &head.kind {
3153        TokKind::Word(w) if is_timeout_literal(w) => Arg::String(w.clone(), false),
3154        TokKind::Punct(VAR_SIGIL_CHAR) => match toks.get(pos + 1) {
3155            Some(var) if var.joint && matches!(&var.kind, TokKind::Word(w) if is_ident_word(w)) => {
3156                match &var.kind {
3157                    TokKind::Word(w) => Arg::Expr(Expr::Var { name: w.clone() }),
3158                    _ => unreachable!(),
3159                }
3160            }
3161            _ => return Ok(None),
3162        },
3163        TokKind::Str { text, .. } => Arg::String(text.clone(), true),
3164        TokKind::BlockStr(full) => Arg::String(crate::command::lower_block_string(full), true),
3165        TokKind::Group {
3166            delim: GroupDelim::Brace,
3167            inner,
3168            open_joint,
3169            close_joint,
3170        } if is_template_brace(&toks[pos]) => Arg::String(
3171            render_group('{', '}', inner, *open_joint, *close_joint),
3172            false,
3173        ),
3174        _ => return Ok(None),
3175    };
3176    let used = match &head.kind {
3177        TokKind::Punct(VAR_SIGIL_CHAR) => 2,
3178        _ => 1,
3179    };
3180    ArgType::Duration.check_arg(&arg).map_err(|e| TokenError {
3181        hint: None,
3182        stmt,
3183        msg: e.to_string(),
3184        line: 0,
3185        col: 0,
3186        kind: None,
3187        diagnostic: Some(Box::new(e)),
3188    })?;
3189    Ok(Some((arg, used)))
3190}
3191
3192/// Parse `WITH_IO [...]` bindings over a bracket group's inner
3193/// tokens: comma-separated `stream[=$var]` / `rows|cols=int`
3194/// bindings, newlines skipping freely like `ws`. Returns `None` on
3195/// shape miss (empty flags, bad stream words, missing commas or
3196/// values: the caller falls back to generic, which fails in lowering).
3197/// Grammar-matched but invalid bindings (tty
3198/// values, out-of-range geometry) fail loudly, mirroring
3199/// `parse_io_binding`'s messages one by one.
3200fn parse_io_bindings(
3201    inner: &[Tok],
3202    stmt: usize,
3203    ctx: &ParseCtx,
3204) -> Result<Option<Vec<IoBinding>>, TokenError> {
3205    let mut parts: Vec<&[Tok]> = Vec::new();
3206    let mut start = 0;
3207    for (i, tok) in inner.iter().enumerate() {
3208        // Newlines skip freely like `ws` (filtered per part below);
3209        // commas split bindings; everything else is content.
3210        if matches!(&tok.kind, TokKind::Punct(',')) {
3211            parts.push(&inner[start..i]);
3212            start = i + 1;
3213        }
3214    }
3215    parts.push(&inner[start..]);
3216    // An empty flag list (`[]`, `[,]`) misses the shape.
3217    if parts.len() == 1 && parts[0].iter().all(|t| matches!(&t.kind, TokKind::Newline)) {
3218        return Ok(None);
3219    }
3220    let mut out = Vec::new();
3221    for part in parts {
3222        let part: Vec<&Tok> = part
3223            .iter()
3224            .filter(|t| !matches!(&t.kind, TokKind::Newline))
3225            .collect();
3226        match parse_io_binding_part(&part, stmt, ctx)? {
3227            Some(binding) => out.push(binding),
3228            None => return Ok(None),
3229        }
3230    }
3231    if out.is_empty() {
3232        return Ok(None);
3233    }
3234    Ok(Some(out))
3235}
3236
3237/// One `stream[=$var]` / `rows|cols=int` binding.
3238/// Gaps ride free around `=`/`,`/names like `ws?`; only `$`+name
3239/// stays gapless (atomic `dollar_ident`), covering `LET` and
3240/// `$`-sigiled `CONST` pipes alike. Streams and size names outside the grammar's words
3241/// miss the shape; a valued `tty` and out-of-range geometry fail
3242/// loudly with exact messages.
3243fn parse_io_binding_part(
3244    part: &[&Tok],
3245    stmt: usize,
3246    _ctx: &ParseCtx,
3247) -> Result<Option<IoBinding>, TokenError> {
3248    let fail = |msg: String| TokenError {
3249        diagnostic: None,
3250        hint: None,
3251        stmt,
3252        msg,
3253        line: 0,
3254        col: 0,
3255        kind: None,
3256    };
3257    let Some(first) = part.first() else {
3258        return Ok(None);
3259    };
3260    let TokKind::Word(stream) = &first.kind else {
3261        return Ok(None);
3262    };
3263    let is_stream = matches!(stream.as_str(), "stdin" | "stdout" | "stderr" | "tty");
3264    let is_size = matches!(stream.as_str(), "rows" | "cols");
3265    if !is_stream && !is_size {
3266        return Ok(None);
3267    }
3268    let rest = &part[1..];
3269    if rest.is_empty() {
3270        if is_size {
3271            // Bare `rows` misses `io_size` (`=` + digits required).
3272            return Ok(None);
3273        }
3274        return Ok(Some(IoBinding {
3275            stream: io_stream_of(stream),
3276            pipe: None,
3277        }));
3278    }
3279    // `= value` at any gap.
3280    if !matches!(rest.first().map(|t| &t.kind), Some(TokKind::Punct('='))) {
3281        return Ok(None);
3282    }
3283    let value = &rest[1..];
3284    if is_size {
3285        // Geometry: one all-digit word, 1-65535 (mirrors `parse_io_size`).
3286        if value.len() != 1 {
3287            return Ok(None);
3288        }
3289        let TokKind::Word(digits) = &value[0].kind else {
3290            return Ok(None);
3291        };
3292        if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
3293            return Ok(None);
3294        }
3295        let dim = digits
3296            .parse::<u64>()
3297            .ok()
3298            .filter(|v| (1..=u64::from(u16::MAX)).contains(v))
3299            .ok_or_else(|| {
3300                fail(
3301                    "WITH_IO terminal geometry needs a positive integer 1-65535 (e.g. `rows=40`)"
3302                        .to_string(),
3303                )
3304            })?;
3305        let dim = dim as u16;
3306        return Ok(Some(IoBinding {
3307            stream: if stream == "rows" {
3308                IoStream::Rows(dim)
3309            } else {
3310                IoStream::Cols(dim)
3311            },
3312            pipe: None,
3313        }));
3314    }
3315    // Stream pipe: `= $var` with a gapless name.
3316    if value.len() == 2
3317        && matches!(&value[0].kind, TokKind::Punct(VAR_SIGIL_CHAR))
3318        && let TokKind::Word(var) = &value[1].kind
3319        && value[1].joint
3320        && is_ident_word(var)
3321    {
3322        if stream == "tty" {
3323            return Err(fail(
3324                "WITH_IO [tty] takes no value: use bare `tty`, with `rows = <int>` / `cols = <int>` for geometry (e.g. `[tty, rows=40, cols=100]`)"
3325                    .to_string(),
3326            ));
3327        }
3328        return Ok(Some(IoBinding {
3329            stream: io_stream_of(stream),
3330            pipe: Some(crate::ast::PipeTarget::Var { name: var.clone() }),
3331        }));
3332    }
3333    Ok(None)
3334}
3335
3336/// Stream word to [`IoStream`]: only grammar words reach here, so
3337/// the mapping is total (mirrors `parse_io_stream`).
3338fn io_stream_of(name: &str) -> IoStream {
3339    match name {
3340        "stdin" => IoStream::Stdin,
3341        "stdout" => IoStream::Stdout,
3342        "stderr" => IoStream::Stderr,
3343        _ => IoStream::Tty,
3344    }
3345}
3346
3347/// `AWAIT`/`CANCEL $var` shape at `pos` (`$`-sigiled, covering `LET`
3348/// and `CONST` handles alike). A head without `$` misses
3349/// (`None`: generic fails it in lowering); once `$` commits, the
3350/// name must follow and parse errors stay loud. `var_joint`
3351/// enforces atomic adjacency inside compound parents.
3352fn parse_await_cancel_at(
3353    toks: &[Tok],
3354    pos: usize,
3355    stmt: usize,
3356    var_joint: bool,
3357    _ctx: &ParseCtx,
3358) -> Result<Option<(StepKind, usize)>, TokenError> {
3359    let head = match toks.get(pos).map(|t| &t.kind) {
3360        Some(TokKind::Word(w)) if w == KEYWORD_AWAIT || w == KEYWORD_CANCEL => w.clone(),
3361        _ => return Ok(None),
3362    };
3363    if matches!(
3364        toks.get(pos + 1).map(|t| &t.kind),
3365        Some(TokKind::Punct(VAR_SIGIL_CHAR))
3366    ) {
3367        let var = match toks.get(pos + 2) {
3368            Some(t)
3369                if matches!(&t.kind, TokKind::Word(w) if is_ident_word(w))
3370                    && (!var_joint || t.joint) =>
3371            {
3372                match &t.kind {
3373                    TokKind::Word(w) => w.clone(),
3374                    _ => unreachable!(),
3375                }
3376            }
3377            _ => {
3378                return Err(TokenError {
3379                    diagnostic: None,
3380                    hint: None,
3381                    stmt,
3382                    msg: format!("{head} requires a variable"),
3383                    line: 0,
3384                    col: 0,
3385                    kind: None,
3386                });
3387            }
3388        };
3389        return Ok(Some((
3390            if head == KEYWORD_AWAIT {
3391                StepKind::Await { var }
3392            } else {
3393                StepKind::Cancel { var }
3394            },
3395            3,
3396        )));
3397    }
3398    Ok(None)
3399}
3400
3401/// Wrapper strictness for one single-command inner: `AWAIT` parses
3402/// dedicated in `TIMEOUT`/`ISOLATED` inners but falls to generic in
3403/// `WITH_IO`/`ASYNC` inners (where lowering fails it, probed), and
3404/// `WITH_IO` recurses everywhere but directly under `ASYNC` (where
3405/// lowering fails it, probed). Shared predicates, never restated.
3406#[derive(Clone, Copy)]
3407struct InnerRules {
3408    allow_await: bool,
3409    allow_with_io: bool,
3410}
3411
3412/// Parse one single (non-block) inner command, returning the kind
3413/// and tokens consumed: dedicated await/cancel, while/remote, calls,
3414/// RUN-exec, nested wrappers, strict `INHERIT_ENV` (the caller
3415/// rejects the nesting or rewrites it), or the generic instruction
3416/// path (which consumes everything and fails unknown heads in
3417/// lowering, exactly like the grammar's committed `instruction`).
3418fn parse_single_inner(
3419    toks: &[Tok],
3420    pos: usize,
3421    stmt: usize,
3422    ctx: &ParseCtx,
3423    rules: InnerRules,
3424) -> Result<(StepKind, usize), TokenError> {
3425    let head_word = match toks.get(pos).map(|t| &t.kind) {
3426        Some(TokKind::Word(w)) => Some(w.clone()),
3427        _ => None,
3428    };
3429    // Nested `WHILE`/`REMOTE` recurse structurally (both ride every
3430    // inner-command set in the grammar); misses fall through to
3431    // generic below.
3432    if head_word.as_deref() == Some(KEYWORD_WHILE) {
3433        match parse_while_single(toks, pos, stmt, ctx) {
3434            Ok(Some((kind, used))) => return Ok((kind, used)),
3435            Ok(None) => {}
3436            Err(e) => return Err(e),
3437        }
3438    }
3439    if head_word.as_deref() == Some(KEYWORD_REMOTE) {
3440        match parse_remote_single(toks, pos, stmt, ctx) {
3441            Ok(Some((kind, used))) => return Ok((kind, used)),
3442            Ok(None) => {}
3443            Err(e) => return Err(e),
3444        }
3445    }
3446    // File `IMPORT "path" AS ALIAS` (#115) rides every single-inner
3447    // set (TIMEOUT/ISOLATED/WITH_IO/ASYNC, LET ASYNC): exactly one file
3448    // entry and no modules, else a hard error; shape misses fall through
3449    // to generic below, which fails them in lowering.
3450    if head_word.as_deref() == Some(KEYWORD_IMPORT)
3451        && let Some((path, alias, used)) = parse_single_file_import(toks, pos, stmt, ctx)?
3452    {
3453        return Ok((StepKind::ImportFile { path, alias }, used));
3454    }
3455    // Dedicated await/cancel first (await gated by parent); anything
3456    // they decline falls through to generic below.
3457    if head_word.as_deref() == Some(KEYWORD_AWAIT)
3458        && rules.allow_await
3459        && let Some(found) = parse_await_cancel_at(toks, pos, stmt, true, ctx)?
3460    {
3461        return Ok(found);
3462    }
3463    if head_word.as_deref() == Some(KEYWORD_CANCEL)
3464        && let Some(found) = parse_await_cancel_at(toks, pos, stmt, true, ctx)?
3465    {
3466        return Ok(found);
3467    }
3468    // Calls and RUN-exec end mid-run; the caller continues past them.
3469    if let Some((call_name, paren)) = call_shape_at(toks, pos, true) {
3470        let inner = match &toks[paren].kind {
3471            TokKind::Group { inner, .. } => inner.clone(),
3472            _ => unreachable!(),
3473        };
3474        let args = parse_call_args(&inner, stmt, ctx)?;
3475        if !call_name.contains(MODULE_SEPARATOR) {
3476            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
3477                .map_err(|e| lower_err(stmt, e))?;
3478        }
3479        let qualified = resolve_name(ctx, stmt, &call_name)?;
3480        return Ok((
3481            StepKind::Call {
3482                name: qualified,
3483                args,
3484            },
3485            paren + 1 - pos,
3486        ));
3487    }
3488    if head_word.as_deref() == Some(KEYWORD_RUN)
3489        && matches!(
3490            toks.get(pos + 1).map(|t| &t.kind),
3491            Some(TokKind::Group {
3492                delim: GroupDelim::Bracket,
3493                ..
3494            })
3495        )
3496    {
3497        // Gapped like the grammar's `sep`; a joint bracket is a
3498        // hard error, never a spliced arg (probed `RUN["a"]`).
3499        if toks[pos + 1].joint {
3500            return Err(TokenError {
3501                diagnostic: None,
3502                hint: None,
3503                stmt,
3504                msg: format!("{KEYWORD_RUN} [...] requires a gap after {KEYWORD_RUN}"),
3505                line: 0,
3506                col: 0,
3507                kind: None,
3508            });
3509        }
3510        let inner = match &toks[pos + 1].kind {
3511            TokKind::Group { inner, .. } => inner.clone(),
3512            _ => unreachable!(),
3513        };
3514        let exec_list = parse_run_exec_list(&inner, stmt, ctx)?;
3515        // Non-map blocks miss the exec shape (the grammar has no
3516        // `block` alternative here); fall through to generic below,
3517        // which reads the shell path literally.
3518        if let Some(list) = exec_list {
3519            let kind =
3520                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
3521            return Ok((kind, 2));
3522        }
3523    }
3524    // Nested wrappers recurse structurally; a `WITH_IO` directly
3525    // under `ASYNC` goes generic instead (lowering fails it, probed).
3526    match head_word.as_deref() {
3527        Some(KEYWORD_WITH_IO) if rules.allow_with_io => {
3528            match parse_with_io_single(toks, pos, stmt, ctx) {
3529                Ok(Some((kind, used))) => return Ok((kind, used)),
3530                Ok(None) => {}
3531                Err(e) => return Err(e),
3532            }
3533        }
3534        Some(KEYWORD_TIMEOUT) => match parse_timeout_single(toks, pos, stmt, ctx) {
3535            Ok(Some((kind, used))) => return Ok((kind, used)),
3536            Ok(None) => {}
3537            Err(e) => return Err(e),
3538        },
3539        Some(KEYWORD_ISOLATED) => match parse_isolated_single(toks, pos, stmt, ctx) {
3540            Ok(Some((kind, used))) => return Ok((kind, used)),
3541            Ok(None) => {}
3542            Err(e) => return Err(e),
3543        },
3544        Some(KEYWORD_ASYNC) => match parse_async_single(toks, pos, stmt, ctx) {
3545            Ok(Some((kind, used))) => return Ok((kind, used)),
3546            Ok(None) => {}
3547            Err(e) => return Err(e),
3548        },
3549        // `INHERIT_ENV [...]` parses strictly here (shared with
3550        // element level); the caller either rejects the nesting or
3551        // rewrites it, same as the shared validator. Trailing
3552        // elements loop on outside (a bad follower fails there, like
3553        // the grammar's line end).
3554        Some(KEYWORD_INHERIT_ENV) => {
3555            if let Some(found) = parse_inherit_env_at(toks, pos, stmt)? {
3556                return Ok(found);
3557            }
3558        }
3559        _ => {}
3560    }
3561    // Generic instruction: consumes the whole run; unknown heads
3562    // (LET/RETURN/FUNC/IF/...) fail in lowering.
3563    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
3564    Ok((kind, used))
3565}
3566
3567/// Parse an `INHERIT_ENV [...]` key list over a bracket group's
3568/// inner tokens, mirroring `inherit_list` strictly: comma-separated
3569/// keys, gaps/newlines only around keys and commas (never inside:
3570/// keys are atomic), each key a joint run validated against the
3571/// `guard_key_char` exclusions (`: = ! , | ( ) ] $`, plus the `//`
3572/// and `/*` comment opens). Groups and strings render raw (they read
3573/// as ordinary characters here); anything else misses
3574/// the shape (`None`: generic fails it in lowering).
3575/// Statement-level `INHERIT_ENV` stays generic (slice 5 directives);
3576/// this serves wrapper inners, where the nesting check (or the
3577/// isolated rewrite) consumes the result.
3578fn parse_inherit_keys(inner: &[Tok], stmt: usize) -> Result<Option<Vec<String>>, TokenError> {
3579    let mut parts: Vec<&[Tok]> = Vec::new();
3580    let mut start = 0;
3581    for (i, tok) in inner.iter().enumerate() {
3582        if matches!(&tok.kind, TokKind::Punct(',')) {
3583            parts.push(&inner[start..i]);
3584            start = i + 1;
3585        }
3586    }
3587    parts.push(&inner[start..]);
3588    let mut out = Vec::new();
3589    for part in parts {
3590        // Newlines skip at the edges only, like `ws?`.
3591        let mut part = part;
3592        while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
3593            part = &part[1..];
3594        }
3595        while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
3596            part = &part[..part.len() - 1];
3597        }
3598        let Some(key) = render_inherit_key(part, stmt)? else {
3599            return Ok(None);
3600        };
3601        out.push(key);
3602    }
3603    if out.is_empty() {
3604        return Ok(None);
3605    }
3606    Ok(Some(out))
3607}
3608
3609/// True when a `/` opens an inline comment: joint `//` or `/*`
3610/// (mirroring the grammar's comment literals, which need adjacency;
3611/// a gapped second char is payload text, like `a/ /b`). Used
3612/// everywhere `gap`/`gap_nl` admit comments.
3613fn is_comment_open(toks: &[Tok], pos: usize) -> bool {
3614    matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct('/')))
3615        && matches!(
3616            toks.get(pos + 1).map(|t| (&t.kind, t.joint)),
3617            Some((TokKind::Punct('/'), true)) | Some((TokKind::Punct('*'), true))
3618        )
3619}
3620
3621/// Skip one inline comment starting at `pos` (which holds the `/`;
3622/// see [`is_comment_open`): `//` runs to a newline or the end,
3623/// `/* */` balances (nesting like the grammar) across newlines.
3624/// Returns the first position past the comment, or `None` when the
3625/// block never closes (the grammar fails unclosed comments too).
3626fn skip_inline_comment(toks: &[Tok], pos: usize) -> Option<usize> {
3627    let second = match toks.get(pos + 1).map(|t| &t.kind) {
3628        Some(TokKind::Punct('/')) => '/',
3629        Some(TokKind::Punct('*')) => '*',
3630        _ => return None,
3631    };
3632    if second == '/' {
3633        let mut p = pos + 2;
3634        while p < toks.len() && !matches!(&toks[p].kind, TokKind::Newline) {
3635            p += 1;
3636        }
3637        return Some(p);
3638    }
3639    let mut depth = 1usize;
3640    let mut p = pos + 2;
3641    while p < toks.len() {
3642        let is_open = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('/')))
3643            && matches!(
3644                toks.get(p + 1).map(|t| (&t.kind, t.joint)),
3645                Some((TokKind::Punct('*'), true))
3646            );
3647        let is_close = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('*')))
3648            && matches!(
3649                toks.get(p + 1).map(|t| (&t.kind, t.joint)),
3650                Some((TokKind::Punct('/'), true))
3651            );
3652        if is_open {
3653            depth += 1;
3654            p += 2;
3655        } else if is_close {
3656            depth -= 1;
3657            p += 2;
3658            if depth == 0 {
3659                return Some(p);
3660            }
3661        } else {
3662            p += 1;
3663        }
3664    }
3665    None
3666}
3667
3668/// Parse one inherit key: a maximal key-char run, then only
3669/// trailing gap content (`gap_nl`: newlines, comments, `#`). Key
3670/// chars exclude `: = ! , | ( ) ] $`, whitespace, and the `//` / `/*`
3671/// comment opens; a joint `#`
3672/// stays literal, a gapped one opens a trailing comment. Groups and
3673/// strings render raw for the exclusion check (they read as
3674/// ordinary characters here). `None` on shape miss.
3675fn render_inherit_key(part: &[Tok], stmt: usize) -> Result<Option<String>, TokenError> {
3676    let mut out = String::new();
3677    let mut i = 0;
3678    // Key run: words, puncts (except comment opens), groups and
3679    // strings rendered raw; ends at any gap, newline, comment, or
3680    // `//` / `/*` open.
3681    while i < part.len() {
3682        let tok = &part[i];
3683        if i > 0 && !tok.joint {
3684            break;
3685        }
3686        match &tok.kind {
3687            TokKind::Word(w) => {
3688                out.push_str(w);
3689                i += 1;
3690            }
3691            TokKind::Punct('/') if is_comment_open(part, i) => break,
3692            // `#` stays literal at key start (`#c`) or joint
3693            // (`a#b`); gapped mid-key it opens a trailing
3694            // comment like the grammar's `gap_nl`.
3695            TokKind::Punct('#') if tok.joint || out.is_empty() => {
3696                // `#` stays literal at key start (`#c`) or joint
3697                // (`a#b`).
3698                out.push('#');
3699                i += 1;
3700            }
3701            // Gapped mid-key `#` opens a trailing comment (handled
3702            // by the trailer check below, like `gap_nl`).
3703            TokKind::Punct('#') => break,
3704            TokKind::Punct(c) => {
3705                out.push(*c);
3706                i += 1;
3707            }
3708            TokKind::Semicolon => {
3709                out.push(';');
3710                i += 1;
3711            }
3712            TokKind::Str { text, quote } => {
3713                out.push(*quote);
3714                out.push_str(text);
3715                out.push(*quote);
3716                i += 1;
3717            }
3718            TokKind::BlockStr(full) => {
3719                out.push_str(full);
3720                i += 1;
3721            }
3722            TokKind::Group {
3723                delim,
3724                inner,
3725                open_joint,
3726                close_joint,
3727            } => {
3728                let (open, close) = match delim {
3729                    GroupDelim::Bracket => ('[', ']'),
3730                    GroupDelim::Paren => ('(', ')'),
3731                    GroupDelim::Brace => ('{', '}'),
3732                };
3733                out.push_str(&render_group(open, close, inner, *open_joint, *close_joint));
3734                i += 1;
3735            }
3736            // Newlines and comment markers end the key; the trailer
3737            // check below admits them.
3738            TokKind::Newline | TokKind::Comment(_) => break,
3739        }
3740    }
3741    if out.is_empty() {
3742        return Ok(None);
3743    }
3744    // Trailer: only gap content (`gap_nl`) may follow the key.
3745    let mut j = i;
3746    while j < part.len() {
3747        let tok = &part[j];
3748        match &tok.kind {
3749            TokKind::Newline | TokKind::Comment(_) => {
3750                j += 1;
3751            }
3752            TokKind::Punct('/') if is_comment_open(part, j) => {
3753                j = skip_inline_comment(part, j).ok_or(TokenError {
3754                    diagnostic: None,
3755                    hint: None,
3756                    stmt,
3757                    msg: "unclosed block comment".to_string(),
3758                    line: 0,
3759                    col: 0,
3760                    kind: None,
3761                })?;
3762            }
3763            TokKind::Punct('#') => {
3764                // `#` comment runs to a newline or the part end.
3765                while j < part.len() && !matches!(&part[j].kind, TokKind::Newline) {
3766                    j += 1;
3767                }
3768            }
3769            _ => return Ok(None),
3770        }
3771    }
3772    // `guard_key_char` exclusions: the single-char set plus the
3773    // comment opens (`//`, `/*`); lone `/` stays legal.
3774    if out.contains("//") || out.contains("/*") {
3775        return Ok(None);
3776    }
3777    if out.chars().any(|c| {
3778        matches!(
3779            c,
3780            ':' | '=' | '!' | ',' | '|' | '(' | ')' | ']' | VAR_SIGIL_CHAR
3781        )
3782    }) {
3783        return Ok(None);
3784    }
3785    Ok(Some(out))
3786}
3787
3788/// Strict `INHERIT_ENV [...]` at an element or single-inner
3789/// position: bracket riding gapped with valid keys yields the
3790/// directive (trailing elements loop on outside); anything else
3791/// misses (`None`) and generic fails it in lowering.
3792/// Serves both levels so keys stay exact everywhere; slice 5 adds
3793/// only the prelude-order validation.
3794fn parse_inherit_env_at(
3795    toks: &[Tok],
3796    pos: usize,
3797    stmt: usize,
3798) -> Result<Option<(StepKind, usize)>, TokenError> {
3799    // The bracket rides gapped (`sep`); anything else misses and
3800    // generic fails it in lowering.
3801    let bracket = match toks.get(pos + 1) {
3802        Some(t)
3803            if !t.joint
3804                && matches!(
3805                    &t.kind,
3806                    TokKind::Group {
3807                        delim: GroupDelim::Bracket,
3808                        ..
3809                    }
3810                ) =>
3811        {
3812            Some(t)
3813        }
3814        _ => None,
3815    };
3816    let Some(bracket) = bracket else {
3817        return Ok(None);
3818    };
3819    let inner = match &bracket.kind {
3820        TokKind::Group { inner, .. } => inner,
3821        _ => unreachable!(),
3822    };
3823    match parse_inherit_keys(inner, stmt)? {
3824        Some(keys) => Ok(Some((StepKind::InheritEnv { keys }, 2))),
3825        None => Ok(None),
3826    }
3827}
3828
3829/// Parse a brace block body into steps: statements split and lower
3830/// recursively, each keeping its own guard. `mark` selects scope
3831/// marking: top-level guard-block bodies mark (each nesting level
3832/// bumps first/last); wrapper bodies
3833/// (`IF`/`FOR`/`WHILE`/`FUNC`/`REMOTE`/wrappers/io-blocks) never mark
3834/// (block-element lowering pins 0/0).
3835fn parse_body_steps(
3836    inner: &[Tok],
3837    stmt: usize,
3838    ctx: &ParseCtx,
3839    mark: bool,
3840) -> Result<Vec<Step>, TokenError> {
3841    // One function/import scope per braced body (mirroring the
3842    // runtime push/pop boundary): same-block
3843    // `FUNC` redefinition errors, nested shadowing stays allowed.
3844    // Errors abort the whole parse (frames discarded with it), so no
3845    // exit runs on failure.
3846    ctx.funcs.borrow_mut().push(HashSet::new());
3847    ctx.imports.borrow_mut().push(Vec::new());
3848    ctx.forward.borrow_mut().push(HashSet::new());
3849    // Nested splits count lines from the enclosing statement's line
3850    // (headers are single-line, so the brace shares it). Save and
3851    // restore the discipline around the loop: sibling bodies after
3852    // this one must see the enclosing line, not the last inner one.
3853    // (On error the parse aborts and the context is discarded.)
3854    let saved = *ctx.current_line.borrow();
3855    let mut out = Vec::new();
3856    let stmts = split_statements(inner, saved)?;
3857    predeclare_forward_funcs(&stmts, ctx);
3858
3859    for s in &stmts {
3860        // The innermost statement owns error positions: record it for
3861        // nested splits and stamp failures that have none yet (deeper
3862        // frames stamp first, so this never overwrites real positions).
3863        *ctx.current_line.borrow_mut() = s.line;
3864        out.extend(
3865            lower_stmt_steps(s, stmt, ctx, true, mark).map_err(|e| stamp_pos(e, s.line, s.col))?,
3866        );
3867    }
3868    *ctx.current_line.borrow_mut() = saved;
3869    ctx.funcs.borrow_mut().pop();
3870    ctx.imports.borrow_mut().pop();
3871    ctx.forward.borrow_mut().pop();
3872    Ok(out)
3873}
3874
3875/// Single (non-block) `WITH_IO`: bindings plus an optional inner
3876/// command. `None` on shape miss (no/gapped bracket: generic fails
3877/// it in lowering). A brace in single-inner position is
3878/// the grammar's pending-guard error, never an io-block; a bare
3879/// bracket leaks the transient `WithIoBlock` into the body (probed).
3880fn parse_with_io_single(
3881    toks: &[Tok],
3882    pos: usize,
3883    stmt: usize,
3884    ctx: &ParseCtx,
3885) -> Result<Option<(StepKind, usize)>, TokenError> {
3886    let bracket = match toks.get(pos + 1) {
3887        // The bracket rides gapped (`sep`); anything else misses the
3888        // shape and generic fails it in lowering.
3889        Some(t)
3890            if !t.joint
3891                && matches!(
3892                    &t.kind,
3893                    TokKind::Group {
3894                        delim: GroupDelim::Bracket,
3895                        ..
3896                    }
3897                ) =>
3898        {
3899            t
3900        }
3901        _ => return Ok(None),
3902    };
3903    let inner = match &bracket.kind {
3904        TokKind::Group { inner, .. } => inner.clone(),
3905        _ => unreachable!(),
3906    };
3907    let bindings = match parse_io_bindings(&inner, stmt, ctx)? {
3908        Some(bindings) => bindings,
3909        None => return Ok(None),
3910    };
3911    let rest = pos + 2;
3912    // A brace directly after the bracket is the pending-guard error
3913    // in single-inner position (probed); templates fall to generic.
3914    if let Some(next) = toks.get(rest)
3915        && matches!(
3916            &next.kind,
3917            TokKind::Group {
3918                delim: GroupDelim::Brace,
3919                ..
3920            }
3921        )
3922        && !is_template_brace(next)
3923    {
3924        return Err(TokenError {
3925            diagnostic: None,
3926            hint: None,
3927            stmt,
3928            msg: "'{' without a pending guard".to_string(),
3929            line: 0,
3930            col: 0,
3931            kind: None,
3932        });
3933    }
3934    if rest >= toks.len() {
3935        // Bare bracket: the transient block node leaks into wrapper
3936        // bodies (statement level never reaches
3937        // here; the splitter holds it for `{`).
3938        return Ok(Some((StepKind::WithIoBlock { bindings }, 2)));
3939    }
3940    // A joint follower misses the inner `sep`: the bracket stands
3941    // bare (probed `TIMEOUT 10s WITH_IO [..]ECHO hi` yields the
3942    // transient node) and trailing elements loop on outside.
3943    if toks[rest].joint {
3944        return Ok(Some((StepKind::WithIoBlock { bindings }, 2)));
3945    }
3946    let (cmd, used) = parse_single_inner(
3947        toks,
3948        rest,
3949        stmt,
3950        ctx,
3951        InnerRules {
3952            allow_await: false,
3953            allow_with_io: true,
3954        },
3955    )?;
3956    let span = lowering_ctx(stmt);
3957    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| lower_err(stmt, e))?;
3958    let kind = StepKind::WithIo {
3959        bindings,
3960        cmd: Box::new(cmd),
3961    };
3962    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
3963    Ok(Some((kind, 2 + used)))
3964}
3965
3966/// Single (non-block) `TIMEOUT`: duration plus one inner command.
3967/// `None` on shape miss (bad duration, missing/joint inner: generic
3968/// fails it in lowering). Blocks parse inline; the body
3969/// holds one step for single inners.
3970fn parse_timeout_single(
3971    toks: &[Tok],
3972    pos: usize,
3973    stmt: usize,
3974    ctx: &ParseCtx,
3975) -> Result<Option<(StepKind, usize)>, TokenError> {
3976    let Some((duration, dused)) = parse_timeout_duration_at(toks, pos + 1, stmt)? else {
3977        return Ok(None);
3978    };
3979    let rest = pos + 1 + dused;
3980    let Some(next) = toks.get(rest) else {
3981        // `TIMEOUT 10s` alone is a generic instruction (lowering
3982        // fails it, probed), never a bare wrapper.
3983        return Ok(None);
3984    };
3985    if next.joint {
3986        return Ok(None);
3987    }
3988    let body = if matches!(
3989        &next.kind,
3990        TokKind::Group {
3991            delim: GroupDelim::Brace,
3992            ..
3993        }
3994    ) && !is_template_brace(next)
3995    {
3996        let inner = match &next.kind {
3997            TokKind::Group { inner, .. } => inner.clone(),
3998            _ => unreachable!(),
3999        };
4000        let steps = parse_body_steps(&inner, stmt, ctx, false)?;
4001        (steps, 1)
4002    } else {
4003        let (cmd, used) = parse_single_inner(
4004            toks,
4005            rest,
4006            stmt,
4007            ctx,
4008            InnerRules {
4009                allow_await: true,
4010                allow_with_io: true,
4011            },
4012        )?;
4013        (
4014            vec![Step {
4015                guard: None,
4016                kind: cmd,
4017                scope_enter: 0,
4018                scope_exit: 0,
4019                line: 0,
4020                col: 0,
4021            }],
4022            used,
4023        )
4024    };
4025    let kind = StepKind::Timeout {
4026        duration,
4027        body: body.0,
4028    };
4029    let span = lowering_ctx(stmt);
4030    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
4031    Ok(Some((kind, 1 + dused + body.1)))
4032}
4033
4034/// Single (non-block) `ISOLATED`: one inner command or block; the
4035/// body rewrites nested `INHERIT_ENV` through the shared pass.
4036/// `None` on shape miss (missing/joint inner: generic fails it).
4037fn parse_isolated_single(
4038    toks: &[Tok],
4039    pos: usize,
4040    stmt: usize,
4041    ctx: &ParseCtx,
4042) -> Result<Option<(StepKind, usize)>, TokenError> {
4043    let Some(next) = toks.get(pos + 1) else {
4044        return Ok(None);
4045    };
4046    if next.joint {
4047        return Ok(None);
4048    }
4049    let (mut body, used) = if matches!(
4050        &next.kind,
4051        TokKind::Group {
4052            delim: GroupDelim::Brace,
4053            ..
4054        }
4055    ) && !is_template_brace(next)
4056    {
4057        let inner = match &next.kind {
4058            TokKind::Group { inner, .. } => inner.clone(),
4059            _ => unreachable!(),
4060        };
4061        (parse_body_steps(&inner, stmt, ctx, false)?, 1)
4062    } else {
4063        let (cmd, used) = parse_single_inner(
4064            toks,
4065            pos + 1,
4066            stmt,
4067            ctx,
4068            InnerRules {
4069                allow_await: true,
4070                allow_with_io: true,
4071            },
4072        )?;
4073        (
4074            vec![Step {
4075                guard: None,
4076                kind: cmd,
4077                scope_enter: 0,
4078                scope_exit: 0,
4079                line: 0,
4080                col: 0,
4081            }],
4082            used,
4083        )
4084    };
4085    crate::commands::rewrite_isolated_inherit(&mut body);
4086    Ok(Some((StepKind::Isolated { body }, 1 + used)))
4087}
4088
4089/// `FAIL [<code>] [<message>] [{ <block> }]`: message and/or block
4090/// required, code optional. The trailing brace (when present and not
4091/// a `{{ }}` template) parses as a child-scope body that reads
4092/// caller locals; the remaining tokens lower as 0-2 plain args (no `KEY=VAL`). One arg
4093/// is the message unless it is a bare int literal, which is the
4094/// code (`FAIL 2` exits silently, `FAIL "2"` prints); two args are
4095/// code plus message with the code statically int-checked like
4096/// `EXIT`. `None` on shape miss (joint head, `KEY=VAL`, >2 args fall
4097/// to generic, which fails with the `FAIL` hint).
4098fn parse_fail_single(
4099    toks: &[Tok],
4100    pos: usize,
4101    stmt: usize,
4102    ctx: &ParseCtx,
4103) -> Result<Option<(StepKind, usize)>, TokenError> {
4104    let head_ok =
4105        matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FAIL);
4106    if !head_ok {
4107        return Ok(None);
4108    }
4109    let next_joint = toks.get(pos + 1).is_some_and(|t| t.joint);
4110    if next_joint {
4111        return Ok(None);
4112    }
4113    let end = toks.len();
4114    let mut arg_end = end;
4115    let mut body: Vec<Step> = Vec::new();
4116    // Brace presence is tracked apart from body length: `FAIL {}`
4117    // is a valid empty block, while a missing block leaves no
4118    // braces at all.
4119    let mut has_block = false;
4120    if let Some(last) = toks.last()
4121        && matches!(
4122            &last.kind,
4123            TokKind::Group {
4124                delim: GroupDelim::Brace,
4125                ..
4126            }
4127        )
4128        && !is_template_brace(last)
4129        && end > pos + 1
4130    {
4131        let inner = match &last.kind {
4132            TokKind::Group { inner, .. } => inner.clone(),
4133            _ => unreachable!(),
4134        };
4135        body = parse_body_steps(&inner, stmt, ctx, false)?;
4136        arg_end = end - 1;
4137        has_block = true;
4138    }
4139    let arg_toks = if arg_end > pos + 1 {
4140        &toks[pos + 1..arg_end]
4141    } else {
4142        &[]
4143    };
4144    if !arg_toks.is_empty() && arg_toks.first().is_some_and(|t| t.joint) {
4145        return Ok(None);
4146    }
4147    let (tokens, deferred) = build_arg_tokens(arg_toks, stmt, ctx)?;
4148    let mut args: Vec<Arg> = Vec::with_capacity(tokens.len());
4149    for token in tokens {
4150        match token {
4151            InsToken::Pos(arg) => args.push(arg),
4152            InsToken::Assign(..) => return Ok(None),
4153        }
4154    }
4155    if args.len() > 2 {
4156        return Ok(None);
4157    }
4158    if args.is_empty() && !has_block {
4159        return Ok(None);
4160    }
4161    if let Some(err) = deferred {
4162        return Err(err);
4163    }
4164    let (code, message) = match args.len() {
4165        0 => (None, None),
4166        1 => {
4167            let mut it = args.into_iter();
4168            let only = it.next();
4169            // A lone bare int is a silent code (`FAIL 2`); anything
4170            // else (quoted text, `$var`, templates) is the message.
4171            // Quoting decides: `FAIL "2"` prints `2` and exits 1.
4172            match &only {
4173                Some(Arg::String(s, false))
4174                    if crate::command::strip_digit_separators(s)
4175                        .parse::<i64>()
4176                        .is_ok() =>
4177                {
4178                    (only, None)
4179                }
4180                _ => (None, only),
4181            }
4182        }
4183        _ => {
4184            let mut it = args.into_iter();
4185            let code = it.next();
4186            let message = it.next();
4187            // The code position is statically int-checked like
4188            // `EXIT`: a non-int literal fails here, while `$var`
4189            // and templates defer to runtime resolution.
4190            if let Some(arg) = &code {
4191                crate::command::ArgType::Int
4192                    .check_arg(arg)
4193                    .map_err(|e| TokenError {
4194                        hint: None,
4195                        stmt,
4196                        msg: e.to_string(),
4197                        line: 0,
4198                        col: 0,
4199                        kind: Some(ParseErrorKind::Validation {
4200                            command: KEYWORD_FAIL.to_string(),
4201                        }),
4202                        diagnostic: Some(Box::new(e)),
4203                    })?;
4204            }
4205            (code, message)
4206        }
4207    };
4208    crate::commands::rewrite_isolated_inherit(&mut body);
4209    let kind = StepKind::Fail {
4210        code,
4211        message,
4212        body,
4213    };
4214    let span = lowering_ctx(stmt);
4215    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
4216    Ok(Some((kind, end - pos)))
4217}
4218
4219/// Single (non-block) `ASYNC`: one inner command or block (blocks
4220/// admit a joint brace, like `async_statement_block`'s `sep?`).
4221/// Top-level `WITH_IO` steps fail through the shared reject; the
4222/// `LET` path never scans (probed: it accepts). `None` on shape
4223/// miss (missing/joint-single inner: generic fails it).
4224fn parse_async_single(
4225    toks: &[Tok],
4226    pos: usize,
4227    stmt: usize,
4228    ctx: &ParseCtx,
4229) -> Result<Option<(StepKind, usize)>, TokenError> {
4230    let Some(next) = toks.get(pos + 1) else {
4231        return Ok(None);
4232    };
4233    // Block form admits a joint brace (`ASYNC{...}`, probed); the
4234    // single form needs its `sep`.
4235    if matches!(
4236        &next.kind,
4237        TokKind::Group {
4238            delim: GroupDelim::Brace,
4239            ..
4240        }
4241    ) && !is_template_brace(next)
4242    {
4243        let inner = match &next.kind {
4244            TokKind::Group { inner, .. } => inner.clone(),
4245            _ => unreachable!(),
4246        };
4247        let body = parse_body_steps(&inner, stmt, ctx, false)?;
4248        let span = lowering_ctx(stmt);
4249        crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| lower_err(stmt, e))?;
4250        let kind = StepKind::AsyncBlock { body };
4251        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
4252        return Ok(Some((kind, 2)));
4253    }
4254    if next.joint {
4255        return Ok(None);
4256    }
4257    let (cmd, used) = parse_single_inner(
4258        toks,
4259        pos + 1,
4260        stmt,
4261        ctx,
4262        InnerRules {
4263            allow_await: false,
4264            allow_with_io: false,
4265        },
4266    )?;
4267    let body = vec![Step {
4268        guard: None,
4269        kind: cmd,
4270        scope_enter: 0,
4271        scope_exit: 0,
4272        line: 0,
4273        col: 0,
4274    }];
4275    let span = lowering_ctx(stmt);
4276    crate::commands::reject_with_io_in_async(&span, &body).map_err(|e| lower_err(stmt, e))?;
4277    let kind = StepKind::AsyncBlock { body };
4278    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
4279    Ok(Some((kind, 1 + used)))
4280}
4281
4282// ---- Block statements, directives, REMOTE ----
4283// `IF`/`FOR`/`WHILE`/`FUNC` parse their headers token-natively with
4284// miss-to-generic fallback (the grammar's committed `instruction`
4285// path); bodies lower recursively with pushed scopes. `TYPE` builds
4286// aliases through a maximal type-shape match; `IMPORT`/`EXPORT` are
4287// zero-step frame/table directives; `REMOTE` validates targets,
4288// bindings, bodies, and outer-call containment through the shared
4289// validators. Guard blocks fold guards with scope markers at top
4290// level and mirror the nested quirk formula in bodies. A whole-script
4291// post-pass runs the shared validations (prelude order, COPY
4292// placement, EXPORT membership).
4293
4294/// Uppercase identifier mirror (`func_ident`, `type_name`,
4295/// `import_module`): ASCII upper start, upper/digit/`_` rest.
4296fn is_upper_ident(w: &str) -> bool {
4297    !w.is_empty()
4298        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
4299        && w.chars()
4300            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
4301}
4302
4303/// Lowercase identifier mirror (`field_name`): ASCII lower start,
4304/// lower/digit/`_` rest.
4305fn is_lower_ident(w: &str) -> bool {
4306    !w.is_empty()
4307        && w.chars().next().is_some_and(|c| c.is_ascii_lowercase())
4308        && w.chars()
4309            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
4310}
4311
4312/// `$name` with gapless adjacency (atomic `dollar_ident`); `None` on
4313/// shape miss (the caller falls back to generic, which fails in
4314/// lowering like the grammar's committed `instruction`).
4315fn peek_dollar_var(toks: &[Tok], pos: usize) -> Option<(String, usize)> {
4316    match (toks.get(pos), toks.get(pos + 1)) {
4317        (Some(dollar), Some(name))
4318            if matches!(&dollar.kind, TokKind::Punct(VAR_SIGIL_CHAR))
4319                && name.joint
4320                && matches!(&name.kind, TokKind::Word(w) if is_ident_word(w)) =>
4321        {
4322            match &name.kind {
4323                TokKind::Word(w) => Some((w.clone(), 2)),
4324                _ => unreachable!(),
4325            }
4326        }
4327        _ => None,
4328    }
4329}
4330
4331/// Skip statement-level newlines (multi-line `<...>` shapes ride
4332/// them into the body) before the next type token. Narrower than
4333/// `gap_nl` on purpose: comments keep failing here exactly like
4334/// single-line shapes, so only the separator moves.
4335fn skip_type_nl(toks: &[Tok], mut p: usize) -> usize {
4336    while matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Newline)) {
4337        p += 1;
4338    }
4339    p
4340}
4341
4342/// Maximal `type_tag` match over toks (non-atomic: gaps free
4343/// everywhere): atoms with `<>` args, `|` unions, `name?:` fields,
4344/// and one `= literal` default tail per field.
4345/// Returns the exclusive end index, or `None` on shape miss.
4346fn parse_type_shape(toks: &[Tok], pos: usize) -> Option<usize> {
4347    let mut p = parse_type_atom(toks, skip_type_nl(toks, pos))?;
4348    loop {
4349        let q = skip_type_nl(toks, p);
4350        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('|'))) {
4351            return Some(p);
4352        }
4353        p = parse_type_atom(toks, skip_type_nl(toks, q + 1))?;
4354    }
4355}
4356
4357fn parse_type_atom(toks: &[Tok], pos: usize) -> Option<usize> {
4358    let pos = skip_type_nl(toks, pos);
4359    match toks.get(pos).map(|t| &t.kind) {
4360        Some(TokKind::Word(w)) if is_upper_ident(w) => {}
4361        _ => return None,
4362    }
4363    let mut p = skip_type_nl(toks, pos + 1);
4364    // Qualified `ALIAS::NAME`: two colons plus a second uppercase word.
4365    // The renderer joins tokens joint-aware so the spelling keeps `::`.
4366    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')))
4367        && matches!(toks.get(p + 1).map(|t| &t.kind), Some(TokKind::Punct(':')))
4368        && matches!(toks.get(p + 2).map(|t| &t.kind), Some(TokKind::Word(w)) if is_upper_ident(w))
4369    {
4370        p = skip_type_nl(toks, p + 3);
4371    }
4372    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('<'))) {
4373        p = parse_type_args(toks, skip_type_nl(toks, p + 1))?;
4374        p = skip_type_nl(toks, p);
4375        if !matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('>'))) {
4376            return None;
4377        }
4378        p += 1;
4379    }
4380    Some(p)
4381}
4382
4383fn parse_type_args(toks: &[Tok], pos: usize) -> Option<usize> {
4384    let mut p = parse_type_field(toks, skip_type_nl(toks, pos))?;
4385    loop {
4386        let q = skip_type_nl(toks, p);
4387        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(','))) {
4388            return Some(p);
4389        }
4390        p = parse_type_field(toks, skip_type_nl(toks, q + 1))?;
4391    }
4392}
4393
4394fn parse_type_field(toks: &[Tok], pos: usize) -> Option<usize> {
4395    let mut p = skip_type_nl(toks, pos);
4396    // Optional `name?:` prefix (lowercase names only, like the
4397    // grammar's `field_name`).
4398    if let Some(TokKind::Word(w)) = toks.get(p).map(|t| &t.kind)
4399        && is_lower_ident(w)
4400    {
4401        let mut q = skip_type_nl(toks, p + 1);
4402        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('?'))) {
4403            q = skip_type_nl(toks, q + 1);
4404        }
4405        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4406            p = skip_type_nl(toks, q + 1);
4407        }
4408    }
4409    let mut p = parse_type_shape(toks, p)?;
4410    // Optional `ALIAS name` clauses (#310.5): one alternate CLI spelling
4411    // per field, but the matcher covers every consecutive clause so the
4412    // spelling parser owns arity (second ALIAS fails there naming both
4413    // names, never here as shape miss). The renderer carries raw tokens
4414    // through. Order is fixed: `TYPE [ALIAS alias]* [= default]`.
4415    loop {
4416        let q = skip_type_nl(toks, p);
4417        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Word(w)) if w == crate::tag::ALIAS_KEYWORD)
4418        {
4419            break;
4420        }
4421        p = skip_type_nl(toks, q + 1);
4422        if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Word(_))) {
4423            p = skip_type_nl(toks, p + 1);
4424        } else {
4425            break;
4426        }
4427    }
4428    // Optional `= ...` default tail: consume to the next field
4429    // delimiter (`,`, `>`, `|` at angle depth zero), tracking `<>`
4430    // so nested shapes ride along. Any spacing, any tokens:
4431    // literals, `$vars`, `env:` reads, calls. The spelling parser
4432    // owns literal validation, so non-literals fail there naming
4433    // the alias instead of missing here as unknown-command noise.
4434    let q = skip_type_nl(toks, p);
4435    if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('=')))
4436        && !matches!(toks.get(q + 1).map(|t| &t.kind), Some(TokKind::Punct('=')))
4437    {
4438        let mut r = skip_type_nl(toks, q + 1);
4439        let mut depth = 0usize;
4440        loop {
4441            match toks.get(r).map(|t| &t.kind) {
4442                Some(TokKind::Punct('<')) => {
4443                    depth += 1;
4444                    r = skip_type_nl(toks, r + 1);
4445                }
4446                Some(TokKind::Punct('>')) => {
4447                    if depth == 0 {
4448                        break;
4449                    }
4450                    depth -= 1;
4451                    r = skip_type_nl(toks, r + 1);
4452                }
4453                Some(TokKind::Punct(',' | '|')) if depth == 0 => break,
4454                Some(_) => {
4455                    r += 1;
4456                }
4457                None => break,
4458            }
4459        }
4460        p = r;
4461    }
4462    Some(p)
4463}
4464
4465/// Single (non-block) `IF`: condition plus then-block with an
4466/// opportunistic `ELSE` chain (a malformed `ELSE` stays for the
4467/// element loop, which fails it in lowering exactly like the
4468/// grammar). `None` on shape miss (missing/joint-agnostic block or
4469/// unclassified bad condition: generic fails it); classified
4470/// expression failures (unknown/ambiguous callees) and inline-block
4471/// failures propagate (blocks lower here, so their errors surface
4472/// directly).
4473fn parse_if_at(
4474    toks: &[Tok],
4475    pos: usize,
4476    stmt: usize,
4477    ctx: &ParseCtx,
4478) -> Result<Option<(StepKind, usize)>, TokenError> {
4479    // Condition entry skips leading gap comments (`IF` uses `gap`).
4480    let mut lead = Cursor::expr(&toks[pos + 1..], stmt);
4481    lead.skip_gap();
4482    let mut cur = Cursor::expr(&toks[pos + 1 + lead.pos..], stmt);
4483    let cond = match parse_expr_checked(&mut cur, ctx) {
4484        Ok(expr) => expr,
4485        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4486        // Classified failures (unknown/ambiguous callees) name the
4487        // culprit instead of missing to the generic IF hint: the head
4488        // is unambiguously `IF`, so there is no alternative parse.
4489        Err(e) if e.kind.is_some() => return Err(e),
4490        Err(_) => return Ok(None),
4491    };
4492    let cond_end = pos + 1 + lead.pos + cur.pos;
4493    // Then-block: any gap (`gap` zero-width), never a template.
4494    let then_brace = match toks.get(cond_end) {
4495        Some(t)
4496            if matches!(
4497                &t.kind,
4498                TokKind::Group {
4499                    delim: GroupDelim::Brace,
4500                    ..
4501                }
4502            ) && !is_template_brace(t) =>
4503        {
4504            t
4505        }
4506        _ => return Ok(None),
4507    };
4508    let then_inner = match &then_brace.kind {
4509        TokKind::Group { inner, .. } => inner.clone(),
4510        _ => unreachable!(),
4511    };
4512    let then_body = parse_body_steps(&then_inner, stmt, ctx, false)?;
4513    let mut p = cond_end + 1;
4514    // Gap comments between the blocks and `ELSE` vanish (merge
4515    // junctions contribute newlines, crossed like `blank*`).
4516    {
4517        let mut gcur = Cursor::expr(&toks[p..], stmt);
4518        gcur.skip_gap_nl();
4519        p += gcur.pos;
4520    }
4521    let mut else_ifs = Vec::new();
4522    let mut else_body = None;
4523    loop {
4524        // `ELSE IF cond block`: any gaps (non-atomic chain).
4525        let is_else_if = matches!(
4526            toks.get(p).map(|t| &t.kind),
4527            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4528        ) && matches!(
4529            toks.get(p + 1).map(|t| &t.kind),
4530            Some(TokKind::Word(w)) if w == KEYWORD_IF
4531        );
4532        if is_else_if {
4533            let mut ecur = Cursor::expr(&toks[p + 2..], stmt);
4534            ecur.skip_gap();
4535            let econd = match parse_expr_checked(&mut ecur, ctx) {
4536                Ok(expr) => expr,
4537                Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4538                // Same classified-error rule as the `IF` head above:
4539                // an `ELSE IF` with a resolvable-but-unknown callee
4540                // names it instead of silently dropping the branch.
4541                Err(e) if e.kind.is_some() => return Err(e),
4542                Err(_) => break,
4543            };
4544            let ebrace = p + 2 + ecur.pos;
4545            let eblock_ok = matches!(
4546                toks.get(ebrace).map(|t| &t.kind),
4547                Some(TokKind::Group {
4548                    delim: GroupDelim::Brace,
4549                    ..
4550                })
4551            ) && toks.get(ebrace).is_some_and(|t| !is_template_brace(t));
4552            if !eblock_ok {
4553                break;
4554            }
4555            let einner = match &toks[ebrace].kind {
4556                TokKind::Group { inner, .. } => inner.clone(),
4557                _ => unreachable!(),
4558            };
4559            let ebody = parse_body_steps(&einner, stmt, ctx, false)?;
4560            else_ifs.push((Box::new(econd), ebody));
4561            p = ebrace + 1;
4562            // Gap comments before a further `ELSE` vanish too
4563            // (merge junctions contribute newlines).
4564            {
4565                let mut gcur = Cursor::expr(&toks[p..], stmt);
4566                gcur.skip_gap_nl();
4567                p += gcur.pos;
4568            }
4569            continue;
4570        }
4571        // `ELSE block`: same opportunism (a bare `ELSE` stays for
4572        // the loop, failing in lowering like the grammar).
4573        let is_else = matches!(
4574            toks.get(p).map(|t| &t.kind),
4575            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4576        ) && matches!(
4577            toks.get(p + 1).map(|t| &t.kind),
4578            Some(TokKind::Group {
4579                delim: GroupDelim::Brace,
4580                ..
4581            })
4582        ) && toks.get(p + 1).is_some_and(|t| !is_template_brace(t));
4583        if !is_else {
4584            break;
4585        }
4586        let einner = match &toks[p + 1].kind {
4587            TokKind::Group { inner, .. } => inner.clone(),
4588            _ => unreachable!(),
4589        };
4590        else_body = Some(parse_body_steps(&einner, stmt, ctx, false)?);
4591        p += 2;
4592        break;
4593    }
4594    let kind = StepKind::If {
4595        cond: Box::new(cond),
4596        then_body,
4597        else_ifs,
4598        else_body,
4599    };
4600    Ok(Some((kind, p - pos)))
4601}
4602
4603/// Parse one `CASE` value list: comma-separated expressions up to (not
4604/// including) the arm body brace. Groups are atomic tokens, so commas
4605/// inside calls, lists, and maps never split. Returns the values plus
4606/// the token count consumed past the `CASE` word.
4607fn parse_case_values(
4608    toks: &[Tok],
4609    stmt: usize,
4610    ctx: &ParseCtx,
4611) -> Result<(Vec<Expr>, usize), TokenError> {
4612    let mut values = Vec::new();
4613    let mut p = 0;
4614    loop {
4615        let mut gcur = Cursor::expr(&toks[p..], stmt);
4616        gcur.skip_gap_nl();
4617        let start = p + gcur.pos;
4618        let mut vcur = Cursor::expr(&toks[start..], stmt);
4619        let value = match parse_expr_checked(&mut vcur, ctx) {
4620            Ok(expr) => expr,
4621            Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4622            Err(e) => return Err(e),
4623        };
4624        // A `{ ... }` block is never a case value: without this, a
4625        // missing `CASE` value consumes the arm body as a block
4626        // expression and fails downstream instead of naming the miss.
4627        if matches!(value, Expr::Block(_)) {
4628            return Err(TokenError {
4629                diagnostic: None,
4630                hint: None,
4631                stmt,
4632                line: 0,
4633                col: 0,
4634                msg: format!(
4635                    "{KEYWORD_SWITCH} {KEYWORD_CASE} requires a value or condition before '{{'"
4636                ),
4637                kind: None,
4638            });
4639        }
4640        values.push(value);
4641        p = start + vcur.pos;
4642        let mut gcur = Cursor::expr(&toks[p..], stmt);
4643        gcur.skip_gap_nl();
4644        p += gcur.pos;
4645        if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(','))) {
4646            p += 1;
4647            continue;
4648        }
4649        break;
4650    }
4651    Ok((values, p))
4652}
4653
4654/// Parsed `SWITCH` arms: one value list plus body per `CASE`, with
4655/// an optional trailing `DEFAULT` body.
4656type SwitchArms = (Vec<(Vec<Expr>, Vec<Step>)>, Option<Vec<Step>>);
4657
4658/// Parse the arms inside a `SWITCH` body brace: `CASE <values> { ... }`
4659/// arms plus an optional trailing `DEFAULT { ... }`. Hard errors once
4660/// committed (the `SWITCH` head is unambiguous): unknown words, empty
4661/// bodies, missing blocks, duplicate or non-trailing `DEFAULT`.
4662fn parse_switch_body(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<SwitchArms, TokenError> {
4663    let err = |msg: String| TokenError {
4664        diagnostic: None,
4665        hint: None,
4666        stmt,
4667        line: 0,
4668        col: 0,
4669        msg,
4670        kind: None,
4671    };
4672    let mut cases: Vec<(Vec<Expr>, Vec<Step>)> = Vec::new();
4673    let mut default_body: Option<Vec<Step>> = None;
4674    let mut p = 0;
4675    loop {
4676        let mut gcur = Cursor::expr(&inner[p..], stmt);
4677        gcur.skip_gap_nl();
4678        p += gcur.pos;
4679        if p >= inner.len() {
4680            break;
4681        }
4682        let word = match &inner[p].kind {
4683            TokKind::Word(w) => w.clone(),
4684            _ => {
4685                return Err(err(format!(
4686                    "{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 }} }}`"
4687                )));
4688            }
4689        };
4690        if word == KEYWORD_CASE {
4691            if default_body.is_some() {
4692                return Err(err(format!(
4693                    "{KEYWORD_SWITCH} {KEYWORD_DEFAULT} must be the last arm; no {KEYWORD_CASE} may follow it"
4694                )));
4695            }
4696            let (values, used) = parse_case_values(&inner[p + 1..], stmt, ctx)?;
4697            p += 1 + used;
4698            let mut bcur = Cursor::expr(&inner[p..], stmt);
4699            bcur.skip_gap_nl();
4700            p += bcur.pos;
4701            let arm_ok = matches!(
4702                inner.get(p).map(|t| &t.kind),
4703                Some(TokKind::Group {
4704                    delim: GroupDelim::Brace,
4705                    ..
4706                })
4707            ) && inner.get(p).is_some_and(|t| !is_template_brace(t));
4708            if !arm_ok {
4709                return Err(err(
4710                    "SWITCH CASE needs a braced block, e.g. `CASE \"a\", \"b\" { ECHO yes }`"
4711                        .to_string(),
4712                ));
4713            }
4714            let arm_inner = match &inner[p].kind {
4715                TokKind::Group { inner, .. } => inner.clone(),
4716                _ => unreachable!(),
4717            };
4718            let body = parse_body_steps(&arm_inner, stmt, ctx, false)?;
4719            cases.push((values, body));
4720            p += 1;
4721        } else if word == KEYWORD_DEFAULT {
4722            if default_body.is_some() {
4723                return Err(err(format!(
4724                    "{KEYWORD_SWITCH} allows only one {KEYWORD_DEFAULT} arm"
4725                )));
4726            }
4727            p += 1;
4728            let mut bcur = Cursor::expr(&inner[p..], stmt);
4729            bcur.skip_gap_nl();
4730            p += bcur.pos;
4731            let arm_ok = matches!(
4732                inner.get(p).map(|t| &t.kind),
4733                Some(TokKind::Group {
4734                    delim: GroupDelim::Brace,
4735                    ..
4736                })
4737            ) && inner.get(p).is_some_and(|t| !is_template_brace(t));
4738            if !arm_ok {
4739                return Err(err(
4740                    "SWITCH DEFAULT needs a braced block, e.g. `DEFAULT { ECHO fallback }`"
4741                        .to_string(),
4742                ));
4743            }
4744            let arm_inner = match &inner[p].kind {
4745                TokKind::Group { inner, .. } => inner.clone(),
4746                _ => unreachable!(),
4747            };
4748            default_body = Some(parse_body_steps(&arm_inner, stmt, ctx, false)?);
4749            p += 1;
4750        } else {
4751            return Err(err(format!(
4752                "{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 }} }}`"
4753            )));
4754        }
4755    }
4756    if cases.is_empty() && default_body.is_none() {
4757        return Err(err(format!(
4758            "{KEYWORD_SWITCH} needs at least one {KEYWORD_CASE} or {KEYWORD_DEFAULT} arm"
4759        )));
4760    }
4761    Ok((cases, default_body))
4762}
4763
4764/// `SWITCH [disc] { CASE v, ... { ... } ... [DEFAULT { ... }] }` or
4765/// bare `SWITCH { CASE <bool> { ... } ... }`. `None` on shape miss (no
4766/// outer brace: falls to generic, which fails it with the SWITCH hint);
4767/// classified expression failures propagate like `IF`, and arm errors
4768/// are hard (the head commits the shape).
4769fn parse_switch_at(
4770    toks: &[Tok],
4771    pos: usize,
4772    stmt: usize,
4773    ctx: &ParseCtx,
4774) -> Result<Option<(StepKind, usize)>, TokenError> {
4775    // Bare head: gaps skipped like the discriminant entry below; the
4776    // token then opens the body brace, so no discriminant is parsed
4777    // (every `CASE` carries its own condition).
4778    let mut gap = Cursor::expr(&toks[pos + 1..], stmt);
4779    gap.skip_gap();
4780    let brace_pos = pos + 1 + gap.pos;
4781    let bare_head = matches!(
4782        toks.get(brace_pos).map(|t| &t.kind),
4783        Some(TokKind::Group {
4784            delim: GroupDelim::Brace,
4785            ..
4786        })
4787    ) && toks.get(brace_pos).is_some_and(|t| !is_template_brace(t));
4788    let p: usize;
4789    let discriminant = if bare_head {
4790        p = brace_pos;
4791        None
4792    } else {
4793        // Discriminant entry reuses the skipped gaps above (`IF` uses
4794        // the same gap rule).
4795        let mut cur = Cursor::expr(&toks[brace_pos..], stmt);
4796        let disc = match parse_expr_checked(&mut cur, ctx) {
4797            Ok(expr) => expr,
4798            Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4799            // Same classified-error rule as the `IF` head above: the
4800            // head is unambiguous, so resolvable-but-unknown callees
4801            // name the culprit instead of the generic hint.
4802            Err(e) if e.kind.is_some() => return Err(e),
4803            Err(_) => return Ok(None),
4804        };
4805        p = brace_pos + cur.pos;
4806        Some(Box::new(disc))
4807    };
4808    let body_ok = matches!(
4809        toks.get(p).map(|t| &t.kind),
4810        Some(TokKind::Group {
4811            delim: GroupDelim::Brace,
4812            ..
4813        })
4814    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4815    if !body_ok {
4816        return Ok(None);
4817    }
4818    let inner = match &toks[p].kind {
4819        TokKind::Group { inner, .. } => inner.clone(),
4820        _ => unreachable!(),
4821    };
4822    let (cases, default_body) = parse_switch_body(&inner, stmt, ctx)?;
4823    let kind = StepKind::Switch {
4824        discriminant,
4825        cases,
4826        default_body,
4827    };
4828    Ok(Some((kind, p + 1 - pos)))
4829}
4830
4831/// Single (non-block) `FOR`: `$var[: TYPE] (, $var[: TYPE])? IN
4832/// expr` plus block. Header shapes miss to generic (a third variable,
4833/// a missing block, a bad name all fail in lowering like the
4834/// grammar); completed headers validate counts and key types loudly.
4835/// Expression failures from inline blocks propagate (blocks lower
4836/// here); other expression failures miss (generic fails them like a
4837/// committed `instruction` would).
4838fn parse_for_at(
4839    toks: &[Tok],
4840    pos: usize,
4841    stmt: usize,
4842    ctx: &ParseCtx,
4843) -> Result<Option<(StepKind, usize)>, TokenError> {
4844    let mut p = pos + 1;
4845    let mut idents = Vec::new();
4846    let mut types = Vec::new();
4847    // First `$var[: TYPE]` (gapless `$var`; gaps free elsewhere).
4848    let Some((var1, _)) = peek_dollar_var(toks, p) else {
4849        return Ok(None);
4850    };
4851    idents.push(var1);
4852    p += 2;
4853    let mut cur = Cursor::expr(&toks[p..], stmt);
4854    cur.skip_gap();
4855    p += cur.pos;
4856    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4857        p += 1;
4858        let mut tcur = Cursor::expr(&toks[p..], stmt);
4859        tcur.skip_gap();
4860        let tstart = p + tcur.pos;
4861        let Some(tend) = parse_type_shape(toks, tstart) else {
4862            return Ok(None);
4863        };
4864        // `render_type_region` canonicalizes (shared spelling).
4865        types.push(render_type_region(&toks[tstart..tend], stmt)?);
4866        p = tend;
4867    }
4868    // Optional `, $var2[: TYPE2]`.
4869    {
4870        let mut ccur = Cursor::expr(&toks[p..], stmt);
4871        ccur.skip_gap();
4872        if matches!(
4873            ccur.toks.get(ccur.pos).map(|t| &t.kind),
4874            Some(TokKind::Punct(','))
4875        ) {
4876            ccur.pos += 1;
4877            ccur.skip_gap();
4878            let base = p + ccur.pos;
4879            let Some((var2, _)) = peek_dollar_var(toks, base) else {
4880                return Ok(None);
4881            };
4882            idents.push(var2);
4883            let mut q = base + 2;
4884            let mut qcur = Cursor::expr(&toks[q..], stmt);
4885            qcur.skip_gap();
4886            q += qcur.pos;
4887            if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4888                q += 1;
4889                let mut tcur = Cursor::expr(&toks[q..], stmt);
4890                tcur.skip_gap();
4891                let tstart = q + tcur.pos;
4892                let Some(tend) = parse_type_shape(toks, tstart) else {
4893                    return Ok(None);
4894                };
4895                types.push(render_type_region(&toks[tstart..tend], stmt)?);
4896                q = tend;
4897            }
4898            p = q;
4899        }
4900    }
4901    // `IN expr block`.
4902    {
4903        let mut icur = Cursor::expr(&toks[p..], stmt);
4904        icur.skip_gap();
4905        if !matches!(
4906            icur.toks.get(icur.pos).map(|t| &t.kind),
4907            Some(TokKind::Word(w)) if w == KEYWORD_IN
4908        ) {
4909            return Ok(None);
4910        }
4911        icur.pos += 1;
4912        p += icur.pos;
4913    }
4914    let mut ecur = Cursor::expr(&toks[p..], stmt);
4915    ecur.skip_gap();
4916    let in_expr = match parse_expr_checked(&mut ecur, ctx) {
4917        Ok(expr) => expr,
4918        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4919        // Classified failures name the callee: `FOR ... IN` is
4920        // committed once the header matched this far.
4921        Err(e) if e.kind.is_some() => return Err(e),
4922        Err(_) => return Ok(None),
4923    };
4924    p += ecur.pos;
4925    let block_ok = matches!(
4926        toks.get(p).map(|t| &t.kind),
4927        Some(TokKind::Group {
4928            delim: GroupDelim::Brace,
4929            ..
4930        })
4931    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4932    if !block_ok {
4933        return Ok(None);
4934    }
4935    let inner = match &toks[p].kind {
4936        TokKind::Group { inner, .. } => inner.clone(),
4937        _ => unreachable!(),
4938    };
4939    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4940    p += 1;
4941    if idents.len() != types.len() {
4942        return Err(TokenError {
4943            diagnostic: None,
4944            hint: None,
4945            stmt,
4946            msg: format!(
4947                "FOR requires explicit types: FOR $item: TYPE IN <expr> (got {} vars, {} types)",
4948                idents.len(),
4949                types.len()
4950            ),
4951            line: 0,
4952            col: 0,
4953            kind: Some(ParseErrorKind::Validation {
4954                command: KEYWORD_FOR.to_string(),
4955            }),
4956        });
4957    }
4958    let (key_var, key_type, var, var_type) = match idents.len() {
4959        1 => (
4960            None,
4961            None,
4962            idents.into_iter().next().unwrap_or_default(),
4963            types.into_iter().next().unwrap_or_default(),
4964        ),
4965        2 => {
4966            let mut iv = idents.into_iter();
4967            let mut tv = types.into_iter();
4968            (
4969                Some(iv.next().unwrap_or_default()),
4970                Some(tv.next().unwrap_or_default()),
4971                iv.next().unwrap_or_default(),
4972                tv.next().unwrap_or_default(),
4973            )
4974        }
4975        _ => {
4976            return Err(TokenError {
4977                diagnostic: None,
4978                hint: None,
4979                stmt,
4980                msg: format!("{KEYWORD_FOR} requires one or two variables"),
4981                line: 0,
4982                col: 0,
4983                kind: Some(ParseErrorKind::Validation {
4984                    command: KEYWORD_FOR.to_string(),
4985                }),
4986            });
4987        }
4988    };
4989    if let Some(kt) = &key_type
4990        && kt != crate::TypeTag::String.name()
4991        && kt != crate::TypeTag::Int.name()
4992    {
4993        return Err(TokenError {
4994            diagnostic: None,
4995            hint: None,
4996            stmt,
4997            msg: format!(
4998                "{KEYWORD_FOR} key variable must be {INT_TYPE_NAME} or {STRING_TYPE_NAME}, got {kt}"
4999            ),
5000            line: 0,
5001            col: 0,
5002            kind: Some(ParseErrorKind::Validation {
5003                command: KEYWORD_FOR.to_string(),
5004            }),
5005        });
5006    }
5007    let kind = StepKind::For {
5008        key_var,
5009        key_type,
5010        var,
5011        var_type,
5012        in_expr,
5013        body,
5014    };
5015    Ok(Some((kind, p - pos)))
5016}
5017
5018/// Single (non-block) `WHILE`: condition plus block. `None` on
5019/// shape miss (missing block: generic fails it); classified
5020/// expression failures and inline-block failures propagate, other
5021/// expression failures miss (generic fails them like a committed
5022/// `instruction` would).
5023/// No leading gap-skip: `WHILE` takes `sep`, so a joint follower
5024/// never reaches here with a valid shape... (misses fall through
5025/// the same way regardless).
5026fn parse_while_single(
5027    toks: &[Tok],
5028    pos: usize,
5029    stmt: usize,
5030    ctx: &ParseCtx,
5031) -> Result<Option<(StepKind, usize)>, TokenError> {
5032    let mut cur = Cursor::expr(&toks[pos + 1..], stmt);
5033    let cond = match parse_expr_checked(&mut cur, ctx) {
5034        Ok(expr) => expr,
5035        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
5036        // Same rule as `IF`: the head is unambiguous, so classified
5037        // failures name the culprit instead of the generic hint.
5038        Err(e) if e.kind.is_some() => return Err(e),
5039        Err(_) => return Ok(None),
5040    };
5041    let brace = pos + 1 + cur.pos;
5042    let block_ok = matches!(
5043        toks.get(brace).map(|t| &t.kind),
5044        Some(TokKind::Group {
5045            delim: GroupDelim::Brace,
5046            ..
5047        })
5048    ) && toks.get(brace).is_some_and(|t| !is_template_brace(t));
5049    if !block_ok {
5050        return Ok(None);
5051    }
5052    let inner = match &toks[brace].kind {
5053        TokKind::Group { inner, .. } => inner.clone(),
5054        _ => unreachable!(),
5055    };
5056    let body = parse_body_steps(&inner, stmt, ctx, false)?;
5057    let kind = StepKind::While {
5058        cond: Box::new(cond),
5059        body,
5060    };
5061    Ok(Some((kind, brace + 1 - pos)))
5062}
5063
5064/// Validated `FUNC` header shape: name, parameter list, return type,
5065/// and body block. Single owner for the header grammar, shared by
5066/// `parse_func_at` and `predeclare_forward_funcs` so the hoist set can
5067/// never admit what the real path rejects (or reject what it admits).
5068/// Returns the header plus tokens consumed; `None` on shape miss
5069/// (lowercase names, missing paren/colon/block all miss to generic,
5070/// probed). Content failures (bad params, missing return type, bad
5071/// trailing tokens) carry the bare diagnostic: `parse_func_at`
5072/// adorns it, pre-declaration drops it (silent skip, letting the main
5073/// pass own the error).
5074struct FuncHeader {
5075    name: String,
5076    params: Vec<(String, String, bool)>,
5077    return_type: String,
5078    block: usize,
5079}
5080
5081#[allow(clippy::too_many_lines)]
5082fn parse_func_header(
5083    toks: &[Tok],
5084    pos: usize,
5085    stmt: usize,
5086    keyword: &str,
5087) -> Result<Option<(FuncHeader, usize)>, String> {
5088    // Head word: `FUNC` (callers normalize `ASYNC FUNC` to `pos`
5089    // first, so the header shape stays prefix-free).
5090    if !matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC) {
5091        return Ok(None);
5092    }
5093    // Name: UPPERCASE ident (lowercase misses to generic, probed).
5094    let def_name = match toks.get(pos + 1).map(|t| &t.kind) {
5095        Some(TokKind::Word(w))
5096            if crate::resolve::check_func_ident(&lowering_ctx(stmt), w).is_ok() =>
5097        {
5098            w.clone()
5099        }
5100        _ => return Ok(None),
5101    };
5102    // Paren group at any gap (`gap` zero-width): params live inside
5103    // its inner tokens, parsed with `gap_nl` discipline (newlines ride
5104    // free like call args and generics, via the shared helper).
5105    let mut p = pos + 2;
5106    let paren_inner = match toks.get(p).map(|t| &t.kind) {
5107        Some(TokKind::Group {
5108            delim: GroupDelim::Paren,
5109            inner,
5110            ..
5111        }) => inner.clone(),
5112        _ => return Ok(None),
5113    };
5114    p += 1;
5115    let mut params = Vec::new();
5116    let mut seen_optional = false;
5117    {
5118        let mut pcur = Cursor::expr(&paren_inner, stmt);
5119        pcur.skip_gap_nl();
5120        if !pcur.done() {
5121            loop {
5122                let base = pcur.pos;
5123                let Some((pname, _)) = peek_dollar_var(&paren_inner, base) else {
5124                    return Err(format!(
5125                        "FUNC {def_name} params must be `$name: TYPE` separated by commas"
5126                    ));
5127                };
5128                pcur.pos = base + 2;
5129                pcur.skip_gap_nl();
5130                // Optional params carry `?` before the colon
5131                // (`$flag?: BOOL`); all params are otherwise required.
5132                let optional = pcur.eat_punct('?');
5133                pcur.skip_gap_nl();
5134                if !pcur.eat_punct(':') {
5135                    return Err(format!(
5136                        "FUNC {def_name} param `${pname}` needs `: TYPE` after the name"
5137                    ));
5138                }
5139                pcur.skip_gap_nl();
5140                let tstart = pcur.pos;
5141                let Some(tend) = parse_type_shape(&paren_inner, tstart) else {
5142                    let got = match paren_inner.get(tstart).map(|tok| &tok.kind) {
5143                        Some(TokKind::Word(word)) => format!("; got `{word}`"),
5144                        _ => String::new(),
5145                    };
5146                    return Err(format!(
5147                        "FUNC {def_name} param `${pname}` needs an uppercase type after `:` (e.g. STRING, INT, BOOL){got}"
5148                    ));
5149                };
5150                // Post-match the span holds words/puncts only, so the
5151                // shared renderer cannot fail; stay failed regardless.
5152                let ptype =
5153                    render_type_region(&paren_inner[tstart..tend], stmt).unwrap_or_default();
5154                if optional {
5155                    seen_optional = true;
5156                } else if seen_optional {
5157                    return Err(format!(
5158                        "FUNC {def_name} optional ? params must be trailing: `${pname}` follows an optional param"
5159                    ));
5160                }
5161                params.push((pname, ptype, optional));
5162                pcur.pos = tend;
5163                pcur.skip_gap_nl();
5164                if pcur.eat_punct(',') {
5165                    pcur.skip_gap_nl();
5166                    // Trailing comma misses (a param must follow).
5167                    if pcur.done() {
5168                        return Err(format!(
5169                            "FUNC {def_name} params must not end with a trailing comma"
5170                        ));
5171                    }
5172                    continue;
5173                }
5174                break;
5175            }
5176            // Trailing junk (including newlines) misses to generic.
5177            pcur.skip_gap_nl();
5178            if !pcur.done() {
5179                return Err(format!(
5180                    "FUNC {def_name} params must be `$name: TYPE` separated by commas"
5181                ));
5182            }
5183        }
5184    }
5185    // Mandatory return annotation: FUNC NAME(...): RET { ... }.
5186    // After paren group, require gap-optional colon then type shape.
5187    // Missing colon after matched name+parens is a hard parse error
5188    // (no legacy fallback). Non-block tails (neither colon nor brace)
5189    // miss to generic (probed FUNC FOO() ECHO hi).
5190    let is_colon = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')));
5191    if !is_colon {
5192        let is_brace = matches!(
5193            toks.get(p).map(|t| &t.kind),
5194            Some(TokKind::Group {
5195                delim: GroupDelim::Brace,
5196                ..
5197            })
5198        ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
5199        if is_brace {
5200            return Err(format!(
5201                "{keyword} {def_name} requires a return type : TYPE (e.g. : VOID, : STRING)"
5202            ));
5203        }
5204        return Ok(None);
5205    }
5206    let Some(ret_end) = parse_type_shape(toks, p + 1) else {
5207        return Err(format!(
5208            "{keyword} {def_name} requires a return type : TYPE after ':'"
5209        ));
5210    };
5211    let return_type = render_type_region(&toks[p + 1..ret_end], stmt).map_err(|_| {
5212        format!("{keyword} {def_name} requires a return type : {KEYWORD_TYPE} after ':'")
5213    })?;
5214    let return_type = crate::canonicalize_spelling(&return_type);
5215    p = ret_end;
5216    // Block at any gap (never a template); missing blocks miss to
5217    // generic (probed FUNC FOO() ECHO hi).
5218    let block_ok = matches!(
5219        toks.get(p).map(|t| &t.kind),
5220        Some(TokKind::Group {
5221            delim: GroupDelim::Brace,
5222            ..
5223        })
5224    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
5225    if !block_ok {
5226        return Ok(None);
5227    }
5228    Ok(Some((
5229        FuncHeader {
5230            name: def_name,
5231            params,
5232            return_type,
5233            block: p,
5234        },
5235        p + 1 - pos,
5236    )))
5237}
5238
5239/// Single (non-block) `FUNC`: name, parenthesized params, block. The
5240/// shape parses purely first (misses fall to generic, declaring
5241/// nothing — the grammar only lowers matched pairs); then the name
5242/// declares in the enclosing scope before the body lowers (so
5243/// recursion resolves), and the body pushes a fresh scope.
5244/// Duplicates, reserved shadows, and parameter dupes fail loudly.
5245fn parse_func_at(
5246    toks: &[Tok],
5247    pos: usize,
5248    stmt: usize,
5249    ctx: &ParseCtx,
5250    is_async: bool,
5251) -> Result<Option<(StepKind, usize)>, TokenError> {
5252    let keyword = if is_async { "ASYNC FUNC" } else { KEYWORD_FUNC };
5253    let fail = |msg: String| TokenError {
5254        diagnostic: None,
5255        hint: None,
5256        stmt,
5257        msg,
5258        line: 0,
5259        col: 0,
5260        kind: Some(ParseErrorKind::Validation {
5261            command: KEYWORD_FUNC.to_string(),
5262        }),
5263    };
5264    // Phase 1 (pure shape) through the single header owner:
5265    // adorn content errors with the `FUNC` / `ASYNC FUNC` keyword,
5266    // miss to generic on shape miss exactly as before.
5267    let Some((header, used)) = parse_func_header(toks, pos, stmt, keyword).map_err(fail)? else {
5268        return Ok(None);
5269    };
5270    let FuncHeader {
5271        name: def_name,
5272        params,
5273        return_type,
5274        block: p,
5275    } = header;
5276    // Phase 2 (effects): reserved shadows and same-scope duplicates
5277    // fail at the definition line, verbatim.
5278    if ctx.reserved.contains(&def_name) || ctx.modules.reserved_base_names().contains(&def_name) {
5279        return Err(fail(format!(
5280            "FUNC {def_name} cannot shadow reserved function `{def_name}`"
5281        )));
5282    }
5283    if !ctx.declare_func(&def_name) {
5284        return Err(fail(format!(
5285            "duplicate function `{def_name}` in same scope"
5286        )));
5287    }
5288    let mut seen = HashSet::new();
5289    for (pname, _, _) in &params {
5290        if !seen.insert(pname.clone()) {
5291            return Err(fail(format!(
5292                "FUNC {def_name} declares duplicate parameter ${pname}"
5293            )));
5294        }
5295    }
5296    let inner = match &toks[p].kind {
5297        TokKind::Group { inner, .. } => inner.clone(),
5298        _ => unreachable!(),
5299    };
5300    let body = parse_body_steps(&inner, stmt, ctx, false)?;
5301    let kind = StepKind::FuncDef {
5302        name: def_name,
5303        params,
5304        return_type,
5305        is_async,
5306        body,
5307        docs: None,
5308    };
5309    Ok(Some((kind, used)))
5310}
5311
5312/// `REMOTE` header bindings `[$var, env:KEY]` over a bracket
5313/// group's inner tokens: comma-separated, newlines and comments free
5314/// like `gap_nl`. `$`+name and `env`+`:`+key all ride gapless (the
5315/// enclosing rule is compound-atomic). Empty lists parse (probed);
5316/// anything else misses the shape (`None`: generic fails it like
5317/// the grammar's dropped optional).
5318#[allow(clippy::type_complexity)]
5319fn parse_remote_bindings(
5320    inner: &[Tok],
5321    stmt: usize,
5322    _ctx: &ParseCtx,
5323) -> Result<Option<(Vec<String>, Vec<String>)>, TokenError> {
5324    let _ = stmt;
5325    let mut parts: Vec<&[Tok]> = Vec::new();
5326    let mut start = 0;
5327    for (i, tok) in inner.iter().enumerate() {
5328        if matches!(&tok.kind, TokKind::Punct(',')) {
5329            parts.push(&inner[start..i]);
5330            start = i + 1;
5331        }
5332    }
5333    parts.push(&inner[start..]);
5334    // An empty list (`[]`, whitespace/comment-only) holds no bindings.
5335    if parts.len() == 1
5336        && parts[0]
5337            .iter()
5338            .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
5339    {
5340        return Ok(Some((Vec::new(), Vec::new())));
5341    }
5342    let mut vars = Vec::new();
5343    let mut env = Vec::new();
5344    for part in parts {
5345        // Edges admit gaps, newlines, and comments, like `gap_nl`.
5346        let mut part = part;
5347        while matches!(
5348            part.first().map(|t| &t.kind),
5349            Some(TokKind::Newline | TokKind::Comment(_))
5350        ) {
5351            part = &part[1..];
5352        }
5353        while matches!(
5354            part.last().map(|t| &t.kind),
5355            Some(TokKind::Newline | TokKind::Comment(_))
5356        ) {
5357            part = &part[..part.len() - 1];
5358        }
5359        // `$var` entries only: bare words are literal text, never
5360        // bindings.
5361        if matches!(
5362            part.first().map(|t| &t.kind),
5363            Some(TokKind::Punct(VAR_SIGIL_CHAR))
5364        ) && part.len() == 2
5365        {
5366            if part[1].joint
5367                && let TokKind::Word(w) = &part[1].kind
5368                && is_ident_word(w)
5369            {
5370                vars.push(w.clone());
5371                continue;
5372            }
5373            return Ok(None);
5374        }
5375        // `env:KEY`: gapless triple with an uppercase key.
5376        if part.len() == 3
5377            && matches!(&part[0].kind, TokKind::Word(w) if w == "env")
5378            && matches!(&part[1].kind, TokKind::Punct(':'))
5379            && part[1].joint
5380            && part[2].joint
5381        {
5382            if let TokKind::Word(k) = &part[2].kind
5383                && is_env_key(k)
5384            {
5385                env.push(k.clone());
5386                continue;
5387            }
5388            return Ok(None);
5389        }
5390        return Ok(None);
5391    }
5392    Ok(Some((vars, env)))
5393}
5394
5395/// `IMPORT` statement at `pos` (#115): module form (`IMPORT MOD`,
5396/// `IMPORT [A, B]`), file form (`IMPORT "p" AS A`,
5397/// `IMPORT ["p" AS A]`), mixed/multi forms
5398/// (`IMPORT [STD, "p" AS A, "q" AS B]`, multi-line included), and
5399/// selective harvests (`IMPORT [[F, G FROM "p" (AS A)?]]`).
5400/// Returns module names plus `ImportFile`/`ImportFuncs` steps in source
5401/// order, plus tokens consumed (relative to `pos`), or `None` on shape
5402/// miss (generic lowering fails it like the grammar). Validation is
5403/// hard: unknown modules, bad names, collisions, templates, and remote
5404/// URLs fail here, and validated entries register immediately
5405/// (modules, aliases, and bare harvest names share the innermost
5406/// frames).
5407type ImportEntries = (Vec<String>, Vec<StepKind>);
5408
5409fn parse_import_statement(
5410    toks: &[Tok],
5411    pos: usize,
5412    stmt: usize,
5413    ctx: &ParseCtx,
5414    guarded: bool,
5415) -> Result<Option<(ImportEntries, usize)>, TokenError> {
5416    let fail = |msg: String| TokenError {
5417        diagnostic: None,
5418        hint: None,
5419        stmt,
5420        msg,
5421        line: 0,
5422        col: 0,
5423        kind: Some(ParseErrorKind::Validation {
5424            command: KEYWORD_IMPORT.to_string(),
5425        }),
5426    };
5427    let next = match toks.get(pos + 1) {
5428        // `sep` after `IMPORT`: joint followers miss.
5429        Some(t) if !t.joint => t,
5430        _ => return Ok(None),
5431    };
5432    // Parse entries first, validate in source order after.
5433    enum RawEntry {
5434        Module(String),
5435        File {
5436            path: String,
5437            alias: String,
5438        },
5439        From {
5440            func_names: Vec<String>,
5441            type_names: Vec<String>,
5442            path: String,
5443            alias: Option<String>,
5444        },
5445    }
5446    let mut raw: Vec<RawEntry> = Vec::new();
5447    let used;
5448    if matches!(
5449        &next.kind,
5450        TokKind::Group {
5451            delim: GroupDelim::Brace,
5452            ..
5453        }
5454    ) {
5455        return Ok(None);
5456    }
5457    if let TokKind::Group {
5458        delim: GroupDelim::Bracket,
5459        inner,
5460        ..
5461    } = &next.kind
5462    {
5463        // Comma-separated entries, `ws` gaps (newlines ok inside and
5464        // around entries, comments MISS — `ws` admits neither).
5465        // Single-file multi-name harvests skip the split: in
5466        // `[TYPE A, TYPE B FROM "f"]` the first comma-part (`[TYPE A]`)
5467        // carries no FROM and is invalid alone, so the whole bracket
5468        // is one harvest (see `whole_file_harvest`).
5469        // Bare-multi hint: `[FOO, BAR FROM "f"]` reads FOO as a
5470        // module for back-compat (bare words stay modules in single
5471        // brackets). If that word is not a known module but a harvest
5472        // follows, fail fast naming the two valid spellings instead
5473        // of the misleading unknown-module error.
5474        if let Some(comment) = find_bracket_comment(inner) {
5475            let mut err = lower_err(
5476                stmt,
5477                ParseError::from_diagnostic(
5478                    ParseErrorKind::InvalidSyntax {
5479                        command: KEYWORD_IMPORT.to_string(),
5480                    },
5481                    dsl_diag::spelling_bracket_list_comment(KEYWORD_IMPORT),
5482                    &lowering_ctx(stmt),
5483                ),
5484            );
5485            err.line = comment.line;
5486            err.col = comment.col;
5487            return Err(err);
5488        }
5489        let whole = whole_file_harvest(inner);
5490        if whole.is_none()
5491            && let Some(word) = single_bare_first_part(inner)
5492            && !ctx.modules.modules.contains_key(word)
5493            && has_top_level_from_after_comma(inner)
5494        {
5495            return Err(fail(format!(
5496                "unknown module `{word}`; to harvest multiple names qualify each kind (`IMPORT [FUNC FOO, FUNC BAR FROM \"f\"]`)"
5497            )));
5498        }
5499        let mut parts: Vec<&[Tok]> = Vec::new();
5500        if whole.is_some() {
5501            parts.push(inner);
5502        } else {
5503            let mut start = 0;
5504            for (i, tok) in inner.iter().enumerate() {
5505                if matches!(&tok.kind, TokKind::Punct(',')) {
5506                    parts.push(&inner[start..i]);
5507                    start = i + 1;
5508                }
5509            }
5510            parts.push(&inner[start..]);
5511        }
5512        for part in parts {
5513            let dense: Vec<&Tok> = part
5514                .iter()
5515                .filter(|t| !matches!(&t.kind, TokKind::Newline))
5516                .collect();
5517            // `[[F, G FROM "path" (AS ALIAS)?]]`: selective function
5518            // harvest. Anything else bracketed here misses.
5519            if let [bracket] = dense.as_slice()
5520                && let TokKind::Group {
5521                    delim: GroupDelim::Bracket,
5522                    inner,
5523                    ..
5524                } = &bracket.kind
5525            {
5526                let Some(HarvestImport {
5527                    func_names,
5528                    type_names,
5529                    path,
5530                    alias,
5531                }) = parse_from_entry(inner)
5532                else {
5533                    return Ok(None);
5534                };
5535                raw.push(RawEntry::From {
5536                    func_names,
5537                    type_names,
5538                    path,
5539                    alias,
5540                });
5541                continue;
5542            }
5543            // `[F FROM "path" (AS ALIAS)?]`: single harvest without
5544            // inner brackets. The `FROM` keyword is the discriminant
5545            // (module and file parts never contain a top-level one);
5546            // multi-name harvests keep `[[F, G FROM ...]]` so the comma
5547            // stays grouped inside its own scope.
5548            if dense.len() >= 3 {
5549                let owned: Vec<Tok> = dense.iter().map(|t| (*t).clone()).collect();
5550                if let Some(HarvestImport {
5551                    func_names,
5552                    type_names,
5553                    path,
5554                    alias,
5555                }) = parse_from_entry(&owned)
5556                {
5557                    raw.push(RawEntry::From {
5558                        func_names,
5559                        type_names,
5560                        path,
5561                        alias,
5562                    });
5563                    continue;
5564                }
5565            }
5566            match dense.as_slice() {
5567                [tok] => match &tok.kind {
5568                    TokKind::Word(w) if is_upper_ident(w) => {
5569                        raw.push(RawEntry::Module(w.clone()));
5570                    }
5571                    _ => return Ok(None),
5572                },
5573                [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5574                    let (
5575                        TokKind::Str { text, .. },
5576                        TokKind::Word(as_word),
5577                        TokKind::Word(alias_word),
5578                    ) = (&path_tok.kind, &as_tok.kind, &alias_tok.kind)
5579                    else {
5580                        return Ok(None);
5581                    };
5582                    if as_word != KEYWORD_AS {
5583                        return Ok(None);
5584                    }
5585                    raw.push(RawEntry::File {
5586                        path: text.clone(),
5587                        alias: alias_word.clone(),
5588                    });
5589                }
5590                _ => return Ok(None),
5591            }
5592        }
5593        if raw.is_empty() {
5594            return Ok(None);
5595        }
5596        used = 2;
5597    } else if let TokKind::Word(w) = &next.kind {
5598        // Bare `IMPORT MOD` (single module, probed).
5599        if !is_upper_ident(w) {
5600            return Ok(None);
5601        }
5602        raw.push(RawEntry::Module(w.clone()));
5603        used = 2;
5604    } else if let TokKind::Str { text, .. } = &next.kind {
5605        // Bare `IMPORT "path" AS ALIAS`.
5606        let (Some(as_tok), Some(alias_tok)) = (toks.get(pos + 2), toks.get(pos + 3)) else {
5607            return Ok(None);
5608        };
5609        if as_tok.joint || alias_tok.joint {
5610            return Ok(None);
5611        }
5612        let (TokKind::Word(as_word), TokKind::Word(alias_word)) = (&as_tok.kind, &alias_tok.kind)
5613        else {
5614            return Ok(None);
5615        };
5616        if as_word != KEYWORD_AS {
5617            return Ok(None);
5618        }
5619        raw.push(RawEntry::File {
5620            path: text.clone(),
5621            alias: alias_word.clone(),
5622        });
5623        used = 4;
5624    } else {
5625        return Ok(None);
5626    }
5627    // Validate in source order: unknown modules fail with the exact
5628    // backend message (sorted known list); file and harvest entries
5629    // validate hard (bad names, collisions, templates, remote URLs).
5630    let mut modules = Vec::new();
5631    let mut steps = Vec::new();
5632    for entry in raw {
5633        match entry {
5634            RawEntry::Module(module) => {
5635                if !ctx.modules.modules.contains_key(&module) {
5636                    let mut known: Vec<String> = ctx.modules.modules.keys().cloned().collect();
5637                    known.sort();
5638                    return Err(fail(format!(
5639                        "unknown module `{module}`; known modules: {}",
5640                        known.join(", ")
5641                    )));
5642                }
5643                ctx.import_into_frame(std::slice::from_ref(&module), false);
5644                modules.push(module);
5645            }
5646            RawEntry::File { path, alias } => {
5647                let (path, alias) =
5648                    validate_file_import(&path, &alias, ctx, guarded).map_err(fail)?;
5649                steps.push(StepKind::ImportFile { path, alias });
5650            }
5651            RawEntry::From {
5652                func_names,
5653                type_names,
5654                path,
5655                alias,
5656            } => {
5657                let HarvestImport {
5658                    func_names,
5659                    type_names,
5660                    path,
5661                    alias,
5662                } = validate_from_import(
5663                    &func_names,
5664                    &type_names,
5665                    &path,
5666                    alias.as_deref(),
5667                    ctx,
5668                    guarded,
5669                )
5670                .map_err(fail)?;
5671                steps.push(StepKind::ImportFuncs {
5672                    path,
5673                    alias,
5674                    func_names,
5675                    type_names,
5676                });
5677            }
5678        }
5679    }
5680    Ok(Some(((modules, steps), used)))
5681}
5682
5683/// Single file import for value positions (#115): exactly one
5684/// `"path" AS ALIAS` entry and no modules. Anything else shaped like an
5685/// import is a hard error naming the restriction; shape misses return
5686/// `None` for the generic path.
5687fn parse_single_file_import(
5688    toks: &[Tok],
5689    pos: usize,
5690    stmt: usize,
5691    ctx: &ParseCtx,
5692) -> Result<Option<(String, String, usize)>, TokenError> {
5693    let Some(((modules, mut kinds), used)) = parse_import_statement(toks, pos, stmt, ctx, false)?
5694    else {
5695        return Ok(None);
5696    };
5697    if !modules.is_empty() || !matches!(kinds.as_slice(), [StepKind::ImportFile { .. }]) {
5698        return Err(TokenError {
5699            diagnostic: None,
5700            hint: None,
5701            stmt,
5702            msg: if !modules.is_empty()
5703                || kinds
5704                    .iter()
5705                    .any(|k| matches!(k, StepKind::ImportFuncs { .. }))
5706            {
5707                format!(
5708                    "{KEYWORD_IMPORT} here takes a single file import ({KEYWORD_IMPORT} [\"<path>\" AS <ALIAS>]); modules and function harvests stay at statement level"
5709                )
5710            } else {
5711                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>])"
5712                    .to_string()
5713            },
5714            line: 0,
5715            col: 0,
5716            kind: Some(ParseErrorKind::Validation {
5717                command: KEYWORD_IMPORT.to_string(),
5718            }),
5719        });
5720    }
5721    let Some(StepKind::ImportFile { path, alias }) = kinds.pop() else {
5722        unreachable!("length and variant checked above")
5723    };
5724    Ok(Some((path, alias, used)))
5725}
5726
5727/// One `EXPORT` name: an uppercase word with an optional joint
5728/// `::UPPER` tail. Returns the name and tokens consumed, `Ok(None)`
5729/// on shape miss, or `Err` when a recognizable identifier carries
5730/// the wrong sigil (`CONST` requires `$`, `FUNC`/`TYPE` forbid it).
5731fn parse_export_name(
5732    toks: &[Tok],
5733    pos: usize,
5734    require_sigil: bool,
5735    stmt: usize,
5736) -> Result<Option<(String, usize)>, TokenError> {
5737    // Sigil rule: `EXPORT CONST $N` and `EXPORT CONST $LIB::V` require
5738    // the `$`, exactly like every other `CONST` read; `EXPORT FOO`,
5739    // `EXPORT TYPE T`, and qualified func forwards never take one.
5740    // Stored without the sigil; downstream matching (top-level tables,
5741    // harvest maps) is unchanged. `$` must ride gapless onto the
5742    // name, like every `$` read.
5743    let fail = |msg: String| TokenError {
5744        diagnostic: None,
5745        hint: None,
5746        stmt,
5747        line: 0,
5748        col: 0,
5749        kind: None,
5750        msg,
5751    };
5752    let offset = match toks.get(pos).map(|t| &t.kind) {
5753        Some(TokKind::Punct(VAR_SIGIL_CHAR)) if toks.get(pos + 1).is_some_and(|t| t.joint) => 1,
5754        Some(TokKind::Punct(VAR_SIGIL_CHAR)) => return Ok(None),
5755        _ => 0,
5756    };
5757    if require_sigil != (offset == 1) {
5758        let head = toks.get(pos + offset).map(|t| &t.kind);
5759        let recognizable = matches!(head, Some(TokKind::Word(w)) if is_upper_ident(w));
5760        if !recognizable {
5761            return Ok(None);
5762        }
5763        if require_sigil {
5764            return Err(fail(format!(
5765                "{KEYWORD_EXPORT} {KEYWORD_CONST} requires `$`: write {KEYWORD_EXPORT} {KEYWORD_CONST} $NAME (never bare)"
5766            )));
5767        } else {
5768            return Err(fail(format!(
5769                "{KEYWORD_EXPORT} {KEYWORD_FUNC} and {KEYWORD_EXPORT} {KEYWORD_TYPE} names never take `$`: write {KEYWORD_EXPORT} FOO"
5770            )));
5771        }
5772    }
5773    let head = match toks.get(pos + offset).map(|t| &t.kind) {
5774        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
5775        _ => return Ok(None),
5776    };
5777    let mut name = head;
5778    let mut used = 1 + offset;
5779    // Greedy-prefix `::tail` (atomic, like the grammar): a valid
5780    // tail joins, an invalid one stays trailing (failing downstream
5781    // exactly like the grammar's committed prefix).
5782    if matches!(
5783        toks.get(pos + offset + 1).map(|t| &t.kind),
5784        Some(TokKind::Punct(':'))
5785    ) && toks.get(pos + offset + 1).is_some_and(|t| t.joint)
5786        && matches!(
5787            toks.get(pos + offset + 2).map(|t| &t.kind),
5788            Some(TokKind::Punct(':'))
5789        )
5790        && toks.get(pos + offset + 2).is_some_and(|t| t.joint)
5791        && let Some(TokKind::Word(tail)) = toks.get(pos + offset + 3).map(|t| &t.kind)
5792        && toks[pos + offset + 3].joint
5793        && is_upper_ident(tail)
5794    {
5795        name.push_str(MODULE_SEPARATOR);
5796        name.push_str(tail);
5797        used = 4 + offset;
5798    }
5799    Ok(Some((name, used)))
5800}
5801
5802/// One selective harvest (`[[F, G FROM "path" (AS ALIAS)?]]`): the
5803/// wanted function and type names plus the path and optional alias.
5804/// Bare names are functions; `TYPE`/`FUNC` prefixes select the kind
5805/// explicitly (`[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`).
5806struct HarvestImport {
5807    func_names: Vec<String>,
5808    type_names: Vec<String>,
5809    path: String,
5810    alias: Option<String>,
5811}
5812
5813/// One `[[F, G FROM "path" (AS ALIAS)?]]` entry: selective function
5814/// harvest with optional `TYPE`/`FUNC` qualifiers per name:
5815/// `[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`
5816/// (bare stays func for back-compat).
5817/// Returns the harvest, or `None` on shape miss (generic lowering fails
5818/// it). Name case is validated hard by the caller, like file aliases.
5819fn parse_from_entry(inner: &[Tok]) -> Option<HarvestImport> {
5820    let dense: Vec<&Tok> = inner
5821        .iter()
5822        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5823        .collect();
5824    let from = dense
5825        .iter()
5826        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5827    if from == 0 {
5828        return None;
5829    }
5830    // Names: comma-separated entries, each `NAME` (func) or
5831    // `TYPE NAME` / `FUNC NAME` (explicit kind for clarity).
5832    let mut func_names = Vec::new();
5833    let mut type_names = Vec::new();
5834    let mut start = 0;
5835    let head = &dense[..from];
5836    // Local helper: classify one comma-separated part.
5837    fn classify_part(part: &[&Tok]) -> Option<(bool, String)> {
5838        match part {
5839            [tok] => {
5840                let TokKind::Word(w) = &tok.kind else {
5841                    return None;
5842                };
5843                Some((false, w.clone()))
5844            }
5845            // `TYPE NAME` / `FUNC NAME`: the name must be `sep` (gapped
5846            // from the kind); the kind may be joint to a preceding `[`
5847            // or `,` (no space required there), so only the name's joint
5848            // flag matters.
5849            [kind_tok, name_tok] if !name_tok.joint => {
5850                let (TokKind::Word(kind), TokKind::Word(name)) = (&kind_tok.kind, &name_tok.kind)
5851                else {
5852                    return None;
5853                };
5854                if kind == KEYWORD_TYPE {
5855                    Some((true, name.clone()))
5856                } else if kind == KEYWORD_FUNC {
5857                    Some((false, name.clone()))
5858                } else {
5859                    None
5860                }
5861            }
5862            _ => None,
5863        }
5864    }
5865    for (i, tok) in head.iter().enumerate() {
5866        if matches!(&tok.kind, TokKind::Punct(',')) {
5867            let part = &head[start..i];
5868            let (is_type, name) = classify_part(part)?;
5869            if is_type {
5870                type_names.push(name);
5871            } else {
5872                func_names.push(name);
5873            }
5874            start = i + 1;
5875        }
5876    }
5877    let part = &head[start..];
5878    let (is_type, name) = classify_part(part)?;
5879    if is_type {
5880        type_names.push(name);
5881    } else {
5882        func_names.push(name);
5883    }
5884    // Tail: `"path"` or bare `MODULE` with an optional gapped `AS ALIAS`.
5885    // Quoted is a file path (module fallback only when no file matches);
5886    // bare is a host module (no file probe ambiguity).
5887    let tail = &dense[from + 1..];
5888    let path_text = |tok: &Tok| match &tok.kind {
5889        TokKind::Str { text, .. } => Some(text.clone()),
5890        TokKind::Word(w) if is_upper_ident(w) => Some(w.clone()),
5891        _ => None,
5892    };
5893    match tail {
5894        [path_tok] => {
5895            let text = path_text(path_tok)?;
5896            Some(HarvestImport {
5897                func_names,
5898                type_names,
5899                path: text,
5900                alias: None,
5901            })
5902        }
5903        [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5904            let text = path_text(path_tok)?;
5905            let (TokKind::Word(as_word), TokKind::Word(alias_word)) =
5906                (&as_tok.kind, &alias_tok.kind)
5907            else {
5908                return None;
5909            };
5910            if as_word != KEYWORD_AS {
5911                return None;
5912            }
5913            Some(HarvestImport {
5914                func_names,
5915                type_names,
5916                path: text,
5917                alias: Some(alias_word.clone()),
5918            })
5919        }
5920        _ => None,
5921    }
5922}
5923
5924/// First comma-part of a bracket when it is exactly one bare
5925/// uppercase word: the back-compat module reading. Anything else
5926/// (prefixed names, groups, multiple words) is not a bare module.
5927fn single_bare_first_part(inner: &[Tok]) -> Option<&str> {
5928    let end = inner
5929        .iter()
5930        .position(|t| matches!(&t.kind, TokKind::Punct(',')))
5931        .unwrap_or(inner.len());
5932    let mut words = inner[..end]
5933        .iter()
5934        .filter(|t| !matches!(&t.kind, TokKind::Newline));
5935    match (words.next(), words.next()) {
5936        (Some(tok), None) => match &tok.kind {
5937            TokKind::Word(w) if is_upper_ident(w) => Some(w.as_str()),
5938            _ => None,
5939        },
5940        _ => None,
5941    }
5942}
5943
5944/// Whether a top-level `FROM` follows the first top-level comma:
5945/// distinguishes a module-plus-harvest entry (`[STD, T FROM "f"]`)
5946/// from a bare word the author meant as a harvest name.
5947fn has_top_level_from_after_comma(inner: &[Tok]) -> bool {
5948    let mut seen_comma = false;
5949    for tok in inner {
5950        match &tok.kind {
5951            TokKind::Punct(',') => seen_comma = true,
5952            TokKind::Word(w) if seen_comma && w == KEYWORD_FROM => return true,
5953            _ => {}
5954        }
5955    }
5956    false
5957}
5958
5959/// Whole-bracket single-file harvest (`[TYPE A, TYPE B FROM "f"]`):
5960/// the comma-split would orphan `[TYPE A]` (no FROM, invalid alone),
5961/// so the entire bracket parses as one harvest. Only explicitly
5962/// prefixed names qualify: a bare word keeps its legacy module
5963/// reading, so `[STD, TYPE T FROM "f"]` still splits into a module
5964/// plus a harvest instead of harvesting STD as a function.
5965fn whole_file_harvest(inner: &[Tok]) -> Option<HarvestImport> {
5966    let owned: Vec<Tok> = inner.to_vec();
5967    let harvest = parse_from_entry(&owned)?;
5968    let dense: Vec<&Tok> = inner
5969        .iter()
5970        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5971        .collect();
5972    let from = dense
5973        .iter()
5974        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5975    let mut start = 0;
5976    for (i, tok) in dense[..from].iter().enumerate() {
5977        if matches!(&tok.kind, TokKind::Punct(',')) {
5978            if !is_prefixed_name(&dense[start..i]) {
5979                return None;
5980            }
5981            start = i + 1;
5982        }
5983    }
5984    if !is_prefixed_name(&dense[start..from]) {
5985        return None;
5986    }
5987    Some(harvest)
5988}
5989
5990/// One explicitly prefixed name (`TYPE NAME` / `FUNC NAME`): the name
5991/// stays gapped from its kind; the kind may joint to `[` or `,`.
5992fn is_prefixed_name(part: &[&Tok]) -> bool {
5993    match part {
5994        [kind_tok, name_tok] if !name_tok.joint => {
5995            matches!(
5996                (&kind_tok.kind, &name_tok.kind),
5997                (
5998                    TokKind::Word(kind),
5999                    TokKind::Word(_)
6000                ) if kind == KEYWORD_TYPE || kind == KEYWORD_FUNC
6001            )
6002        }
6003        _ => false,
6004    }
6005}
6006
6007/// Validate an `IMPORT` alias: hard errors (never shape misses) plus
6008/// registration into the innermost import frame. Same-frame duplicates
6009/// reject, unless the new import and every visible same-alias entry
6010/// are guard-gated: an unguarded duplicate always collides at runtime
6011/// (probable typo, fail fast), while guarded duplicates may be
6012/// platform branches whose disjointness the static pass decides.
6013fn validate_import_alias(alias: &str, ctx: &ParseCtx, guarded: bool) -> Result<String, String> {
6014    if !is_upper_ident(alias) {
6015        return Err(format!(
6016            "IMPORT alias must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{alias}`"
6017        ));
6018    }
6019    if ctx.modules.modules.contains_key(alias) {
6020        return Err(format!(
6021            "IMPORT alias `{alias}` collides with module `{alias}`"
6022        ));
6023    }
6024    let flags = ctx.import_guard_flags(alias);
6025    if !flags.is_empty() && (!guarded || flags.iter().any(|g| !g)) {
6026        return Err(format!("duplicate {KEYWORD_IMPORT} alias `{alias}`"));
6027    }
6028    ctx.import_into_frame(std::slice::from_ref(&alias.to_string()), guarded);
6029    Ok(alias.to_string())
6030}
6031
6032/// Validate an `IMPORT` path: hard errors, never shape misses.
6033fn validate_import_path(path: &str) -> Result<String, String> {
6034    if path.is_empty() {
6035        return Err(format!("{KEYWORD_IMPORT} path must not be empty"));
6036    }
6037    if path.contains("{{") {
6038        return Err(format!(
6039            "{KEYWORD_IMPORT} path must be a literal string (no {{{{ }}}} templates)"
6040        ));
6041    }
6042    if path.contains("://") {
6043        return Err(
6044            "remote imports are deferred to #270 (net: Run scripts from a remote URL)".to_string(),
6045        );
6046    }
6047    Ok(path.to_string())
6048}
6049
6050/// Validate a file-import path/alias pair: hard errors (never shape
6051/// misses) plus alias registration into the innermost import frame.
6052/// `guarded` marks a guard-gated statement, relaxing the same-frame
6053/// duplicate gate for platform branches (see `validate_import_alias`).
6054fn validate_file_import(
6055    path: &str,
6056    alias: &str,
6057    ctx: &ParseCtx,
6058    guarded: bool,
6059) -> Result<(String, String), String> {
6060    let alias = validate_import_alias(alias, ctx, guarded)?;
6061    let path = validate_import_path(path)?;
6062    Ok((path, alias))
6063}
6064
6065/// Validate a `[[F, G FROM "path" (AS ALIAS)?]]` entry: hard errors
6066/// (never shape misses). Bare func names declare into the innermost
6067/// `FUNC` frame so calls resolve statically; the runtime defines them
6068/// (and fails unknown names there). Type names need no func-frame
6069/// declaration (types resolve through the global type directory);
6070/// the runtime validates them against the file's `EXPORT TYPE` list.
6071/// An alias registers like a file import.
6072fn validate_from_import(
6073    func_names: &[String],
6074    type_names: &[String],
6075    path: &str,
6076    alias: Option<&str>,
6077    ctx: &ParseCtx,
6078    guarded: bool,
6079) -> Result<HarvestImport, String> {
6080    let path = validate_import_path(path)?;
6081    let mut out_func_names = Vec::with_capacity(func_names.len());
6082    for name in func_names {
6083        if !is_upper_ident(name) {
6084            return Err(format!(
6085                "IMPORT function names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
6086            ));
6087        }
6088        if ctx.reserved.contains(name) {
6089            return Err(format!("cannot shadow reserved function `{name}`"));
6090        }
6091        out_func_names.push(name.clone());
6092    }
6093    let mut out_type_names = Vec::with_capacity(type_names.len());
6094    for name in type_names {
6095        if !is_upper_ident(name) {
6096            return Err(format!(
6097                "IMPORT type names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
6098            ));
6099        }
6100        out_type_names.push(name.clone());
6101    }
6102    if out_func_names.is_empty() && out_type_names.is_empty() {
6103        return Err(format!(
6104            "{KEYWORD_IMPORT} harvest needs at least one function or type name"
6105        ));
6106    }
6107    if let Some(alias) = alias {
6108        let alias = validate_import_alias(alias, ctx, guarded)?;
6109        Ok(HarvestImport {
6110            func_names: out_func_names,
6111            type_names: out_type_names,
6112            path,
6113            alias: Some(alias),
6114        })
6115    } else {
6116        for name in &out_func_names {
6117            if !ctx.declare_func(name) {
6118                return Err(format!("duplicate function `{name}` in same scope"));
6119            }
6120        }
6121        // Type harvests without alias land bare in the global type
6122        // directory: duplicates across files fail at import time
6123        // (different targets), not at parse time (targets need IO).
6124        Ok(HarvestImport {
6125            func_names: out_func_names,
6126            type_names: out_type_names,
6127            path,
6128            alias: None,
6129        })
6130    }
6131}
6132
6133/// One `EXPORT ...` name list: function, type, and const names in
6134/// source order. Bare names are functions; explicit `TYPE`/`FUNC`/
6135/// `CONST` prefixes select the kind.
6136struct ExportNames {
6137    func_names: Vec<String>,
6138    type_names: Vec<String>,
6139    const_names: Vec<String>,
6140}
6141
6142/// `EXPORT ...` names at `pos`: bracket list (strict, `ws` gaps:
6143/// newlines ok, comments miss) or a bare greedy-prefix name.
6144/// Supports explicit `TYPE`/`FUNC`/`CONST` qualifiers for clarity:
6145/// `EXPORT TYPE FOO`, `EXPORT FUNC FOO`, `EXPORT CONST $FOO`,
6146/// plus mixed `EXPORT [TYPE A, FUNC B, CONST $C, D]` (bare stays func).
6147/// Returns the name lists plus tokens consumed, `Ok(None)` on shape
6148/// miss (generic fails it in lowering like the grammar), or `Err`
6149/// when a recognizable name carries the wrong sigil. Recording and
6150/// duplicate checks live with the caller (they need the guard and
6151/// level context).
6152fn parse_export_at(
6153    toks: &[Tok],
6154    pos: usize,
6155    stmt: usize,
6156) -> Result<Option<(ExportNames, usize)>, TokenError> {
6157    let next = match toks.get(pos + 1) {
6158        // `sep` after `EXPORT`: joint followers miss.
6159        Some(t) if !t.joint => t,
6160        _ => return Ok(None),
6161    };
6162    // Explicit `EXPORT TYPE ...`, `EXPORT FUNC ...`, or
6163    // `EXPORT CONST ...` prefix.
6164    if let TokKind::Word(w) = &next.kind
6165        && (w == KEYWORD_TYPE || w == KEYWORD_FUNC || w == KEYWORD_CONST)
6166    {
6167        let kind = w.as_str();
6168        let after = match toks.get(pos + 2) {
6169            Some(t) if !t.joint => t,
6170            _ => return Ok(None),
6171        };
6172        if let TokKind::Group {
6173            delim: GroupDelim::Bracket,
6174            inner,
6175            ..
6176        } = &after.kind
6177        {
6178            if let Some(comment) = find_bracket_comment(inner) {
6179                let mut err = lower_err(
6180                    stmt,
6181                    ParseError::from_diagnostic(
6182                        ParseErrorKind::InvalidSyntax {
6183                            command: KEYWORD_EXPORT.to_string(),
6184                        },
6185                        dsl_diag::spelling_bracket_list_comment(KEYWORD_EXPORT),
6186                        &lowering_ctx(stmt),
6187                    ),
6188                );
6189                err.line = comment.line;
6190                err.col = comment.col;
6191                return Err(err);
6192            }
6193            let mut func_names = Vec::new();
6194            let mut type_names = Vec::new();
6195            let mut const_names = Vec::new();
6196            for part in split_bracket_entries(inner) {
6197                let part = trim_export_part(part);
6198                // A trailing comma leaves an empty final entry; it
6199                // carries no name and must not fail the list.
6200                if part.is_empty() {
6201                    continue;
6202                }
6203                let require_sigil = kind == KEYWORD_CONST;
6204                let Some((name, used)) = parse_export_name(part, 0, require_sigil, stmt)? else {
6205                    return Ok(None);
6206                };
6207                if used != part.len() {
6208                    return Ok(None);
6209                }
6210                match kind {
6211                    k if k == KEYWORD_TYPE => type_names.push(name),
6212                    k if k == KEYWORD_CONST => const_names.push(name),
6213                    _ => func_names.push(name),
6214                }
6215            }
6216            if func_names.is_empty() && type_names.is_empty() && const_names.is_empty() {
6217                return Ok(None);
6218            }
6219            return Ok(Some((
6220                ExportNames {
6221                    func_names,
6222                    type_names,
6223                    const_names,
6224                },
6225                3,
6226            )));
6227        }
6228        if matches!(&after.kind, TokKind::Group { .. }) {
6229            return Ok(None);
6230        }
6231        let require_sigil = kind == KEYWORD_CONST;
6232        let Some((name, used)) = parse_export_name(toks, pos + 2, require_sigil, stmt)? else {
6233            return Ok(None);
6234        };
6235        // Bare name after TYPE/FUNC/CONST prefix must consume exactly
6236        // one name; trailing loops stay outside like the unprefixed
6237        // case. `used` counts from pos+2, so 1 name is valid.
6238        if used == 0 {
6239            return Ok(None);
6240        }
6241        return Ok(Some((
6242            match kind {
6243                k if k == KEYWORD_TYPE => ExportNames {
6244                    func_names: Vec::new(),
6245                    type_names: vec![name],
6246                    const_names: Vec::new(),
6247                },
6248                k if k == KEYWORD_CONST => ExportNames {
6249                    func_names: Vec::new(),
6250                    type_names: Vec::new(),
6251                    const_names: vec![name],
6252                },
6253                _ => ExportNames {
6254                    func_names: vec![name],
6255                    type_names: Vec::new(),
6256                    const_names: Vec::new(),
6257                },
6258            },
6259            2 + used,
6260        )));
6261    }
6262    if let TokKind::Group {
6263        delim: GroupDelim::Bracket,
6264        inner,
6265        ..
6266    } = &next.kind
6267    {
6268        if let Some(comment) = find_bracket_comment(inner) {
6269            let mut err = lower_err(
6270                stmt,
6271                ParseError::from_diagnostic(
6272                    ParseErrorKind::InvalidSyntax {
6273                        command: KEYWORD_EXPORT.to_string(),
6274                    },
6275                    dsl_diag::spelling_bracket_list_comment(KEYWORD_EXPORT),
6276                    &lowering_ctx(stmt),
6277                ),
6278            );
6279            err.line = comment.line;
6280            err.col = comment.col;
6281            return Err(err);
6282        }
6283        let mut func_names = Vec::new();
6284        let mut type_names = Vec::new();
6285        let mut const_names = Vec::new();
6286        for part in split_bracket_entries(inner) {
6287            let part = trim_export_part(part);
6288            // A trailing comma leaves an empty final entry; it
6289            // carries no name and must not fail the list.
6290            if part.is_empty() {
6291                continue;
6292            }
6293            let (kind, rest) = split_export_prefix(part);
6294            let is_const = matches!(&kind, TokKind::Word(w) if w == KEYWORD_CONST);
6295            let is_type = matches!(&kind, TokKind::Word(w) if w == KEYWORD_TYPE);
6296            // Exactly one name per entry (entries never trail).
6297            let Some((name, used)) = parse_export_name(rest, 0, is_const, stmt)? else {
6298                return Ok(None);
6299            };
6300            if used != rest.len() {
6301                return Ok(None);
6302            }
6303            if is_const {
6304                const_names.push(name);
6305            } else if is_type {
6306                type_names.push(name);
6307            } else {
6308                func_names.push(name);
6309            }
6310        }
6311        if func_names.is_empty() && type_names.is_empty() && const_names.is_empty() {
6312            return Ok(None);
6313        }
6314        return Ok(Some((
6315            ExportNames {
6316                func_names,
6317                type_names,
6318                const_names,
6319            },
6320            2,
6321        )));
6322    }
6323    if matches!(&next.kind, TokKind::Group { .. }) {
6324        return Ok(None);
6325    }
6326    // Bare name (greedy `::` prefix; trailing loops outside). Bare
6327    // stays func for back-compat; `TYPE`/`FUNC` prefix selects above.
6328    // Func names never take `$`: `EXPORT $X` errors inside
6329    // `parse_export_name`, exactly like a `$`-less read elsewhere.
6330    match parse_export_name(toks, pos + 1, false, stmt)? {
6331        Some((name, used)) => Ok(Some((
6332            ExportNames {
6333                func_names: vec![name],
6334                type_names: Vec::new(),
6335                const_names: Vec::new(),
6336            },
6337            1 + used,
6338        ))),
6339        None => Ok(None),
6340    }
6341}
6342
6343/// Trim leading/trailing newlines around one `EXPORT` bracket entry.
6344/// Single owner so the explicit-prefix and mixed-list loops cannot
6345/// drift on trailing-comma handling.
6346fn trim_export_part(part: &[Tok]) -> &[Tok] {
6347    let mut part = part;
6348    while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
6349        part = &part[1..];
6350    }
6351    while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
6352        part = &part[..part.len() - 1];
6353    }
6354    part
6355}
6356
6357/// Split one mixed-list `EXPORT` entry into its kind prefix and name
6358/// slice. `TYPE`/`FUNC`/`CONST` plus a gapped name selects the kind;
6359/// anything else defaults to `FUNC`. Single owner so both bracket
6360/// loops agree on prefix parsing.
6361fn split_export_prefix(part: &[Tok]) -> (TokKind, &[Tok]) {
6362    // Optional per-entry `TYPE`/`FUNC`/`CONST` prefix for mixed
6363    // lists: `EXPORT [TYPE A, FUNC B, CONST $C, D]` (bare stays
6364    // func, `CONST` entries require `$`). The name must be `sep`
6365    // from the prefix; the prefix itself may be joint to a
6366    // preceding `[` or `,`, so only the name's joint flag matters.
6367    match part {
6368        [first, second, ..]
6369            if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_TYPE || w == KEYWORD_FUNC || w == KEYWORD_CONST)
6370                && !second.joint =>
6371        {
6372            (first.kind.clone(), &part[1..])
6373        }
6374        _ => (TokKind::Word(KEYWORD_FUNC.to_string()), part),
6375    }
6376}
6377
6378/// Split bracket inner tokens on top-level commas, preserving entries
6379/// for per-entry `TYPE`/`FUNC` handling. Newlines trim at the caller.
6380fn split_bracket_entries(inner: &[Tok]) -> Vec<&[Tok]> {
6381    let mut parts: Vec<&[Tok]> = Vec::new();
6382    let mut start = 0;
6383    for (i, tok) in inner.iter().enumerate() {
6384        if matches!(&tok.kind, TokKind::Punct(',')) {
6385            parts.push(&inner[start..i]);
6386            start = i + 1;
6387        }
6388    }
6389    parts.push(&inner[start..]);
6390    parts
6391}
6392
6393/// First comment token inside a bracket name list, if any. Single
6394/// owner for the shared `IMPORT`/`EXPORT` bracket rule (newlines ok,
6395/// comments miss): every bracket-list entry loop consults this
6396/// before treating the list as a shape miss, so the failure names
6397/// and points at the comment instead of falling through to the
6398/// generic statement error. Recurses into nested groups so
6399/// selective-harvest `[[...]]` entries report the same way through
6400/// the one key. Callers stamp the returned token's coordinates onto
6401/// the error (`stamp_pos` never overwrites real positions).
6402fn find_bracket_comment(inner: &[Tok]) -> Option<&Tok> {
6403    inner.iter().find_map(|t| match &t.kind {
6404        TokKind::Comment(_) => Some(t),
6405        TokKind::Group { inner, .. } => find_bracket_comment(inner),
6406        _ => None,
6407    })
6408}
6409
6410/// `TYPE NAME = SHAPE` at `pos`: uppercase name, single `=`, maximal
6411/// type-tag shape canonicalized through the shared spelling.
6412/// Returns the alias plus tokens consumed, or `None` on shape miss
6413/// (generic fails it in lowering like the grammar).
6414fn parse_type_stmt_at(
6415    toks: &[Tok],
6416    pos: usize,
6417    stmt: usize,
6418) -> Result<Option<(StepKind, usize)>, TokenError> {
6419    let name = match toks.get(pos + 1).map(|t| &t.kind) {
6420        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
6421        _ => return Ok(None),
6422    };
6423    // Single `=` at any gap (`gap` zero-width); `==` misses.
6424    if !matches!(
6425        toks.get(pos + 2).map(|t| &t.kind),
6426        Some(TokKind::Punct('='))
6427    ) {
6428        return Ok(None);
6429    }
6430    if matches!(
6431        toks.get(pos + 3).map(|t| &t.kind),
6432        Some(TokKind::Punct('='))
6433    ) {
6434        return Ok(None);
6435    }
6436    let Some(end) = parse_type_shape(toks, pos + 3) else {
6437        return Ok(None);
6438    };
6439    // Post-match the span holds words, puncts, and default literals
6440    // only, so the shared renderer cannot fail; stay failed regardless.
6441    let target = render_type_region(&toks[pos + 3..end], stmt).unwrap_or_default();
6442    Ok(Some((StepKind::TypeAlias { name, target }, end - pos)))
6443}
6444
6445/// Single (non-block) `REMOTE`: target, optional bindings, block.
6446/// The target reads a maximal joint run in the grammar's superset
6447/// charset (misses fall to generic); strict validity fails loudly
6448/// with the exact backend message. Bindings miss to generic;
6449/// empty/missing bodies and nesting violations fail loudly.
6450fn parse_remote_single(
6451    toks: &[Tok],
6452    pos: usize,
6453    stmt: usize,
6454    ctx: &ParseCtx,
6455) -> Result<Option<(StepKind, usize)>, TokenError> {
6456    let fail = |msg: String| TokenError {
6457        diagnostic: None,
6458        hint: None,
6459        stmt,
6460        msg,
6461        line: 0,
6462        col: 0,
6463        kind: Some(ParseErrorKind::Validation {
6464            command: KEYWORD_REMOTE.to_string(),
6465        }),
6466    };
6467    // Target: joint run in the superset charset (alnum/`_`/`-`/`.`/`:`).
6468    // Anything else (joint or not) ends the run; an empty run misses
6469    // to generic. (`sep` needs no explicit check: a joint `(` is a
6470    // call routed before this ever runs, and anything unparseable
6471    // misses the same way.)
6472    let mut target = String::new();
6473    let mut p = pos + 1;
6474    while let Some(t) = toks.get(p) {
6475        if !t.joint && !target.is_empty() {
6476            break;
6477        }
6478        match &t.kind {
6479            TokKind::Word(w)
6480                if w.chars().all(|c| {
6481                    c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' || c == ':'
6482                }) =>
6483            {
6484                // Words arrive whole from the lexer; a bad word ends
6485                // the run (never partially appends), like the grammar.
6486                target.push_str(w);
6487                p += 1;
6488            }
6489            TokKind::Punct(c)
6490                if matches!(c, '_' | '-' | '.' | ':') && (target.is_empty() || t.joint) =>
6491            {
6492                target.push(*c);
6493                p += 1;
6494            }
6495            _ => break,
6496        }
6497    }
6498    if target.is_empty() {
6499        return Ok(None);
6500    }
6501    if !crate::commands::is_valid_remote_target(&target) {
6502        return Err(fail(format!(
6503            "invalid REMOTE target `{target}`: start alphanumeric, then alphanumeric, `_`, or `-`, max 64 chars, never SNAPSHOT, LOCAL, CACHE, SYSTEM, or REMOTE"
6504        )));
6505    }
6506    // Optional bindings `[$var, env:KEY]` at any gap (even joint,
6507    // probed); malformed bindings miss the whole shape to generic.
6508    let mut vars = Vec::new();
6509    let mut env = Vec::new();
6510    if let Some(bracket) = toks.get(p)
6511        && matches!(
6512            &bracket.kind,
6513            TokKind::Group {
6514                delim: GroupDelim::Bracket,
6515                ..
6516            }
6517        )
6518    {
6519        let inner = match &bracket.kind {
6520            TokKind::Group { inner, .. } => inner.clone(),
6521            _ => unreachable!(),
6522        };
6523        match parse_remote_bindings(&inner, stmt, ctx)? {
6524            Some((v, e)) => {
6525                vars = v;
6526                env = e;
6527            }
6528            None => return Ok(None),
6529        }
6530        p += 1;
6531    }
6532    // Block required (any gap, never a template); missing blocks
6533    // miss to generic.
6534    let block_ok = matches!(
6535        toks.get(p).map(|t| &t.kind),
6536        Some(TokKind::Group {
6537            delim: GroupDelim::Brace,
6538            ..
6539        })
6540    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
6541    if !block_ok {
6542        return Ok(None);
6543    }
6544    let inner = match &toks[p].kind {
6545        TokKind::Group { inner, .. } => inner.clone(),
6546        _ => unreachable!(),
6547    };
6548    let body = parse_body_steps(&inner, stmt, ctx, false)?;
6549    p += 1;
6550    if body.is_empty() {
6551        return Err(fail(format!(
6552            "{KEYWORD_REMOTE} requires a non-empty braced block"
6553        )));
6554    }
6555    if crate::commands::contains_remote_block(&body) {
6556        return Err(fail(format!(
6557            "REMOTE blocks cannot nest (target `{target}` contains another REMOTE block)"
6558        )));
6559    }
6560    if body
6561        .iter()
6562        .any(|s| crate::commands::contains_inherit_env(&s.kind))
6563    {
6564        return Err(fail(format!(
6565            "{KEYWORD_INHERIT_ENV} cannot appear inside a {KEYWORD_REMOTE} block: the guest inherits its own process environment"
6566        )));
6567    }
6568    // Outer-function containment (same rule as the shared remote
6569    // validators): body calls resolving to visible
6570    // outer `SCRIPT` defs (without same-body definitions) fail.
6571    {
6572        let mut inner_defs = HashSet::new();
6573        let mut calls = Vec::new();
6574        crate::commands::collect_remote_body_symbols(&body, &mut inner_defs, &mut calls);
6575        let outer_defs: HashSet<String> = ctx.funcs.borrow().iter().flatten().cloned().collect();
6576        for call in &calls {
6577            let bare = crate::constants::base_name(call);
6578            let is_script_call = match crate::constants::split_qualified(call) {
6579                Some((module, _)) => module == crate::constants::SCRIPT_MODULE_NAME,
6580                None => true,
6581            };
6582            if is_script_call && outer_defs.contains(bare) && !inner_defs.contains(bare) {
6583                return Err(fail(format!(
6584                    "REMOTE '{target}' calls outer function '{bare}' (functions must be defined inside the block)"
6585                )));
6586            }
6587        }
6588    }
6589    Ok(Some((
6590        StepKind::RemoteBlock {
6591            target,
6592            vars,
6593            env,
6594            body,
6595        },
6596        p - pos,
6597    )))
6598}
6599// ---- LET/SET/RETURN + expressions ----
6600// Expression tiers over [`Tok`] implement the precedence chain
6601// (or > and > comparison > ordering > add > mul > unary > atom);
6602// arithmetic/comparison lowering runs through the shared constructors
6603// (`make_arith`, `make_compare`, `apply_unary_neg`), so folding, RPN
6604// compilation, and overflow behavior are identical by construction,
6605// never re-derived.
6606
6607/// Eat a one- or two-char operator: single puncts match directly;
6608/// pairs (`==`, `!=`, `<=`, `>=`, `&&`, `||`, `::`) require a joint
6609/// second punct. Newlines never skip here (expression mode).
6610fn eat_op(cur: &mut Cursor, first: char, second: Option<char>) -> bool {
6611    // Gaps (comments included) are skipped before every operator.
6612    cur.skip_gap();
6613    let (a, b) = match (cur.toks.get(cur.pos), cur.toks.get(cur.pos + 1)) {
6614        (Some(a), b) => (a, b),
6615        _ => return false,
6616    };
6617    if !matches!(&a.kind, TokKind::Punct(c) if *c == first) {
6618        return false;
6619    }
6620    match second {
6621        None => {
6622            cur.pos += 1;
6623            true
6624        }
6625        Some(c2) => match b {
6626            Some(t) if t.joint && matches!(&t.kind, TokKind::Punct(c) if *c == c2) => {
6627                cur.pos += 2;
6628                true
6629            }
6630            _ => false,
6631        },
6632    }
6633}
6634
6635/// Dummy span for the shared lowering constructors: v2 owns no source
6636/// positions yet, so only success values (span-free) participate in
6637/// parity; failures surface through [`TokenError`] text.
6638fn lowering_ctx(stmt: usize) -> SpanContext<'static> {
6639    let _ = stmt;
6640    SpanContext::line_only(0)
6641}
6642
6643fn parse_expr_or(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6644    let mut left = parse_expr_and(cur, ctx)?;
6645    while eat_op(cur, '|', Some('|')) {
6646        cur.skip_gap();
6647        let right = parse_expr_and(cur, ctx)?;
6648        // No folding, no boundary checks: unfused literal runs stay
6649        // literal here.
6650        left = Expr::Logical {
6651            op: LogicalOp::Or,
6652            left: Box::new(left),
6653            right: Box::new(right),
6654        };
6655    }
6656    Ok(left)
6657}
6658
6659fn parse_expr_and(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6660    let mut left = parse_expr_cmp(cur, ctx)?;
6661    while eat_op(cur, '&', Some('&')) {
6662        cur.skip_gap();
6663        let right = parse_expr_cmp(cur, ctx)?;
6664        reject_boundary(&lowering_ctx(cur.stmt), &left).map_err(|e| cur.err(e.to_string()))?;
6665        reject_boundary(&lowering_ctx(cur.stmt), &right).map_err(|e| cur.err(e.to_string()))?;
6666        left = Expr::Logical {
6667            op: LogicalOp::And,
6668            left: Box::new(left),
6669            right: Box::new(right),
6670        };
6671    }
6672    Ok(left)
6673}
6674
6675fn parse_expr_cmp(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6676    let left = parse_expr_ord(cur, ctx)?;
6677    let op = if eat_op(cur, '=', Some('=')) {
6678        CompareOp::Eq
6679    } else if eat_op(cur, '!', Some('=')) {
6680        CompareOp::Ne
6681    } else {
6682        return Ok(left);
6683    };
6684    cur.skip_gap();
6685    let right = parse_expr_ord(cur, ctx)?;
6686    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
6687        .map_err(|e| cur.err(e.to_string()))?;
6688    reject_chained_compare(cur, false)?;
6689    Ok(expr)
6690}
6691
6692/// Reject a comparison operator trailing a complete comparison:
6693/// no grammar position continues with one, so the shape always fails —
6694/// loudly here instead of stranding text for a confusing downstream
6695/// error. The equality tier rejects all six (`$a == $b == $c`,
6696/// `$a == $b < $c < $d`); the ordering tier rejects ordering only
6697/// (`$a < $b < $c`), since `$a < $b == $c` is a legitimate equality
6698/// over an ordering result. Probes without consuming.
6699fn reject_chained_compare(cur: &mut Cursor, ordering_only: bool) -> Result<(), TokenError> {
6700    let mut probe = Cursor::expr(cur.toks, cur.stmt);
6701    probe.pos = cur.pos;
6702    probe.skip_gap();
6703    let chained = match probe.toks.get(probe.pos).map(|t| &t.kind) {
6704        Some(TokKind::Punct('<' | '>')) => true,
6705        Some(TokKind::Punct('=' | '!')) => !ordering_only,
6706        _ => false,
6707    };
6708    if chained {
6709        return Err(cur
6710            .err("chained comparison operators need explicit parentheses, e.g. `($a < $b) < $c`"));
6711    }
6712    Ok(())
6713}
6714
6715fn parse_expr_ord(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6716    let left = parse_expr_add(cur, ctx)?;
6717    let op = if eat_op(cur, '<', Some('=')) {
6718        CompareOp::Le
6719    } else if eat_op(cur, '>', Some('=')) {
6720        CompareOp::Ge
6721    } else if eat_op(cur, '<', None) {
6722        CompareOp::Lt
6723    } else if eat_op(cur, '>', None) {
6724        CompareOp::Gt
6725    } else {
6726        return Ok(left);
6727    };
6728    cur.skip_gap();
6729    let right = parse_expr_add(cur, ctx)?;
6730    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
6731        .map_err(|e| cur.err(e.to_string()))?;
6732    reject_chained_compare(cur, true)?;
6733    Ok(expr)
6734}
6735
6736fn parse_expr_add(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6737    let mut left = parse_expr_mul(cur, ctx)?;
6738    loop {
6739        let op = if eat_op(cur, '+', None) {
6740            ArithOp::Add
6741        } else if eat_op(cur, '-', None) {
6742            ArithOp::Sub
6743        } else {
6744            break;
6745        };
6746        cur.skip_gap();
6747        let right = parse_expr_mul(cur, ctx)?;
6748        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
6749            .map_err(|e| cur.err(e.to_string()))?;
6750    }
6751    Ok(left)
6752}
6753
6754fn parse_expr_mul(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6755    let mut left = parse_expr_unary(cur, ctx)?;
6756    loop {
6757        let op = if eat_op(cur, '*', None) {
6758            ArithOp::Mul
6759        } else if eat_op(cur, '/', None) {
6760            ArithOp::Div
6761        } else {
6762            break;
6763        };
6764        cur.skip_gap();
6765        let right = parse_expr_unary(cur, ctx)?;
6766        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
6767            .map_err(|e| cur.err(e.to_string()))?;
6768    }
6769    Ok(left)
6770}
6771
6772/// A `-` opens a bare word (never negation) when gaplessly followed by
6773/// a letter, `_`, or `/` — the `neg_op` lookahead, read off `joint`.
6774fn dash_is_bare(cur: &Cursor) -> bool {
6775    let next = cur.toks.get(cur.pos + 1);
6776    match next {
6777        Some(t) if t.joint => match &t.kind {
6778            TokKind::Word(w) => w
6779                .chars()
6780                .next()
6781                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_'),
6782            TokKind::Punct('/') => true,
6783            _ => false,
6784        },
6785        _ => false,
6786    }
6787}
6788
6789fn parse_expr_unary(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6790    let mut prefixes = Vec::new();
6791    loop {
6792        match cur.toks.get(cur.pos).map(|t| &t.kind) {
6793            Some(TokKind::Punct('!')) => {
6794                cur.pos += 1;
6795                // Each prefix is gap-separated.
6796                cur.skip_gap();
6797                prefixes.push(false);
6798            }
6799            Some(TokKind::Punct('-')) if !dash_is_bare(cur) => {
6800                cur.pos += 1;
6801                cur.skip_gap();
6802                prefixes.push(true);
6803            }
6804            _ => break,
6805        }
6806    }
6807    let mut expr = parse_expr_atom(cur, ctx)?;
6808    // Innermost prefix is closest to the atom: apply in reverse order.
6809    for is_neg in prefixes.into_iter().rev() {
6810        if is_neg {
6811            expr = apply_unary_neg(&lowering_ctx(cur.stmt), expr)
6812                .map_err(|e| cur.err(e.to_string()))?;
6813        } else {
6814            reject_boundary(&lowering_ctx(cur.stmt), &expr).map_err(|e| cur.err(e.to_string()))?;
6815            expr = Expr::Not(Box::new(expr));
6816        }
6817    }
6818    Ok(expr)
6819}
6820
6821/// Identifier charset for `$var` and `.segment` parts. Segments admit
6822/// digits-only too (`$a.0`); anything else ends the key path and errors
6823/// downstream, like the grammar's backtrack to `variable`.
6824fn is_ident_word(w: &str) -> bool {
6825    !w.is_empty() && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
6826}
6827
6828/// One joint `::NAME` tail at `pos` (the first `:`): both colons and
6829/// the name ride gapless, and the name matches [`is_ident_word`].
6830/// Single owner for qualified-`$ALIAS::NAME` matching, so `$` arms
6831/// and bare-word diagnostics cannot drift on jointness or charset.
6832fn match_joint_qualified(toks: &[Tok], pos: usize) -> Option<String> {
6833    let first = matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct(':')))
6834        && toks.get(pos).is_some_and(|t| t.joint);
6835    let second = matches!(
6836        toks.get(pos + 1).map(|t| &t.kind),
6837        Some(TokKind::Punct(':'))
6838    ) && toks.get(pos + 1).is_some_and(|t| t.joint);
6839    let name_tok = toks.get(pos + 2);
6840    let ok = first
6841        && second
6842        && matches!(name_tok.map(|t| &t.kind), Some(TokKind::Word(w)) if is_ident_word(w))
6843        && name_tok.is_some_and(|t| t.joint);
6844    if !ok {
6845        return None;
6846    }
6847    match &name_tok.expect("checked").kind {
6848        TokKind::Word(w) => Some(w.clone()),
6849        _ => unreachable!(),
6850    }
6851}
6852
6853fn is_key_segment(w: &str) -> bool {
6854    !w.is_empty()
6855        && (w.chars().all(|c| c.is_ascii_digit())
6856            || (w
6857                .chars()
6858                .next()
6859                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
6860                && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')))
6861}
6862
6863fn is_env_key(w: &str) -> bool {
6864    !w.is_empty()
6865        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
6866        && w.chars()
6867            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
6868}
6869
6870/// Maximal joint run of words and `-/.'/'` puncts: the bare-word
6871/// shape (which admits `/` anywhere, so `//c`, `/a`, `a/b`, and the
6872/// `/`-`c`-`/` operands of `/*c*/` math all read literally here).
6873/// Callers classify (`true`/`false`/string); the numeric path
6874/// runs first and falls back here on shape/follower mismatch.
6875/// Backslash escapes are arg-position syntax: the bare-word shape admits
6876/// no `\`, so expression runs containing one fail here (never drift
6877/// into a string the grammar rejects).
6878fn expr_bare_run(cur: &mut Cursor, leading_dash: bool) -> Result<String, TokenError> {
6879    let mut out = String::new();
6880    if leading_dash {
6881        match cur.next() {
6882            Some(t) if matches!(&t.kind, TokKind::Punct('-')) => out.push('-'),
6883            _ => return Err(cur.err("missing expression operand")),
6884        }
6885    }
6886    match cur.next() {
6887        Some(t) => match &t.kind {
6888            TokKind::Word(w) => out.push_str(w),
6889            // Leading `/` (operand position only; operators are
6890            // consumed by the tiers before operands parse).
6891            TokKind::Punct('/') => out.push('/'),
6892            _ => return Err(cur.err("missing expression operand")),
6893        },
6894        None => return Err(cur.err("missing expression operand")),
6895    }
6896    loop {
6897        let next = match cur.toks.get(cur.pos) {
6898            Some(t) if t.joint => t,
6899            _ => break,
6900        };
6901        match &next.kind {
6902            TokKind::Word(w) => {
6903                // Abutting words only continue through an operator gap
6904                // the tiers own (`a -b` never fuses); without a joint
6905                // punct between, stop. Since this token IS joint, the
6906                // previous token must have been a bare punct.
6907                out.push_str(w);
6908                cur.pos += 1;
6909            }
6910            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
6911                out.push(*c);
6912                cur.pos += 1;
6913            }
6914            _ => break,
6915        }
6916    }
6917    if out.contains('\\') {
6918        return Err(cur.err("unexpected escape in expression"));
6919    }
6920    Ok(out)
6921}
6922
6923/// Numeric literal head: digit-led word plus joint `.digits` tails.
6924/// Callers apply the separator-shape gate and the follower rule, then
6925/// the shared classifier.
6926fn number_head(cur: &mut Cursor) -> Option<String> {
6927    let first = match cur.toks.get(cur.pos).map(|t| &t.kind) {
6928        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => w.clone(),
6929        _ => return None,
6930    };
6931    let mut text = first;
6932    let mut pos = cur.pos + 1;
6933    loop {
6934        let dot = matches!(
6935            cur.toks.get(pos).map(|t| &t.kind),
6936            Some(TokKind::Punct('.'))
6937        ) && cur.toks.get(pos).is_some_and(|t| t.joint);
6938        let digits = cur.toks.get(pos + 1);
6939        let digits_ok = dot
6940            && matches!(digits.map(|t| &t.kind), Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_'))
6941            && digits.is_some_and(|t| t.joint);
6942        if !digits_ok {
6943            break;
6944        }
6945        text.push('.');
6946        if let Some(TokKind::Word(w)) = digits.map(|t| &t.kind) {
6947            text.push_str(w);
6948        }
6949        pos += 2;
6950    }
6951    Some(text)
6952}
6953
6954/// `_`-separator shape gate mirroring the `numeric_literal` rule:
6955/// digits with single-underscore separators, at most one fraction.
6956fn numeric_shape_ok(text: &str) -> bool {
6957    let mut parts = text.split('.');
6958    let int_part = parts.next().unwrap_or("");
6959    let frac_part = parts.next();
6960    if parts.next().is_some() {
6961        return false;
6962    }
6963    fn run_ok(s: &str) -> bool {
6964        !s.is_empty()
6965            && s.chars().all(|c| c.is_ascii_digit() || c == '_')
6966            && !s.starts_with('_')
6967            && !s.ends_with('_')
6968            && !s.contains("__")
6969    }
6970    run_ok(int_part) && frac_part.is_none_or(run_ok)
6971}
6972
6973/// Follower rule mirroring the `numeric_literal` trailing guard
6974/// (`!(ALNUM | "_" | "." | "/")`): a joint word, `.`, or `/` continues
6975/// into a bare word (`30s`, `1.`, `4/2`); `-`/`+`/operators let the
6976/// number stand for the tiers (`1-2` is `Sub`, like the grammar).
6977fn number_falls_to_bare(cur: &Cursor, consumed: usize) -> bool {
6978    match cur.toks.get(cur.pos + consumed) {
6979        Some(t) if t.joint => matches!(
6980            &t.kind,
6981            TokKind::Word(_) | TokKind::Punct('.') | TokKind::Punct('/')
6982        ),
6983        _ => false,
6984    }
6985}
6986
6987fn parse_expr_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6988    match cur.toks.get(cur.pos).map(|t| &t.kind) {
6989        Some(TokKind::Group {
6990            delim: GroupDelim::Paren,
6991            inner,
6992            ..
6993        }) => {
6994            let inner = inner.clone();
6995            cur.pos += 1;
6996            let mut sub = Cursor::expr(&inner, cur.stmt);
6997            sub.skip_gap_nl();
6998            let expr = parse_expr_or(&mut sub, ctx)?;
6999            sub.skip_gap_nl();
7000            if !sub.done() {
7001                return Err(sub.err("unexpected text in parentheses"));
7002            }
7003            Ok(expr)
7004        }
7005        Some(TokKind::Word(_)) if call_shape_at(cur.toks, cur.pos, false).is_some() => {
7006            let (name, paren) =
7007                call_shape_at(cur.toks, cur.pos, false).ok_or_else(|| cur.err("unreachable"))?;
7008            let inner = match &cur.toks[paren].kind {
7009                TokKind::Group { inner, .. } => inner.clone(),
7010                _ => unreachable!(),
7011            };
7012            cur.pos = paren + 1;
7013            parse_expr_call(name, &inner, cur.stmt, ctx)
7014        }
7015        Some(TokKind::Punct(VAR_SIGIL_CHAR)) => {
7016            cur.pos += 1;
7017            // Atomic `variable`: `$` and the name ride gapless (the
7018            // enclosing rules are compound-atomic).
7019            let base = match cur.next() {
7020                Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
7021                    match &t.kind {
7022                        TokKind::Word(w) => w.clone(),
7023                        _ => unreachable!(),
7024                    }
7025                }
7026                _ => return Err(cur.err("`$` requires a variable name")),
7027            };
7028            let mut keys = Vec::new();
7029            // Qualified immutable read (`$ALIAS::NAME`). Key paths
7030            // never ride qualified names: copy to a local first.
7031            if let Some(name) = match_joint_qualified(cur.toks, cur.pos) {
7032                cur.pos += 3;
7033                if matches!(
7034                    cur.toks.get(cur.pos).map(|t| &t.kind),
7035                    Some(TokKind::Punct('.'))
7036                ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint)
7037                {
7038                    return Err(cur.err(crate::template::qualified_keypath_error()));
7039                }
7040                return Ok(Expr::ConstRef { alias: base, name });
7041            }
7042            loop {
7043                // Key-path dots are gapless too (`~` without `gap`).
7044                let dot = matches!(
7045                    cur.toks.get(cur.pos).map(|t| &t.kind),
7046                    Some(TokKind::Punct('.'))
7047                ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
7048                let seg = cur.toks.get(cur.pos + 1);
7049                let seg_ok = dot
7050                    && matches!(seg.map(|t| &t.kind), Some(TokKind::Word(w)) if is_key_segment(w))
7051                    && seg.is_some_and(|t| t.joint);
7052                if !seg_ok {
7053                    break;
7054                }
7055                if let Some(TokKind::Word(w)) = seg.map(|t| &t.kind) {
7056                    keys.push(w.clone());
7057                }
7058                cur.pos += 2;
7059            }
7060            if keys.is_empty() {
7061                Ok(Expr::Var { name: base })
7062            } else {
7063                Ok(Expr::KeyPath { base, keys })
7064            }
7065        }
7066        Some(TokKind::Word(w)) if w == "env" => {
7067            // `env:KEY` read when the full shape matches gaplessly
7068            // (atomic `env_read`); otherwise a bare word (`env` alone,
7069            // `env:k` lowercase) for the error path, exactly like the
7070            // grammar's mismatch.
7071            let key_ok = matches!(
7072                cur.toks.get(cur.pos + 1).map(|t| &t.kind),
7073                Some(TokKind::Punct(':'))
7074            ) && cur.toks.get(cur.pos + 1).is_some_and(|t| t.joint)
7075                && matches!(
7076                    cur.toks.get(cur.pos + 2).map(|t| &t.kind),
7077                    Some(TokKind::Word(k)) if is_env_key(k)
7078                )
7079                && cur.toks.get(cur.pos + 2).is_some_and(|t| t.joint);
7080            if !key_ok {
7081                return parse_bare_atom(cur, ctx, false);
7082            }
7083            cur.pos += 1;
7084            cur.pos += 1;
7085            match cur.next() {
7086                Some(t) => match &t.kind {
7087                    TokKind::Word(k) => Ok(Expr::Env(k.clone())),
7088                    _ => Err(cur.err("unreachable")),
7089                },
7090                None => Err(cur.err("unreachable")),
7091            }
7092        }
7093        Some(TokKind::Group {
7094            delim: GroupDelim::Bracket,
7095            inner,
7096            ..
7097        }) => {
7098            let inner = inner.clone();
7099            cur.pos += 1;
7100            parse_list_literal(&inner, cur.stmt, ctx)
7101        }
7102        Some(TokKind::Group {
7103            delim: GroupDelim::Brace,
7104            inner,
7105            ..
7106        }) => {
7107            let inner = inner.clone();
7108            cur.pos += 1;
7109            parse_map_or_block(&inner, cur.stmt, ctx)
7110        }
7111        Some(TokKind::Str { text, .. }) => {
7112            let text = text.clone();
7113            cur.pos += 1;
7114            Ok(Expr::Literal(Value::string(text)))
7115        }
7116        Some(TokKind::BlockStr(full)) => {
7117            let full = full.clone();
7118            cur.pos += 1;
7119            Ok(Expr::Literal(Value::string(
7120                crate::command::lower_block_string(&full),
7121            )))
7122        }
7123        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => {
7124            parse_numeric_atom(cur, ctx)
7125        }
7126        Some(TokKind::Word(_)) => {
7127            // Bare `ALIAS::NAME` never reads: without the `$` sigil
7128            // there is no qualified shape, only a bare word followed
7129            // by stray punctuation. Name the `$` form instead of
7130            // stranding the reader on the colons.
7131            if let Some(TokKind::Word(base)) = cur.toks.get(cur.pos).map(|t| &t.kind)
7132                && is_ident_word(base)
7133                && let Some(name) = match_joint_qualified(cur.toks, cur.pos + 1)
7134            {
7135                let base = base.clone();
7136                return Err(cur.err(crate::template::bare_sigil_error(&qualify(&base, &name))));
7137            }
7138            parse_bare_atom(cur, ctx, false)
7139        }
7140        Some(TokKind::Punct('-')) => parse_bare_atom(cur, ctx, true),
7141        Some(TokKind::Punct('/')) => parse_bare_atom(cur, ctx, false),
7142        _ => Err(cur.err("missing expression operand")),
7143    }
7144}
7145
7146/// Bare-word atom with a `-` lead (the caller proved it is not
7147/// negation): consumes the joint `-/.'/'` run for the bare-word
7148/// shape.
7149fn parse_bare_atom(
7150    cur: &mut Cursor,
7151    _ctx: &ParseCtx,
7152    leading_dash: bool,
7153) -> Result<Expr, TokenError> {
7154    let text = expr_bare_run(cur, leading_dash)?;
7155    match text.as_str() {
7156        "true" => Ok(Expr::Literal(Value::bool(true))),
7157        "false" => Ok(Expr::Literal(Value::bool(false))),
7158        _ => Ok(Expr::Literal(Value::string(text))),
7159    }
7160}
7161
7162/// Numeric atom: rejoin dotted tails, apply the shape gate and the
7163/// follower rule, then the shared classifier. Anything failing the
7164/// gate or follower reparses as a bare word (durations, versions,
7165/// paths), exactly like the grammar's numeric-literal-or-bare-word
7166/// order.
7167fn parse_numeric_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7168    let start = cur.pos;
7169    let text = number_head(cur).ok_or_else(|| cur.err("missing expression operand"))?;
7170    let consumed = {
7171        let mut n = 1;
7172        let mut p = start + 1;
7173        while matches!(cur.toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('.')))
7174            && cur.toks.get(p).is_some_and(|t| t.joint)
7175            && matches!(
7176                cur.toks.get(p + 1).map(|t| &t.kind),
7177                Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_')
7178            )
7179            && cur.toks.get(p + 1).is_some_and(|t| t.joint)
7180        {
7181            n += 2;
7182            p += 2;
7183        }
7184        n
7185    };
7186    if !numeric_shape_ok(&text) || number_falls_to_bare(cur, consumed) {
7187        return parse_bare_atom(cur, ctx, false);
7188    }
7189    cur.pos += consumed;
7190    classify_numeric_text(&text).map_err(|msg| cur.err(msg))
7191}
7192
7193/// Full expression with the top-level boundary rejection (mirrors
7194/// `parse_expr`): a stray `UnsignedIntBoundary` that no unary `-`
7195/// consumed is an overflow error.
7196fn parse_expr_checked(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7197    let expr = parse_expr_or(cur, ctx)?;
7198    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
7199        return Err(cur.err("integer overflow: 9223372036854775808 exceeds i64::MAX"));
7200    }
7201    Ok(expr)
7202}
7203
7204/// List literal over a bracket group's contents: the shared bracket
7205/// core (see [`parse_bracket_list`]) in `Expr` mode. Expression
7206/// positions fail loudly instead of missing, so `None` is unreachable.
7207fn parse_list_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7208    parse_bracket_list(inner, stmt, ctx, BracketItems::Expr)
7209        .map(|list| list.expect("expression lists fail loudly, never miss"))
7210}
7211
7212/// Map literal attempt over a brace group's contents: comma-separated
7213/// `key: value` entries with `gap` (never newline) around the colon.
7214/// Any entry failing the shape is not a map: the caller reports the
7215/// deferred block slice (the grammar tries `block` next, which fails
7216/// the same inputs at this stage).
7217/// Marker message for a map entry run that ends without a comma
7218/// where another entry follows. Matched by exact equality in
7219/// [`parse_map_or_block`], never by prefix, so wording changes stay
7220/// local to this const and its one reader.
7221const MISSING_MAP_COMMA_MSG: &str = "missing comma between map entries";
7222
7223fn parse_map_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7224    let mut entries = Vec::new();
7225    // Empty (or blank/comment-only) braces are an empty map.
7226    if inner
7227        .iter()
7228        .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
7229    {
7230        return Ok(Expr::Map(vec![]));
7231    }
7232    for part in split_top_commas(inner) {
7233        let mut sub = Cursor::expr(part, stmt);
7234        sub.skip_gap_nl();
7235        let (key, val) = parse_map_entry(&mut sub, ctx, stmt)?;
7236        sub.skip_gap_nl();
7237        if !sub.done() {
7238            return Err(map_trailing_error(&sub, ctx, stmt));
7239        }
7240        entries.push((key, val));
7241    }
7242    Ok(Expr::Map(entries))
7243}
7244
7245/// One `key: value` map entry: string, block-string, or bare key,
7246/// a colon, then a full checked expression. Every failure reads
7247/// `not a map literal` exactly like the old inline loop, so only
7248/// the trailing rule changes the surface.
7249fn parse_map_entry(
7250    sub: &mut Cursor,
7251    ctx: &ParseCtx,
7252    stmt: usize,
7253) -> Result<(String, Expr), TokenError> {
7254    let key = match sub.toks.get(sub.pos).map(|t| &t.kind) {
7255        Some(TokKind::Str { text, .. }) => {
7256            let key = text.clone();
7257            sub.pos += 1;
7258            key
7259        }
7260        Some(TokKind::BlockStr(full)) => {
7261            let key = crate::command::lower_block_string(full);
7262            sub.pos += 1;
7263            key
7264        }
7265        Some(TokKind::Word(_)) | Some(TokKind::Punct('-')) | Some(TokKind::Punct('/')) => {
7266            map_bare_key(sub)?
7267        }
7268        _ => return Err(sub.err("not a map literal")),
7269    };
7270    sub.skip_gap();
7271    if !sub.eat_punct(':') {
7272        return Err(sub.err("not a map literal"));
7273    }
7274    let val = parse_expr_checked(sub, ctx)?;
7275    reject_boundary(&lowering_ctx(stmt), &val).map_err(|e| sub.err(e.to_string()))?;
7276    Ok((key, val))
7277}
7278
7279/// Trailing content after a complete map entry: stamps the
7280/// offending token and names the likely missing comma when the
7281/// remainder parses as another entry. Anything else keeps the old
7282/// `not a map literal` text. Error-path only.
7283fn map_trailing_error(sub: &Cursor, ctx: &ParseCtx, stmt: usize) -> TokenError {
7284    let (line, col) = sub
7285        .toks
7286        .get(sub.pos)
7287        .map(|t| (t.line, t.col))
7288        .unwrap_or((0, 0));
7289    let mut probe = Cursor::expr(&sub.toks[sub.pos.min(sub.toks.len())..], stmt);
7290    probe.skip_gap_nl();
7291    if parse_map_entry(&mut probe, ctx, stmt).is_ok() {
7292        return TokenError {
7293            diagnostic: None,
7294            hint: None,
7295            stmt,
7296            line,
7297            col,
7298            msg: MISSING_MAP_COMMA_MSG.to_string(),
7299            kind: None,
7300        };
7301    }
7302    sub.err("not a map literal")
7303}
7304
7305/// Bare map key: joint `-/.'/'`-run, mirroring the bare-word charset
7306/// (no bool/numeric classification: keys are always strings).
7307fn map_bare_key(sub: &mut Cursor) -> Result<String, TokenError> {
7308    let mut out = String::new();
7309    if matches!(
7310        sub.toks.get(sub.pos).map(|t| &t.kind),
7311        Some(TokKind::Punct('-'))
7312    ) {
7313        out.push('-');
7314        sub.pos += 1;
7315    }
7316    // Leading `/` reads literally too (the bare-word shape admits `/`
7317    // anywhere: `{/a: 1}`, `{//c: 1}`); the joint loop below
7318    // continues the run.
7319    if matches!(
7320        sub.toks.get(sub.pos).map(|t| &t.kind),
7321        Some(TokKind::Punct('/'))
7322    ) {
7323        out.push('/');
7324        sub.pos += 1;
7325    }
7326    match sub.toks.get(sub.pos).map(|t| &t.kind) {
7327        Some(TokKind::Word(w)) => {
7328            out.push_str(w);
7329            sub.pos += 1;
7330        }
7331        // A leading `/` above already started the run; anything
7332        // else still needs a word head.
7333        _ if !out.is_empty() => {}
7334        _ => return Err(sub.err("not a map literal")),
7335    }
7336    while let Some(t) = sub.toks.get(sub.pos) {
7337        if !t.joint {
7338            break;
7339        }
7340        match &t.kind {
7341            TokKind::Word(w) => {
7342                out.push_str(w);
7343                sub.pos += 1;
7344            }
7345            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
7346                out.push(*c);
7347                sub.pos += 1;
7348            }
7349            _ => break,
7350        }
7351    }
7352    if out.contains('\\') {
7353        return Err(sub.err("unexpected escape in map key"));
7354    }
7355    Ok(out)
7356}
7357
7358/// Map-or-block over a brace group's contents: maps parse literally;
7359/// anything else is an inline block (`Expr::Block` over the body
7360/// steps, scopes unmarked like every braced body).
7361fn parse_map_or_block(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7362    match parse_map_literal(inner, stmt, ctx) {
7363        Ok(map) => Ok(map),
7364        // A detected missing comma is never a block: its `key:`
7365        // remainder cannot parse as a statement (a `name: "a"` line
7366        // fails as `unknown command`), so the block path can only
7367        // misreport it. Surface the map error instead; every other
7368        // map failure keeps the block fallback exactly as before.
7369        Err(e) if e.msg == MISSING_MAP_COMMA_MSG => Err(e),
7370        Err(_) => Ok(Expr::Block(parse_body_steps(inner, stmt, ctx, false)?)),
7371    }
7372}
7373
7374/// Parse one standalone expression from lexed tokens (the
7375/// `parse_expression_str` entry point): a full tier parse with
7376/// top-level boundary rejection and full consumption.
7377pub(crate) fn parse_single_expr(
7378    toks: &[Tok],
7379    stmt: usize,
7380    ctx: &ParseCtx,
7381) -> Result<Expr, TokenError> {
7382    let mut cur = Cursor::expr(toks, stmt);
7383    let expr = parse_expr_checked(&mut cur, ctx)?;
7384    if !cur.done() {
7385        return Err(cur.err("unexpected text in expression"));
7386    }
7387    Ok(expr)
7388}
7389
7390/// Assignment `=`: the first depth-zero `=` neither glued to a
7391/// following `=` (`==`) nor glued after `!`/`<`/`>`/`=` (`!=`, `<=`,
7392/// `>=`, second of `==`). `<>` shape brackets own any `=` inside
7393/// them (field defaults), so LET annotations with defaults find the
7394/// real assignment. Glued-ness reads off the `=`'s own `joint` (gap
7395/// before it) and the follower's (gap after it). Anything else leaves
7396/// the statement bare (`LET $p: PIPE`), exactly where the grammar's
7397/// `"="` match fails.
7398fn find_assign_eq(body: &[Tok]) -> Option<usize> {
7399    let mut depth = 0usize;
7400    for (i, tok) in body.iter().enumerate() {
7401        match &tok.kind {
7402            TokKind::Punct('<') => depth += 1,
7403            TokKind::Punct('>') if depth > 0 => depth -= 1,
7404            TokKind::Punct('=') if depth == 0 => {
7405                let next_eq = body
7406                    .get(i + 1)
7407                    .is_some_and(|t| t.joint && matches!(&t.kind, TokKind::Punct('=')));
7408                let prev_op = tok.joint
7409                    && i > 0
7410                    && matches!(&body[i - 1].kind, TokKind::Punct('!' | '<' | '>' | '='));
7411                if !next_eq && !prev_op {
7412                    return Some(i);
7413                }
7414            }
7415            _ => {}
7416        }
7417    }
7418    None
7419}
7420
7421/// Render a type region joint-aware (`LIST< MAP >` keeps its gaps for
7422/// the shared canonicalizer, exactly like `type_tag.as_str()`).
7423fn render_type_region(toks: &[Tok], stmt: usize) -> Result<String, TokenError> {
7424    let mut out = String::new();
7425    for tok in toks {
7426        // Ridden newlines from multi-line `<...>` shapes carry no
7427        // output, so the shape canonicalizes exactly like one line.
7428        if matches!(&tok.kind, TokKind::Newline) {
7429            continue;
7430        }
7431        if !tok.joint && !out.is_empty() {
7432            out.push(' ');
7433        }
7434        match &tok.kind {
7435            TokKind::Word(w) => out.push_str(w),
7436            TokKind::Punct(c) => out.push(*c),
7437            TokKind::Str { text, quote } => {
7438                out.push(*quote);
7439                out.push_str(text);
7440                out.push(*quote);
7441            }
7442            TokKind::BlockStr(full) => out.push_str(full),
7443            _ => {
7444                return Err(TokenError {
7445                    diagnostic: None,
7446                    hint: None,
7447                    stmt,
7448                    msg: format!("malformed type in {KEYWORD_LET}"),
7449                    line: 0,
7450                    col: 0,
7451                    kind: None,
7452                });
7453            }
7454        }
7455    }
7456    if out.is_empty() {
7457        return Err(TokenError {
7458            diagnostic: None,
7459            hint: None,
7460            stmt,
7461            msg: format!(
7462                "{KEYWORD_LET} requires explicit type: {KEYWORD_LET} $var: {KEYWORD_TYPE} = <expr>"
7463            ),
7464            line: 0,
7465            col: 0,
7466            kind: None,
7467        });
7468    }
7469    Ok(crate::canonicalize_spelling(&out))
7470}
7471
7472fn expect_dollar_var(cur: &mut Cursor, msg: &str) -> Result<String, TokenError> {
7473    // Atomic `dollar_ident`: no gap between `$` and the name (the
7474    // enclosing statements are compound-atomic, so implicit spacing is
7475    // off and only explicit `gap`s admit whitespace).
7476    match cur.next() {
7477        Some(t) if matches!(&t.kind, TokKind::Punct(VAR_SIGIL_CHAR)) => {}
7478        _ => return Err(cur.err(msg)),
7479    }
7480    match cur.next() {
7481        Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
7482            match &t.kind {
7483                TokKind::Word(w) => Ok(w.clone()),
7484                _ => unreachable!(),
7485            }
7486        }
7487        _ => Err(cur.err(msg)),
7488    }
7489}
7490
7491/// Reject a qualified `$ALIAS::NAME` where a declaration or mutation
7492/// target stands: bindings declare plain locals, and module `CONST`s
7493/// are immutable (reads use `$ALIAS::NAME` in expressions).
7494/// Single owner for the qualified-target gate, shared by the binding
7495/// (`LET`/`CONST`) and reassignment (`$var = <expr>`) heads so all fail
7496/// with one message shape.
7497fn reject_qualified_target(cur: &Cursor, base: &str) -> Result<(), TokenError> {
7498    let first = matches!(
7499        cur.toks.get(cur.pos).map(|t| &t.kind),
7500        Some(TokKind::Punct(':'))
7501    ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
7502    let second = matches!(
7503        cur.toks.get(cur.pos + 1).map(|t| &t.kind),
7504        Some(TokKind::Punct(':'))
7505    ) && cur.toks.get(cur.pos + 1).is_some_and(|t| t.joint);
7506    if first && second {
7507        return Err(cur.err(format!(
7508            "cannot declare or assign ${base}::...: module values read as $ALIAS::NAME in expressions and are never binding targets"
7509        )));
7510    }
7511    Ok(())
7512}
7513
7514/// `LET`/`CONST` body: the keyword is already matched. Returns `None`
7515/// (miss to generic, which fails in lowering like the grammar's
7516/// committed `instruction`) when the shape cannot match any binding
7517/// form: no gapless `$var`, or no `:` after it
7518/// (every form needs `: TYPE`). Past that the shape is committed and
7519/// malformed tails fail loudly. `kw` selects the produced StepKind
7520/// family (`LET` or `CONST`) and the diagnostic spellings.
7521fn parse_let_body(
7522    body: &[Tok],
7523    stmt: usize,
7524    ctx: &ParseCtx,
7525) -> Result<Option<(StepKind, usize)>, TokenError> {
7526    parse_binding_body(body, stmt, ctx, KEYWORD_LET)
7527}
7528
7529/// `CONST` body: same shapes as `LET`, producing the `Const` family.
7530/// Miss semantics mirror [`parse_let_body`].
7531fn parse_const_body(
7532    body: &[Tok],
7533    stmt: usize,
7534    ctx: &ParseCtx,
7535) -> Result<Option<(StepKind, usize)>, TokenError> {
7536    parse_binding_body(body, stmt, ctx, KEYWORD_CONST)
7537}
7538
7539/// Shared `LET`/`CONST` body: the head keyword is already matched.
7540/// `kw` must be `KEYWORD_LET` or `KEYWORD_CONST`. Both take a `$var`
7541/// head; `CONST` additionally requires an uppercase name.
7542/// Single owner for the binding header: the `is_const` flag rides
7543/// straight into [`StepKind::Bind`], so no post-pass flips per form.
7544fn parse_binding_body(
7545    body: &[Tok],
7546    stmt: usize,
7547    ctx: &ParseCtx,
7548    kw: &'static str,
7549) -> Result<Option<(StepKind, usize)>, TokenError> {
7550    use crate::commands::BindRhs;
7551    let is_const = kw == KEYWORD_CONST;
7552    let mut cur = Cursor::expr(body, stmt);
7553    match cur.next() {
7554        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == kw) => {}
7555        _ => return Err(cur.err("unreachable")),
7556    }
7557    // Head: `$var` for both `LET` and `CONST`. `CONST` additionally
7558    // requires an uppercase name (see `validate_const_name`). The
7559    // keyword already committed to a binding, so a malformed head
7560    // fails loudly; only a non-name head misses to generic.
7561    let var = if is_const {
7562        cur.skip_gap();
7563        match cur.toks.get(cur.pos).map(|t| &t.kind) {
7564            Some(TokKind::Punct(VAR_SIGIL_CHAR)) => {
7565                let var = expect_dollar_var(
7566                    &mut cur,
7567                    "CONST requires a `$NAME` head: CONST $NAME: TYPE = ...",
7568                )?;
7569                reject_qualified_target(&cur, &var)?;
7570                validate_const_name(ctx, &cur, &var)?;
7571                var
7572            }
7573            Some(TokKind::Word(_)) => {
7574                return Err(
7575                    cur.err(format!("{KEYWORD_CONST} requires `$`: write {KEYWORD_CONST} $NAME: {KEYWORD_TYPE} = ... (never bare)"))
7576                );
7577            }
7578            _ => return Ok(None),
7579        }
7580    } else {
7581        // No `$var`: no binding form can match (miss, never a hard fail).
7582        let var = match expect_dollar_var(&mut cur, &format!("{kw} requires a variable")) {
7583            Ok(var) => var,
7584            Err(_) => return Ok(None),
7585        };
7586        reject_qualified_target(&cur, &var)?;
7587        var
7588    };
7589    // The header allows gaps (comments, never newlines).
7590    cur.skip_gap();
7591    // No `:`: untyped bindings are rejected outright. Every binding is
7592    // typed; the old miss-to-generic path only hid that behind a
7593    // rambling "invalid syntax" message. (FOR already does this.)
7594    let head_example = if is_const { "$NAME" } else { "$var" };
7595    if !cur.eat_punct(':') {
7596        return Err(TokenError {
7597            diagnostic: None,
7598            hint: None,
7599            stmt,
7600            msg: format!(
7601                "{kw} requires explicit types: {kw} {head_example}: {KEYWORD_TYPE} = <expr>"
7602            ),
7603            line: 0,
7604            col: 0,
7605            kind: Some(ParseErrorKind::InvalidSyntax {
7606                command: kw.to_string(),
7607            }),
7608        });
7609    }
7610    // Type region runs to the depth-zero assignment `=`; `<>`
7611    // shapes own any `=` inside them (field defaults).
7612    let type_start = cur.pos;
7613    let assign = find_assign_eq(&body[type_start..]).map(|i| i + type_start);
7614    let Some(eq) = assign else {
7615        // Bare `$p: PIPE` mints a fresh pipe and ends with the
7616        // type word (trailing elements loop on, probed); every other
7617        // bare type is a validation error, mirroring the grammar.
7618        if matches!(
7619            body.get(type_start).map(|t| &t.kind),
7620            Some(TokKind::Word(w)) if w == crate::TypeTag::Pipe.name()
7621        ) {
7622            let kind = StepKind::Bind {
7623                var: var.clone(),
7624                decl_type: crate::TypeTag::Pipe.name().to_string(),
7625                is_const,
7626                rhs: BindRhs::Expr(Expr::FreshPipe),
7627            };
7628            return Ok(Some((kind, type_start + 1)));
7629        }
7630        return Err(cur.err(format!(
7631            "{kw} requires an expression: {kw} {head_example}: TYPE = <expr> (only {kw} {head_example}: PIPE omits the initializer)"
7632        )));
7633    };
7634    let decl_type = render_type_region(&body[type_start..eq], stmt)?;
7635    let (kind, rhs_used) = parse_let_rhs(&body[eq + 1..], var, decl_type, stmt, ctx, is_const)?;
7636    Ok(Some((kind, eq + 1 + rhs_used)))
7637}
7638
7639/// Collision gate for `CONST` names: uppercase plus keywords,
7640/// commands, types, and workspace targets. `FUNC` names and host
7641/// functions live in separate namespaces and may share a spelling
7642/// with a private `CONST`.
7643/// Same-scope `LET`/`CONST` duplicates rely on the static gate so
7644/// guard-disjoint declarations stay legal.
7645fn validate_const_name(ctx: &ParseCtx, cur: &Cursor, name: &str) -> Result<(), TokenError> {
7646    let _ = ctx;
7647    // Single gate for the declaration spelling: uppercase plus
7648    // freedom from reserved words (see [`crate::constants`]).
7649    if !crate::constants::is_const_name(name) {
7650        return Err(cur.err(format!(
7651            "{KEYWORD_CONST} names must be UPPERCASE: got `{name}`"
7652        )));
7653    }
7654    if crate::commands::is_reserved_const_name(name) {
7655        return Err(cur.err(format!(
7656            "CONST {name} collides with reserved keyword `{name}`"
7657        )));
7658    }
7659    Ok(())
7660}
7661
7662/// LET right-hand side dispatch, mirroring the grammar order
7663/// (`let_async`, then `let_capture`, then `let_statement`):
7664/// `WITH_IO`-led lines branch async/sync like
7665/// `parse_let_async_statement_from_pair`, `ASYNC`-led lines spawn
7666/// tasks, `TIMEOUT`-led lines capture through the wrapper,
7667/// `AWAIT $v` captures, RUN exec-form captures, known commands
7668/// capture through the generic parser (lowering failures fatal,
7669/// exactly like the committed grammar alternative), and anything
7670/// else parses as an expression (unknown leads included). Returns
7671/// the kind and RHS tokens consumed: captures ending in structural
7672/// pairs leave trailing elements for the caller.
7673fn parse_let_rhs(
7674    rhs: &[Tok],
7675    var: String,
7676    decl_type: String,
7677    stmt: usize,
7678    ctx: &ParseCtx,
7679    is_const: bool,
7680) -> Result<(StepKind, usize), TokenError> {
7681    // Leading gap comments vanish like the `=` gap (but a `//`/`#`
7682    // to end of input leaves no expression, failing).
7683    let mut lead = Cursor::expr(rhs, stmt);
7684    lead.skip_gap();
7685    let (rhs, skipped) = (&rhs[lead.pos..], lead.pos);
7686    let head_word = match rhs.first().map(|t| &t.kind) {
7687        Some(TokKind::Word(w)) => Some(w.clone()),
7688        _ => None,
7689    };
7690    // `WITH_IO`-led lines share `let_async_statement` with the
7691    // `ASYNC` forms (the grammar claims every WITH_IO-led LET
7692    // there); shape misses fall through to generic below.
7693    if head_word.as_deref() == Some(KEYWORD_WITH_IO)
7694        && let Some(found) =
7695            try_let_with_io_rhs(rhs, var.clone(), decl_type.clone(), stmt, ctx, is_const)?
7696    {
7697        let (kind, used) = found;
7698        return Ok((kind, skipped + used));
7699    }
7700    // `ASYNC`-led lines (with followers; alone they commit to the
7701    // generic path like the grammar, failing in lowering) spawn
7702    // background tasks. No `WITH_IO` scan here (probed: the LET
7703    // path accepts what statement `ASYNC` rejects).
7704    if head_word.as_deref() == Some(KEYWORD_ASYNC) && rhs.len() > 1 {
7705        let (kind, used) = parse_let_async_rhs(&rhs[1..], var, decl_type, stmt, ctx, is_const)?;
7706        return Ok((kind, skipped + 1 + used));
7707    }
7708    // `TIMEOUT`-led lines capture through the wrapper (shape misses
7709    // fall through to generic, which fails in lowering).
7710    if head_word.as_deref() == Some(KEYWORD_TIMEOUT)
7711        && let Some((kind, used)) = parse_timeout_single(rhs, 0, stmt, ctx)?
7712    {
7713        let span = lowering_ctx(stmt);
7714        crate::commands::reject_async_in_capture(&span, &kind).map_err(|e| lower_err(stmt, e))?;
7715        crate::commands::reject_pipe_stdout_in_capture(&span, &kind)
7716            .map_err(|e| lower_err(stmt, e))?;
7717        return Ok((
7718            StepKind::Bind {
7719                var,
7720                decl_type,
7721                is_const,
7722                rhs: BindRhs::Capture(Box::new(kind)),
7723            },
7724            skipped + used,
7725        ));
7726    }
7727    // `AWAIT $v` captures the task output (`$`+name ride gapless in
7728    // this atomic position, like the grammar). Anything else
7729    // `AWAIT`-led goes generic below (lowering fails it, probed).
7730    if head_word.as_deref() == Some(KEYWORD_AWAIT)
7731        && rhs.len() == 3
7732        && let (Some(dollar), Some(task)) = (rhs.get(1), rhs.get(2))
7733        && matches!(&dollar.kind, TokKind::Punct(VAR_SIGIL_CHAR))
7734        && task.joint
7735        && let TokKind::Word(task_var) = &task.kind
7736        && is_ident_word(task_var)
7737    {
7738        return Ok((
7739            StepKind::Bind {
7740                var,
7741                decl_type,
7742                is_const,
7743                rhs: BindRhs::Await {
7744                    task_var: task_var.clone(),
7745                },
7746            },
7747            skipped + 3,
7748        ));
7749    }
7750    // RUN exec form captures the structured argv (gapped bracket;
7751    // a joint bracket falls through to generic, which fails it in
7752    // lowering).
7753    if head_word.as_deref() == Some(KEYWORD_RUN)
7754        && matches!(
7755            rhs.get(1).map(|t| (&t.kind, t.joint)),
7756            Some((
7757                TokKind::Group {
7758                    delim: GroupDelim::Bracket,
7759                    ..
7760                },
7761                false
7762            ))
7763        )
7764        && rhs.len() == 2
7765    {
7766        let inner = match &rhs[1].kind {
7767            TokKind::Group { inner, .. } => inner.clone(),
7768            _ => unreachable!(),
7769        };
7770        // Non-map blocks miss the exec shape; fall through below
7771        // (known-command capture, then expression), mirroring the
7772        // grammar's ordered alternatives.
7773        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
7774            let kind =
7775                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
7776            return Ok((
7777                StepKind::Bind {
7778                    var,
7779                    decl_type,
7780                    is_const,
7781                    rhs: BindRhs::Capture(Box::new(kind)),
7782                },
7783                skipped + 2,
7784            ));
7785        }
7786    }
7787    // File `IMPORT ["path" AS ALIAS]` (#115) captures the imported
7788    // pipeline's `RETURN` value like a call (`LET $r: STRING = IMPORT ...`
7789    // lowers to `AssignCapture`): exactly one file entry, no modules.
7790    // Anything else shaped like an import is a hard error; shape misses
7791    // fall through to generic below, which fails them in lowering.
7792    if head_word.as_deref() == Some(KEYWORD_IMPORT)
7793        && let Some((path, alias, used)) = parse_single_file_import(rhs, 0, stmt, ctx)?
7794    {
7795        return Ok((
7796            StepKind::Bind {
7797                var,
7798                decl_type,
7799                is_const,
7800                rhs: BindRhs::Capture(Box::new(StepKind::ImportFile { path, alias })),
7801            },
7802            skipped + used,
7803        ));
7804    }
7805    // Known-command leads capture through the generic parser
7806    // (lowering failures are fatal here, exactly like the committed
7807    // grammar alternative: probed wrapper-alone and `ISOLATED`-led
7808    // shapes error in lowering); unknown leads parse as expressions.
7809    match &head_word {
7810        Some(head) if is_known_command(head) => {
7811            let (cmd, used) = parse_inner_command(rhs, stmt, ctx)?;
7812            let span = lowering_ctx(stmt);
7813            crate::commands::reject_async_in_capture(&span, &cmd)
7814                .map_err(|e| lower_err(stmt, e))?;
7815            crate::commands::reject_pipe_stdout_in_capture(&span, &cmd)
7816                .map_err(|e| lower_err(stmt, e))?;
7817            // `INHERIT_ENV`-led lines land here (generic): the
7818            // nesting check rejects them (probed).
7819            crate::commands::reject_nested_inherit_env(&span, &cmd)
7820                .map_err(|e| lower_err(stmt, e))?;
7821            return Ok((
7822                StepKind::Bind {
7823                    var,
7824                    decl_type,
7825                    is_const,
7826                    rhs: BindRhs::Capture(Box::new(cmd)),
7827                },
7828                skipped + used,
7829            ));
7830        }
7831        _ => {}
7832    }
7833    let mut cur = Cursor::expr(rhs, stmt);
7834    let expr = parse_expr_checked(&mut cur, ctx)?;
7835    let used = skipped + cur.pos;
7836    Ok((
7837        StepKind::Bind {
7838            var,
7839            decl_type,
7840            is_const,
7841            rhs: BindRhs::Expr(expr),
7842        },
7843        used,
7844    ))
7845}
7846
7847/// `WITH_IO`-led LET right-hand side, mirroring
7848/// `parse_let_async_statement_from_pair`'s `with_io_command` branch:
7849/// wrapping `ASYNC` binds a pipe-wired background task (multi-step
7850/// blocks fail loudly), wrapping a sync command captures its stdout
7851/// (async bodies and `stdout` pipes fail loudly), and a bare
7852/// bracket fails validation. `None` on shape miss (bad bracket:
7853/// the caller goes generic, which fails in lowering).
7854fn try_let_with_io_rhs(
7855    rhs: &[Tok],
7856    var: String,
7857    decl_type: String,
7858    stmt: usize,
7859    ctx: &ParseCtx,
7860    is_const: bool,
7861) -> Result<Option<(StepKind, usize)>, TokenError> {
7862    let kw = if is_const { KEYWORD_CONST } else { KEYWORD_LET };
7863    let bracket = match rhs.get(1) {
7864        Some(t)
7865            if !t.joint
7866                && matches!(
7867                    &t.kind,
7868                    TokKind::Group {
7869                        delim: GroupDelim::Bracket,
7870                        ..
7871                    }
7872                ) =>
7873        {
7874            t
7875        }
7876        _ => return Ok(None),
7877    };
7878    let inner = match &bracket.kind {
7879        TokKind::Group { inner, .. } => inner.clone(),
7880        _ => unreachable!(),
7881    };
7882    let bindings = match parse_io_bindings(&inner, stmt, ctx)? {
7883        Some(bindings) => bindings,
7884        None => return Ok(None),
7885    };
7886    let fail = |msg: String| TokenError {
7887        diagnostic: None,
7888        hint: None,
7889        stmt,
7890        msg,
7891        line: 0,
7892        col: 0,
7893        kind: None,
7894    };
7895    let rest = &rhs[2..];
7896    let Some(first) = rest.first() else {
7897        // Bare bracket: the grammar's committed validation error.
7898        return Err(fail(format!(
7899            "{kw} $var: TYPE = WITH_IO requires an ASYNC command (e.g. {kw} $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7900        )));
7901    };
7902    if first.joint {
7903        // The inner rides after a `sep`: joint followers miss the
7904        // shape and fail validation like the grammar's bare bracket.
7905        return Err(fail(format!(
7906            "{kw} $var: TYPE = WITH_IO requires an ASYNC command (e.g. {kw} $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7907        )));
7908    }
7909    if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_ASYNC) {
7910        // `WITH_IO [..] ASYNC <single|block>`: the bindings apply
7911        // inside the task thread (same shape as a one-step body
7912        // holding one `WITH_IO` step, which the runtime supports).
7913        // A bare `ASYNC` goes generic and fails in lowering
7914        // (`unknown command: ASYNC`, probed).
7915        let after = &rest[1..];
7916        if after.is_empty() {
7917            // Bare `ASYNC`: the grammar commits to `instruction`
7918            // and lowering fails it (`unknown command: ASYNC`,
7919            // probed); mirror by running generic, staying failed
7920            // even under a lenient dispatcher.
7921            match parse_inner_command(&rest[..1], stmt, ctx) {
7922                Err(e) => return Err(e),
7923                Ok(_) => {
7924                    return Err(fail(format!(
7925                        "{kw} $var: HANDLE<T> = ASYNC requires a body"
7926                    )));
7927                }
7928            }
7929        }
7930        if let Some(second) = after.first()
7931            && matches!(
7932                &second.kind,
7933                TokKind::Group {
7934                    delim: GroupDelim::Brace,
7935                    ..
7936                }
7937            )
7938            && !is_template_brace(second)
7939        {
7940            let brace_inner = match &second.kind {
7941                TokKind::Group { inner, .. } => inner.clone(),
7942                _ => unreachable!(),
7943            };
7944            let body = parse_body_steps(&brace_inner, stmt, ctx, false)?;
7945            if body.len() != 1 {
7946                return Err(fail(format!(
7947                    "{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"
7948                )));
7949            }
7950            let wrapped = Step {
7951                guard: None,
7952                kind: StepKind::WithIo {
7953                    bindings,
7954                    cmd: Box::new(
7955                        body.into_iter()
7956                            .next()
7957                            .ok_or_else(|| {
7958                                fail(format!("{KEYWORD_LET} $var: {HANDLE_TYPE_NAME}<T> = {KEYWORD_ASYNC} requires a body"))
7959                            })?
7960                            .kind,
7961                    ),
7962                },
7963                scope_enter: 0,
7964                scope_exit: 0,
7965                line: 0,
7966                col: 0,
7967            };
7968            return Ok(Some((
7969                StepKind::Bind {
7970                    var,
7971                    decl_type,
7972                    is_const,
7973                    rhs: BindRhs::Async(vec![wrapped]),
7974                },
7975                2 + 2,
7976            )));
7977        }
7978        if after.first().is_some_and(|t| t.joint) {
7979            // Joint followers miss the inner `sep`: same validation
7980            // error as the bare bracket.
7981            return Err(fail(
7982                "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7983                    .to_string(),
7984            ));
7985        }
7986        let (cmd, used) = parse_single_inner(
7987            rest,
7988            1,
7989            stmt,
7990            ctx,
7991            InnerRules {
7992                allow_await: false,
7993                allow_with_io: false,
7994            },
7995        )?;
7996        let wrapped = Step {
7997            guard: None,
7998            kind: StepKind::WithIo {
7999                bindings,
8000                cmd: Box::new(cmd),
8001            },
8002            scope_enter: 0,
8003            scope_exit: 0,
8004            line: 0,
8005            col: 0,
8006        };
8007        let kind = StepKind::Bind {
8008            var,
8009            decl_type,
8010            is_const,
8011            rhs: BindRhs::Async(vec![wrapped]),
8012        };
8013        let span = lowering_ctx(stmt);
8014        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
8015        return Ok(Some((kind, 2 + 1 + used)));
8016    }
8017    if matches!(
8018        &first.kind,
8019        TokKind::Group {
8020            delim: GroupDelim::Brace,
8021            ..
8022        }
8023    ) {
8024        // A brace is no sync command: same validation error (probed).
8025        return Err(fail(format!(
8026            "{kw} $var: TYPE = WITH_IO requires an ASYNC command (e.g. {kw} $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
8027        )));
8028    }
8029    // Sync inner: capture with the shared checks (the capture sink
8030    // owns stdout; async never runs inline).
8031    let (cmd, used) = parse_single_inner(
8032        rest,
8033        0,
8034        stmt,
8035        ctx,
8036        InnerRules {
8037            allow_await: false,
8038            allow_with_io: true,
8039        },
8040    )?;
8041    let span = lowering_ctx(stmt);
8042    if crate::commands::has_stdout_pipe(&bindings) {
8043        return Err(fail(format!(
8044            "{kw} capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
8045        )));
8046    }
8047    crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| lower_err(stmt, e))?;
8048    Ok(Some((
8049        StepKind::Bind {
8050            var,
8051            decl_type,
8052            is_const,
8053            rhs: BindRhs::Capture(Box::new(StepKind::WithIo {
8054                bindings,
8055                cmd: Box::new(cmd),
8056            })),
8057        },
8058        2 + used,
8059    )))
8060}
8061
8062/// `ASYNC`-led LET right-hand side (the tokens after `ASYNC`):
8063/// a block or single command becomes the task body. No `WITH_IO`
8064/// scan (probed: this path accepts what statement `ASYNC`
8065/// rejects); nesting still fails loudly through the shared check.
8066fn parse_let_async_rhs(
8067    rest: &[Tok],
8068    var: String,
8069    decl_type: String,
8070    stmt: usize,
8071    ctx: &ParseCtx,
8072    is_const: bool,
8073) -> Result<(StepKind, usize), TokenError> {
8074    let Some(first) = rest.first() else {
8075        return Err(TokenError {
8076            diagnostic: None,
8077            hint: None,
8078            stmt,
8079            msg: format!("binding $var: {HANDLE_TYPE_NAME}<T> = {KEYWORD_ASYNC} requires a body"),
8080            line: 0,
8081            col: 0,
8082            kind: None,
8083        });
8084    };
8085    if matches!(
8086        &first.kind,
8087        TokKind::Group {
8088            delim: GroupDelim::Brace,
8089            ..
8090        }
8091    ) && !is_template_brace(first)
8092    {
8093        let inner = match &first.kind {
8094            TokKind::Group { inner, .. } => inner.clone(),
8095            _ => unreachable!(),
8096        };
8097        let body = parse_body_steps(&inner, stmt, ctx, false)?;
8098        let kind = StepKind::Bind {
8099            var,
8100            decl_type,
8101            is_const,
8102            rhs: BindRhs::Async(body),
8103        };
8104        let span = lowering_ctx(stmt);
8105        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
8106        return Ok((kind, 1));
8107    }
8108    if first.joint {
8109        return Err(TokenError {
8110            diagnostic: None,
8111            hint: None,
8112            stmt,
8113            msg: format!("binding $var: {HANDLE_TYPE_NAME}<T> = {KEYWORD_ASYNC} requires a body"),
8114            line: 0,
8115            col: 0,
8116            kind: None,
8117        });
8118    }
8119    let (cmd, used) = parse_single_inner(
8120        rest,
8121        0,
8122        stmt,
8123        ctx,
8124        InnerRules {
8125            allow_await: false,
8126            allow_with_io: false,
8127        },
8128    )?;
8129    let kind = StepKind::Bind {
8130        var,
8131        decl_type,
8132        is_const,
8133        rhs: BindRhs::Async(vec![Step {
8134            guard: None,
8135            kind: cmd,
8136            scope_enter: 0,
8137            scope_exit: 0,
8138            line: 0,
8139            col: 0,
8140        }]),
8141    };
8142    let span = lowering_ctx(stmt);
8143    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
8144    Ok((kind, used))
8145}
8146
8147fn parse_set_body(
8148    body: &[Tok],
8149    stmt: usize,
8150    ctx: &ParseCtx,
8151) -> Result<(StepKind, usize), TokenError> {
8152    let mut cur = Cursor::expr(body, stmt);
8153    if matches!(
8154        cur.toks.get(cur.pos).map(|t| &t.kind),
8155        Some(TokKind::Punct(VAR_SIGIL_CHAR))
8156    ) {
8157        let var = expect_dollar_var(&mut cur, "mutation requires a variable: $var = <expr>")?;
8158        reject_qualified_target(&cur, &var)?;
8159        // Key paths never serve as mutation targets: without this,
8160        // `$M.a = ...` would drop `.a` when the head jumps to `=`
8161        // below and silently rebind the whole `$M`. Reads use key
8162        // paths in expressions; writes rebind the variable
8163        // (e.g. `$M = MAP_SET($M, "a", 2)`).
8164        if matches!(
8165            cur.toks.get(cur.pos).map(|t| &t.kind),
8166            Some(TokKind::Punct('.'))
8167        ) {
8168            let mut target = sigil_var(&var);
8169            let mut p = cur.pos;
8170            loop {
8171                let dot = matches!(cur.toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('.')));
8172                let word = match cur.toks.get(p + 1).map(|t| &t.kind) {
8173                    Some(TokKind::Word(w)) if is_key_segment(w) => w.clone(),
8174                    _ => break,
8175                };
8176                if !dot {
8177                    break;
8178                }
8179                target.push('.');
8180                target.push_str(&word);
8181                p += 2;
8182            }
8183            return Err(cur.err(format!(
8184                "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))",
8185                example = sigil_var(&var),
8186            )));
8187        }
8188        let assign = find_assign_eq(&body[cur.pos..]).map(|i| i + cur.pos);
8189        let eq = match assign {
8190            Some(eq) => eq,
8191            None => {
8192                return Err(cur.err("mutation requires a variable: $var = <expr>"));
8193            }
8194        };
8195        cur.pos = eq + 1;
8196        cur.skip_gap();
8197        let expr = parse_expr_checked(&mut cur, ctx)?;
8198        return Ok((StepKind::Set { var, expr }, cur.pos));
8199    }
8200    // Bare words are literal text, never variable targets: only
8201    // `$var = <expr>` mutates.
8202    Err(cur.err("mutation requires a variable: $var = <expr>"))
8203}
8204
8205fn parse_return_body(
8206    body: &[Tok],
8207    stmt: usize,
8208    ctx: &ParseCtx,
8209) -> Result<(StepKind, usize), TokenError> {
8210    let mut cur = Cursor::expr(body, stmt);
8211    match cur.next() {
8212        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_RETURN) => {}
8213        _ => return Err(cur.err("unreachable")),
8214    }
8215    if cur.done() {
8216        return Ok((
8217            StepKind::Return {
8218                expr: Box::new(Expr::Literal(Value::string(String::new()))),
8219                is_bare: true,
8220            },
8221            cur.pos,
8222        ));
8223    }
8224    let expr = parse_expr_checked(&mut cur, ctx)?;
8225    Ok((
8226        StepKind::Return {
8227            expr: Box::new(expr),
8228            is_bare: false,
8229        },
8230        cur.pos,
8231    ))
8232}
8233
8234/// Lower one statement to steps through the element loop: the
8235/// statement guard attaches to the first element only (trailing
8236/// elements ride guardless, probed): the pending guard clears after
8237/// the first command token.
8238fn lower_stmt_steps(
8239    stmt: &Stmt,
8240    idx: usize,
8241    ctx: &ParseCtx,
8242    in_block: bool,
8243    mark: bool,
8244) -> Result<Vec<Step>, TokenError> {
8245    let guard = parse_guard_groups(&stmt.guard, idx)?;
8246    // Statement-head braces route here (mid-run braces fail inside
8247    // the element loop): templates and guardless/bare blocks fail
8248    // loudly; guarded braces open guard blocks (top level) or the
8249    // nested quirk (in bodies).
8250    let mut steps = if starts_brace(&stmt.body) {
8251        parse_brace_head(stmt, guard, idx, ctx, in_block, mark)?
8252    } else {
8253        parse_elements(&stmt.body, idx, ctx, guard, in_block)?
8254    };
8255    // Stamp the statement's source position on every directly
8256    // produced step still missing one. Nested body steps were stamped
8257    // by their own statements during recursion, so only direct
8258    // products are claimed here; inner statements keep their own
8259    // lines and columns.
8260    for step in &mut steps {
8261        if step.line == 0 {
8262            step.line = stmt.line;
8263        }
8264        if step.col == 0 {
8265            step.col = stmt.col;
8266        }
8267    }
8268    // Qualify bare placeholder calls (`{{ NAME(args) }}`) through
8269    // the shared static resolver, so templates obey exactly the
8270    // statement-position scope rule. Nested bodies were already
8271    // qualified by their own recursive statements with their own
8272    // frames, so only direct products are visited here. Both
8273    // `Arg::String` fragments (via `walk_raw_strings_mut`) and
8274    // `Expr::Literal` strings (LET/SET/RETURN/call args/list/map
8275    // literals/parenthesized args) are qualified: expression
8276    // positions expand through the same `expand_string` at runtime,
8277    // so they must see the same parse-time rewrite. `WithIo` and
8278    // `AssignCapture` box their inner command directly (no recursive
8279    // statement pass), so the helper descends into them; all other
8280    // bodies were already qualified with their own frames.
8281    // `Step.guards` carry no template text (`Guard::Attr` triples
8282    // evaluated via `guard_allows`, never expanded), so there is
8283    // nothing to qualify there.
8284    let mut failed: Option<TokenError> = None;
8285    for step in &mut steps {
8286        qualify_step_templates(step, ctx, idx, &mut failed);
8287        if failed.is_some() {
8288            break;
8289        }
8290    }
8291    if let Some(err) = failed {
8292        return Err(err);
8293    }
8294    Ok(steps)
8295}
8296
8297/// Qualify one direct statement product plus any boxed `WithIo` /
8298/// `AssignCapture` inner command (same scope frame, never a
8299/// recursive statement pass). Body vectors are skipped: their steps
8300/// were qualified by their own recursive statements.
8301fn qualify_step_templates(
8302    step: &mut Step,
8303    ctx: &ParseCtx,
8304    stmt: usize,
8305    failed: &mut Option<TokenError>,
8306) {
8307    qualify_kind_templates(&mut step.kind, ctx, stmt, failed);
8308}
8309
8310/// Qualify one `StepKind` plus boxed inner commands sharing the
8311/// same scope frame.
8312fn qualify_kind_templates(
8313    kind: &mut StepKind,
8314    ctx: &ParseCtx,
8315    stmt: usize,
8316    failed: &mut Option<TokenError>,
8317) {
8318    kind.walk_raw_strings_mut(&mut |text| {
8319        if failed.is_none() {
8320            match qualify_template_calls(text, ctx, stmt) {
8321                Ok(Some(rewritten)) => *text = rewritten,
8322                Ok(None) => {}
8323                Err(err) => *failed = Some(err),
8324            }
8325        }
8326    });
8327    if failed.is_some() {
8328        return;
8329    }
8330    kind.walk_exprs_mut(&mut |expr| {
8331        if failed.is_some() {
8332            return;
8333        }
8334        expr.walk_mut(&mut |node| {
8335            if failed.is_some() {
8336                return;
8337            }
8338            if let Expr::Literal(value) = node
8339                && let Some(text) = value.as_str()
8340            {
8341                match qualify_template_calls(text, ctx, stmt) {
8342                    Ok(Some(rewritten)) => {
8343                        *value = Value::string(rewritten);
8344                    }
8345                    Ok(None) => {}
8346                    Err(err) => *failed = Some(err),
8347                }
8348            }
8349        });
8350    });
8351    if failed.is_some() {
8352        return;
8353    }
8354    // Boxed single commands share the outer scope frame (no recursive
8355    // statement pass built them): qualify the inner kind directly.
8356    match kind {
8357        StepKind::WithIo { cmd, .. } => {
8358            qualify_kind_templates(cmd, ctx, stmt, failed);
8359        }
8360        StepKind::Bind {
8361            rhs: BindRhs::Capture(cmd),
8362            ..
8363        } => {
8364            qualify_kind_templates(cmd, ctx, stmt, failed);
8365        }
8366        _ => {}
8367    }
8368    if failed.is_some() {
8369        return;
8370    }
8371    // Single-command synthetic bodies share the outer frame: `TIMEOUT 5s
8372    // <cmd>`, `ISOLATED <cmd>`, `ASYNC <cmd>`, and `AssignAsync` wrappers
8373    // build their `body` inline via `parse_single_inner` with no recursive
8374    // `lower_stmt_steps` pass, so their one synthetic step needs this one.
8375    // Brace-delimited bodies are NEVER re-walked here: they were already
8376    // lowered via `parse_body_steps` with their own frames and statement
8377    // indices (mirroring `Expr::walk_mut` skipping `Expr::Block`), and
8378    // re-resolving under the outer frame would corrupt scope isolation
8379    // and error attribution. The match names only the synthetic carriers;
8380    // any other body (If/For/While/FuncDef/RemoteBlock/WithIoBlock) stays
8381    // exactly as its own recursive pass left it.
8382    match kind {
8383        StepKind::Timeout { body, .. }
8384        | StepKind::Isolated { body }
8385        | StepKind::AsyncBlock { body } => {
8386            for step in body.iter_mut() {
8387                if failed.is_some() {
8388                    return;
8389                }
8390                qualify_step_templates(step, ctx, stmt, failed);
8391            }
8392        }
8393        StepKind::Bind { rhs, .. } => match rhs {
8394            BindRhs::Async(body) => {
8395                for step in body.iter_mut() {
8396                    if failed.is_some() {
8397                        return;
8398                    }
8399                    qualify_step_templates(step, ctx, stmt, failed);
8400                }
8401            }
8402            BindRhs::Capture(_) | BindRhs::Expr(_) | BindRhs::Await { .. } => {}
8403        },
8404        _ => {}
8405    }
8406}
8407
8408/// Statement-head `{...}` dispatcher. Template braces fail (the
8409/// grammar strands them); guardless top-level braces fail; detached
8410/// or guardless in-body braces fail (no `block_start` in
8411/// `block_element`); guarded braces open a guard scope at top level
8412/// or mirror the nested quirk formula in bodies. Trailing elements
8413/// loop on guardless outside (like the grammar's continued line).
8414fn parse_brace_head(
8415    stmt: &Stmt,
8416    guard: Option<GuardExpr>,
8417    idx: usize,
8418    ctx: &ParseCtx,
8419    in_block: bool,
8420    mark: bool,
8421) -> Result<Vec<Step>, TokenError> {
8422    let brace = &stmt.body[0];
8423    if is_template_brace(brace) {
8424        return Err(TokenError {
8425            diagnostic: None,
8426            hint: None,
8427            stmt: idx,
8428            msg: "'{' without a pending guard".to_string(),
8429            line: 0,
8430            col: 0,
8431            kind: None,
8432        });
8433    }
8434    let inner = match &brace.kind {
8435        TokKind::Group { inner, .. } => inner.clone(),
8436        _ => unreachable!(),
8437    };
8438    if in_block {
8439        // Attached guarded braces only: pending holds all groups but
8440        // the last (the block's own), mirroring the pair structure.
8441        if guard.is_none() || stmt.brace_detached || stmt.guard.is_empty() {
8442            return Err(TokenError {
8443                diagnostic: None,
8444                hint: None,
8445                stmt: idx,
8446                msg: "unexpected '{' in block body".to_string(),
8447                line: 0,
8448                col: 0,
8449                kind: None,
8450            });
8451        }
8452        let n = stmt.guard.len();
8453        let mut pending = None;
8454        if n > 1 {
8455            pending = parse_guard_groups(&stmt.guard[..n - 1], idx)?;
8456        }
8457        let block_guard = parse_guard_groups(&stmt.guard[n - 1..n], idx)?.ok_or(TokenError {
8458            diagnostic: None,
8459            hint: None,
8460            stmt: idx,
8461            msg: "unexpected '{' in block body".to_string(),
8462            line: 0,
8463            col: 0,
8464            kind: None,
8465        })?;
8466        let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
8467        // Guard-block bodies propagate the ambient marking context
8468        // (top-level nesting marks; wrapper bodies never mark).
8469        // Quirk formula verbatim (including the dropped block guard
8470        // with inner guards, probed).
8471        for s in &mut steps {
8472            let inner_guard = s.guard.take();
8473            s.guard = Some(match (pending.clone(), inner_guard) {
8474                (Some(p), Some(e)) => GuardExpr::all(vec![p, e]),
8475                (Some(p), None) => GuardExpr::all(vec![p, block_guard.clone()]),
8476                (None, Some(e)) => e,
8477                (None, None) => block_guard.clone(),
8478            });
8479        }
8480        // Marking contexts bump each nesting level (probed top-level
8481        // double-block 2/2); wrapper bodies stay 0/0.
8482        // Trailing elements ride outside, unmarked.
8483        if mark {
8484            if let Some(first) = steps.first_mut() {
8485                first.scope_enter += 1;
8486            }
8487            if let Some(last) = steps.last_mut() {
8488                last.scope_exit += 1;
8489            }
8490        }
8491        // Trailing elements loop on guardless outside.
8492        if stmt.body.len() > 1 {
8493            let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
8494            steps.append(&mut rest);
8495        }
8496        return Ok(steps);
8497    }
8498    // Top level: guardless braces fail; guarded braces open a guard
8499    // scope (each step folds outer-then-inner with markers).
8500    let Some(outer) = guard else {
8501        return Err(TokenError {
8502            diagnostic: None,
8503            hint: None,
8504            stmt: idx,
8505            msg: "'{' without a pending guard".to_string(),
8506            line: 0,
8507            col: 0,
8508            kind: None,
8509        });
8510    };
8511    let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
8512    if steps.is_empty() {
8513        return Err(TokenError {
8514            diagnostic: None,
8515            hint: None,
8516            stmt: idx,
8517            msg: "guard block must contain at least one command".to_string(),
8518            line: 0,
8519            col: 0,
8520            kind: None,
8521        });
8522    }
8523    for s in &mut steps {
8524        let inner_guard = s.guard.take();
8525        s.guard = Some(match inner_guard {
8526            Some(e) => GuardExpr::all(vec![outer.clone(), e]),
8527            None => outer.clone(),
8528        });
8529    }
8530    if let Some(first) = steps.first_mut() {
8531        first.scope_enter += 1;
8532    }
8533    if let Some(last) = steps.last_mut() {
8534        last.scope_exit += 1;
8535    }
8536    if stmt.body.len() > 1 {
8537        let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
8538        steps.append(&mut rest);
8539    }
8540    Ok(steps)
8541}
8542
8543/// Parse consecutive elements to end of run (the grammar's
8544/// `element*`): structural pairs (calls, RUN-exec, await/cancel,
8545/// wrapper blocks) end mid-run and trailing elements form following
8546/// steps; instructions and expressions consume greedily to the end.
8547fn parse_elements(
8548    toks: &[Tok],
8549    stmt: usize,
8550    ctx: &ParseCtx,
8551    guard: Option<GuardExpr>,
8552    in_block: bool,
8553) -> Result<Vec<Step>, TokenError> {
8554    let mut steps = Vec::new();
8555    let mut pos = 0;
8556    // Statement guard: consumed by the first element that yields a
8557    // step. `IMPORT` yields none, so the guard leaks to the next
8558    // element (probed).
8559    let mut pending_guard: Option<GuardExpr> = guard;
8560    while pos < toks.len() {
8561        // Trailing gap comments between elements (`} #c`, `F("a")
8562        // /*c*/ ECHO`, `LET $x: INT = 1 //c` — the pair ended, so the
8563        // comment is silent like the grammar, never payload):
8564        // `#` and lexer `Comment` markers run to the run end, `//`
8565        // likewise (line comments eat `;` too, and runs hold no
8566        // newlines), `/* */` balances. Mid-run `#`/`/*` stay payload
8567        // text inside the generic path, which consumes everything
8568        // and never loops back here.
8569        if matches!(&toks[pos].kind, TokKind::Punct('#'))
8570            || matches!(&toks[pos].kind, TokKind::Comment(_))
8571        {
8572            break;
8573        }
8574        if matches!(&toks[pos].kind, TokKind::Punct('/')) && is_comment_open(toks, pos) {
8575            if matches!(
8576                toks.get(pos + 1).map(|t| &t.kind),
8577                Some(TokKind::Punct('/'))
8578            ) {
8579                break;
8580            }
8581            match skip_inline_comment(toks, pos) {
8582                Some(past) => {
8583                    pos = past;
8584                    continue;
8585                }
8586                None => {
8587                    return Err(TokenError {
8588                        diagnostic: None,
8589                        hint: None,
8590                        stmt,
8591                        msg: "unclosed block comment".to_string(),
8592                        line: 0,
8593                        col: 0,
8594                        kind: None,
8595                    });
8596                }
8597            }
8598        }
8599        // `IMPORT` statements update the import frames; module entries
8600        // emit no step (the guard leaks to the next element, probed,
8601        // unless this is top level, where a guarded module import
8602        // fails), while each file entry emits one `ImportFile` step
8603        // carrying the guard. Shape misses fall through to generic
8604        // (lowering fails them).
8605        if matches!(
8606            toks.get(pos).map(|t| &t.kind),
8607            Some(TokKind::Word(w)) if w == KEYWORD_IMPORT
8608        ) {
8609            // Unified statement form (#115): each entry validates hard
8610            // (unknown modules, bad aliases, templates, remote URLs);
8611            // module entries update the frame and emit no step, file
8612            // and harvest entries emit one step each, in source order.
8613            // A top-level guard on a statement with module entries fails
8614            // like the historical directive; file-only statements consume
8615            // the guard like any other element.
8616            if let Some(((modules, kinds), used)) =
8617                parse_import_statement(toks, pos, stmt, ctx, pending_guard.is_some())?
8618            {
8619                if !modules.is_empty() && !in_block && pending_guard.is_some() {
8620                    return Err(TokenError {
8621                        diagnostic: None,
8622                        hint: None,
8623                        stmt,
8624                        msg: format!("{KEYWORD_IMPORT} cannot be guarded"),
8625                        line: 0,
8626                        col: 0,
8627                        kind: None,
8628                    });
8629                }
8630                // Modules-only statements stay zero-step directives: the
8631                // guard leaks to the next element (probed). Anything with
8632                // file or harvest entries consumes it.
8633                let guard = if kinds.is_empty() {
8634                    None
8635                } else {
8636                    pending_guard.take()
8637                };
8638                for kind in kinds {
8639                    steps.push(Step {
8640                        guard: guard.clone(),
8641                        kind,
8642                        scope_enter: 0,
8643                        scope_exit: 0,
8644                        line: 0,
8645                        col: 0,
8646                    });
8647                }
8648                pos += used;
8649                continue;
8650            }
8651        }
8652        let guard = pending_guard.take();
8653        let (mut got, used) = parse_element_at(toks, pos, stmt, ctx, guard, in_block)?;
8654        if used == 0 {
8655            return Err(TokenError {
8656                diagnostic: None,
8657                hint: None,
8658                stmt,
8659                msg: "element consumed no input".to_string(),
8660                line: 0,
8661                col: 0,
8662                kind: None,
8663            });
8664        }
8665        steps.append(&mut got);
8666        pos += used;
8667    }
8668    Ok(steps)
8669}
8670
8671/// Parse one element at `pos`, returning built steps (guard already
8672/// assigned: `first_guard` for the first, folded per io-block inner
8673/// step) and tokens consumed.
8674fn parse_element_at(
8675    toks: &[Tok],
8676    pos: usize,
8677    stmt: usize,
8678    ctx: &ParseCtx,
8679    first_guard: Option<GuardExpr>,
8680    in_block: bool,
8681) -> Result<(Vec<Step>, usize), TokenError> {
8682    let step = |kind: StepKind| Step {
8683        guard: first_guard.clone(),
8684        kind,
8685        scope_enter: 0,
8686        scope_exit: 0,
8687        line: 0,
8688        col: 0,
8689    };
8690    let head_word = match toks.get(pos).map(|t| &t.kind) {
8691        Some(TokKind::Word(w)) => Some(w.clone()),
8692        _ => None,
8693    };
8694    // Mid-run `{...}` (after a call, wrapper block, ...): the
8695    // grammar strands it (`block_start` needs a pending guard or
8696    // `WITH_IO` wait, both consumed), so fail loudly. Statement-head
8697    // braces route through `lower_stmt_steps`, never here.
8698    if starts_brace(&toks[pos..]) {
8699        return Err(TokenError {
8700            diagnostic: None,
8701            hint: None,
8702            stmt,
8703            msg: "'{' without a pending guard".to_string(),
8704            line: 0,
8705            col: 0,
8706            kind: None,
8707        });
8708    }
8709    // LET/CONST/SET/RETURN heads parse with groups intact, then trailing
8710    // elements loop on (probed `LET $x: INT = 1 ECHO bye`). Binding shape
8711    // misses fall to generic (lowering fails them like a committed
8712    // `instruction` would, e.g. `LET foo`).
8713    if head_word.as_deref() == Some(KEYWORD_LET)
8714        && let Some((kind, used)) = parse_let_body(&toks[pos..], stmt, ctx)?
8715    {
8716        return Ok((vec![step(kind)], used));
8717    }
8718    if head_word.as_deref() == Some(KEYWORD_CONST)
8719        && let Some((kind, used)) = parse_const_body(&toks[pos..], stmt, ctx)?
8720    {
8721        return Ok((vec![step(kind)], used));
8722    }
8723    if matches!(
8724        toks.get(pos).map(|t| &t.kind),
8725        Some(TokKind::Punct(VAR_SIGIL_CHAR))
8726    ) {
8727        let (kind, used) = parse_set_body(&toks[pos..], stmt, ctx)?;
8728        return Ok((vec![step(kind)], used));
8729    }
8730    if head_word.as_deref() == Some(KEYWORD_RETURN) {
8731        let (kind, used) = parse_return_body(&toks[pos..], stmt, ctx)?;
8732        return Ok((vec![step(kind)], used));
8733    }
8734    // Calls route before heads (even known commands take the call
8735    // path with a joint paren, probed `ECHO("hi")`); the call ends
8736    // mid-run and trailing elements loop on (fixes the slice-4a
8737    // divergence, probed).
8738    if call_shape_at(toks, pos, true).is_some() {
8739        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8740        return Ok((vec![step(kind)], used));
8741    }
8742    if let Some(TokKind::Word(base)) = toks.get(pos).map(|t| &t.kind)
8743        && is_ident_word(base)
8744        && match_joint_qualified(toks, pos + 1).is_some()
8745    {
8746        // Qualified calls already returned above; anything else
8747        // starting `ALIAS::NAME` is a binding-target misuse.
8748        return Err(TokenError {
8749            diagnostic: None,
8750            hint: None,
8751            stmt,
8752            msg: "cannot declare or assign ALIAS::NAME: module values read as $ALIAS::NAME in expressions and are never binding targets".to_string(),
8753            line: 0,
8754            col: 0,
8755            kind: None,
8756        });
8757    }
8758    // Block statements (shape misses fall to generic, which fails
8759    // them in lowering like the grammar's committed `instruction`).
8760    // `BREAK`/`CONTINUE` take no args (structural, like the grammar):
8761    // each consumes one token and trailing elements loop on (probed
8762    // `BREAK ECHO hi`); a lone trailing word fails downstream like
8763    // the grammar's committed mismatch.
8764    match head_word.as_deref() {
8765        Some(KEYWORD_BREAK) => {
8766            return Ok((vec![step(StepKind::Break)], 1));
8767        }
8768        Some(KEYWORD_CONTINUE) => {
8769            return Ok((vec![step(StepKind::Continue)], 1));
8770        }
8771        Some(KEYWORD_IF) => {
8772            if let Some((kind, used)) = parse_if_at(toks, pos, stmt, ctx)? {
8773                return Ok((vec![step(kind)], used));
8774            }
8775        }
8776        Some(KEYWORD_SWITCH) => {
8777            if let Some((kind, used)) = parse_switch_at(toks, pos, stmt, ctx)? {
8778                return Ok((vec![step(kind)], used));
8779            }
8780        }
8781        Some(KEYWORD_FOR) => {
8782            if let Some((kind, used)) = parse_for_at(toks, pos, stmt, ctx)? {
8783                return Ok((vec![step(kind)], used));
8784            }
8785        }
8786        Some(KEYWORD_WHILE) => {
8787            if let Some((kind, used)) = parse_while_single(toks, pos, stmt, ctx)? {
8788                return Ok((vec![step(kind)], used));
8789            }
8790        }
8791        Some(KEYWORD_FUNC) => {
8792            if let Some((kind, used)) = parse_func_at(toks, pos, stmt, ctx, false)? {
8793                return Ok((vec![step(kind)], used));
8794            }
8795        }
8796        Some(KEYWORD_REMOTE) => {
8797            if let Some((kind, used)) = parse_remote_single(toks, pos, stmt, ctx)? {
8798                return Ok((vec![step(kind)], used));
8799            }
8800        }
8801        _ => {}
8802    }
8803    // Wrappers (block or single); shape misses fall to generic.
8804    match head_word.as_deref() {
8805        Some(KEYWORD_WITH_IO) => {
8806            return parse_with_io_element(toks, pos, stmt, ctx, first_guard);
8807        }
8808        Some(KEYWORD_TIMEOUT) => {
8809            if let Some((kind, used)) = parse_timeout_single(toks, pos, stmt, ctx)? {
8810                return Ok((vec![step(kind)], used));
8811            }
8812        }
8813        Some(KEYWORD_ISOLATED) => {
8814            if let Some((kind, used)) = parse_isolated_single(toks, pos, stmt, ctx)? {
8815                return Ok((vec![step(kind)], used));
8816            }
8817        }
8818        Some(KEYWORD_FAIL) => {
8819            if let Some((kind, used)) = parse_fail_single(toks, pos, stmt, ctx)? {
8820                return Ok((vec![step(kind)], used));
8821            }
8822        }
8823        Some(KEYWORD_ASYNC) => {
8824            // ASYNC FUNC definition form: prefix, parser records is_async
8825            // with no type-constraint validation (checker owns HANDLE rule).
8826            if matches!(toks.get(pos + 1).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC)
8827                && let Some((kind, used)) = parse_func_at(toks, pos + 1, stmt, ctx, true)?
8828            {
8829                return Ok((vec![step(kind)], 1 + used));
8830            }
8831            if let Some((kind, used)) = parse_async_single(toks, pos, stmt, ctx)? {
8832                return Ok((vec![step(kind)], used));
8833            }
8834        }
8835        _ => {}
8836    }
8837    // AWAIT/CANCEL statements (element level admits the `$` gap,
8838    // probed); heads without `$` go generic (lowering fails the
8839    // rest).
8840    if matches!(
8841        head_word.as_deref(),
8842        Some(KEYWORD_AWAIT) | Some(KEYWORD_CANCEL)
8843    ) && let Some((kind, used)) = parse_await_cancel_at(toks, pos, stmt, false, ctx)?
8844    {
8845        return Ok((vec![step(kind)], used));
8846    }
8847    // `INHERIT_ENV [...]` parses strictly even at element level
8848    // (keys stay exact everywhere; slice 5 adds only the
8849    // prelude-order validation). Shape misses go generic.
8850    if head_word.as_deref() == Some(KEYWORD_INHERIT_ENV)
8851        && let Some((kind, used)) = parse_inherit_env_at(toks, pos, stmt)?
8852    {
8853        return Ok((vec![step(kind)], used));
8854    }
8855    // `EXPORT ...` records names (zero steps) or misses to generic;
8856    // level, guard, and sigil violations fail loudly like the backend.
8857    if head_word.as_deref() == Some(KEYWORD_EXPORT) {
8858        if in_block {
8859            return Err(TokenError {
8860                diagnostic: None,
8861                hint: None,
8862                stmt,
8863                msg: format!("{KEYWORD_EXPORT} is only allowed at the top level"),
8864                line: 0,
8865                col: 0,
8866                kind: None,
8867            });
8868        }
8869        if first_guard.is_some() {
8870            return Err(TokenError {
8871                diagnostic: None,
8872                hint: None,
8873                stmt,
8874                msg: format!("{KEYWORD_EXPORT} cannot be guarded"),
8875                line: 0,
8876                col: 0,
8877                kind: None,
8878            });
8879        }
8880        if let Some((
8881            ExportNames {
8882                func_names,
8883                type_names,
8884                const_names,
8885            },
8886            used,
8887        )) = parse_export_at(toks, pos, stmt)?
8888        {
8889            for name in &func_names {
8890                for part in name.split(MODULE_SEPARATOR) {
8891                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8892                        .map_err(|e| lower_err(stmt, e))?;
8893                }
8894                // Recording and the duplicate rule live in
8895                // `Exports::insert` (single owner); this loop only
8896                // validates identifier shapes.
8897                if let Err(msg) = ctx
8898                    .exports
8899                    .borrow_mut()
8900                    .insert(ExportKind::Func, name.clone())
8901                {
8902                    return Err(TokenError {
8903                        diagnostic: None,
8904                        hint: None,
8905                        stmt,
8906                        msg,
8907                        line: 0,
8908                        col: 0,
8909                        kind: Some(ParseErrorKind::Validation {
8910                            command: KEYWORD_EXPORT.to_string(),
8911                        }),
8912                    });
8913                }
8914            }
8915            for name in &type_names {
8916                for part in name.split(MODULE_SEPARATOR) {
8917                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8918                        .map_err(|e| lower_err(stmt, e))?;
8919                }
8920                if let Err(msg) = ctx
8921                    .exports
8922                    .borrow_mut()
8923                    .insert(ExportKind::Type, name.clone())
8924                {
8925                    return Err(TokenError {
8926                        diagnostic: None,
8927                        hint: None,
8928                        stmt,
8929                        msg,
8930                        line: 0,
8931                        col: 0,
8932                        kind: Some(ParseErrorKind::Validation {
8933                            command: KEYWORD_EXPORT.to_string(),
8934                        }),
8935                    });
8936                }
8937            }
8938            for name in &const_names {
8939                for part in name.split(MODULE_SEPARATOR) {
8940                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8941                        .map_err(|e| lower_err(stmt, e))?;
8942                }
8943                if let Err(msg) = ctx
8944                    .exports
8945                    .borrow_mut()
8946                    .insert(ExportKind::Const, name.clone())
8947                {
8948                    return Err(TokenError {
8949                        diagnostic: None,
8950                        hint: None,
8951                        stmt,
8952                        msg,
8953                        line: 0,
8954                        col: 0,
8955                        kind: Some(ParseErrorKind::Validation {
8956                            command: KEYWORD_EXPORT.to_string(),
8957                        }),
8958                    });
8959                }
8960            }
8961            return Ok((Vec::new(), used));
8962        }
8963    }
8964    // `TYPE NAME = SHAPE` aliases (zero or one step); level and guard
8965    // violations fail loudly, shape misses fall to generic.
8966    if head_word.as_deref() == Some(KEYWORD_TYPE) {
8967        if in_block {
8968            return Err(TokenError {
8969                diagnostic: None,
8970                hint: None,
8971                stmt,
8972                msg: format!("{KEYWORD_TYPE} must appear at top level"),
8973                line: 0,
8974                col: 0,
8975                kind: None,
8976            });
8977        }
8978        if first_guard.is_some() {
8979            return Err(TokenError {
8980                diagnostic: None,
8981                hint: None,
8982                stmt,
8983                msg: format!("{KEYWORD_TYPE} cannot be guarded"),
8984                line: 0,
8985                col: 0,
8986                kind: None,
8987            });
8988        }
8989        if let Some((kind, used)) = parse_type_stmt_at(toks, pos, stmt)? {
8990            return Ok((vec![step(kind)], used));
8991        }
8992    }
8993    // Lowercase heads name their uppercase form (the grammar's
8994    // `command_name` mismatch): never a bare unknown-command.
8995    if let Some(head) = head_word.as_deref()
8996        && head.chars().all(|c| c.is_ascii_lowercase())
8997        && let upper = head.to_ascii_uppercase()
8998        && (is_known_command(&upper) || crate::STRUCTURAL_KEYWORDS.contains(&upper.as_str()))
8999    {
9000        return Err(TokenError {
9001            diagnostic: None,
9002            hint: None,
9003            stmt,
9004            msg: format!("command must be uppercase: found `{head}`, expected `{upper}`"),
9005            line: 0,
9006            col: 0,
9007            kind: Some(ParseErrorKind::Syntax),
9008        });
9009    }
9010    // RUN-exec ends mid-run (trailing loops on, probed); generic
9011    // instructions consume everything.
9012    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
9013    Ok((vec![step(kind)], used))
9014}
9015
9016/// Element-level `WITH_IO`: a same-run brace (any gap: `]{` works,
9017/// probed) opens the io-block form, wrapping every inner step with
9018/// scope markers; a joint non-brace follower is the pending-guard
9019/// error (the splitter only holds bare brackets); anything else is
9020/// the single form. Shape misses go generic.
9021fn parse_with_io_element(
9022    toks: &[Tok],
9023    pos: usize,
9024    stmt: usize,
9025    ctx: &ParseCtx,
9026    first_guard: Option<GuardExpr>,
9027) -> Result<(Vec<Step>, usize), TokenError> {
9028    // The bracket rides gapped (`sep`); anything else misses the
9029    // shape and generic fails it in lowering.
9030    let bracket = match toks.get(pos + 1) {
9031        Some(t)
9032            if !t.joint
9033                && matches!(
9034                    &t.kind,
9035                    TokKind::Group {
9036                        delim: GroupDelim::Bracket,
9037                        ..
9038                    }
9039                ) =>
9040        {
9041            Some(t)
9042        }
9043        _ => None,
9044    };
9045    let Some(bracket) = bracket else {
9046        // Shape miss: generic fails it in lowering.
9047        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
9048        return Ok((
9049            vec![Step {
9050                guard: first_guard,
9051                kind,
9052                scope_enter: 0,
9053                scope_exit: 0,
9054                line: 0,
9055                col: 0,
9056            }],
9057            used,
9058        ));
9059    };
9060    let inner = match &bracket.kind {
9061        TokKind::Group { inner, .. } => inner.clone(),
9062        _ => unreachable!(),
9063    };
9064    let bindings = match parse_io_bindings(&inner, stmt, ctx)? {
9065        Some(bindings) => bindings,
9066        // Shape miss: generic fails it.
9067        None => {
9068            let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
9069            return Ok((
9070                vec![Step {
9071                    guard: first_guard,
9072                    kind,
9073                    scope_enter: 0,
9074                    scope_exit: 0,
9075                    line: 0,
9076                    col: 0,
9077                }],
9078                used,
9079            ));
9080        }
9081    };
9082    let rest = pos + 2;
9083    // Same-run brace opens the io-block form (block-expanded
9084    // bindings skip the tty checks: the runtime repeats them).
9085    if let Some(next) = toks.get(rest)
9086        && matches!(
9087            &next.kind,
9088            TokKind::Group {
9089                delim: GroupDelim::Brace,
9090                ..
9091            }
9092        )
9093        && !is_template_brace(next)
9094    {
9095        let brace_inner = match &next.kind {
9096            TokKind::Group { inner, .. } => inner.clone(),
9097            _ => unreachable!(),
9098        };
9099        let mut steps = parse_body_steps(&brace_inner, stmt, ctx, false)?;
9100        if steps.is_empty() {
9101            return Err(TokenError {
9102                diagnostic: None,
9103                hint: None,
9104                stmt,
9105                msg: format!("{KEYWORD_WITH_IO} block must contain at least one command"),
9106                line: 0,
9107                col: 0,
9108                kind: None,
9109            });
9110        }
9111        // Every inner step wraps (merging when already wrapped,
9112        // like nested io scopes); the line guard folds into each
9113        // inner guard, inner-first (probed fold order).
9114        for s in &mut steps {
9115            let merged = match std::mem::replace(&mut s.kind, StepKind::Continue) {
9116                StepKind::WithIo {
9117                    bindings: inner_bindings,
9118                    cmd,
9119                } => StepKind::WithIo {
9120                    bindings: crate::commands::merge_bindings(&bindings, &inner_bindings),
9121                    cmd,
9122                },
9123                other => StepKind::WithIo {
9124                    bindings: bindings.clone(),
9125                    cmd: Box::new(other),
9126                },
9127            };
9128            s.kind = merged;
9129            s.guard = crate::commands::and_guard_exprs(s.guard.take(), first_guard.clone());
9130        }
9131        let span = lowering_ctx(stmt);
9132        for s in &steps {
9133            crate::commands::reject_nested_inherit_env(&span, &s.kind)
9134                .map_err(|e| lower_err(stmt, e))?;
9135        }
9136        if let Some(first) = steps.first_mut() {
9137            first.scope_enter += 1;
9138        }
9139        if let Some(last) = steps.last_mut() {
9140            last.scope_exit += 1;
9141        }
9142        return Ok((steps, rest + 1 - pos));
9143    }
9144    if rest >= toks.len() {
9145        // Unreachable: the splitter holds bare brackets for `{`.
9146        // Kept for body-parsed runs, mirroring the transient node.
9147        return Ok((
9148            vec![Step {
9149                guard: first_guard,
9150                kind: StepKind::WithIoBlock { bindings },
9151                scope_enter: 0,
9152                scope_exit: 0,
9153                line: 0,
9154                col: 0,
9155            }],
9156            2,
9157        ));
9158    }
9159    // A joint follower misses the inner `sep`: the pending wait
9160    // fails exactly like the grammar.
9161    if toks[rest].joint {
9162        return Err(TokenError {
9163            diagnostic: None,
9164            hint: None,
9165            stmt,
9166            msg: format!("{KEYWORD_WITH_IO} block must be followed by '{{'"),
9167            line: 0,
9168            col: 0,
9169            kind: None,
9170        });
9171    }
9172    // Single form, shared with single-inner (element guards the step).
9173    let (cmd, used) = parse_single_inner(
9174        toks,
9175        rest,
9176        stmt,
9177        ctx,
9178        InnerRules {
9179            allow_await: false,
9180            allow_with_io: true,
9181        },
9182    )?;
9183    let span = lowering_ctx(stmt);
9184    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| lower_err(stmt, e))?;
9185    let kind = StepKind::WithIo {
9186        bindings,
9187        cmd: Box::new(cmd),
9188    };
9189    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
9190    Ok((
9191        vec![Step {
9192            guard: first_guard,
9193            kind,
9194            scope_enter: 0,
9195            scope_exit: 0,
9196            line: 0,
9197            col: 0,
9198        }],
9199        2 + used,
9200    ))
9201}
9202
9203/// Shared inner-command parser: statement calls (joint paren, even on
9204/// known commands), RUN exec
9205/// form, and generic instructions. Returns the kind and tokens
9206/// consumed: calls and RUN-exec end mid-run (the caller continues
9207/// past them, like the grammar's `element*`); generic instructions
9208/// consume everything. Wrappers never route here (element and
9209/// single-inner dispatch own them); slice 4b reuses the call/RUN
9210/// arms for trailing elements.
9211fn parse_inner_command(
9212    body: &[Tok],
9213    stmt: usize,
9214    ctx: &ParseCtx,
9215) -> Result<(StepKind, usize), TokenError> {
9216    // Bare `NAME(...)` calls invoke functions with one syntax; the head
9217    // and `(` ride gapless or the shape stays an instruction (which
9218    // fails later as UnknownCommand), exactly like the grammar.
9219    if let Some((call_name, paren)) = call_shape_at(body, 0, true) {
9220        let inner = match &body[paren].kind {
9221            TokKind::Group { inner, .. } => inner.clone(),
9222            _ => unreachable!(),
9223        };
9224        let args = parse_call_args(&inner, stmt, ctx)?;
9225        // Statement-level `INSPECT(...)` resolves like any other call
9226        // (only expression position mints the node); unknown functions
9227        // fail in the shared resolver with identical messages.
9228        if !call_name.contains(MODULE_SEPARATOR) {
9229            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
9230                .map_err(|e| lower_err(stmt, e))?;
9231        }
9232        let qualified = resolve_name(ctx, stmt, &call_name)?;
9233        return Ok((
9234            StepKind::Call {
9235                name: qualified,
9236                args,
9237            },
9238            paren + 1,
9239        ));
9240    }
9241    let head = match body.first().map(|t| &t.kind) {
9242        Some(TokKind::Word(n)) => n.clone(),
9243        _ => {
9244            return Err(TokenError {
9245                diagnostic: None,
9246                hint: None,
9247                stmt,
9248                msg: "statement must open with a command word".to_string(),
9249                line: 0,
9250                col: 0,
9251                kind: None,
9252            });
9253        }
9254    };
9255    // RUN exec form: the list routes structured through `lower` (the
9256    // mock wraps it in `Run`; production maps it to `RunExec`); the
9257    // caller continues past the list, like the grammar. The list
9258    // rides gapped (`sep`): a joint bracket is a hard error, never
9259    // a spliced arg (probed `RUN["a"]`).
9260    if head == KEYWORD_RUN
9261        && matches!(
9262            body.get(1).map(|t| &t.kind),
9263            Some(TokKind::Group {
9264                delim: GroupDelim::Bracket,
9265                ..
9266            })
9267        )
9268    {
9269        if body[1].joint {
9270            return Err(TokenError {
9271                diagnostic: None,
9272                hint: None,
9273                stmt,
9274                msg: format!("{KEYWORD_RUN} [...] requires a gap after {KEYWORD_RUN}"),
9275                line: 0,
9276                col: 0,
9277                kind: None,
9278            });
9279        }
9280        let inner = match &body[1].kind {
9281            TokKind::Group { inner, .. } => inner.clone(),
9282            _ => unreachable!(),
9283        };
9284        // Non-map blocks miss the exec shape (the grammar has no
9285        // `block` alternative here); fall through to the shell path
9286        // below, which reads the bracket literally.
9287        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
9288            let kind =
9289                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
9290            return Ok((kind, 2));
9291        }
9292    }
9293    let (tokens, deferred) = build_arg_tokens(&body[1..], stmt, ctx)?;
9294    let lowered = lower_generic_args(&head, tokens, stmt, ctx);
9295    match lowered {
9296        Ok(kind) => {
9297            // Stashed call errors surface only for otherwise well-formed
9298            // statements: the command head owns its syntax, so a malformed
9299            // header keeps its tailored error instead of being masked by an
9300            // argument-position resolution failure.
9301            if let Some(err) = deferred {
9302                return Err(err);
9303            }
9304            Ok((kind, body.len()))
9305        }
9306        Err(lower_err) => {
9307            // Fallback raw strings (`NOPE()` rendered as text) can fail
9308            // argument-shape lowering with a misleading error. The
9309            // stashed unknown-callee error names the real culprit, so
9310            // it wins over every argument-level failure (`Validation`,
9311            // `Syntax`, `InvalidSyntax`, or the `None` classification
9312            // that `ENV`/`EXPAND` lowering uses). Heads owned by a
9313            // statement-header parser (`FUNC`, `LET`, `IF`, `FOR`,
9314            // `WHILE`, `TYPE`, `IMPORT`, `EXPORT`, `REMOTE`, `WITH_IO`)
9315            // keep their lowering `InvalidSyntax`: those parsers miss to
9316            // this path on shape miss (e.g. `FUNC FOO() ECHO hi` has no
9317            // body block), so the lowering error names the malformed
9318            // header while the stashed name is its definiendum, never an
9319            // argument-position call. Every other head is a plain
9320            // command, so a lowering `InvalidSyntax` there is an
9321            // argument-shape failure from the raw-text fallback, and
9322            // the stashed callee names the culprit. Only
9323            // head-identity errors (`UnknownCommand`, `Structural`)
9324            // keep their tailored diagnostic everywhere.
9325            let is_header_syntax = matches!(
9326                head.as_str(),
9327                KEYWORD_FUNC
9328                    | KEYWORD_LET
9329                    | KEYWORD_CONST
9330                    | KEYWORD_IF
9331                    | KEYWORD_SWITCH
9332                    | KEYWORD_FOR
9333                    | KEYWORD_WHILE
9334                    | KEYWORD_TYPE
9335                    | KEYWORD_IMPORT
9336                    | KEYWORD_EXPORT
9337                    | KEYWORD_REMOTE
9338                    | KEYWORD_WITH_IO
9339            ) && matches!(
9340                lower_err.kind,
9341                Some(crate::error::ParseErrorKind::InvalidSyntax { .. })
9342            );
9343            if let Some(deferred_err) = deferred
9344                && !is_header_syntax
9345                && matches!(
9346                    lower_err.kind,
9347                    Some(crate::error::ParseErrorKind::Validation { .. })
9348                        | Some(crate::error::ParseErrorKind::Syntax)
9349                        | Some(crate::error::ParseErrorKind::InvalidSyntax { .. })
9350                        | None
9351                )
9352            {
9353                return Err(deferred_err);
9354            }
9355            Err(lower_err)
9356        }
9357    }
9358}
9359
9360/// Parse a token stream (either lexer) into steps. Markers normalize to
9361/// 0/0 like the fuzz harness; scopes arrive with block slices.
9362pub fn parse_tokens(
9363    toks: &[Tok],
9364    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9365) -> Result<Vec<Step>, TokenError> {
9366    let modules = ModuleTable::default();
9367    let reserved = HashSet::new();
9368    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
9369    parse_tokens_with_ctx(toks, &ctx)
9370}
9371
9372/// Parse with an explicit context (module table for call resolution).
9373/// `parse_tokens` uses empty modules.
9374pub fn parse_tokens_with_ctx(toks: &[Tok], ctx: &ParseCtx) -> Result<Vec<Step>, TokenError> {
9375    let mut out = Vec::new();
9376    *ctx.current_line.borrow_mut() = 1;
9377    let stmts = split_statements(toks, 1)?;
9378    predeclare_forward_funcs(&stmts, ctx);
9379    for (i, s) in stmts.iter().enumerate() {
9380        *ctx.current_line.borrow_mut() = s.line;
9381        out.extend(
9382            lower_stmt_steps(s, i, ctx, false, true).map_err(|e| stamp_pos(e, s.line, s.col))?,
9383        );
9384    }
9385    // Whole-script validations through the shared validators.
9386    // `INHERIT_ENV` prelude order: only leading positions read.
9387    {
9388        let mut seen_non_prelude = false;
9389        for step in &out {
9390            match &step.kind {
9391                StepKind::InheritEnv { .. } => {
9392                    if seen_non_prelude {
9393                        return Err(TokenError {
9394                            diagnostic: None,
9395                            hint: None,
9396                            stmt: out.len(),
9397                            msg: format!(
9398                                "{KEYWORD_INHERIT_ENV} must appear before any other commands"
9399                            ),
9400                            line: 0,
9401                            col: 0,
9402                            kind: None,
9403                        });
9404                    }
9405                }
9406                kind => {
9407                    if crate::commands::contains_inherit_env(kind) {
9408                        return Err(TokenError {
9409                            diagnostic: None,
9410                            hint: None,
9411                            stmt: out.len(),
9412                            msg: format!(
9413                                "{KEYWORD_INHERIT_ENV} cannot be nested inside other commands"
9414                            ),
9415                            line: 0,
9416                            col: 0,
9417                            kind: None,
9418                        });
9419                    }
9420                    // Harvest imports stay prelude: they bind functions
9421                    // and types without executing module bodies, so they
9422                    // neither read nor disturb the inherited environment.
9423                    // File imports execute arbitrary top-level steps on
9424                    // import, so they end the prelude like any other
9425                    // side-effecting command. Host-only IMPORTs emit no
9426                    // step at all, which is why they never tripped this
9427                    // gate.
9428                    if !matches!(kind, StepKind::ImportFuncs { .. }) {
9429                        seen_non_prelude = true;
9430                    }
9431                }
9432            }
9433        }
9434    }
9435    crate::commands::validate_remote_copy_placement(&out, &lowering_ctx(out.len()))
9436        .map_err(|e| lower_err(out.len(), e))?;
9437    {
9438        let top: HashSet<String> = ctx.funcs.borrow().first().cloned().unwrap_or_default();
9439        let top_imports: Vec<String> = ctx
9440            .imports
9441            .borrow()
9442            .first()
9443            .cloned()
9444            .unwrap_or_default()
9445            .into_iter()
9446            .map(|(name, _)| name)
9447            .collect();
9448        let mut top_types = HashSet::new();
9449        let mut top_consts = HashSet::new();
9450        for step in &out {
9451            if let StepKind::TypeAlias { name, .. } = &step.kind {
9452                top_types.insert(name.clone());
9453            }
9454            match &step.kind {
9455                StepKind::Bind { var, is_const, .. } if *is_const => {
9456                    top_consts.insert(var.clone());
9457                }
9458                _ => {}
9459            }
9460        }
9461        crate::commands::validate_exports(
9462            &lowering_ctx(out.len()),
9463            &ctx.exports.borrow(),
9464            &top,
9465            &top_types,
9466            &top_consts,
9467            ctx.modules,
9468            &top_imports,
9469        )
9470        .map_err(|e| lower_err(out.len(), e))?;
9471    }
9472    Ok(out)
9473}
9474
9475// ---- String entry points: lex, lower, collect exports and docs ----
9476
9477/// Source text of a 1-based line. The line just past a trailing
9478/// newline (where unbalanced groups report) reads as empty text so
9479/// caret blocks still render.
9480fn source_line_of(input: &str, line: usize) -> Option<String> {
9481    let count = input.lines().count();
9482    let idx = line.checked_sub(1)?;
9483    if idx < count {
9484        input.lines().nth(idx).map(str::to_string)
9485    } else if idx == count {
9486        Some(String::new())
9487    } else {
9488        None
9489    }
9490}
9491
9492/// Last script line (end-of-script validations blame it).
9493fn last_line(input: &str) -> usize {
9494    input.lines().count().max(1)
9495}
9496
9497/// Convert a lexer failure: low-level syntax kind, exact lexer
9498/// position, and the source line for the caret block. Unclosed groups
9499/// name their opener (no grammar dumps); the closer expectation rides
9500/// along so `expected()` stays informative. A lexer-known kind (an
9501/// unclosed `WITH_IO` bracket) converts verbatim.
9502fn lex_error(input: &str, e: LexError) -> ParseError {
9503    let line = e.line.max(1);
9504    let ctx = match source_line_of(input, line) {
9505        Some(source_line) => SpanContext::full(line, e.col.max(1), e.col.max(1), source_line),
9506        None => SpanContext::line_only(line),
9507    };
9508    if let Some(ParseErrorKind::InvalidSyntax { command }) = e.kind {
9509        // Lexer-known command syntax (an unclosed `WITH_IO` bracket).
9510        return ParseError::invalid_syntax(
9511            &command,
9512            e.msg,
9513            None,
9514            vec!["`]`".to_string()],
9515            None,
9516            &ctx,
9517        );
9518    }
9519    let expected = if e.msg.starts_with("unclosed") {
9520        vec!["`}`".to_string()]
9521    } else {
9522        Vec::new()
9523    };
9524    ParseError::syntax(e.msg, expected, None, &ctx)
9525}
9526
9527/// Convert a backend failure, preserving the dispatcher's error kind
9528/// and completing line/source context the token stream knows. Spans
9529/// open at the statement's start column and cover its whole first line
9530/// (multi-line spans clamp to the start line), so caret blocks render
9531/// for every string-path error.
9532fn token_error(input: &str, e: TokenError) -> ParseError {
9533    let line = if e.line == 0 {
9534        last_line(input)
9535    } else {
9536        e.line
9537    };
9538    let start_col = e.col.max(1);
9539    let ctx = match source_line_of(input, line) {
9540        Some(source_line) => {
9541            let end = source_line.len().max(start_col);
9542            SpanContext::full(line, start_col, end, source_line)
9543        }
9544        None => SpanContext::line_only(line),
9545    };
9546    // Column spans are statement granularity (every error names its
9547    // statement's first column); the caret block still renders.
9548    // A carried diagnostic reattaches verbatim (key and fields
9549    // survive); only parser-native errors rewrap from the message
9550    // string as before. A carried hint reattaches alongside, so
9551    // `hint()` survives the round trip on every path.
9552    if let Some(diagnostic) = e.diagnostic {
9553        let kind = e.kind.unwrap_or(ParseErrorKind::Structural {
9554            rule: "statement".to_string(),
9555        });
9556        return ParseError::from_diagnostic(kind, *diagnostic, &ctx).with_hint(e.hint);
9557    }
9558    let hint = e.hint;
9559    match e.kind {
9560        Some(crate::error::ParseErrorKind::UnknownCommand { name }) => {
9561            ParseError::unknown_command(&name, e.msg, hint, &ctx)
9562        }
9563        Some(crate::error::ParseErrorKind::InvalidSyntax { command }) => {
9564            ParseError::invalid_syntax(&command, e.msg, None, Vec::new(), hint, &ctx)
9565        }
9566        Some(crate::error::ParseErrorKind::Validation { command }) => {
9567            ParseError::validation(&command, e.msg, &ctx)
9568        }
9569        Some(crate::error::ParseErrorKind::Syntax) => {
9570            ParseError::syntax(e.msg, Vec::new(), hint, &ctx)
9571        }
9572        Some(crate::error::ParseErrorKind::Structural { rule }) => {
9573            ParseError::structural(&rule, e.msg, &ctx)
9574        }
9575        None => ParseError::structural("statement", e.msg, &ctx),
9576    }
9577}
9578
9579/// Shared parse driver: lex, lower with preseeded frames, and collect
9580/// `EXPORT` names (validated at end of parse, forward references
9581/// allowed).
9582fn parse_with_ctx(
9583    input: &str,
9584    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9585    reserved_names: HashSet<String>,
9586    modules: ModuleTable,
9587    preseed_funcs: HashSet<String>,
9588    preseed_imports: Vec<String>,
9589) -> ParseResult<ScriptWithExports> {
9590    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
9591    let ctx = ParseCtx::empty(&lower, &modules, &reserved_names);
9592    // Snippet re-parses seed their base frames so lookup behaves
9593    // identically; snippets never define, only read.
9594    ctx.funcs.borrow_mut()[0].extend(preseed_funcs);
9595    ctx.imports.borrow_mut()[0].extend(preseed_imports.into_iter().map(|name| (name, false)));
9596    let steps = parse_tokens_with_ctx(&toks, &ctx).map_err(|e| token_error(input, e))?;
9597    let mut steps = steps;
9598    stamp_func_docs(input, &mut steps);
9599    Ok(ScriptWithExports {
9600        steps,
9601        exports: ctx.exports.borrow().clone(),
9602    })
9603}
9604
9605/// Steps plus single-file `EXPORT` metadata, before `#` doc stamping.
9606/// Callers needing docs build a [`ParsedScript`] from this.
9607struct ScriptWithExports {
9608    steps: Vec<Step>,
9609    exports: Exports,
9610}
9611
9612/// Parse a script with an unknown host environment.
9613pub fn parse_script(
9614    input: &str,
9615    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9616) -> ParseResult<Vec<Step>> {
9617    Ok(parse_with_ctx(
9618        input,
9619        lower,
9620        HashSet::new(),
9621        ModuleTable::default(),
9622        HashSet::new(),
9623        Vec::new(),
9624    )?
9625    .steps)
9626}
9627
9628/// Parse a snippet with an enclosing parse's visible scope state, so
9629/// re-parsed inner commands (async bodies) resolve calls identically.
9630/// The snippet never defines, only reads: seeds affect lookup alone.
9631pub fn parse_script_with_preseed(
9632    input: &str,
9633    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9634    reserved_names: HashSet<String>,
9635    modules: ModuleTable,
9636    preseed_funcs: HashSet<String>,
9637    preseed_imports: Vec<String>,
9638) -> ParseResult<Vec<Step>> {
9639    Ok(parse_with_ctx(
9640        input,
9641        lower,
9642        reserved_names,
9643        modules,
9644        preseed_funcs,
9645        preseed_imports,
9646    )?
9647    .steps)
9648}
9649
9650/// Parse with a module provenance table so calls resolve statically:
9651/// qualified `MODULE::NAME` checks membership, bare `NAME` resolves through
9652/// `SCRIPT` definitions and `IMPORT`ed modules, and anything else fails at
9653/// parse time instead of at runtime.
9654pub fn parse_script_with_modules(
9655    input: &str,
9656    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9657    reserved_names: HashSet<String>,
9658    modules: ModuleTable,
9659) -> ParseResult<Vec<Step>> {
9660    Ok(parse_script_with_modules_and_exports(input, lower, reserved_names, modules)?.steps)
9661}
9662
9663/// Parse with modules plus single-file `EXPORT` metadata and `#` doc
9664/// comments for top-level `FUNC`s. Used by the MCP host; the linear
9665/// runner keeps using `parse_script_with_modules` and ignores exports.
9666pub fn parse_script_with_modules_and_exports(
9667    input: &str,
9668    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9669    reserved_names: HashSet<String>,
9670    modules: ModuleTable,
9671) -> ParseResult<ParsedScript> {
9672    let ScriptWithExports { steps, exports } = parse_with_ctx(
9673        input,
9674        lower,
9675        reserved_names,
9676        modules,
9677        HashSet::new(),
9678        Vec::new(),
9679    )?;
9680    Ok(ParsedScript {
9681        func_docs: collect_func_docs(input, &steps),
9682        steps,
9683        exports,
9684    })
9685}
9686
9687/// Parse without modules plus `EXPORT` metadata. Used by tests and
9688/// tooling that lower with the shared mock.
9689pub fn parse_script_with_exports(
9690    input: &str,
9691    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9692) -> ParseResult<ParsedScript> {
9693    let ScriptWithExports { steps, exports } = parse_with_ctx(
9694        input,
9695        lower,
9696        HashSet::new(),
9697        ModuleTable::default(),
9698        HashSet::new(),
9699        Vec::new(),
9700    )?;
9701    Ok(ParsedScript {
9702        func_docs: collect_func_docs(input, &steps),
9703        steps,
9704        exports,
9705    })
9706}
9707
9708/// Parse one expression from source text with an empty module scope, for
9709/// tooling that shows lowering without running (docs demos, explain output).
9710/// No imports exist here, so bare function calls fail and qualified calls
9711/// fail against the empty table; only `INSPECT` passes through untouched.
9712/// Arithmetic, comparison, variables, env reads, keypaths, and literals
9713/// lower normally, with literal only subtrees folded before flattening.
9714pub fn parse_expression_str(input: &str) -> ParseResult<Expr> {
9715    // Trailing whitespace lexes unconsumed, so lex the trimmed text:
9716    // otherwise padded but valid input fails the full consumption check.
9717    let trimmed = input.trim();
9718    let toks = lex_str(trimmed).map_err(|e| lex_error(trimmed, e))?;
9719    let modules = ModuleTable::default();
9720    let reserved = HashSet::new();
9721    let lower = crate::commands::lower_command as fn(&str, Vec<Arg>) -> ParseResult<StepKind>;
9722    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
9723    *ctx.current_line.borrow_mut() = 1;
9724    parse_single_expr(&toks, 0, &ctx).map_err(|e| token_error(trimmed, e))
9725}
9726
9727/// Parse one guard expression from source text (a bare `guard_seq`:
9728/// predicates, `not`/`any`/`all`, comma lists), for tooling and tests.
9729pub fn parse_guard_expr_str(input: &str) -> ParseResult<GuardExpr> {
9730    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
9731    parse_single_guard(&toks, 0).map_err(|e| token_error(input, e))
9732}
9733
9734/// Parsed script with single-file `EXPORT` metadata. `steps` is the
9735/// linear execution plan, `exports` the `EXPORT` names in source order
9736/// per kind, and `func_docs` maps top-level `FUNC` base names to
9737/// (summary, docs) collected from the immediately preceding `#`
9738/// comment block.
9739#[derive(Debug, Clone, Default)]
9740pub struct ParsedScript {
9741    pub steps: Vec<Step>,
9742    pub exports: Exports,
9743    pub func_docs: std::collections::HashMap<String, (String, String)>,
9744}
9745
9746/// One `EXPORT` list kind. Single owner for the func/type/const
9747/// distinction, so the duplicate rule and every holder never restate
9748/// the three-way split.
9749#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9750pub enum ExportKind {
9751    Func,
9752    Type,
9753    Const,
9754}
9755
9756/// Single-file `EXPORT` metadata: per-kind names in source order.
9757/// Separate lists (never one mixed vec) so the MCP server never
9758/// confuses a type for a tool, and reads stay kind-addressed.
9759#[derive(Debug, Clone, Default)]
9760pub struct Exports {
9761    pub funcs: Vec<String>,
9762    pub types: Vec<String>,
9763    pub consts: Vec<String>,
9764}
9765
9766impl Exports {
9767    /// Record one `EXPORT` name, enforcing the duplicate rule.
9768    /// Uniqueness is by exported base name for every kind: `EXPORT FOO`
9769    /// and `EXPORT LIB::FOO` name one servable tool, `EXPORT CONST $N`
9770    /// and `EXPORT CONST $A::N` name one read, so the second spelling
9771    /// shapes the same `duplicate EXPORT` instead of silently
9772    /// shadowing. One base name rides exactly one export kind.
9773    /// `Err` carries the `duplicate EXPORT` message unchanged.
9774    pub fn insert(&mut self, kind: ExportKind, name: String) -> Result<(), String> {
9775        let base = crate::base_name(&name);
9776        let clash = [&self.funcs, &self.types, &self.consts]
9777            .iter()
9778            .any(|list| list.iter().any(|e| crate::base_name(e) == base));
9779        if clash {
9780            return Err(format!("duplicate {KEYWORD_EXPORT} `{name}`"));
9781        }
9782        match kind {
9783            ExportKind::Func => self.funcs.push(name),
9784            ExportKind::Type => self.types.push(name),
9785            ExportKind::Const => self.consts.push(name),
9786        }
9787        Ok(())
9788    }
9789}
9790
9791fn collect_func_docs(
9792    input: &str,
9793    steps: &[Step],
9794) -> std::collections::HashMap<String, (String, String)> {
9795    use std::collections::{HashMap, HashSet};
9796    let lines: Vec<&str> = input.lines().collect();
9797    // Top-level FUNC definition lines keyed by base name. Brace depth
9798    // tracks nesting so only depth-0 `FUNC` lines count; the first
9799    // occurrence wins because same-scope duplicates fail at lowering.
9800    let mut def_lines: HashMap<String, usize> = HashMap::new();
9801    let mut seen: HashSet<String> = HashSet::new();
9802    let mut depth: usize = 0;
9803    for (idx, line) in lines.iter().enumerate() {
9804        let trimmed = line.trim_start();
9805        let is_comment = trimmed.starts_with('#');
9806        let is_guard_only = trimmed.starts_with('[');
9807        if !is_comment
9808            && !is_guard_only
9809            && let Some(rest) = strip_func_head(trimmed)
9810            && depth == 0
9811            && !seen.contains(&rest)
9812        {
9813            seen.insert(rest.clone());
9814            def_lines.insert(rest, idx + 1);
9815        }
9816        if !is_comment {
9817            for ch in line.chars() {
9818                if ch == '{' {
9819                    depth = depth.saturating_add(1);
9820                } else if ch == '}' {
9821                    depth = depth.saturating_sub(1);
9822                }
9823            }
9824        }
9825    }
9826    let mut out: HashMap<String, (String, String)> = HashMap::new();
9827    for step in steps {
9828        if let StepKind::FuncDef { name, .. } = &step.kind
9829            && !out.contains_key(name)
9830            && let Some(&line_no) = def_lines.get(name)
9831            && let Some((summary, docs)) = docs_above(&lines, line_no)
9832        {
9833            out.insert(name.clone(), (summary, docs));
9834        }
9835    }
9836    out
9837}
9838
9839/// Stamp `#` doc blocks onto top-level `FUNC` steps, from the same map
9840/// that feeds `func_docs`, so step-carried docs and the sidecar can
9841/// never disagree. Only top-level definitions qualify (same rule as
9842/// collection); nested shadowing keeps `docs: None`.
9843fn stamp_func_docs(input: &str, steps: &mut [Step]) {
9844    let docs = collect_func_docs(input, steps);
9845    for step in steps {
9846        if let StepKind::FuncDef {
9847            name, docs: slot, ..
9848        } = &mut step.kind
9849            && slot.is_none()
9850            && let Some(pair) = docs.get(name)
9851        {
9852            *slot = Some(pair.clone());
9853        }
9854    }
9855}
9856
9857fn strip_func_head(trimmed: &str) -> Option<String> {
9858    let rest = trimmed.strip_prefix(KEYWORD_FUNC)?;
9859    let after = rest.strip_prefix([' ', '\t'])?;
9860    if after.is_empty() {
9861        return None;
9862    }
9863    let name: String = after
9864        .chars()
9865        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
9866        .collect();
9867    if name.is_empty()
9868        || !name
9869            .bytes()
9870            .all(|b| b.is_ascii_uppercase() || b == b'_' || b.is_ascii_digit())
9871    {
9872        return None;
9873    }
9874    if name.starts_with(|c: char| c.is_ascii_digit()) {
9875        return None;
9876    }
9877    Some(name)
9878}
9879
9880fn docs_above(lines: &[&str], line_no: usize) -> Option<(String, String)> {
9881    if line_no <= 1 {
9882        return None;
9883    }
9884    let mut block: Vec<String> = Vec::new();
9885    let mut idx = line_no - 1;
9886    while idx > 0 {
9887        idx -= 1;
9888        let trimmed = lines[idx].trim_start();
9889        if trimmed.is_empty() {
9890            break;
9891        }
9892        if let Some(body) = trimmed.strip_prefix('#') {
9893            let text = body.strip_prefix(' ').unwrap_or(body);
9894            block.push(text.to_string());
9895        } else {
9896            break;
9897        }
9898        if idx == 0 {
9899            break;
9900        }
9901    }
9902    if block.is_empty() {
9903        return None;
9904    }
9905    block.reverse();
9906    let summary = block.first().cloned().unwrap_or_default();
9907    let docs = block.join("\n");
9908    Some((summary, docs))
9909}
9910
9911#[cfg(test)]
9912mod tests {
9913    use super::*;
9914    use crate::test_lower_mock;
9915    use indoc::indoc;
9916
9917    fn lower(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9918        test_lower_mock::lower(name, args)
9919    }
9920
9921    /// Lexer-agreement oracle: both frontends must deliver identical
9922    /// steps through the single backend. `parse_script` is the string
9923    /// entry point; `parse_tokens` runs each lexer's output directly.
9924    fn assert_parity(text: &str) {
9925        let old = crate::parse_script(text, lower)
9926            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9927        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9928        let new = parse_tokens(&toks, lower)
9929            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9930        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9931        #[cfg(feature = "proc-macro-api")]
9932        {
9933            let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
9934            let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
9935            let new = parse_tokens(&toks, lower).expect("token path must parse token script");
9936            assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
9937        }
9938    }
9939
9940    /// String-path-only oracle for shapes `rustc` cannot carry at all
9941    /// (lifetime-like quotes). The backend must still agree there.
9942    fn assert_parity_string_only(text: &str) {
9943        let old = crate::parse_script(text, lower)
9944            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9945        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9946        let new = parse_tokens(&toks, lower)
9947            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9948        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9949    }
9950
9951    #[test]
9952    fn token_and_string_paths_agree_on_wrappers() {
9953        // Single-command wrappers, io-blocks, await/cancel,
9954        // LET wrapper forms — three-way agreement per script.
9955        for text in [
9956            "WITH_IO [stdout=$p] ECHO hi",
9957            "WITH_IO [stdin=$p] ECHO hi",
9958            "WITH_IO [stdin] ECHO hi",
9959            "WITH_IO [stdout] ECHO hi",
9960            "WITH_IO [stdin=$p, stdout=$q] ECHO hi",
9961            "WITH_IO [stdin=$p, stdin=$q] ECHO hi",
9962            "WITH_IO [tty] RUN echo hi",
9963            "WITH_IO [tty, rows=40, cols=100] RUN echo hi",
9964            "WITH_IO [rows=40, cols=100, tty] RUN echo hi",
9965            "WITH_IO [stdin =$p] ECHO hi",
9966            "WITH_IO [stdin= $p] ECHO hi",
9967            "WITH_IO [ stdin=$p ] ECHO hi",
9968            "WITH_IO [\nstdin=$p\n] ECHO hi",
9969            "WITH_IO [stdin=$p\n, stdout=$q] ECHO hi",
9970            "WITH_IO [stdout=$p] ASYNC ECHO hi",
9971            "WITH_IO [stdin=$p] WITH_IO [stderr=$e] ECHO hi",
9972            "WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
9973            "WITH_IO [stdin=$p] ISOLATED ECHO hi",
9974            "WITH_IO [stdin=$p] CANCEL $t",
9975            "WITH_IO [stdin=$p] CANCEL $t ECHO bye",
9976            "WITH_IO [stdin=$p] { ECHO hi }",
9977            "WITH_IO [stdin=$p]\n{ ECHO hi }",
9978            "WITH_IO [stdin=$p]; { ECHO hi }",
9979            "WITH_IO [stdin=$p]{ ECHO hi }",
9980            "WITH_IO [stdin=$p] { ECHO a\nECHO b }",
9981            "WITH_IO [stdin=$p] { ECHO hi } ECHO bye",
9982            "WITH_IO [rows=40] { ECHO hi }",
9983            "WITH_IO [tty] { ECHO hi }",
9984            "WITH_IO [stdin=$p] { WITH_IO [stderr=$e] ECHO hi }",
9985            "TIMEOUT 10s ECHO hi",
9986            "TIMEOUT 10 ECHO hi",
9987            "TIMEOUT 500ms ECHO hi",
9988            "TIMEOUT 5m ECHO hi",
9989            "TIMEOUT 2h ECHO hi",
9990            "TIMEOUT $d ECHO hi",
9991            "TIMEOUT \"10s\" ECHO hi",
9992            "TIMEOUT \"30 s\" ECHO hi",
9993            "TIMEOUT {{ $d }} ECHO hi",
9994            "TIMEOUT 10s AWAIT $t",
9995            "TIMEOUT 10s CANCEL $t",
9996            "TIMEOUT 10s AWAIT $t ECHO bye",
9997            "TIMEOUT 10s CANCEL $t ECHO bye",
9998            "TIMEOUT 10s { ECHO hi }",
9999            "TIMEOUT 10s {\nECHO hi\n}",
10000            "TIMEOUT 10s { ECHO hi } ECHO bye",
10001            "TIMEOUT 10s { ECHO hi } TIMEOUT 5s ECHO bye",
10002            "TIMEOUT 10s TIMEOUT 5s ECHO hi",
10003            "TIMEOUT 10s { ECHO a\nECHO b }",
10004            "TIMEOUT 10s ECHO hi extra",
10005            "ISOLATED ECHO hi",
10006            "ISOLATED { ECHO hi }",
10007            "ISOLATED { ECHO hi } ECHO bye",
10008            "ISOLATED AWAIT $t",
10009            "ISOLATED INHERIT_ENV [M]",
10010            "ISOLATED { INHERIT_ENV [M] }",
10011            "ISOLATED { INHERIT_ENV [MODE]\nECHO hi }",
10012            "ASYNC ECHO hi",
10013            "ASYNC { ECHO hi }",
10014            "ASYNC{ECHO hi}",
10015            "ASYNC { ECHO a\nECHO b }",
10016            "ASYNC { ECHO hi } ECHO bye",
10017            "ASYNC CANCEL $t",
10018            "ASYNC CANCEL $t ECHO bye",
10019            "AWAIT $t",
10020            "AWAIT$t",
10021            "AWAIT $ t",
10022            "AWAIT $T",
10023            "AWAIT $t2",
10024            "AWAIT $_t",
10025            "CANCEL $t",
10026            "CANCEL$t",
10027            "CANCEL $ t",
10028            "AWAIT $t ECHO bye",
10029            "CANCEL $t ECHO bye",
10030            "AWAIT $t AWAIT $u",
10031            "AWAIT $t\nECHO bye",
10032            "LET $t: HANDLE = ASYNC ECHO hi",
10033            "LET $t: HANDLE = ASYNC { ECHO hi }",
10034            "LET $t: HANDLE = ASYNC { ECHO hi } ECHO bye",
10035            "LET $a: STRING = ASYNC ECHO hi",
10036            "LET $t: HANDLE = ASYNC { WITH_IO [stdin=$p] ECHO hi }",
10037            "LET $w: STRING = WITH_IO [stdin=$p] ASYNC ECHO hi",
10038            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC ECHO hi",
10039            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi }",
10040            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi } ECHO bye",
10041            "LET $x: STRING = WITH_IO [stdin=$p] ECHO hi",
10042            "LET $x: STRING = WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
10043            "LET $x: STRING = TIMEOUT 10s ECHO hi",
10044            "LET $x: STRING = TIMEOUT 10s { ECHO hi }",
10045            "LET $x: STRING = TIMEOUT 10s ECHO hi ECHO bye",
10046            "LET $o: STRING = AWAIT $t",
10047            "LET $p: PIPE ECHO bye",
10048            "TIMEOUT 10s WITH_IO [stdin=$p]",
10049            "TIMEOUT 10s WITH_IO [stdin=$p]ECHO hi",
10050            "ISOLATED INHERIT_ENV [A, B]",
10051            "ISOLATED INHERIT_ENV [A-B]",
10052            "TIMEOUT 10s { [os:linux] ECHO hi }",
10053            "ASYNC { [os:linux] ECHO hi }",
10054            "ISOLATED { [os:linux] ECHO hi }",
10055            "[os:linux] WITH_IO [stdin=$p]\n{ ECHO hi }",
10056            "LET $x: INT = 1 ECHO bye",
10057            "CANCEL $t LET $x: INT = 1",
10058            "CANCEL $t $x = 1",
10059            "CANCEL $t RETURN \"hi\"",
10060            "TIMEOUT 10s { ECHO hi } LET $x: INT = 1",
10061            "RUN [\"a\"] ECHO bye",
10062            "[os:linux] AWAIT $t",
10063            "[os:linux] TIMEOUT 10s { ECHO hi } ECHO bye",
10064            "[os:linux] ASYNC CANCEL $t ECHO bye",
10065            "[os:linux] WITH_IO [stdin=$p] { [os:macos] ECHO hi }",
10066        ] {
10067            assert_parity(text);
10068        }
10069    }
10070
10071    #[test]
10072    fn token_and_string_paths_agree_on_blocks() {
10073        // Slice 5: `IF`/`FOR`/`WHILE`/`FUNC` with inline and
10074        // cross-newline `ELSE` chains, guard blocks (top-level and
10075        // nested quirk), and multi-element trailing — three-way
10076        // agreement per script.
10077        for text in [
10078            "IF true { ECHO hi }",
10079            "IF $x { ECHO hi } ELSE { ECHO bye }",
10080            "IF true { ECHO a } ELSE IF false { ECHO b } ELSE { ECHO c }",
10081            "IF true{ ECHO hi }",
10082            "IF true { ECHO hi } ECHO bye",
10083            "IF true { ECHO hi }\nELSE { ECHO bye }",
10084            "IF true { ECHO hi }\nELSE IF false { ECHO b }\nELSE { ECHO c }",
10085            "IF true { ECHO hi } //c\nELSE { ECHO bye }",
10086            "IF true { ECHO hi } #c\nELSE { ECHO bye }",
10087            "IF true { ECHO hi }//c\nELSE { ECHO bye }",
10088            "IF true { ECHO hi } /*c*/ ELSE { ECHO bye }",
10089            "IF true { ECHO hi } /*c1*/ /*c2*/\nELSE { ECHO bye }",
10090            "IF true { /*c*/ ECHO hi }",
10091            "IF true { [os:linux] ECHO hi }",
10092            "TIMEOUT 10s { IF true { ECHO hi } }",
10093            "TIMEOUT 10s { IF true { ECHO hi }\nELSE { ECHO bye } }",
10094            "FOR $x: INT IN [1] { ECHO hi }",
10095            "FOR $k: STRING, $v: INT IN $m { ECHO hi }",
10096            "FOR $k: INT IN [1] { ECHO hi }",
10097            "FOR $x: INT IN [1]{ ECHO hi }",
10098            "FOR $x: MAP<name: STRING> IN [1] { ECHO hi }",
10099            "FOR $x: INT IN [1] { ECHO hi } ECHO bye",
10100            "WHILE true { ECHO hi }",
10101            "WHILE $x { ECHO hi }",
10102            "WHILE true{ ECHO hi }",
10103            "TIMEOUT 10s WHILE true { ECHO hi }",
10104            "ASYNC WHILE true { ECHO hi }",
10105            "FUNC FOO(): INT { RETURN 1 }",
10106            "FUNC FOO(): INT { RETURN 1 }",
10107            "FUNC FOO($x: INT): INT { RETURN $x }",
10108            "FUNC FOO($x: INT, $y: STRING): INT { RETURN $x }",
10109            "FUNC FOO(): INT { FUNC FOO(): INT { RETURN 1 } }",
10110            "FUNC FOO(): INT { RETURN 1 }\nFUNC BAR(): VOID { FOO() }\nBAR()",
10111            "TYPE PERSON = MAP<name: STRING>",
10112            "TYPE A=B",
10113            "TYPE A = B | C",
10114            "TYPE A = B\nTYPE A = C",
10115            "INHERIT_ENV [A]\nECHO hi",
10116            "[os:linux] INHERIT_ENV [M]",
10117            "INHERIT_ENV [A]\nINHERIT_ENV [B]\nECHO hi",
10118            "ISOLATED INHERIT_ENV [M]",
10119            "ISOLATED { INHERIT_ENV [M] }",
10120            "ISOLATED INHERIT_ENV [A, B]",
10121            "ISOLATED INHERIT_ENV [A-B]",
10122            "REMOTE prod { ECHO hi }",
10123            "REMOTE prod [$v] { ECHO hi }",
10124            "REMOTE prod [$v, env:E] { ECHO hi }",
10125            "REMOTE prod [] { ECHO hi }",
10126            "REMOTE prod[$v] { ECHO hi }",
10127            "REMOTE prod [$v]{ ECHO hi }",
10128            "REMOTE prod{ ECHO hi }",
10129            "REMOTE  prod  { ECHO hi }",
10130            "REMOTE prod [$v, $v] { ECHO hi }",
10131            "REMOTE prod { ECHO hi } ECHO bye",
10132            "TIMEOUT 10s REMOTE prod { ECHO hi }",
10133            "ASYNC REMOTE prod [$v] { ECHO hi }",
10134            "[os:linux] { ECHO hi }",
10135            "[os:linux]\n{ ECHO hi }",
10136            "[os:linux] { [os:macos] ECHO hi }",
10137            "[os:linux] { [os:macos] ECHO hi\nECHO bye }",
10138            "[os:linux] { [os:macos] { ECHO hi } }",
10139            "TIMEOUT 10s { [os:linux] { [os:macos] ECHO hi } }",
10140            "TIMEOUT 10s { [os:linux] [os:windows] { ECHO hi } }",
10141            "TIMEOUT 10s { [os:linux] { ECHO hi } ECHO bye }",
10142            "LET $x: INT = 1 ECHO bye",
10143            KEYWORD_BREAK,
10144            KEYWORD_CONTINUE,
10145            "BREAK ECHO hi",
10146            "FOR $x: INT IN [1] { BREAK }",
10147            "LET $b: STRING = { RETURN \"hi\" }",
10148            "ECHO { RETURN \"hi\" }",
10149            "RUN [{ RETURN \"hi\" }]",
10150            "[not(env:FOO)] WRITE x",
10151            "[\nnot(env:FOO)\n] WRITE x",
10152            "WRITE env.txt \"{{ env:GREETING }}\"",
10153            "CANCEL $t LET $x: INT = 1",
10154            "RUN [\"a\"] ECHO bye",
10155        ] {
10156            assert_parity(text);
10157        }
10158    }
10159
10160    #[test]
10161    fn multi_line_generics_match_single_line_shape() {
10162        // Multi-line `<...>` shapes parse, and canonicalize exactly
10163        // like their single-line spelling.
10164        for (single, multi) in [
10165            (
10166                "TYPE R = MAP<name: STRING, value: INT>",
10167                "TYPE R = MAP<name: STRING,\nvalue: INT>",
10168            ),
10169            (
10170                "TYPE R = MAP<name: STRING, value: LIST<INT>>",
10171                "TYPE R = MAP<name: STRING,\nvalue: LIST<INT>>",
10172            ),
10173            (
10174                "TYPE R = MAP<name: STRING, value: INT>",
10175                "TYPE R = MAP<\nname: STRING,\nvalue: INT\n>",
10176            ),
10177            (
10178                "LET $m: MAP<name: STRING, value: INT> = {}",
10179                "LET $m: MAP<name: STRING,\nvalue: INT> = {}",
10180            ),
10181            (
10182                "FOR $x: LIST<INT> IN [1] { ECHO hi }",
10183                "FOR $x: LIST<\nINT> IN [1] { ECHO hi }",
10184            ),
10185            ("TYPE R = MAP<x: A | B>", "TYPE R = MAP<x: A |\nB>"),
10186        ] {
10187            assert_parity(multi);
10188            let want = crate::parse_script(single, lower)
10189                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
10190            let got = crate::parse_script(multi, lower)
10191                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
10192            assert_eq!(
10193                got, want,
10194                "multi-line must canonicalize like one line: {multi:?}"
10195            );
10196        }
10197    }
10198
10199    #[test]
10200    fn type_field_defaults_parse_to_canonical_targets() {
10201        // Token-level regression: `= literal` tails belong to the
10202        // field (floats lex as three tokens), and the statement
10203        // target canonicalizes exactly like the spelling parser.
10204        for (text, want) in [
10205            ("TYPE F = MAP<retries: INT = 2>", "MAP<retries: INT = 2>"),
10206            ("TYPE F = MAP<retries: INT=-2>", "MAP<retries: INT = -2>"),
10207            (
10208                "TYPE F = MAP<ratio: FLOAT = 2.5>",
10209                "MAP<ratio: FLOAT = 2.5>",
10210            ),
10211            ("TYPE F = MAP<on: BOOL = true>", "MAP<on: BOOL = true>"),
10212            (
10213                "TYPE F = MAP<model: STRING = \"gpt-4\">",
10214                "MAP<model: STRING = \"gpt-4\">",
10215            ),
10216            (
10217                "TYPE F = MAP<k: STRING = \"d\", n: INT = 3>",
10218                "MAP<k: STRING = \"d\", n: INT = 3>",
10219            ),
10220        ] {
10221            assert_parity(text);
10222            let steps = crate::parse_script(text, lower)
10223                .unwrap_or_else(|e| panic!("default spelling must parse {text:?}: {e}"));
10224            let target = steps
10225                .iter()
10226                .find_map(|s| match &s.kind {
10227                    StepKind::TypeAlias { target, .. } => Some(target.clone()),
10228                    _ => None,
10229                })
10230                .expect("TYPE alias step");
10231            assert_eq!(target, want, "canonical target for {text:?}");
10232        }
10233    }
10234
10235    #[test]
10236    fn multi_line_run_exec_matches_single_line_shape() {
10237        // `RUN [...]` rides the shared bracket core, so a wrapped exec
10238        // list parses exactly like its single-line spelling (and agrees
10239        // across lexer frontends).
10240        for (single, multi) in [
10241            ("RUN [\"echo\", \"hi\"]", "RUN [\"echo\",\n\"hi\"]"),
10242            ("RUN [\"echo\", \"hi\"]", "RUN [\n\"echo\",\n\"hi\"\n]"),
10243            (
10244                "LET $o: STRING = RUN [\"echo\", \"hi\"]",
10245                "LET $o: STRING = RUN [\"echo\",\n\"hi\"]",
10246            ),
10247        ] {
10248            assert_parity(multi);
10249            let want = crate::parse_script(single, lower)
10250                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
10251            let got = crate::parse_script(multi, lower)
10252                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
10253            assert_eq!(
10254                got, want,
10255                "multi-line must canonicalize like one line: {multi:?}"
10256            );
10257        }
10258    }
10259
10260    #[test]
10261    fn untyped_let_fails_in_every_rhs_shape() {
10262        // The everything-typed rule: a missing `:` is a hard error
10263        // carrying the explicit-types message, regardless of what
10264        // follows the `=`. Every binding shape is covered, so no
10265        // untyped position can slip back in unnoticed.
10266        for text in [
10267            "LET $x = 1\n",
10268            "LET $x = \"hi\"\n",
10269            "LET $x = $y\n",
10270            "LET $x = [\"a\", \"b\"]\n",
10271            "LET $x = [\"a\",\n\"b\"]\n",
10272            "LET $x = ECHO hi\n",
10273            "LET $x = AWAIT $t\n",
10274            "LET $x = ASYNC ECHO hi\n",
10275            "LET $x = {\nRETURN 1\n}\n",
10276            "LET $x = WITH_IO [stdin=$p] ASYNC ECHO hi\n",
10277        ] {
10278            let err = crate::parse_script(text, lower).expect_err("untyped LET must fail");
10279            assert!(
10280                err.to_string().contains("LET requires explicit types"),
10281                "wrong error for {text:?}: {err}"
10282            );
10283        }
10284        // Typed spellings of the same shapes keep parsing through
10285        // every lexer frontend.
10286        for text in [
10287            "LET $x: INT = 1\n",
10288            "LET $x: STRING = \"hi\"\n",
10289            "LET $x: LIST<STRING> = [\"a\", \"b\"]\n",
10290            "LET $x: LIST<STRING> = [\"a\",\n\"b\"]\n",
10291            "LET $x: STRING = ECHO hi\n",
10292            "LET $x: STRING = AWAIT $t\n",
10293            "LET $x: HANDLE<VOID> = ASYNC ECHO hi\n",
10294            "LET $x: INT = {\nRETURN 1\n}\n",
10295        ] {
10296            assert_parity(text);
10297        }
10298    }
10299
10300    #[test]
10301    fn missing_comma_points_at_the_item() {
10302        // A forgotten comma between items names the missing
10303        // comma and points at the item's line, not the statement
10304        // head. Lists and call arguments share the rule.
10305        let text = indoc! {r#"
10306            LET $x: LIST<STRING> = [
10307            "a"
10308            "b",
10309            "c"
10310            ]
10311        "#};
10312        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
10313        assert!(
10314            err.to_string().contains("missing comma between list items"),
10315            "wrong error: {err}"
10316        );
10317        assert_eq!(err.line(), 3, "caret names the item line: {err}");
10318        // Same shape on one line.
10319        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" \"b\"]\n", lower)
10320            .expect_err("missing comma must fail");
10321        assert!(
10322            err.to_string().contains("missing comma between list items"),
10323            "wrong error: {err}"
10324        );
10325        assert_eq!(err.line(), 1, "single-line points at line 1: {err}");
10326        // Call arguments share the rule.
10327        let err = crate::parse_script("LET $x: STRING = FOO(\"a\" \"b\")\n", lower)
10328            .expect_err("missing comma must fail");
10329        assert!(
10330            err.to_string()
10331                .contains("missing comma between call arguments"),
10332            "wrong error: {err}"
10333        );
10334        // Genuine trailing garbage keeps the old message but still
10335        // points at the garbage instead of the statement head.
10336        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" : \"b\"]\n", lower)
10337            .expect_err("garbage must fail");
10338        assert!(
10339            err.to_string().contains("unexpected text in list"),
10340            "wrong error: {err}"
10341        );
10342        // Maps share the rule: a forgotten comma between entries
10343        // names it at the entry's line instead of misreporting the
10344        // key as an unknown command.
10345        let text = indoc! {r#"
10346            LET $m: MAP<name: STRING> = {
10347            name: "a"
10348            value: "b"
10349            }
10350        "#};
10351        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
10352        assert!(
10353            err.to_string()
10354                .contains("missing comma between map entries"),
10355            "wrong error: {err}"
10356        );
10357        assert_eq!(err.line(), 3, "caret names the entry line: {err}");
10358        let err = crate::parse_script(
10359            "LET $m: MAP<name: STRING> = {name: \"a\" value: \"b\"}\n",
10360            lower,
10361        )
10362        .expect_err("missing comma must fail");
10363        assert!(
10364            err.to_string()
10365                .contains("missing comma between map entries"),
10366            "wrong error: {err}"
10367        );
10368    }
10369
10370    #[test]
10371    fn spaced_comparisons_still_end_the_statement() {
10372        // A spaced `<` is a comparison, never a generic open: the
10373        // newline still ends the statement.
10374        let steps = crate::parse_script("LET $b: BOOL = $a < $b\nECHO hi", lower)
10375            .expect("comparison plus follower must parse");
10376        assert_eq!(steps.len(), 2, "newline ends the comparison statement");
10377    }
10378
10379    #[test]
10380    fn token_and_string_paths_agree_on_flat_commands() {
10381        for text in [
10382            "ECHO hi",
10383            "ECHO hi\nWRITE x out",
10384            "WRITE x",
10385            "ECHO \"quoted\" unquoted",
10386            "ENV COVERAGE=covered",
10387            "ECHO a; ECHO b",
10388            "// comment\nECHO hi",
10389            "ECHO 1.0.0 --flag a/b",
10390            "ECHO $x",
10391            "\n\nECHO hi\n\n",
10392        ] {
10393            assert_parity(text);
10394        }
10395    }
10396
10397    #[cfg(feature = "proc-macro-api")]
10398    #[test]
10399    fn backslash_outside_strings_is_string_only() {
10400        // `rustc` rejects a bare `\`, so unquoted backslash escapes
10401        // cannot cross `TokenStream` (same exclusion class as raw-`"`
10402        // blocks): the string lexer keeps them, the token path fails to
10403        // tokenize before v2 is ever reached.
10404        let toks = crate::tok::lex_str("ECHO a\\nb").expect("string lex keeps escapes");
10405        let old = crate::parse_script("ECHO a\\nb", lower).expect("string path parses it");
10406        assert_eq!(
10407            parse_tokens(&toks, lower).expect("token path parses it"),
10408            old
10409        );
10410        assert!("ECHO a\\nb".parse::<proc_macro2::TokenStream>().is_err());
10411    }
10412
10413    #[test]
10414    fn escaped_backslash_pair_is_atomic() {
10415        // `"a\\"` parses (one escape pair plus the closer): the pair
10416        // scans atomically, like the block-string arm and `lex_word`.
10417        // The value stays raw (`\\` verbatim for runtime
10418        // `expand_string`), so this pins parsing, not unescaping.
10419        assert_parity("ECHO \"a\\\\\"");
10420        let steps = crate::parse_script("ECHO \"a\\\\\"", lower).expect("escaped pair must parse");
10421        match &steps[..] {
10422            [s] => assert!(
10423                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a\\\\"),
10424                "escaped pair must survive raw: {s:?}"
10425            ),
10426            _ => panic!("one step: {steps:?}"),
10427        }
10428    }
10429
10430    #[test]
10431    fn joint_double_slash_stays_literal() {
10432        // `rustc` strips `//` before the macro ever runs, so these are
10433        // string-path-only by construction: joint `a//b` is one literal
10434        // arg, and `[a //c]` closes its group (the in-group `//` copy
10435        // stops at the closer).
10436        for text in ["ECHO a//b", "ECHO [a //c]"] {
10437            assert_parity_string_only(text);
10438        }
10439        let steps = crate::parse_script("ECHO a//b", lower).expect("joint slashes parse");
10440        match &steps[..] {
10441            [s] => assert!(
10442                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a//b"),
10443                "joint `//` must glue literally: {s:?}"
10444            ),
10445            _ => panic!("one step: {steps:?}"),
10446        }
10447        let steps = crate::parse_script("ECHO [a //c]", lower).expect("group must close");
10448        assert_eq!(steps.len(), 1, "one step: {steps:?}");
10449        // Full content survives literally: the mock joins WRITE args
10450        // with spaces, so the round trip is byte-exact here.
10451        let steps = crate::parse_script("WRITE f [a //c]", lower).expect("group must close");
10452        match &steps[..] {
10453            [s] => assert!(
10454                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a //c]"),
10455                "group content must survive literally: {s:?}"
10456            ),
10457            _ => panic!("one step: {steps:?}"),
10458        }
10459    }
10460
10461    #[test]
10462    fn block_comment_in_group_closes_like_line_comment() {
10463        // `[a /* c]` reads literally on the old backend (first arg
10464        // `[a`, joined `[a /* c]`), so the in-group `/*` copy breaks
10465        // at the depth-zero closer exactly like `//` does. The bare
10466        // `/*` reads literally too.
10467        for text in ["ECHO [a /* c]", "WRITE f [a /* c]", "ECHO /*"] {
10468            assert_parity_string_only(text);
10469        }
10470        let steps = crate::parse_script("ECHO /*", lower).expect("bare block open parses");
10471        match &steps[..] {
10472            [s] => assert!(
10473                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "/*"),
10474                "bare `/*` must stay literal: {s:?}"
10475            ),
10476            _ => panic!("one step: {steps:?}"),
10477        }
10478        let steps = crate::parse_script("WRITE f [a /* c]", 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]"),
10482                "group content must survive literally: {s:?}"
10483            ),
10484            _ => panic!("one step: {steps:?}"),
10485        }
10486        // Terminated spans keep working through the same path: the
10487        // run carries its closer, so math still gets first refusal.
10488        let steps = crate::parse_script("WRITE f [a /* c */ d]", lower).expect("group must close");
10489        match &steps[..] {
10490            [s] => assert!(
10491                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c */ d]"),
10492                "terminated group content must survive: {s:?}"
10493            ),
10494            _ => panic!("one step: {steps:?}"),
10495        }
10496    }
10497
10498    #[test]
10499    fn single_quoted_multiline_keeps_line_tracking() {
10500        // The `'` arm counts embedded newlines like the `"` arm, so the
10501        // statement after a multiline single-quoted string keeps its
10502        // own lines (func-docs stamping keys off them).
10503        let text = "ECHO 'a\nb'\nECHO c";
10504        assert_parity_string_only(text);
10505        let steps = crate::parse_script(text, lower).expect("must parse");
10506        assert_eq!(steps.len(), 2, "two steps: {steps:?}");
10507        assert_eq!((steps[0].line, steps[0].col), (1, 1));
10508        assert_eq!((steps[1].line, steps[1].col), (3, 1), "{steps:?}");
10509    }
10510
10511    #[test]
10512    fn token_and_string_paths_agree_on_guarded_commands() {
10513        for text in [
10514            "[env:X] ECHO hi",
10515            "[env:A] [os:linux] ECHO hi",
10516            "[os:macos] WRITE x",
10517            "[not(os:windows)] WRITE f x",
10518            "[any(os:macos, os:linux)] ECHO hi",
10519            "[all(env:A, os:linux)] ECHO hi",
10520            "[eq(env:K, v)] ECHO hi",
10521            "[ne(env:K, v)] ECHO hi",
10522            "[bool:true] ECHO hi",
10523            "[arch:arm] ECHO hi",
10524            "[family:unix] ECHO hi",
10525            "[(os:linux)] ECHO hi",
10526            "[env:A, os:linux] ECHO hi",
10527            "WRITE x\n[env:X] ECHO hi",
10528            "[env:K] ECHO $x",
10529            "[__OXDOCK_INJECT_1__] ECHO hi",
10530            "[eq(env:K, \"a b\")] ECHO hi",
10531            "[\nenv:X\n] ECHO hi",
10532            // In-body brackets are raw text split on whitespace (probed
10533            // parity: `[a, b]` is args `"[a,"` + `"b]"`, quotes kept).
10534            "ECHO [a, b] hi",
10535            "WRITE f [env:X]",
10536            "ECHO [env:X] hi",
10537            "WRITE f [\"a b\"]",
10538            "ECHO foo[bar]baz",
10539            "ECHO [a ]",
10540            "ECHO [ a]",
10541            "WRITE out x [env:X]",
10542        ] {
10543            assert_parity(text);
10544        }
10545        // `rustc` lexes `'a` as a lifetime start and rejects the
10546        // space: string-path-only by construction.
10547        assert_parity_string_only("ECHO ['a b']");
10548    }
10549
10550    #[test]
10551    fn token_and_string_paths_agree_on_calls_and_exact_args() {
10552        use crate::ast::{ModuleFuncs, ModuleTable};
10553        use std::collections::{HashMap, HashSet};
10554        let std_table = || ModuleTable {
10555            modules: HashMap::from([(
10556                crate::constants::STD_MODULE_NAME.to_string(),
10557                Some(ModuleFuncs {
10558                    func_names: HashSet::from(["LEN".to_string()]),
10559                }),
10560            )]),
10561        };
10562        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10563            test_lower_mock::lower(name, args)
10564        }
10565        // One table for both pathways: STD exports LEN.
10566        // Rebuilt per case (parse-time only, keeps borrows local).
10567        for text in [
10568            "LET $n: INT = STD::LEN(\"hi\")",
10569            "STD::LEN(\"hi\")",
10570            "LET $n: INT = STD::LEN(\"a\", \"b\")",
10571            "LET $s: STRING = INSPECT($x)",
10572            "INSPECT($x)",
10573            "LET $x: STRING = ECHO hi",
10574            "LET $t: STRING = WRITE x",
10575            "LET $o: STRING = RUN echo hi",
10576            "RUN [\"echo\", \"hi\"]",
10577            "RUN echo [a]",
10578            "LET $r: STRING = RUN [\"echo\"]",
10579            "ECHO K=v",
10580            "ECHO K = v",
10581            "ECHO K=a b",
10582            "ECHO K=a, b",
10583            "ECHO K=\"a b\"",
10584            "ECHO K=$x",
10585            "ECHO K=",
10586            "ECHO a = = b",
10587            "WRITE f K=v",
10588            "ECHO $a + $b",
10589            "ECHO $a==$b",
10590            "ECHO a $x b",
10591            "ECHO 5 + 3",
10592            "WRITE f ( \"hi\" )",
10593            "ECHO [a, b] hi",
10594            "ECHO {{x}}",
10595            "ECHO {{ $x }}",
10596            "ECHO $x=K",
10597            "ECHO a$x",
10598            "ECHO a$(x)",
10599            "ECHO K=$x tail",
10600            "EXPAND K1=$x K2=$y",
10601            "EXPAND a",
10602            "ENV K = v",
10603            "COPY a b",
10604            "ECHO foo[bar]baz",
10605            "LET $x: STRING = FOOBAR",
10606            "STD::LEN(\"hi\") ECHO bye",
10607            "LET $n: INT = STD::LEN(\"a\") ECHO bye",
10608            "TIMEOUT 10s STD::LEN(\"hi\")",
10609            "TIMEOUT 10s STD::LEN(\"hi\") ECHO bye",
10610            "LET $n: INT = STD::LEN(\"a\")STD::LEN(\"b\")",
10611        ] {
10612            let table = std_table();
10613            let old =
10614                crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
10615                    .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
10616            let reserved = HashSet::new();
10617            let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
10618            let toks = crate::tok::lex_str(text).expect("string lex must succeed");
10619            let new = parse_tokens_with_ctx(&toks, &ctx)
10620                .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
10621            assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
10622            #[cfg(feature = "proc-macro-api")]
10623            {
10624                let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
10625                let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
10626                let new = parse_tokens_with_ctx(&toks, &ctx)
10627                    .unwrap_or_else(|e| panic!("token path must parse token {text:?}: {e}"));
10628                assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
10629            }
10630        }
10631    }
10632
10633    #[test]
10634    fn placeholder_bare_calls_resolve_like_statements() {
10635        // `{{ NAME(args) }}` obeys exactly the statement-position
10636        // scope rule: `IMPORT [MOD]` brings the names into scope,
10637        // unimported names fail naming the fix, ambiguity fails
10638        // closed. The rewrite below is byte-identical past the
10639        // qualified head, so expansion sees the same args.
10640        use crate::ast::{ModuleFuncs, ModuleTable};
10641        use std::collections::{HashMap, HashSet};
10642        let table = || ModuleTable {
10643            modules: HashMap::from([
10644                (
10645                    crate::constants::STD_MODULE_NAME.to_string(),
10646                    Some(ModuleFuncs {
10647                        func_names: HashSet::from(["LEN".to_string()]),
10648                    }),
10649                ),
10650                (
10651                    "OTHER".to_string(),
10652                    Some(ModuleFuncs {
10653                        func_names: HashSet::from(["LEN".to_string()]),
10654                    }),
10655                ),
10656            ]),
10657        };
10658        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10659            test_lower_mock::lower(name, args)
10660        }
10661        fn echo_text(steps: &[crate::Step]) -> String {
10662            match steps {
10663                [s] => match &s.kind {
10664                    StepKind::Echo(Arg::String(text, _)) => text.clone(),
10665                    other => panic!("expected ECHO string, got {other:?}"),
10666                },
10667                _ => panic!("expected one step, got {steps:?}"),
10668            }
10669        }
10670        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10671            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10672        }
10673        // Imported bare names qualify; everything else rides through
10674        // byte-identical for the runtime to handle as before.
10675        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }}\"\n";
10676        let out = echo_text(&parse(text, table()).expect("imported bare call parses"));
10677        assert_eq!(out, "n: {{ STD::LEN($x) }}", "bare call qualifies: {out}");
10678        let text = "IMPORT [STD]\nECHO \"n: {{ STD::LEN($x) }}\"\n";
10679        let out = echo_text(&parse(text, table()).expect("qualified parses"));
10680        assert_eq!(
10681            out, "n: {{ STD::LEN($x) }}",
10682            "qualified keys stay untouched: {out}"
10683        );
10684        let text = "IMPORT [STD]\nECHO \"hi {{ $x }} and {{ bare }} and {{ env:K }}\"\n";
10685        let out = echo_text(&parse(text, table()).expect("non-calls parse"));
10686        assert_eq!(
10687            out, "hi {{ $x }} and {{ bare }} and {{ env:K }}",
10688            "non-call keys stay untouched: {out}"
10689        );
10690        let text = "IMPORT [STD]\nECHO \"lit \\{{ LEN($x) }}\"\n";
10691        let out = echo_text(&parse(text, table()).expect("escaped parses"));
10692        assert_eq!(
10693            out, "lit \\{{ LEN($x) }}",
10694            "escaped openers stay literal: {out}"
10695        );
10696        // Nested bodies resolve against the enclosing imports, exactly
10697        // like statement-position calls in the same body.
10698        let text = indoc! {r#"
10699            IMPORT [STD]
10700            FUNC F(): VOID {
10701            ECHO "n: {{ LEN($x) }}"
10702            }
10703        "#};
10704        let steps = parse(text, table()).expect("nested bare call parses");
10705        let body = steps.iter().find_map(|s| match &s.kind {
10706            StepKind::FuncDef { body, .. } => Some(body),
10707            _ => None,
10708        });
10709        match body.map(Vec::as_slice) {
10710            Some([inner]) => match &inner.kind {
10711                StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10712                    echoed, "n: {{ STD::LEN($x) }}",
10713                    "nested body qualifies: {echoed}"
10714                ),
10715                other => panic!("expected nested ECHO, got {other:?}"),
10716            },
10717            _ => panic!("expected one FUNC with one body step, got {steps:?}"),
10718        };
10719        // Neighboring placeholders keep their exact bytes: only the
10720        // head span changes, so payloads never lose formatting.
10721        let text = "IMPORT [STD]\nECHO \"Call {{ LEN($x) }} and value {{ $y }}\"\n";
10722        let out = echo_text(&parse(text, table()).expect("mixed template parses"));
10723        assert_eq!(
10724            out, "Call {{ STD::LEN($x) }} and value {{ $y }}",
10725            "only the head span changes: {out}"
10726        );
10727        // Unimported bare names fail exactly like statement position:
10728        // qualify it or add the import.
10729        let err = parse("ECHO \"n: {{ LEN($x) }}\"\n", table()).expect_err("must fail");
10730        assert!(
10731            err.to_string().contains("unknown function `LEN`")
10732                && err.to_string().contains("or add `IMPORT"),
10733            "names the fix: {err}"
10734        );
10735        // Two exporters fail closed instead of picking one.
10736        let err = parse(
10737            "IMPORT [STD]\nIMPORT [OTHER]\nECHO \"n: {{ LEN($x) }}\"\n",
10738            table(),
10739        )
10740        .expect_err("must fail");
10741        assert!(
10742            err.to_string().contains("ambiguous function `LEN`"),
10743            "ambiguity fails closed: {err}"
10744        );
10745        // Both lexing pathways agree on rewritten templates.
10746        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }} and {{ $y }}\"\n";
10747        let table = table();
10748        let old = crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
10749            .expect("string path parses");
10750        let reserved = HashSet::new();
10751        let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
10752        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
10753        let new = parse_tokens_with_ctx(&toks, &ctx).expect("token path parses");
10754        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
10755    }
10756
10757    #[test]
10758    fn placeholder_bare_calls_qualify_in_expr_positions() {
10759        // Regression: `walk_raw_strings_mut` skips `Assign`/`Set`/
10760        // `Call`/`Return`/`If`/`For`/`While`, so `LET`/`RETURN`/call
10761        // args/list/map literals never qualified and failed at
10762        // runtime as undefined variables. Both carriers now qualify.
10763        use crate::ast::{ModuleFuncs, ModuleTable};
10764        use std::collections::{HashMap, HashSet};
10765        let table = || ModuleTable {
10766            modules: HashMap::from([(
10767                crate::constants::STD_MODULE_NAME.to_string(),
10768                Some(ModuleFuncs {
10769                    func_names: HashSet::from(["LEN".to_string()]),
10770                }),
10771            )]),
10772        };
10773        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10774            test_lower_mock::lower(name, args)
10775        }
10776        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10777            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10778        }
10779        // LET string literal qualifies.
10780        let steps = parse(
10781            "IMPORT [STD]\nLET $s: STRING = \"n: {{ LEN($x) }}\"\n",
10782            table(),
10783        )
10784        .expect("LET template parses");
10785        match &steps[0].kind {
10786            StepKind::Bind {
10787                rhs: BindRhs::Expr(expr),
10788                ..
10789            } => match expr {
10790                Expr::Literal(value) => assert_eq!(
10791                    value.as_str().unwrap_or_default(),
10792                    "n: {{ STD::LEN($x) }}",
10793                    "LET qualifies"
10794                ),
10795                other => panic!("expected literal, got {other:?}"),
10796            },
10797            other => panic!("expected Bind, got {other:?}"),
10798        }
10799        // RETURN string literal qualifies.
10800        let steps = parse(
10801            "IMPORT [STD]\nFUNC F(): STRING {\nRETURN \"n: {{ LEN($x) }}\"\n}\n",
10802            table(),
10803        )
10804        .expect("RETURN template parses");
10805        let body = steps.iter().find_map(|s| match &s.kind {
10806            StepKind::FuncDef { body, .. } => Some(body),
10807            _ => None,
10808        });
10809        match body.map(Vec::as_slice) {
10810            Some([inner]) => match &inner.kind {
10811                StepKind::Return { expr, .. } => match &**expr {
10812                    Expr::Literal(value) => assert_eq!(
10813                        value.as_str().unwrap_or_default(),
10814                        "n: {{ STD::LEN($x) }}",
10815                        "RETURN qualifies"
10816                    ),
10817                    other => panic!("expected literal, got {other:?}"),
10818                },
10819                other => panic!("expected RETURN, got {other:?}"),
10820            },
10821            _ => panic!("expected one FUNC, got {steps:?}"),
10822        }
10823        // Call args, list and map literals qualify.
10824        let steps = parse(
10825            "IMPORT [STD]\nLET $y: INT = LEN(\"b: {{ LEN($x) }}\")\n",
10826            table(),
10827        )
10828        .expect("call-arg template parses");
10829        let rendered = format!("{:?}", steps[0].kind);
10830        assert!(
10831            rendered.contains("STD::LEN"),
10832            "call arg qualifies: {rendered}"
10833        );
10834        let steps = parse(
10835            "IMPORT [STD]\nLET $l: LIST<STRING> = [\"{{ LEN($x) }}\"]\n",
10836            table(),
10837        )
10838        .expect("list template parses");
10839        let rendered = format!("{:?}", steps[0].kind);
10840        assert!(rendered.contains("STD::LEN"), "list qualifies: {rendered}");
10841        // Compound placeholders are not single calls: they pass
10842        // through untouched (no partial rewrite) for the runtime to
10843        // fail closed on the whole key.
10844        let text = "IMPORT [STD]\nECHO \"v: {{ LEN($a) + LEN($b) }}\"\n";
10845        let steps = parse(text, table()).expect("compound parses");
10846        match &steps[0].kind {
10847            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10848                echoed, "v: {{ LEN($a) + LEN($b) }}",
10849                "compound untouched: {echoed}"
10850            ),
10851            other => panic!("expected ECHO string, got {other:?}"),
10852        }
10853        // Quoted parens inside args do not end the call early.
10854        let text = "IMPORT [STD]\nECHO 'v: {{ LEN(\"a(b\") }}'\n";
10855        let steps = parse(text, table()).expect("quoted paren parses");
10856        match &steps[0].kind {
10857            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10858                echoed, "v: {{ STD::LEN(\"a(b\") }}",
10859                "quoted paren qualifies: {echoed}"
10860            ),
10861            other => panic!("expected ECHO string, got {other:?}"),
10862        }
10863        // Single-quoted args balance the same way.
10864        let text = "IMPORT [STD]\nECHO \"v: {{ LEN('a(b') }}\"\n";
10865        let steps = parse(text, table()).expect("single-quoted paren parses");
10866        match &steps[0].kind {
10867            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10868                echoed, "v: {{ STD::LEN('a(b') }}",
10869                "single-quoted paren qualifies: {echoed}"
10870            ),
10871            other => panic!("expected ECHO string, got {other:?}"),
10872        }
10873        // `WithIo` boxes its inner command directly (no recursive
10874        // statement pass), so the qualifier must descend into it.
10875        // `LET $p: PIPE` plus bindings keep the shape realistic.
10876        let text = "IMPORT [STD]\nLET $p: PIPE\nWITH_IO [stdout=$p] ECHO 'v: {{ LEN($x) }}'\n";
10877        let steps = parse(text, table()).expect("with-io template parses");
10878        match &steps[1].kind {
10879            StepKind::WithIo { cmd, .. } => {
10880                let rendered = format!("{cmd:?}");
10881                assert!(
10882                    rendered.contains("STD::LEN"),
10883                    "with-io inner qualifies: {rendered}"
10884                );
10885            }
10886            other => panic!("expected WithIo, got {other:?}"),
10887        }
10888        // Single-command wrappers build synthetic body steps without a
10889        // recursive pass: `TIMEOUT 5s <cmd>` and `ASYNC <cmd>` share
10890        // the outer frame, so the qualifier must descend into bodies.
10891        let text = "IMPORT [STD]\nTIMEOUT 5s ECHO 't: {{ LEN($x) }}'\n";
10892        let steps = parse(text, table()).expect("timeout template parses");
10893        let rendered = format!("{:?}", steps[0].kind);
10894        assert!(
10895            rendered.contains("STD::LEN"),
10896            "timeout single qualifies: {rendered}"
10897        );
10898        let text = "IMPORT [STD]\nLET $h: HANDLE<ANY> = ASYNC ECHO 'a: {{ LEN($x) }}'\n";
10899        let steps = parse(text, table()).expect("async template parses");
10900        let rendered = format!("{:?}", steps[0].kind);
10901        assert!(
10902            rendered.contains("STD::LEN"),
10903            "async single qualifies: {rendered}"
10904        );
10905        // Brace bodies keep their own frames: the outer qualifier must
10906        // never re-walk them. A valid nested body qualifies via its own
10907        // recursive pass, and an unknown callee inside one fails with
10908        // the inner position, never re-resolved against the outer frame.
10909        let text = "IMPORT [STD]\nIF true {\nECHO 'v: {{ LEN($x) }}'\n}\n";
10910        let steps = parse(text, table()).expect("nested body qualifies");
10911        let rendered = format!("{:?}", steps[0].kind);
10912        assert!(
10913            rendered.contains("STD::LEN"),
10914            "nested IF body qualifies via its own frame: {rendered}"
10915        );
10916        let err = parse(
10917            "IMPORT [STD]\nIF true {\nECHO 'v: {{ NOPE($x) }}'\n}\n",
10918            table(),
10919        )
10920        .expect_err("nested unknown must fail");
10921        assert!(
10922            err.to_string().contains("unknown function `NOPE`"),
10923            "nested unknown names culprit: {err}"
10924        );
10925    }
10926
10927    #[test]
10928    fn block_conditions_name_unknown_callees() {
10929        // Regression: an unknown callee in a block header condition
10930        // used to miss to the generic `IF needs a condition and a
10931        // block` hint. Classified resolution failures now propagate
10932        // and name the culprit on all four speculative headers.
10933        use crate::ast::{ModuleFuncs, ModuleTable};
10934        use std::collections::{HashMap, HashSet};
10935        let table = || ModuleTable {
10936            modules: HashMap::from([(
10937                crate::constants::STD_MODULE_NAME.to_string(),
10938                Some(ModuleFuncs {
10939                    func_names: HashSet::from(["LEN".to_string()]),
10940                }),
10941            )]),
10942        };
10943        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10944            test_lower_mock::lower(name, args)
10945        }
10946        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10947            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10948        }
10949        for text in [
10950            "IMPORT [STD]\nIF NOPE($x) == 0 {\nECHO hi\n}\n",
10951            "IMPORT [STD]\nIF LEN($x) == 0 {\nECHO hi\n} ELSE IF NOPE($x) == 1 {\nECHO yo\n}\n",
10952            "IMPORT [STD]\nWHILE NOPE($x) > 0 {\nECHO hi\n}\n",
10953            "IMPORT [STD]\nFOR $i: STRING IN NOPE($x) {\nECHO $i\n}\n",
10954        ] {
10955            let err = parse(text, table()).expect_err("unknown callee must fail");
10956            assert!(
10957                err.to_string().contains("unknown function `NOPE`"),
10958                "names the culprit: {err}"
10959            );
10960        }
10961        // Unclassified shape misses still miss (the exact generic
10962        // hint comes from the real dispatcher, which the mock lacks).
10963        parse("IF {\nECHO hi\n}\n", table()).expect_err("empty condition must still fail");
10964    }
10965
10966    #[test]
10967    fn token_and_string_paths_agree_on_let_set_return() {
10968        for text in [
10969            "LET $x: INT = 1",
10970            "LET $s: STRING = \"hi\"",
10971            "LET $b: BOOL = true",
10972            "LET $f: FLOAT = 1.5",
10973            "LET $p: PIPE",
10974            "LET $l: LIST<STRING> = [\"a\", \"b\"]",
10975            "LET $e: LIST<STRING> = []",
10976            "LET $m: MAP = {k: 1}",
10977            "LET $m2: MAP = {\"a b\": 2, k: [1, 2]}",
10978            "LET $n: INT = $a + $b",
10979            "LET $c: BOOL = ($a == 3) && ($b == 4)",
10980            "LET $g: BOOL = !$ok",
10981            "LET $nn: BOOL = true && false",
10982            "LET $e2: STRING = env:HOME",
10983            "LET $k: STRING = $a.b.c",
10984            "LET $u: INT = -5",
10985            "LET $v: INT = 9223372036854775807",
10986            "LET $min: INT = -9223372036854775808",
10987            "LET $w: INT = 1_000",
10988            "LET $z: STRING = a/b",
10989            "LET $d: STRING = -f",
10990            "LET $t: STRING = 30s",
10991            "LET $q: STRING = \"\"\"hi\"\"\"",
10992            "LET $f2: FLOAT = 2 * -3",
10993            "LET $o: BOOL = 2 + 3 > 4",
10994            "LET $l2: LIST< MAP > = []",
10995            "LET $a1: INT = 1 + 2",
10996            "LET $s1: INT = 10 - 4 - 3",
10997            "LET $m1: INT = 2 * 3 + 4",
10998            "LET $x1: BOOL = 1 < 2 == true",
10999            "LET $or: BOOL = $a || $b",
11000            "LET $dbl: BOOL = !!$x",
11001            "LET $ver: STRING = 1.0.0",
11002            "LET $dash: STRING = a-b",
11003            "LET $div: INT = 4 / 2",
11004            "LET $bad: INT = 1__0 + 0",
11005            "LET $strdiv: STRING = 4/2",
11006            "LET $sp: INT = $a - $b",
11007            "$x = 1",
11008            "$x = $a + 1",
11009            "RETURN 1",
11010            KEYWORD_RETURN,
11011            "RETURN $x",
11012            "[env:X] LET $x: INT = 1",
11013            "[os:linux] $x = 2",
11014        ] {
11015            assert_parity(text);
11016        }
11017    }
11018
11019    #[test]
11020    fn malformed_shapes_fail_on_both_paths() {
11021        // Malformed shapes fail on both lexers (messages may differ;
11022        // success/failure must agree). Unbalanced groups fail even
11023        // earlier, at lex time: both layers reject, which is what the
11024        // oracle pins.
11025        for text in [
11026            "[a] ECHO hi",
11027            "[os:atari] ECHO hi",
11028            "[foo:bar] ECHO hi",
11029            "[any(os:linux)] ECHO hi",
11030            "[all()] ECHO hi",
11031            "[env:] ECHO hi",
11032            "[eq(env:K)] ECHO hi",
11033            "[not] ECHO hi",
11034            "ECHO [a;b]",
11035            "ECHO (a;b)",
11036            "ECHO a;b",
11037            "LET $x = 1",
11038            "LET $s: STRING",
11039            "LET $x: INT = 1 2",
11040            "LET $x: INT = (1",
11041            "LET $x: INT = 9223372036854775808",
11042            "$x =",
11043            "RETURN (",
11044            "[env:X]",
11045            "LET $x: INT = $a == $b == $c",
11046            "LET $x: BOOL = $a < $b < $c",
11047            "LET $bs: STRING = a\\nb",
11048            "FOO(\"a\")",
11049            "FOO (\"a\")",
11050            "ECHO FOO(\"a\")",
11051            "ECHO(\"hi\")",
11052            "RUN [a] extra",
11053            "RUN[\"a\"]",
11054            "TIMEOUT 10s RUN[\"a\"]",
11055            "LET $r: STRING = RUN[\"a\"]",
11056            "LET $e: STRING = ECHO",
11057            "ENV A=1 B=2",
11058            "EXPAND \"a b\" c",
11059            "ECHO {a}",
11060            "ECHO K=${x}",
11061            "[!env:A==1] RUN echo no",
11062            "run echo hi",
11063            "LET $x: STRING = AWAIT",
11064            "LET $o: STRING = CANCEL $t",
11065            "LET $x: STRING = ASYNC",
11066            "LET $x: STRING = WITH_IO",
11067            "LET $x: STRING = TIMEOUT",
11068            "LET $x: STRING = ISOLATED",
11069            "LET $x: STRING = ISOLATED ECHO hi",
11070            "COPY A=1",
11071            "WITH_IO [rows=40] RUN echo hi",
11072            "WITH_IO [tty] ECHO hi",
11073            "WITH_IO [tty, stderr=$p] RUN echo hi",
11074            "WITH_IO [tty=$p] RUN echo hi",
11075            "WITH_IO [cols=0] RUN echo hi",
11076            "WITH_IO [cols=65536] RUN echo hi",
11077            "WITH_IO [] ECHO hi",
11078            "WITH_IO [stdin=$p,] ECHO hi",
11079            "WITH_IO stdin=$p ECHO hi",
11080            "WITH_IO [STDIN=$p] ECHO hi",
11081            "WITH_IO [rows] RUN echo hi",
11082            KEYWORD_WITH_IO,
11083            "WITH_IO [stdout=$p]",
11084            "WITH_IO [stdin=$p]\n[os:linux] { ECHO hi }",
11085            "WITH_IO [stdin=$p] { }",
11086            "WITH_IO[stdin=$p] ECHO hi",
11087            "WITH_IO [stdin=$p]ECHO hi",
11088            "WITH_IO [stdin=$p] {{ $x }}",
11089            "ASYNC WITH_IO [stdout=$p] ECHO hi",
11090            "WITH_IO [stdin=$p] AWAIT $t",
11091            "ASYNC AWAIT $t",
11092            "WITH_IO [stdin=$p] RETURN \"hi\"",
11093            "ASYNC RETURN \"hi\"",
11094            "TIMEOUT 10s RETURN \"hi\"",
11095            "TIMEOUT banana ECHO hi",
11096            "TIMEOUT 10ss ECHO hi",
11097            "TIMEOUT 10 s ECHO hi",
11098            "TIMEOUT -5s ECHO hi",
11099            "TIMEOUT 0s ECHO hi",
11100            KEYWORD_TIMEOUT,
11101            "TIMEOUT 10s",
11102            "TIMEOUT { ECHO hi }",
11103            "TIMEOUT \"10s\"",
11104            "TIMEOUT 10s{ECHO hi}",
11105            "TIMEOUT 10sECHO hi",
11106            "TIMEOUT 10s {{ $d }}",
11107            "TIMEOUT 10s { $d }",
11108            "TIMEOUT { $d } ECHO hi",
11109            KEYWORD_ASYNC,
11110            KEYWORD_ISOLATED,
11111            "ISOLATED{ECHO hi}",
11112            KEYWORD_AWAIT,
11113            KEYWORD_CANCEL,
11114            "AWAIT t",
11115            "AWAIT $",
11116            "AWAIT $t extra",
11117            "CANCEL $t extra",
11118            "TIMEOUT 5s INHERIT_ENV [M]",
11119            "TIMEOUT 5s { INHERIT_ENV [M] }",
11120            "ASYNC { INHERIT_ENV [M] }",
11121            "LET $x: STRING = INHERIT_ENV [M]",
11122            "TIMEOUT 10s WITH_IO [stdin=$p] { ECHO hi }",
11123            "ISOLATED WITH_IO [stdin=$p] { ECHO hi }",
11124            "TIMEOUT 10s AWAIT $ t",
11125            "LET $o: STRING = AWAIT $ t",
11126            "ISOLATED AWAIT $ t",
11127            "WITH_IO [stdin=$p] CANCEL $ t",
11128            "LET $ x: INT = 1",
11129            "LET $x: STRING = WITH_IO [stdin=$p] { ECHO hi }",
11130            "LET $x: STRING = WITH_IO [stdin=$p] ASYNC",
11131            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO a\nECHO b }",
11132            "LET $x: STRING = WITH_IO [stdout=$p] ECHO hi",
11133            "LET $x: STRING = TIMEOUT 10s AWAIT $t",
11134            "LET $x: STRING = CANCEL $t",
11135            "LET $x: STRING = ASYNC",
11136            "LET $x: STRING = WITH_IO",
11137            "TIMEOUT 10s LET $x: INT = 1",
11138            "LET $x: STRING = FOO bar",
11139            "LET(\"a\")",
11140            "AWAIT($t)",
11141            "CANCEL($t)",
11142            "TIMEOUT(\"10s\") ECHO hi",
11143            "RETURN ECHO bye",
11144        ] {
11145            match crate::tok::lex_str(text) {
11146                Err(_) => {
11147                    assert!(
11148                        crate::parse_script(text, lower).is_err(),
11149                        "backend must also reject lex-broken input: {text:?}"
11150                    );
11151                    continue;
11152                }
11153                Ok(toks) => {
11154                    assert!(
11155                        parse_tokens(&toks, lower).is_err(),
11156                        "v2 must explicitly reject (not silently drift): {text:?}"
11157                    );
11158                }
11159            }
11160            assert!(
11161                crate::parse_script(text, lower).is_err(),
11162                "backend must also reject (oracle agreement): {text:?}"
11163            );
11164        }
11165        // No deferred shapes remain: every statement-level block and
11166        // inline-block expression parses natively.
11167    }
11168
11169    #[test]
11170    fn deferred_unknown_callee_beats_validation_arg_error() {
11171        // Directive 5: `WORKSPACE NOPE()` stashes `unknown function
11172        // NOPE` while the fallback raw string fails `WORKSPACE`
11173        // validation. On a well-formed header the stashed callee error
11174        // names the culprit instead of the misleading arg-shape error.
11175        let err =
11176            crate::parse_script("WORKSPACE NOPE()", lower).expect_err("unknown callee must fail");
11177        assert!(
11178            err.to_string().contains("unknown function `NOPE`"),
11179            "deferred must beat validation, got: {err}"
11180        );
11181    }
11182
11183    #[test]
11184    fn paren_line_break_reports_token_position() {
11185        // Directive 5: multiline paren breaks carry the offending
11186        // token's line/col, not a stamped 0/0. The break sits on line 2
11187        // while the statement opens on line 1.
11188        let err = crate::parse_script("ECHO (a\nb)", lower).expect_err("break must fail");
11189        let rendered = err.to_string();
11190        assert!(
11191            rendered.contains("unexpected line break"),
11192            "break must report, got: {rendered}"
11193        );
11194    }
11195
11196    #[test]
11197    fn deferred_unknown_callee_beats_invalid_syntax_arg_error() {
11198        // Fallback raw strings can trigger `InvalidSyntax` lowering
11199        // (for example `COPY NOPE()`). The stashed unknown-callee error
11200        // still names the culprit on a recognized head.
11201        for text in ["COPY NOPE()", "WRITE NOPE()"] {
11202            let err = crate::parse_script(text, lower).expect_err("unknown callee must fail");
11203            assert!(
11204                err.to_string().contains("unknown function `NOPE`"),
11205                "deferred must beat InvalidSyntax for {text:?}, got: {err}"
11206            );
11207        }
11208    }
11209
11210    #[test]
11211    fn deferred_beats_lowering_invalid_syntax_on_plain_heads() {
11212        // Plain command heads own no header grammar, so a lowering
11213        // `InvalidSyntax` there is an argument-shape failure from the
11214        // raw-text fallback: the stashed unknown-callee names the
11215        // culprit on every such head (no per-command allowlist).
11216        let lower_invalid =
11217            |name: &str, _args: Vec<crate::Arg>| -> crate::ParseResult<crate::StepKind> {
11218                Err(crate::ParseError::invalid_syntax(
11219                    name,
11220                    format!("{name} header is malformed"),
11221                    None,
11222                    Vec::new(),
11223                    None,
11224                    &crate::error::SpanContext::line_only(0),
11225                ))
11226            };
11227        for text in [
11228            "ASSERT_EQ $a NOSUCHFUNC()",
11229            "SYMLINK $a NOSUCHFUNC()",
11230            "COPY $a NOSUCHFUNC()",
11231            "WRITE $a NOSUCHFUNC()",
11232        ] {
11233            let err = crate::parse_script(text, lower_invalid).expect_err("arg error must fail");
11234            assert!(
11235                err.to_string().contains("unknown function `NOSUCHFUNC`"),
11236                "deferred must beat lowering InvalidSyntax for {text:?}, got: {err}"
11237            );
11238        }
11239        // Header-owned heads keep their lowering `InvalidSyntax`: the
11240        // native parser missed to the generic path on shape miss, so
11241        // the lowering error names the malformed header while the
11242        // stashed name is its definiendum, never a call.
11243        let err = crate::parse_script("FUNC $a NOSUCHFUNC()", lower_invalid)
11244            .expect_err("header syntax must fail");
11245        assert!(
11246            err.to_string().contains("header is malformed"),
11247            "header InvalidSyntax must stand on FUNC, got: {err}"
11248        );
11249    }
11250
11251    #[test]
11252    fn trailing_tokens_after_func_block_never_hoist() {
11253        // A `FUNC` header with trailing tokens after the body block is
11254        // malformed (the real path rejects it), so pre-declaration
11255        // must not hoist the name: the forward call fails instead of
11256        // resolving.
11257        let err = crate::parse_script(
11258            "LET $x: STRING = FOO()\nFUNC FOO(): STRING { RETURN \"a\" } TRAILING\n",
11259            lower,
11260        )
11261        .expect_err("trailing tokens must fail");
11262        assert!(
11263            err.to_string().contains("unknown function `FOO`"),
11264            "unhoisted forward call must fail, got: {err}"
11265        );
11266    }
11267
11268    #[test]
11269    fn forward_reference_resolves_regardless_of_order() {
11270        // `CALLER` calls `CALLEE` defined later. Top-level
11271        // pre-declaration hoists names before lowering, so order
11272        // does not matter. Runtime still executes sequentially;
11273        // the call below runs after both definitions.
11274        let steps = crate::parse_script(
11275            "FUNC CALLER(): STRING { RETURN CALLEE() }\nFUNC CALLEE(): STRING { RETURN \"forward-ok\" }\n",
11276            lower,
11277        )
11278        .expect("forward ref must parse");
11279        assert!(
11280            matches!(&steps[0].kind, crate::StepKind::FuncDef { name, .. } if name == "CALLER"),
11281            "first def kept, got: {:?}",
11282            steps[0].kind
11283        );
11284    }
11285
11286    #[test]
11287    fn forward_reference_to_guarded_func_resolves() {
11288        // Guarded definitions hoist like unguarded ones: `parse_func_at`
11289        // registers `[os:macos] FUNC FOO` unconditionally, so a forward
11290        // call before the definition must resolve identically to a
11291        // backward call after it.
11292        let steps = crate::parse_script(
11293            "LET $x: STRING = FOO()\n[os:macos] FUNC FOO(): STRING { RETURN \"guarded\" }\n",
11294            lower,
11295        )
11296        .expect("forward guarded ref must parse");
11297        assert!(
11298            matches!(&steps[1].kind, crate::StepKind::FuncDef { name, .. } if name == "FOO"),
11299            "guarded def kept, got: {:?}",
11300            steps[1].kind
11301        );
11302    }
11303}