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    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('<'))) {
4365        p = parse_type_args(toks, skip_type_nl(toks, p + 1))?;
4366        p = skip_type_nl(toks, p);
4367        if !matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('>'))) {
4368            return None;
4369        }
4370        p += 1;
4371    }
4372    Some(p)
4373}
4374
4375fn parse_type_args(toks: &[Tok], pos: usize) -> Option<usize> {
4376    let mut p = parse_type_field(toks, skip_type_nl(toks, pos))?;
4377    loop {
4378        let q = skip_type_nl(toks, p);
4379        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(','))) {
4380            return Some(p);
4381        }
4382        p = parse_type_field(toks, skip_type_nl(toks, q + 1))?;
4383    }
4384}
4385
4386fn parse_type_field(toks: &[Tok], pos: usize) -> Option<usize> {
4387    let mut p = skip_type_nl(toks, pos);
4388    // Optional `name?:` prefix (lowercase names only, like the
4389    // grammar's `field_name`).
4390    if let Some(TokKind::Word(w)) = toks.get(p).map(|t| &t.kind)
4391        && is_lower_ident(w)
4392    {
4393        let mut q = skip_type_nl(toks, p + 1);
4394        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('?'))) {
4395            q = skip_type_nl(toks, q + 1);
4396        }
4397        if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4398            p = skip_type_nl(toks, q + 1);
4399        }
4400    }
4401    let mut p = parse_type_shape(toks, p)?;
4402    // Optional `ALIAS name` clauses (#310.5): one alternate CLI spelling
4403    // per field, but the matcher covers every consecutive clause so the
4404    // spelling parser owns arity (second ALIAS fails there naming both
4405    // names, never here as shape miss). The renderer carries raw tokens
4406    // through. Order is fixed: `TYPE [ALIAS alias]* [= default]`.
4407    loop {
4408        let q = skip_type_nl(toks, p);
4409        if !matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Word(w)) if w == crate::tag::ALIAS_KEYWORD)
4410        {
4411            break;
4412        }
4413        p = skip_type_nl(toks, q + 1);
4414        if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Word(_))) {
4415            p = skip_type_nl(toks, p + 1);
4416        } else {
4417            break;
4418        }
4419    }
4420    // Optional `= ...` default tail: consume to the next field
4421    // delimiter (`,`, `>`, `|` at angle depth zero), tracking `<>`
4422    // so nested shapes ride along. Any spacing, any tokens:
4423    // literals, `$vars`, `env:` reads, calls. The spelling parser
4424    // owns literal validation, so non-literals fail there naming
4425    // the alias instead of missing here as unknown-command noise.
4426    let q = skip_type_nl(toks, p);
4427    if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct('=')))
4428        && !matches!(toks.get(q + 1).map(|t| &t.kind), Some(TokKind::Punct('=')))
4429    {
4430        let mut r = skip_type_nl(toks, q + 1);
4431        let mut depth = 0usize;
4432        loop {
4433            match toks.get(r).map(|t| &t.kind) {
4434                Some(TokKind::Punct('<')) => {
4435                    depth += 1;
4436                    r = skip_type_nl(toks, r + 1);
4437                }
4438                Some(TokKind::Punct('>')) => {
4439                    if depth == 0 {
4440                        break;
4441                    }
4442                    depth -= 1;
4443                    r = skip_type_nl(toks, r + 1);
4444                }
4445                Some(TokKind::Punct(',' | '|')) if depth == 0 => break,
4446                Some(_) => {
4447                    r += 1;
4448                }
4449                None => break,
4450            }
4451        }
4452        p = r;
4453    }
4454    Some(p)
4455}
4456
4457/// Single (non-block) `IF`: condition plus then-block with an
4458/// opportunistic `ELSE` chain (a malformed `ELSE` stays for the
4459/// element loop, which fails it in lowering exactly like the
4460/// grammar). `None` on shape miss (missing/joint-agnostic block or
4461/// unclassified bad condition: generic fails it); classified
4462/// expression failures (unknown/ambiguous callees) and inline-block
4463/// failures propagate (blocks lower here, so their errors surface
4464/// directly).
4465fn parse_if_at(
4466    toks: &[Tok],
4467    pos: usize,
4468    stmt: usize,
4469    ctx: &ParseCtx,
4470) -> Result<Option<(StepKind, usize)>, TokenError> {
4471    // Condition entry skips leading gap comments (`IF` uses `gap`).
4472    let mut lead = Cursor::expr(&toks[pos + 1..], stmt);
4473    lead.skip_gap();
4474    let mut cur = Cursor::expr(&toks[pos + 1 + lead.pos..], stmt);
4475    let cond = match parse_expr_checked(&mut cur, ctx) {
4476        Ok(expr) => expr,
4477        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4478        // Classified failures (unknown/ambiguous callees) name the
4479        // culprit instead of missing to the generic IF hint: the head
4480        // is unambiguously `IF`, so there is no alternative parse.
4481        Err(e) if e.kind.is_some() => return Err(e),
4482        Err(_) => return Ok(None),
4483    };
4484    let cond_end = pos + 1 + lead.pos + cur.pos;
4485    // Then-block: any gap (`gap` zero-width), never a template.
4486    let then_brace = match toks.get(cond_end) {
4487        Some(t)
4488            if matches!(
4489                &t.kind,
4490                TokKind::Group {
4491                    delim: GroupDelim::Brace,
4492                    ..
4493                }
4494            ) && !is_template_brace(t) =>
4495        {
4496            t
4497        }
4498        _ => return Ok(None),
4499    };
4500    let then_inner = match &then_brace.kind {
4501        TokKind::Group { inner, .. } => inner.clone(),
4502        _ => unreachable!(),
4503    };
4504    let then_body = parse_body_steps(&then_inner, stmt, ctx, false)?;
4505    let mut p = cond_end + 1;
4506    // Gap comments between the blocks and `ELSE` vanish (merge
4507    // junctions contribute newlines, crossed like `blank*`).
4508    {
4509        let mut gcur = Cursor::expr(&toks[p..], stmt);
4510        gcur.skip_gap_nl();
4511        p += gcur.pos;
4512    }
4513    let mut else_ifs = Vec::new();
4514    let mut else_body = None;
4515    loop {
4516        // `ELSE IF cond block`: any gaps (non-atomic chain).
4517        let is_else_if = matches!(
4518            toks.get(p).map(|t| &t.kind),
4519            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4520        ) && matches!(
4521            toks.get(p + 1).map(|t| &t.kind),
4522            Some(TokKind::Word(w)) if w == KEYWORD_IF
4523        );
4524        if is_else_if {
4525            let mut ecur = Cursor::expr(&toks[p + 2..], stmt);
4526            ecur.skip_gap();
4527            let econd = match parse_expr_checked(&mut ecur, ctx) {
4528                Ok(expr) => expr,
4529                Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4530                // Same classified-error rule as the `IF` head above:
4531                // an `ELSE IF` with a resolvable-but-unknown callee
4532                // names it instead of silently dropping the branch.
4533                Err(e) if e.kind.is_some() => return Err(e),
4534                Err(_) => break,
4535            };
4536            let ebrace = p + 2 + ecur.pos;
4537            let eblock_ok = matches!(
4538                toks.get(ebrace).map(|t| &t.kind),
4539                Some(TokKind::Group {
4540                    delim: GroupDelim::Brace,
4541                    ..
4542                })
4543            ) && toks.get(ebrace).is_some_and(|t| !is_template_brace(t));
4544            if !eblock_ok {
4545                break;
4546            }
4547            let einner = match &toks[ebrace].kind {
4548                TokKind::Group { inner, .. } => inner.clone(),
4549                _ => unreachable!(),
4550            };
4551            let ebody = parse_body_steps(&einner, stmt, ctx, false)?;
4552            else_ifs.push((Box::new(econd), ebody));
4553            p = ebrace + 1;
4554            // Gap comments before a further `ELSE` vanish too
4555            // (merge junctions contribute newlines).
4556            {
4557                let mut gcur = Cursor::expr(&toks[p..], stmt);
4558                gcur.skip_gap_nl();
4559                p += gcur.pos;
4560            }
4561            continue;
4562        }
4563        // `ELSE block`: same opportunism (a bare `ELSE` stays for
4564        // the loop, failing in lowering like the grammar).
4565        let is_else = matches!(
4566            toks.get(p).map(|t| &t.kind),
4567            Some(TokKind::Word(w)) if w == KEYWORD_ELSE
4568        ) && matches!(
4569            toks.get(p + 1).map(|t| &t.kind),
4570            Some(TokKind::Group {
4571                delim: GroupDelim::Brace,
4572                ..
4573            })
4574        ) && toks.get(p + 1).is_some_and(|t| !is_template_brace(t));
4575        if !is_else {
4576            break;
4577        }
4578        let einner = match &toks[p + 1].kind {
4579            TokKind::Group { inner, .. } => inner.clone(),
4580            _ => unreachable!(),
4581        };
4582        else_body = Some(parse_body_steps(&einner, stmt, ctx, false)?);
4583        p += 2;
4584        break;
4585    }
4586    let kind = StepKind::If {
4587        cond: Box::new(cond),
4588        then_body,
4589        else_ifs,
4590        else_body,
4591    };
4592    Ok(Some((kind, p - pos)))
4593}
4594
4595/// Parse one `CASE` value list: comma-separated expressions up to (not
4596/// including) the arm body brace. Groups are atomic tokens, so commas
4597/// inside calls, lists, and maps never split. Returns the values plus
4598/// the token count consumed past the `CASE` word.
4599fn parse_case_values(
4600    toks: &[Tok],
4601    stmt: usize,
4602    ctx: &ParseCtx,
4603) -> Result<(Vec<Expr>, usize), TokenError> {
4604    let mut values = Vec::new();
4605    let mut p = 0;
4606    loop {
4607        let mut gcur = Cursor::expr(&toks[p..], stmt);
4608        gcur.skip_gap_nl();
4609        let start = p + gcur.pos;
4610        let mut vcur = Cursor::expr(&toks[start..], stmt);
4611        let value = match parse_expr_checked(&mut vcur, ctx) {
4612            Ok(expr) => expr,
4613            Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4614            Err(e) => return Err(e),
4615        };
4616        // A `{ ... }` block is never a case value: without this, a
4617        // missing `CASE` value consumes the arm body as a block
4618        // expression and fails downstream instead of naming the miss.
4619        if matches!(value, Expr::Block(_)) {
4620            return Err(TokenError {
4621                diagnostic: None,
4622                hint: None,
4623                stmt,
4624                line: 0,
4625                col: 0,
4626                msg: format!(
4627                    "{KEYWORD_SWITCH} {KEYWORD_CASE} requires a value or condition before '{{'"
4628                ),
4629                kind: None,
4630            });
4631        }
4632        values.push(value);
4633        p = start + vcur.pos;
4634        let mut gcur = Cursor::expr(&toks[p..], stmt);
4635        gcur.skip_gap_nl();
4636        p += gcur.pos;
4637        if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(','))) {
4638            p += 1;
4639            continue;
4640        }
4641        break;
4642    }
4643    Ok((values, p))
4644}
4645
4646/// Parsed `SWITCH` arms: one value list plus body per `CASE`, with
4647/// an optional trailing `DEFAULT` body.
4648type SwitchArms = (Vec<(Vec<Expr>, Vec<Step>)>, Option<Vec<Step>>);
4649
4650/// Parse the arms inside a `SWITCH` body brace: `CASE <values> { ... }`
4651/// arms plus an optional trailing `DEFAULT { ... }`. Hard errors once
4652/// committed (the `SWITCH` head is unambiguous): unknown words, empty
4653/// bodies, missing blocks, duplicate or non-trailing `DEFAULT`.
4654fn parse_switch_body(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<SwitchArms, TokenError> {
4655    let err = |msg: String| TokenError {
4656        diagnostic: None,
4657        hint: None,
4658        stmt,
4659        line: 0,
4660        col: 0,
4661        msg,
4662        kind: None,
4663    };
4664    let mut cases: Vec<(Vec<Expr>, Vec<Step>)> = Vec::new();
4665    let mut default_body: Option<Vec<Step>> = None;
4666    let mut p = 0;
4667    loop {
4668        let mut gcur = Cursor::expr(&inner[p..], stmt);
4669        gcur.skip_gap_nl();
4670        p += gcur.pos;
4671        if p >= inner.len() {
4672            break;
4673        }
4674        let word = match &inner[p].kind {
4675            TokKind::Word(w) => w.clone(),
4676            _ => {
4677                return Err(err(format!(
4678                    "{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 }} }}`"
4679                )));
4680            }
4681        };
4682        if word == KEYWORD_CASE {
4683            if default_body.is_some() {
4684                return Err(err(format!(
4685                    "{KEYWORD_SWITCH} {KEYWORD_DEFAULT} must be the last arm; no {KEYWORD_CASE} may follow it"
4686                )));
4687            }
4688            let (values, used) = parse_case_values(&inner[p + 1..], stmt, ctx)?;
4689            p += 1 + used;
4690            let mut bcur = Cursor::expr(&inner[p..], stmt);
4691            bcur.skip_gap_nl();
4692            p += bcur.pos;
4693            let arm_ok = matches!(
4694                inner.get(p).map(|t| &t.kind),
4695                Some(TokKind::Group {
4696                    delim: GroupDelim::Brace,
4697                    ..
4698                })
4699            ) && inner.get(p).is_some_and(|t| !is_template_brace(t));
4700            if !arm_ok {
4701                return Err(err(
4702                    "SWITCH CASE needs a braced block, e.g. `CASE \"a\", \"b\" { ECHO yes }`"
4703                        .to_string(),
4704                ));
4705            }
4706            let arm_inner = match &inner[p].kind {
4707                TokKind::Group { inner, .. } => inner.clone(),
4708                _ => unreachable!(),
4709            };
4710            let body = parse_body_steps(&arm_inner, stmt, ctx, false)?;
4711            cases.push((values, body));
4712            p += 1;
4713        } else if word == KEYWORD_DEFAULT {
4714            if default_body.is_some() {
4715                return Err(err(format!(
4716                    "{KEYWORD_SWITCH} allows only one {KEYWORD_DEFAULT} arm"
4717                )));
4718            }
4719            p += 1;
4720            let mut bcur = Cursor::expr(&inner[p..], stmt);
4721            bcur.skip_gap_nl();
4722            p += bcur.pos;
4723            let arm_ok = matches!(
4724                inner.get(p).map(|t| &t.kind),
4725                Some(TokKind::Group {
4726                    delim: GroupDelim::Brace,
4727                    ..
4728                })
4729            ) && inner.get(p).is_some_and(|t| !is_template_brace(t));
4730            if !arm_ok {
4731                return Err(err(
4732                    "SWITCH DEFAULT needs a braced block, e.g. `DEFAULT { ECHO fallback }`"
4733                        .to_string(),
4734                ));
4735            }
4736            let arm_inner = match &inner[p].kind {
4737                TokKind::Group { inner, .. } => inner.clone(),
4738                _ => unreachable!(),
4739            };
4740            default_body = Some(parse_body_steps(&arm_inner, stmt, ctx, false)?);
4741            p += 1;
4742        } else {
4743            return Err(err(format!(
4744                "{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 }} }}`"
4745            )));
4746        }
4747    }
4748    if cases.is_empty() && default_body.is_none() {
4749        return Err(err(format!(
4750            "{KEYWORD_SWITCH} needs at least one {KEYWORD_CASE} or {KEYWORD_DEFAULT} arm"
4751        )));
4752    }
4753    Ok((cases, default_body))
4754}
4755
4756/// `SWITCH [disc] { CASE v, ... { ... } ... [DEFAULT { ... }] }` or
4757/// bare `SWITCH { CASE <bool> { ... } ... }`. `None` on shape miss (no
4758/// outer brace: falls to generic, which fails it with the SWITCH hint);
4759/// classified expression failures propagate like `IF`, and arm errors
4760/// are hard (the head commits the shape).
4761fn parse_switch_at(
4762    toks: &[Tok],
4763    pos: usize,
4764    stmt: usize,
4765    ctx: &ParseCtx,
4766) -> Result<Option<(StepKind, usize)>, TokenError> {
4767    // Bare head: gaps skipped like the discriminant entry below; the
4768    // token then opens the body brace, so no discriminant is parsed
4769    // (every `CASE` carries its own condition).
4770    let mut gap = Cursor::expr(&toks[pos + 1..], stmt);
4771    gap.skip_gap();
4772    let brace_pos = pos + 1 + gap.pos;
4773    let bare_head = matches!(
4774        toks.get(brace_pos).map(|t| &t.kind),
4775        Some(TokKind::Group {
4776            delim: GroupDelim::Brace,
4777            ..
4778        })
4779    ) && toks.get(brace_pos).is_some_and(|t| !is_template_brace(t));
4780    let p: usize;
4781    let discriminant = if bare_head {
4782        p = brace_pos;
4783        None
4784    } else {
4785        // Discriminant entry reuses the skipped gaps above (`IF` uses
4786        // the same gap rule).
4787        let mut cur = Cursor::expr(&toks[brace_pos..], stmt);
4788        let disc = match parse_expr_checked(&mut cur, ctx) {
4789            Ok(expr) => expr,
4790            Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4791            // Same classified-error rule as the `IF` head above: the
4792            // head is unambiguous, so resolvable-but-unknown callees
4793            // name the culprit instead of the generic hint.
4794            Err(e) if e.kind.is_some() => return Err(e),
4795            Err(_) => return Ok(None),
4796        };
4797        p = brace_pos + cur.pos;
4798        Some(Box::new(disc))
4799    };
4800    let body_ok = matches!(
4801        toks.get(p).map(|t| &t.kind),
4802        Some(TokKind::Group {
4803            delim: GroupDelim::Brace,
4804            ..
4805        })
4806    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4807    if !body_ok {
4808        return Ok(None);
4809    }
4810    let inner = match &toks[p].kind {
4811        TokKind::Group { inner, .. } => inner.clone(),
4812        _ => unreachable!(),
4813    };
4814    let (cases, default_body) = parse_switch_body(&inner, stmt, ctx)?;
4815    let kind = StepKind::Switch {
4816        discriminant,
4817        cases,
4818        default_body,
4819    };
4820    Ok(Some((kind, p + 1 - pos)))
4821}
4822
4823/// Single (non-block) `FOR`: `$var[: TYPE] (, $var[: TYPE])? IN
4824/// expr` plus block. Header shapes miss to generic (a third variable,
4825/// a missing block, a bad name all fail in lowering like the
4826/// grammar); completed headers validate counts and key types loudly.
4827/// Expression failures from inline blocks propagate (blocks lower
4828/// here); other expression failures miss (generic fails them like a
4829/// committed `instruction` would).
4830fn parse_for_at(
4831    toks: &[Tok],
4832    pos: usize,
4833    stmt: usize,
4834    ctx: &ParseCtx,
4835) -> Result<Option<(StepKind, usize)>, TokenError> {
4836    let mut p = pos + 1;
4837    let mut idents = Vec::new();
4838    let mut types = Vec::new();
4839    // First `$var[: TYPE]` (gapless `$var`; gaps free elsewhere).
4840    let Some((var1, _)) = peek_dollar_var(toks, p) else {
4841        return Ok(None);
4842    };
4843    idents.push(var1);
4844    p += 2;
4845    let mut cur = Cursor::expr(&toks[p..], stmt);
4846    cur.skip_gap();
4847    p += cur.pos;
4848    if matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4849        p += 1;
4850        let mut tcur = Cursor::expr(&toks[p..], stmt);
4851        tcur.skip_gap();
4852        let tstart = p + tcur.pos;
4853        let Some(tend) = parse_type_shape(toks, tstart) else {
4854            return Ok(None);
4855        };
4856        // `render_type_region` canonicalizes (shared spelling).
4857        types.push(render_type_region(&toks[tstart..tend], stmt)?);
4858        p = tend;
4859    }
4860    // Optional `, $var2[: TYPE2]`.
4861    {
4862        let mut ccur = Cursor::expr(&toks[p..], stmt);
4863        ccur.skip_gap();
4864        if matches!(
4865            ccur.toks.get(ccur.pos).map(|t| &t.kind),
4866            Some(TokKind::Punct(','))
4867        ) {
4868            ccur.pos += 1;
4869            ccur.skip_gap();
4870            let base = p + ccur.pos;
4871            let Some((var2, _)) = peek_dollar_var(toks, base) else {
4872                return Ok(None);
4873            };
4874            idents.push(var2);
4875            let mut q = base + 2;
4876            let mut qcur = Cursor::expr(&toks[q..], stmt);
4877            qcur.skip_gap();
4878            q += qcur.pos;
4879            if matches!(toks.get(q).map(|t| &t.kind), Some(TokKind::Punct(':'))) {
4880                q += 1;
4881                let mut tcur = Cursor::expr(&toks[q..], stmt);
4882                tcur.skip_gap();
4883                let tstart = q + tcur.pos;
4884                let Some(tend) = parse_type_shape(toks, tstart) else {
4885                    return Ok(None);
4886                };
4887                types.push(render_type_region(&toks[tstart..tend], stmt)?);
4888                q = tend;
4889            }
4890            p = q;
4891        }
4892    }
4893    // `IN expr block`.
4894    {
4895        let mut icur = Cursor::expr(&toks[p..], stmt);
4896        icur.skip_gap();
4897        if !matches!(
4898            icur.toks.get(icur.pos).map(|t| &t.kind),
4899            Some(TokKind::Word(w)) if w == KEYWORD_IN
4900        ) {
4901            return Ok(None);
4902        }
4903        icur.pos += 1;
4904        p += icur.pos;
4905    }
4906    let mut ecur = Cursor::expr(&toks[p..], stmt);
4907    ecur.skip_gap();
4908    let in_expr = match parse_expr_checked(&mut ecur, ctx) {
4909        Ok(expr) => expr,
4910        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
4911        // Classified failures name the callee: `FOR ... IN` is
4912        // committed once the header matched this far.
4913        Err(e) if e.kind.is_some() => return Err(e),
4914        Err(_) => return Ok(None),
4915    };
4916    p += ecur.pos;
4917    let block_ok = matches!(
4918        toks.get(p).map(|t| &t.kind),
4919        Some(TokKind::Group {
4920            delim: GroupDelim::Brace,
4921            ..
4922        })
4923    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
4924    if !block_ok {
4925        return Ok(None);
4926    }
4927    let inner = match &toks[p].kind {
4928        TokKind::Group { inner, .. } => inner.clone(),
4929        _ => unreachable!(),
4930    };
4931    let body = parse_body_steps(&inner, stmt, ctx, false)?;
4932    p += 1;
4933    if idents.len() != types.len() {
4934        return Err(TokenError {
4935            diagnostic: None,
4936            hint: None,
4937            stmt,
4938            msg: format!(
4939                "FOR requires explicit types: FOR $item: TYPE IN <expr> (got {} vars, {} types)",
4940                idents.len(),
4941                types.len()
4942            ),
4943            line: 0,
4944            col: 0,
4945            kind: Some(ParseErrorKind::Validation {
4946                command: KEYWORD_FOR.to_string(),
4947            }),
4948        });
4949    }
4950    let (key_var, key_type, var, var_type) = match idents.len() {
4951        1 => (
4952            None,
4953            None,
4954            idents.into_iter().next().unwrap_or_default(),
4955            types.into_iter().next().unwrap_or_default(),
4956        ),
4957        2 => {
4958            let mut iv = idents.into_iter();
4959            let mut tv = types.into_iter();
4960            (
4961                Some(iv.next().unwrap_or_default()),
4962                Some(tv.next().unwrap_or_default()),
4963                iv.next().unwrap_or_default(),
4964                tv.next().unwrap_or_default(),
4965            )
4966        }
4967        _ => {
4968            return Err(TokenError {
4969                diagnostic: None,
4970                hint: None,
4971                stmt,
4972                msg: format!("{KEYWORD_FOR} requires one or two variables"),
4973                line: 0,
4974                col: 0,
4975                kind: Some(ParseErrorKind::Validation {
4976                    command: KEYWORD_FOR.to_string(),
4977                }),
4978            });
4979        }
4980    };
4981    if let Some(kt) = &key_type
4982        && kt != crate::TypeTag::String.name()
4983        && kt != crate::TypeTag::Int.name()
4984    {
4985        return Err(TokenError {
4986            diagnostic: None,
4987            hint: None,
4988            stmt,
4989            msg: format!(
4990                "{KEYWORD_FOR} key variable must be {INT_TYPE_NAME} or {STRING_TYPE_NAME}, got {kt}"
4991            ),
4992            line: 0,
4993            col: 0,
4994            kind: Some(ParseErrorKind::Validation {
4995                command: KEYWORD_FOR.to_string(),
4996            }),
4997        });
4998    }
4999    let kind = StepKind::For {
5000        key_var,
5001        key_type,
5002        var,
5003        var_type,
5004        in_expr,
5005        body,
5006    };
5007    Ok(Some((kind, p - pos)))
5008}
5009
5010/// Single (non-block) `WHILE`: condition plus block. `None` on
5011/// shape miss (missing block: generic fails it); classified
5012/// expression failures and inline-block failures propagate, other
5013/// expression failures miss (generic fails them like a committed
5014/// `instruction` would).
5015/// No leading gap-skip: `WHILE` takes `sep`, so a joint follower
5016/// never reaches here with a valid shape... (misses fall through
5017/// the same way regardless).
5018fn parse_while_single(
5019    toks: &[Tok],
5020    pos: usize,
5021    stmt: usize,
5022    ctx: &ParseCtx,
5023) -> Result<Option<(StepKind, usize)>, TokenError> {
5024    let mut cur = Cursor::expr(&toks[pos + 1..], stmt);
5025    let cond = match parse_expr_checked(&mut cur, ctx) {
5026        Ok(expr) => expr,
5027        Err(e) if e.msg.starts_with("unsupported in parse_tokens") => return Err(e),
5028        // Same rule as `IF`: the head is unambiguous, so classified
5029        // failures name the culprit instead of the generic hint.
5030        Err(e) if e.kind.is_some() => return Err(e),
5031        Err(_) => return Ok(None),
5032    };
5033    let brace = pos + 1 + cur.pos;
5034    let block_ok = matches!(
5035        toks.get(brace).map(|t| &t.kind),
5036        Some(TokKind::Group {
5037            delim: GroupDelim::Brace,
5038            ..
5039        })
5040    ) && toks.get(brace).is_some_and(|t| !is_template_brace(t));
5041    if !block_ok {
5042        return Ok(None);
5043    }
5044    let inner = match &toks[brace].kind {
5045        TokKind::Group { inner, .. } => inner.clone(),
5046        _ => unreachable!(),
5047    };
5048    let body = parse_body_steps(&inner, stmt, ctx, false)?;
5049    let kind = StepKind::While {
5050        cond: Box::new(cond),
5051        body,
5052    };
5053    Ok(Some((kind, brace + 1 - pos)))
5054}
5055
5056/// Validated `FUNC` header shape: name, parameter list, return type,
5057/// and body block. Single owner for the header grammar, shared by
5058/// `parse_func_at` and `predeclare_forward_funcs` so the hoist set can
5059/// never admit what the real path rejects (or reject what it admits).
5060/// Returns the header plus tokens consumed; `None` on shape miss
5061/// (lowercase names, missing paren/colon/block all miss to generic,
5062/// probed). Content failures (bad params, missing return type, bad
5063/// trailing tokens) carry the bare diagnostic: `parse_func_at`
5064/// adorns it, pre-declaration drops it (silent skip, letting the main
5065/// pass own the error).
5066struct FuncHeader {
5067    name: String,
5068    params: Vec<(String, String, bool)>,
5069    return_type: String,
5070    block: usize,
5071}
5072
5073#[allow(clippy::too_many_lines)]
5074fn parse_func_header(
5075    toks: &[Tok],
5076    pos: usize,
5077    stmt: usize,
5078    keyword: &str,
5079) -> Result<Option<(FuncHeader, usize)>, String> {
5080    // Head word: `FUNC` (callers normalize `ASYNC FUNC` to `pos`
5081    // first, so the header shape stays prefix-free).
5082    if !matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC) {
5083        return Ok(None);
5084    }
5085    // Name: UPPERCASE ident (lowercase misses to generic, probed).
5086    let def_name = match toks.get(pos + 1).map(|t| &t.kind) {
5087        Some(TokKind::Word(w))
5088            if crate::resolve::check_func_ident(&lowering_ctx(stmt), w).is_ok() =>
5089        {
5090            w.clone()
5091        }
5092        _ => return Ok(None),
5093    };
5094    // Paren group at any gap (`gap` zero-width): params live inside
5095    // its inner tokens, parsed with `gap_nl` discipline (newlines ride
5096    // free like call args and generics, via the shared helper).
5097    let mut p = pos + 2;
5098    let paren_inner = match toks.get(p).map(|t| &t.kind) {
5099        Some(TokKind::Group {
5100            delim: GroupDelim::Paren,
5101            inner,
5102            ..
5103        }) => inner.clone(),
5104        _ => return Ok(None),
5105    };
5106    p += 1;
5107    let mut params = Vec::new();
5108    let mut seen_optional = false;
5109    {
5110        let mut pcur = Cursor::expr(&paren_inner, stmt);
5111        pcur.skip_gap_nl();
5112        if !pcur.done() {
5113            loop {
5114                let base = pcur.pos;
5115                let Some((pname, _)) = peek_dollar_var(&paren_inner, base) else {
5116                    return Err(format!(
5117                        "FUNC {def_name} params must be `$name: TYPE` separated by commas"
5118                    ));
5119                };
5120                pcur.pos = base + 2;
5121                pcur.skip_gap_nl();
5122                // Optional params carry `?` before the colon
5123                // (`$flag?: BOOL`); all params are otherwise required.
5124                let optional = pcur.eat_punct('?');
5125                pcur.skip_gap_nl();
5126                if !pcur.eat_punct(':') {
5127                    return Err(format!(
5128                        "FUNC {def_name} param `${pname}` needs `: TYPE` after the name"
5129                    ));
5130                }
5131                pcur.skip_gap_nl();
5132                let tstart = pcur.pos;
5133                let Some(tend) = parse_type_shape(&paren_inner, tstart) else {
5134                    let got = match paren_inner.get(tstart).map(|tok| &tok.kind) {
5135                        Some(TokKind::Word(word)) => format!("; got `{word}`"),
5136                        _ => String::new(),
5137                    };
5138                    return Err(format!(
5139                        "FUNC {def_name} param `${pname}` needs an uppercase type after `:` (e.g. STRING, INT, BOOL){got}"
5140                    ));
5141                };
5142                // Post-match the span holds words/puncts only, so the
5143                // shared renderer cannot fail; stay failed regardless.
5144                let ptype =
5145                    render_type_region(&paren_inner[tstart..tend], stmt).unwrap_or_default();
5146                if optional {
5147                    seen_optional = true;
5148                } else if seen_optional {
5149                    return Err(format!(
5150                        "FUNC {def_name} optional ? params must be trailing: `${pname}` follows an optional param"
5151                    ));
5152                }
5153                params.push((pname, ptype, optional));
5154                pcur.pos = tend;
5155                pcur.skip_gap_nl();
5156                if pcur.eat_punct(',') {
5157                    pcur.skip_gap_nl();
5158                    // Trailing comma misses (a param must follow).
5159                    if pcur.done() {
5160                        return Err(format!(
5161                            "FUNC {def_name} params must not end with a trailing comma"
5162                        ));
5163                    }
5164                    continue;
5165                }
5166                break;
5167            }
5168            // Trailing junk (including newlines) misses to generic.
5169            pcur.skip_gap_nl();
5170            if !pcur.done() {
5171                return Err(format!(
5172                    "FUNC {def_name} params must be `$name: TYPE` separated by commas"
5173                ));
5174            }
5175        }
5176    }
5177    // Mandatory return annotation: FUNC NAME(...): RET { ... }.
5178    // After paren group, require gap-optional colon then type shape.
5179    // Missing colon after matched name+parens is a hard parse error
5180    // (no legacy fallback). Non-block tails (neither colon nor brace)
5181    // miss to generic (probed FUNC FOO() ECHO hi).
5182    let is_colon = matches!(toks.get(p).map(|t| &t.kind), Some(TokKind::Punct(':')));
5183    if !is_colon {
5184        let is_brace = matches!(
5185            toks.get(p).map(|t| &t.kind),
5186            Some(TokKind::Group {
5187                delim: GroupDelim::Brace,
5188                ..
5189            })
5190        ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
5191        if is_brace {
5192            return Err(format!(
5193                "{keyword} {def_name} requires a return type : TYPE (e.g. : VOID, : STRING)"
5194            ));
5195        }
5196        return Ok(None);
5197    }
5198    let Some(ret_end) = parse_type_shape(toks, p + 1) else {
5199        return Err(format!(
5200            "{keyword} {def_name} requires a return type : TYPE after ':'"
5201        ));
5202    };
5203    let return_type = render_type_region(&toks[p + 1..ret_end], stmt).map_err(|_| {
5204        format!("{keyword} {def_name} requires a return type : {KEYWORD_TYPE} after ':'")
5205    })?;
5206    let return_type = crate::canonicalize_spelling(&return_type);
5207    p = ret_end;
5208    // Block at any gap (never a template); missing blocks miss to
5209    // generic (probed FUNC FOO() ECHO hi).
5210    let block_ok = matches!(
5211        toks.get(p).map(|t| &t.kind),
5212        Some(TokKind::Group {
5213            delim: GroupDelim::Brace,
5214            ..
5215        })
5216    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
5217    if !block_ok {
5218        return Ok(None);
5219    }
5220    Ok(Some((
5221        FuncHeader {
5222            name: def_name,
5223            params,
5224            return_type,
5225            block: p,
5226        },
5227        p + 1 - pos,
5228    )))
5229}
5230
5231/// Single (non-block) `FUNC`: name, parenthesized params, block. The
5232/// shape parses purely first (misses fall to generic, declaring
5233/// nothing — the grammar only lowers matched pairs); then the name
5234/// declares in the enclosing scope before the body lowers (so
5235/// recursion resolves), and the body pushes a fresh scope.
5236/// Duplicates, reserved shadows, and parameter dupes fail loudly.
5237fn parse_func_at(
5238    toks: &[Tok],
5239    pos: usize,
5240    stmt: usize,
5241    ctx: &ParseCtx,
5242    is_async: bool,
5243) -> Result<Option<(StepKind, usize)>, TokenError> {
5244    let keyword = if is_async { "ASYNC FUNC" } else { KEYWORD_FUNC };
5245    let fail = |msg: String| TokenError {
5246        diagnostic: None,
5247        hint: None,
5248        stmt,
5249        msg,
5250        line: 0,
5251        col: 0,
5252        kind: Some(ParseErrorKind::Validation {
5253            command: KEYWORD_FUNC.to_string(),
5254        }),
5255    };
5256    // Phase 1 (pure shape) through the single header owner:
5257    // adorn content errors with the `FUNC` / `ASYNC FUNC` keyword,
5258    // miss to generic on shape miss exactly as before.
5259    let Some((header, used)) = parse_func_header(toks, pos, stmt, keyword).map_err(fail)? else {
5260        return Ok(None);
5261    };
5262    let FuncHeader {
5263        name: def_name,
5264        params,
5265        return_type,
5266        block: p,
5267    } = header;
5268    // Phase 2 (effects): reserved shadows and same-scope duplicates
5269    // fail at the definition line, verbatim.
5270    if ctx.reserved.contains(&def_name) || ctx.modules.reserved_base_names().contains(&def_name) {
5271        return Err(fail(format!(
5272            "FUNC {def_name} cannot shadow reserved function `{def_name}`"
5273        )));
5274    }
5275    if !ctx.declare_func(&def_name) {
5276        return Err(fail(format!(
5277            "duplicate function `{def_name}` in same scope"
5278        )));
5279    }
5280    let mut seen = HashSet::new();
5281    for (pname, _, _) in &params {
5282        if !seen.insert(pname.clone()) {
5283            return Err(fail(format!(
5284                "FUNC {def_name} declares duplicate parameter ${pname}"
5285            )));
5286        }
5287    }
5288    let inner = match &toks[p].kind {
5289        TokKind::Group { inner, .. } => inner.clone(),
5290        _ => unreachable!(),
5291    };
5292    let body = parse_body_steps(&inner, stmt, ctx, false)?;
5293    let kind = StepKind::FuncDef {
5294        name: def_name,
5295        params,
5296        return_type,
5297        is_async,
5298        body,
5299        docs: None,
5300    };
5301    Ok(Some((kind, used)))
5302}
5303
5304/// `REMOTE` header bindings `[$var, env:KEY]` over a bracket
5305/// group's inner tokens: comma-separated, newlines and comments free
5306/// like `gap_nl`. `$`+name and `env`+`:`+key all ride gapless (the
5307/// enclosing rule is compound-atomic). Empty lists parse (probed);
5308/// anything else misses the shape (`None`: generic fails it like
5309/// the grammar's dropped optional).
5310#[allow(clippy::type_complexity)]
5311fn parse_remote_bindings(
5312    inner: &[Tok],
5313    stmt: usize,
5314    _ctx: &ParseCtx,
5315) -> Result<Option<(Vec<String>, Vec<String>)>, TokenError> {
5316    let _ = stmt;
5317    let mut parts: Vec<&[Tok]> = Vec::new();
5318    let mut start = 0;
5319    for (i, tok) in inner.iter().enumerate() {
5320        if matches!(&tok.kind, TokKind::Punct(',')) {
5321            parts.push(&inner[start..i]);
5322            start = i + 1;
5323        }
5324    }
5325    parts.push(&inner[start..]);
5326    // An empty list (`[]`, whitespace/comment-only) holds no bindings.
5327    if parts.len() == 1
5328        && parts[0]
5329            .iter()
5330            .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
5331    {
5332        return Ok(Some((Vec::new(), Vec::new())));
5333    }
5334    let mut vars = Vec::new();
5335    let mut env = Vec::new();
5336    for part in parts {
5337        // Edges admit gaps, newlines, and comments, like `gap_nl`.
5338        let mut part = part;
5339        while matches!(
5340            part.first().map(|t| &t.kind),
5341            Some(TokKind::Newline | TokKind::Comment(_))
5342        ) {
5343            part = &part[1..];
5344        }
5345        while matches!(
5346            part.last().map(|t| &t.kind),
5347            Some(TokKind::Newline | TokKind::Comment(_))
5348        ) {
5349            part = &part[..part.len() - 1];
5350        }
5351        // `$var` entries only: bare words are literal text, never
5352        // bindings.
5353        if matches!(
5354            part.first().map(|t| &t.kind),
5355            Some(TokKind::Punct(VAR_SIGIL_CHAR))
5356        ) && part.len() == 2
5357        {
5358            if part[1].joint
5359                && let TokKind::Word(w) = &part[1].kind
5360                && is_ident_word(w)
5361            {
5362                vars.push(w.clone());
5363                continue;
5364            }
5365            return Ok(None);
5366        }
5367        // `env:KEY`: gapless triple with an uppercase key.
5368        if part.len() == 3
5369            && matches!(&part[0].kind, TokKind::Word(w) if w == "env")
5370            && matches!(&part[1].kind, TokKind::Punct(':'))
5371            && part[1].joint
5372            && part[2].joint
5373        {
5374            if let TokKind::Word(k) = &part[2].kind
5375                && is_env_key(k)
5376            {
5377                env.push(k.clone());
5378                continue;
5379            }
5380            return Ok(None);
5381        }
5382        return Ok(None);
5383    }
5384    Ok(Some((vars, env)))
5385}
5386
5387/// `IMPORT` statement at `pos` (#115): module form (`IMPORT MOD`,
5388/// `IMPORT [A, B]`), file form (`IMPORT "p" AS A`,
5389/// `IMPORT ["p" AS A]`), mixed/multi forms
5390/// (`IMPORT [STD, "p" AS A, "q" AS B]`, multi-line included), and
5391/// selective harvests (`IMPORT [[F, G FROM "p" (AS A)?]]`).
5392/// Returns module names plus `ImportFile`/`ImportFuncs` steps in source
5393/// order, plus tokens consumed (relative to `pos`), or `None` on shape
5394/// miss (generic lowering fails it like the grammar). Validation is
5395/// hard: unknown modules, bad names, collisions, templates, and remote
5396/// URLs fail here, and validated entries register immediately
5397/// (modules, aliases, and bare harvest names share the innermost
5398/// frames).
5399type ImportEntries = (Vec<String>, Vec<StepKind>);
5400
5401fn parse_import_statement(
5402    toks: &[Tok],
5403    pos: usize,
5404    stmt: usize,
5405    ctx: &ParseCtx,
5406    guarded: bool,
5407) -> Result<Option<(ImportEntries, usize)>, TokenError> {
5408    let fail = |msg: String| TokenError {
5409        diagnostic: None,
5410        hint: None,
5411        stmt,
5412        msg,
5413        line: 0,
5414        col: 0,
5415        kind: Some(ParseErrorKind::Validation {
5416            command: KEYWORD_IMPORT.to_string(),
5417        }),
5418    };
5419    let next = match toks.get(pos + 1) {
5420        // `sep` after `IMPORT`: joint followers miss.
5421        Some(t) if !t.joint => t,
5422        _ => return Ok(None),
5423    };
5424    // Parse entries first, validate in source order after.
5425    enum RawEntry {
5426        Module(String),
5427        File {
5428            path: String,
5429            alias: String,
5430        },
5431        From {
5432            func_names: Vec<String>,
5433            type_names: Vec<String>,
5434            path: String,
5435            alias: Option<String>,
5436        },
5437    }
5438    let mut raw: Vec<RawEntry> = Vec::new();
5439    let used;
5440    if matches!(
5441        &next.kind,
5442        TokKind::Group {
5443            delim: GroupDelim::Brace,
5444            ..
5445        }
5446    ) {
5447        return Ok(None);
5448    }
5449    if let TokKind::Group {
5450        delim: GroupDelim::Bracket,
5451        inner,
5452        ..
5453    } = &next.kind
5454    {
5455        // Comma-separated entries, `ws` gaps (newlines ok inside and
5456        // around entries, comments MISS — `ws` admits neither).
5457        // Single-file multi-name harvests skip the split: in
5458        // `[TYPE A, TYPE B FROM "f"]` the first comma-part (`[TYPE A]`)
5459        // carries no FROM and is invalid alone, so the whole bracket
5460        // is one harvest (see `whole_file_harvest`).
5461        // Bare-multi hint: `[FOO, BAR FROM "f"]` reads FOO as a
5462        // module for back-compat (bare words stay modules in single
5463        // brackets). If that word is not a known module but a harvest
5464        // follows, fail fast naming the two valid spellings instead
5465        // of the misleading unknown-module error.
5466        if let Some(comment) = find_bracket_comment(inner) {
5467            let mut err = lower_err(
5468                stmt,
5469                ParseError::from_diagnostic(
5470                    ParseErrorKind::InvalidSyntax {
5471                        command: KEYWORD_IMPORT.to_string(),
5472                    },
5473                    dsl_diag::spelling_bracket_list_comment(KEYWORD_IMPORT),
5474                    &lowering_ctx(stmt),
5475                ),
5476            );
5477            err.line = comment.line;
5478            err.col = comment.col;
5479            return Err(err);
5480        }
5481        let whole = whole_file_harvest(inner);
5482        if whole.is_none()
5483            && let Some(word) = single_bare_first_part(inner)
5484            && !ctx.modules.modules.contains_key(word)
5485            && has_top_level_from_after_comma(inner)
5486        {
5487            return Err(fail(format!(
5488                "unknown module `{word}`; to harvest multiple names qualify each kind (`IMPORT [FUNC FOO, FUNC BAR FROM \"f\"]`)"
5489            )));
5490        }
5491        let mut parts: Vec<&[Tok]> = Vec::new();
5492        if whole.is_some() {
5493            parts.push(inner);
5494        } else {
5495            let mut start = 0;
5496            for (i, tok) in inner.iter().enumerate() {
5497                if matches!(&tok.kind, TokKind::Punct(',')) {
5498                    parts.push(&inner[start..i]);
5499                    start = i + 1;
5500                }
5501            }
5502            parts.push(&inner[start..]);
5503        }
5504        for part in parts {
5505            let dense: Vec<&Tok> = part
5506                .iter()
5507                .filter(|t| !matches!(&t.kind, TokKind::Newline))
5508                .collect();
5509            // `[[F, G FROM "path" (AS ALIAS)?]]`: selective function
5510            // harvest. Anything else bracketed here misses.
5511            if let [bracket] = dense.as_slice()
5512                && let TokKind::Group {
5513                    delim: GroupDelim::Bracket,
5514                    inner,
5515                    ..
5516                } = &bracket.kind
5517            {
5518                let Some(HarvestImport {
5519                    func_names,
5520                    type_names,
5521                    path,
5522                    alias,
5523                }) = parse_from_entry(inner)
5524                else {
5525                    return Ok(None);
5526                };
5527                raw.push(RawEntry::From {
5528                    func_names,
5529                    type_names,
5530                    path,
5531                    alias,
5532                });
5533                continue;
5534            }
5535            // `[F FROM "path" (AS ALIAS)?]`: single harvest without
5536            // inner brackets. The `FROM` keyword is the discriminant
5537            // (module and file parts never contain a top-level one);
5538            // multi-name harvests keep `[[F, G FROM ...]]` so the comma
5539            // stays grouped inside its own scope.
5540            if dense.len() >= 3 {
5541                let owned: Vec<Tok> = dense.iter().map(|t| (*t).clone()).collect();
5542                if let Some(HarvestImport {
5543                    func_names,
5544                    type_names,
5545                    path,
5546                    alias,
5547                }) = parse_from_entry(&owned)
5548                {
5549                    raw.push(RawEntry::From {
5550                        func_names,
5551                        type_names,
5552                        path,
5553                        alias,
5554                    });
5555                    continue;
5556                }
5557            }
5558            match dense.as_slice() {
5559                [tok] => match &tok.kind {
5560                    TokKind::Word(w) if is_upper_ident(w) => {
5561                        raw.push(RawEntry::Module(w.clone()));
5562                    }
5563                    _ => return Ok(None),
5564                },
5565                [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5566                    let (
5567                        TokKind::Str { text, .. },
5568                        TokKind::Word(as_word),
5569                        TokKind::Word(alias_word),
5570                    ) = (&path_tok.kind, &as_tok.kind, &alias_tok.kind)
5571                    else {
5572                        return Ok(None);
5573                    };
5574                    if as_word != KEYWORD_AS {
5575                        return Ok(None);
5576                    }
5577                    raw.push(RawEntry::File {
5578                        path: text.clone(),
5579                        alias: alias_word.clone(),
5580                    });
5581                }
5582                _ => return Ok(None),
5583            }
5584        }
5585        if raw.is_empty() {
5586            return Ok(None);
5587        }
5588        used = 2;
5589    } else if let TokKind::Word(w) = &next.kind {
5590        // Bare `IMPORT MOD` (single module, probed).
5591        if !is_upper_ident(w) {
5592            return Ok(None);
5593        }
5594        raw.push(RawEntry::Module(w.clone()));
5595        used = 2;
5596    } else if let TokKind::Str { text, .. } = &next.kind {
5597        // Bare `IMPORT "path" AS ALIAS`.
5598        let (Some(as_tok), Some(alias_tok)) = (toks.get(pos + 2), toks.get(pos + 3)) else {
5599            return Ok(None);
5600        };
5601        if as_tok.joint || alias_tok.joint {
5602            return Ok(None);
5603        }
5604        let (TokKind::Word(as_word), TokKind::Word(alias_word)) = (&as_tok.kind, &alias_tok.kind)
5605        else {
5606            return Ok(None);
5607        };
5608        if as_word != KEYWORD_AS {
5609            return Ok(None);
5610        }
5611        raw.push(RawEntry::File {
5612            path: text.clone(),
5613            alias: alias_word.clone(),
5614        });
5615        used = 4;
5616    } else {
5617        return Ok(None);
5618    }
5619    // Validate in source order: unknown modules fail with the exact
5620    // backend message (sorted known list); file and harvest entries
5621    // validate hard (bad names, collisions, templates, remote URLs).
5622    let mut modules = Vec::new();
5623    let mut steps = Vec::new();
5624    for entry in raw {
5625        match entry {
5626            RawEntry::Module(module) => {
5627                if !ctx.modules.modules.contains_key(&module) {
5628                    let mut known: Vec<String> = ctx.modules.modules.keys().cloned().collect();
5629                    known.sort();
5630                    return Err(fail(format!(
5631                        "unknown module `{module}`; known modules: {}",
5632                        known.join(", ")
5633                    )));
5634                }
5635                ctx.import_into_frame(std::slice::from_ref(&module), false);
5636                modules.push(module);
5637            }
5638            RawEntry::File { path, alias } => {
5639                let (path, alias) =
5640                    validate_file_import(&path, &alias, ctx, guarded).map_err(fail)?;
5641                steps.push(StepKind::ImportFile { path, alias });
5642            }
5643            RawEntry::From {
5644                func_names,
5645                type_names,
5646                path,
5647                alias,
5648            } => {
5649                let HarvestImport {
5650                    func_names,
5651                    type_names,
5652                    path,
5653                    alias,
5654                } = validate_from_import(
5655                    &func_names,
5656                    &type_names,
5657                    &path,
5658                    alias.as_deref(),
5659                    ctx,
5660                    guarded,
5661                )
5662                .map_err(fail)?;
5663                steps.push(StepKind::ImportFuncs {
5664                    path,
5665                    alias,
5666                    func_names,
5667                    type_names,
5668                });
5669            }
5670        }
5671    }
5672    Ok(Some(((modules, steps), used)))
5673}
5674
5675/// Single file import for value positions (#115): exactly one
5676/// `"path" AS ALIAS` entry and no modules. Anything else shaped like an
5677/// import is a hard error naming the restriction; shape misses return
5678/// `None` for the generic path.
5679fn parse_single_file_import(
5680    toks: &[Tok],
5681    pos: usize,
5682    stmt: usize,
5683    ctx: &ParseCtx,
5684) -> Result<Option<(String, String, usize)>, TokenError> {
5685    let Some(((modules, mut kinds), used)) = parse_import_statement(toks, pos, stmt, ctx, false)?
5686    else {
5687        return Ok(None);
5688    };
5689    if !modules.is_empty() || !matches!(kinds.as_slice(), [StepKind::ImportFile { .. }]) {
5690        return Err(TokenError {
5691            diagnostic: None,
5692            hint: None,
5693            stmt,
5694            msg: if !modules.is_empty()
5695                || kinds
5696                    .iter()
5697                    .any(|k| matches!(k, StepKind::ImportFuncs { .. }))
5698            {
5699                format!(
5700                    "{KEYWORD_IMPORT} here takes a single file import ({KEYWORD_IMPORT} [\"<path>\" AS <ALIAS>]); modules and function harvests stay at statement level"
5701                )
5702            } else {
5703                "IMPORT here takes a single file import (IMPORT [\"<path>\" AS <ALIAS>])"
5704                    .to_string()
5705            },
5706            line: 0,
5707            col: 0,
5708            kind: Some(ParseErrorKind::Validation {
5709                command: KEYWORD_IMPORT.to_string(),
5710            }),
5711        });
5712    }
5713    let Some(StepKind::ImportFile { path, alias }) = kinds.pop() else {
5714        unreachable!("length and variant checked above")
5715    };
5716    Ok(Some((path, alias, used)))
5717}
5718
5719/// One `EXPORT` name: an uppercase word with an optional joint
5720/// `::UPPER` tail. Returns the name and tokens consumed, `Ok(None)`
5721/// on shape miss, or `Err` when a recognizable identifier carries
5722/// the wrong sigil (`CONST` requires `$`, `FUNC`/`TYPE` forbid it).
5723fn parse_export_name(
5724    toks: &[Tok],
5725    pos: usize,
5726    require_sigil: bool,
5727    stmt: usize,
5728) -> Result<Option<(String, usize)>, TokenError> {
5729    // Sigil rule: `EXPORT CONST $N` and `EXPORT CONST $LIB::V` require
5730    // the `$`, exactly like every other `CONST` read; `EXPORT FOO`,
5731    // `EXPORT TYPE T`, and qualified func forwards never take one.
5732    // Stored without the sigil; downstream matching (top-level tables,
5733    // harvest maps) is unchanged. `$` must ride gapless onto the
5734    // name, like every `$` read.
5735    let fail = |msg: String| TokenError {
5736        diagnostic: None,
5737        hint: None,
5738        stmt,
5739        line: 0,
5740        col: 0,
5741        kind: None,
5742        msg,
5743    };
5744    let offset = match toks.get(pos).map(|t| &t.kind) {
5745        Some(TokKind::Punct(VAR_SIGIL_CHAR)) if toks.get(pos + 1).is_some_and(|t| t.joint) => 1,
5746        Some(TokKind::Punct(VAR_SIGIL_CHAR)) => return Ok(None),
5747        _ => 0,
5748    };
5749    if require_sigil != (offset == 1) {
5750        let head = toks.get(pos + offset).map(|t| &t.kind);
5751        let recognizable = matches!(head, Some(TokKind::Word(w)) if is_upper_ident(w));
5752        if !recognizable {
5753            return Ok(None);
5754        }
5755        if require_sigil {
5756            return Err(fail(format!(
5757                "{KEYWORD_EXPORT} {KEYWORD_CONST} requires `$`: write {KEYWORD_EXPORT} {KEYWORD_CONST} $NAME (never bare)"
5758            )));
5759        } else {
5760            return Err(fail(format!(
5761                "{KEYWORD_EXPORT} {KEYWORD_FUNC} and {KEYWORD_EXPORT} {KEYWORD_TYPE} names never take `$`: write {KEYWORD_EXPORT} FOO"
5762            )));
5763        }
5764    }
5765    let head = match toks.get(pos + offset).map(|t| &t.kind) {
5766        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
5767        _ => return Ok(None),
5768    };
5769    let mut name = head;
5770    let mut used = 1 + offset;
5771    // Greedy-prefix `::tail` (atomic, like the grammar): a valid
5772    // tail joins, an invalid one stays trailing (failing downstream
5773    // exactly like the grammar's committed prefix).
5774    if matches!(
5775        toks.get(pos + offset + 1).map(|t| &t.kind),
5776        Some(TokKind::Punct(':'))
5777    ) && toks.get(pos + offset + 1).is_some_and(|t| t.joint)
5778        && matches!(
5779            toks.get(pos + offset + 2).map(|t| &t.kind),
5780            Some(TokKind::Punct(':'))
5781        )
5782        && toks.get(pos + offset + 2).is_some_and(|t| t.joint)
5783        && let Some(TokKind::Word(tail)) = toks.get(pos + offset + 3).map(|t| &t.kind)
5784        && toks[pos + offset + 3].joint
5785        && is_upper_ident(tail)
5786    {
5787        name.push_str(MODULE_SEPARATOR);
5788        name.push_str(tail);
5789        used = 4 + offset;
5790    }
5791    Ok(Some((name, used)))
5792}
5793
5794/// One selective harvest (`[[F, G FROM "path" (AS ALIAS)?]]`): the
5795/// wanted function and type names plus the path and optional alias.
5796/// Bare names are functions; `TYPE`/`FUNC` prefixes select the kind
5797/// explicitly (`[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`).
5798struct HarvestImport {
5799    func_names: Vec<String>,
5800    type_names: Vec<String>,
5801    path: String,
5802    alias: Option<String>,
5803}
5804
5805/// One `[[F, G FROM "path" (AS ALIAS)?]]` entry: selective function
5806/// harvest with optional `TYPE`/`FUNC` qualifiers per name:
5807/// `[[TYPE PERSON, FUNC FOO, BAR FROM "path"]]`
5808/// (bare stays func for back-compat).
5809/// Returns the harvest, or `None` on shape miss (generic lowering fails
5810/// it). Name case is validated hard by the caller, like file aliases.
5811fn parse_from_entry(inner: &[Tok]) -> Option<HarvestImport> {
5812    let dense: Vec<&Tok> = inner
5813        .iter()
5814        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5815        .collect();
5816    let from = dense
5817        .iter()
5818        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5819    if from == 0 {
5820        return None;
5821    }
5822    // Names: comma-separated entries, each `NAME` (func) or
5823    // `TYPE NAME` / `FUNC NAME` (explicit kind for clarity).
5824    let mut func_names = Vec::new();
5825    let mut type_names = Vec::new();
5826    let mut start = 0;
5827    let head = &dense[..from];
5828    // Local helper: classify one comma-separated part.
5829    fn classify_part(part: &[&Tok]) -> Option<(bool, String)> {
5830        match part {
5831            [tok] => {
5832                let TokKind::Word(w) = &tok.kind else {
5833                    return None;
5834                };
5835                Some((false, w.clone()))
5836            }
5837            // `TYPE NAME` / `FUNC NAME`: the name must be `sep` (gapped
5838            // from the kind); the kind may be joint to a preceding `[`
5839            // or `,` (no space required there), so only the name's joint
5840            // flag matters.
5841            [kind_tok, name_tok] if !name_tok.joint => {
5842                let (TokKind::Word(kind), TokKind::Word(name)) = (&kind_tok.kind, &name_tok.kind)
5843                else {
5844                    return None;
5845                };
5846                if kind == KEYWORD_TYPE {
5847                    Some((true, name.clone()))
5848                } else if kind == KEYWORD_FUNC {
5849                    Some((false, name.clone()))
5850                } else {
5851                    None
5852                }
5853            }
5854            _ => None,
5855        }
5856    }
5857    for (i, tok) in head.iter().enumerate() {
5858        if matches!(&tok.kind, TokKind::Punct(',')) {
5859            let part = &head[start..i];
5860            let (is_type, name) = classify_part(part)?;
5861            if is_type {
5862                type_names.push(name);
5863            } else {
5864                func_names.push(name);
5865            }
5866            start = i + 1;
5867        }
5868    }
5869    let part = &head[start..];
5870    let (is_type, name) = classify_part(part)?;
5871    if is_type {
5872        type_names.push(name);
5873    } else {
5874        func_names.push(name);
5875    }
5876    // Tail: `"path"` or bare `MODULE` with an optional gapped `AS ALIAS`.
5877    // Quoted is a file path (module fallback only when no file matches);
5878    // bare is a host module (no file probe ambiguity).
5879    let tail = &dense[from + 1..];
5880    let path_text = |tok: &Tok| match &tok.kind {
5881        TokKind::Str { text, .. } => Some(text.clone()),
5882        TokKind::Word(w) if is_upper_ident(w) => Some(w.clone()),
5883        _ => None,
5884    };
5885    match tail {
5886        [path_tok] => {
5887            let text = path_text(path_tok)?;
5888            Some(HarvestImport {
5889                func_names,
5890                type_names,
5891                path: text,
5892                alias: None,
5893            })
5894        }
5895        [path_tok, as_tok, alias_tok] if !as_tok.joint && !alias_tok.joint => {
5896            let text = path_text(path_tok)?;
5897            let (TokKind::Word(as_word), TokKind::Word(alias_word)) =
5898                (&as_tok.kind, &alias_tok.kind)
5899            else {
5900                return None;
5901            };
5902            if as_word != KEYWORD_AS {
5903                return None;
5904            }
5905            Some(HarvestImport {
5906                func_names,
5907                type_names,
5908                path: text,
5909                alias: Some(alias_word.clone()),
5910            })
5911        }
5912        _ => None,
5913    }
5914}
5915
5916/// First comma-part of a bracket when it is exactly one bare
5917/// uppercase word: the back-compat module reading. Anything else
5918/// (prefixed names, groups, multiple words) is not a bare module.
5919fn single_bare_first_part(inner: &[Tok]) -> Option<&str> {
5920    let end = inner
5921        .iter()
5922        .position(|t| matches!(&t.kind, TokKind::Punct(',')))
5923        .unwrap_or(inner.len());
5924    let mut words = inner[..end]
5925        .iter()
5926        .filter(|t| !matches!(&t.kind, TokKind::Newline));
5927    match (words.next(), words.next()) {
5928        (Some(tok), None) => match &tok.kind {
5929            TokKind::Word(w) if is_upper_ident(w) => Some(w.as_str()),
5930            _ => None,
5931        },
5932        _ => None,
5933    }
5934}
5935
5936/// Whether a top-level `FROM` follows the first top-level comma:
5937/// distinguishes a module-plus-harvest entry (`[STD, T FROM "f"]`)
5938/// from a bare word the author meant as a harvest name.
5939fn has_top_level_from_after_comma(inner: &[Tok]) -> bool {
5940    let mut seen_comma = false;
5941    for tok in inner {
5942        match &tok.kind {
5943            TokKind::Punct(',') => seen_comma = true,
5944            TokKind::Word(w) if seen_comma && w == KEYWORD_FROM => return true,
5945            _ => {}
5946        }
5947    }
5948    false
5949}
5950
5951/// Whole-bracket single-file harvest (`[TYPE A, TYPE B FROM "f"]`):
5952/// the comma-split would orphan `[TYPE A]` (no FROM, invalid alone),
5953/// so the entire bracket parses as one harvest. Only explicitly
5954/// prefixed names qualify: a bare word keeps its legacy module
5955/// reading, so `[STD, TYPE T FROM "f"]` still splits into a module
5956/// plus a harvest instead of harvesting STD as a function.
5957fn whole_file_harvest(inner: &[Tok]) -> Option<HarvestImport> {
5958    let owned: Vec<Tok> = inner.to_vec();
5959    let harvest = parse_from_entry(&owned)?;
5960    let dense: Vec<&Tok> = inner
5961        .iter()
5962        .filter(|t| !matches!(&t.kind, TokKind::Newline))
5963        .collect();
5964    let from = dense
5965        .iter()
5966        .position(|t| matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_FROM))?;
5967    let mut start = 0;
5968    for (i, tok) in dense[..from].iter().enumerate() {
5969        if matches!(&tok.kind, TokKind::Punct(',')) {
5970            if !is_prefixed_name(&dense[start..i]) {
5971                return None;
5972            }
5973            start = i + 1;
5974        }
5975    }
5976    if !is_prefixed_name(&dense[start..from]) {
5977        return None;
5978    }
5979    Some(harvest)
5980}
5981
5982/// One explicitly prefixed name (`TYPE NAME` / `FUNC NAME`): the name
5983/// stays gapped from its kind; the kind may joint to `[` or `,`.
5984fn is_prefixed_name(part: &[&Tok]) -> bool {
5985    match part {
5986        [kind_tok, name_tok] if !name_tok.joint => {
5987            matches!(
5988                (&kind_tok.kind, &name_tok.kind),
5989                (
5990                    TokKind::Word(kind),
5991                    TokKind::Word(_)
5992                ) if kind == KEYWORD_TYPE || kind == KEYWORD_FUNC
5993            )
5994        }
5995        _ => false,
5996    }
5997}
5998
5999/// Validate an `IMPORT` alias: hard errors (never shape misses) plus
6000/// registration into the innermost import frame. Same-frame duplicates
6001/// reject, unless the new import and every visible same-alias entry
6002/// are guard-gated: an unguarded duplicate always collides at runtime
6003/// (probable typo, fail fast), while guarded duplicates may be
6004/// platform branches whose disjointness the static pass decides.
6005fn validate_import_alias(alias: &str, ctx: &ParseCtx, guarded: bool) -> Result<String, String> {
6006    if !is_upper_ident(alias) {
6007        return Err(format!(
6008            "IMPORT alias must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{alias}`"
6009        ));
6010    }
6011    if ctx.modules.modules.contains_key(alias) {
6012        return Err(format!(
6013            "IMPORT alias `{alias}` collides with module `{alias}`"
6014        ));
6015    }
6016    let flags = ctx.import_guard_flags(alias);
6017    if !flags.is_empty() && (!guarded || flags.iter().any(|g| !g)) {
6018        return Err(format!("duplicate {KEYWORD_IMPORT} alias `{alias}`"));
6019    }
6020    ctx.import_into_frame(std::slice::from_ref(&alias.to_string()), guarded);
6021    Ok(alias.to_string())
6022}
6023
6024/// Validate an `IMPORT` path: hard errors, never shape misses.
6025fn validate_import_path(path: &str) -> Result<String, String> {
6026    if path.is_empty() {
6027        return Err(format!("{KEYWORD_IMPORT} path must not be empty"));
6028    }
6029    if path.contains("{{") {
6030        return Err(format!(
6031            "{KEYWORD_IMPORT} path must be a literal string (no {{{{ }}}} templates)"
6032        ));
6033    }
6034    if path.contains("://") {
6035        return Err(
6036            "remote imports are deferred to #270 (net: Run scripts from a remote URL)".to_string(),
6037        );
6038    }
6039    Ok(path.to_string())
6040}
6041
6042/// Validate a file-import path/alias pair: hard errors (never shape
6043/// misses) plus alias registration into the innermost import frame.
6044/// `guarded` marks a guard-gated statement, relaxing the same-frame
6045/// duplicate gate for platform branches (see `validate_import_alias`).
6046fn validate_file_import(
6047    path: &str,
6048    alias: &str,
6049    ctx: &ParseCtx,
6050    guarded: bool,
6051) -> Result<(String, String), String> {
6052    let alias = validate_import_alias(alias, ctx, guarded)?;
6053    let path = validate_import_path(path)?;
6054    Ok((path, alias))
6055}
6056
6057/// Validate a `[[F, G FROM "path" (AS ALIAS)?]]` entry: hard errors
6058/// (never shape misses). Bare func names declare into the innermost
6059/// `FUNC` frame so calls resolve statically; the runtime defines them
6060/// (and fails unknown names there). Type names need no func-frame
6061/// declaration (types resolve through the global type directory);
6062/// the runtime validates them against the file's `EXPORT TYPE` list.
6063/// An alias registers like a file import.
6064fn validate_from_import(
6065    func_names: &[String],
6066    type_names: &[String],
6067    path: &str,
6068    alias: Option<&str>,
6069    ctx: &ParseCtx,
6070    guarded: bool,
6071) -> Result<HarvestImport, String> {
6072    let path = validate_import_path(path)?;
6073    let mut out_func_names = Vec::with_capacity(func_names.len());
6074    for name in func_names {
6075        if !is_upper_ident(name) {
6076            return Err(format!(
6077                "IMPORT function names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
6078            ));
6079        }
6080        if ctx.reserved.contains(name) {
6081            return Err(format!("cannot shadow reserved function `{name}`"));
6082        }
6083        out_func_names.push(name.clone());
6084    }
6085    let mut out_type_names = Vec::with_capacity(type_names.len());
6086    for name in type_names {
6087        if !is_upper_ident(name) {
6088            return Err(format!(
6089                "IMPORT type names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
6090            ));
6091        }
6092        out_type_names.push(name.clone());
6093    }
6094    if out_func_names.is_empty() && out_type_names.is_empty() {
6095        return Err(format!(
6096            "{KEYWORD_IMPORT} harvest needs at least one function or type name"
6097        ));
6098    }
6099    if let Some(alias) = alias {
6100        let alias = validate_import_alias(alias, ctx, guarded)?;
6101        Ok(HarvestImport {
6102            func_names: out_func_names,
6103            type_names: out_type_names,
6104            path,
6105            alias: Some(alias),
6106        })
6107    } else {
6108        for name in &out_func_names {
6109            if !ctx.declare_func(name) {
6110                return Err(format!("duplicate function `{name}` in same scope"));
6111            }
6112        }
6113        // Type harvests without alias land bare in the global type
6114        // directory: duplicates across files fail at import time
6115        // (different targets), not at parse time (targets need IO).
6116        Ok(HarvestImport {
6117            func_names: out_func_names,
6118            type_names: out_type_names,
6119            path,
6120            alias: None,
6121        })
6122    }
6123}
6124
6125/// One `EXPORT ...` name list: function, type, and const names in
6126/// source order. Bare names are functions; explicit `TYPE`/`FUNC`/
6127/// `CONST` prefixes select the kind.
6128struct ExportNames {
6129    func_names: Vec<String>,
6130    type_names: Vec<String>,
6131    const_names: Vec<String>,
6132}
6133
6134/// `EXPORT ...` names at `pos`: bracket list (strict, `ws` gaps:
6135/// newlines ok, comments miss) or a bare greedy-prefix name.
6136/// Supports explicit `TYPE`/`FUNC`/`CONST` qualifiers for clarity:
6137/// `EXPORT TYPE FOO`, `EXPORT FUNC FOO`, `EXPORT CONST $FOO`,
6138/// plus mixed `EXPORT [TYPE A, FUNC B, CONST $C, D]` (bare stays func).
6139/// Returns the name lists plus tokens consumed, `Ok(None)` on shape
6140/// miss (generic fails it in lowering like the grammar), or `Err`
6141/// when a recognizable name carries the wrong sigil. Recording and
6142/// duplicate checks live with the caller (they need the guard and
6143/// level context).
6144fn parse_export_at(
6145    toks: &[Tok],
6146    pos: usize,
6147    stmt: usize,
6148) -> Result<Option<(ExportNames, usize)>, TokenError> {
6149    let next = match toks.get(pos + 1) {
6150        // `sep` after `EXPORT`: joint followers miss.
6151        Some(t) if !t.joint => t,
6152        _ => return Ok(None),
6153    };
6154    // Explicit `EXPORT TYPE ...`, `EXPORT FUNC ...`, or
6155    // `EXPORT CONST ...` prefix.
6156    if let TokKind::Word(w) = &next.kind
6157        && (w == KEYWORD_TYPE || w == KEYWORD_FUNC || w == KEYWORD_CONST)
6158    {
6159        let kind = w.as_str();
6160        let after = match toks.get(pos + 2) {
6161            Some(t) if !t.joint => t,
6162            _ => return Ok(None),
6163        };
6164        if let TokKind::Group {
6165            delim: GroupDelim::Bracket,
6166            inner,
6167            ..
6168        } = &after.kind
6169        {
6170            if let Some(comment) = find_bracket_comment(inner) {
6171                let mut err = lower_err(
6172                    stmt,
6173                    ParseError::from_diagnostic(
6174                        ParseErrorKind::InvalidSyntax {
6175                            command: KEYWORD_EXPORT.to_string(),
6176                        },
6177                        dsl_diag::spelling_bracket_list_comment(KEYWORD_EXPORT),
6178                        &lowering_ctx(stmt),
6179                    ),
6180                );
6181                err.line = comment.line;
6182                err.col = comment.col;
6183                return Err(err);
6184            }
6185            let mut func_names = Vec::new();
6186            let mut type_names = Vec::new();
6187            let mut const_names = Vec::new();
6188            for part in split_bracket_entries(inner) {
6189                let part = trim_export_part(part);
6190                // A trailing comma leaves an empty final entry; it
6191                // carries no name and must not fail the list.
6192                if part.is_empty() {
6193                    continue;
6194                }
6195                let require_sigil = kind == KEYWORD_CONST;
6196                let Some((name, used)) = parse_export_name(part, 0, require_sigil, stmt)? else {
6197                    return Ok(None);
6198                };
6199                if used != part.len() {
6200                    return Ok(None);
6201                }
6202                match kind {
6203                    k if k == KEYWORD_TYPE => type_names.push(name),
6204                    k if k == KEYWORD_CONST => const_names.push(name),
6205                    _ => func_names.push(name),
6206                }
6207            }
6208            if func_names.is_empty() && type_names.is_empty() && const_names.is_empty() {
6209                return Ok(None);
6210            }
6211            return Ok(Some((
6212                ExportNames {
6213                    func_names,
6214                    type_names,
6215                    const_names,
6216                },
6217                3,
6218            )));
6219        }
6220        if matches!(&after.kind, TokKind::Group { .. }) {
6221            return Ok(None);
6222        }
6223        let require_sigil = kind == KEYWORD_CONST;
6224        let Some((name, used)) = parse_export_name(toks, pos + 2, require_sigil, stmt)? else {
6225            return Ok(None);
6226        };
6227        // Bare name after TYPE/FUNC/CONST prefix must consume exactly
6228        // one name; trailing loops stay outside like the unprefixed
6229        // case. `used` counts from pos+2, so 1 name is valid.
6230        if used == 0 {
6231            return Ok(None);
6232        }
6233        return Ok(Some((
6234            match kind {
6235                k if k == KEYWORD_TYPE => ExportNames {
6236                    func_names: Vec::new(),
6237                    type_names: vec![name],
6238                    const_names: Vec::new(),
6239                },
6240                k if k == KEYWORD_CONST => ExportNames {
6241                    func_names: Vec::new(),
6242                    type_names: Vec::new(),
6243                    const_names: vec![name],
6244                },
6245                _ => ExportNames {
6246                    func_names: vec![name],
6247                    type_names: Vec::new(),
6248                    const_names: Vec::new(),
6249                },
6250            },
6251            2 + used,
6252        )));
6253    }
6254    if let TokKind::Group {
6255        delim: GroupDelim::Bracket,
6256        inner,
6257        ..
6258    } = &next.kind
6259    {
6260        if let Some(comment) = find_bracket_comment(inner) {
6261            let mut err = lower_err(
6262                stmt,
6263                ParseError::from_diagnostic(
6264                    ParseErrorKind::InvalidSyntax {
6265                        command: KEYWORD_EXPORT.to_string(),
6266                    },
6267                    dsl_diag::spelling_bracket_list_comment(KEYWORD_EXPORT),
6268                    &lowering_ctx(stmt),
6269                ),
6270            );
6271            err.line = comment.line;
6272            err.col = comment.col;
6273            return Err(err);
6274        }
6275        let mut func_names = Vec::new();
6276        let mut type_names = Vec::new();
6277        let mut const_names = Vec::new();
6278        for part in split_bracket_entries(inner) {
6279            let part = trim_export_part(part);
6280            // A trailing comma leaves an empty final entry; it
6281            // carries no name and must not fail the list.
6282            if part.is_empty() {
6283                continue;
6284            }
6285            let (kind, rest) = split_export_prefix(part);
6286            let is_const = matches!(&kind, TokKind::Word(w) if w == KEYWORD_CONST);
6287            let is_type = matches!(&kind, TokKind::Word(w) if w == KEYWORD_TYPE);
6288            // Exactly one name per entry (entries never trail).
6289            let Some((name, used)) = parse_export_name(rest, 0, is_const, stmt)? else {
6290                return Ok(None);
6291            };
6292            if used != rest.len() {
6293                return Ok(None);
6294            }
6295            if is_const {
6296                const_names.push(name);
6297            } else if is_type {
6298                type_names.push(name);
6299            } else {
6300                func_names.push(name);
6301            }
6302        }
6303        if func_names.is_empty() && type_names.is_empty() && const_names.is_empty() {
6304            return Ok(None);
6305        }
6306        return Ok(Some((
6307            ExportNames {
6308                func_names,
6309                type_names,
6310                const_names,
6311            },
6312            2,
6313        )));
6314    }
6315    if matches!(&next.kind, TokKind::Group { .. }) {
6316        return Ok(None);
6317    }
6318    // Bare name (greedy `::` prefix; trailing loops outside). Bare
6319    // stays func for back-compat; `TYPE`/`FUNC` prefix selects above.
6320    // Func names never take `$`: `EXPORT $X` errors inside
6321    // `parse_export_name`, exactly like a `$`-less read elsewhere.
6322    match parse_export_name(toks, pos + 1, false, stmt)? {
6323        Some((name, used)) => Ok(Some((
6324            ExportNames {
6325                func_names: vec![name],
6326                type_names: Vec::new(),
6327                const_names: Vec::new(),
6328            },
6329            1 + used,
6330        ))),
6331        None => Ok(None),
6332    }
6333}
6334
6335/// Trim leading/trailing newlines around one `EXPORT` bracket entry.
6336/// Single owner so the explicit-prefix and mixed-list loops cannot
6337/// drift on trailing-comma handling.
6338fn trim_export_part(part: &[Tok]) -> &[Tok] {
6339    let mut part = part;
6340    while matches!(part.first().map(|t| &t.kind), Some(TokKind::Newline)) {
6341        part = &part[1..];
6342    }
6343    while matches!(part.last().map(|t| &t.kind), Some(TokKind::Newline)) {
6344        part = &part[..part.len() - 1];
6345    }
6346    part
6347}
6348
6349/// Split one mixed-list `EXPORT` entry into its kind prefix and name
6350/// slice. `TYPE`/`FUNC`/`CONST` plus a gapped name selects the kind;
6351/// anything else defaults to `FUNC`. Single owner so both bracket
6352/// loops agree on prefix parsing.
6353fn split_export_prefix(part: &[Tok]) -> (TokKind, &[Tok]) {
6354    // Optional per-entry `TYPE`/`FUNC`/`CONST` prefix for mixed
6355    // lists: `EXPORT [TYPE A, FUNC B, CONST $C, D]` (bare stays
6356    // func, `CONST` entries require `$`). The name must be `sep`
6357    // from the prefix; the prefix itself may be joint to a
6358    // preceding `[` or `,`, so only the name's joint flag matters.
6359    match part {
6360        [first, second, ..]
6361            if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_TYPE || w == KEYWORD_FUNC || w == KEYWORD_CONST)
6362                && !second.joint =>
6363        {
6364            (first.kind.clone(), &part[1..])
6365        }
6366        _ => (TokKind::Word(KEYWORD_FUNC.to_string()), part),
6367    }
6368}
6369
6370/// Split bracket inner tokens on top-level commas, preserving entries
6371/// for per-entry `TYPE`/`FUNC` handling. Newlines trim at the caller.
6372fn split_bracket_entries(inner: &[Tok]) -> Vec<&[Tok]> {
6373    let mut parts: Vec<&[Tok]> = Vec::new();
6374    let mut start = 0;
6375    for (i, tok) in inner.iter().enumerate() {
6376        if matches!(&tok.kind, TokKind::Punct(',')) {
6377            parts.push(&inner[start..i]);
6378            start = i + 1;
6379        }
6380    }
6381    parts.push(&inner[start..]);
6382    parts
6383}
6384
6385/// First comment token inside a bracket name list, if any. Single
6386/// owner for the shared `IMPORT`/`EXPORT` bracket rule (newlines ok,
6387/// comments miss): every bracket-list entry loop consults this
6388/// before treating the list as a shape miss, so the failure names
6389/// and points at the comment instead of falling through to the
6390/// generic statement error. Recurses into nested groups so
6391/// selective-harvest `[[...]]` entries report the same way through
6392/// the one key. Callers stamp the returned token's coordinates onto
6393/// the error (`stamp_pos` never overwrites real positions).
6394fn find_bracket_comment(inner: &[Tok]) -> Option<&Tok> {
6395    inner.iter().find_map(|t| match &t.kind {
6396        TokKind::Comment(_) => Some(t),
6397        TokKind::Group { inner, .. } => find_bracket_comment(inner),
6398        _ => None,
6399    })
6400}
6401
6402/// `TYPE NAME = SHAPE` at `pos`: uppercase name, single `=`, maximal
6403/// type-tag shape canonicalized through the shared spelling.
6404/// Returns the alias plus tokens consumed, or `None` on shape miss
6405/// (generic fails it in lowering like the grammar).
6406fn parse_type_stmt_at(
6407    toks: &[Tok],
6408    pos: usize,
6409    stmt: usize,
6410) -> Result<Option<(StepKind, usize)>, TokenError> {
6411    let name = match toks.get(pos + 1).map(|t| &t.kind) {
6412        Some(TokKind::Word(w)) if is_upper_ident(w) => w.clone(),
6413        _ => return Ok(None),
6414    };
6415    // Single `=` at any gap (`gap` zero-width); `==` misses.
6416    if !matches!(
6417        toks.get(pos + 2).map(|t| &t.kind),
6418        Some(TokKind::Punct('='))
6419    ) {
6420        return Ok(None);
6421    }
6422    if matches!(
6423        toks.get(pos + 3).map(|t| &t.kind),
6424        Some(TokKind::Punct('='))
6425    ) {
6426        return Ok(None);
6427    }
6428    let Some(end) = parse_type_shape(toks, pos + 3) else {
6429        return Ok(None);
6430    };
6431    // Post-match the span holds words, puncts, and default literals
6432    // only, so the shared renderer cannot fail; stay failed regardless.
6433    let target = render_type_region(&toks[pos + 3..end], stmt).unwrap_or_default();
6434    Ok(Some((StepKind::TypeAlias { name, target }, end - pos)))
6435}
6436
6437/// Single (non-block) `REMOTE`: target, optional bindings, block.
6438/// The target reads a maximal joint run in the grammar's superset
6439/// charset (misses fall to generic); strict validity fails loudly
6440/// with the exact backend message. Bindings miss to generic;
6441/// empty/missing bodies and nesting violations fail loudly.
6442fn parse_remote_single(
6443    toks: &[Tok],
6444    pos: usize,
6445    stmt: usize,
6446    ctx: &ParseCtx,
6447) -> Result<Option<(StepKind, usize)>, TokenError> {
6448    let fail = |msg: String| TokenError {
6449        diagnostic: None,
6450        hint: None,
6451        stmt,
6452        msg,
6453        line: 0,
6454        col: 0,
6455        kind: Some(ParseErrorKind::Validation {
6456            command: KEYWORD_REMOTE.to_string(),
6457        }),
6458    };
6459    // Target: joint run in the superset charset (alnum/`_`/`-`/`.`/`:`).
6460    // Anything else (joint or not) ends the run; an empty run misses
6461    // to generic. (`sep` needs no explicit check: a joint `(` is a
6462    // call routed before this ever runs, and anything unparseable
6463    // misses the same way.)
6464    let mut target = String::new();
6465    let mut p = pos + 1;
6466    while let Some(t) = toks.get(p) {
6467        if !t.joint && !target.is_empty() {
6468            break;
6469        }
6470        match &t.kind {
6471            TokKind::Word(w)
6472                if w.chars().all(|c| {
6473                    c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' || c == ':'
6474                }) =>
6475            {
6476                // Words arrive whole from the lexer; a bad word ends
6477                // the run (never partially appends), like the grammar.
6478                target.push_str(w);
6479                p += 1;
6480            }
6481            TokKind::Punct(c)
6482                if matches!(c, '_' | '-' | '.' | ':') && (target.is_empty() || t.joint) =>
6483            {
6484                target.push(*c);
6485                p += 1;
6486            }
6487            _ => break,
6488        }
6489    }
6490    if target.is_empty() {
6491        return Ok(None);
6492    }
6493    if !crate::commands::is_valid_remote_target(&target) {
6494        return Err(fail(format!(
6495            "invalid REMOTE target `{target}`: start alphanumeric, then alphanumeric, `_`, or `-`, max 64 chars, never SNAPSHOT, LOCAL, CACHE, SYSTEM, or REMOTE"
6496        )));
6497    }
6498    // Optional bindings `[$var, env:KEY]` at any gap (even joint,
6499    // probed); malformed bindings miss the whole shape to generic.
6500    let mut vars = Vec::new();
6501    let mut env = Vec::new();
6502    if let Some(bracket) = toks.get(p)
6503        && matches!(
6504            &bracket.kind,
6505            TokKind::Group {
6506                delim: GroupDelim::Bracket,
6507                ..
6508            }
6509        )
6510    {
6511        let inner = match &bracket.kind {
6512            TokKind::Group { inner, .. } => inner.clone(),
6513            _ => unreachable!(),
6514        };
6515        match parse_remote_bindings(&inner, stmt, ctx)? {
6516            Some((v, e)) => {
6517                vars = v;
6518                env = e;
6519            }
6520            None => return Ok(None),
6521        }
6522        p += 1;
6523    }
6524    // Block required (any gap, never a template); missing blocks
6525    // miss to generic.
6526    let block_ok = matches!(
6527        toks.get(p).map(|t| &t.kind),
6528        Some(TokKind::Group {
6529            delim: GroupDelim::Brace,
6530            ..
6531        })
6532    ) && toks.get(p).is_some_and(|t| !is_template_brace(t));
6533    if !block_ok {
6534        return Ok(None);
6535    }
6536    let inner = match &toks[p].kind {
6537        TokKind::Group { inner, .. } => inner.clone(),
6538        _ => unreachable!(),
6539    };
6540    let body = parse_body_steps(&inner, stmt, ctx, false)?;
6541    p += 1;
6542    if body.is_empty() {
6543        return Err(fail(format!(
6544            "{KEYWORD_REMOTE} requires a non-empty braced block"
6545        )));
6546    }
6547    if crate::commands::contains_remote_block(&body) {
6548        return Err(fail(format!(
6549            "REMOTE blocks cannot nest (target `{target}` contains another REMOTE block)"
6550        )));
6551    }
6552    if body
6553        .iter()
6554        .any(|s| crate::commands::contains_inherit_env(&s.kind))
6555    {
6556        return Err(fail(format!(
6557            "{KEYWORD_INHERIT_ENV} cannot appear inside a {KEYWORD_REMOTE} block: the guest inherits its own process environment"
6558        )));
6559    }
6560    // Outer-function containment (same rule as the shared remote
6561    // validators): body calls resolving to visible
6562    // outer `SCRIPT` defs (without same-body definitions) fail.
6563    {
6564        let mut inner_defs = HashSet::new();
6565        let mut calls = Vec::new();
6566        crate::commands::collect_remote_body_symbols(&body, &mut inner_defs, &mut calls);
6567        let outer_defs: HashSet<String> = ctx.funcs.borrow().iter().flatten().cloned().collect();
6568        for call in &calls {
6569            let bare = crate::constants::base_name(call);
6570            let is_script_call = match crate::constants::split_qualified(call) {
6571                Some((module, _)) => module == crate::constants::SCRIPT_MODULE_NAME,
6572                None => true,
6573            };
6574            if is_script_call && outer_defs.contains(bare) && !inner_defs.contains(bare) {
6575                return Err(fail(format!(
6576                    "REMOTE '{target}' calls outer function '{bare}' (functions must be defined inside the block)"
6577                )));
6578            }
6579        }
6580    }
6581    Ok(Some((
6582        StepKind::RemoteBlock {
6583            target,
6584            vars,
6585            env,
6586            body,
6587        },
6588        p - pos,
6589    )))
6590}
6591// ---- LET/SET/RETURN + expressions ----
6592// Expression tiers over [`Tok`] implement the precedence chain
6593// (or > and > comparison > ordering > add > mul > unary > atom);
6594// arithmetic/comparison lowering runs through the shared constructors
6595// (`make_arith`, `make_compare`, `apply_unary_neg`), so folding, RPN
6596// compilation, and overflow behavior are identical by construction,
6597// never re-derived.
6598
6599/// Eat a one- or two-char operator: single puncts match directly;
6600/// pairs (`==`, `!=`, `<=`, `>=`, `&&`, `||`, `::`) require a joint
6601/// second punct. Newlines never skip here (expression mode).
6602fn eat_op(cur: &mut Cursor, first: char, second: Option<char>) -> bool {
6603    // Gaps (comments included) are skipped before every operator.
6604    cur.skip_gap();
6605    let (a, b) = match (cur.toks.get(cur.pos), cur.toks.get(cur.pos + 1)) {
6606        (Some(a), b) => (a, b),
6607        _ => return false,
6608    };
6609    if !matches!(&a.kind, TokKind::Punct(c) if *c == first) {
6610        return false;
6611    }
6612    match second {
6613        None => {
6614            cur.pos += 1;
6615            true
6616        }
6617        Some(c2) => match b {
6618            Some(t) if t.joint && matches!(&t.kind, TokKind::Punct(c) if *c == c2) => {
6619                cur.pos += 2;
6620                true
6621            }
6622            _ => false,
6623        },
6624    }
6625}
6626
6627/// Dummy span for the shared lowering constructors: v2 owns no source
6628/// positions yet, so only success values (span-free) participate in
6629/// parity; failures surface through [`TokenError`] text.
6630fn lowering_ctx(stmt: usize) -> SpanContext<'static> {
6631    let _ = stmt;
6632    SpanContext::line_only(0)
6633}
6634
6635fn parse_expr_or(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6636    let mut left = parse_expr_and(cur, ctx)?;
6637    while eat_op(cur, '|', Some('|')) {
6638        cur.skip_gap();
6639        let right = parse_expr_and(cur, ctx)?;
6640        // No folding, no boundary checks: unfused literal runs stay
6641        // literal here.
6642        left = Expr::Logical {
6643            op: LogicalOp::Or,
6644            left: Box::new(left),
6645            right: Box::new(right),
6646        };
6647    }
6648    Ok(left)
6649}
6650
6651fn parse_expr_and(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6652    let mut left = parse_expr_cmp(cur, ctx)?;
6653    while eat_op(cur, '&', Some('&')) {
6654        cur.skip_gap();
6655        let right = parse_expr_cmp(cur, ctx)?;
6656        reject_boundary(&lowering_ctx(cur.stmt), &left).map_err(|e| cur.err(e.to_string()))?;
6657        reject_boundary(&lowering_ctx(cur.stmt), &right).map_err(|e| cur.err(e.to_string()))?;
6658        left = Expr::Logical {
6659            op: LogicalOp::And,
6660            left: Box::new(left),
6661            right: Box::new(right),
6662        };
6663    }
6664    Ok(left)
6665}
6666
6667fn parse_expr_cmp(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6668    let left = parse_expr_ord(cur, ctx)?;
6669    let op = if eat_op(cur, '=', Some('=')) {
6670        CompareOp::Eq
6671    } else if eat_op(cur, '!', Some('=')) {
6672        CompareOp::Ne
6673    } else {
6674        return Ok(left);
6675    };
6676    cur.skip_gap();
6677    let right = parse_expr_ord(cur, ctx)?;
6678    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
6679        .map_err(|e| cur.err(e.to_string()))?;
6680    reject_chained_compare(cur, false)?;
6681    Ok(expr)
6682}
6683
6684/// Reject a comparison operator trailing a complete comparison:
6685/// no grammar position continues with one, so the shape always fails —
6686/// loudly here instead of stranding text for a confusing downstream
6687/// error. The equality tier rejects all six (`$a == $b == $c`,
6688/// `$a == $b < $c < $d`); the ordering tier rejects ordering only
6689/// (`$a < $b < $c`), since `$a < $b == $c` is a legitimate equality
6690/// over an ordering result. Probes without consuming.
6691fn reject_chained_compare(cur: &mut Cursor, ordering_only: bool) -> Result<(), TokenError> {
6692    let mut probe = Cursor::expr(cur.toks, cur.stmt);
6693    probe.pos = cur.pos;
6694    probe.skip_gap();
6695    let chained = match probe.toks.get(probe.pos).map(|t| &t.kind) {
6696        Some(TokKind::Punct('<' | '>')) => true,
6697        Some(TokKind::Punct('=' | '!')) => !ordering_only,
6698        _ => false,
6699    };
6700    if chained {
6701        return Err(cur
6702            .err("chained comparison operators need explicit parentheses, e.g. `($a < $b) < $c`"));
6703    }
6704    Ok(())
6705}
6706
6707fn parse_expr_ord(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6708    let left = parse_expr_add(cur, ctx)?;
6709    let op = if eat_op(cur, '<', Some('=')) {
6710        CompareOp::Le
6711    } else if eat_op(cur, '>', Some('=')) {
6712        CompareOp::Ge
6713    } else if eat_op(cur, '<', None) {
6714        CompareOp::Lt
6715    } else if eat_op(cur, '>', None) {
6716        CompareOp::Gt
6717    } else {
6718        return Ok(left);
6719    };
6720    cur.skip_gap();
6721    let right = parse_expr_add(cur, ctx)?;
6722    let expr = make_compare(&lowering_ctx(cur.stmt), op, left, right)
6723        .map_err(|e| cur.err(e.to_string()))?;
6724    reject_chained_compare(cur, true)?;
6725    Ok(expr)
6726}
6727
6728fn parse_expr_add(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6729    let mut left = parse_expr_mul(cur, ctx)?;
6730    loop {
6731        let op = if eat_op(cur, '+', None) {
6732            ArithOp::Add
6733        } else if eat_op(cur, '-', None) {
6734            ArithOp::Sub
6735        } else {
6736            break;
6737        };
6738        cur.skip_gap();
6739        let right = parse_expr_mul(cur, ctx)?;
6740        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
6741            .map_err(|e| cur.err(e.to_string()))?;
6742    }
6743    Ok(left)
6744}
6745
6746fn parse_expr_mul(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6747    let mut left = parse_expr_unary(cur, ctx)?;
6748    loop {
6749        let op = if eat_op(cur, '*', None) {
6750            ArithOp::Mul
6751        } else if eat_op(cur, '/', None) {
6752            ArithOp::Div
6753        } else {
6754            break;
6755        };
6756        cur.skip_gap();
6757        let right = parse_expr_unary(cur, ctx)?;
6758        left = make_arith(&lowering_ctx(cur.stmt), op, left, right)
6759            .map_err(|e| cur.err(e.to_string()))?;
6760    }
6761    Ok(left)
6762}
6763
6764/// A `-` opens a bare word (never negation) when gaplessly followed by
6765/// a letter, `_`, or `/` — the `neg_op` lookahead, read off `joint`.
6766fn dash_is_bare(cur: &Cursor) -> bool {
6767    let next = cur.toks.get(cur.pos + 1);
6768    match next {
6769        Some(t) if t.joint => match &t.kind {
6770            TokKind::Word(w) => w
6771                .chars()
6772                .next()
6773                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_'),
6774            TokKind::Punct('/') => true,
6775            _ => false,
6776        },
6777        _ => false,
6778    }
6779}
6780
6781fn parse_expr_unary(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6782    let mut prefixes = Vec::new();
6783    loop {
6784        match cur.toks.get(cur.pos).map(|t| &t.kind) {
6785            Some(TokKind::Punct('!')) => {
6786                cur.pos += 1;
6787                // Each prefix is gap-separated.
6788                cur.skip_gap();
6789                prefixes.push(false);
6790            }
6791            Some(TokKind::Punct('-')) if !dash_is_bare(cur) => {
6792                cur.pos += 1;
6793                cur.skip_gap();
6794                prefixes.push(true);
6795            }
6796            _ => break,
6797        }
6798    }
6799    let mut expr = parse_expr_atom(cur, ctx)?;
6800    // Innermost prefix is closest to the atom: apply in reverse order.
6801    for is_neg in prefixes.into_iter().rev() {
6802        if is_neg {
6803            expr = apply_unary_neg(&lowering_ctx(cur.stmt), expr)
6804                .map_err(|e| cur.err(e.to_string()))?;
6805        } else {
6806            reject_boundary(&lowering_ctx(cur.stmt), &expr).map_err(|e| cur.err(e.to_string()))?;
6807            expr = Expr::Not(Box::new(expr));
6808        }
6809    }
6810    Ok(expr)
6811}
6812
6813/// Identifier charset for `$var` and `.segment` parts. Segments admit
6814/// digits-only too (`$a.0`); anything else ends the key path and errors
6815/// downstream, like the grammar's backtrack to `variable`.
6816fn is_ident_word(w: &str) -> bool {
6817    !w.is_empty() && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
6818}
6819
6820/// One joint `::NAME` tail at `pos` (the first `:`): both colons and
6821/// the name ride gapless, and the name matches [`is_ident_word`].
6822/// Single owner for qualified-`$ALIAS::NAME` matching, so `$` arms
6823/// and bare-word diagnostics cannot drift on jointness or charset.
6824fn match_joint_qualified(toks: &[Tok], pos: usize) -> Option<String> {
6825    let first = matches!(toks.get(pos).map(|t| &t.kind), Some(TokKind::Punct(':')))
6826        && toks.get(pos).is_some_and(|t| t.joint);
6827    let second = matches!(
6828        toks.get(pos + 1).map(|t| &t.kind),
6829        Some(TokKind::Punct(':'))
6830    ) && toks.get(pos + 1).is_some_and(|t| t.joint);
6831    let name_tok = toks.get(pos + 2);
6832    let ok = first
6833        && second
6834        && matches!(name_tok.map(|t| &t.kind), Some(TokKind::Word(w)) if is_ident_word(w))
6835        && name_tok.is_some_and(|t| t.joint);
6836    if !ok {
6837        return None;
6838    }
6839    match &name_tok.expect("checked").kind {
6840        TokKind::Word(w) => Some(w.clone()),
6841        _ => unreachable!(),
6842    }
6843}
6844
6845fn is_key_segment(w: &str) -> bool {
6846    !w.is_empty()
6847        && (w.chars().all(|c| c.is_ascii_digit())
6848            || (w
6849                .chars()
6850                .next()
6851                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
6852                && w.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')))
6853}
6854
6855fn is_env_key(w: &str) -> bool {
6856    !w.is_empty()
6857        && w.chars().next().is_some_and(|c| c.is_ascii_uppercase())
6858        && w.chars()
6859            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
6860}
6861
6862/// Maximal joint run of words and `-/.'/'` puncts: the bare-word
6863/// shape (which admits `/` anywhere, so `//c`, `/a`, `a/b`, and the
6864/// `/`-`c`-`/` operands of `/*c*/` math all read literally here).
6865/// Callers classify (`true`/`false`/string); the numeric path
6866/// runs first and falls back here on shape/follower mismatch.
6867/// Backslash escapes are arg-position syntax: the bare-word shape admits
6868/// no `\`, so expression runs containing one fail here (never drift
6869/// into a string the grammar rejects).
6870fn expr_bare_run(cur: &mut Cursor, leading_dash: bool) -> Result<String, TokenError> {
6871    let mut out = String::new();
6872    if leading_dash {
6873        match cur.next() {
6874            Some(t) if matches!(&t.kind, TokKind::Punct('-')) => out.push('-'),
6875            _ => return Err(cur.err("missing expression operand")),
6876        }
6877    }
6878    match cur.next() {
6879        Some(t) => match &t.kind {
6880            TokKind::Word(w) => out.push_str(w),
6881            // Leading `/` (operand position only; operators are
6882            // consumed by the tiers before operands parse).
6883            TokKind::Punct('/') => out.push('/'),
6884            _ => return Err(cur.err("missing expression operand")),
6885        },
6886        None => return Err(cur.err("missing expression operand")),
6887    }
6888    loop {
6889        let next = match cur.toks.get(cur.pos) {
6890            Some(t) if t.joint => t,
6891            _ => break,
6892        };
6893        match &next.kind {
6894            TokKind::Word(w) => {
6895                // Abutting words only continue through an operator gap
6896                // the tiers own (`a -b` never fuses); without a joint
6897                // punct between, stop. Since this token IS joint, the
6898                // previous token must have been a bare punct.
6899                out.push_str(w);
6900                cur.pos += 1;
6901            }
6902            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
6903                out.push(*c);
6904                cur.pos += 1;
6905            }
6906            _ => break,
6907        }
6908    }
6909    if out.contains('\\') {
6910        return Err(cur.err("unexpected escape in expression"));
6911    }
6912    Ok(out)
6913}
6914
6915/// Numeric literal head: digit-led word plus joint `.digits` tails.
6916/// Callers apply the separator-shape gate and the follower rule, then
6917/// the shared classifier.
6918fn number_head(cur: &mut Cursor) -> Option<String> {
6919    let first = match cur.toks.get(cur.pos).map(|t| &t.kind) {
6920        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => w.clone(),
6921        _ => return None,
6922    };
6923    let mut text = first;
6924    let mut pos = cur.pos + 1;
6925    loop {
6926        let dot = matches!(
6927            cur.toks.get(pos).map(|t| &t.kind),
6928            Some(TokKind::Punct('.'))
6929        ) && cur.toks.get(pos).is_some_and(|t| t.joint);
6930        let digits = cur.toks.get(pos + 1);
6931        let digits_ok = dot
6932            && matches!(digits.map(|t| &t.kind), Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_'))
6933            && digits.is_some_and(|t| t.joint);
6934        if !digits_ok {
6935            break;
6936        }
6937        text.push('.');
6938        if let Some(TokKind::Word(w)) = digits.map(|t| &t.kind) {
6939            text.push_str(w);
6940        }
6941        pos += 2;
6942    }
6943    Some(text)
6944}
6945
6946/// `_`-separator shape gate mirroring the `numeric_literal` rule:
6947/// digits with single-underscore separators, at most one fraction.
6948fn numeric_shape_ok(text: &str) -> bool {
6949    let mut parts = text.split('.');
6950    let int_part = parts.next().unwrap_or("");
6951    let frac_part = parts.next();
6952    if parts.next().is_some() {
6953        return false;
6954    }
6955    fn run_ok(s: &str) -> bool {
6956        !s.is_empty()
6957            && s.chars().all(|c| c.is_ascii_digit() || c == '_')
6958            && !s.starts_with('_')
6959            && !s.ends_with('_')
6960            && !s.contains("__")
6961    }
6962    run_ok(int_part) && frac_part.is_none_or(run_ok)
6963}
6964
6965/// Follower rule mirroring the `numeric_literal` trailing guard
6966/// (`!(ALNUM | "_" | "." | "/")`): a joint word, `.`, or `/` continues
6967/// into a bare word (`30s`, `1.`, `4/2`); `-`/`+`/operators let the
6968/// number stand for the tiers (`1-2` is `Sub`, like the grammar).
6969fn number_falls_to_bare(cur: &Cursor, consumed: usize) -> bool {
6970    match cur.toks.get(cur.pos + consumed) {
6971        Some(t) if t.joint => matches!(
6972            &t.kind,
6973            TokKind::Word(_) | TokKind::Punct('.') | TokKind::Punct('/')
6974        ),
6975        _ => false,
6976    }
6977}
6978
6979fn parse_expr_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
6980    match cur.toks.get(cur.pos).map(|t| &t.kind) {
6981        Some(TokKind::Group {
6982            delim: GroupDelim::Paren,
6983            inner,
6984            ..
6985        }) => {
6986            let inner = inner.clone();
6987            cur.pos += 1;
6988            let mut sub = Cursor::expr(&inner, cur.stmt);
6989            sub.skip_gap_nl();
6990            let expr = parse_expr_or(&mut sub, ctx)?;
6991            sub.skip_gap_nl();
6992            if !sub.done() {
6993                return Err(sub.err("unexpected text in parentheses"));
6994            }
6995            Ok(expr)
6996        }
6997        Some(TokKind::Word(_)) if call_shape_at(cur.toks, cur.pos, false).is_some() => {
6998            let (name, paren) =
6999                call_shape_at(cur.toks, cur.pos, false).ok_or_else(|| cur.err("unreachable"))?;
7000            let inner = match &cur.toks[paren].kind {
7001                TokKind::Group { inner, .. } => inner.clone(),
7002                _ => unreachable!(),
7003            };
7004            cur.pos = paren + 1;
7005            parse_expr_call(name, &inner, cur.stmt, ctx)
7006        }
7007        Some(TokKind::Punct(VAR_SIGIL_CHAR)) => {
7008            cur.pos += 1;
7009            // Atomic `variable`: `$` and the name ride gapless (the
7010            // enclosing rules are compound-atomic).
7011            let base = match cur.next() {
7012                Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
7013                    match &t.kind {
7014                        TokKind::Word(w) => w.clone(),
7015                        _ => unreachable!(),
7016                    }
7017                }
7018                _ => return Err(cur.err("`$` requires a variable name")),
7019            };
7020            let mut keys = Vec::new();
7021            // Qualified immutable read (`$ALIAS::NAME`). Key paths
7022            // never ride qualified names: copy to a local first.
7023            if let Some(name) = match_joint_qualified(cur.toks, cur.pos) {
7024                cur.pos += 3;
7025                if matches!(
7026                    cur.toks.get(cur.pos).map(|t| &t.kind),
7027                    Some(TokKind::Punct('.'))
7028                ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint)
7029                {
7030                    return Err(cur.err(crate::template::qualified_keypath_error()));
7031                }
7032                return Ok(Expr::ConstRef { alias: base, name });
7033            }
7034            loop {
7035                // Key-path dots are gapless too (`~` without `gap`).
7036                let dot = matches!(
7037                    cur.toks.get(cur.pos).map(|t| &t.kind),
7038                    Some(TokKind::Punct('.'))
7039                ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
7040                let seg = cur.toks.get(cur.pos + 1);
7041                let seg_ok = dot
7042                    && matches!(seg.map(|t| &t.kind), Some(TokKind::Word(w)) if is_key_segment(w))
7043                    && seg.is_some_and(|t| t.joint);
7044                if !seg_ok {
7045                    break;
7046                }
7047                if let Some(TokKind::Word(w)) = seg.map(|t| &t.kind) {
7048                    keys.push(w.clone());
7049                }
7050                cur.pos += 2;
7051            }
7052            if keys.is_empty() {
7053                Ok(Expr::Var { name: base })
7054            } else {
7055                Ok(Expr::KeyPath { base, keys })
7056            }
7057        }
7058        Some(TokKind::Word(w)) if w == "env" => {
7059            // `env:KEY` read when the full shape matches gaplessly
7060            // (atomic `env_read`); otherwise a bare word (`env` alone,
7061            // `env:k` lowercase) for the error path, exactly like the
7062            // grammar's mismatch.
7063            let key_ok = matches!(
7064                cur.toks.get(cur.pos + 1).map(|t| &t.kind),
7065                Some(TokKind::Punct(':'))
7066            ) && cur.toks.get(cur.pos + 1).is_some_and(|t| t.joint)
7067                && matches!(
7068                    cur.toks.get(cur.pos + 2).map(|t| &t.kind),
7069                    Some(TokKind::Word(k)) if is_env_key(k)
7070                )
7071                && cur.toks.get(cur.pos + 2).is_some_and(|t| t.joint);
7072            if !key_ok {
7073                return parse_bare_atom(cur, ctx, false);
7074            }
7075            cur.pos += 1;
7076            cur.pos += 1;
7077            match cur.next() {
7078                Some(t) => match &t.kind {
7079                    TokKind::Word(k) => Ok(Expr::Env(k.clone())),
7080                    _ => Err(cur.err("unreachable")),
7081                },
7082                None => Err(cur.err("unreachable")),
7083            }
7084        }
7085        Some(TokKind::Group {
7086            delim: GroupDelim::Bracket,
7087            inner,
7088            ..
7089        }) => {
7090            let inner = inner.clone();
7091            cur.pos += 1;
7092            parse_list_literal(&inner, cur.stmt, ctx)
7093        }
7094        Some(TokKind::Group {
7095            delim: GroupDelim::Brace,
7096            inner,
7097            ..
7098        }) => {
7099            let inner = inner.clone();
7100            cur.pos += 1;
7101            parse_map_or_block(&inner, cur.stmt, ctx)
7102        }
7103        Some(TokKind::Str { text, .. }) => {
7104            let text = text.clone();
7105            cur.pos += 1;
7106            Ok(Expr::Literal(Value::string(text)))
7107        }
7108        Some(TokKind::BlockStr(full)) => {
7109            let full = full.clone();
7110            cur.pos += 1;
7111            Ok(Expr::Literal(Value::string(
7112                crate::command::lower_block_string(&full),
7113            )))
7114        }
7115        Some(TokKind::Word(w)) if w.chars().next().is_some_and(|c| c.is_ascii_digit()) => {
7116            parse_numeric_atom(cur, ctx)
7117        }
7118        Some(TokKind::Word(_)) => {
7119            // Bare `ALIAS::NAME` never reads: without the `$` sigil
7120            // there is no qualified shape, only a bare word followed
7121            // by stray punctuation. Name the `$` form instead of
7122            // stranding the reader on the colons.
7123            if let Some(TokKind::Word(base)) = cur.toks.get(cur.pos).map(|t| &t.kind)
7124                && is_ident_word(base)
7125                && let Some(name) = match_joint_qualified(cur.toks, cur.pos + 1)
7126            {
7127                let base = base.clone();
7128                return Err(cur.err(crate::template::bare_sigil_error(&qualify(&base, &name))));
7129            }
7130            parse_bare_atom(cur, ctx, false)
7131        }
7132        Some(TokKind::Punct('-')) => parse_bare_atom(cur, ctx, true),
7133        Some(TokKind::Punct('/')) => parse_bare_atom(cur, ctx, false),
7134        _ => Err(cur.err("missing expression operand")),
7135    }
7136}
7137
7138/// Bare-word atom with a `-` lead (the caller proved it is not
7139/// negation): consumes the joint `-/.'/'` run for the bare-word
7140/// shape.
7141fn parse_bare_atom(
7142    cur: &mut Cursor,
7143    _ctx: &ParseCtx,
7144    leading_dash: bool,
7145) -> Result<Expr, TokenError> {
7146    let text = expr_bare_run(cur, leading_dash)?;
7147    match text.as_str() {
7148        "true" => Ok(Expr::Literal(Value::bool(true))),
7149        "false" => Ok(Expr::Literal(Value::bool(false))),
7150        _ => Ok(Expr::Literal(Value::string(text))),
7151    }
7152}
7153
7154/// Numeric atom: rejoin dotted tails, apply the shape gate and the
7155/// follower rule, then the shared classifier. Anything failing the
7156/// gate or follower reparses as a bare word (durations, versions,
7157/// paths), exactly like the grammar's numeric-literal-or-bare-word
7158/// order.
7159fn parse_numeric_atom(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7160    let start = cur.pos;
7161    let text = number_head(cur).ok_or_else(|| cur.err("missing expression operand"))?;
7162    let consumed = {
7163        let mut n = 1;
7164        let mut p = start + 1;
7165        while matches!(cur.toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('.')))
7166            && cur.toks.get(p).is_some_and(|t| t.joint)
7167            && matches!(
7168                cur.toks.get(p + 1).map(|t| &t.kind),
7169                Some(TokKind::Word(w)) if w.chars().all(|c| c.is_ascii_digit() || c == '_')
7170            )
7171            && cur.toks.get(p + 1).is_some_and(|t| t.joint)
7172        {
7173            n += 2;
7174            p += 2;
7175        }
7176        n
7177    };
7178    if !numeric_shape_ok(&text) || number_falls_to_bare(cur, consumed) {
7179        return parse_bare_atom(cur, ctx, false);
7180    }
7181    cur.pos += consumed;
7182    classify_numeric_text(&text).map_err(|msg| cur.err(msg))
7183}
7184
7185/// Full expression with the top-level boundary rejection (mirrors
7186/// `parse_expr`): a stray `UnsignedIntBoundary` that no unary `-`
7187/// consumed is an overflow error.
7188fn parse_expr_checked(cur: &mut Cursor, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7189    let expr = parse_expr_or(cur, ctx)?;
7190    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
7191        return Err(cur.err("integer overflow: 9223372036854775808 exceeds i64::MAX"));
7192    }
7193    Ok(expr)
7194}
7195
7196/// List literal over a bracket group's contents: the shared bracket
7197/// core (see [`parse_bracket_list`]) in `Expr` mode. Expression
7198/// positions fail loudly instead of missing, so `None` is unreachable.
7199fn parse_list_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7200    parse_bracket_list(inner, stmt, ctx, BracketItems::Expr)
7201        .map(|list| list.expect("expression lists fail loudly, never miss"))
7202}
7203
7204/// Map literal attempt over a brace group's contents: comma-separated
7205/// `key: value` entries with `gap` (never newline) around the colon.
7206/// Any entry failing the shape is not a map: the caller reports the
7207/// deferred block slice (the grammar tries `block` next, which fails
7208/// the same inputs at this stage).
7209/// Marker message for a map entry run that ends without a comma
7210/// where another entry follows. Matched by exact equality in
7211/// [`parse_map_or_block`], never by prefix, so wording changes stay
7212/// local to this const and its one reader.
7213const MISSING_MAP_COMMA_MSG: &str = "missing comma between map entries";
7214
7215fn parse_map_literal(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7216    let mut entries = Vec::new();
7217    // Empty (or blank/comment-only) braces are an empty map.
7218    if inner
7219        .iter()
7220        .all(|t| matches!(&t.kind, TokKind::Newline | TokKind::Comment(_)))
7221    {
7222        return Ok(Expr::Map(vec![]));
7223    }
7224    for part in split_top_commas(inner) {
7225        let mut sub = Cursor::expr(part, stmt);
7226        sub.skip_gap_nl();
7227        let (key, val) = parse_map_entry(&mut sub, ctx, stmt)?;
7228        sub.skip_gap_nl();
7229        if !sub.done() {
7230            return Err(map_trailing_error(&sub, ctx, stmt));
7231        }
7232        entries.push((key, val));
7233    }
7234    Ok(Expr::Map(entries))
7235}
7236
7237/// One `key: value` map entry: string, block-string, or bare key,
7238/// a colon, then a full checked expression. Every failure reads
7239/// `not a map literal` exactly like the old inline loop, so only
7240/// the trailing rule changes the surface.
7241fn parse_map_entry(
7242    sub: &mut Cursor,
7243    ctx: &ParseCtx,
7244    stmt: usize,
7245) -> Result<(String, Expr), TokenError> {
7246    let key = match sub.toks.get(sub.pos).map(|t| &t.kind) {
7247        Some(TokKind::Str { text, .. }) => {
7248            let key = text.clone();
7249            sub.pos += 1;
7250            key
7251        }
7252        Some(TokKind::BlockStr(full)) => {
7253            let key = crate::command::lower_block_string(full);
7254            sub.pos += 1;
7255            key
7256        }
7257        Some(TokKind::Word(_)) | Some(TokKind::Punct('-')) | Some(TokKind::Punct('/')) => {
7258            map_bare_key(sub)?
7259        }
7260        _ => return Err(sub.err("not a map literal")),
7261    };
7262    sub.skip_gap();
7263    if !sub.eat_punct(':') {
7264        return Err(sub.err("not a map literal"));
7265    }
7266    let val = parse_expr_checked(sub, ctx)?;
7267    reject_boundary(&lowering_ctx(stmt), &val).map_err(|e| sub.err(e.to_string()))?;
7268    Ok((key, val))
7269}
7270
7271/// Trailing content after a complete map entry: stamps the
7272/// offending token and names the likely missing comma when the
7273/// remainder parses as another entry. Anything else keeps the old
7274/// `not a map literal` text. Error-path only.
7275fn map_trailing_error(sub: &Cursor, ctx: &ParseCtx, stmt: usize) -> TokenError {
7276    let (line, col) = sub
7277        .toks
7278        .get(sub.pos)
7279        .map(|t| (t.line, t.col))
7280        .unwrap_or((0, 0));
7281    let mut probe = Cursor::expr(&sub.toks[sub.pos.min(sub.toks.len())..], stmt);
7282    probe.skip_gap_nl();
7283    if parse_map_entry(&mut probe, ctx, stmt).is_ok() {
7284        return TokenError {
7285            diagnostic: None,
7286            hint: None,
7287            stmt,
7288            line,
7289            col,
7290            msg: MISSING_MAP_COMMA_MSG.to_string(),
7291            kind: None,
7292        };
7293    }
7294    sub.err("not a map literal")
7295}
7296
7297/// Bare map key: joint `-/.'/'`-run, mirroring the bare-word charset
7298/// (no bool/numeric classification: keys are always strings).
7299fn map_bare_key(sub: &mut Cursor) -> Result<String, TokenError> {
7300    let mut out = String::new();
7301    if matches!(
7302        sub.toks.get(sub.pos).map(|t| &t.kind),
7303        Some(TokKind::Punct('-'))
7304    ) {
7305        out.push('-');
7306        sub.pos += 1;
7307    }
7308    // Leading `/` reads literally too (the bare-word shape admits `/`
7309    // anywhere: `{/a: 1}`, `{//c: 1}`); the joint loop below
7310    // continues the run.
7311    if matches!(
7312        sub.toks.get(sub.pos).map(|t| &t.kind),
7313        Some(TokKind::Punct('/'))
7314    ) {
7315        out.push('/');
7316        sub.pos += 1;
7317    }
7318    match sub.toks.get(sub.pos).map(|t| &t.kind) {
7319        Some(TokKind::Word(w)) => {
7320            out.push_str(w);
7321            sub.pos += 1;
7322        }
7323        // A leading `/` above already started the run; anything
7324        // else still needs a word head.
7325        _ if !out.is_empty() => {}
7326        _ => return Err(sub.err("not a map literal")),
7327    }
7328    while let Some(t) = sub.toks.get(sub.pos) {
7329        if !t.joint {
7330            break;
7331        }
7332        match &t.kind {
7333            TokKind::Word(w) => {
7334                out.push_str(w);
7335                sub.pos += 1;
7336            }
7337            TokKind::Punct(c) if matches!(c, '-' | '.' | '/') => {
7338                out.push(*c);
7339                sub.pos += 1;
7340            }
7341            _ => break,
7342        }
7343    }
7344    if out.contains('\\') {
7345        return Err(sub.err("unexpected escape in map key"));
7346    }
7347    Ok(out)
7348}
7349
7350/// Map-or-block over a brace group's contents: maps parse literally;
7351/// anything else is an inline block (`Expr::Block` over the body
7352/// steps, scopes unmarked like every braced body).
7353fn parse_map_or_block(inner: &[Tok], stmt: usize, ctx: &ParseCtx) -> Result<Expr, TokenError> {
7354    match parse_map_literal(inner, stmt, ctx) {
7355        Ok(map) => Ok(map),
7356        // A detected missing comma is never a block: its `key:`
7357        // remainder cannot parse as a statement (a `name: "a"` line
7358        // fails as `unknown command`), so the block path can only
7359        // misreport it. Surface the map error instead; every other
7360        // map failure keeps the block fallback exactly as before.
7361        Err(e) if e.msg == MISSING_MAP_COMMA_MSG => Err(e),
7362        Err(_) => Ok(Expr::Block(parse_body_steps(inner, stmt, ctx, false)?)),
7363    }
7364}
7365
7366/// Parse one standalone expression from lexed tokens (the
7367/// `parse_expression_str` entry point): a full tier parse with
7368/// top-level boundary rejection and full consumption.
7369pub(crate) fn parse_single_expr(
7370    toks: &[Tok],
7371    stmt: usize,
7372    ctx: &ParseCtx,
7373) -> Result<Expr, TokenError> {
7374    let mut cur = Cursor::expr(toks, stmt);
7375    let expr = parse_expr_checked(&mut cur, ctx)?;
7376    if !cur.done() {
7377        return Err(cur.err("unexpected text in expression"));
7378    }
7379    Ok(expr)
7380}
7381
7382/// Assignment `=`: the first depth-zero `=` neither glued to a
7383/// following `=` (`==`) nor glued after `!`/`<`/`>`/`=` (`!=`, `<=`,
7384/// `>=`, second of `==`). `<>` shape brackets own any `=` inside
7385/// them (field defaults), so LET annotations with defaults find the
7386/// real assignment. Glued-ness reads off the `=`'s own `joint` (gap
7387/// before it) and the follower's (gap after it). Anything else leaves
7388/// the statement bare (`LET $p: PIPE`), exactly where the grammar's
7389/// `"="` match fails.
7390fn find_assign_eq(body: &[Tok]) -> Option<usize> {
7391    let mut depth = 0usize;
7392    for (i, tok) in body.iter().enumerate() {
7393        match &tok.kind {
7394            TokKind::Punct('<') => depth += 1,
7395            TokKind::Punct('>') if depth > 0 => depth -= 1,
7396            TokKind::Punct('=') if depth == 0 => {
7397                let next_eq = body
7398                    .get(i + 1)
7399                    .is_some_and(|t| t.joint && matches!(&t.kind, TokKind::Punct('=')));
7400                let prev_op = tok.joint
7401                    && i > 0
7402                    && matches!(&body[i - 1].kind, TokKind::Punct('!' | '<' | '>' | '='));
7403                if !next_eq && !prev_op {
7404                    return Some(i);
7405                }
7406            }
7407            _ => {}
7408        }
7409    }
7410    None
7411}
7412
7413/// Render a type region joint-aware (`LIST< MAP >` keeps its gaps for
7414/// the shared canonicalizer, exactly like `type_tag.as_str()`).
7415fn render_type_region(toks: &[Tok], stmt: usize) -> Result<String, TokenError> {
7416    let mut out = String::new();
7417    for tok in toks {
7418        // Ridden newlines from multi-line `<...>` shapes carry no
7419        // output, so the shape canonicalizes exactly like one line.
7420        if matches!(&tok.kind, TokKind::Newline) {
7421            continue;
7422        }
7423        if !tok.joint && !out.is_empty() {
7424            out.push(' ');
7425        }
7426        match &tok.kind {
7427            TokKind::Word(w) => out.push_str(w),
7428            TokKind::Punct(c) => out.push(*c),
7429            TokKind::Str { text, quote } => {
7430                out.push(*quote);
7431                out.push_str(text);
7432                out.push(*quote);
7433            }
7434            TokKind::BlockStr(full) => out.push_str(full),
7435            _ => {
7436                return Err(TokenError {
7437                    diagnostic: None,
7438                    hint: None,
7439                    stmt,
7440                    msg: format!("malformed type in {KEYWORD_LET}"),
7441                    line: 0,
7442                    col: 0,
7443                    kind: None,
7444                });
7445            }
7446        }
7447    }
7448    if out.is_empty() {
7449        return Err(TokenError {
7450            diagnostic: None,
7451            hint: None,
7452            stmt,
7453            msg: format!(
7454                "{KEYWORD_LET} requires explicit type: {KEYWORD_LET} $var: {KEYWORD_TYPE} = <expr>"
7455            ),
7456            line: 0,
7457            col: 0,
7458            kind: None,
7459        });
7460    }
7461    Ok(crate::canonicalize_spelling(&out))
7462}
7463
7464fn expect_dollar_var(cur: &mut Cursor, msg: &str) -> Result<String, TokenError> {
7465    // Atomic `dollar_ident`: no gap between `$` and the name (the
7466    // enclosing statements are compound-atomic, so implicit spacing is
7467    // off and only explicit `gap`s admit whitespace).
7468    match cur.next() {
7469        Some(t) if matches!(&t.kind, TokKind::Punct(VAR_SIGIL_CHAR)) => {}
7470        _ => return Err(cur.err(msg)),
7471    }
7472    match cur.next() {
7473        Some(t) if t.joint && matches!(&t.kind, TokKind::Word(w) if is_ident_word(w)) => {
7474            match &t.kind {
7475                TokKind::Word(w) => Ok(w.clone()),
7476                _ => unreachable!(),
7477            }
7478        }
7479        _ => Err(cur.err(msg)),
7480    }
7481}
7482
7483/// Reject a qualified `$ALIAS::NAME` where a declaration or mutation
7484/// target stands: bindings declare plain locals, and module `CONST`s
7485/// are immutable (reads use `$ALIAS::NAME` in expressions).
7486/// Single owner for the qualified-target gate, shared by the binding
7487/// (`LET`/`CONST`) and reassignment (`$var = <expr>`) heads so all fail
7488/// with one message shape.
7489fn reject_qualified_target(cur: &Cursor, base: &str) -> Result<(), TokenError> {
7490    let first = matches!(
7491        cur.toks.get(cur.pos).map(|t| &t.kind),
7492        Some(TokKind::Punct(':'))
7493    ) && cur.toks.get(cur.pos).is_some_and(|t| t.joint);
7494    let second = matches!(
7495        cur.toks.get(cur.pos + 1).map(|t| &t.kind),
7496        Some(TokKind::Punct(':'))
7497    ) && cur.toks.get(cur.pos + 1).is_some_and(|t| t.joint);
7498    if first && second {
7499        return Err(cur.err(format!(
7500            "cannot declare or assign ${base}::...: module values read as $ALIAS::NAME in expressions and are never binding targets"
7501        )));
7502    }
7503    Ok(())
7504}
7505
7506/// `LET`/`CONST` body: the keyword is already matched. Returns `None`
7507/// (miss to generic, which fails in lowering like the grammar's
7508/// committed `instruction`) when the shape cannot match any binding
7509/// form: no gapless `$var`, or no `:` after it
7510/// (every form needs `: TYPE`). Past that the shape is committed and
7511/// malformed tails fail loudly. `kw` selects the produced StepKind
7512/// family (`LET` or `CONST`) and the diagnostic spellings.
7513fn parse_let_body(
7514    body: &[Tok],
7515    stmt: usize,
7516    ctx: &ParseCtx,
7517) -> Result<Option<(StepKind, usize)>, TokenError> {
7518    parse_binding_body(body, stmt, ctx, KEYWORD_LET)
7519}
7520
7521/// `CONST` body: same shapes as `LET`, producing the `Const` family.
7522/// Miss semantics mirror [`parse_let_body`].
7523fn parse_const_body(
7524    body: &[Tok],
7525    stmt: usize,
7526    ctx: &ParseCtx,
7527) -> Result<Option<(StepKind, usize)>, TokenError> {
7528    parse_binding_body(body, stmt, ctx, KEYWORD_CONST)
7529}
7530
7531/// Shared `LET`/`CONST` body: the head keyword is already matched.
7532/// `kw` must be `KEYWORD_LET` or `KEYWORD_CONST`. Both take a `$var`
7533/// head; `CONST` additionally requires an uppercase name.
7534/// Single owner for the binding header: the `is_const` flag rides
7535/// straight into [`StepKind::Bind`], so no post-pass flips per form.
7536fn parse_binding_body(
7537    body: &[Tok],
7538    stmt: usize,
7539    ctx: &ParseCtx,
7540    kw: &'static str,
7541) -> Result<Option<(StepKind, usize)>, TokenError> {
7542    use crate::commands::BindRhs;
7543    let is_const = kw == KEYWORD_CONST;
7544    let mut cur = Cursor::expr(body, stmt);
7545    match cur.next() {
7546        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == kw) => {}
7547        _ => return Err(cur.err("unreachable")),
7548    }
7549    // Head: `$var` for both `LET` and `CONST`. `CONST` additionally
7550    // requires an uppercase name (see `validate_const_name`). The
7551    // keyword already committed to a binding, so a malformed head
7552    // fails loudly; only a non-name head misses to generic.
7553    let var = if is_const {
7554        cur.skip_gap();
7555        match cur.toks.get(cur.pos).map(|t| &t.kind) {
7556            Some(TokKind::Punct(VAR_SIGIL_CHAR)) => {
7557                let var = expect_dollar_var(
7558                    &mut cur,
7559                    "CONST requires a `$NAME` head: CONST $NAME: TYPE = ...",
7560                )?;
7561                reject_qualified_target(&cur, &var)?;
7562                validate_const_name(ctx, &cur, &var)?;
7563                var
7564            }
7565            Some(TokKind::Word(_)) => {
7566                return Err(
7567                    cur.err(format!("{KEYWORD_CONST} requires `$`: write {KEYWORD_CONST} $NAME: {KEYWORD_TYPE} = ... (never bare)"))
7568                );
7569            }
7570            _ => return Ok(None),
7571        }
7572    } else {
7573        // No `$var`: no binding form can match (miss, never a hard fail).
7574        let var = match expect_dollar_var(&mut cur, &format!("{kw} requires a variable")) {
7575            Ok(var) => var,
7576            Err(_) => return Ok(None),
7577        };
7578        reject_qualified_target(&cur, &var)?;
7579        var
7580    };
7581    // The header allows gaps (comments, never newlines).
7582    cur.skip_gap();
7583    // No `:`: untyped bindings are rejected outright. Every binding is
7584    // typed; the old miss-to-generic path only hid that behind a
7585    // rambling "invalid syntax" message. (FOR already does this.)
7586    let head_example = if is_const { "$NAME" } else { "$var" };
7587    if !cur.eat_punct(':') {
7588        return Err(TokenError {
7589            diagnostic: None,
7590            hint: None,
7591            stmt,
7592            msg: format!(
7593                "{kw} requires explicit types: {kw} {head_example}: {KEYWORD_TYPE} = <expr>"
7594            ),
7595            line: 0,
7596            col: 0,
7597            kind: Some(ParseErrorKind::InvalidSyntax {
7598                command: kw.to_string(),
7599            }),
7600        });
7601    }
7602    // Type region runs to the depth-zero assignment `=`; `<>`
7603    // shapes own any `=` inside them (field defaults).
7604    let type_start = cur.pos;
7605    let assign = find_assign_eq(&body[type_start..]).map(|i| i + type_start);
7606    let Some(eq) = assign else {
7607        // Bare `$p: PIPE` mints a fresh pipe and ends with the
7608        // type word (trailing elements loop on, probed); every other
7609        // bare type is a validation error, mirroring the grammar.
7610        if matches!(
7611            body.get(type_start).map(|t| &t.kind),
7612            Some(TokKind::Word(w)) if w == crate::TypeTag::Pipe.name()
7613        ) {
7614            let kind = StepKind::Bind {
7615                var: var.clone(),
7616                decl_type: crate::TypeTag::Pipe.name().to_string(),
7617                is_const,
7618                rhs: BindRhs::Expr(Expr::FreshPipe),
7619            };
7620            return Ok(Some((kind, type_start + 1)));
7621        }
7622        return Err(cur.err(format!(
7623            "{kw} requires an expression: {kw} {head_example}: TYPE = <expr> (only {kw} {head_example}: PIPE omits the initializer)"
7624        )));
7625    };
7626    let decl_type = render_type_region(&body[type_start..eq], stmt)?;
7627    let (kind, rhs_used) = parse_let_rhs(&body[eq + 1..], var, decl_type, stmt, ctx, is_const)?;
7628    Ok(Some((kind, eq + 1 + rhs_used)))
7629}
7630
7631/// Collision gate for `CONST` names: uppercase plus keywords,
7632/// commands, types, and workspace targets. `FUNC` names and host
7633/// functions live in separate namespaces and may share a spelling
7634/// with a private `CONST`.
7635/// Same-scope `LET`/`CONST` duplicates rely on the static gate so
7636/// guard-disjoint declarations stay legal.
7637fn validate_const_name(ctx: &ParseCtx, cur: &Cursor, name: &str) -> Result<(), TokenError> {
7638    let _ = ctx;
7639    // Single gate for the declaration spelling: uppercase plus
7640    // freedom from reserved words (see [`crate::constants`]).
7641    if !crate::constants::is_const_name(name) {
7642        return Err(cur.err(format!(
7643            "{KEYWORD_CONST} names must be UPPERCASE: got `{name}`"
7644        )));
7645    }
7646    if crate::commands::is_reserved_const_name(name) {
7647        return Err(cur.err(format!(
7648            "CONST {name} collides with reserved keyword `{name}`"
7649        )));
7650    }
7651    Ok(())
7652}
7653
7654/// LET right-hand side dispatch, mirroring the grammar order
7655/// (`let_async`, then `let_capture`, then `let_statement`):
7656/// `WITH_IO`-led lines branch async/sync like
7657/// `parse_let_async_statement_from_pair`, `ASYNC`-led lines spawn
7658/// tasks, `TIMEOUT`-led lines capture through the wrapper,
7659/// `AWAIT $v` captures, RUN exec-form captures, known commands
7660/// capture through the generic parser (lowering failures fatal,
7661/// exactly like the committed grammar alternative), and anything
7662/// else parses as an expression (unknown leads included). Returns
7663/// the kind and RHS tokens consumed: captures ending in structural
7664/// pairs leave trailing elements for the caller.
7665fn parse_let_rhs(
7666    rhs: &[Tok],
7667    var: String,
7668    decl_type: String,
7669    stmt: usize,
7670    ctx: &ParseCtx,
7671    is_const: bool,
7672) -> Result<(StepKind, usize), TokenError> {
7673    // Leading gap comments vanish like the `=` gap (but a `//`/`#`
7674    // to end of input leaves no expression, failing).
7675    let mut lead = Cursor::expr(rhs, stmt);
7676    lead.skip_gap();
7677    let (rhs, skipped) = (&rhs[lead.pos..], lead.pos);
7678    let head_word = match rhs.first().map(|t| &t.kind) {
7679        Some(TokKind::Word(w)) => Some(w.clone()),
7680        _ => None,
7681    };
7682    // `WITH_IO`-led lines share `let_async_statement` with the
7683    // `ASYNC` forms (the grammar claims every WITH_IO-led LET
7684    // there); shape misses fall through to generic below.
7685    if head_word.as_deref() == Some(KEYWORD_WITH_IO)
7686        && let Some(found) =
7687            try_let_with_io_rhs(rhs, var.clone(), decl_type.clone(), stmt, ctx, is_const)?
7688    {
7689        let (kind, used) = found;
7690        return Ok((kind, skipped + used));
7691    }
7692    // `ASYNC`-led lines (with followers; alone they commit to the
7693    // generic path like the grammar, failing in lowering) spawn
7694    // background tasks. No `WITH_IO` scan here (probed: the LET
7695    // path accepts what statement `ASYNC` rejects).
7696    if head_word.as_deref() == Some(KEYWORD_ASYNC) && rhs.len() > 1 {
7697        let (kind, used) = parse_let_async_rhs(&rhs[1..], var, decl_type, stmt, ctx, is_const)?;
7698        return Ok((kind, skipped + 1 + used));
7699    }
7700    // `TIMEOUT`-led lines capture through the wrapper (shape misses
7701    // fall through to generic, which fails in lowering).
7702    if head_word.as_deref() == Some(KEYWORD_TIMEOUT)
7703        && let Some((kind, used)) = parse_timeout_single(rhs, 0, stmt, ctx)?
7704    {
7705        let span = lowering_ctx(stmt);
7706        crate::commands::reject_async_in_capture(&span, &kind).map_err(|e| lower_err(stmt, e))?;
7707        crate::commands::reject_pipe_stdout_in_capture(&span, &kind)
7708            .map_err(|e| lower_err(stmt, e))?;
7709        return Ok((
7710            StepKind::Bind {
7711                var,
7712                decl_type,
7713                is_const,
7714                rhs: BindRhs::Capture(Box::new(kind)),
7715            },
7716            skipped + used,
7717        ));
7718    }
7719    // `AWAIT $v` captures the task output (`$`+name ride gapless in
7720    // this atomic position, like the grammar). Anything else
7721    // `AWAIT`-led goes generic below (lowering fails it, probed).
7722    if head_word.as_deref() == Some(KEYWORD_AWAIT)
7723        && rhs.len() == 3
7724        && let (Some(dollar), Some(task)) = (rhs.get(1), rhs.get(2))
7725        && matches!(&dollar.kind, TokKind::Punct(VAR_SIGIL_CHAR))
7726        && task.joint
7727        && let TokKind::Word(task_var) = &task.kind
7728        && is_ident_word(task_var)
7729    {
7730        return Ok((
7731            StepKind::Bind {
7732                var,
7733                decl_type,
7734                is_const,
7735                rhs: BindRhs::Await {
7736                    task_var: task_var.clone(),
7737                },
7738            },
7739            skipped + 3,
7740        ));
7741    }
7742    // RUN exec form captures the structured argv (gapped bracket;
7743    // a joint bracket falls through to generic, which fails it in
7744    // lowering).
7745    if head_word.as_deref() == Some(KEYWORD_RUN)
7746        && matches!(
7747            rhs.get(1).map(|t| (&t.kind, t.joint)),
7748            Some((
7749                TokKind::Group {
7750                    delim: GroupDelim::Bracket,
7751                    ..
7752                },
7753                false
7754            ))
7755        )
7756        && rhs.len() == 2
7757    {
7758        let inner = match &rhs[1].kind {
7759            TokKind::Group { inner, .. } => inner.clone(),
7760            _ => unreachable!(),
7761        };
7762        // Non-map blocks miss the exec shape; fall through below
7763        // (known-command capture, then expression), mirroring the
7764        // grammar's ordered alternatives.
7765        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
7766            let kind =
7767                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
7768            return Ok((
7769                StepKind::Bind {
7770                    var,
7771                    decl_type,
7772                    is_const,
7773                    rhs: BindRhs::Capture(Box::new(kind)),
7774                },
7775                skipped + 2,
7776            ));
7777        }
7778    }
7779    // File `IMPORT ["path" AS ALIAS]` (#115) captures the imported
7780    // pipeline's `RETURN` value like a call (`LET $r: STRING = IMPORT ...`
7781    // lowers to `AssignCapture`): exactly one file entry, no modules.
7782    // Anything else shaped like an import is a hard error; shape misses
7783    // fall through to generic below, which fails them in lowering.
7784    if head_word.as_deref() == Some(KEYWORD_IMPORT)
7785        && let Some((path, alias, used)) = parse_single_file_import(rhs, 0, stmt, ctx)?
7786    {
7787        return Ok((
7788            StepKind::Bind {
7789                var,
7790                decl_type,
7791                is_const,
7792                rhs: BindRhs::Capture(Box::new(StepKind::ImportFile { path, alias })),
7793            },
7794            skipped + used,
7795        ));
7796    }
7797    // Known-command leads capture through the generic parser
7798    // (lowering failures are fatal here, exactly like the committed
7799    // grammar alternative: probed wrapper-alone and `ISOLATED`-led
7800    // shapes error in lowering); unknown leads parse as expressions.
7801    match &head_word {
7802        Some(head) if is_known_command(head) => {
7803            let (cmd, used) = parse_inner_command(rhs, stmt, ctx)?;
7804            let span = lowering_ctx(stmt);
7805            crate::commands::reject_async_in_capture(&span, &cmd)
7806                .map_err(|e| lower_err(stmt, e))?;
7807            crate::commands::reject_pipe_stdout_in_capture(&span, &cmd)
7808                .map_err(|e| lower_err(stmt, e))?;
7809            // `INHERIT_ENV`-led lines land here (generic): the
7810            // nesting check rejects them (probed).
7811            crate::commands::reject_nested_inherit_env(&span, &cmd)
7812                .map_err(|e| lower_err(stmt, e))?;
7813            return Ok((
7814                StepKind::Bind {
7815                    var,
7816                    decl_type,
7817                    is_const,
7818                    rhs: BindRhs::Capture(Box::new(cmd)),
7819                },
7820                skipped + used,
7821            ));
7822        }
7823        _ => {}
7824    }
7825    let mut cur = Cursor::expr(rhs, stmt);
7826    let expr = parse_expr_checked(&mut cur, ctx)?;
7827    let used = skipped + cur.pos;
7828    Ok((
7829        StepKind::Bind {
7830            var,
7831            decl_type,
7832            is_const,
7833            rhs: BindRhs::Expr(expr),
7834        },
7835        used,
7836    ))
7837}
7838
7839/// `WITH_IO`-led LET right-hand side, mirroring
7840/// `parse_let_async_statement_from_pair`'s `with_io_command` branch:
7841/// wrapping `ASYNC` binds a pipe-wired background task (multi-step
7842/// blocks fail loudly), wrapping a sync command captures its stdout
7843/// (async bodies and `stdout` pipes fail loudly), and a bare
7844/// bracket fails validation. `None` on shape miss (bad bracket:
7845/// the caller goes generic, which fails in lowering).
7846fn try_let_with_io_rhs(
7847    rhs: &[Tok],
7848    var: String,
7849    decl_type: String,
7850    stmt: usize,
7851    ctx: &ParseCtx,
7852    is_const: bool,
7853) -> Result<Option<(StepKind, usize)>, TokenError> {
7854    let kw = if is_const { KEYWORD_CONST } else { KEYWORD_LET };
7855    let bracket = match rhs.get(1) {
7856        Some(t)
7857            if !t.joint
7858                && matches!(
7859                    &t.kind,
7860                    TokKind::Group {
7861                        delim: GroupDelim::Bracket,
7862                        ..
7863                    }
7864                ) =>
7865        {
7866            t
7867        }
7868        _ => return Ok(None),
7869    };
7870    let inner = match &bracket.kind {
7871        TokKind::Group { inner, .. } => inner.clone(),
7872        _ => unreachable!(),
7873    };
7874    let bindings = match parse_io_bindings(&inner, stmt, ctx)? {
7875        Some(bindings) => bindings,
7876        None => return Ok(None),
7877    };
7878    let fail = |msg: String| TokenError {
7879        diagnostic: None,
7880        hint: None,
7881        stmt,
7882        msg,
7883        line: 0,
7884        col: 0,
7885        kind: None,
7886    };
7887    let rest = &rhs[2..];
7888    let Some(first) = rest.first() else {
7889        // Bare bracket: the grammar's committed validation error.
7890        return Err(fail(format!(
7891            "{kw} $var: TYPE = WITH_IO requires an ASYNC command (e.g. {kw} $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7892        )));
7893    };
7894    if first.joint {
7895        // The inner rides after a `sep`: joint followers miss the
7896        // shape and fail validation like the grammar's bare bracket.
7897        return Err(fail(format!(
7898            "{kw} $var: TYPE = WITH_IO requires an ASYNC command (e.g. {kw} $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7899        )));
7900    }
7901    if matches!(&first.kind, TokKind::Word(w) if w == KEYWORD_ASYNC) {
7902        // `WITH_IO [..] ASYNC <single|block>`: the bindings apply
7903        // inside the task thread (same shape as a one-step body
7904        // holding one `WITH_IO` step, which the runtime supports).
7905        // A bare `ASYNC` goes generic and fails in lowering
7906        // (`unknown command: ASYNC`, probed).
7907        let after = &rest[1..];
7908        if after.is_empty() {
7909            // Bare `ASYNC`: the grammar commits to `instruction`
7910            // and lowering fails it (`unknown command: ASYNC`,
7911            // probed); mirror by running generic, staying failed
7912            // even under a lenient dispatcher.
7913            match parse_inner_command(&rest[..1], stmt, ctx) {
7914                Err(e) => return Err(e),
7915                Ok(_) => {
7916                    return Err(fail(format!(
7917                        "{kw} $var: HANDLE<T> = ASYNC requires a body"
7918                    )));
7919                }
7920            }
7921        }
7922        if let Some(second) = after.first()
7923            && matches!(
7924                &second.kind,
7925                TokKind::Group {
7926                    delim: GroupDelim::Brace,
7927                    ..
7928                }
7929            )
7930            && !is_template_brace(second)
7931        {
7932            let brace_inner = match &second.kind {
7933                TokKind::Group { inner, .. } => inner.clone(),
7934                _ => unreachable!(),
7935            };
7936            let body = parse_body_steps(&brace_inner, stmt, ctx, false)?;
7937            if body.len() != 1 {
7938                return Err(fail(format!(
7939                    "{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"
7940                )));
7941            }
7942            let wrapped = Step {
7943                guard: None,
7944                kind: StepKind::WithIo {
7945                    bindings,
7946                    cmd: Box::new(
7947                        body.into_iter()
7948                            .next()
7949                            .ok_or_else(|| {
7950                                fail(format!("{KEYWORD_LET} $var: {HANDLE_TYPE_NAME}<T> = {KEYWORD_ASYNC} requires a body"))
7951                            })?
7952                            .kind,
7953                    ),
7954                },
7955                scope_enter: 0,
7956                scope_exit: 0,
7957                line: 0,
7958                col: 0,
7959            };
7960            return Ok(Some((
7961                StepKind::Bind {
7962                    var,
7963                    decl_type,
7964                    is_const,
7965                    rhs: BindRhs::Async(vec![wrapped]),
7966                },
7967                2 + 2,
7968            )));
7969        }
7970        if after.first().is_some_and(|t| t.joint) {
7971            // Joint followers miss the inner `sep`: same validation
7972            // error as the bare bracket.
7973            return Err(fail(
7974                "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
7975                    .to_string(),
7976            ));
7977        }
7978        let (cmd, used) = parse_single_inner(
7979            rest,
7980            1,
7981            stmt,
7982            ctx,
7983            InnerRules {
7984                allow_await: false,
7985                allow_with_io: false,
7986            },
7987        )?;
7988        let wrapped = Step {
7989            guard: None,
7990            kind: StepKind::WithIo {
7991                bindings,
7992                cmd: Box::new(cmd),
7993            },
7994            scope_enter: 0,
7995            scope_exit: 0,
7996            line: 0,
7997            col: 0,
7998        };
7999        let kind = StepKind::Bind {
8000            var,
8001            decl_type,
8002            is_const,
8003            rhs: BindRhs::Async(vec![wrapped]),
8004        };
8005        let span = lowering_ctx(stmt);
8006        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
8007        return Ok(Some((kind, 2 + 1 + used)));
8008    }
8009    if matches!(
8010        &first.kind,
8011        TokKind::Group {
8012            delim: GroupDelim::Brace,
8013            ..
8014        }
8015    ) {
8016        // A brace is no sync command: same validation error (probed).
8017        return Err(fail(format!(
8018            "{kw} $var: TYPE = WITH_IO requires an ASYNC command (e.g. {kw} $t: HANDLE<VOID> = WITH_IO [stdin=$p] ASYNC WRITE \"f\")"
8019        )));
8020    }
8021    // Sync inner: capture with the shared checks (the capture sink
8022    // owns stdout; async never runs inline).
8023    let (cmd, used) = parse_single_inner(
8024        rest,
8025        0,
8026        stmt,
8027        ctx,
8028        InnerRules {
8029            allow_await: false,
8030            allow_with_io: true,
8031        },
8032    )?;
8033    let span = lowering_ctx(stmt);
8034    if crate::commands::has_stdout_pipe(&bindings) {
8035        return Err(fail(format!(
8036            "{kw} capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
8037        )));
8038    }
8039    crate::commands::reject_async_in_capture(&span, &cmd).map_err(|e| lower_err(stmt, e))?;
8040    Ok(Some((
8041        StepKind::Bind {
8042            var,
8043            decl_type,
8044            is_const,
8045            rhs: BindRhs::Capture(Box::new(StepKind::WithIo {
8046                bindings,
8047                cmd: Box::new(cmd),
8048            })),
8049        },
8050        2 + used,
8051    )))
8052}
8053
8054/// `ASYNC`-led LET right-hand side (the tokens after `ASYNC`):
8055/// a block or single command becomes the task body. No `WITH_IO`
8056/// scan (probed: this path accepts what statement `ASYNC`
8057/// rejects); nesting still fails loudly through the shared check.
8058fn parse_let_async_rhs(
8059    rest: &[Tok],
8060    var: String,
8061    decl_type: String,
8062    stmt: usize,
8063    ctx: &ParseCtx,
8064    is_const: bool,
8065) -> Result<(StepKind, usize), TokenError> {
8066    let Some(first) = rest.first() else {
8067        return Err(TokenError {
8068            diagnostic: None,
8069            hint: None,
8070            stmt,
8071            msg: format!("binding $var: {HANDLE_TYPE_NAME}<T> = {KEYWORD_ASYNC} requires a body"),
8072            line: 0,
8073            col: 0,
8074            kind: None,
8075        });
8076    };
8077    if matches!(
8078        &first.kind,
8079        TokKind::Group {
8080            delim: GroupDelim::Brace,
8081            ..
8082        }
8083    ) && !is_template_brace(first)
8084    {
8085        let inner = match &first.kind {
8086            TokKind::Group { inner, .. } => inner.clone(),
8087            _ => unreachable!(),
8088        };
8089        let body = parse_body_steps(&inner, stmt, ctx, false)?;
8090        let kind = StepKind::Bind {
8091            var,
8092            decl_type,
8093            is_const,
8094            rhs: BindRhs::Async(body),
8095        };
8096        let span = lowering_ctx(stmt);
8097        crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
8098        return Ok((kind, 1));
8099    }
8100    if first.joint {
8101        return Err(TokenError {
8102            diagnostic: None,
8103            hint: None,
8104            stmt,
8105            msg: format!("binding $var: {HANDLE_TYPE_NAME}<T> = {KEYWORD_ASYNC} requires a body"),
8106            line: 0,
8107            col: 0,
8108            kind: None,
8109        });
8110    }
8111    let (cmd, used) = parse_single_inner(
8112        rest,
8113        0,
8114        stmt,
8115        ctx,
8116        InnerRules {
8117            allow_await: false,
8118            allow_with_io: false,
8119        },
8120    )?;
8121    let kind = StepKind::Bind {
8122        var,
8123        decl_type,
8124        is_const,
8125        rhs: BindRhs::Async(vec![Step {
8126            guard: None,
8127            kind: cmd,
8128            scope_enter: 0,
8129            scope_exit: 0,
8130            line: 0,
8131            col: 0,
8132        }]),
8133    };
8134    let span = lowering_ctx(stmt);
8135    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
8136    Ok((kind, used))
8137}
8138
8139fn parse_set_body(
8140    body: &[Tok],
8141    stmt: usize,
8142    ctx: &ParseCtx,
8143) -> Result<(StepKind, usize), TokenError> {
8144    let mut cur = Cursor::expr(body, stmt);
8145    if matches!(
8146        cur.toks.get(cur.pos).map(|t| &t.kind),
8147        Some(TokKind::Punct(VAR_SIGIL_CHAR))
8148    ) {
8149        let var = expect_dollar_var(&mut cur, "mutation requires a variable: $var = <expr>")?;
8150        reject_qualified_target(&cur, &var)?;
8151        // Key paths never serve as mutation targets: without this,
8152        // `$M.a = ...` would drop `.a` when the head jumps to `=`
8153        // below and silently rebind the whole `$M`. Reads use key
8154        // paths in expressions; writes rebind the variable
8155        // (e.g. `$M = MAP_SET($M, "a", 2)`).
8156        if matches!(
8157            cur.toks.get(cur.pos).map(|t| &t.kind),
8158            Some(TokKind::Punct('.'))
8159        ) {
8160            let mut target = sigil_var(&var);
8161            let mut p = cur.pos;
8162            loop {
8163                let dot = matches!(cur.toks.get(p).map(|t| &t.kind), Some(TokKind::Punct('.')));
8164                let word = match cur.toks.get(p + 1).map(|t| &t.kind) {
8165                    Some(TokKind::Word(w)) if is_key_segment(w) => w.clone(),
8166                    _ => break,
8167                };
8168                if !dot {
8169                    break;
8170                }
8171                target.push('.');
8172                target.push_str(&word);
8173                p += 2;
8174            }
8175            return Err(cur.err(format!(
8176                "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))",
8177                example = sigil_var(&var),
8178            )));
8179        }
8180        let assign = find_assign_eq(&body[cur.pos..]).map(|i| i + cur.pos);
8181        let eq = match assign {
8182            Some(eq) => eq,
8183            None => {
8184                return Err(cur.err("mutation requires a variable: $var = <expr>"));
8185            }
8186        };
8187        cur.pos = eq + 1;
8188        cur.skip_gap();
8189        let expr = parse_expr_checked(&mut cur, ctx)?;
8190        return Ok((StepKind::Set { var, expr }, cur.pos));
8191    }
8192    // Bare words are literal text, never variable targets: only
8193    // `$var = <expr>` mutates.
8194    Err(cur.err("mutation requires a variable: $var = <expr>"))
8195}
8196
8197fn parse_return_body(
8198    body: &[Tok],
8199    stmt: usize,
8200    ctx: &ParseCtx,
8201) -> Result<(StepKind, usize), TokenError> {
8202    let mut cur = Cursor::expr(body, stmt);
8203    match cur.next() {
8204        Some(t) if matches!(&t.kind, TokKind::Word(w) if w == KEYWORD_RETURN) => {}
8205        _ => return Err(cur.err("unreachable")),
8206    }
8207    if cur.done() {
8208        return Ok((
8209            StepKind::Return {
8210                expr: Box::new(Expr::Literal(Value::string(String::new()))),
8211                is_bare: true,
8212            },
8213            cur.pos,
8214        ));
8215    }
8216    let expr = parse_expr_checked(&mut cur, ctx)?;
8217    Ok((
8218        StepKind::Return {
8219            expr: Box::new(expr),
8220            is_bare: false,
8221        },
8222        cur.pos,
8223    ))
8224}
8225
8226/// Lower one statement to steps through the element loop: the
8227/// statement guard attaches to the first element only (trailing
8228/// elements ride guardless, probed): the pending guard clears after
8229/// the first command token.
8230fn lower_stmt_steps(
8231    stmt: &Stmt,
8232    idx: usize,
8233    ctx: &ParseCtx,
8234    in_block: bool,
8235    mark: bool,
8236) -> Result<Vec<Step>, TokenError> {
8237    let guard = parse_guard_groups(&stmt.guard, idx)?;
8238    // Statement-head braces route here (mid-run braces fail inside
8239    // the element loop): templates and guardless/bare blocks fail
8240    // loudly; guarded braces open guard blocks (top level) or the
8241    // nested quirk (in bodies).
8242    let mut steps = if starts_brace(&stmt.body) {
8243        parse_brace_head(stmt, guard, idx, ctx, in_block, mark)?
8244    } else {
8245        parse_elements(&stmt.body, idx, ctx, guard, in_block)?
8246    };
8247    // Stamp the statement's source position on every directly
8248    // produced step still missing one. Nested body steps were stamped
8249    // by their own statements during recursion, so only direct
8250    // products are claimed here; inner statements keep their own
8251    // lines and columns.
8252    for step in &mut steps {
8253        if step.line == 0 {
8254            step.line = stmt.line;
8255        }
8256        if step.col == 0 {
8257            step.col = stmt.col;
8258        }
8259    }
8260    // Qualify bare placeholder calls (`{{ NAME(args) }}`) through
8261    // the shared static resolver, so templates obey exactly the
8262    // statement-position scope rule. Nested bodies were already
8263    // qualified by their own recursive statements with their own
8264    // frames, so only direct products are visited here. Both
8265    // `Arg::String` fragments (via `walk_raw_strings_mut`) and
8266    // `Expr::Literal` strings (LET/SET/RETURN/call args/list/map
8267    // literals/parenthesized args) are qualified: expression
8268    // positions expand through the same `expand_string` at runtime,
8269    // so they must see the same parse-time rewrite. `WithIo` and
8270    // `AssignCapture` box their inner command directly (no recursive
8271    // statement pass), so the helper descends into them; all other
8272    // bodies were already qualified with their own frames.
8273    // `Step.guards` carry no template text (`Guard::Attr` triples
8274    // evaluated via `guard_allows`, never expanded), so there is
8275    // nothing to qualify there.
8276    let mut failed: Option<TokenError> = None;
8277    for step in &mut steps {
8278        qualify_step_templates(step, ctx, idx, &mut failed);
8279        if failed.is_some() {
8280            break;
8281        }
8282    }
8283    if let Some(err) = failed {
8284        return Err(err);
8285    }
8286    Ok(steps)
8287}
8288
8289/// Qualify one direct statement product plus any boxed `WithIo` /
8290/// `AssignCapture` inner command (same scope frame, never a
8291/// recursive statement pass). Body vectors are skipped: their steps
8292/// were qualified by their own recursive statements.
8293fn qualify_step_templates(
8294    step: &mut Step,
8295    ctx: &ParseCtx,
8296    stmt: usize,
8297    failed: &mut Option<TokenError>,
8298) {
8299    qualify_kind_templates(&mut step.kind, ctx, stmt, failed);
8300}
8301
8302/// Qualify one `StepKind` plus boxed inner commands sharing the
8303/// same scope frame.
8304fn qualify_kind_templates(
8305    kind: &mut StepKind,
8306    ctx: &ParseCtx,
8307    stmt: usize,
8308    failed: &mut Option<TokenError>,
8309) {
8310    kind.walk_raw_strings_mut(&mut |text| {
8311        if failed.is_none() {
8312            match qualify_template_calls(text, ctx, stmt) {
8313                Ok(Some(rewritten)) => *text = rewritten,
8314                Ok(None) => {}
8315                Err(err) => *failed = Some(err),
8316            }
8317        }
8318    });
8319    if failed.is_some() {
8320        return;
8321    }
8322    kind.walk_exprs_mut(&mut |expr| {
8323        if failed.is_some() {
8324            return;
8325        }
8326        expr.walk_mut(&mut |node| {
8327            if failed.is_some() {
8328                return;
8329            }
8330            if let Expr::Literal(value) = node
8331                && let Some(text) = value.as_str()
8332            {
8333                match qualify_template_calls(text, ctx, stmt) {
8334                    Ok(Some(rewritten)) => {
8335                        *value = Value::string(rewritten);
8336                    }
8337                    Ok(None) => {}
8338                    Err(err) => *failed = Some(err),
8339                }
8340            }
8341        });
8342    });
8343    if failed.is_some() {
8344        return;
8345    }
8346    // Boxed single commands share the outer scope frame (no recursive
8347    // statement pass built them): qualify the inner kind directly.
8348    match kind {
8349        StepKind::WithIo { cmd, .. } => {
8350            qualify_kind_templates(cmd, ctx, stmt, failed);
8351        }
8352        StepKind::Bind {
8353            rhs: BindRhs::Capture(cmd),
8354            ..
8355        } => {
8356            qualify_kind_templates(cmd, ctx, stmt, failed);
8357        }
8358        _ => {}
8359    }
8360    if failed.is_some() {
8361        return;
8362    }
8363    // Single-command synthetic bodies share the outer frame: `TIMEOUT 5s
8364    // <cmd>`, `ISOLATED <cmd>`, `ASYNC <cmd>`, and `AssignAsync` wrappers
8365    // build their `body` inline via `parse_single_inner` with no recursive
8366    // `lower_stmt_steps` pass, so their one synthetic step needs this one.
8367    // Brace-delimited bodies are NEVER re-walked here: they were already
8368    // lowered via `parse_body_steps` with their own frames and statement
8369    // indices (mirroring `Expr::walk_mut` skipping `Expr::Block`), and
8370    // re-resolving under the outer frame would corrupt scope isolation
8371    // and error attribution. The match names only the synthetic carriers;
8372    // any other body (If/For/While/FuncDef/RemoteBlock/WithIoBlock) stays
8373    // exactly as its own recursive pass left it.
8374    match kind {
8375        StepKind::Timeout { body, .. }
8376        | StepKind::Isolated { body }
8377        | StepKind::AsyncBlock { body } => {
8378            for step in body.iter_mut() {
8379                if failed.is_some() {
8380                    return;
8381                }
8382                qualify_step_templates(step, ctx, stmt, failed);
8383            }
8384        }
8385        StepKind::Bind { rhs, .. } => match rhs {
8386            BindRhs::Async(body) => {
8387                for step in body.iter_mut() {
8388                    if failed.is_some() {
8389                        return;
8390                    }
8391                    qualify_step_templates(step, ctx, stmt, failed);
8392                }
8393            }
8394            BindRhs::Capture(_) | BindRhs::Expr(_) | BindRhs::Await { .. } => {}
8395        },
8396        _ => {}
8397    }
8398}
8399
8400/// Statement-head `{...}` dispatcher. Template braces fail (the
8401/// grammar strands them); guardless top-level braces fail; detached
8402/// or guardless in-body braces fail (no `block_start` in
8403/// `block_element`); guarded braces open a guard scope at top level
8404/// or mirror the nested quirk formula in bodies. Trailing elements
8405/// loop on guardless outside (like the grammar's continued line).
8406fn parse_brace_head(
8407    stmt: &Stmt,
8408    guard: Option<GuardExpr>,
8409    idx: usize,
8410    ctx: &ParseCtx,
8411    in_block: bool,
8412    mark: bool,
8413) -> Result<Vec<Step>, TokenError> {
8414    let brace = &stmt.body[0];
8415    if is_template_brace(brace) {
8416        return Err(TokenError {
8417            diagnostic: None,
8418            hint: None,
8419            stmt: idx,
8420            msg: "'{' without a pending guard".to_string(),
8421            line: 0,
8422            col: 0,
8423            kind: None,
8424        });
8425    }
8426    let inner = match &brace.kind {
8427        TokKind::Group { inner, .. } => inner.clone(),
8428        _ => unreachable!(),
8429    };
8430    if in_block {
8431        // Attached guarded braces only: pending holds all groups but
8432        // the last (the block's own), mirroring the pair structure.
8433        if guard.is_none() || stmt.brace_detached || stmt.guard.is_empty() {
8434            return Err(TokenError {
8435                diagnostic: None,
8436                hint: None,
8437                stmt: idx,
8438                msg: "unexpected '{' in block body".to_string(),
8439                line: 0,
8440                col: 0,
8441                kind: None,
8442            });
8443        }
8444        let n = stmt.guard.len();
8445        let mut pending = None;
8446        if n > 1 {
8447            pending = parse_guard_groups(&stmt.guard[..n - 1], idx)?;
8448        }
8449        let block_guard = parse_guard_groups(&stmt.guard[n - 1..n], idx)?.ok_or(TokenError {
8450            diagnostic: None,
8451            hint: None,
8452            stmt: idx,
8453            msg: "unexpected '{' in block body".to_string(),
8454            line: 0,
8455            col: 0,
8456            kind: None,
8457        })?;
8458        let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
8459        // Guard-block bodies propagate the ambient marking context
8460        // (top-level nesting marks; wrapper bodies never mark).
8461        // Quirk formula verbatim (including the dropped block guard
8462        // with inner guards, probed).
8463        for s in &mut steps {
8464            let inner_guard = s.guard.take();
8465            s.guard = Some(match (pending.clone(), inner_guard) {
8466                (Some(p), Some(e)) => GuardExpr::all(vec![p, e]),
8467                (Some(p), None) => GuardExpr::all(vec![p, block_guard.clone()]),
8468                (None, Some(e)) => e,
8469                (None, None) => block_guard.clone(),
8470            });
8471        }
8472        // Marking contexts bump each nesting level (probed top-level
8473        // double-block 2/2); wrapper bodies stay 0/0.
8474        // Trailing elements ride outside, unmarked.
8475        if mark {
8476            if let Some(first) = steps.first_mut() {
8477                first.scope_enter += 1;
8478            }
8479            if let Some(last) = steps.last_mut() {
8480                last.scope_exit += 1;
8481            }
8482        }
8483        // Trailing elements loop on guardless outside.
8484        if stmt.body.len() > 1 {
8485            let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
8486            steps.append(&mut rest);
8487        }
8488        return Ok(steps);
8489    }
8490    // Top level: guardless braces fail; guarded braces open a guard
8491    // scope (each step folds outer-then-inner with markers).
8492    let Some(outer) = guard else {
8493        return Err(TokenError {
8494            diagnostic: None,
8495            hint: None,
8496            stmt: idx,
8497            msg: "'{' without a pending guard".to_string(),
8498            line: 0,
8499            col: 0,
8500            kind: None,
8501        });
8502    };
8503    let mut steps = parse_body_steps(&inner, idx, ctx, mark)?;
8504    if steps.is_empty() {
8505        return Err(TokenError {
8506            diagnostic: None,
8507            hint: None,
8508            stmt: idx,
8509            msg: "guard block must contain at least one command".to_string(),
8510            line: 0,
8511            col: 0,
8512            kind: None,
8513        });
8514    }
8515    for s in &mut steps {
8516        let inner_guard = s.guard.take();
8517        s.guard = Some(match inner_guard {
8518            Some(e) => GuardExpr::all(vec![outer.clone(), e]),
8519            None => outer.clone(),
8520        });
8521    }
8522    if let Some(first) = steps.first_mut() {
8523        first.scope_enter += 1;
8524    }
8525    if let Some(last) = steps.last_mut() {
8526        last.scope_exit += 1;
8527    }
8528    if stmt.body.len() > 1 {
8529        let mut rest = parse_elements(&stmt.body[1..], idx, ctx, None, in_block)?;
8530        steps.append(&mut rest);
8531    }
8532    Ok(steps)
8533}
8534
8535/// Parse consecutive elements to end of run (the grammar's
8536/// `element*`): structural pairs (calls, RUN-exec, await/cancel,
8537/// wrapper blocks) end mid-run and trailing elements form following
8538/// steps; instructions and expressions consume greedily to the end.
8539fn parse_elements(
8540    toks: &[Tok],
8541    stmt: usize,
8542    ctx: &ParseCtx,
8543    guard: Option<GuardExpr>,
8544    in_block: bool,
8545) -> Result<Vec<Step>, TokenError> {
8546    let mut steps = Vec::new();
8547    let mut pos = 0;
8548    // Statement guard: consumed by the first element that yields a
8549    // step. `IMPORT` yields none, so the guard leaks to the next
8550    // element (probed).
8551    let mut pending_guard: Option<GuardExpr> = guard;
8552    while pos < toks.len() {
8553        // Trailing gap comments between elements (`} #c`, `F("a")
8554        // /*c*/ ECHO`, `LET $x: INT = 1 //c` — the pair ended, so the
8555        // comment is silent like the grammar, never payload):
8556        // `#` and lexer `Comment` markers run to the run end, `//`
8557        // likewise (line comments eat `;` too, and runs hold no
8558        // newlines), `/* */` balances. Mid-run `#`/`/*` stay payload
8559        // text inside the generic path, which consumes everything
8560        // and never loops back here.
8561        if matches!(&toks[pos].kind, TokKind::Punct('#'))
8562            || matches!(&toks[pos].kind, TokKind::Comment(_))
8563        {
8564            break;
8565        }
8566        if matches!(&toks[pos].kind, TokKind::Punct('/')) && is_comment_open(toks, pos) {
8567            if matches!(
8568                toks.get(pos + 1).map(|t| &t.kind),
8569                Some(TokKind::Punct('/'))
8570            ) {
8571                break;
8572            }
8573            match skip_inline_comment(toks, pos) {
8574                Some(past) => {
8575                    pos = past;
8576                    continue;
8577                }
8578                None => {
8579                    return Err(TokenError {
8580                        diagnostic: None,
8581                        hint: None,
8582                        stmt,
8583                        msg: "unclosed block comment".to_string(),
8584                        line: 0,
8585                        col: 0,
8586                        kind: None,
8587                    });
8588                }
8589            }
8590        }
8591        // `IMPORT` statements update the import frames; module entries
8592        // emit no step (the guard leaks to the next element, probed,
8593        // unless this is top level, where a guarded module import
8594        // fails), while each file entry emits one `ImportFile` step
8595        // carrying the guard. Shape misses fall through to generic
8596        // (lowering fails them).
8597        if matches!(
8598            toks.get(pos).map(|t| &t.kind),
8599            Some(TokKind::Word(w)) if w == KEYWORD_IMPORT
8600        ) {
8601            // Unified statement form (#115): each entry validates hard
8602            // (unknown modules, bad aliases, templates, remote URLs);
8603            // module entries update the frame and emit no step, file
8604            // and harvest entries emit one step each, in source order.
8605            // A top-level guard on a statement with module entries fails
8606            // like the historical directive; file-only statements consume
8607            // the guard like any other element.
8608            if let Some(((modules, kinds), used)) =
8609                parse_import_statement(toks, pos, stmt, ctx, pending_guard.is_some())?
8610            {
8611                if !modules.is_empty() && !in_block && pending_guard.is_some() {
8612                    return Err(TokenError {
8613                        diagnostic: None,
8614                        hint: None,
8615                        stmt,
8616                        msg: format!("{KEYWORD_IMPORT} cannot be guarded"),
8617                        line: 0,
8618                        col: 0,
8619                        kind: None,
8620                    });
8621                }
8622                // Modules-only statements stay zero-step directives: the
8623                // guard leaks to the next element (probed). Anything with
8624                // file or harvest entries consumes it.
8625                let guard = if kinds.is_empty() {
8626                    None
8627                } else {
8628                    pending_guard.take()
8629                };
8630                for kind in kinds {
8631                    steps.push(Step {
8632                        guard: guard.clone(),
8633                        kind,
8634                        scope_enter: 0,
8635                        scope_exit: 0,
8636                        line: 0,
8637                        col: 0,
8638                    });
8639                }
8640                pos += used;
8641                continue;
8642            }
8643        }
8644        let guard = pending_guard.take();
8645        let (mut got, used) = parse_element_at(toks, pos, stmt, ctx, guard, in_block)?;
8646        if used == 0 {
8647            return Err(TokenError {
8648                diagnostic: None,
8649                hint: None,
8650                stmt,
8651                msg: "element consumed no input".to_string(),
8652                line: 0,
8653                col: 0,
8654                kind: None,
8655            });
8656        }
8657        steps.append(&mut got);
8658        pos += used;
8659    }
8660    Ok(steps)
8661}
8662
8663/// Parse one element at `pos`, returning built steps (guard already
8664/// assigned: `first_guard` for the first, folded per io-block inner
8665/// step) and tokens consumed.
8666fn parse_element_at(
8667    toks: &[Tok],
8668    pos: usize,
8669    stmt: usize,
8670    ctx: &ParseCtx,
8671    first_guard: Option<GuardExpr>,
8672    in_block: bool,
8673) -> Result<(Vec<Step>, usize), TokenError> {
8674    let step = |kind: StepKind| Step {
8675        guard: first_guard.clone(),
8676        kind,
8677        scope_enter: 0,
8678        scope_exit: 0,
8679        line: 0,
8680        col: 0,
8681    };
8682    let head_word = match toks.get(pos).map(|t| &t.kind) {
8683        Some(TokKind::Word(w)) => Some(w.clone()),
8684        _ => None,
8685    };
8686    // Mid-run `{...}` (after a call, wrapper block, ...): the
8687    // grammar strands it (`block_start` needs a pending guard or
8688    // `WITH_IO` wait, both consumed), so fail loudly. Statement-head
8689    // braces route through `lower_stmt_steps`, never here.
8690    if starts_brace(&toks[pos..]) {
8691        return Err(TokenError {
8692            diagnostic: None,
8693            hint: None,
8694            stmt,
8695            msg: "'{' without a pending guard".to_string(),
8696            line: 0,
8697            col: 0,
8698            kind: None,
8699        });
8700    }
8701    // LET/CONST/SET/RETURN heads parse with groups intact, then trailing
8702    // elements loop on (probed `LET $x: INT = 1 ECHO bye`). Binding shape
8703    // misses fall to generic (lowering fails them like a committed
8704    // `instruction` would, e.g. `LET foo`).
8705    if head_word.as_deref() == Some(KEYWORD_LET)
8706        && let Some((kind, used)) = parse_let_body(&toks[pos..], stmt, ctx)?
8707    {
8708        return Ok((vec![step(kind)], used));
8709    }
8710    if head_word.as_deref() == Some(KEYWORD_CONST)
8711        && let Some((kind, used)) = parse_const_body(&toks[pos..], stmt, ctx)?
8712    {
8713        return Ok((vec![step(kind)], used));
8714    }
8715    if matches!(
8716        toks.get(pos).map(|t| &t.kind),
8717        Some(TokKind::Punct(VAR_SIGIL_CHAR))
8718    ) {
8719        let (kind, used) = parse_set_body(&toks[pos..], stmt, ctx)?;
8720        return Ok((vec![step(kind)], used));
8721    }
8722    if head_word.as_deref() == Some(KEYWORD_RETURN) {
8723        let (kind, used) = parse_return_body(&toks[pos..], stmt, ctx)?;
8724        return Ok((vec![step(kind)], used));
8725    }
8726    // Calls route before heads (even known commands take the call
8727    // path with a joint paren, probed `ECHO("hi")`); the call ends
8728    // mid-run and trailing elements loop on (fixes the slice-4a
8729    // divergence, probed).
8730    if call_shape_at(toks, pos, true).is_some() {
8731        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
8732        return Ok((vec![step(kind)], used));
8733    }
8734    if let Some(TokKind::Word(base)) = toks.get(pos).map(|t| &t.kind)
8735        && is_ident_word(base)
8736        && match_joint_qualified(toks, pos + 1).is_some()
8737    {
8738        // Qualified calls already returned above; anything else
8739        // starting `ALIAS::NAME` is a binding-target misuse.
8740        return Err(TokenError {
8741            diagnostic: None,
8742            hint: None,
8743            stmt,
8744            msg: "cannot declare or assign ALIAS::NAME: module values read as $ALIAS::NAME in expressions and are never binding targets".to_string(),
8745            line: 0,
8746            col: 0,
8747            kind: None,
8748        });
8749    }
8750    // Block statements (shape misses fall to generic, which fails
8751    // them in lowering like the grammar's committed `instruction`).
8752    // `BREAK`/`CONTINUE` take no args (structural, like the grammar):
8753    // each consumes one token and trailing elements loop on (probed
8754    // `BREAK ECHO hi`); a lone trailing word fails downstream like
8755    // the grammar's committed mismatch.
8756    match head_word.as_deref() {
8757        Some(KEYWORD_BREAK) => {
8758            return Ok((vec![step(StepKind::Break)], 1));
8759        }
8760        Some(KEYWORD_CONTINUE) => {
8761            return Ok((vec![step(StepKind::Continue)], 1));
8762        }
8763        Some(KEYWORD_IF) => {
8764            if let Some((kind, used)) = parse_if_at(toks, pos, stmt, ctx)? {
8765                return Ok((vec![step(kind)], used));
8766            }
8767        }
8768        Some(KEYWORD_SWITCH) => {
8769            if let Some((kind, used)) = parse_switch_at(toks, pos, stmt, ctx)? {
8770                return Ok((vec![step(kind)], used));
8771            }
8772        }
8773        Some(KEYWORD_FOR) => {
8774            if let Some((kind, used)) = parse_for_at(toks, pos, stmt, ctx)? {
8775                return Ok((vec![step(kind)], used));
8776            }
8777        }
8778        Some(KEYWORD_WHILE) => {
8779            if let Some((kind, used)) = parse_while_single(toks, pos, stmt, ctx)? {
8780                return Ok((vec![step(kind)], used));
8781            }
8782        }
8783        Some(KEYWORD_FUNC) => {
8784            if let Some((kind, used)) = parse_func_at(toks, pos, stmt, ctx, false)? {
8785                return Ok((vec![step(kind)], used));
8786            }
8787        }
8788        Some(KEYWORD_REMOTE) => {
8789            if let Some((kind, used)) = parse_remote_single(toks, pos, stmt, ctx)? {
8790                return Ok((vec![step(kind)], used));
8791            }
8792        }
8793        _ => {}
8794    }
8795    // Wrappers (block or single); shape misses fall to generic.
8796    match head_word.as_deref() {
8797        Some(KEYWORD_WITH_IO) => {
8798            return parse_with_io_element(toks, pos, stmt, ctx, first_guard);
8799        }
8800        Some(KEYWORD_TIMEOUT) => {
8801            if let Some((kind, used)) = parse_timeout_single(toks, pos, stmt, ctx)? {
8802                return Ok((vec![step(kind)], used));
8803            }
8804        }
8805        Some(KEYWORD_ISOLATED) => {
8806            if let Some((kind, used)) = parse_isolated_single(toks, pos, stmt, ctx)? {
8807                return Ok((vec![step(kind)], used));
8808            }
8809        }
8810        Some(KEYWORD_FAIL) => {
8811            if let Some((kind, used)) = parse_fail_single(toks, pos, stmt, ctx)? {
8812                return Ok((vec![step(kind)], used));
8813            }
8814        }
8815        Some(KEYWORD_ASYNC) => {
8816            // ASYNC FUNC definition form: prefix, parser records is_async
8817            // with no type-constraint validation (checker owns HANDLE rule).
8818            if matches!(toks.get(pos + 1).map(|t| &t.kind), Some(TokKind::Word(w)) if w == KEYWORD_FUNC)
8819                && let Some((kind, used)) = parse_func_at(toks, pos + 1, stmt, ctx, true)?
8820            {
8821                return Ok((vec![step(kind)], 1 + used));
8822            }
8823            if let Some((kind, used)) = parse_async_single(toks, pos, stmt, ctx)? {
8824                return Ok((vec![step(kind)], used));
8825            }
8826        }
8827        _ => {}
8828    }
8829    // AWAIT/CANCEL statements (element level admits the `$` gap,
8830    // probed); heads without `$` go generic (lowering fails the
8831    // rest).
8832    if matches!(
8833        head_word.as_deref(),
8834        Some(KEYWORD_AWAIT) | Some(KEYWORD_CANCEL)
8835    ) && let Some((kind, used)) = parse_await_cancel_at(toks, pos, stmt, false, ctx)?
8836    {
8837        return Ok((vec![step(kind)], used));
8838    }
8839    // `INHERIT_ENV [...]` parses strictly even at element level
8840    // (keys stay exact everywhere; slice 5 adds only the
8841    // prelude-order validation). Shape misses go generic.
8842    if head_word.as_deref() == Some(KEYWORD_INHERIT_ENV)
8843        && let Some((kind, used)) = parse_inherit_env_at(toks, pos, stmt)?
8844    {
8845        return Ok((vec![step(kind)], used));
8846    }
8847    // `EXPORT ...` records names (zero steps) or misses to generic;
8848    // level, guard, and sigil violations fail loudly like the backend.
8849    if head_word.as_deref() == Some(KEYWORD_EXPORT) {
8850        if in_block {
8851            return Err(TokenError {
8852                diagnostic: None,
8853                hint: None,
8854                stmt,
8855                msg: format!("{KEYWORD_EXPORT} is only allowed at the top level"),
8856                line: 0,
8857                col: 0,
8858                kind: None,
8859            });
8860        }
8861        if first_guard.is_some() {
8862            return Err(TokenError {
8863                diagnostic: None,
8864                hint: None,
8865                stmt,
8866                msg: format!("{KEYWORD_EXPORT} cannot be guarded"),
8867                line: 0,
8868                col: 0,
8869                kind: None,
8870            });
8871        }
8872        if let Some((
8873            ExportNames {
8874                func_names,
8875                type_names,
8876                const_names,
8877            },
8878            used,
8879        )) = parse_export_at(toks, pos, stmt)?
8880        {
8881            for name in &func_names {
8882                for part in name.split(MODULE_SEPARATOR) {
8883                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8884                        .map_err(|e| lower_err(stmt, e))?;
8885                }
8886                // Recording and the duplicate rule live in
8887                // `Exports::insert` (single owner); this loop only
8888                // validates identifier shapes.
8889                if let Err(msg) = ctx
8890                    .exports
8891                    .borrow_mut()
8892                    .insert(ExportKind::Func, name.clone())
8893                {
8894                    return Err(TokenError {
8895                        diagnostic: None,
8896                        hint: None,
8897                        stmt,
8898                        msg,
8899                        line: 0,
8900                        col: 0,
8901                        kind: Some(ParseErrorKind::Validation {
8902                            command: KEYWORD_EXPORT.to_string(),
8903                        }),
8904                    });
8905                }
8906            }
8907            for name in &type_names {
8908                for part in name.split(MODULE_SEPARATOR) {
8909                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8910                        .map_err(|e| lower_err(stmt, e))?;
8911                }
8912                if let Err(msg) = ctx
8913                    .exports
8914                    .borrow_mut()
8915                    .insert(ExportKind::Type, name.clone())
8916                {
8917                    return Err(TokenError {
8918                        diagnostic: None,
8919                        hint: None,
8920                        stmt,
8921                        msg,
8922                        line: 0,
8923                        col: 0,
8924                        kind: Some(ParseErrorKind::Validation {
8925                            command: KEYWORD_EXPORT.to_string(),
8926                        }),
8927                    });
8928                }
8929            }
8930            for name in &const_names {
8931                for part in name.split(MODULE_SEPARATOR) {
8932                    crate::resolve::check_func_ident(&lowering_ctx(stmt), part)
8933                        .map_err(|e| lower_err(stmt, e))?;
8934                }
8935                if let Err(msg) = ctx
8936                    .exports
8937                    .borrow_mut()
8938                    .insert(ExportKind::Const, name.clone())
8939                {
8940                    return Err(TokenError {
8941                        diagnostic: None,
8942                        hint: None,
8943                        stmt,
8944                        msg,
8945                        line: 0,
8946                        col: 0,
8947                        kind: Some(ParseErrorKind::Validation {
8948                            command: KEYWORD_EXPORT.to_string(),
8949                        }),
8950                    });
8951                }
8952            }
8953            return Ok((Vec::new(), used));
8954        }
8955    }
8956    // `TYPE NAME = SHAPE` aliases (zero or one step); level and guard
8957    // violations fail loudly, shape misses fall to generic.
8958    if head_word.as_deref() == Some(KEYWORD_TYPE) {
8959        if in_block {
8960            return Err(TokenError {
8961                diagnostic: None,
8962                hint: None,
8963                stmt,
8964                msg: format!("{KEYWORD_TYPE} must appear at top level"),
8965                line: 0,
8966                col: 0,
8967                kind: None,
8968            });
8969        }
8970        if first_guard.is_some() {
8971            return Err(TokenError {
8972                diagnostic: None,
8973                hint: None,
8974                stmt,
8975                msg: format!("{KEYWORD_TYPE} cannot be guarded"),
8976                line: 0,
8977                col: 0,
8978                kind: None,
8979            });
8980        }
8981        if let Some((kind, used)) = parse_type_stmt_at(toks, pos, stmt)? {
8982            return Ok((vec![step(kind)], used));
8983        }
8984    }
8985    // Lowercase heads name their uppercase form (the grammar's
8986    // `command_name` mismatch): never a bare unknown-command.
8987    if let Some(head) = head_word.as_deref()
8988        && head.chars().all(|c| c.is_ascii_lowercase())
8989        && let upper = head.to_ascii_uppercase()
8990        && (is_known_command(&upper) || crate::STRUCTURAL_KEYWORDS.contains(&upper.as_str()))
8991    {
8992        return Err(TokenError {
8993            diagnostic: None,
8994            hint: None,
8995            stmt,
8996            msg: format!("command must be uppercase: found `{head}`, expected `{upper}`"),
8997            line: 0,
8998            col: 0,
8999            kind: Some(ParseErrorKind::Syntax),
9000        });
9001    }
9002    // RUN-exec ends mid-run (trailing loops on, probed); generic
9003    // instructions consume everything.
9004    let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
9005    Ok((vec![step(kind)], used))
9006}
9007
9008/// Element-level `WITH_IO`: a same-run brace (any gap: `]{` works,
9009/// probed) opens the io-block form, wrapping every inner step with
9010/// scope markers; a joint non-brace follower is the pending-guard
9011/// error (the splitter only holds bare brackets); anything else is
9012/// the single form. Shape misses go generic.
9013fn parse_with_io_element(
9014    toks: &[Tok],
9015    pos: usize,
9016    stmt: usize,
9017    ctx: &ParseCtx,
9018    first_guard: Option<GuardExpr>,
9019) -> Result<(Vec<Step>, usize), TokenError> {
9020    // The bracket rides gapped (`sep`); anything else misses the
9021    // shape and generic fails it in lowering.
9022    let bracket = match toks.get(pos + 1) {
9023        Some(t)
9024            if !t.joint
9025                && matches!(
9026                    &t.kind,
9027                    TokKind::Group {
9028                        delim: GroupDelim::Bracket,
9029                        ..
9030                    }
9031                ) =>
9032        {
9033            Some(t)
9034        }
9035        _ => None,
9036    };
9037    let Some(bracket) = bracket else {
9038        // Shape miss: generic fails it in lowering.
9039        let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
9040        return Ok((
9041            vec![Step {
9042                guard: first_guard,
9043                kind,
9044                scope_enter: 0,
9045                scope_exit: 0,
9046                line: 0,
9047                col: 0,
9048            }],
9049            used,
9050        ));
9051    };
9052    let inner = match &bracket.kind {
9053        TokKind::Group { inner, .. } => inner.clone(),
9054        _ => unreachable!(),
9055    };
9056    let bindings = match parse_io_bindings(&inner, stmt, ctx)? {
9057        Some(bindings) => bindings,
9058        // Shape miss: generic fails it.
9059        None => {
9060            let (kind, used) = parse_inner_command(&toks[pos..], stmt, ctx)?;
9061            return Ok((
9062                vec![Step {
9063                    guard: first_guard,
9064                    kind,
9065                    scope_enter: 0,
9066                    scope_exit: 0,
9067                    line: 0,
9068                    col: 0,
9069                }],
9070                used,
9071            ));
9072        }
9073    };
9074    let rest = pos + 2;
9075    // Same-run brace opens the io-block form (block-expanded
9076    // bindings skip the tty checks: the runtime repeats them).
9077    if let Some(next) = toks.get(rest)
9078        && matches!(
9079            &next.kind,
9080            TokKind::Group {
9081                delim: GroupDelim::Brace,
9082                ..
9083            }
9084        )
9085        && !is_template_brace(next)
9086    {
9087        let brace_inner = match &next.kind {
9088            TokKind::Group { inner, .. } => inner.clone(),
9089            _ => unreachable!(),
9090        };
9091        let mut steps = parse_body_steps(&brace_inner, stmt, ctx, false)?;
9092        if steps.is_empty() {
9093            return Err(TokenError {
9094                diagnostic: None,
9095                hint: None,
9096                stmt,
9097                msg: format!("{KEYWORD_WITH_IO} block must contain at least one command"),
9098                line: 0,
9099                col: 0,
9100                kind: None,
9101            });
9102        }
9103        // Every inner step wraps (merging when already wrapped,
9104        // like nested io scopes); the line guard folds into each
9105        // inner guard, inner-first (probed fold order).
9106        for s in &mut steps {
9107            let merged = match std::mem::replace(&mut s.kind, StepKind::Continue) {
9108                StepKind::WithIo {
9109                    bindings: inner_bindings,
9110                    cmd,
9111                } => StepKind::WithIo {
9112                    bindings: crate::commands::merge_bindings(&bindings, &inner_bindings),
9113                    cmd,
9114                },
9115                other => StepKind::WithIo {
9116                    bindings: bindings.clone(),
9117                    cmd: Box::new(other),
9118                },
9119            };
9120            s.kind = merged;
9121            s.guard = crate::commands::and_guard_exprs(s.guard.take(), first_guard.clone());
9122        }
9123        let span = lowering_ctx(stmt);
9124        for s in &steps {
9125            crate::commands::reject_nested_inherit_env(&span, &s.kind)
9126                .map_err(|e| lower_err(stmt, e))?;
9127        }
9128        if let Some(first) = steps.first_mut() {
9129            first.scope_enter += 1;
9130        }
9131        if let Some(last) = steps.last_mut() {
9132            last.scope_exit += 1;
9133        }
9134        return Ok((steps, rest + 1 - pos));
9135    }
9136    if rest >= toks.len() {
9137        // Unreachable: the splitter holds bare brackets for `{`.
9138        // Kept for body-parsed runs, mirroring the transient node.
9139        return Ok((
9140            vec![Step {
9141                guard: first_guard,
9142                kind: StepKind::WithIoBlock { bindings },
9143                scope_enter: 0,
9144                scope_exit: 0,
9145                line: 0,
9146                col: 0,
9147            }],
9148            2,
9149        ));
9150    }
9151    // A joint follower misses the inner `sep`: the pending wait
9152    // fails exactly like the grammar.
9153    if toks[rest].joint {
9154        return Err(TokenError {
9155            diagnostic: None,
9156            hint: None,
9157            stmt,
9158            msg: format!("{KEYWORD_WITH_IO} block must be followed by '{{'"),
9159            line: 0,
9160            col: 0,
9161            kind: None,
9162        });
9163    }
9164    // Single form, shared with single-inner (element guards the step).
9165    let (cmd, used) = parse_single_inner(
9166        toks,
9167        rest,
9168        stmt,
9169        ctx,
9170        InnerRules {
9171            allow_await: false,
9172            allow_with_io: true,
9173        },
9174    )?;
9175    let span = lowering_ctx(stmt);
9176    check_tty_wrapping(&bindings, Some(&cmd), &span).map_err(|e| lower_err(stmt, e))?;
9177    let kind = StepKind::WithIo {
9178        bindings,
9179        cmd: Box::new(cmd),
9180    };
9181    crate::commands::reject_nested_inherit_env(&span, &kind).map_err(|e| lower_err(stmt, e))?;
9182    Ok((
9183        vec![Step {
9184            guard: first_guard,
9185            kind,
9186            scope_enter: 0,
9187            scope_exit: 0,
9188            line: 0,
9189            col: 0,
9190        }],
9191        2 + used,
9192    ))
9193}
9194
9195/// Shared inner-command parser: statement calls (joint paren, even on
9196/// known commands), RUN exec
9197/// form, and generic instructions. Returns the kind and tokens
9198/// consumed: calls and RUN-exec end mid-run (the caller continues
9199/// past them, like the grammar's `element*`); generic instructions
9200/// consume everything. Wrappers never route here (element and
9201/// single-inner dispatch own them); slice 4b reuses the call/RUN
9202/// arms for trailing elements.
9203fn parse_inner_command(
9204    body: &[Tok],
9205    stmt: usize,
9206    ctx: &ParseCtx,
9207) -> Result<(StepKind, usize), TokenError> {
9208    // Bare `NAME(...)` calls invoke functions with one syntax; the head
9209    // and `(` ride gapless or the shape stays an instruction (which
9210    // fails later as UnknownCommand), exactly like the grammar.
9211    if let Some((call_name, paren)) = call_shape_at(body, 0, true) {
9212        let inner = match &body[paren].kind {
9213            TokKind::Group { inner, .. } => inner.clone(),
9214            _ => unreachable!(),
9215        };
9216        let args = parse_call_args(&inner, stmt, ctx)?;
9217        // Statement-level `INSPECT(...)` resolves like any other call
9218        // (only expression position mints the node); unknown functions
9219        // fail in the shared resolver with identical messages.
9220        if !call_name.contains(MODULE_SEPARATOR) {
9221            crate::resolve::check_func_ident(&lowering_ctx(stmt), &call_name)
9222                .map_err(|e| lower_err(stmt, e))?;
9223        }
9224        let qualified = resolve_name(ctx, stmt, &call_name)?;
9225        return Ok((
9226            StepKind::Call {
9227                name: qualified,
9228                args,
9229            },
9230            paren + 1,
9231        ));
9232    }
9233    let head = match body.first().map(|t| &t.kind) {
9234        Some(TokKind::Word(n)) => n.clone(),
9235        _ => {
9236            return Err(TokenError {
9237                diagnostic: None,
9238                hint: None,
9239                stmt,
9240                msg: "statement must open with a command word".to_string(),
9241                line: 0,
9242                col: 0,
9243                kind: None,
9244            });
9245        }
9246    };
9247    // RUN exec form: the list routes structured through `lower` (the
9248    // mock wraps it in `Run`; production maps it to `RunExec`); the
9249    // caller continues past the list, like the grammar. The list
9250    // rides gapped (`sep`): a joint bracket is a hard error, never
9251    // a spliced arg (probed `RUN["a"]`).
9252    if head == KEYWORD_RUN
9253        && matches!(
9254            body.get(1).map(|t| &t.kind),
9255            Some(TokKind::Group {
9256                delim: GroupDelim::Bracket,
9257                ..
9258            })
9259        )
9260    {
9261        if body[1].joint {
9262            return Err(TokenError {
9263                diagnostic: None,
9264                hint: None,
9265                stmt,
9266                msg: format!("{KEYWORD_RUN} [...] requires a gap after {KEYWORD_RUN}"),
9267                line: 0,
9268                col: 0,
9269                kind: None,
9270            });
9271        }
9272        let inner = match &body[1].kind {
9273            TokKind::Group { inner, .. } => inner.clone(),
9274            _ => unreachable!(),
9275        };
9276        // Non-map blocks miss the exec shape (the grammar has no
9277        // `block` alternative here); fall through to the shell path
9278        // below, which reads the bracket literally.
9279        if let Some(list) = parse_run_exec_list(&inner, stmt, ctx)? {
9280            let kind =
9281                (ctx.lower)(KEYWORD_RUN, vec![Arg::Expr(list)]).map_err(|e| lower_err(stmt, e))?;
9282            return Ok((kind, 2));
9283        }
9284    }
9285    let (tokens, deferred) = build_arg_tokens(&body[1..], stmt, ctx)?;
9286    let lowered = lower_generic_args(&head, tokens, stmt, ctx);
9287    match lowered {
9288        Ok(kind) => {
9289            // Stashed call errors surface only for otherwise well-formed
9290            // statements: the command head owns its syntax, so a malformed
9291            // header keeps its tailored error instead of being masked by an
9292            // argument-position resolution failure.
9293            if let Some(err) = deferred {
9294                return Err(err);
9295            }
9296            Ok((kind, body.len()))
9297        }
9298        Err(lower_err) => {
9299            // Fallback raw strings (`NOPE()` rendered as text) can fail
9300            // argument-shape lowering with a misleading error. The
9301            // stashed unknown-callee error names the real culprit, so
9302            // it wins over every argument-level failure (`Validation`,
9303            // `Syntax`, `InvalidSyntax`, or the `None` classification
9304            // that `ENV`/`EXPAND` lowering uses). Heads owned by a
9305            // statement-header parser (`FUNC`, `LET`, `IF`, `FOR`,
9306            // `WHILE`, `TYPE`, `IMPORT`, `EXPORT`, `REMOTE`, `WITH_IO`)
9307            // keep their lowering `InvalidSyntax`: those parsers miss to
9308            // this path on shape miss (e.g. `FUNC FOO() ECHO hi` has no
9309            // body block), so the lowering error names the malformed
9310            // header while the stashed name is its definiendum, never an
9311            // argument-position call. Every other head is a plain
9312            // command, so a lowering `InvalidSyntax` there is an
9313            // argument-shape failure from the raw-text fallback, and
9314            // the stashed callee names the culprit. Only
9315            // head-identity errors (`UnknownCommand`, `Structural`)
9316            // keep their tailored diagnostic everywhere.
9317            let is_header_syntax = matches!(
9318                head.as_str(),
9319                KEYWORD_FUNC
9320                    | KEYWORD_LET
9321                    | KEYWORD_CONST
9322                    | KEYWORD_IF
9323                    | KEYWORD_SWITCH
9324                    | KEYWORD_FOR
9325                    | KEYWORD_WHILE
9326                    | KEYWORD_TYPE
9327                    | KEYWORD_IMPORT
9328                    | KEYWORD_EXPORT
9329                    | KEYWORD_REMOTE
9330                    | KEYWORD_WITH_IO
9331            ) && matches!(
9332                lower_err.kind,
9333                Some(crate::error::ParseErrorKind::InvalidSyntax { .. })
9334            );
9335            if let Some(deferred_err) = deferred
9336                && !is_header_syntax
9337                && matches!(
9338                    lower_err.kind,
9339                    Some(crate::error::ParseErrorKind::Validation { .. })
9340                        | Some(crate::error::ParseErrorKind::Syntax)
9341                        | Some(crate::error::ParseErrorKind::InvalidSyntax { .. })
9342                        | None
9343                )
9344            {
9345                return Err(deferred_err);
9346            }
9347            Err(lower_err)
9348        }
9349    }
9350}
9351
9352/// Parse a token stream (either lexer) into steps. Markers normalize to
9353/// 0/0 like the fuzz harness; scopes arrive with block slices.
9354pub fn parse_tokens(
9355    toks: &[Tok],
9356    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9357) -> Result<Vec<Step>, TokenError> {
9358    let modules = ModuleTable::default();
9359    let reserved = HashSet::new();
9360    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
9361    parse_tokens_with_ctx(toks, &ctx)
9362}
9363
9364/// Parse with an explicit context (module table for call resolution).
9365/// `parse_tokens` uses empty modules.
9366pub fn parse_tokens_with_ctx(toks: &[Tok], ctx: &ParseCtx) -> Result<Vec<Step>, TokenError> {
9367    let mut out = Vec::new();
9368    *ctx.current_line.borrow_mut() = 1;
9369    let stmts = split_statements(toks, 1)?;
9370    predeclare_forward_funcs(&stmts, ctx);
9371    for (i, s) in stmts.iter().enumerate() {
9372        *ctx.current_line.borrow_mut() = s.line;
9373        out.extend(
9374            lower_stmt_steps(s, i, ctx, false, true).map_err(|e| stamp_pos(e, s.line, s.col))?,
9375        );
9376    }
9377    // Whole-script validations through the shared validators.
9378    // `INHERIT_ENV` prelude order: only leading positions read.
9379    {
9380        let mut seen_non_prelude = false;
9381        for step in &out {
9382            match &step.kind {
9383                StepKind::InheritEnv { .. } => {
9384                    if seen_non_prelude {
9385                        return Err(TokenError {
9386                            diagnostic: None,
9387                            hint: None,
9388                            stmt: out.len(),
9389                            msg: format!(
9390                                "{KEYWORD_INHERIT_ENV} must appear before any other commands"
9391                            ),
9392                            line: 0,
9393                            col: 0,
9394                            kind: None,
9395                        });
9396                    }
9397                }
9398                kind => {
9399                    if crate::commands::contains_inherit_env(kind) {
9400                        return Err(TokenError {
9401                            diagnostic: None,
9402                            hint: None,
9403                            stmt: out.len(),
9404                            msg: format!(
9405                                "{KEYWORD_INHERIT_ENV} cannot be nested inside other commands"
9406                            ),
9407                            line: 0,
9408                            col: 0,
9409                            kind: None,
9410                        });
9411                    }
9412                    // Harvest imports stay prelude: they bind functions
9413                    // and types without executing module bodies, so they
9414                    // neither read nor disturb the inherited environment.
9415                    // File imports execute arbitrary top-level steps on
9416                    // import, so they end the prelude like any other
9417                    // side-effecting command. Host-only IMPORTs emit no
9418                    // step at all, which is why they never tripped this
9419                    // gate.
9420                    if !matches!(kind, StepKind::ImportFuncs { .. }) {
9421                        seen_non_prelude = true;
9422                    }
9423                }
9424            }
9425        }
9426    }
9427    crate::commands::validate_remote_copy_placement(&out, &lowering_ctx(out.len()))
9428        .map_err(|e| lower_err(out.len(), e))?;
9429    {
9430        let top: HashSet<String> = ctx.funcs.borrow().first().cloned().unwrap_or_default();
9431        let top_imports: Vec<String> = ctx
9432            .imports
9433            .borrow()
9434            .first()
9435            .cloned()
9436            .unwrap_or_default()
9437            .into_iter()
9438            .map(|(name, _)| name)
9439            .collect();
9440        let mut top_types = HashSet::new();
9441        let mut top_consts = HashSet::new();
9442        for step in &out {
9443            if let StepKind::TypeAlias { name, .. } = &step.kind {
9444                top_types.insert(name.clone());
9445            }
9446            match &step.kind {
9447                StepKind::Bind { var, is_const, .. } if *is_const => {
9448                    top_consts.insert(var.clone());
9449                }
9450                _ => {}
9451            }
9452        }
9453        crate::commands::validate_exports(
9454            &lowering_ctx(out.len()),
9455            &ctx.exports.borrow(),
9456            &top,
9457            &top_types,
9458            &top_consts,
9459            ctx.modules,
9460            &top_imports,
9461        )
9462        .map_err(|e| lower_err(out.len(), e))?;
9463    }
9464    Ok(out)
9465}
9466
9467// ---- String entry points: lex, lower, collect exports and docs ----
9468
9469/// Source text of a 1-based line. The line just past a trailing
9470/// newline (where unbalanced groups report) reads as empty text so
9471/// caret blocks still render.
9472fn source_line_of(input: &str, line: usize) -> Option<String> {
9473    let count = input.lines().count();
9474    let idx = line.checked_sub(1)?;
9475    if idx < count {
9476        input.lines().nth(idx).map(str::to_string)
9477    } else if idx == count {
9478        Some(String::new())
9479    } else {
9480        None
9481    }
9482}
9483
9484/// Last script line (end-of-script validations blame it).
9485fn last_line(input: &str) -> usize {
9486    input.lines().count().max(1)
9487}
9488
9489/// Convert a lexer failure: low-level syntax kind, exact lexer
9490/// position, and the source line for the caret block. Unclosed groups
9491/// name their opener (no grammar dumps); the closer expectation rides
9492/// along so `expected()` stays informative. A lexer-known kind (an
9493/// unclosed `WITH_IO` bracket) converts verbatim.
9494fn lex_error(input: &str, e: LexError) -> ParseError {
9495    let line = e.line.max(1);
9496    let ctx = match source_line_of(input, line) {
9497        Some(source_line) => SpanContext::full(line, e.col.max(1), e.col.max(1), source_line),
9498        None => SpanContext::line_only(line),
9499    };
9500    if let Some(ParseErrorKind::InvalidSyntax { command }) = e.kind {
9501        // Lexer-known command syntax (an unclosed `WITH_IO` bracket).
9502        return ParseError::invalid_syntax(
9503            &command,
9504            e.msg,
9505            None,
9506            vec!["`]`".to_string()],
9507            None,
9508            &ctx,
9509        );
9510    }
9511    let expected = if e.msg.starts_with("unclosed") {
9512        vec!["`}`".to_string()]
9513    } else {
9514        Vec::new()
9515    };
9516    ParseError::syntax(e.msg, expected, None, &ctx)
9517}
9518
9519/// Convert a backend failure, preserving the dispatcher's error kind
9520/// and completing line/source context the token stream knows. Spans
9521/// open at the statement's start column and cover its whole first line
9522/// (multi-line spans clamp to the start line), so caret blocks render
9523/// for every string-path error.
9524fn token_error(input: &str, e: TokenError) -> ParseError {
9525    let line = if e.line == 0 {
9526        last_line(input)
9527    } else {
9528        e.line
9529    };
9530    let start_col = e.col.max(1);
9531    let ctx = match source_line_of(input, line) {
9532        Some(source_line) => {
9533            let end = source_line.len().max(start_col);
9534            SpanContext::full(line, start_col, end, source_line)
9535        }
9536        None => SpanContext::line_only(line),
9537    };
9538    // Column spans are statement granularity (every error names its
9539    // statement's first column); the caret block still renders.
9540    // A carried diagnostic reattaches verbatim (key and fields
9541    // survive); only parser-native errors rewrap from the message
9542    // string as before. A carried hint reattaches alongside, so
9543    // `hint()` survives the round trip on every path.
9544    if let Some(diagnostic) = e.diagnostic {
9545        let kind = e.kind.unwrap_or(ParseErrorKind::Structural {
9546            rule: "statement".to_string(),
9547        });
9548        return ParseError::from_diagnostic(kind, *diagnostic, &ctx).with_hint(e.hint);
9549    }
9550    let hint = e.hint;
9551    match e.kind {
9552        Some(crate::error::ParseErrorKind::UnknownCommand { name }) => {
9553            ParseError::unknown_command(&name, e.msg, hint, &ctx)
9554        }
9555        Some(crate::error::ParseErrorKind::InvalidSyntax { command }) => {
9556            ParseError::invalid_syntax(&command, e.msg, None, Vec::new(), hint, &ctx)
9557        }
9558        Some(crate::error::ParseErrorKind::Validation { command }) => {
9559            ParseError::validation(&command, e.msg, &ctx)
9560        }
9561        Some(crate::error::ParseErrorKind::Syntax) => {
9562            ParseError::syntax(e.msg, Vec::new(), hint, &ctx)
9563        }
9564        Some(crate::error::ParseErrorKind::Structural { rule }) => {
9565            ParseError::structural(&rule, e.msg, &ctx)
9566        }
9567        None => ParseError::structural("statement", e.msg, &ctx),
9568    }
9569}
9570
9571/// Shared parse driver: lex, lower with preseeded frames, and collect
9572/// `EXPORT` names (validated at end of parse, forward references
9573/// allowed).
9574fn parse_with_ctx(
9575    input: &str,
9576    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9577    reserved_names: HashSet<String>,
9578    modules: ModuleTable,
9579    preseed_funcs: HashSet<String>,
9580    preseed_imports: Vec<String>,
9581) -> ParseResult<ScriptWithExports> {
9582    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
9583    let ctx = ParseCtx::empty(&lower, &modules, &reserved_names);
9584    // Snippet re-parses seed their base frames so lookup behaves
9585    // identically; snippets never define, only read.
9586    ctx.funcs.borrow_mut()[0].extend(preseed_funcs);
9587    ctx.imports.borrow_mut()[0].extend(preseed_imports.into_iter().map(|name| (name, false)));
9588    let steps = parse_tokens_with_ctx(&toks, &ctx).map_err(|e| token_error(input, e))?;
9589    let mut steps = steps;
9590    stamp_func_docs(input, &mut steps);
9591    Ok(ScriptWithExports {
9592        steps,
9593        exports: ctx.exports.borrow().clone(),
9594    })
9595}
9596
9597/// Steps plus single-file `EXPORT` metadata, before `#` doc stamping.
9598/// Callers needing docs build a [`ParsedScript`] from this.
9599struct ScriptWithExports {
9600    steps: Vec<Step>,
9601    exports: Exports,
9602}
9603
9604/// Parse a script with an unknown host environment.
9605pub fn parse_script(
9606    input: &str,
9607    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9608) -> ParseResult<Vec<Step>> {
9609    Ok(parse_with_ctx(
9610        input,
9611        lower,
9612        HashSet::new(),
9613        ModuleTable::default(),
9614        HashSet::new(),
9615        Vec::new(),
9616    )?
9617    .steps)
9618}
9619
9620/// Parse a snippet with an enclosing parse's visible scope state, so
9621/// re-parsed inner commands (async bodies) resolve calls identically.
9622/// The snippet never defines, only reads: seeds affect lookup alone.
9623pub fn parse_script_with_preseed(
9624    input: &str,
9625    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9626    reserved_names: HashSet<String>,
9627    modules: ModuleTable,
9628    preseed_funcs: HashSet<String>,
9629    preseed_imports: Vec<String>,
9630) -> ParseResult<Vec<Step>> {
9631    Ok(parse_with_ctx(
9632        input,
9633        lower,
9634        reserved_names,
9635        modules,
9636        preseed_funcs,
9637        preseed_imports,
9638    )?
9639    .steps)
9640}
9641
9642/// Parse with a module provenance table so calls resolve statically:
9643/// qualified `MODULE::NAME` checks membership, bare `NAME` resolves through
9644/// `SCRIPT` definitions and `IMPORT`ed modules, and anything else fails at
9645/// parse time instead of at runtime.
9646pub fn parse_script_with_modules(
9647    input: &str,
9648    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9649    reserved_names: HashSet<String>,
9650    modules: ModuleTable,
9651) -> ParseResult<Vec<Step>> {
9652    Ok(parse_script_with_modules_and_exports(input, lower, reserved_names, modules)?.steps)
9653}
9654
9655/// Parse with modules plus single-file `EXPORT` metadata and `#` doc
9656/// comments for top-level `FUNC`s. Used by the MCP host; the linear
9657/// runner keeps using `parse_script_with_modules` and ignores exports.
9658pub fn parse_script_with_modules_and_exports(
9659    input: &str,
9660    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9661    reserved_names: HashSet<String>,
9662    modules: ModuleTable,
9663) -> ParseResult<ParsedScript> {
9664    let ScriptWithExports { steps, exports } = parse_with_ctx(
9665        input,
9666        lower,
9667        reserved_names,
9668        modules,
9669        HashSet::new(),
9670        Vec::new(),
9671    )?;
9672    Ok(ParsedScript {
9673        func_docs: collect_func_docs(input, &steps),
9674        steps,
9675        exports,
9676    })
9677}
9678
9679/// Parse without modules plus `EXPORT` metadata. Used by tests and
9680/// tooling that lower with the shared mock.
9681pub fn parse_script_with_exports(
9682    input: &str,
9683    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
9684) -> ParseResult<ParsedScript> {
9685    let ScriptWithExports { steps, exports } = parse_with_ctx(
9686        input,
9687        lower,
9688        HashSet::new(),
9689        ModuleTable::default(),
9690        HashSet::new(),
9691        Vec::new(),
9692    )?;
9693    Ok(ParsedScript {
9694        func_docs: collect_func_docs(input, &steps),
9695        steps,
9696        exports,
9697    })
9698}
9699
9700/// Parse one expression from source text with an empty module scope, for
9701/// tooling that shows lowering without running (docs demos, explain output).
9702/// No imports exist here, so bare function calls fail and qualified calls
9703/// fail against the empty table; only `INSPECT` passes through untouched.
9704/// Arithmetic, comparison, variables, env reads, keypaths, and literals
9705/// lower normally, with literal only subtrees folded before flattening.
9706pub fn parse_expression_str(input: &str) -> ParseResult<Expr> {
9707    // Trailing whitespace lexes unconsumed, so lex the trimmed text:
9708    // otherwise padded but valid input fails the full consumption check.
9709    let trimmed = input.trim();
9710    let toks = lex_str(trimmed).map_err(|e| lex_error(trimmed, e))?;
9711    let modules = ModuleTable::default();
9712    let reserved = HashSet::new();
9713    let lower = crate::commands::lower_command as fn(&str, Vec<Arg>) -> ParseResult<StepKind>;
9714    let ctx = ParseCtx::empty(&lower, &modules, &reserved);
9715    *ctx.current_line.borrow_mut() = 1;
9716    parse_single_expr(&toks, 0, &ctx).map_err(|e| token_error(trimmed, e))
9717}
9718
9719/// Parse one guard expression from source text (a bare `guard_seq`:
9720/// predicates, `not`/`any`/`all`, comma lists), for tooling and tests.
9721pub fn parse_guard_expr_str(input: &str) -> ParseResult<GuardExpr> {
9722    let toks = lex_str(input).map_err(|e| lex_error(input, e))?;
9723    parse_single_guard(&toks, 0).map_err(|e| token_error(input, e))
9724}
9725
9726/// Parsed script with single-file `EXPORT` metadata. `steps` is the
9727/// linear execution plan, `exports` the `EXPORT` names in source order
9728/// per kind, and `func_docs` maps top-level `FUNC` base names to
9729/// (summary, docs) collected from the immediately preceding `#`
9730/// comment block.
9731#[derive(Debug, Clone, Default)]
9732pub struct ParsedScript {
9733    pub steps: Vec<Step>,
9734    pub exports: Exports,
9735    pub func_docs: std::collections::HashMap<String, (String, String)>,
9736}
9737
9738/// One `EXPORT` list kind. Single owner for the func/type/const
9739/// distinction, so the duplicate rule and every holder never restate
9740/// the three-way split.
9741#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9742pub enum ExportKind {
9743    Func,
9744    Type,
9745    Const,
9746}
9747
9748/// Single-file `EXPORT` metadata: per-kind names in source order.
9749/// Separate lists (never one mixed vec) so the MCP server never
9750/// confuses a type for a tool, and reads stay kind-addressed.
9751#[derive(Debug, Clone, Default)]
9752pub struct Exports {
9753    pub funcs: Vec<String>,
9754    pub types: Vec<String>,
9755    pub consts: Vec<String>,
9756}
9757
9758impl Exports {
9759    /// Record one `EXPORT` name, enforcing the duplicate rule.
9760    /// Uniqueness is by exported base name for every kind: `EXPORT FOO`
9761    /// and `EXPORT LIB::FOO` name one servable tool, `EXPORT CONST $N`
9762    /// and `EXPORT CONST $A::N` name one read, so the second spelling
9763    /// shapes the same `duplicate EXPORT` instead of silently
9764    /// shadowing. One base name rides exactly one export kind.
9765    /// `Err` carries the `duplicate EXPORT` message unchanged.
9766    pub fn insert(&mut self, kind: ExportKind, name: String) -> Result<(), String> {
9767        let base = crate::base_name(&name);
9768        let clash = [&self.funcs, &self.types, &self.consts]
9769            .iter()
9770            .any(|list| list.iter().any(|e| crate::base_name(e) == base));
9771        if clash {
9772            return Err(format!("duplicate {KEYWORD_EXPORT} `{name}`"));
9773        }
9774        match kind {
9775            ExportKind::Func => self.funcs.push(name),
9776            ExportKind::Type => self.types.push(name),
9777            ExportKind::Const => self.consts.push(name),
9778        }
9779        Ok(())
9780    }
9781}
9782
9783fn collect_func_docs(
9784    input: &str,
9785    steps: &[Step],
9786) -> std::collections::HashMap<String, (String, String)> {
9787    use std::collections::{HashMap, HashSet};
9788    let lines: Vec<&str> = input.lines().collect();
9789    // Top-level FUNC definition lines keyed by base name. Brace depth
9790    // tracks nesting so only depth-0 `FUNC` lines count; the first
9791    // occurrence wins because same-scope duplicates fail at lowering.
9792    let mut def_lines: HashMap<String, usize> = HashMap::new();
9793    let mut seen: HashSet<String> = HashSet::new();
9794    let mut depth: usize = 0;
9795    for (idx, line) in lines.iter().enumerate() {
9796        let trimmed = line.trim_start();
9797        let is_comment = trimmed.starts_with('#');
9798        let is_guard_only = trimmed.starts_with('[');
9799        if !is_comment
9800            && !is_guard_only
9801            && let Some(rest) = strip_func_head(trimmed)
9802            && depth == 0
9803            && !seen.contains(&rest)
9804        {
9805            seen.insert(rest.clone());
9806            def_lines.insert(rest, idx + 1);
9807        }
9808        if !is_comment {
9809            for ch in line.chars() {
9810                if ch == '{' {
9811                    depth = depth.saturating_add(1);
9812                } else if ch == '}' {
9813                    depth = depth.saturating_sub(1);
9814                }
9815            }
9816        }
9817    }
9818    let mut out: HashMap<String, (String, String)> = HashMap::new();
9819    for step in steps {
9820        if let StepKind::FuncDef { name, .. } = &step.kind
9821            && !out.contains_key(name)
9822            && let Some(&line_no) = def_lines.get(name)
9823            && let Some((summary, docs)) = docs_above(&lines, line_no)
9824        {
9825            out.insert(name.clone(), (summary, docs));
9826        }
9827    }
9828    out
9829}
9830
9831/// Stamp `#` doc blocks onto top-level `FUNC` steps, from the same map
9832/// that feeds `func_docs`, so step-carried docs and the sidecar can
9833/// never disagree. Only top-level definitions qualify (same rule as
9834/// collection); nested shadowing keeps `docs: None`.
9835fn stamp_func_docs(input: &str, steps: &mut [Step]) {
9836    let docs = collect_func_docs(input, steps);
9837    for step in steps {
9838        if let StepKind::FuncDef {
9839            name, docs: slot, ..
9840        } = &mut step.kind
9841            && slot.is_none()
9842            && let Some(pair) = docs.get(name)
9843        {
9844            *slot = Some(pair.clone());
9845        }
9846    }
9847}
9848
9849fn strip_func_head(trimmed: &str) -> Option<String> {
9850    let rest = trimmed.strip_prefix(KEYWORD_FUNC)?;
9851    let after = rest.strip_prefix([' ', '\t'])?;
9852    if after.is_empty() {
9853        return None;
9854    }
9855    let name: String = after
9856        .chars()
9857        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
9858        .collect();
9859    if name.is_empty()
9860        || !name
9861            .bytes()
9862            .all(|b| b.is_ascii_uppercase() || b == b'_' || b.is_ascii_digit())
9863    {
9864        return None;
9865    }
9866    if name.starts_with(|c: char| c.is_ascii_digit()) {
9867        return None;
9868    }
9869    Some(name)
9870}
9871
9872fn docs_above(lines: &[&str], line_no: usize) -> Option<(String, String)> {
9873    if line_no <= 1 {
9874        return None;
9875    }
9876    let mut block: Vec<String> = Vec::new();
9877    let mut idx = line_no - 1;
9878    while idx > 0 {
9879        idx -= 1;
9880        let trimmed = lines[idx].trim_start();
9881        if trimmed.is_empty() {
9882            break;
9883        }
9884        if let Some(body) = trimmed.strip_prefix('#') {
9885            let text = body.strip_prefix(' ').unwrap_or(body);
9886            block.push(text.to_string());
9887        } else {
9888            break;
9889        }
9890        if idx == 0 {
9891            break;
9892        }
9893    }
9894    if block.is_empty() {
9895        return None;
9896    }
9897    block.reverse();
9898    let summary = block.first().cloned().unwrap_or_default();
9899    let docs = block.join("\n");
9900    Some((summary, docs))
9901}
9902
9903#[cfg(test)]
9904mod tests {
9905    use super::*;
9906    use crate::test_lower_mock;
9907    use indoc::indoc;
9908
9909    fn lower(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
9910        test_lower_mock::lower(name, args)
9911    }
9912
9913    /// Lexer-agreement oracle: both frontends must deliver identical
9914    /// steps through the single backend. `parse_script` is the string
9915    /// entry point; `parse_tokens` runs each lexer's output directly.
9916    fn assert_parity(text: &str) {
9917        let old = crate::parse_script(text, lower)
9918            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9919        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9920        let new = parse_tokens(&toks, lower)
9921            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9922        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9923        #[cfg(feature = "proc-macro-api")]
9924        {
9925            let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
9926            let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
9927            let new = parse_tokens(&toks, lower).expect("token path must parse token script");
9928            assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
9929        }
9930    }
9931
9932    /// String-path-only oracle for shapes `rustc` cannot carry at all
9933    /// (lifetime-like quotes). The backend must still agree there.
9934    fn assert_parity_string_only(text: &str) {
9935        let old = crate::parse_script(text, lower)
9936            .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
9937        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
9938        let new = parse_tokens(&toks, lower)
9939            .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
9940        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
9941    }
9942
9943    #[test]
9944    fn token_and_string_paths_agree_on_wrappers() {
9945        // Single-command wrappers, io-blocks, await/cancel,
9946        // LET wrapper forms — three-way agreement per script.
9947        for text in [
9948            "WITH_IO [stdout=$p] ECHO hi",
9949            "WITH_IO [stdin=$p] ECHO hi",
9950            "WITH_IO [stdin] ECHO hi",
9951            "WITH_IO [stdout] ECHO hi",
9952            "WITH_IO [stdin=$p, stdout=$q] ECHO hi",
9953            "WITH_IO [stdin=$p, stdin=$q] ECHO hi",
9954            "WITH_IO [tty] RUN echo hi",
9955            "WITH_IO [tty, rows=40, cols=100] RUN echo hi",
9956            "WITH_IO [rows=40, cols=100, tty] RUN echo hi",
9957            "WITH_IO [stdin =$p] ECHO hi",
9958            "WITH_IO [stdin= $p] ECHO hi",
9959            "WITH_IO [ stdin=$p ] ECHO hi",
9960            "WITH_IO [\nstdin=$p\n] ECHO hi",
9961            "WITH_IO [stdin=$p\n, stdout=$q] ECHO hi",
9962            "WITH_IO [stdout=$p] ASYNC ECHO hi",
9963            "WITH_IO [stdin=$p] WITH_IO [stderr=$e] ECHO hi",
9964            "WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
9965            "WITH_IO [stdin=$p] ISOLATED ECHO hi",
9966            "WITH_IO [stdin=$p] CANCEL $t",
9967            "WITH_IO [stdin=$p] CANCEL $t ECHO bye",
9968            "WITH_IO [stdin=$p] { ECHO hi }",
9969            "WITH_IO [stdin=$p]\n{ ECHO hi }",
9970            "WITH_IO [stdin=$p]; { ECHO hi }",
9971            "WITH_IO [stdin=$p]{ ECHO hi }",
9972            "WITH_IO [stdin=$p] { ECHO a\nECHO b }",
9973            "WITH_IO [stdin=$p] { ECHO hi } ECHO bye",
9974            "WITH_IO [rows=40] { ECHO hi }",
9975            "WITH_IO [tty] { ECHO hi }",
9976            "WITH_IO [stdin=$p] { WITH_IO [stderr=$e] ECHO hi }",
9977            "TIMEOUT 10s ECHO hi",
9978            "TIMEOUT 10 ECHO hi",
9979            "TIMEOUT 500ms ECHO hi",
9980            "TIMEOUT 5m ECHO hi",
9981            "TIMEOUT 2h ECHO hi",
9982            "TIMEOUT $d ECHO hi",
9983            "TIMEOUT \"10s\" ECHO hi",
9984            "TIMEOUT \"30 s\" ECHO hi",
9985            "TIMEOUT {{ $d }} ECHO hi",
9986            "TIMEOUT 10s AWAIT $t",
9987            "TIMEOUT 10s CANCEL $t",
9988            "TIMEOUT 10s AWAIT $t ECHO bye",
9989            "TIMEOUT 10s CANCEL $t ECHO bye",
9990            "TIMEOUT 10s { ECHO hi }",
9991            "TIMEOUT 10s {\nECHO hi\n}",
9992            "TIMEOUT 10s { ECHO hi } ECHO bye",
9993            "TIMEOUT 10s { ECHO hi } TIMEOUT 5s ECHO bye",
9994            "TIMEOUT 10s TIMEOUT 5s ECHO hi",
9995            "TIMEOUT 10s { ECHO a\nECHO b }",
9996            "TIMEOUT 10s ECHO hi extra",
9997            "ISOLATED ECHO hi",
9998            "ISOLATED { ECHO hi }",
9999            "ISOLATED { ECHO hi } ECHO bye",
10000            "ISOLATED AWAIT $t",
10001            "ISOLATED INHERIT_ENV [M]",
10002            "ISOLATED { INHERIT_ENV [M] }",
10003            "ISOLATED { INHERIT_ENV [MODE]\nECHO hi }",
10004            "ASYNC ECHO hi",
10005            "ASYNC { ECHO hi }",
10006            "ASYNC{ECHO hi}",
10007            "ASYNC { ECHO a\nECHO b }",
10008            "ASYNC { ECHO hi } ECHO bye",
10009            "ASYNC CANCEL $t",
10010            "ASYNC CANCEL $t ECHO bye",
10011            "AWAIT $t",
10012            "AWAIT$t",
10013            "AWAIT $ t",
10014            "AWAIT $T",
10015            "AWAIT $t2",
10016            "AWAIT $_t",
10017            "CANCEL $t",
10018            "CANCEL$t",
10019            "CANCEL $ t",
10020            "AWAIT $t ECHO bye",
10021            "CANCEL $t ECHO bye",
10022            "AWAIT $t AWAIT $u",
10023            "AWAIT $t\nECHO bye",
10024            "LET $t: HANDLE = ASYNC ECHO hi",
10025            "LET $t: HANDLE = ASYNC { ECHO hi }",
10026            "LET $t: HANDLE = ASYNC { ECHO hi } ECHO bye",
10027            "LET $a: STRING = ASYNC ECHO hi",
10028            "LET $t: HANDLE = ASYNC { WITH_IO [stdin=$p] ECHO hi }",
10029            "LET $w: STRING = WITH_IO [stdin=$p] ASYNC ECHO hi",
10030            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC ECHO hi",
10031            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi }",
10032            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO hi } ECHO bye",
10033            "LET $x: STRING = WITH_IO [stdin=$p] ECHO hi",
10034            "LET $x: STRING = WITH_IO [stdin=$p] TIMEOUT 5s ECHO hi",
10035            "LET $x: STRING = TIMEOUT 10s ECHO hi",
10036            "LET $x: STRING = TIMEOUT 10s { ECHO hi }",
10037            "LET $x: STRING = TIMEOUT 10s ECHO hi ECHO bye",
10038            "LET $o: STRING = AWAIT $t",
10039            "LET $p: PIPE ECHO bye",
10040            "TIMEOUT 10s WITH_IO [stdin=$p]",
10041            "TIMEOUT 10s WITH_IO [stdin=$p]ECHO hi",
10042            "ISOLATED INHERIT_ENV [A, B]",
10043            "ISOLATED INHERIT_ENV [A-B]",
10044            "TIMEOUT 10s { [os:linux] ECHO hi }",
10045            "ASYNC { [os:linux] ECHO hi }",
10046            "ISOLATED { [os:linux] ECHO hi }",
10047            "[os:linux] WITH_IO [stdin=$p]\n{ ECHO hi }",
10048            "LET $x: INT = 1 ECHO bye",
10049            "CANCEL $t LET $x: INT = 1",
10050            "CANCEL $t $x = 1",
10051            "CANCEL $t RETURN \"hi\"",
10052            "TIMEOUT 10s { ECHO hi } LET $x: INT = 1",
10053            "RUN [\"a\"] ECHO bye",
10054            "[os:linux] AWAIT $t",
10055            "[os:linux] TIMEOUT 10s { ECHO hi } ECHO bye",
10056            "[os:linux] ASYNC CANCEL $t ECHO bye",
10057            "[os:linux] WITH_IO [stdin=$p] { [os:macos] ECHO hi }",
10058        ] {
10059            assert_parity(text);
10060        }
10061    }
10062
10063    #[test]
10064    fn token_and_string_paths_agree_on_blocks() {
10065        // Slice 5: `IF`/`FOR`/`WHILE`/`FUNC` with inline and
10066        // cross-newline `ELSE` chains, guard blocks (top-level and
10067        // nested quirk), and multi-element trailing — three-way
10068        // agreement per script.
10069        for text in [
10070            "IF true { ECHO hi }",
10071            "IF $x { ECHO hi } ELSE { ECHO bye }",
10072            "IF true { ECHO a } ELSE IF false { ECHO b } ELSE { ECHO c }",
10073            "IF true{ ECHO hi }",
10074            "IF true { ECHO hi } ECHO bye",
10075            "IF true { ECHO hi }\nELSE { ECHO bye }",
10076            "IF true { ECHO hi }\nELSE IF false { ECHO b }\nELSE { ECHO c }",
10077            "IF true { ECHO hi } //c\nELSE { ECHO bye }",
10078            "IF true { ECHO hi } #c\nELSE { ECHO bye }",
10079            "IF true { ECHO hi }//c\nELSE { ECHO bye }",
10080            "IF true { ECHO hi } /*c*/ ELSE { ECHO bye }",
10081            "IF true { ECHO hi } /*c1*/ /*c2*/\nELSE { ECHO bye }",
10082            "IF true { /*c*/ ECHO hi }",
10083            "IF true { [os:linux] ECHO hi }",
10084            "TIMEOUT 10s { IF true { ECHO hi } }",
10085            "TIMEOUT 10s { IF true { ECHO hi }\nELSE { ECHO bye } }",
10086            "FOR $x: INT IN [1] { ECHO hi }",
10087            "FOR $k: STRING, $v: INT IN $m { ECHO hi }",
10088            "FOR $k: INT IN [1] { ECHO hi }",
10089            "FOR $x: INT IN [1]{ ECHO hi }",
10090            "FOR $x: MAP<name: STRING> IN [1] { ECHO hi }",
10091            "FOR $x: INT IN [1] { ECHO hi } ECHO bye",
10092            "WHILE true { ECHO hi }",
10093            "WHILE $x { ECHO hi }",
10094            "WHILE true{ ECHO hi }",
10095            "TIMEOUT 10s WHILE true { ECHO hi }",
10096            "ASYNC WHILE true { ECHO hi }",
10097            "FUNC FOO(): INT { RETURN 1 }",
10098            "FUNC FOO(): INT { RETURN 1 }",
10099            "FUNC FOO($x: INT): INT { RETURN $x }",
10100            "FUNC FOO($x: INT, $y: STRING): INT { RETURN $x }",
10101            "FUNC FOO(): INT { FUNC FOO(): INT { RETURN 1 } }",
10102            "FUNC FOO(): INT { RETURN 1 }\nFUNC BAR(): VOID { FOO() }\nBAR()",
10103            "TYPE PERSON = MAP<name: STRING>",
10104            "TYPE A=B",
10105            "TYPE A = B | C",
10106            "TYPE A = B\nTYPE A = C",
10107            "INHERIT_ENV [A]\nECHO hi",
10108            "[os:linux] INHERIT_ENV [M]",
10109            "INHERIT_ENV [A]\nINHERIT_ENV [B]\nECHO hi",
10110            "ISOLATED INHERIT_ENV [M]",
10111            "ISOLATED { INHERIT_ENV [M] }",
10112            "ISOLATED INHERIT_ENV [A, B]",
10113            "ISOLATED INHERIT_ENV [A-B]",
10114            "REMOTE prod { ECHO hi }",
10115            "REMOTE prod [$v] { ECHO hi }",
10116            "REMOTE prod [$v, env:E] { ECHO hi }",
10117            "REMOTE prod [] { ECHO hi }",
10118            "REMOTE prod[$v] { ECHO hi }",
10119            "REMOTE prod [$v]{ ECHO hi }",
10120            "REMOTE prod{ ECHO hi }",
10121            "REMOTE  prod  { ECHO hi }",
10122            "REMOTE prod [$v, $v] { ECHO hi }",
10123            "REMOTE prod { ECHO hi } ECHO bye",
10124            "TIMEOUT 10s REMOTE prod { ECHO hi }",
10125            "ASYNC REMOTE prod [$v] { ECHO hi }",
10126            "[os:linux] { ECHO hi }",
10127            "[os:linux]\n{ ECHO hi }",
10128            "[os:linux] { [os:macos] ECHO hi }",
10129            "[os:linux] { [os:macos] ECHO hi\nECHO bye }",
10130            "[os:linux] { [os:macos] { ECHO hi } }",
10131            "TIMEOUT 10s { [os:linux] { [os:macos] ECHO hi } }",
10132            "TIMEOUT 10s { [os:linux] [os:windows] { ECHO hi } }",
10133            "TIMEOUT 10s { [os:linux] { ECHO hi } ECHO bye }",
10134            "LET $x: INT = 1 ECHO bye",
10135            KEYWORD_BREAK,
10136            KEYWORD_CONTINUE,
10137            "BREAK ECHO hi",
10138            "FOR $x: INT IN [1] { BREAK }",
10139            "LET $b: STRING = { RETURN \"hi\" }",
10140            "ECHO { RETURN \"hi\" }",
10141            "RUN [{ RETURN \"hi\" }]",
10142            "[not(env:FOO)] WRITE x",
10143            "[\nnot(env:FOO)\n] WRITE x",
10144            "WRITE env.txt \"{{ env:GREETING }}\"",
10145            "CANCEL $t LET $x: INT = 1",
10146            "RUN [\"a\"] ECHO bye",
10147        ] {
10148            assert_parity(text);
10149        }
10150    }
10151
10152    #[test]
10153    fn multi_line_generics_match_single_line_shape() {
10154        // Multi-line `<...>` shapes parse, and canonicalize exactly
10155        // like their single-line spelling.
10156        for (single, multi) in [
10157            (
10158                "TYPE R = MAP<name: STRING, value: INT>",
10159                "TYPE R = MAP<name: STRING,\nvalue: INT>",
10160            ),
10161            (
10162                "TYPE R = MAP<name: STRING, value: LIST<INT>>",
10163                "TYPE R = MAP<name: STRING,\nvalue: LIST<INT>>",
10164            ),
10165            (
10166                "TYPE R = MAP<name: STRING, value: INT>",
10167                "TYPE R = MAP<\nname: STRING,\nvalue: INT\n>",
10168            ),
10169            (
10170                "LET $m: MAP<name: STRING, value: INT> = {}",
10171                "LET $m: MAP<name: STRING,\nvalue: INT> = {}",
10172            ),
10173            (
10174                "FOR $x: LIST<INT> IN [1] { ECHO hi }",
10175                "FOR $x: LIST<\nINT> IN [1] { ECHO hi }",
10176            ),
10177            ("TYPE R = MAP<x: A | B>", "TYPE R = MAP<x: A |\nB>"),
10178        ] {
10179            assert_parity(multi);
10180            let want = crate::parse_script(single, lower)
10181                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
10182            let got = crate::parse_script(multi, lower)
10183                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
10184            assert_eq!(
10185                got, want,
10186                "multi-line must canonicalize like one line: {multi:?}"
10187            );
10188        }
10189    }
10190
10191    #[test]
10192    fn type_field_defaults_parse_to_canonical_targets() {
10193        // Token-level regression: `= literal` tails belong to the
10194        // field (floats lex as three tokens), and the statement
10195        // target canonicalizes exactly like the spelling parser.
10196        for (text, want) in [
10197            ("TYPE F = MAP<retries: INT = 2>", "MAP<retries: INT = 2>"),
10198            ("TYPE F = MAP<retries: INT=-2>", "MAP<retries: INT = -2>"),
10199            (
10200                "TYPE F = MAP<ratio: FLOAT = 2.5>",
10201                "MAP<ratio: FLOAT = 2.5>",
10202            ),
10203            ("TYPE F = MAP<on: BOOL = true>", "MAP<on: BOOL = true>"),
10204            (
10205                "TYPE F = MAP<model: STRING = \"gpt-4\">",
10206                "MAP<model: STRING = \"gpt-4\">",
10207            ),
10208            (
10209                "TYPE F = MAP<k: STRING = \"d\", n: INT = 3>",
10210                "MAP<k: STRING = \"d\", n: INT = 3>",
10211            ),
10212        ] {
10213            assert_parity(text);
10214            let steps = crate::parse_script(text, lower)
10215                .unwrap_or_else(|e| panic!("default spelling must parse {text:?}: {e}"));
10216            let target = steps
10217                .iter()
10218                .find_map(|s| match &s.kind {
10219                    StepKind::TypeAlias { target, .. } => Some(target.clone()),
10220                    _ => None,
10221                })
10222                .expect("TYPE alias step");
10223            assert_eq!(target, want, "canonical target for {text:?}");
10224        }
10225    }
10226
10227    #[test]
10228    fn multi_line_run_exec_matches_single_line_shape() {
10229        // `RUN [...]` rides the shared bracket core, so a wrapped exec
10230        // list parses exactly like its single-line spelling (and agrees
10231        // across lexer frontends).
10232        for (single, multi) in [
10233            ("RUN [\"echo\", \"hi\"]", "RUN [\"echo\",\n\"hi\"]"),
10234            ("RUN [\"echo\", \"hi\"]", "RUN [\n\"echo\",\n\"hi\"\n]"),
10235            (
10236                "LET $o: STRING = RUN [\"echo\", \"hi\"]",
10237                "LET $o: STRING = RUN [\"echo\",\n\"hi\"]",
10238            ),
10239        ] {
10240            assert_parity(multi);
10241            let want = crate::parse_script(single, lower)
10242                .unwrap_or_else(|e| panic!("single-line shape must parse {single:?}: {e}"));
10243            let got = crate::parse_script(multi, lower)
10244                .unwrap_or_else(|e| panic!("multi-line shape must parse {multi:?}: {e}"));
10245            assert_eq!(
10246                got, want,
10247                "multi-line must canonicalize like one line: {multi:?}"
10248            );
10249        }
10250    }
10251
10252    #[test]
10253    fn untyped_let_fails_in_every_rhs_shape() {
10254        // The everything-typed rule: a missing `:` is a hard error
10255        // carrying the explicit-types message, regardless of what
10256        // follows the `=`. Every binding shape is covered, so no
10257        // untyped position can slip back in unnoticed.
10258        for text in [
10259            "LET $x = 1\n",
10260            "LET $x = \"hi\"\n",
10261            "LET $x = $y\n",
10262            "LET $x = [\"a\", \"b\"]\n",
10263            "LET $x = [\"a\",\n\"b\"]\n",
10264            "LET $x = ECHO hi\n",
10265            "LET $x = AWAIT $t\n",
10266            "LET $x = ASYNC ECHO hi\n",
10267            "LET $x = {\nRETURN 1\n}\n",
10268            "LET $x = WITH_IO [stdin=$p] ASYNC ECHO hi\n",
10269        ] {
10270            let err = crate::parse_script(text, lower).expect_err("untyped LET must fail");
10271            assert!(
10272                err.to_string().contains("LET requires explicit types"),
10273                "wrong error for {text:?}: {err}"
10274            );
10275        }
10276        // Typed spellings of the same shapes keep parsing through
10277        // every lexer frontend.
10278        for text in [
10279            "LET $x: INT = 1\n",
10280            "LET $x: STRING = \"hi\"\n",
10281            "LET $x: LIST<STRING> = [\"a\", \"b\"]\n",
10282            "LET $x: LIST<STRING> = [\"a\",\n\"b\"]\n",
10283            "LET $x: STRING = ECHO hi\n",
10284            "LET $x: STRING = AWAIT $t\n",
10285            "LET $x: HANDLE<VOID> = ASYNC ECHO hi\n",
10286            "LET $x: INT = {\nRETURN 1\n}\n",
10287        ] {
10288            assert_parity(text);
10289        }
10290    }
10291
10292    #[test]
10293    fn missing_comma_points_at_the_item() {
10294        // A forgotten comma between items names the missing
10295        // comma and points at the item's line, not the statement
10296        // head. Lists and call arguments share the rule.
10297        let text = indoc! {r#"
10298            LET $x: LIST<STRING> = [
10299            "a"
10300            "b",
10301            "c"
10302            ]
10303        "#};
10304        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
10305        assert!(
10306            err.to_string().contains("missing comma between list items"),
10307            "wrong error: {err}"
10308        );
10309        assert_eq!(err.line(), 3, "caret names the item line: {err}");
10310        // Same shape on one line.
10311        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" \"b\"]\n", lower)
10312            .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(), 1, "single-line points at line 1: {err}");
10318        // Call arguments share the rule.
10319        let err = crate::parse_script("LET $x: STRING = FOO(\"a\" \"b\")\n", lower)
10320            .expect_err("missing comma must fail");
10321        assert!(
10322            err.to_string()
10323                .contains("missing comma between call arguments"),
10324            "wrong error: {err}"
10325        );
10326        // Genuine trailing garbage keeps the old message but still
10327        // points at the garbage instead of the statement head.
10328        let err = crate::parse_script("LET $x: LIST<STRING> = [\"a\" : \"b\"]\n", lower)
10329            .expect_err("garbage must fail");
10330        assert!(
10331            err.to_string().contains("unexpected text in list"),
10332            "wrong error: {err}"
10333        );
10334        // Maps share the rule: a forgotten comma between entries
10335        // names it at the entry's line instead of misreporting the
10336        // key as an unknown command.
10337        let text = indoc! {r#"
10338            LET $m: MAP<name: STRING> = {
10339            name: "a"
10340            value: "b"
10341            }
10342        "#};
10343        let err = crate::parse_script(text, lower).expect_err("missing comma must fail");
10344        assert!(
10345            err.to_string()
10346                .contains("missing comma between map entries"),
10347            "wrong error: {err}"
10348        );
10349        assert_eq!(err.line(), 3, "caret names the entry line: {err}");
10350        let err = crate::parse_script(
10351            "LET $m: MAP<name: STRING> = {name: \"a\" value: \"b\"}\n",
10352            lower,
10353        )
10354        .expect_err("missing comma must fail");
10355        assert!(
10356            err.to_string()
10357                .contains("missing comma between map entries"),
10358            "wrong error: {err}"
10359        );
10360    }
10361
10362    #[test]
10363    fn spaced_comparisons_still_end_the_statement() {
10364        // A spaced `<` is a comparison, never a generic open: the
10365        // newline still ends the statement.
10366        let steps = crate::parse_script("LET $b: BOOL = $a < $b\nECHO hi", lower)
10367            .expect("comparison plus follower must parse");
10368        assert_eq!(steps.len(), 2, "newline ends the comparison statement");
10369    }
10370
10371    #[test]
10372    fn token_and_string_paths_agree_on_flat_commands() {
10373        for text in [
10374            "ECHO hi",
10375            "ECHO hi\nWRITE x out",
10376            "WRITE x",
10377            "ECHO \"quoted\" unquoted",
10378            "ENV COVERAGE=covered",
10379            "ECHO a; ECHO b",
10380            "// comment\nECHO hi",
10381            "ECHO 1.0.0 --flag a/b",
10382            "ECHO $x",
10383            "\n\nECHO hi\n\n",
10384        ] {
10385            assert_parity(text);
10386        }
10387    }
10388
10389    #[cfg(feature = "proc-macro-api")]
10390    #[test]
10391    fn backslash_outside_strings_is_string_only() {
10392        // `rustc` rejects a bare `\`, so unquoted backslash escapes
10393        // cannot cross `TokenStream` (same exclusion class as raw-`"`
10394        // blocks): the string lexer keeps them, the token path fails to
10395        // tokenize before v2 is ever reached.
10396        let toks = crate::tok::lex_str("ECHO a\\nb").expect("string lex keeps escapes");
10397        let old = crate::parse_script("ECHO a\\nb", lower).expect("string path parses it");
10398        assert_eq!(
10399            parse_tokens(&toks, lower).expect("token path parses it"),
10400            old
10401        );
10402        assert!("ECHO a\\nb".parse::<proc_macro2::TokenStream>().is_err());
10403    }
10404
10405    #[test]
10406    fn escaped_backslash_pair_is_atomic() {
10407        // `"a\\"` parses (one escape pair plus the closer): the pair
10408        // scans atomically, like the block-string arm and `lex_word`.
10409        // The value stays raw (`\\` verbatim for runtime
10410        // `expand_string`), so this pins parsing, not unescaping.
10411        assert_parity("ECHO \"a\\\\\"");
10412        let steps = crate::parse_script("ECHO \"a\\\\\"", lower).expect("escaped pair must parse");
10413        match &steps[..] {
10414            [s] => assert!(
10415                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a\\\\"),
10416                "escaped pair must survive raw: {s:?}"
10417            ),
10418            _ => panic!("one step: {steps:?}"),
10419        }
10420    }
10421
10422    #[test]
10423    fn joint_double_slash_stays_literal() {
10424        // `rustc` strips `//` before the macro ever runs, so these are
10425        // string-path-only by construction: joint `a//b` is one literal
10426        // arg, and `[a //c]` closes its group (the in-group `//` copy
10427        // stops at the closer).
10428        for text in ["ECHO a//b", "ECHO [a //c]"] {
10429            assert_parity_string_only(text);
10430        }
10431        let steps = crate::parse_script("ECHO a//b", lower).expect("joint slashes parse");
10432        match &steps[..] {
10433            [s] => assert!(
10434                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "a//b"),
10435                "joint `//` must glue literally: {s:?}"
10436            ),
10437            _ => panic!("one step: {steps:?}"),
10438        }
10439        let steps = crate::parse_script("ECHO [a //c]", lower).expect("group must close");
10440        assert_eq!(steps.len(), 1, "one step: {steps:?}");
10441        // Full content survives literally: the mock joins WRITE args
10442        // with spaces, so the round trip is byte-exact here.
10443        let steps = crate::parse_script("WRITE f [a //c]", lower).expect("group must close");
10444        match &steps[..] {
10445            [s] => assert!(
10446                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a //c]"),
10447                "group content must survive literally: {s:?}"
10448            ),
10449            _ => panic!("one step: {steps:?}"),
10450        }
10451    }
10452
10453    #[test]
10454    fn block_comment_in_group_closes_like_line_comment() {
10455        // `[a /* c]` reads literally on the old backend (first arg
10456        // `[a`, joined `[a /* c]`), so the in-group `/*` copy breaks
10457        // at the depth-zero closer exactly like `//` does. The bare
10458        // `/*` reads literally too.
10459        for text in ["ECHO [a /* c]", "WRITE f [a /* c]", "ECHO /*"] {
10460            assert_parity_string_only(text);
10461        }
10462        let steps = crate::parse_script("ECHO /*", lower).expect("bare block open parses");
10463        match &steps[..] {
10464            [s] => assert!(
10465                matches!(&s.kind, StepKind::Echo(a) if a.as_str() == "/*"),
10466                "bare `/*` must stay literal: {s:?}"
10467            ),
10468            _ => panic!("one step: {steps:?}"),
10469        }
10470        let steps = crate::parse_script("WRITE f [a /* c]", lower).expect("group must close");
10471        match &steps[..] {
10472            [s] => assert!(
10473                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c]"),
10474                "group content must survive literally: {s:?}"
10475            ),
10476            _ => panic!("one step: {steps:?}"),
10477        }
10478        // Terminated spans keep working through the same path: the
10479        // run carries its closer, so math still gets first refusal.
10480        let steps = crate::parse_script("WRITE f [a /* c */ d]", lower).expect("group must close");
10481        match &steps[..] {
10482            [s] => assert!(
10483                matches!(&s.kind, StepKind::Write { contents: Some(c), .. } if c.as_str() == "[a /* c */ d]"),
10484                "terminated group content must survive: {s:?}"
10485            ),
10486            _ => panic!("one step: {steps:?}"),
10487        }
10488    }
10489
10490    #[test]
10491    fn single_quoted_multiline_keeps_line_tracking() {
10492        // The `'` arm counts embedded newlines like the `"` arm, so the
10493        // statement after a multiline single-quoted string keeps its
10494        // own lines (func-docs stamping keys off them).
10495        let text = "ECHO 'a\nb'\nECHO c";
10496        assert_parity_string_only(text);
10497        let steps = crate::parse_script(text, lower).expect("must parse");
10498        assert_eq!(steps.len(), 2, "two steps: {steps:?}");
10499        assert_eq!((steps[0].line, steps[0].col), (1, 1));
10500        assert_eq!((steps[1].line, steps[1].col), (3, 1), "{steps:?}");
10501    }
10502
10503    #[test]
10504    fn token_and_string_paths_agree_on_guarded_commands() {
10505        for text in [
10506            "[env:X] ECHO hi",
10507            "[env:A] [os:linux] ECHO hi",
10508            "[os:macos] WRITE x",
10509            "[not(os:windows)] WRITE f x",
10510            "[any(os:macos, os:linux)] ECHO hi",
10511            "[all(env:A, os:linux)] ECHO hi",
10512            "[eq(env:K, v)] ECHO hi",
10513            "[ne(env:K, v)] ECHO hi",
10514            "[bool:true] ECHO hi",
10515            "[arch:arm] ECHO hi",
10516            "[family:unix] ECHO hi",
10517            "[(os:linux)] ECHO hi",
10518            "[env:A, os:linux] ECHO hi",
10519            "WRITE x\n[env:X] ECHO hi",
10520            "[env:K] ECHO $x",
10521            "[__OXDOCK_INJECT_1__] ECHO hi",
10522            "[eq(env:K, \"a b\")] ECHO hi",
10523            "[\nenv:X\n] ECHO hi",
10524            // In-body brackets are raw text split on whitespace (probed
10525            // parity: `[a, b]` is args `"[a,"` + `"b]"`, quotes kept).
10526            "ECHO [a, b] hi",
10527            "WRITE f [env:X]",
10528            "ECHO [env:X] hi",
10529            "WRITE f [\"a b\"]",
10530            "ECHO foo[bar]baz",
10531            "ECHO [a ]",
10532            "ECHO [ a]",
10533            "WRITE out x [env:X]",
10534        ] {
10535            assert_parity(text);
10536        }
10537        // `rustc` lexes `'a` as a lifetime start and rejects the
10538        // space: string-path-only by construction.
10539        assert_parity_string_only("ECHO ['a b']");
10540    }
10541
10542    #[test]
10543    fn token_and_string_paths_agree_on_calls_and_exact_args() {
10544        use crate::ast::{ModuleFuncs, ModuleTable};
10545        use std::collections::{HashMap, HashSet};
10546        let std_table = || ModuleTable {
10547            modules: HashMap::from([(
10548                crate::constants::STD_MODULE_NAME.to_string(),
10549                Some(ModuleFuncs {
10550                    func_names: HashSet::from(["LEN".to_string()]),
10551                }),
10552            )]),
10553        };
10554        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10555            test_lower_mock::lower(name, args)
10556        }
10557        // One table for both pathways: STD exports LEN.
10558        // Rebuilt per case (parse-time only, keeps borrows local).
10559        for text in [
10560            "LET $n: INT = STD::LEN(\"hi\")",
10561            "STD::LEN(\"hi\")",
10562            "LET $n: INT = STD::LEN(\"a\", \"b\")",
10563            "LET $s: STRING = INSPECT($x)",
10564            "INSPECT($x)",
10565            "LET $x: STRING = ECHO hi",
10566            "LET $t: STRING = WRITE x",
10567            "LET $o: STRING = RUN echo hi",
10568            "RUN [\"echo\", \"hi\"]",
10569            "RUN echo [a]",
10570            "LET $r: STRING = RUN [\"echo\"]",
10571            "ECHO K=v",
10572            "ECHO K = v",
10573            "ECHO K=a b",
10574            "ECHO K=a, b",
10575            "ECHO K=\"a b\"",
10576            "ECHO K=$x",
10577            "ECHO K=",
10578            "ECHO a = = b",
10579            "WRITE f K=v",
10580            "ECHO $a + $b",
10581            "ECHO $a==$b",
10582            "ECHO a $x b",
10583            "ECHO 5 + 3",
10584            "WRITE f ( \"hi\" )",
10585            "ECHO [a, b] hi",
10586            "ECHO {{x}}",
10587            "ECHO {{ $x }}",
10588            "ECHO $x=K",
10589            "ECHO a$x",
10590            "ECHO a$(x)",
10591            "ECHO K=$x tail",
10592            "EXPAND K1=$x K2=$y",
10593            "EXPAND a",
10594            "ENV K = v",
10595            "COPY a b",
10596            "ECHO foo[bar]baz",
10597            "LET $x: STRING = FOOBAR",
10598            "STD::LEN(\"hi\") ECHO bye",
10599            "LET $n: INT = STD::LEN(\"a\") ECHO bye",
10600            "TIMEOUT 10s STD::LEN(\"hi\")",
10601            "TIMEOUT 10s STD::LEN(\"hi\") ECHO bye",
10602            "LET $n: INT = STD::LEN(\"a\")STD::LEN(\"b\")",
10603        ] {
10604            let table = std_table();
10605            let old =
10606                crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
10607                    .unwrap_or_else(|e| panic!("backend must parse parity script {text:?}: {e}"));
10608            let reserved = HashSet::new();
10609            let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
10610            let toks = crate::tok::lex_str(text).expect("string lex must succeed");
10611            let new = parse_tokens_with_ctx(&toks, &ctx)
10612                .unwrap_or_else(|e| panic!("token path must parse {text:?}: {e}"));
10613            assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
10614            #[cfg(feature = "proc-macro-api")]
10615            {
10616                let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
10617                let toks = crate::tok::lex_tokens(&ts).expect("token lex must succeed");
10618                let new = parse_tokens_with_ctx(&toks, &ctx)
10619                    .unwrap_or_else(|e| panic!("token path must parse token {text:?}: {e}"));
10620                assert_eq!(new, old, "v2/token-lex mismatch for {text:?}");
10621            }
10622        }
10623    }
10624
10625    #[test]
10626    fn placeholder_bare_calls_resolve_like_statements() {
10627        // `{{ NAME(args) }}` obeys exactly the statement-position
10628        // scope rule: `IMPORT [MOD]` brings the names into scope,
10629        // unimported names fail naming the fix, ambiguity fails
10630        // closed. The rewrite below is byte-identical past the
10631        // qualified head, so expansion sees the same args.
10632        use crate::ast::{ModuleFuncs, ModuleTable};
10633        use std::collections::{HashMap, HashSet};
10634        let table = || ModuleTable {
10635            modules: HashMap::from([
10636                (
10637                    crate::constants::STD_MODULE_NAME.to_string(),
10638                    Some(ModuleFuncs {
10639                        func_names: HashSet::from(["LEN".to_string()]),
10640                    }),
10641                ),
10642                (
10643                    "OTHER".to_string(),
10644                    Some(ModuleFuncs {
10645                        func_names: HashSet::from(["LEN".to_string()]),
10646                    }),
10647                ),
10648            ]),
10649        };
10650        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10651            test_lower_mock::lower(name, args)
10652        }
10653        fn echo_text(steps: &[crate::Step]) -> String {
10654            match steps {
10655                [s] => match &s.kind {
10656                    StepKind::Echo(Arg::String(text, _)) => text.clone(),
10657                    other => panic!("expected ECHO string, got {other:?}"),
10658                },
10659                _ => panic!("expected one step, got {steps:?}"),
10660            }
10661        }
10662        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10663            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10664        }
10665        // Imported bare names qualify; everything else rides through
10666        // byte-identical for the runtime to handle as before.
10667        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }}\"\n";
10668        let out = echo_text(&parse(text, table()).expect("imported bare call parses"));
10669        assert_eq!(out, "n: {{ STD::LEN($x) }}", "bare call qualifies: {out}");
10670        let text = "IMPORT [STD]\nECHO \"n: {{ STD::LEN($x) }}\"\n";
10671        let out = echo_text(&parse(text, table()).expect("qualified parses"));
10672        assert_eq!(
10673            out, "n: {{ STD::LEN($x) }}",
10674            "qualified keys stay untouched: {out}"
10675        );
10676        let text = "IMPORT [STD]\nECHO \"hi {{ $x }} and {{ bare }} and {{ env:K }}\"\n";
10677        let out = echo_text(&parse(text, table()).expect("non-calls parse"));
10678        assert_eq!(
10679            out, "hi {{ $x }} and {{ bare }} and {{ env:K }}",
10680            "non-call keys stay untouched: {out}"
10681        );
10682        let text = "IMPORT [STD]\nECHO \"lit \\{{ LEN($x) }}\"\n";
10683        let out = echo_text(&parse(text, table()).expect("escaped parses"));
10684        assert_eq!(
10685            out, "lit \\{{ LEN($x) }}",
10686            "escaped openers stay literal: {out}"
10687        );
10688        // Nested bodies resolve against the enclosing imports, exactly
10689        // like statement-position calls in the same body.
10690        let text = indoc! {r#"
10691            IMPORT [STD]
10692            FUNC F(): VOID {
10693            ECHO "n: {{ LEN($x) }}"
10694            }
10695        "#};
10696        let steps = parse(text, table()).expect("nested bare call parses");
10697        let body = steps.iter().find_map(|s| match &s.kind {
10698            StepKind::FuncDef { body, .. } => Some(body),
10699            _ => None,
10700        });
10701        match body.map(Vec::as_slice) {
10702            Some([inner]) => match &inner.kind {
10703                StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10704                    echoed, "n: {{ STD::LEN($x) }}",
10705                    "nested body qualifies: {echoed}"
10706                ),
10707                other => panic!("expected nested ECHO, got {other:?}"),
10708            },
10709            _ => panic!("expected one FUNC with one body step, got {steps:?}"),
10710        };
10711        // Neighboring placeholders keep their exact bytes: only the
10712        // head span changes, so payloads never lose formatting.
10713        let text = "IMPORT [STD]\nECHO \"Call {{ LEN($x) }} and value {{ $y }}\"\n";
10714        let out = echo_text(&parse(text, table()).expect("mixed template parses"));
10715        assert_eq!(
10716            out, "Call {{ STD::LEN($x) }} and value {{ $y }}",
10717            "only the head span changes: {out}"
10718        );
10719        // Unimported bare names fail exactly like statement position:
10720        // qualify it or add the import.
10721        let err = parse("ECHO \"n: {{ LEN($x) }}\"\n", table()).expect_err("must fail");
10722        assert!(
10723            err.to_string().contains("unknown function `LEN`")
10724                && err.to_string().contains("or add `IMPORT"),
10725            "names the fix: {err}"
10726        );
10727        // Two exporters fail closed instead of picking one.
10728        let err = parse(
10729            "IMPORT [STD]\nIMPORT [OTHER]\nECHO \"n: {{ LEN($x) }}\"\n",
10730            table(),
10731        )
10732        .expect_err("must fail");
10733        assert!(
10734            err.to_string().contains("ambiguous function `LEN`"),
10735            "ambiguity fails closed: {err}"
10736        );
10737        // Both lexing pathways agree on rewritten templates.
10738        let text = "IMPORT [STD]\nECHO \"n: {{ LEN($x) }} and {{ $y }}\"\n";
10739        let table = table();
10740        let old = crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table.clone())
10741            .expect("string path parses");
10742        let reserved = HashSet::new();
10743        let ctx = ParseCtx::empty(&lower_fn, &table, &reserved);
10744        let toks = crate::tok::lex_str(text).expect("string lex must succeed");
10745        let new = parse_tokens_with_ctx(&toks, &ctx).expect("token path parses");
10746        assert_eq!(new, old, "token/string-lex mismatch for {text:?}");
10747    }
10748
10749    #[test]
10750    fn placeholder_bare_calls_qualify_in_expr_positions() {
10751        // Regression: `walk_raw_strings_mut` skips `Assign`/`Set`/
10752        // `Call`/`Return`/`If`/`For`/`While`, so `LET`/`RETURN`/call
10753        // args/list/map literals never qualified and failed at
10754        // runtime as undefined variables. Both carriers now qualify.
10755        use crate::ast::{ModuleFuncs, ModuleTable};
10756        use std::collections::{HashMap, HashSet};
10757        let table = || ModuleTable {
10758            modules: HashMap::from([(
10759                crate::constants::STD_MODULE_NAME.to_string(),
10760                Some(ModuleFuncs {
10761                    func_names: HashSet::from(["LEN".to_string()]),
10762                }),
10763            )]),
10764        };
10765        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10766            test_lower_mock::lower(name, args)
10767        }
10768        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10769            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10770        }
10771        // LET string literal qualifies.
10772        let steps = parse(
10773            "IMPORT [STD]\nLET $s: STRING = \"n: {{ LEN($x) }}\"\n",
10774            table(),
10775        )
10776        .expect("LET template parses");
10777        match &steps[0].kind {
10778            StepKind::Bind {
10779                rhs: BindRhs::Expr(expr),
10780                ..
10781            } => match expr {
10782                Expr::Literal(value) => assert_eq!(
10783                    value.as_str().unwrap_or_default(),
10784                    "n: {{ STD::LEN($x) }}",
10785                    "LET qualifies"
10786                ),
10787                other => panic!("expected literal, got {other:?}"),
10788            },
10789            other => panic!("expected Bind, got {other:?}"),
10790        }
10791        // RETURN string literal qualifies.
10792        let steps = parse(
10793            "IMPORT [STD]\nFUNC F(): STRING {\nRETURN \"n: {{ LEN($x) }}\"\n}\n",
10794            table(),
10795        )
10796        .expect("RETURN template parses");
10797        let body = steps.iter().find_map(|s| match &s.kind {
10798            StepKind::FuncDef { body, .. } => Some(body),
10799            _ => None,
10800        });
10801        match body.map(Vec::as_slice) {
10802            Some([inner]) => match &inner.kind {
10803                StepKind::Return { expr, .. } => match &**expr {
10804                    Expr::Literal(value) => assert_eq!(
10805                        value.as_str().unwrap_or_default(),
10806                        "n: {{ STD::LEN($x) }}",
10807                        "RETURN qualifies"
10808                    ),
10809                    other => panic!("expected literal, got {other:?}"),
10810                },
10811                other => panic!("expected RETURN, got {other:?}"),
10812            },
10813            _ => panic!("expected one FUNC, got {steps:?}"),
10814        }
10815        // Call args, list and map literals qualify.
10816        let steps = parse(
10817            "IMPORT [STD]\nLET $y: INT = LEN(\"b: {{ LEN($x) }}\")\n",
10818            table(),
10819        )
10820        .expect("call-arg template parses");
10821        let rendered = format!("{:?}", steps[0].kind);
10822        assert!(
10823            rendered.contains("STD::LEN"),
10824            "call arg qualifies: {rendered}"
10825        );
10826        let steps = parse(
10827            "IMPORT [STD]\nLET $l: LIST<STRING> = [\"{{ LEN($x) }}\"]\n",
10828            table(),
10829        )
10830        .expect("list template parses");
10831        let rendered = format!("{:?}", steps[0].kind);
10832        assert!(rendered.contains("STD::LEN"), "list qualifies: {rendered}");
10833        // Compound placeholders are not single calls: they pass
10834        // through untouched (no partial rewrite) for the runtime to
10835        // fail closed on the whole key.
10836        let text = "IMPORT [STD]\nECHO \"v: {{ LEN($a) + LEN($b) }}\"\n";
10837        let steps = parse(text, table()).expect("compound parses");
10838        match &steps[0].kind {
10839            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10840                echoed, "v: {{ LEN($a) + LEN($b) }}",
10841                "compound untouched: {echoed}"
10842            ),
10843            other => panic!("expected ECHO string, got {other:?}"),
10844        }
10845        // Quoted parens inside args do not end the call early.
10846        let text = "IMPORT [STD]\nECHO 'v: {{ LEN(\"a(b\") }}'\n";
10847        let steps = parse(text, table()).expect("quoted paren parses");
10848        match &steps[0].kind {
10849            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10850                echoed, "v: {{ STD::LEN(\"a(b\") }}",
10851                "quoted paren qualifies: {echoed}"
10852            ),
10853            other => panic!("expected ECHO string, got {other:?}"),
10854        }
10855        // Single-quoted args balance the same way.
10856        let text = "IMPORT [STD]\nECHO \"v: {{ LEN('a(b') }}\"\n";
10857        let steps = parse(text, table()).expect("single-quoted paren parses");
10858        match &steps[0].kind {
10859            StepKind::Echo(Arg::String(echoed, _)) => assert_eq!(
10860                echoed, "v: {{ STD::LEN('a(b') }}",
10861                "single-quoted paren qualifies: {echoed}"
10862            ),
10863            other => panic!("expected ECHO string, got {other:?}"),
10864        }
10865        // `WithIo` boxes its inner command directly (no recursive
10866        // statement pass), so the qualifier must descend into it.
10867        // `LET $p: PIPE` plus bindings keep the shape realistic.
10868        let text = "IMPORT [STD]\nLET $p: PIPE\nWITH_IO [stdout=$p] ECHO 'v: {{ LEN($x) }}'\n";
10869        let steps = parse(text, table()).expect("with-io template parses");
10870        match &steps[1].kind {
10871            StepKind::WithIo { cmd, .. } => {
10872                let rendered = format!("{cmd:?}");
10873                assert!(
10874                    rendered.contains("STD::LEN"),
10875                    "with-io inner qualifies: {rendered}"
10876                );
10877            }
10878            other => panic!("expected WithIo, got {other:?}"),
10879        }
10880        // Single-command wrappers build synthetic body steps without a
10881        // recursive pass: `TIMEOUT 5s <cmd>` and `ASYNC <cmd>` share
10882        // the outer frame, so the qualifier must descend into bodies.
10883        let text = "IMPORT [STD]\nTIMEOUT 5s ECHO 't: {{ LEN($x) }}'\n";
10884        let steps = parse(text, table()).expect("timeout template parses");
10885        let rendered = format!("{:?}", steps[0].kind);
10886        assert!(
10887            rendered.contains("STD::LEN"),
10888            "timeout single qualifies: {rendered}"
10889        );
10890        let text = "IMPORT [STD]\nLET $h: HANDLE<ANY> = ASYNC ECHO 'a: {{ LEN($x) }}'\n";
10891        let steps = parse(text, table()).expect("async template parses");
10892        let rendered = format!("{:?}", steps[0].kind);
10893        assert!(
10894            rendered.contains("STD::LEN"),
10895            "async single qualifies: {rendered}"
10896        );
10897        // Brace bodies keep their own frames: the outer qualifier must
10898        // never re-walk them. A valid nested body qualifies via its own
10899        // recursive pass, and an unknown callee inside one fails with
10900        // the inner position, never re-resolved against the outer frame.
10901        let text = "IMPORT [STD]\nIF true {\nECHO 'v: {{ LEN($x) }}'\n}\n";
10902        let steps = parse(text, table()).expect("nested body qualifies");
10903        let rendered = format!("{:?}", steps[0].kind);
10904        assert!(
10905            rendered.contains("STD::LEN"),
10906            "nested IF body qualifies via its own frame: {rendered}"
10907        );
10908        let err = parse(
10909            "IMPORT [STD]\nIF true {\nECHO 'v: {{ NOPE($x) }}'\n}\n",
10910            table(),
10911        )
10912        .expect_err("nested unknown must fail");
10913        assert!(
10914            err.to_string().contains("unknown function `NOPE`"),
10915            "nested unknown names culprit: {err}"
10916        );
10917    }
10918
10919    #[test]
10920    fn block_conditions_name_unknown_callees() {
10921        // Regression: an unknown callee in a block header condition
10922        // used to miss to the generic `IF needs a condition and a
10923        // block` hint. Classified resolution failures now propagate
10924        // and name the culprit on all four speculative headers.
10925        use crate::ast::{ModuleFuncs, ModuleTable};
10926        use std::collections::{HashMap, HashSet};
10927        let table = || ModuleTable {
10928            modules: HashMap::from([(
10929                crate::constants::STD_MODULE_NAME.to_string(),
10930                Some(ModuleFuncs {
10931                    func_names: HashSet::from(["LEN".to_string()]),
10932                }),
10933            )]),
10934        };
10935        fn lower_fn(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
10936            test_lower_mock::lower(name, args)
10937        }
10938        fn parse(text: &str, table: ModuleTable) -> ParseResult<Vec<crate::Step>> {
10939            crate::parse_script_with_modules(text, lower_fn, HashSet::new(), table)
10940        }
10941        for text in [
10942            "IMPORT [STD]\nIF NOPE($x) == 0 {\nECHO hi\n}\n",
10943            "IMPORT [STD]\nIF LEN($x) == 0 {\nECHO hi\n} ELSE IF NOPE($x) == 1 {\nECHO yo\n}\n",
10944            "IMPORT [STD]\nWHILE NOPE($x) > 0 {\nECHO hi\n}\n",
10945            "IMPORT [STD]\nFOR $i: STRING IN NOPE($x) {\nECHO $i\n}\n",
10946        ] {
10947            let err = parse(text, table()).expect_err("unknown callee must fail");
10948            assert!(
10949                err.to_string().contains("unknown function `NOPE`"),
10950                "names the culprit: {err}"
10951            );
10952        }
10953        // Unclassified shape misses still miss (the exact generic
10954        // hint comes from the real dispatcher, which the mock lacks).
10955        parse("IF {\nECHO hi\n}\n", table()).expect_err("empty condition must still fail");
10956    }
10957
10958    #[test]
10959    fn token_and_string_paths_agree_on_let_set_return() {
10960        for text in [
10961            "LET $x: INT = 1",
10962            "LET $s: STRING = \"hi\"",
10963            "LET $b: BOOL = true",
10964            "LET $f: FLOAT = 1.5",
10965            "LET $p: PIPE",
10966            "LET $l: LIST<STRING> = [\"a\", \"b\"]",
10967            "LET $e: LIST<STRING> = []",
10968            "LET $m: MAP = {k: 1}",
10969            "LET $m2: MAP = {\"a b\": 2, k: [1, 2]}",
10970            "LET $n: INT = $a + $b",
10971            "LET $c: BOOL = ($a == 3) && ($b == 4)",
10972            "LET $g: BOOL = !$ok",
10973            "LET $nn: BOOL = true && false",
10974            "LET $e2: STRING = env:HOME",
10975            "LET $k: STRING = $a.b.c",
10976            "LET $u: INT = -5",
10977            "LET $v: INT = 9223372036854775807",
10978            "LET $min: INT = -9223372036854775808",
10979            "LET $w: INT = 1_000",
10980            "LET $z: STRING = a/b",
10981            "LET $d: STRING = -f",
10982            "LET $t: STRING = 30s",
10983            "LET $q: STRING = \"\"\"hi\"\"\"",
10984            "LET $f2: FLOAT = 2 * -3",
10985            "LET $o: BOOL = 2 + 3 > 4",
10986            "LET $l2: LIST< MAP > = []",
10987            "LET $a1: INT = 1 + 2",
10988            "LET $s1: INT = 10 - 4 - 3",
10989            "LET $m1: INT = 2 * 3 + 4",
10990            "LET $x1: BOOL = 1 < 2 == true",
10991            "LET $or: BOOL = $a || $b",
10992            "LET $dbl: BOOL = !!$x",
10993            "LET $ver: STRING = 1.0.0",
10994            "LET $dash: STRING = a-b",
10995            "LET $div: INT = 4 / 2",
10996            "LET $bad: INT = 1__0 + 0",
10997            "LET $strdiv: STRING = 4/2",
10998            "LET $sp: INT = $a - $b",
10999            "$x = 1",
11000            "$x = $a + 1",
11001            "RETURN 1",
11002            KEYWORD_RETURN,
11003            "RETURN $x",
11004            "[env:X] LET $x: INT = 1",
11005            "[os:linux] $x = 2",
11006        ] {
11007            assert_parity(text);
11008        }
11009    }
11010
11011    #[test]
11012    fn malformed_shapes_fail_on_both_paths() {
11013        // Malformed shapes fail on both lexers (messages may differ;
11014        // success/failure must agree). Unbalanced groups fail even
11015        // earlier, at lex time: both layers reject, which is what the
11016        // oracle pins.
11017        for text in [
11018            "[a] ECHO hi",
11019            "[os:atari] ECHO hi",
11020            "[foo:bar] ECHO hi",
11021            "[any(os:linux)] ECHO hi",
11022            "[all()] ECHO hi",
11023            "[env:] ECHO hi",
11024            "[eq(env:K)] ECHO hi",
11025            "[not] ECHO hi",
11026            "ECHO [a;b]",
11027            "ECHO (a;b)",
11028            "ECHO a;b",
11029            "LET $x = 1",
11030            "LET $s: STRING",
11031            "LET $x: INT = 1 2",
11032            "LET $x: INT = (1",
11033            "LET $x: INT = 9223372036854775808",
11034            "$x =",
11035            "RETURN (",
11036            "[env:X]",
11037            "LET $x: INT = $a == $b == $c",
11038            "LET $x: BOOL = $a < $b < $c",
11039            "LET $bs: STRING = a\\nb",
11040            "FOO(\"a\")",
11041            "FOO (\"a\")",
11042            "ECHO FOO(\"a\")",
11043            "ECHO(\"hi\")",
11044            "RUN [a] extra",
11045            "RUN[\"a\"]",
11046            "TIMEOUT 10s RUN[\"a\"]",
11047            "LET $r: STRING = RUN[\"a\"]",
11048            "LET $e: STRING = ECHO",
11049            "ENV A=1 B=2",
11050            "EXPAND \"a b\" c",
11051            "ECHO {a}",
11052            "ECHO K=${x}",
11053            "[!env:A==1] RUN echo no",
11054            "run echo hi",
11055            "LET $x: STRING = AWAIT",
11056            "LET $o: STRING = CANCEL $t",
11057            "LET $x: STRING = ASYNC",
11058            "LET $x: STRING = WITH_IO",
11059            "LET $x: STRING = TIMEOUT",
11060            "LET $x: STRING = ISOLATED",
11061            "LET $x: STRING = ISOLATED ECHO hi",
11062            "COPY A=1",
11063            "WITH_IO [rows=40] RUN echo hi",
11064            "WITH_IO [tty] ECHO hi",
11065            "WITH_IO [tty, stderr=$p] RUN echo hi",
11066            "WITH_IO [tty=$p] RUN echo hi",
11067            "WITH_IO [cols=0] RUN echo hi",
11068            "WITH_IO [cols=65536] RUN echo hi",
11069            "WITH_IO [] ECHO hi",
11070            "WITH_IO [stdin=$p,] ECHO hi",
11071            "WITH_IO stdin=$p ECHO hi",
11072            "WITH_IO [STDIN=$p] ECHO hi",
11073            "WITH_IO [rows] RUN echo hi",
11074            KEYWORD_WITH_IO,
11075            "WITH_IO [stdout=$p]",
11076            "WITH_IO [stdin=$p]\n[os:linux] { ECHO hi }",
11077            "WITH_IO [stdin=$p] { }",
11078            "WITH_IO[stdin=$p] ECHO hi",
11079            "WITH_IO [stdin=$p]ECHO hi",
11080            "WITH_IO [stdin=$p] {{ $x }}",
11081            "ASYNC WITH_IO [stdout=$p] ECHO hi",
11082            "WITH_IO [stdin=$p] AWAIT $t",
11083            "ASYNC AWAIT $t",
11084            "WITH_IO [stdin=$p] RETURN \"hi\"",
11085            "ASYNC RETURN \"hi\"",
11086            "TIMEOUT 10s RETURN \"hi\"",
11087            "TIMEOUT banana ECHO hi",
11088            "TIMEOUT 10ss ECHO hi",
11089            "TIMEOUT 10 s ECHO hi",
11090            "TIMEOUT -5s ECHO hi",
11091            "TIMEOUT 0s ECHO hi",
11092            KEYWORD_TIMEOUT,
11093            "TIMEOUT 10s",
11094            "TIMEOUT { ECHO hi }",
11095            "TIMEOUT \"10s\"",
11096            "TIMEOUT 10s{ECHO hi}",
11097            "TIMEOUT 10sECHO hi",
11098            "TIMEOUT 10s {{ $d }}",
11099            "TIMEOUT 10s { $d }",
11100            "TIMEOUT { $d } ECHO hi",
11101            KEYWORD_ASYNC,
11102            KEYWORD_ISOLATED,
11103            "ISOLATED{ECHO hi}",
11104            KEYWORD_AWAIT,
11105            KEYWORD_CANCEL,
11106            "AWAIT t",
11107            "AWAIT $",
11108            "AWAIT $t extra",
11109            "CANCEL $t extra",
11110            "TIMEOUT 5s INHERIT_ENV [M]",
11111            "TIMEOUT 5s { INHERIT_ENV [M] }",
11112            "ASYNC { INHERIT_ENV [M] }",
11113            "LET $x: STRING = INHERIT_ENV [M]",
11114            "TIMEOUT 10s WITH_IO [stdin=$p] { ECHO hi }",
11115            "ISOLATED WITH_IO [stdin=$p] { ECHO hi }",
11116            "TIMEOUT 10s AWAIT $ t",
11117            "LET $o: STRING = AWAIT $ t",
11118            "ISOLATED AWAIT $ t",
11119            "WITH_IO [stdin=$p] CANCEL $ t",
11120            "LET $ x: INT = 1",
11121            "LET $x: STRING = WITH_IO [stdin=$p] { ECHO hi }",
11122            "LET $x: STRING = WITH_IO [stdin=$p] ASYNC",
11123            "LET $w: HANDLE = WITH_IO [stdin=$p] ASYNC { ECHO a\nECHO b }",
11124            "LET $x: STRING = WITH_IO [stdout=$p] ECHO hi",
11125            "LET $x: STRING = TIMEOUT 10s AWAIT $t",
11126            "LET $x: STRING = CANCEL $t",
11127            "LET $x: STRING = ASYNC",
11128            "LET $x: STRING = WITH_IO",
11129            "TIMEOUT 10s LET $x: INT = 1",
11130            "LET $x: STRING = FOO bar",
11131            "LET(\"a\")",
11132            "AWAIT($t)",
11133            "CANCEL($t)",
11134            "TIMEOUT(\"10s\") ECHO hi",
11135            "RETURN ECHO bye",
11136        ] {
11137            match crate::tok::lex_str(text) {
11138                Err(_) => {
11139                    assert!(
11140                        crate::parse_script(text, lower).is_err(),
11141                        "backend must also reject lex-broken input: {text:?}"
11142                    );
11143                    continue;
11144                }
11145                Ok(toks) => {
11146                    assert!(
11147                        parse_tokens(&toks, lower).is_err(),
11148                        "v2 must explicitly reject (not silently drift): {text:?}"
11149                    );
11150                }
11151            }
11152            assert!(
11153                crate::parse_script(text, lower).is_err(),
11154                "backend must also reject (oracle agreement): {text:?}"
11155            );
11156        }
11157        // No deferred shapes remain: every statement-level block and
11158        // inline-block expression parses natively.
11159    }
11160
11161    #[test]
11162    fn deferred_unknown_callee_beats_validation_arg_error() {
11163        // Directive 5: `WORKSPACE NOPE()` stashes `unknown function
11164        // NOPE` while the fallback raw string fails `WORKSPACE`
11165        // validation. On a well-formed header the stashed callee error
11166        // names the culprit instead of the misleading arg-shape error.
11167        let err =
11168            crate::parse_script("WORKSPACE NOPE()", lower).expect_err("unknown callee must fail");
11169        assert!(
11170            err.to_string().contains("unknown function `NOPE`"),
11171            "deferred must beat validation, got: {err}"
11172        );
11173    }
11174
11175    #[test]
11176    fn paren_line_break_reports_token_position() {
11177        // Directive 5: multiline paren breaks carry the offending
11178        // token's line/col, not a stamped 0/0. The break sits on line 2
11179        // while the statement opens on line 1.
11180        let err = crate::parse_script("ECHO (a\nb)", lower).expect_err("break must fail");
11181        let rendered = err.to_string();
11182        assert!(
11183            rendered.contains("unexpected line break"),
11184            "break must report, got: {rendered}"
11185        );
11186    }
11187
11188    #[test]
11189    fn deferred_unknown_callee_beats_invalid_syntax_arg_error() {
11190        // Fallback raw strings can trigger `InvalidSyntax` lowering
11191        // (for example `COPY NOPE()`). The stashed unknown-callee error
11192        // still names the culprit on a recognized head.
11193        for text in ["COPY NOPE()", "WRITE NOPE()"] {
11194            let err = crate::parse_script(text, lower).expect_err("unknown callee must fail");
11195            assert!(
11196                err.to_string().contains("unknown function `NOPE`"),
11197                "deferred must beat InvalidSyntax for {text:?}, got: {err}"
11198            );
11199        }
11200    }
11201
11202    #[test]
11203    fn deferred_beats_lowering_invalid_syntax_on_plain_heads() {
11204        // Plain command heads own no header grammar, so a lowering
11205        // `InvalidSyntax` there is an argument-shape failure from the
11206        // raw-text fallback: the stashed unknown-callee names the
11207        // culprit on every such head (no per-command allowlist).
11208        let lower_invalid =
11209            |name: &str, _args: Vec<crate::Arg>| -> crate::ParseResult<crate::StepKind> {
11210                Err(crate::ParseError::invalid_syntax(
11211                    name,
11212                    format!("{name} header is malformed"),
11213                    None,
11214                    Vec::new(),
11215                    None,
11216                    &crate::error::SpanContext::line_only(0),
11217                ))
11218            };
11219        for text in [
11220            "ASSERT_EQ $a NOSUCHFUNC()",
11221            "SYMLINK $a NOSUCHFUNC()",
11222            "COPY $a NOSUCHFUNC()",
11223            "WRITE $a NOSUCHFUNC()",
11224        ] {
11225            let err = crate::parse_script(text, lower_invalid).expect_err("arg error must fail");
11226            assert!(
11227                err.to_string().contains("unknown function `NOSUCHFUNC`"),
11228                "deferred must beat lowering InvalidSyntax for {text:?}, got: {err}"
11229            );
11230        }
11231        // Header-owned heads keep their lowering `InvalidSyntax`: the
11232        // native parser missed to the generic path on shape miss, so
11233        // the lowering error names the malformed header while the
11234        // stashed name is its definiendum, never a call.
11235        let err = crate::parse_script("FUNC $a NOSUCHFUNC()", lower_invalid)
11236            .expect_err("header syntax must fail");
11237        assert!(
11238            err.to_string().contains("header is malformed"),
11239            "header InvalidSyntax must stand on FUNC, got: {err}"
11240        );
11241    }
11242
11243    #[test]
11244    fn trailing_tokens_after_func_block_never_hoist() {
11245        // A `FUNC` header with trailing tokens after the body block is
11246        // malformed (the real path rejects it), so pre-declaration
11247        // must not hoist the name: the forward call fails instead of
11248        // resolving.
11249        let err = crate::parse_script(
11250            "LET $x: STRING = FOO()\nFUNC FOO(): STRING { RETURN \"a\" } TRAILING\n",
11251            lower,
11252        )
11253        .expect_err("trailing tokens must fail");
11254        assert!(
11255            err.to_string().contains("unknown function `FOO`"),
11256            "unhoisted forward call must fail, got: {err}"
11257        );
11258    }
11259
11260    #[test]
11261    fn forward_reference_resolves_regardless_of_order() {
11262        // `CALLER` calls `CALLEE` defined later. Top-level
11263        // pre-declaration hoists names before lowering, so order
11264        // does not matter. Runtime still executes sequentially;
11265        // the call below runs after both definitions.
11266        let steps = crate::parse_script(
11267            "FUNC CALLER(): STRING { RETURN CALLEE() }\nFUNC CALLEE(): STRING { RETURN \"forward-ok\" }\n",
11268            lower,
11269        )
11270        .expect("forward ref must parse");
11271        assert!(
11272            matches!(&steps[0].kind, crate::StepKind::FuncDef { name, .. } if name == "CALLER"),
11273            "first def kept, got: {:?}",
11274            steps[0].kind
11275        );
11276    }
11277
11278    #[test]
11279    fn forward_reference_to_guarded_func_resolves() {
11280        // Guarded definitions hoist like unguarded ones: `parse_func_at`
11281        // registers `[os:macos] FUNC FOO` unconditionally, so a forward
11282        // call before the definition must resolve identically to a
11283        // backward call after it.
11284        let steps = crate::parse_script(
11285            "LET $x: STRING = FOO()\n[os:macos] FUNC FOO(): STRING { RETURN \"guarded\" }\n",
11286            lower,
11287        )
11288        .expect("forward guarded ref must parse");
11289        assert!(
11290            matches!(&steps[1].kind, crate::StepKind::FuncDef { name, .. } if name == "FOO"),
11291            "guarded def kept, got: {:?}",
11292            steps[1].kind
11293        );
11294    }
11295}