Skip to main content

oxdock_parser/
parser.rs

1use crate::ast::{
2    ARCH_VALUES, Arg, Expr, Guard, GuardExpr, IoBinding, IoStream, MathOp, ModuleTable, Ns,
3    PipeTarget, Step, StepKind,
4};
5use crate::command::ArgType;
6use crate::constants::{
7    KEYWORD_EXPORT, KEYWORD_IMPORT, KEYWORD_INSPECT, KEYWORD_TYPE, MODULE_SEPARATOR,
8    SCRIPT_MODULE_NAME, qualify, split_qualified,
9};
10use crate::error::{ParseError, ParseResult, SpanContext};
11use crate::lexer::{
12    self, LanguageParser, RawToken, Rule, parse_pest_error, refine_span, span_for_line, span_of,
13};
14use pest::Parser as _;
15use pest::iterators::Pair;
16use std::cell::RefCell;
17use std::collections::{HashSet, VecDeque};
18
19/// Lowering context threaded through every grammar rule that can contain a
20/// block or a `FUNC` definition (issue #146).
21///
22/// This replaces the bare `lower: &dyn Fn` parameter the free lowering
23/// functions used to take. Bundling matters: `FUNC` duplicate and shadow
24/// validation needs the exact pest `SpanContext` at the definition site
25/// (post-parse AST walks only see the end of file), so the per-scope
26/// `FUNC` names ride alongside the dispatcher instead of a second pass.
27pub(super) struct LowerCtx<'a> {
28    /// Production command dispatcher (`lower_command`).
29    pub lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
30    /// Host-registered function names for parse-time shadow rejection.
31    /// Empty when hosts are unknown at parse time; the runtime
32    /// `define_func` guard still rejects those redefinitions.
33    pub reserved_names: &'a HashSet<String>,
34    /// Shared per-scope defined `FUNC` names. The `RefCell` lets every free
35    /// lowering function share one scope stack through plain `&LowerCtx`
36    /// references: `parse()` owns the stack plus the top-level scope, and
37    /// each `LowerCtx` is built fresh per statement so no `&self` borrow is
38    /// ever held across a `&mut self` call.
39    func_scopes: &'a RefCell<Vec<HashSet<String>>>,
40    /// Module provenance table for static call resolution.
41    modules: &'a ModuleTable,
42    /// Import frames mirroring scope structure, each holding imported
43    /// module names in `IMPORT` order. Chained lookup like var scopes:
44    /// inner frames see outer imports, frames drop on scope exit.
45    import_scopes: &'a RefCell<Vec<Vec<String>>>,
46}
47
48impl<'a> LowerCtx<'a> {
49    pub(super) fn new(
50        lower: &'a dyn Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
51        reserved_names: &'a HashSet<String>,
52        func_scopes: &'a RefCell<Vec<HashSet<String>>>,
53        modules: &'a ModuleTable,
54        import_scopes: &'a RefCell<Vec<Vec<String>>>,
55    ) -> Self {
56        Self {
57            lower,
58            reserved_names,
59            func_scopes,
60            modules,
61            import_scopes,
62        }
63    }
64
65    pub(super) fn enter_scope(&self) {
66        self.func_scopes.borrow_mut().push(HashSet::new());
67        self.import_scopes.borrow_mut().push(Vec::new());
68    }
69
70    pub(super) fn exit_scope(&self) {
71        self.func_scopes.borrow_mut().pop();
72        self.import_scopes.borrow_mut().pop();
73    }
74
75    /// Record a `FUNC` name in the innermost scope. Returns false when the
76    /// name was already defined in that same scope (nested shadowing of an
77    /// outer DSL name stays allowed).
78    pub(super) fn declare_func(&self, name: &str) -> bool {
79        let mut scopes = self.func_scopes.borrow_mut();
80        match scopes.last_mut() {
81            Some(current) => current.insert(name.to_string()),
82            None => true,
83        }
84    }
85
86    /// All `FUNC` names visible from the current position (every enclosing
87    /// scope, innermost last). Used by `REMOTE` self-containment: a body
88    /// call resolving to one of these without a same-body definition
89    /// would die on the guest with `UnknownFunction`.
90    pub(super) fn visible_func_names(&self) -> HashSet<String> {
91        self.func_scopes
92            .borrow()
93            .iter()
94            .flatten()
95            .cloned()
96            .collect()
97    }
98
99    /// Record `IMPORT`ed modules in the innermost import frame.
100    pub(super) fn import_modules(&self, ctx: &SpanContext, modules: &[String]) -> ParseResult<()> {
101        let mut known: Vec<String> = self.modules.modules.keys().cloned().collect();
102        known.sort();
103        for module in modules {
104            if !self.modules.modules.contains_key(module) {
105                return Err(ParseError::validation(
106                    KEYWORD_IMPORT,
107                    format!(
108                        "unknown module `{module}`; known modules: {}",
109                        known.join(", ")
110                    ),
111                    ctx,
112                ));
113            }
114            let mut frames = self.import_scopes.borrow_mut();
115            match frames.last_mut() {
116                Some(frame) => {
117                    if !frame.contains(module) {
118                        frame.push(module.clone());
119                    }
120                }
121                None => {
122                    frames.push(vec![module.clone()]);
123                }
124            }
125        }
126        Ok(())
127    }
128
129    /// Resolve a call name to its qualified `MODULE::NAME` form.
130    ///
131    /// Qualified names check module membership directly (opaque modules pass
132    /// through for runtime checking). Bare names resolve to `SCRIPT` defs
133    /// first, then to exactly one exporting module across all visible
134    /// import frames; zero or several matches fail. `INSPECT` passes
135    /// through untouched: it is a dedicated AST node, not a registry entry.
136    pub(super) fn resolve_call(&self, ctx: &SpanContext, name: &str) -> ParseResult<String> {
137        if let Some((module, base)) = split_qualified(name) {
138            if base == KEYWORD_INSPECT {
139                return Err(ParseError::validation(
140                    "FUNC",
141                    "INSPECT is a builtin keyword and cannot be module-qualified".to_string(),
142                    ctx,
143                ));
144            }
145            check_func_ident(ctx, module)?;
146            check_func_ident(ctx, base)?;
147            match self.modules.modules.get(module) {
148                None => {
149                    let mut known: Vec<String> = self.modules.modules.keys().cloned().collect();
150                    known.sort();
151                    Err(ParseError::validation(
152                        "FUNC",
153                        format!(
154                            "unknown module `{module}`; known modules: {}",
155                            known.join(", ")
156                        ),
157                        ctx,
158                    ))
159                }
160                Some(None) => Ok(name.to_string()),
161                Some(Some(funcs)) => {
162                    if funcs.functions.contains(base) {
163                        Ok(qualify(module, base))
164                    } else {
165                        Err(ParseError::validation(
166                            "FUNC",
167                            format!("unknown function `{module}::{base}`"),
168                            ctx,
169                        ))
170                    }
171                }
172            }
173        } else {
174            if name == KEYWORD_IMPORT || name == KEYWORD_EXPORT {
175                return Err(ParseError::validation(
176                    "FUNC",
177                    format!("`{name}` is a directive, not a function"),
178                    ctx,
179                ));
180            }
181            if name == KEYWORD_INSPECT {
182                return Ok(name.to_string());
183            }
184            let scopes = self.func_scopes.borrow();
185            if scopes.iter().rev().any(|scope| scope.contains(name)) {
186                return Ok(qualify(SCRIPT_MODULE_NAME, name));
187            }
188            drop(scopes);
189            // Distinct exporting modules across all visible import frames.
190            // Several matches fail instead of shadowing silently: qualify it.
191            let frames = self.import_scopes.borrow();
192            let mut known_matches: Vec<String> = Vec::new();
193            let mut opaque_matches: Vec<String> = Vec::new();
194            for frame in frames.iter() {
195                for module in frame {
196                    match self.modules.modules.get(module) {
197                        Some(Some(funcs)) => {
198                            if funcs.functions.contains(name) && !known_matches.contains(module) {
199                                known_matches.push(module.clone());
200                            }
201                        }
202                        Some(None) if !opaque_matches.contains(module) => {
203                            opaque_matches.push(module.clone());
204                        }
205                        Some(None) | None => {}
206                    }
207                }
208            }
209            drop(frames);
210            if known_matches.len() > 1 {
211                known_matches.sort();
212                return Err(ParseError::validation(
213                    "FUNC",
214                    format!(
215                        "ambiguous function `{name}`: exported by {}; qualify it (e.g. `{}::{name}`)",
216                        known_matches.join(", "),
217                        known_matches[0],
218                    ),
219                    ctx,
220                ));
221            }
222            if let Some(module) = known_matches.pop() {
223                return Ok(qualify(&module, name));
224            }
225            if opaque_matches.len() > 1 {
226                opaque_matches.sort();
227                return Err(ParseError::validation(
228                    "FUNC",
229                    format!(
230                        "ambiguous function `{name}`: imported opaque modules {}; qualify it",
231                        opaque_matches.join(", "),
232                    ),
233                    ctx,
234                ));
235            }
236            if let Some(module) = opaque_matches.pop() {
237                return Ok(qualify(&module, name));
238            }
239            // Nothing in scope: point at the fix when a known module
240            // exports the name but was never imported.
241            let mut exporters: Vec<String> = self
242                .modules
243                .modules
244                .iter()
245                .filter_map(|(module, funcs)| match funcs {
246                    Some(funcs) if funcs.functions.contains(name) => Some(module.clone()),
247                    _ => None,
248                })
249                .collect();
250            exporters.sort();
251            if let Some(first) = exporters.first() {
252                return Err(ParseError::validation(
253                    "FUNC",
254                    format!(
255                        "unknown function `{name}`; qualify it (`{first}::{name}`) or add `IMPORT [{first}]`"
256                    ),
257                    ctx,
258                ));
259            }
260            Err(ParseError::validation(
261                "FUNC",
262                format!("unknown function `{name}`"),
263                ctx,
264            ))
265        }
266    }
267
268    /// Base names exported by every known module. Backs the `FUNC` shadow
269    /// check alongside the flat reserved set.
270    pub(super) fn module_base_names(&self) -> HashSet<String> {
271        self.modules.reserved_base_names()
272    }
273
274    /// Snapshot of everything visible at this point: `FUNC` names unioned
275    /// across frames plus imports flattened outer-to-inner. Snippet
276    /// re-parses (async inner commands) seed their base frames with this so
277    /// lookup behaves identically; snippets never define, only read.
278    fn visible_snapshot(&self) -> (HashSet<String>, Vec<String>) {
279        let mut funcs = HashSet::new();
280        for scope in self.func_scopes.borrow().iter() {
281            funcs.extend(scope.iter().cloned());
282        }
283        let mut imports = Vec::new();
284        for frame in self.import_scopes.borrow().iter() {
285            for module in frame {
286                if !imports.contains(module) {
287                    imports.push(module.clone());
288                }
289            }
290        }
291        (funcs, imports)
292    }
293}
294
295#[derive(Clone)]
296struct ScopeFrame {
297    line_no: usize,
298    had_command: bool,
299}
300
301/// Parsed script with single-file `EXPORT` metadata. `steps` is the
302/// linear execution plan, `exports` the `EXPORT` names in source order,
303/// and `func_docs` maps top-level `FUNC` base names to (summary, docs)
304/// collected from the immediately preceding `#` comment block.
305#[derive(Debug, Clone, Default)]
306pub struct ParsedScript {
307    pub steps: Vec<Step>,
308    pub exports: Vec<String>,
309    pub func_docs: std::collections::HashMap<String, (String, String)>,
310}
311
312#[derive(Clone)]
313struct PendingIoBlock<'a> {
314    line_no: usize,
315    span: SpanContext<'a>,
316    bindings: Vec<IoBinding>,
317    guards: Option<GuardExpr>,
318}
319
320#[derive(Clone)]
321struct IoScopeFrame {
322    line_no: usize,
323    had_command: bool,
324    bindings: Vec<IoBinding>,
325    guards: Option<GuardExpr>,
326    /// Step index where this block's first command will land. Used to mark
327    /// scope boundaries so WITH_IO block bodies scope LET/ENV/WORKDIR like
328    /// every other braced block (only pipes leak).
329    first_step: usize,
330}
331
332#[derive(Clone, Copy, Debug)]
333enum BlockKind {
334    Guard,
335    Io,
336}
337
338#[derive(Default)]
339struct IoBindingSet {
340    stdin: Option<IoBinding>,
341    stdout: Option<IoBinding>,
342    stderr: Option<IoBinding>,
343}
344
345impl IoBindingSet {
346    fn insert(&mut self, binding: IoBinding) {
347        match binding.stream {
348            IoStream::Stdin => self.stdin = Some(binding),
349            IoStream::Stdout => self.stdout = Some(binding),
350            IoStream::Stderr => self.stderr = Some(binding),
351        }
352    }
353
354    fn into_vec(self) -> Vec<IoBinding> {
355        let mut out = Vec::new();
356        if let Some(binding) = self.stdin {
357            out.push(binding);
358        }
359        if let Some(binding) = self.stdout {
360            out.push(binding);
361        }
362        if let Some(binding) = self.stderr {
363            out.push(binding);
364        }
365        out
366    }
367}
368
369pub struct ScriptParser<'a, F: Fn(&str, Vec<Arg>) -> ParseResult<StepKind>> {
370    input: &'a str,
371    tokens: VecDeque<RawToken<'a>>,
372    steps: Vec<Step>,
373    guard_stack: Vec<Option<GuardExpr>>,
374    pending_guards: Option<GuardExpr>,
375    pending_inline_guards: Option<GuardExpr>,
376    pending_can_open_block: bool,
377    pending_scope_enters: usize,
378    scope_stack: Vec<ScopeFrame>,
379    pending_io_block: Option<PendingIoBlock<'a>>,
380    io_scope_stack: Vec<IoScopeFrame>,
381    block_stack: Vec<BlockKind>,
382    lower: F,
383    /// Host-registered function names, consulted by the post-parse scope
384    /// validation so `FUNC` cannot shadow runtime hosts. Empty when hosts
385    /// are unknown at parse time (e.g. compile-time macros); the runtime
386    /// `define_func` guard still rejects those redefinitions.
387    reserved_names: HashSet<String>,
388    /// Module provenance table for static call resolution. Empty when
389    /// modules are unknown at parse time; resolved calls stay qualified
390    /// only against this table.
391    modules: ModuleTable,
392    /// Seed for the base import frame, from an enclosing parse's visible
393    /// imports (snippet re-parses). Empty for top-level parses.
394    preseed_imports: Vec<String>,
395    /// Seed for the base `FUNC` scope, from an enclosing parse's visible
396    /// definitions (snippet re-parses). Empty for top-level parses.
397    preseed_funcs: HashSet<String>,
398    /// Single-file `EXPORT` names in source order. Top-level only;
399    /// validated against top-level `FUNC` definitions at end of parse.
400    exports: Vec<String>,
401}
402
403impl<'a, F: Fn(&str, Vec<Arg>) -> ParseResult<StepKind>> ScriptParser<'a, F> {
404    pub fn new(input: &'a str, lower: F) -> ParseResult<Self> {
405        Self::new_with_hosts(input, lower, HashSet::new())
406    }
407
408    pub fn new_with_hosts(
409        input: &'a str,
410        lower: F,
411        reserved_names: HashSet<String>,
412    ) -> ParseResult<Self> {
413        Self::new_with_modules(input, lower, reserved_names, ModuleTable::default())
414    }
415
416    pub fn new_with_modules(
417        input: &'a str,
418        lower: F,
419        reserved_names: HashSet<String>,
420        modules: ModuleTable,
421    ) -> ParseResult<Self> {
422        Self::new_with_preseed(
423            input,
424            lower,
425            reserved_names,
426            modules,
427            HashSet::new(),
428            Vec::new(),
429        )
430    }
431
432    pub fn new_with_preseed(
433        input: &'a str,
434        lower: F,
435        reserved_names: HashSet<String>,
436        modules: ModuleTable,
437        preseed_funcs: HashSet<String>,
438        preseed_imports: Vec<String>,
439    ) -> ParseResult<Self> {
440        let tokens = VecDeque::from(lexer::tokenize(input)?);
441        Ok(Self {
442            input,
443            tokens,
444            steps: Vec::new(),
445            guard_stack: vec![None],
446            pending_guards: None,
447            pending_inline_guards: None,
448            pending_can_open_block: false,
449            pending_scope_enters: 0,
450            scope_stack: Vec::new(),
451            pending_io_block: None,
452            io_scope_stack: Vec::new(),
453            block_stack: Vec::new(),
454            lower,
455            reserved_names,
456            modules,
457            preseed_funcs,
458            preseed_imports,
459            exports: Vec::new(),
460        })
461    }
462
463    /// Span for end of script errors (no failing token site).
464    fn eof_span(&self) -> SpanContext<'_> {
465        let lines = self.input.lines().count().max(1);
466        span_for_line(self.input, lines)
467    }
468
469    pub fn parse(self) -> ParseResult<Vec<Step>> {
470        Ok(self.parse_with_exports()?.steps)
471    }
472
473    /// Parse and return steps plus single-file `EXPORT` names and
474    /// preceding `#` doc comments for top-level `FUNC`s. Forward
475    /// references allowed: `EXPORT` may precede its `FUNC`s.
476    pub fn parse_with_exports(mut self) -> ParseResult<ParsedScript> {
477        // Function scope tracking rides alongside lowering (issue #146).
478        // `func_scopes` is a parse-local stack: the bottom is the top-level
479        // scope, `{`/`}` toggle nested ones below, and braced statement
480        // bodies push their own in `parse_block_elements_with_lower`. This
481        // mirrors the runtime `push_scope`/`pop_scope` boundaries, so
482        // duplicate and shadow errors fire at the definition line instead of
483        // end of file. Each `LowerCtx` is built fresh per statement from
484        // short borrows, so no `&self` borrow crosses a `&mut self` call.
485        let func_scopes: RefCell<Vec<HashSet<String>>> = RefCell::new(vec![HashSet::new()]);
486        // Import frames ride the same boundaries: the bottom is the top-level
487        // scope, blocks and `FUNC` bodies push their own, and exit drops
488        // them, so `IMPORT` applies from its line to the enclosing block end.
489        let import_scopes: RefCell<Vec<Vec<String>>> = RefCell::new(vec![Vec::new()]);
490        // Snippet re-parses seed their base frames with the enclosing
491        // parse's visible state so lookup behaves identically.
492        func_scopes.borrow_mut()[0].extend(self.preseed_funcs.iter().cloned());
493        import_scopes.borrow_mut()[0].extend(self.preseed_imports.iter().cloned());
494        while let Some(token) = self.tokens.pop_front() {
495            let step_index = self.steps.len();
496            if self.pending_io_block.is_some()
497                && !matches!(
498                    token,
499                    RawToken::BlockStart { .. }
500                        | RawToken::Command { .. }
501                        | RawToken::Instruction { .. }
502                        | RawToken::RunExec { .. }
503                )
504            {
505                let pending = self.pending_io_block.take().unwrap();
506                return Err(ParseError::structural(
507                    "with_io",
508                    format!(
509                        "line {}: WITH_IO block must be followed by '{{'",
510                        pending.line_no
511                    ),
512                    &pending.span,
513                ));
514            }
515            match token {
516                RawToken::Guard {
517                    pair,
518                    line_end,
519                    span,
520                } => {
521                    let span = span.with_step(step_index);
522                    let groups = parse_guard_line(&span, pair)?;
523                    self.handle_guard_token(line_end, groups)?;
524                }
525                RawToken::BlockStart { line_no, span } => {
526                    let span = span.with_step(step_index);
527                    self.start_block(&span, line_no)?;
528                    LowerCtx::new(
529                        &self.lower,
530                        &self.reserved_names,
531                        &func_scopes,
532                        &self.modules,
533                        &import_scopes,
534                    )
535                    .enter_scope();
536                }
537                RawToken::BlockEnd { line_no, span } => {
538                    let span = span.with_step(step_index);
539                    self.end_block(&span, line_no)?;
540                    LowerCtx::new(
541                        &self.lower,
542                        &self.reserved_names,
543                        &func_scopes,
544                        &self.modules,
545                        &import_scopes,
546                    )
547                    .exit_scope();
548                }
549                RawToken::Command {
550                    pair,
551                    line_no,
552                    span,
553                } => {
554                    let span = span.with_step(step_index);
555                    let lctx = LowerCtx::new(
556                        &self.lower,
557                        &self.reserved_names,
558                        &func_scopes,
559                        &self.modules,
560                        &import_scopes,
561                    );
562                    // IMPORT/EXPORT are lowering directives, not steps:
563                    // IMPORT updates the import frames, EXPORT records
564                    // single-file tool names. Both emit zero runtime
565                    // steps. Neither may be guarded: a guard here would
566                    // leak onto the following statement.
567                    if pair.as_rule() == Rule::import_statement {
568                        if self.pending_guards.is_some() || self.pending_inline_guards.is_some() {
569                            return Err(ParseError::structural(
570                                KEYWORD_IMPORT,
571                                "IMPORT cannot be guarded".to_string(),
572                                &span,
573                            ));
574                        }
575                        self.lower_import(&span, pair, &lctx)?;
576                        continue;
577                    }
578                    if pair.as_rule() == Rule::export_statement {
579                        if self.pending_guards.is_some() || self.pending_inline_guards.is_some() {
580                            return Err(ParseError::structural(
581                                KEYWORD_EXPORT,
582                                "EXPORT cannot be guarded".to_string(),
583                                &span,
584                            ));
585                        }
586                        self.lower_export(&span, pair)?;
587                        continue;
588                    }
589                    if pair.as_rule() == Rule::type_statement
590                        && (self.pending_guards.is_some() || self.pending_inline_guards.is_some())
591                    {
592                        return Err(ParseError::structural(
593                            KEYWORD_TYPE,
594                            "TYPE cannot be guarded".to_string(),
595                            &span,
596                        ));
597                    }
598                    let kind = parse_structural_command_with_lower(&span, pair, &lctx)?;
599                    self.handle_command_token(&span, line_no, kind)?;
600                }
601                RawToken::Instruction {
602                    pair,
603                    line_no,
604                    span,
605                } => {
606                    let span = span.with_step(step_index);
607                    let lctx = LowerCtx::new(
608                        &self.lower,
609                        &self.reserved_names,
610                        &func_scopes,
611                        &self.modules,
612                        &import_scopes,
613                    );
614                    // A `{` token on the same line after a keyword-led
615                    // instruction marks a fragmented block statement (issue
616                    // #215). The peek is free and the head name below
617                    // allocates only in that rare case, so valid scripts
618                    // pay nothing for the diagnostic fallback. The pair
619                    // always starts with its command name (grammar-ordered
620                    // first child: comments lex as separate elements and
621                    // compact `IF(` forms lex as calls), so the first
622                    // token is the keyword.
623                    let input = self.input;
624                    let opens_block = matches!(
625                        self.tokens.front(),
626                        Some(RawToken::BlockStart { line_no: next, .. }) if *next == line_no
627                    );
628                    let head_start = pair.as_span().start();
629                    let head_name = opens_block.then(|| {
630                        pair.as_str()
631                            .split_whitespace()
632                            .next()
633                            .unwrap_or("")
634                            .to_string()
635                    });
636                    let head_line = span.line;
637                    let head_step = span.step_index;
638                    let kind = self.lower_instruction(&span, pair, &lctx).map_err(|e| {
639                        let headed = e.with_span(&span);
640                        match head_name {
641                            Some(name) => refine_fragmented_block_error(
642                                input, head_start, &name, head_line, head_step, headed,
643                            ),
644                            None => headed,
645                        }
646                    })?;
647                    self.handle_command_token(&span, line_no, kind)?;
648                }
649                RawToken::RunExec {
650                    pair,
651                    line_no,
652                    span,
653                } => {
654                    let span = span.with_step(step_index);
655                    let lctx = LowerCtx::new(
656                        &self.lower,
657                        &self.reserved_names,
658                        &func_scopes,
659                        &self.modules,
660                        &import_scopes,
661                    );
662                    let kind = lower_run_exec_pair(&span, pair, &lctx)?;
663                    self.handle_command_token(&span, line_no, kind)?;
664                }
665            }
666        }
667
668        if let Some(pending) = self.pending_io_block.take() {
669            return Err(ParseError::structural(
670                "with_io",
671                format!(
672                    "line {}: WITH_IO block must be followed by '{{'",
673                    pending.line_no
674                ),
675                &pending.span,
676            ));
677        }
678
679        if self.guard_stack.len() != 1 {
680            let ctx = self.eof_span();
681            return Err(ParseError::structural(
682                "guard",
683                "unclosed guard block at end of script".to_string(),
684                &ctx,
685            ));
686        }
687        if self.pending_guards.is_some() {
688            let ctx = self.eof_span();
689            return Err(ParseError::structural(
690                "guard",
691                "guard declared on final lines without a following command".to_string(),
692                &ctx,
693            ));
694        }
695
696        if let Some(frame) = self.io_scope_stack.last() {
697            let ctx = span_for_line(self.input, frame.line_no);
698            return Err(ParseError::structural(
699                "with_io",
700                format!(
701                    "WITH_IO block starting on line {} was not closed",
702                    frame.line_no
703                ),
704                &ctx,
705            ));
706        }
707
708        // Validate `INHERIT_ENV` directives: only allowed in the prelude
709        // (before any other commands). Several may appear so
710        // platform-specific names ride guarded lines
711        // (`[family:windows] INHERIT_ENV [SystemRoot]`); each guarded
712        // line runs only when its guard passes, like any other step.
713        {
714            let ctx = self.eof_span();
715            let mut seen_non_prelude = false;
716            for step in &self.steps {
717                match &step.kind {
718                    StepKind::InheritEnv { .. } => {
719                        if seen_non_prelude {
720                            return Err(ParseError::structural(
721                                "inherit_env",
722                                "INHERIT_ENV must appear before any other commands".to_string(),
723                                &ctx,
724                            ));
725                        }
726                    }
727                    kind => {
728                        if contains_inherit_env(kind) {
729                            return Err(ParseError::structural(
730                                "inherit_env",
731                                "INHERIT_ENV cannot be nested inside other commands".to_string(),
732                                &ctx,
733                            ));
734                        }
735                        seen_non_prelude = true;
736                    }
737                }
738            }
739        }
740
741        // Validate `COPY --from-host` / `--to-host` placement: transfer
742        // declarations are only meaningful inside a `REMOTE` body, where
743        // the session hoists them around execution. Anywhere else they
744        // would silently behave as local copies, so they fail fast.
745        {
746            let ctx = self.eof_span();
747            validate_remote_copy_placement(&self.steps, &ctx)?;
748        }
749
750        // Validate `EXPORT` names at end of parse. Forward references
751        // are allowed (EXPORT may precede its FUNCs), so this runs
752        // against the completed top-level scope. Bare names must match
753        // a top-level `FUNC`; qualified `MOD::NAME` names must match a
754        // known module member (opaque modules skip the member check;
755        // the runtime registry resolves them or fails serving).
756        // Duplicates are rejected at the EXPORT site.
757        {
758            let top: HashSet<String> = func_scopes.borrow()[0].clone();
759            for name in &self.exports {
760                let valid = match name.split_once("::") {
761                    None => top.contains(name),
762                    Some((module, base)) if module == SCRIPT_MODULE_NAME => top.contains(base),
763                    Some((module, base)) => match self.modules.modules.get(module) {
764                        None => false,
765                        Some(None) => true,
766                        Some(Some(funcs)) => funcs.functions.contains(base),
767                    },
768                };
769                if !valid {
770                    let ctx = self.eof_span();
771                    return Err(ParseError::validation(
772                        KEYWORD_EXPORT,
773                        format!(
774                            "EXPORT `{name}` does not match any top-level FUNC or known module member"
775                        ),
776                        &ctx,
777                    ));
778                }
779            }
780        }
781
782        let func_docs = collect_func_docs(self.input, &self.steps);
783        let exports = std::mem::take(&mut self.exports);
784        let steps = std::mem::take(&mut self.steps);
785        Ok(ParsedScript {
786            steps,
787            exports,
788            func_docs,
789        })
790    }
791
792    fn lower_instruction(
793        &self,
794        ctx: &SpanContext,
795        pair: Pair<Rule>,
796        lctx: &LowerCtx,
797    ) -> ParseResult<StepKind> {
798        lower_instruction_pair(ctx, pair, lctx)
799    }
800
801    /// Lower an `IMPORT` statement: update the import frames, emit nothing.
802    /// Guards are rejected by the caller: with zero steps there is nothing
803    /// to attach them to, so they would leak onto the next statement.
804    fn lower_import(
805        &self,
806        ctx: &SpanContext,
807        pair: Pair<Rule>,
808        lctx: &LowerCtx,
809    ) -> ParseResult<()> {
810        lower_import_statement(ctx, pair, lctx)
811    }
812
813    /// Lower an `EXPORT` statement: record script tool names plus
814    /// qualified host names in source order, emit nothing. Guards are
815    /// rejected by the caller. Duplicates fail here; unknown names fail
816    /// at end of parse so forward references (`EXPORT` before `FUNC`)
817    /// keep working.
818    fn lower_export(&mut self, ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<()> {
819        let mut names = Vec::new();
820        for inner in pair.into_inner() {
821            match inner.as_rule() {
822                Rule::export_list => {
823                    for item in inner.into_inner() {
824                        if item.as_rule() == Rule::export_ident {
825                            names.push(item.as_str().to_string());
826                        }
827                    }
828                }
829                Rule::export_ident => names.push(inner.as_str().to_string()),
830                _ => {}
831            }
832        }
833        if names.is_empty() {
834            return Err(ParseError::validation(
835                KEYWORD_EXPORT,
836                "EXPORT requires at least one function name, e.g. `EXPORT FOO` or `EXPORT [FOO, BAR]`"
837                    .to_string(),
838                ctx,
839            ));
840        }
841        for name in names {
842            for part in name.split("::") {
843                check_func_ident(ctx, part)?;
844            }
845            if self.exports.contains(&name) {
846                return Err(ParseError::validation(
847                    KEYWORD_EXPORT,
848                    format!("duplicate EXPORT `{name}`"),
849                    ctx,
850                ));
851            }
852            self.exports.push(name);
853        }
854        Ok(())
855    }
856
857    fn handle_guard_token(&mut self, line_end: usize, expr: GuardExpr) -> ParseResult<()> {
858        if let Some(RawToken::Command { line_no, .. }) = self.tokens.front()
859            && *line_no == line_end
860        {
861            self.pending_inline_guards = Some(expr);
862            self.pending_can_open_block = false;
863            return Ok(());
864        }
865        self.stash_pending_guard(expr);
866        self.pending_can_open_block = true;
867        Ok(())
868    }
869
870    fn handle_command_token(
871        &mut self,
872        ctx: &SpanContext<'a>,
873        line_no: usize,
874        kind: StepKind,
875    ) -> ParseResult<()> {
876        let inline = self.pending_inline_guards.take();
877        self.handle_command(ctx, line_no, kind, inline)
878    }
879
880    fn stash_pending_guard(&mut self, guard: GuardExpr) {
881        self.pending_guards = Some(if let Some(existing) = self.pending_guards.take() {
882            GuardExpr::all(vec![existing, guard])
883        } else {
884            guard
885        });
886    }
887
888    fn start_guard_block_from_pending(
889        &mut self,
890        ctx: &SpanContext,
891        line_no: usize,
892    ) -> ParseResult<()> {
893        let guards = self.pending_guards.take().ok_or_else(|| {
894            ParseError::structural(
895                "guard",
896                format!("line {}: '{{' without a pending guard", line_no),
897                ctx,
898            )
899        })?;
900        if !self.pending_can_open_block {
901            return Err(ParseError::structural(
902                "guard",
903                format!("line {}: '{{' must directly follow a guard", line_no),
904                ctx,
905            ));
906        }
907        self.pending_can_open_block = false;
908        self.enter_guard_block(guards, line_no)
909    }
910
911    fn enter_guard_block(&mut self, guard: GuardExpr, line_no: usize) -> ParseResult<()> {
912        let composed = if let Some(pending) = self.pending_guards.take() {
913            GuardExpr::all(vec![pending, guard])
914        } else {
915            guard
916        };
917        let parent = self.guard_stack.last().cloned().unwrap_or(None);
918        let next = and_guard_exprs(parent, Some(composed));
919        self.guard_stack.push(next);
920        self.scope_stack.push(ScopeFrame {
921            line_no,
922            had_command: false,
923        });
924        self.pending_scope_enters += 1;
925        Ok(())
926    }
927
928    fn begin_io_block(
929        &mut self,
930        ctx: &SpanContext<'a>,
931        line_no: usize,
932        bindings: Vec<IoBinding>,
933        guards: Option<GuardExpr>,
934    ) -> ParseResult<()> {
935        if self.pending_io_block.is_some() {
936            return Err(ParseError::structural(
937                "with_io",
938                format!(
939                    "line {}: previous WITH_IO block is still waiting for '{{'",
940                    line_no
941                ),
942                ctx,
943            ));
944        }
945        self.pending_io_block = Some(PendingIoBlock {
946            line_no,
947            span: ctx.clone(),
948            bindings,
949            guards,
950        });
951        Ok(())
952    }
953
954    fn start_block(&mut self, ctx: &SpanContext, line_no: usize) -> ParseResult<()> {
955        if let Some(pending) = self.pending_io_block.take() {
956            self.block_stack.push(BlockKind::Io);
957            self.io_scope_stack.push(IoScopeFrame {
958                line_no: pending.line_no,
959                had_command: false,
960                bindings: pending.bindings,
961                guards: pending.guards,
962                first_step: self.steps.len(),
963            });
964            Ok(())
965        } else {
966            self.start_guard_block_from_pending(ctx, line_no)?;
967            self.block_stack.push(BlockKind::Guard);
968            Ok(())
969        }
970    }
971
972    fn end_block(&mut self, ctx: &SpanContext, line_no: usize) -> ParseResult<()> {
973        let kind = self.block_stack.pop().ok_or_else(|| {
974            ParseError::structural("block", format!("line {}: unexpected '}}'", line_no), ctx)
975        })?;
976        match kind {
977            BlockKind::Guard => self.end_guard_block(ctx, line_no),
978            BlockKind::Io => self.end_io_block(ctx, line_no),
979        }
980    }
981
982    fn end_guard_block(&mut self, ctx: &SpanContext, line_no: usize) -> ParseResult<()> {
983        if self.guard_stack.len() == 1 {
984            return Err(ParseError::structural(
985                "guard",
986                format!("line {}: unexpected '}}'", line_no),
987                ctx,
988            ));
989        }
990        if self.pending_guards.is_some() {
991            return Err(ParseError::structural(
992                "guard",
993                format!(
994                    "line {}: guard declared immediately before '}}' without a command",
995                    line_no
996                ),
997                ctx,
998            ));
999        }
1000        let frame = self.scope_stack.last().cloned().ok_or_else(|| {
1001            ParseError::structural(
1002                "guard",
1003                format!("line {}: scope stack underflow", line_no),
1004                ctx,
1005            )
1006        })?;
1007        if !frame.had_command {
1008            return Err(ParseError::structural(
1009                "guard",
1010                format!(
1011                    "line {}: guard block starting on line {} must contain at least one command",
1012                    line_no, frame.line_no
1013                ),
1014                ctx,
1015            ));
1016        }
1017        let step = self.steps.last_mut().ok_or_else(|| {
1018            ParseError::structural(
1019                "guard",
1020                format!("line {}: guard block closed without any commands", line_no),
1021                ctx,
1022            )
1023        })?;
1024        step.scope_exit += 1;
1025        self.scope_stack.pop();
1026        self.guard_stack.pop();
1027        Ok(())
1028    }
1029
1030    fn end_io_block(&mut self, ctx: &SpanContext, line_no: usize) -> ParseResult<()> {
1031        let frame = self.io_scope_stack.pop().ok_or_else(|| {
1032            ParseError::structural("with_io", format!("line {}: unexpected '}}'", line_no), ctx)
1033        })?;
1034        if !frame.had_command {
1035            return Err(ParseError::structural(
1036                "with_io",
1037                format!(
1038                    "line {}: WITH_IO block starting on line {} must contain at least one command",
1039                    line_no, frame.line_no
1040                ),
1041                ctx,
1042            ));
1043        }
1044        // WITH_IO block bodies are lexical scopes like guard blocks: mark
1045        // scope boundaries so LET/ENV/WORKDIR/WORKSPACE revert on exit.
1046        // Pipe registrations live in ExecIo and are unaffected (they leak).
1047        if self.steps.len() > frame.first_step {
1048            self.steps[frame.first_step].scope_enter += 1;
1049            if let Some(last) = self.steps.last_mut() {
1050                last.scope_exit += 1;
1051            }
1052        }
1053        Ok(())
1054    }
1055
1056    fn guard_context(&mut self, inline: Option<GuardExpr>) -> Option<GuardExpr> {
1057        let mut context = self.guard_stack.last().cloned().unwrap_or(None);
1058        if let Some(pending) = self.pending_guards.take() {
1059            context = and_guard_exprs(context, Some(pending));
1060            self.pending_can_open_block = false;
1061        }
1062        if let Some(inline_guard) = inline {
1063            context = and_guard_exprs(context, Some(inline_guard));
1064        }
1065        context
1066    }
1067
1068    fn handle_command(
1069        &mut self,
1070        ctx: &SpanContext<'a>,
1071        line_no: usize,
1072        kind: StepKind,
1073        inline_guards: Option<GuardExpr>,
1074    ) -> ParseResult<()> {
1075        if let StepKind::WithIoBlock { bindings } = kind {
1076            let guards = self.guard_context(inline_guards);
1077            self.begin_io_block(ctx, line_no, bindings, guards)?;
1078            return Ok(());
1079        }
1080
1081        let guards = self.guard_context(inline_guards);
1082        let guards = self.apply_io_guards(guards);
1083        let scope_enter = self.pending_scope_enters;
1084        self.pending_scope_enters = 0;
1085        for frame in self.scope_stack.iter_mut() {
1086            frame.had_command = true;
1087        }
1088        for frame in self.io_scope_stack.iter_mut() {
1089            frame.had_command = true;
1090        }
1091        let kind = self.apply_io_defaults(kind);
1092        self.steps.push(Step {
1093            guard: guards,
1094            kind,
1095            scope_enter,
1096            scope_exit: 0,
1097        });
1098        Ok(())
1099    }
1100
1101    fn apply_io_defaults(&self, kind: StepKind) -> StepKind {
1102        let defaults = self.current_io_defaults();
1103        if defaults.is_empty() {
1104            return kind;
1105        }
1106        match kind {
1107            StepKind::WithIo { bindings, cmd } => StepKind::WithIo {
1108                bindings: merge_bindings(&defaults, &bindings),
1109                cmd,
1110            },
1111            other => StepKind::WithIo {
1112                bindings: defaults,
1113                cmd: Box::new(other),
1114            },
1115        }
1116    }
1117
1118    fn current_io_defaults(&self) -> Vec<IoBinding> {
1119        if self.io_scope_stack.is_empty() {
1120            return Vec::new();
1121        }
1122        let mut set = IoBindingSet::default();
1123        for frame in &self.io_scope_stack {
1124            for binding in &frame.bindings {
1125                set.insert(binding.clone());
1126            }
1127        }
1128        set.into_vec()
1129    }
1130
1131    fn apply_io_guards(&self, guard: Option<GuardExpr>) -> Option<GuardExpr> {
1132        self.io_scope_stack.iter().fold(guard, |acc, frame| {
1133            and_guard_exprs(acc, frame.guards.clone())
1134        })
1135    }
1136}
1137
1138pub fn parse_script(
1139    input: &str,
1140    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
1141) -> ParseResult<Vec<Step>> {
1142    ScriptParser::new(input, lower)?.parse()
1143}
1144
1145/// Parse a snippet with an enclosing parse's visible scope state, so
1146/// re-parsed inner commands (async bodies) resolve calls identically.
1147/// The snippet never defines, only reads: seeds affect lookup alone.
1148pub fn parse_script_with_preseed(
1149    input: &str,
1150    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
1151    reserved_names: HashSet<String>,
1152    modules: ModuleTable,
1153    preseed_funcs: HashSet<String>,
1154    preseed_imports: Vec<String>,
1155) -> ParseResult<Vec<Step>> {
1156    ScriptParser::new_with_preseed(
1157        input,
1158        lower,
1159        reserved_names,
1160        modules,
1161        preseed_funcs,
1162        preseed_imports,
1163    )?
1164    .parse()
1165}
1166
1167/// Parse with a module provenance table so calls resolve statically:
1168/// qualified `MODULE::NAME` checks membership, bare `NAME` resolves through
1169/// `SCRIPT` definitions and `IMPORT`ed modules, and anything else fails at
1170/// parse time instead of at runtime.
1171pub fn parse_script_with_modules(
1172    input: &str,
1173    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
1174    reserved_names: HashSet<String>,
1175    modules: ModuleTable,
1176) -> ParseResult<Vec<Step>> {
1177    Ok(parse_script_with_modules_and_exports(input, lower, reserved_names, modules)?.steps)
1178}
1179
1180/// Parse with modules plus single-file `EXPORT` metadata and `#` doc
1181/// comments for top-level `FUNC`s. Used by the MCP host; the linear
1182/// runner keeps using `parse_script_with_modules` and ignores exports.
1183pub fn parse_script_with_modules_and_exports(
1184    input: &str,
1185    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
1186    reserved_names: HashSet<String>,
1187    modules: ModuleTable,
1188) -> ParseResult<ParsedScript> {
1189    ScriptParser::new_with_modules(input, lower, reserved_names, modules)?.parse_with_exports()
1190}
1191
1192/// Parse without modules plus `EXPORT` metadata. Used by tests and
1193/// tooling that lower with the shared mock.
1194pub fn parse_script_with_exports(
1195    input: &str,
1196    lower: impl Fn(&str, Vec<Arg>) -> ParseResult<StepKind>,
1197) -> ParseResult<ParsedScript> {
1198    ScriptParser::new(input, lower)?.parse_with_exports()
1199}
1200
1201/// Collect `(summary, docs)` for top-level `FUNC`s from the immediately
1202/// preceding `#` comment block. Scoped to FUNC definition lines only:
1203/// the global lexer still discards `#` everywhere else, so no grammar
1204/// rule changes and no blast radius. A blank line breaks the block.
1205fn collect_func_docs(
1206    input: &str,
1207    steps: &[Step],
1208) -> std::collections::HashMap<String, (String, String)> {
1209    use std::collections::{HashMap, HashSet};
1210    let lines: Vec<&str> = input.lines().collect();
1211    // Top-level FUNC definition lines keyed by base name. Brace depth
1212    // tracks nesting so only depth-0 `FUNC` lines count; the first
1213    // occurrence wins because same-scope duplicates fail at lowering.
1214    let mut def_lines: HashMap<String, usize> = HashMap::new();
1215    let mut seen: HashSet<String> = HashSet::new();
1216    let mut depth: usize = 0;
1217    for (idx, line) in lines.iter().enumerate() {
1218        let trimmed = line.trim_start();
1219        let is_comment = trimmed.starts_with('#');
1220        let is_guard_only = trimmed.starts_with('[');
1221        if !is_comment
1222            && !is_guard_only
1223            && let Some(rest) = strip_func_head(trimmed)
1224            && depth == 0
1225            && !seen.contains(&rest)
1226        {
1227            seen.insert(rest.clone());
1228            def_lines.insert(rest, idx + 1);
1229        }
1230        if !is_comment {
1231            for ch in line.chars() {
1232                if ch == '{' {
1233                    depth = depth.saturating_add(1);
1234                } else if ch == '}' {
1235                    depth = depth.saturating_sub(1);
1236                }
1237            }
1238        }
1239    }
1240    let mut out: HashMap<String, (String, String)> = HashMap::new();
1241    for step in steps {
1242        if let StepKind::FuncDef { name, .. } = &step.kind
1243            && !out.contains_key(name)
1244            && let Some(&line_no) = def_lines.get(name)
1245            && let Some((summary, docs)) = docs_above(&lines, line_no)
1246        {
1247            out.insert(name.clone(), (summary, docs));
1248        }
1249    }
1250    out
1251}
1252
1253/// Strip a `FUNC NAME` head, returning the bare uppercase name. Rejects
1254/// qualified or malformed heads by returning `None`.
1255fn strip_func_head(trimmed: &str) -> Option<String> {
1256    let rest = trimmed.strip_prefix("FUNC")?;
1257    let after = rest.strip_prefix([' ', '\t'])?;
1258    if after.is_empty() {
1259        return None;
1260    }
1261    let name: String = after
1262        .chars()
1263        .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
1264        .collect();
1265    if name.is_empty()
1266        || !name
1267            .bytes()
1268            .all(|b| b.is_ascii_uppercase() || b == b'_' || b.is_ascii_digit())
1269    {
1270        return None;
1271    }
1272    if name.starts_with(|c: char| c.is_ascii_digit()) {
1273        return None;
1274    }
1275    Some(name)
1276}
1277
1278/// Read the contiguous `#` block immediately above `line_no` (1-based).
1279/// Returns `(summary, docs)` with `#` prefixes stripped. `None` when no
1280/// comment block is adjacent. Exported through unit tests via steps.
1281fn docs_above(lines: &[&str], line_no: usize) -> Option<(String, String)> {
1282    if line_no <= 1 {
1283        return None;
1284    }
1285    let mut block: Vec<String> = Vec::new();
1286    let mut idx = line_no - 1;
1287    while idx > 0 {
1288        idx -= 1;
1289        let trimmed = lines[idx].trim_start();
1290        if trimmed.is_empty() {
1291            break;
1292        }
1293        if let Some(body) = trimmed.strip_prefix('#') {
1294            let text = body.strip_prefix(' ').unwrap_or(body);
1295            block.push(text.to_string());
1296        } else {
1297            break;
1298        }
1299        if idx == 0 {
1300            break;
1301        }
1302    }
1303    if block.is_empty() {
1304        return None;
1305    }
1306    block.reverse();
1307    let summary = block.first().cloned().unwrap_or_default();
1308    let docs = block.join("\n");
1309    Some((summary, docs))
1310}
1311
1312/// Parse one expression from source text with an empty module scope, for
1313/// tooling that shows lowering without running (docs demos, explain output).
1314/// No imports exist here, so bare function calls fail and qualified calls
1315/// fail against the empty table; only `INSPECT` passes through untouched.
1316/// Arithmetic, comparison, variables, env reads, keypaths, and literals
1317/// lower normally, with literal only subtrees folded before flattening.
1318pub fn parse_expression_str(input: &str) -> ParseResult<Expr> {
1319    use pest::Parser;
1320    // `Rule::expr` leaves trailing whitespace and newlines unconsumed, so
1321    // lex the trimmed text and measure the span against it: otherwise padded
1322    // but valid input fails the full consumption check below.
1323    let trimmed = input.trim();
1324    let pairs = lexer::LanguageParser::parse(Rule::expr, trimmed).map_err(parse_pest_error)?;
1325    let pair = pairs.into_iter().next().ok_or_else(|| {
1326        ParseError::structural(
1327            "expr",
1328            "empty expression".to_string(),
1329            &span_for_line(trimmed, 1),
1330        )
1331    })?;
1332    if pair.as_span().end() != trimmed.len() {
1333        return Err(ParseError::structural(
1334            "expr",
1335            format!("invalid expression {input:?}"),
1336            &span_of(&pair, trimmed),
1337        ));
1338    }
1339    let ctx = span_of(&pair, trimmed);
1340    let reserved = HashSet::new();
1341    let func_scopes = RefCell::new(vec![HashSet::new()]);
1342    let modules = ModuleTable {
1343        modules: std::collections::HashMap::new(),
1344    };
1345    let import_scopes = RefCell::new(vec![Vec::new()]);
1346    let lower = crate::commands::lower_command as fn(&str, Vec<Arg>) -> ParseResult<StepKind>;
1347    let lctx = LowerCtx::new(&lower, &reserved, &func_scopes, &modules, &import_scopes);
1348    parse_expr(&ctx, &lctx, pair)
1349}
1350
1351pub fn parse_guard_expr_str(input: &str) -> ParseResult<GuardExpr> {
1352    use pest::Parser;
1353    let pairs = lexer::LanguageParser::parse(Rule::guard_expr, input).map_err(parse_pest_error)?;
1354    let pair = pairs.into_iter().next().ok_or_else(|| {
1355        ParseError::structural("guard", "empty guard".to_string(), &span_for_line(input, 1))
1356    })?;
1357    let ctx = span_of(&pair, input);
1358    parse_guard_expr(&ctx, pair)
1359}
1360
1361fn and_guard_exprs(left: Option<GuardExpr>, right: Option<GuardExpr>) -> Option<GuardExpr> {
1362    match (left, right) {
1363        (None, None) => None,
1364        (Some(expr), None) | (None, Some(expr)) => Some(expr),
1365        (Some(lhs), Some(rhs)) => Some(GuardExpr::all(vec![lhs, rhs])),
1366    }
1367}
1368
1369/// Candidate structural rules for a fragmented keyword head (issue #215).
1370/// Each rule opens its `block` on the head line and may nest further
1371/// blocks, so re-parsing the tail with it surfaces pest's deepest inner
1372/// failure. Only rules with a demonstrated refinement are listed: every
1373/// other block shape (`WITH_IO` bodies, `LET` forms, inline `ASYNC`
1374/// commands) resolves through dedicated token paths or fails on its head
1375/// line, so no candidate there can ever report past the head. `ELSE`
1376/// lists both clauses; furthest failure wins, exactly like PEG recovery.
1377/// A candidate that matches the tail reports `Ok`: full consumption means
1378/// the head is structurally sound and the lowering error stands, while a
1379/// partial prefix match cannot exonerate the head, so evaluation
1380/// continues instead of aborting.
1381fn block_fragment_candidates(name: &str) -> Option<&'static [Rule]> {
1382    match name {
1383        "IF" => Some(&[Rule::if_statement]),
1384        "WHILE" => Some(&[Rule::while_statement]),
1385        "FOR" => Some(&[Rule::for_statement]),
1386        "FUNC" => Some(&[Rule::func_def]),
1387        "TIMEOUT" => Some(&[Rule::timeout_statement]),
1388        "ISOLATED" => Some(&[Rule::isolated_statement]),
1389        "REMOTE" => Some(&[Rule::remote_statement]),
1390        "ASYNC" => Some(&[Rule::async_statement_block]),
1391        "ELSE" => Some(&[Rule::else_if_clause, Rule::else_clause]),
1392        _ => None,
1393    }
1394}
1395
1396/// Replace a fragmented block head error with a readable inner diagnostic
1397/// (issue #215). The caller has already verified a `{` token on the head
1398/// line, so a missing opener cannot misattribute here, and only failures
1399/// past the head line refine, which keeps single-line diagnostics
1400/// byte-identical. The message names the block and its opener line; the
1401/// full pest expected set stays attached as structured data instead of
1402/// leaking grammar rule names into user-facing text.
1403fn refine_fragmented_block_error(
1404    input: &str,
1405    start: usize,
1406    name: &str,
1407    head_line: usize,
1408    step_index: Option<usize>,
1409    outer: ParseError,
1410) -> ParseError {
1411    if head_line == 0 || start >= input.len() {
1412        return outer;
1413    }
1414    let Some(candidates) = block_fragment_candidates(name) else {
1415        return outer;
1416    };
1417    let tail = &input[start..];
1418    let mut best: Option<(usize, usize, usize, Vec<String>)> = None;
1419    for rule in candidates {
1420        match LanguageParser::parse(*rule, tail) {
1421            Ok(mut pairs) => {
1422                if pairs
1423                    .next()
1424                    .is_some_and(|pair| pair.as_span().end() == tail.len())
1425                {
1426                    return outer;
1427                }
1428            }
1429            Err(pest_err) => {
1430                let (rel_line, rel_start, rel_end) =
1431                    crate::lexer::pest_span_parts(&pest_err.line_col);
1432                if rel_line == 1 {
1433                    continue;
1434                }
1435                let (_, expected) = crate::lexer::pest_variant_parts(&pest_err.variant);
1436                let abs_line = head_line + rel_line - 1;
1437                let deeper = match &best {
1438                    None => true,
1439                    Some((best_line, best_col, _, _)) => {
1440                        (abs_line, rel_start) > (*best_line, *best_col)
1441                    }
1442                };
1443                if deeper {
1444                    best = Some((abs_line, rel_start, rel_end, expected));
1445                }
1446            }
1447        }
1448    }
1449    let Some((abs_line, abs_start, abs_end, expected)) = best else {
1450        return outer;
1451    };
1452    // One short-circuiting pass: a position past the final line is the
1453    // empty terminal line of a trailing newline, rendered exactly like
1454    // top-level end-of-input diagnostics. That position means the input
1455    // ended inside the block, so the block is unclosed; a failure on a
1456    // content line is an inner syntax error. Either way the header stays
1457    // human: block keyword plus opener line. The pest expected set rides
1458    // along as structured data only.
1459    let found = input.lines().nth(abs_line.saturating_sub(1));
1460    let terminal = found.is_none();
1461    let eff_text = found.unwrap_or("").to_string();
1462    let header = if terminal {
1463        format!("unclosed `{name}` block opened on line {head_line}")
1464    } else {
1465        format!("syntax error in `{name}` block opened on line {head_line}")
1466    };
1467    crate::lexer::pest_error_at(&header, expected, abs_line, abs_start, abs_end, eff_text)
1468        .with_step(step_index.unwrap_or(0))
1469}
1470
1471fn merge_bindings(defaults: &[IoBinding], overrides: &[IoBinding]) -> Vec<IoBinding> {
1472    let mut set = IoBindingSet::default();
1473    for binding in defaults {
1474        set.insert(binding.clone());
1475    }
1476    for binding in overrides {
1477        set.insert(binding.clone());
1478    }
1479    set.into_vec()
1480}
1481
1482/// Reject `COPY --from-host` / `--to-host` outside `REMOTE` bodies.
1483/// Transfer declarations only mean something where a session hoists them;
1484/// anywhere else they would silently behave as local copies.
1485fn validate_remote_copy_placement(steps: &[Step], ctx: &SpanContext) -> ParseResult<()> {
1486    fn visit_kind(kind: &StepKind, in_remote: bool, ctx: &SpanContext) -> ParseResult<()> {
1487        if let StepKind::Copy {
1488            from_host, to_host, ..
1489        } = kind
1490            && (*from_host || *to_host)
1491            && !in_remote
1492        {
1493            return Err(ParseError::structural(
1494                "copy",
1495                "COPY --from-host and --to-host are only valid inside a REMOTE block".to_string(),
1496                ctx,
1497            ));
1498        }
1499        let child_remote = in_remote || matches!(kind, StepKind::RemoteBlock { .. });
1500        let mut result = Ok(());
1501        kind.walk_child_kinds(&mut |child| {
1502            if result.is_ok() {
1503                result = visit_kind(child, child_remote, ctx);
1504            }
1505        });
1506        result
1507    }
1508    for step in steps {
1509        visit_kind(&step.kind, false, ctx)?;
1510    }
1511    Ok(())
1512}
1513
1514fn contains_inherit_env(kind: &StepKind) -> bool {
1515    if matches!(kind, StepKind::InheritEnv { .. }) {
1516        return true;
1517    }
1518    let mut found = false;
1519    kind.walk_child_kinds(&mut |child| {
1520        found = found || contains_inherit_env(child);
1521    });
1522    found
1523}
1524
1525/// True when bindings reroute stdout into a named pipe. A `LET`-capture owns
1526/// the step's stdout, so combining the two is a parse error.
1527fn has_stdout_pipe(bindings: &[IoBinding]) -> bool {
1528    bindings
1529        .iter()
1530        .any(|b| b.stream == IoStream::Stdout && b.pipe.is_some())
1531}
1532
1533/// Reject async machinery inside a capture body: background tasks are
1534/// captured via `LET $o: STRING = AWAIT $t`, never inline.
1535fn reject_async_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
1536    let bad = match kind {
1537        StepKind::AsyncBlock { .. }
1538        | StepKind::AssignAsync { .. }
1539        | StepKind::Await { .. }
1540        | StepKind::AwaitCapture { .. }
1541        | StepKind::Cancel { .. } => true,
1542        _ => {
1543            let mut bad = false;
1544            kind.walk_child_kinds(&mut |child| {
1545                bad = bad || reject_async_in_capture(ctx, child).is_err();
1546            });
1547            bad
1548        }
1549    };
1550    if bad {
1551        return Err(ParseError::structural("let", "LET capture cannot run ASYNC/AWAIT/CANCEL inline; use LET $t: HANDLE = ASYNC ... then LET $o: STRING = AWAIT $t".to_string(), ctx));
1552    }
1553    Ok(())
1554}
1555
1556/// Reject `WITH_IO [stdout=$var]` anywhere inside a capture body: the
1557/// capture sink owns stdout.
1558fn reject_pipe_stdout_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
1559    if let StepKind::WithIo { bindings, .. } = kind
1560        && has_stdout_pipe(bindings)
1561    {
1562        return Err(ParseError::structural(
1563            "let",
1564            "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
1565                .to_string(),
1566            ctx,
1567        ));
1568    }
1569    let mut result = Ok(());
1570    kind.walk_child_kinds(&mut |child| {
1571        if result.is_ok() {
1572            result = reject_pipe_stdout_in_capture(ctx, child);
1573        }
1574    });
1575    result
1576}
1577
1578/// Re-parse raw RHS text as an expression (fallback when the `LET` RHS lead
1579/// token is not a known command). Requires the expression to consume the
1580/// full text so `LET $x: STRING = FOO bar` stays an error instead of binding `FOO`.
1581fn parse_expr_str(ctx: &SpanContext, lctx: &LowerCtx, text: &str) -> ParseResult<Expr> {
1582    use pest::Parser;
1583    let mut pairs = lexer::LanguageParser::parse(Rule::expr, text).map_err(parse_pest_error)?;
1584    let pair = pairs.next().ok_or_else(|| {
1585        ParseError::validation("LET", "LET requires an expression".to_string(), ctx)
1586    })?;
1587    if pair.as_span().end() != text.len() {
1588        return Err(ParseError::structural(
1589            "expr",
1590            format!("invalid LET expression {text:?}"),
1591            ctx,
1592        ));
1593    }
1594    parse_expr(ctx, lctx, pair)
1595}
1596
1597fn parse_structural_command_with_lower(
1598    ctx: &SpanContext,
1599    pair: Pair<Rule>,
1600    lctx: &LowerCtx,
1601) -> ParseResult<StepKind> {
1602    let span = refine_span(ctx, &pair);
1603    let kind = match pair.as_rule() {
1604        Rule::inherit_env_command => {
1605            let mut keys = Vec::new();
1606            for inner in pair.into_inner() {
1607                if inner.as_rule() == Rule::inherit_list {
1608                    for key in inner.into_inner() {
1609                        if key.as_rule() == Rule::env_key {
1610                            keys.push(key.as_str().trim().to_string());
1611                        }
1612                    }
1613                } else if inner.as_rule() == Rule::env_key {
1614                    keys.push(inner.as_str().trim().to_string());
1615                }
1616            }
1617            StepKind::InheritEnv { keys }
1618        }
1619        Rule::with_io_command => {
1620            let mut bindings = Vec::new();
1621            let mut cmd = None;
1622            for inner in pair.into_inner() {
1623                match inner.as_rule() {
1624                    Rule::io_flags => {
1625                        for flag in inner.into_inner() {
1626                            if flag.as_rule() == Rule::io_binding {
1627                                bindings.push(parse_io_binding(ctx, flag)?);
1628                            }
1629                        }
1630                    }
1631                    Rule::with_io_command => {
1632                        cmd = Some(Box::new(parse_structural_command_with_lower(
1633                            ctx, inner, lctx,
1634                        )?));
1635                    }
1636                    Rule::inherit_env_command => {
1637                        cmd = Some(Box::new(parse_structural_command_with_lower(
1638                            ctx, inner, lctx,
1639                        )?));
1640                    }
1641                    Rule::async_statement | Rule::async_statement_block => {
1642                        cmd = Some(Box::new(parse_structural_command_with_lower(
1643                            ctx, inner, lctx,
1644                        )?));
1645                    }
1646                    Rule::timeout_statement | Rule::cancel_statement => {
1647                        cmd = Some(Box::new(parse_structural_command_with_lower(
1648                            ctx, inner, lctx,
1649                        )?));
1650                    }
1651                    Rule::isolated_statement => {
1652                        cmd = Some(Box::new(parse_structural_command_with_lower(
1653                            ctx, inner, lctx,
1654                        )?));
1655                    }
1656                    Rule::remote_statement => {
1657                        cmd = Some(Box::new(parse_structural_command_with_lower(
1658                            ctx, inner, lctx,
1659                        )?));
1660                    }
1661                    Rule::call_statement | Rule::while_statement => {
1662                        cmd = Some(Box::new(parse_structural_command_with_lower(
1663                            ctx, inner, lctx,
1664                        )?));
1665                    }
1666                    Rule::func_def
1667                    | Rule::return_statement
1668                    | Rule::break_statement
1669                    | Rule::continue_statement => {
1670                        return Err(ParseError::structural(
1671                            "parser",
1672                            format!(
1673                                "WITH_IO cannot wrap {:?}; place it around a command or block instead",
1674                                inner.as_rule()
1675                            ),
1676                            &span,
1677                        ));
1678                    }
1679                    Rule::instruction | Rule::instruction_inner => {
1680                        cmd = Some(Box::new(lower_instruction_pair(ctx, inner, lctx)?));
1681                    }
1682                    Rule::run_exec_statement | Rule::run_exec_inner => {
1683                        cmd = Some(Box::new(lower_run_exec_pair(ctx, inner, lctx)?));
1684                    }
1685                    _ => {}
1686                }
1687            }
1688            if let Some(cmd) = cmd {
1689                StepKind::WithIo { bindings, cmd }
1690            } else {
1691                StepKind::WithIoBlock { bindings }
1692            }
1693        }
1694        Rule::for_statement => parse_for_statement_from_pair(ctx, pair, lctx)?,
1695        Rule::while_statement => parse_while_statement_from_pair(ctx, pair, lctx)?,
1696        Rule::func_def => parse_func_def_from_pair(ctx, pair, lctx)?,
1697        Rule::call_statement => parse_call_statement_from_pair(ctx, lctx, pair)?,
1698        Rule::return_statement => parse_return_statement_from_pair(ctx, lctx, pair)?,
1699        Rule::break_statement => StepKind::Break,
1700        Rule::continue_statement => StepKind::Continue,
1701        Rule::let_statement => parse_let_statement_from_pair(ctx, lctx, pair)?,
1702        Rule::mutate_statement => parse_mutate_statement_from_pair(ctx, lctx, pair)?,
1703        Rule::let_async_statement => parse_let_async_statement_from_pair(ctx, pair, lctx)?,
1704        Rule::let_capture_statement => parse_let_capture_statement_from_pair(ctx, pair, lctx)?,
1705        Rule::await_statement => parse_await_statement_from_pair(ctx, pair)?,
1706        Rule::cancel_statement => parse_cancel_statement_from_pair(ctx, pair)?,
1707        Rule::if_statement => parse_if_statement_from_pair(ctx, pair, lctx)?,
1708        Rule::async_statement => parse_async_statement_from_pair(ctx, pair, lctx)?,
1709        Rule::async_statement_block => parse_async_statement_block_from_pair(ctx, pair, lctx)?,
1710        Rule::timeout_statement => parse_timeout_statement_from_pair(ctx, pair, lctx)?,
1711        Rule::isolated_statement => parse_isolated_statement_from_pair(ctx, pair, lctx)?,
1712        Rule::remote_statement => parse_remote_statement_from_pair(ctx, pair, lctx)?,
1713        Rule::type_statement => parse_type_statement_from_pair(ctx, pair)?,
1714        Rule::command_inner => {
1715            // command_inner = { inherit_env_command | instruction }
1716            // Unwrap to the inner rule
1717            let inner = pair.into_inner().next().ok_or_else(|| {
1718                ParseError::structural("parser", "empty command_inner".to_string(), &span)
1719            })?;
1720            parse_structural_command_with_lower(ctx, inner, lctx)?
1721        }
1722        Rule::instruction | Rule::instruction_inner => lower_instruction_pair(ctx, pair, lctx)?,
1723        Rule::run_exec_statement | Rule::run_exec_inner => lower_run_exec_pair(ctx, pair, lctx)?,
1724        _ => {
1725            return Err(ParseError::structural(
1726                "parser",
1727                format!("unexpected structural command rule: {:?}", pair.as_rule()),
1728                &span,
1729            ));
1730        }
1731    };
1732    Ok(kind)
1733}
1734
1735fn extract_instruction(
1736    ctx: &SpanContext,
1737    pair: Pair<Rule>,
1738    lctx: &LowerCtx,
1739) -> ParseResult<(String, Vec<InsToken>)> {
1740    let span = refine_span(ctx, &pair);
1741    let mut name = None;
1742    let mut args = Vec::new();
1743    for inner in pair.into_inner() {
1744        match inner.as_rule() {
1745            Rule::command_name => {
1746                name = Some(inner.as_str().to_string());
1747            }
1748            Rule::argument => {
1749                args.extend(
1750                    parse_argument(ctx, lctx, inner)?
1751                        .into_iter()
1752                        .map(InsToken::Pos),
1753                );
1754            }
1755            Rule::assignment => {
1756                let (key, value) = parse_assignment(ctx, lctx, inner)?;
1757                args.push(InsToken::Assign(key, value));
1758            }
1759            _ => {}
1760        }
1761    }
1762    let name = name.ok_or_else(|| {
1763        ParseError::structural(
1764            "instruction",
1765            "instruction missing command name".to_string(),
1766            &span,
1767        )
1768    })?;
1769    Ok((name, args))
1770}
1771
1772/// One lowered instruction token: a positional argument, or a pre-split
1773/// `KEY=value` assignment from the unified grammar rule. Assignments reach
1774/// ENV/EXPAND lowerings intact; every other command sees them collapsed to
1775/// canonical `key=value` text (see `lower_instruction_pair`).
1776enum InsToken {
1777    Pos(Arg),
1778    Assign(String, Arg),
1779}
1780
1781/// Lower one generic instruction pair: ENV/EXPAND build `StepKind` directly
1782/// from pre-split assignments (never via the injected `lower`, mirroring how
1783/// LET/FOR/IF bypass it); all other commands flow through `lower` with
1784/// assignments in canonical text form.
1785fn lower_instruction_pair(
1786    ctx: &SpanContext,
1787    pair: Pair<Rule>,
1788    lctx: &LowerCtx,
1789) -> ParseResult<StepKind> {
1790    let span = refine_span(ctx, &pair);
1791    let (name, tokens) = extract_instruction(ctx, pair, lctx)?;
1792    if name == "ENV" {
1793        return lower_env_command(ctx, tokens);
1794    }
1795    if name == "EXPAND" {
1796        return lower_expand_command(ctx, tokens);
1797    }
1798    let args = tokens
1799        .into_iter()
1800        .map(|token| match token {
1801            InsToken::Pos(arg) => arg,
1802            InsToken::Assign(key, value) => crate::commands::canonical_assignment_arg(&key, &value),
1803        })
1804        .collect();
1805    (lctx.lower)(&name, args).map_err(|e| e.with_span(&span))
1806}
1807
1808/// Lower a `run_exec` grammar pair: the PEG engine has already validated the
1809/// full `RUN [...]` span, so extract the inner `list_literal` and route the
1810/// structured `Expr::List` through the injected `lower` as `RUN` with one
1811/// typed argument (production `lower_command` maps it to `StepKind::RunExec`;
1812/// the grammar-test mock wraps it in `StepKind::Run`).
1813fn lower_run_exec_pair(
1814    ctx: &SpanContext,
1815    pair: Pair<Rule>,
1816    lctx: &LowerCtx,
1817) -> ParseResult<StepKind> {
1818    let span = refine_span(ctx, &pair);
1819    let mut list = None;
1820    for inner in pair.into_inner() {
1821        if inner.as_rule() == Rule::run_exec_list {
1822            list = Some(parse_run_exec_list(ctx, lctx, inner)?);
1823        }
1824    }
1825    let list = list.ok_or_else(|| {
1826        ParseError::structural(
1827            "run_exec",
1828            "RUN exec form missing list literal".to_string(),
1829            &span,
1830        )
1831    })?;
1832    (lctx.lower)("RUN", vec![Arg::Expr(list)]).map_err(|e| e.with_span(&span))
1833}
1834
1835/// Lower a `run_exec_list` pair: like `parse_list_literal` but elements are
1836/// atoms only (see `run_exec_arg` in the grammar), so shell bracket content
1837/// never parses here. Numeric atoms lower exactly like expression atoms
1838/// (including the `i64::MIN` boundary rejection).
1839fn parse_run_exec_list(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
1840    let mut items = Vec::new();
1841    for inner in pair.into_inner() {
1842        if inner.as_rule() == Rule::run_exec_arg {
1843            let item = parse_run_exec_arg(ctx, lctx, inner)?;
1844            reject_boundary(ctx, &item)?;
1845            items.push(item);
1846        }
1847    }
1848    Ok(Expr::List(items))
1849}
1850
1851fn parse_run_exec_arg(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
1852    let span = refine_span(ctx, &pair);
1853    let inner = pair.into_inner().next().ok_or_else(|| {
1854        ParseError::structural("run_exec", "RUN exec argument is empty".to_string(), &span)
1855    })?;
1856    match inner.as_rule() {
1857        Rule::parenthesized_expr => parse_expr_inner(ctx, lctx, inner.into_inner().next().unwrap()),
1858        Rule::func_call => parse_func_call(ctx, lctx, inner),
1859        Rule::key_path => parse_key_path(ctx, inner),
1860        Rule::variable => {
1861            let name = inner.as_str();
1862            let name = name.strip_prefix('$').unwrap_or(name).to_string();
1863            Ok(Expr::Var(name))
1864        }
1865        Rule::env_read => parse_env_read(ctx, inner).map(Expr::Env),
1866        Rule::list_literal => parse_list_literal(ctx, lctx, inner),
1867        Rule::map_literal => parse_map_literal(ctx, lctx, inner),
1868        Rule::block => Ok(Expr::Block(parse_block_elements_with_lower(
1869            ctx, inner, lctx,
1870        )?)),
1871        Rule::string_literal | Rule::quoted_string => {
1872            let s = parse_quoted_string(inner)?;
1873            Ok(Expr::Literal(Value::string(s)))
1874        }
1875        Rule::numeric_literal => parse_numeric_literal(ctx, inner),
1876        Rule::bare_word => {
1877            let s = inner.as_str().to_string();
1878            match s.as_str() {
1879                "true" => Ok(Expr::Literal(Value::bool(true))),
1880                "false" => Ok(Expr::Literal(Value::bool(false))),
1881                _ => Ok(Expr::Literal(Value::string(s))),
1882            }
1883        }
1884        _ => Err(ParseError::structural(
1885            "run_exec",
1886            format!("unexpected RUN exec argument rule: {:?}", inner.as_rule()),
1887            &span,
1888        )),
1889    }
1890}
1891
1892/// Split one `assignment` pair into its key and lowered value.
1893fn parse_assignment(
1894    ctx: &SpanContext,
1895    lctx: &LowerCtx,
1896    pair: Pair<Rule>,
1897) -> ParseResult<(String, Arg)> {
1898    let span = refine_span(ctx, &pair);
1899    let mut key = None;
1900    let mut value = None;
1901    for inner in pair.into_inner() {
1902        match inner.as_rule() {
1903            Rule::assign_key => {
1904                key = Some(inner.as_str().to_string());
1905            }
1906            Rule::assign_value => {
1907                value = Some(lower_command_value(ctx, lctx, inner)?);
1908            }
1909            _ => {
1910                return Err(ParseError::structural(
1911                    "assignment",
1912                    format!("unexpected assignment rule: {:?}", inner.as_rule()),
1913                    &span,
1914                ));
1915            }
1916        }
1917    }
1918    Ok((
1919        key.ok_or_else(|| {
1920            ParseError::structural("assignment", "assignment missing key".to_string(), &span)
1921        })?,
1922        value.unwrap_or(Arg::String(String::new(), false)),
1923    ))
1924}
1925
1926/// Single unified value lowering: every command's free-text value flows through
1927/// here on raw pest spans. Quoted bytes stay exact, lone `$var`/`$a.b`/`F()`
1928/// stay typed `Arg::Expr`, and anything else becomes literal text with only
1929/// `{{ }}` as the interpolation trigger. No heuristic rewriting, ever.
1930fn lower_command_value(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Arg> {
1931    let span = refine_span(ctx, &pair);
1932    let inner = pair.into_inner().next().ok_or_else(|| {
1933        ParseError::structural("assignment", "assignment value is empty".to_string(), &span)
1934    })?;
1935    match inner.as_rule() {
1936        Rule::quoted_string => Ok(Arg::String(parse_quoted_string(inner)?, true)),
1937        Rule::assign_expr => {
1938            let shape = inner.into_inner().next().ok_or_else(|| {
1939                ParseError::structural(
1940                    "assignment",
1941                    "assignment expression is empty".to_string(),
1942                    &span,
1943                )
1944            })?;
1945            match shape.as_rule() {
1946                Rule::variable => Ok(Arg::Expr(Expr::Var(parse_dollar_ident(shape)))),
1947                Rule::key_path => Ok(Arg::Expr(parse_key_path(ctx, shape)?)),
1948                Rule::env_read => Ok(Arg::Expr(Expr::Env(parse_env_read(ctx, shape)?))),
1949                Rule::func_call => Ok(Arg::Expr(parse_func_call(ctx, lctx, shape)?)),
1950                other => Err(ParseError::structural(
1951                    "assignment",
1952                    format!("unexpected assignment expression shape: {:?}", other),
1953                    &span,
1954                )),
1955            }
1956        }
1957        Rule::raw_fragments => lower_raw_fragments(ctx, inner),
1958        other => Err(ParseError::structural(
1959            "assignment",
1960            format!("unexpected assignment value rule: {:?}", other),
1961            &span,
1962        )),
1963    }
1964}
1965
1966/// Assemble a bounded raw span into one literal `Arg::String`: `{{ }}` template
1967/// chunks pass through verbatim for `expand_string`, quoted chunks unquote
1968/// once with exact bytes, and unquoted runs collapse whitespace to single
1969/// spaces (trailing/leading edges trimmed). Pure text needs no `Parts` : every
1970/// fragment resolves through the same `expand_string` pass.
1971fn lower_raw_fragments(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<Arg> {
1972    let span = refine_span(ctx, &pair);
1973    let mut body = String::new();
1974    for fragment in pair.into_inner() {
1975        match fragment.as_rule() {
1976            Rule::quoted_string => body.push_str(&parse_quoted_string(fragment)?),
1977            Rule::templated_arg => body.push_str(fragment.as_str()),
1978            Rule::raw_text => body.push_str(&collapse_ws(fragment.as_str())),
1979            other => {
1980                return Err(ParseError::structural(
1981                    "assignment",
1982                    format!("unexpected raw value fragment: {:?}", other),
1983                    &span,
1984                ));
1985            }
1986        }
1987    }
1988    Ok(Arg::String(body.trim().to_string(), false))
1989}
1990
1991/// Collapse every whitespace run to a single space, preserving edge positions
1992/// (callers trim the assembled value).
1993fn collapse_ws(s: &str) -> String {
1994    let mut out = String::with_capacity(s.len());
1995    let mut in_run = false;
1996    for c in s.chars() {
1997        if c.is_whitespace() {
1998            if !in_run {
1999                out.push(' ');
2000                in_run = true;
2001            }
2002        } else {
2003            out.push(c);
2004            in_run = false;
2005        }
2006    }
2007    out
2008}
2009
2010/// Parser-direct `ENV` lowering: exactly one assignment. A lone positional
2011/// holding `=` is the exotic-key fringe (keys the grammar cannot classify);
2012/// anything else is a precise error instead of a silent drop.
2013fn lower_env_command(ctx: &SpanContext, tokens: Vec<InsToken>) -> ParseResult<StepKind> {
2014    if tokens.is_empty() {
2015        return Err(ParseError::validation(
2016            "ENV",
2017            "ENV requires KEY=value".to_string(),
2018            ctx,
2019        ));
2020    }
2021    match tokens.as_slice() {
2022        [InsToken::Assign(key, value)] => {
2023            // Same KEY=value check the ENV lower applies on the
2024            // `lower_command` path, over the joined assignment form.
2025            if crate::command::split_assignment(&format!("{key}={}", value.render()))
2026                .map_err(|e| ParseError::validation("ENV", e.to_string(), ctx))?
2027                .is_none()
2028            {
2029                return Err(ParseError::validation(
2030                    "ENV",
2031                    "ENV requires KEY=value format".to_string(),
2032                    ctx,
2033                ));
2034            }
2035            Ok(StepKind::Env {
2036                key: key.clone(),
2037                value: value.clone(),
2038            })
2039        }
2040        [InsToken::Pos(Arg::String(text, _))] => match crate::command::split_assignment(text)
2041            .map_err(|e| ParseError::validation("ENV", e.to_string(), ctx))?
2042        {
2043            Some((key, value)) => Ok(StepKind::Env { key, value }),
2044            None => Err(ParseError::validation(
2045                "ENV",
2046                "ENV requires KEY=value format".to_string(),
2047                ctx,
2048            )),
2049        },
2050        _ => Err(ParseError::validation(
2051            "ENV",
2052            "ENV requires KEY=value format".to_string(),
2053            ctx,
2054        )),
2055    }
2056}
2057
2058/// Parser-direct `EXPAND` lowering: positional tokens are the optional path,
2059/// assignments are overrides. Split quoted values can never masquerade as
2060/// extra paths : tokenize time already proved they are one value.
2061fn lower_expand_command(ctx: &SpanContext, tokens: Vec<InsToken>) -> ParseResult<StepKind> {
2062    let mut path = None;
2063    let mut overrides = Vec::new();
2064    for token in tokens {
2065        match token {
2066            InsToken::Assign(key, value) => {
2067                if key.is_empty() {
2068                    return Err(ParseError::validation(
2069                        "EXPAND",
2070                        "EXPAND requires KEY=value format for overrides".to_string(),
2071                        ctx,
2072                    ));
2073                }
2074                overrides.push((key, value));
2075            }
2076            InsToken::Pos(arg) => match &arg {
2077                Arg::String(text, quoted) if !quoted && text.contains('=') => {
2078                    let Some((key, value)) = crate::command::split_assignment(text)
2079                        .map_err(|e| ParseError::validation("EXPAND", e.to_string(), ctx))?
2080                    else {
2081                        return Err(ParseError::validation(
2082                            "EXPAND",
2083                            "EXPAND requires KEY=value format for overrides".to_string(),
2084                            ctx,
2085                        ));
2086                    };
2087                    overrides.push((key, value));
2088                }
2089                _ => {
2090                    if path.is_none() {
2091                        // Path-typed positional, checked like every other
2092                        // `lower_command` path arg (literals always pass;
2093                        // resolution stays runtime).
2094                        ArgType::Path
2095                            .check_arg(&arg)
2096                            .map_err(|e| ParseError::validation("EXPAND", e.to_string(), ctx))?;
2097                        path = Some(arg);
2098                    } else {
2099                        return Err(ParseError::validation(
2100                            "EXPAND",
2101                            "EXPAND accepts at most one path".to_string(),
2102                            ctx,
2103                        ));
2104                    }
2105                }
2106            },
2107        }
2108    }
2109    Ok(StepKind::Expand { path, overrides })
2110}
2111
2112fn parse_type_tag(pair: Pair<Rule>) -> String {
2113    // Canonicalize to the no-space form: `LIST<MAP>` and `LIST< MAP >`
2114    // (including macro token-stream reconstructions, which space
2115    // punctuation) are one spelling from here on. Resolution keys
2116    // on this form, so interning and pointer equality hold across
2117    // parse pathways.
2118    crate::canonicalize_spelling(pair.as_str())
2119}
2120
2121/// Lower a `TYPE NAME = <shape>` alias declaration. Both halves flow
2122/// through as text: the binder is a bare `type_name`, the target the
2123/// full (possibly generic) `type_tag` spelling. Shape validation,
2124/// collision checks, and resolution all happen at collection time in
2125/// `oxdock-core`, never here.
2126fn parse_type_statement_from_pair(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<StepKind> {
2127    let span = refine_span(ctx, &pair);
2128    let mut name: Option<String> = None;
2129    let mut target: Option<String> = None;
2130    for inner in pair.into_inner() {
2131        match inner.as_rule() {
2132            Rule::type_name => name = Some(inner.as_str().trim().to_string()),
2133            Rule::type_tag => target = Some(parse_type_tag(inner)),
2134            _ => {}
2135        }
2136    }
2137    let (Some(name), Some(target)) = (name, target) else {
2138        return Err(ParseError::structural(
2139            KEYWORD_TYPE,
2140            "TYPE requires a name and a shape (`TYPE NAME = SHAPE`)".to_string(),
2141            &span,
2142        ));
2143    };
2144    Ok(StepKind::TypeAlias { name, target })
2145}
2146
2147fn check_func_ident(ctx: &SpanContext, name: &str) -> ParseResult<()> {
2148    let ok = name
2149        .chars()
2150        .next()
2151        .map(|c| c.is_ascii_uppercase())
2152        .unwrap_or(false)
2153        && name
2154            .chars()
2155            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_');
2156    if !ok {
2157        return Err(ParseError::validation(
2158            "FUNC",
2159            format!(
2160                "function names must be UPPERCASE (ASCII_ALPHA_UPPER, digits, _), got `{name}`"
2161            ),
2162            ctx,
2163        ));
2164    }
2165    Ok(())
2166}
2167
2168fn parse_while_statement_from_pair(
2169    ctx: &SpanContext,
2170    pair: Pair<Rule>,
2171    lctx: &LowerCtx,
2172) -> ParseResult<StepKind> {
2173    let span = refine_span(ctx, &pair);
2174    let mut cond = None;
2175    let mut body = None;
2176    for inner in pair.into_inner() {
2177        match inner.as_rule() {
2178            Rule::expr => {
2179                if cond.is_none() {
2180                    cond = Some(parse_expr(ctx, lctx, inner)?);
2181                }
2182            }
2183            Rule::block => {
2184                body = Some(parse_block_elements_with_lower(ctx, inner, lctx)?);
2185            }
2186            _ => {}
2187        }
2188    }
2189    Ok(StepKind::While {
2190        cond: Box::new(cond.ok_or_else(|| {
2191            ParseError::validation("WHILE", "WHILE requires a condition".to_string(), &span)
2192        })?),
2193        body: body.ok_or_else(|| {
2194            ParseError::validation("WHILE", "WHILE requires a block".to_string(), &span)
2195        })?,
2196    })
2197}
2198
2199fn parse_func_def_from_pair(
2200    ctx: &SpanContext,
2201    pair: Pair<Rule>,
2202    lctx: &LowerCtx,
2203) -> ParseResult<StepKind> {
2204    let span = refine_span(ctx, &pair);
2205    // Declare before lowering the body so recursive self-calls resolve:
2206    // the name is visible from its definition line, in execution order,
2207    // exactly like `LET`. (Mutual recursion stays unsupported: the second
2208    // name does not exist while the first body lowers.)
2209    let def_name = pair
2210        .clone()
2211        .into_inner()
2212        .find(|inner| inner.as_rule() == Rule::func_ident)
2213        .map(|inner| inner.as_str().to_string())
2214        .ok_or_else(|| ParseError::validation("FUNC", "FUNC requires a name".to_string(), &span))?;
2215    check_func_ident(ctx, &def_name)?;
2216    // Same-scope duplicates and reserved-name shadows fail here, at the
2217    // definition line: the post-parse AST keeps no spans, so a later walk
2218    // could only point at end of file. Nested shadowing of an outer DSL
2219    // name stays allowed and reverts on scope exit at runtime. Reserved
2220    // covers the flat host set plus every module's base names: a `FUNC`
2221    // defines `SCRIPT::NAME`, which would collide on bare resolution.
2222    if lctx.reserved_names.contains(&def_name) || lctx.module_base_names().contains(&def_name) {
2223        return Err(ParseError::validation(
2224            "FUNC",
2225            format!("FUNC {def_name} cannot shadow reserved function `{def_name}`"),
2226            &span,
2227        ));
2228    }
2229    if !lctx.declare_func(&def_name) {
2230        return Err(ParseError::validation(
2231            "FUNC",
2232            format!("duplicate function `{def_name}` in same scope"),
2233            &span,
2234        ));
2235    }
2236    let mut name: Option<String> = None;
2237    let mut param_names: Vec<String> = Vec::new();
2238    let mut param_types: Vec<String> = Vec::new();
2239    let mut body = None;
2240    for inner in pair.into_inner() {
2241        match inner.as_rule() {
2242            Rule::func_ident => {
2243                if name.is_none() {
2244                    name = Some(inner.as_str().to_string());
2245                }
2246            }
2247            Rule::func_param => {
2248                let mut pname = None;
2249                let mut ptype = None;
2250                for part in inner.into_inner() {
2251                    match part.as_rule() {
2252                        Rule::dollar_ident => {
2253                            pname = Some(parse_dollar_ident(part));
2254                        }
2255                        Rule::type_tag => {
2256                            ptype = Some(parse_type_tag(part));
2257                        }
2258                        _ => {}
2259                    }
2260                }
2261                param_names.push(pname.ok_or_else(|| {
2262                    ParseError::validation(
2263                        "FUNC",
2264                        "FUNC parameter requires a $variable".to_string(),
2265                        &span,
2266                    )
2267                })?);
2268                param_types.push(ptype.ok_or_else(|| {
2269                    ParseError::validation(
2270                        "FUNC",
2271                        "FUNC parameters require explicit types: FUNC NAME($p: TYPE, ...)"
2272                            .to_string(),
2273                        &span,
2274                    )
2275                })?);
2276            }
2277            Rule::block => {
2278                body = Some(parse_block_elements_with_lower(ctx, inner, lctx)?);
2279            }
2280            _ => {}
2281        }
2282    }
2283    let name = name
2284        .ok_or_else(|| ParseError::validation("FUNC", "FUNC requires a name".to_string(), &span))?;
2285    check_func_ident(ctx, &name)?;
2286    if param_names.len() != param_types.len() {
2287        return Err(ParseError::validation(
2288            "FUNC",
2289            format!("FUNC {name} has mismatched parameter names and types"),
2290            &span,
2291        ));
2292    }
2293    let mut seen = std::collections::HashSet::new();
2294    for pname in &param_names {
2295        if !seen.insert(pname.clone()) {
2296            return Err(ParseError::validation(
2297                "FUNC",
2298                format!("FUNC {name} declares duplicate parameter ${pname}"),
2299                &span,
2300            ));
2301        }
2302    }
2303    Ok(StepKind::FuncDef {
2304        name,
2305        params: param_names.into_iter().zip(param_types).collect(),
2306        body: body.ok_or_else(|| {
2307            ParseError::validation("FUNC", "FUNC requires a block".to_string(), &span)
2308        })?,
2309    })
2310}
2311
2312fn parse_call_statement_from_pair(
2313    ctx: &SpanContext,
2314    lctx: &LowerCtx,
2315    pair: Pair<Rule>,
2316) -> ParseResult<StepKind> {
2317    let span = refine_span(ctx, &pair);
2318    let mut name: Option<String> = None;
2319    let mut args = Vec::new();
2320    // The head arrives wrapped in the atomic `call_head_paren` token (which
2321    // is what forbids whitespace before `(`). Atomic tokens produce no
2322    // inner pairs, so the name comes from the token text minus its `(`.
2323    for inner in pair.into_inner() {
2324        match inner.as_rule() {
2325            Rule::call_head_paren => {
2326                if name.is_none() {
2327                    let text = inner.as_str();
2328                    name = Some(text.strip_suffix('(').unwrap_or(text).to_string());
2329                }
2330            }
2331            Rule::func_call_head => {
2332                if name.is_none() {
2333                    name = Some(inner.as_str().to_string());
2334                }
2335            }
2336            Rule::expr => {
2337                args.push(parse_expr(ctx, lctx, inner)?);
2338            }
2339            _ => {}
2340        }
2341    }
2342    let name = name.ok_or_else(|| {
2343        ParseError::validation(
2344            "FUNC",
2345            "function call requires a function name".to_string(),
2346            &span,
2347        )
2348    })?;
2349    // Bare heads keep the legacy UPPERCASE check; qualified heads validate
2350    // per part inside resolution. Either way the emitted call is qualified.
2351    if !name.contains(MODULE_SEPARATOR) {
2352        check_func_ident(ctx, &name)?;
2353    }
2354    let qualified = lctx.resolve_call(&span, &name)?;
2355    Ok(StepKind::Call {
2356        name: qualified,
2357        args,
2358    })
2359}
2360
2361fn parse_return_statement_from_pair(
2362    ctx: &SpanContext,
2363    lctx: &LowerCtx,
2364    pair: Pair<Rule>,
2365) -> ParseResult<StepKind> {
2366    use crate::ast::Value;
2367    for inner in pair.into_inner() {
2368        if inner.as_rule() == Rule::expr {
2369            return Ok(StepKind::Return {
2370                expr: Box::new(parse_expr(ctx, lctx, inner)?),
2371            });
2372        }
2373    }
2374    Ok(StepKind::Return {
2375        expr: Box::new(Expr::Literal(Value::string(String::new()))),
2376    })
2377}
2378
2379fn parse_for_statement_from_pair(
2380    ctx: &SpanContext,
2381    pair: Pair<Rule>,
2382    lctx: &LowerCtx,
2383) -> ParseResult<StepKind> {
2384    let span = refine_span(ctx, &pair);
2385    let mut idents: Vec<String> = Vec::new();
2386    let mut types: Vec<String> = Vec::new();
2387    let mut type_spans: Vec<SpanContext> = Vec::new();
2388    let mut in_expr = None;
2389    let mut body_steps = Vec::new();
2390    for inner in pair.into_inner() {
2391        match inner.as_rule() {
2392            Rule::dollar_ident => {
2393                idents.push(parse_dollar_ident(inner));
2394            }
2395            Rule::type_tag => {
2396                type_spans.push(refine_span(ctx, &inner));
2397                types.push(parse_type_tag(inner));
2398            }
2399            Rule::expr => {
2400                in_expr = Some(parse_expr(ctx, lctx, inner)?);
2401            }
2402            Rule::block => {
2403                body_steps = parse_block_elements_with_lower(ctx, inner, lctx)?;
2404            }
2405            _ => {}
2406        }
2407    }
2408    if idents.len() != types.len() {
2409        return Err(ParseError::validation(
2410            "FOR",
2411            format!(
2412                "FOR requires explicit types: FOR $item: TYPE IN <expr> (got {} vars, {} types)",
2413                idents.len(),
2414                types.len()
2415            ),
2416            &span,
2417        ));
2418    }
2419    let (key_var, key_type, var, var_type) = match idents.len() {
2420        1 => (
2421            None,
2422            None,
2423            idents.into_iter().next().unwrap(),
2424            types.into_iter().next().unwrap(),
2425        ),
2426        2 => {
2427            let mut iv = idents.into_iter();
2428            let mut tv = types.into_iter();
2429            (
2430                Some(iv.next().unwrap()),
2431                Some(tv.next().unwrap()),
2432                iv.next().unwrap(),
2433                tv.next().unwrap(),
2434            )
2435        }
2436        _ => {
2437            return Err(ParseError::validation(
2438                "FOR",
2439                "FOR requires one or two variables".to_string(),
2440                &span,
2441            ));
2442        }
2443    };
2444    if let Some(kt) = &key_type
2445        && kt != "STRING"
2446        && kt != "INT"
2447    {
2448        // Pinpoint the offending key type tag rather than the statement.
2449        let at = type_spans.first().unwrap_or(&span);
2450        return Err(ParseError::validation(
2451            "FOR",
2452            format!("FOR key variable must be INT or STRING, got {kt}"),
2453            at,
2454        ));
2455    }
2456    Ok(StepKind::For {
2457        key_var,
2458        key_type,
2459        var,
2460        var_type,
2461        in_expr: in_expr.ok_or_else(|| {
2462            ParseError::validation(
2463                "FOR",
2464                "FOR requires an iterable expression".to_string(),
2465                &span,
2466            )
2467        })?,
2468        body: body_steps,
2469    })
2470}
2471
2472fn parse_let_statement_from_pair(
2473    ctx: &SpanContext,
2474    lctx: &LowerCtx,
2475    pair: Pair<Rule>,
2476) -> ParseResult<StepKind> {
2477    let span = refine_span(ctx, &pair);
2478    let mut var = None;
2479    let mut decl_type = None;
2480    let mut expr = None;
2481    for inner in pair.into_inner() {
2482        match inner.as_rule() {
2483            Rule::dollar_ident => {
2484                var = Some(parse_dollar_ident(inner));
2485            }
2486            Rule::type_tag => {
2487                decl_type = Some(parse_type_tag(inner));
2488            }
2489            Rule::expr => {
2490                expr = Some(parse_expr(ctx, lctx, inner)?);
2491            }
2492            _ => {}
2493        }
2494    }
2495    let var = var.ok_or_else(|| {
2496        ParseError::validation("LET", "LET requires a variable".to_string(), &span)
2497    })?;
2498    let decl_type = decl_type.ok_or_else(|| {
2499        ParseError::validation(
2500            "LET",
2501            "LET requires explicit type: LET $var: TYPE = <expr>".to_string(),
2502            &span,
2503        )
2504    })?;
2505    // Bare `LET $p: PIPE` (no initializer) mints a fresh anonymous pipe.
2506    // Every other type still requires `= <expr>`.
2507    let expr = match expr {
2508        Some(e) => e,
2509        None if decl_type == "PIPE" => Expr::FreshPipe,
2510        None => {
2511            return Err(ParseError::validation(
2512                "LET",
2513                "LET requires an expression: LET $var: TYPE = <expr> (only LET $p: PIPE omits the initializer)".to_string(),
2514                &span,
2515            ));
2516        }
2517    };
2518    Ok(StepKind::Assign {
2519        var,
2520        decl_type,
2521        expr,
2522    })
2523}
2524
2525fn parse_mutate_statement_from_pair(
2526    ctx: &SpanContext,
2527    lctx: &LowerCtx,
2528    pair: Pair<Rule>,
2529) -> ParseResult<StepKind> {
2530    let span = refine_span(ctx, &pair);
2531    let mut var = None;
2532    let mut expr = None;
2533    for inner in pair.into_inner() {
2534        match inner.as_rule() {
2535            Rule::dollar_ident => {
2536                var = Some(parse_dollar_ident(inner));
2537            }
2538            Rule::expr => {
2539                expr = Some(parse_expr(ctx, lctx, inner)?);
2540            }
2541            _ => {}
2542        }
2543    }
2544    Ok(StepKind::Set {
2545        var: var.ok_or_else(|| {
2546            ParseError::validation(
2547                "mutate",
2548                "mutation requires a variable: $var = <expr>".to_string(),
2549                &span,
2550            )
2551        })?,
2552        expr: expr.ok_or_else(|| {
2553            ParseError::validation(
2554                "mutate",
2555                "mutation requires an expression: $var = <expr>".to_string(),
2556                &span,
2557            )
2558        })?,
2559    })
2560}
2561
2562fn parse_let_async_statement_from_pair(
2563    ctx: &SpanContext,
2564    pair: Pair<Rule>,
2565    lctx: &LowerCtx,
2566) -> ParseResult<StepKind> {
2567    let span = refine_span(ctx, &pair);
2568    let mut var = None;
2569    let mut decl_type: Option<String> = None;
2570    let mut body = None;
2571    for inner in pair.into_inner() {
2572        match inner.as_rule() {
2573            Rule::dollar_ident => {
2574                var = Some(parse_dollar_ident(inner));
2575            }
2576            Rule::type_tag => {
2577                decl_type = Some(parse_type_tag(inner));
2578            }
2579            Rule::block => {
2580                body = Some(parse_block_elements_with_lower(ctx, inner, lctx)?);
2581            }
2582            Rule::command_inner => {
2583                // command_inner = { inherit_env_command | async_statement | async_statement_block | instruction }
2584                // Unwrap to the inner rule
2585                let inner = inner.into_inner().next().ok_or_else(|| {
2586                    ParseError::structural("let", "empty command_inner".to_string(), &span)
2587                })?;
2588                let step_kind = parse_structural_command_with_lower(ctx, inner, lctx)?;
2589                body = Some(vec![Step {
2590                    guard: None,
2591                    kind: step_kind,
2592                    scope_enter: 0,
2593                    scope_exit: 0,
2594                }]);
2595            }
2596            Rule::with_io_command => {
2597                // LET $var: TYPE = WITH_IO [flags] ... : two shapes share this rule
2598                // (`let_async_statement` precedes `let_capture_statement` in
2599                // the grammar, so every WITH_IO-led LET lands here):
2600                // - wrapping ASYNC binds a pipe-wired background task. The
2601                //   bindings apply inside the task thread : the same shape as
2602                //   a braced body holding one WITH_IO step, which the
2603                //   AssignAsync runtime path supports.
2604                // - wrapping a synchronous command captures its stdout into
2605                //   the variable (same semantics as LET $x: STRING = <command>).
2606                let kind = parse_structural_command_with_lower(ctx, inner, lctx)?;
2607                let StepKind::WithIo { bindings, cmd } = kind else {
2608                    return Err(ParseError::validation("LET", "LET $var: TYPE = WITH_IO requires an ASYNC command (e.g. LET $t = WITH_IO [stdin=$p] ASYNC WRITE \"f\")".to_string(), &span));
2609                };
2610                match *cmd {
2611                    StepKind::AsyncBlock { body: async_body } => {
2612                        if async_body.len() != 1 {
2613                            return Err(ParseError::structural("let", "LET $var: TYPE = WITH_IO [..] ASYNC accepts a single command; use LET $var: HANDLE = ASYNC {{ ... }} with WITH_IO inside the block for multi-step tasks".to_string(), &span));
2614                        }
2615                        let step = async_body.into_iter().next().ok_or_else(|| {
2616                            ParseError::validation(
2617                                "LET",
2618                                "LET $var: HANDLE = ASYNC requires a body".to_string(),
2619                                &span,
2620                            )
2621                        })?;
2622                        body = Some(vec![Step {
2623                            guard: step.guard,
2624                            kind: StepKind::WithIo {
2625                                bindings,
2626                                cmd: Box::new(step.kind),
2627                            },
2628                            scope_enter: step.scope_enter,
2629                            scope_exit: step.scope_exit,
2630                        }]);
2631                    }
2632                    sync_cmd => {
2633                        if has_stdout_pipe(&bindings) {
2634                            return Err(ParseError::structural("let", "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout".to_string(), &span));
2635                        }
2636                        reject_async_in_capture(ctx, &sync_cmd)?;
2637                        let name = var.clone().ok_or_else(|| {
2638                            ParseError::validation(
2639                                "LET",
2640                                "LET $var: TYPE = WITH_IO requires a variable".to_string(),
2641                                &span,
2642                            )
2643                        })?;
2644                        let dtype = decl_type.ok_or_else(|| {
2645                            ParseError::validation(
2646                                "LET",
2647                                "LET requires explicit type: LET $var: TYPE = ...".to_string(),
2648                                &span,
2649                            )
2650                        })?;
2651                        return Ok(StepKind::AssignCapture {
2652                            var: name,
2653                            decl_type: dtype,
2654                            cmd: Box::new(StepKind::WithIo {
2655                                bindings,
2656                                cmd: Box::new(sync_cmd),
2657                            }),
2658                        });
2659                    }
2660                }
2661            }
2662            _ => {}
2663        }
2664    }
2665    Ok(StepKind::AssignAsync {
2666        var: var.ok_or_else(|| {
2667            ParseError::validation(
2668                "LET",
2669                "LET $var: HANDLE = ASYNC requires a variable".to_string(),
2670                &span,
2671            )
2672        })?,
2673        decl_type: decl_type.ok_or_else(|| {
2674            ParseError::validation(
2675                "LET",
2676                "LET requires explicit type: LET $var: TYPE = ...".to_string(),
2677                &span,
2678            )
2679        })?,
2680        body: body.ok_or_else(|| {
2681            ParseError::validation(
2682                "LET",
2683                "LET $var: HANDLE = ASYNC requires a body".to_string(),
2684                &span,
2685            )
2686        })?,
2687    })
2688}
2689
2690/// Lower `LET $var: STRING = <sync command>` / `LET $out: STRING = AWAIT $task`.
2691///
2692/// Shadow-safe by construction: the grammar only routes UPPERCASE-led
2693/// `instruction` lines here (`let_async_statement` claims ASYNC-led and
2694/// WITH_IO-led lines first; lowercase/digit/sigil RHSs never match). Rust
2695/// then branches on the lead token: known commands lower to capture,
2696/// unknown leads re-parse as plain expressions.
2697fn parse_let_capture_statement_from_pair(
2698    ctx: &SpanContext,
2699    pair: Pair<Rule>,
2700    lctx: &LowerCtx,
2701) -> ParseResult<StepKind> {
2702    let span = refine_span(ctx, &pair);
2703    let mut var = None;
2704    let mut decl_type: Option<String> = None;
2705    let mut await_pair = None;
2706    let mut timeout_pair = None;
2707    let mut run_exec_pair = None;
2708    let mut instruction_pair = None;
2709    for inner in pair.into_inner() {
2710        match inner.as_rule() {
2711            Rule::dollar_ident => {
2712                var = Some(parse_dollar_ident(inner));
2713            }
2714            Rule::type_tag => {
2715                decl_type = Some(parse_type_tag(inner));
2716            }
2717            Rule::await_statement => {
2718                await_pair = Some(inner);
2719            }
2720            Rule::timeout_statement => {
2721                timeout_pair = Some(inner);
2722            }
2723            Rule::run_exec_statement => {
2724                run_exec_pair = Some(inner);
2725            }
2726            Rule::instruction => {
2727                instruction_pair = Some(inner);
2728            }
2729            _ => {}
2730        }
2731    }
2732    let var = var.ok_or_else(|| {
2733        ParseError::validation("LET", "LET requires a variable".to_string(), &span)
2734    })?;
2735    let dtype: String = decl_type.ok_or_else(|| {
2736        ParseError::validation(
2737            "LET",
2738            "LET requires explicit type: LET $var: TYPE = ...".to_string(),
2739            &span,
2740        )
2741    })?;
2742    if let Some(awaited) = await_pair {
2743        let mut task_var = None;
2744        for inner in awaited.into_inner() {
2745            if inner.as_rule() == Rule::ident {
2746                task_var = Some(inner.as_str().to_string());
2747            }
2748        }
2749        return Ok(StepKind::AwaitCapture {
2750            out_var: var,
2751            out_type: dtype,
2752            task_var: task_var.ok_or_else(|| {
2753                ParseError::validation(
2754                    "LET",
2755                    "LET $out = AWAIT requires a task variable".to_string(),
2756                    &span,
2757                )
2758            })?,
2759        });
2760    }
2761    if let Some(timeouted) = timeout_pair {
2762        let kind = parse_structural_command_with_lower(ctx, timeouted, lctx)?;
2763        reject_async_in_capture(ctx, &kind)?;
2764        reject_pipe_stdout_in_capture(ctx, &kind)?;
2765        return Ok(StepKind::AssignCapture {
2766            var,
2767            decl_type: dtype,
2768            cmd: Box::new(kind),
2769        });
2770    }
2771    if let Some(exec) = run_exec_pair {
2772        let kind = lower_run_exec_pair(ctx, exec, lctx)?;
2773        reject_async_in_capture(ctx, &kind)?;
2774        reject_pipe_stdout_in_capture(ctx, &kind)?;
2775        return Ok(StepKind::AssignCapture {
2776            var,
2777            decl_type: dtype,
2778            cmd: Box::new(kind),
2779        });
2780    }
2781    if let Some(ins) = instruction_pair {
2782        let text = ins.as_str().to_string();
2783        let mut lead = None;
2784        for token in ins.clone().into_inner() {
2785            if token.as_rule() == Rule::command_name {
2786                lead = Some(token.as_str().to_string());
2787                break;
2788            }
2789        }
2790        let lead = lead.ok_or_else(|| {
2791            ParseError::validation("LET", "LET capture requires a command".to_string(), &span)
2792        })?;
2793        if crate::commands::is_known_command(&lead) {
2794            // Lower the already-parsed pair directly. Re-parsing its
2795            // text would nest a second full parse inside this one and
2796            // exhaust small stacks (musl release runner); spans also
2797            // keep their real line numbers this way.
2798            let kind = lower_instruction_pair(ctx, ins, lctx)?;
2799            reject_async_in_capture(ctx, &kind)?;
2800            reject_pipe_stdout_in_capture(ctx, &kind)?;
2801            return Ok(StepKind::AssignCapture {
2802                var,
2803                decl_type: dtype,
2804                cmd: Box::new(kind),
2805            });
2806        }
2807        let expr = parse_expr_str(&span, lctx, &text)?;
2808        return Ok(StepKind::Assign {
2809            var,
2810            decl_type: dtype,
2811            expr,
2812        });
2813    }
2814    Err(ParseError::structural(
2815        "let",
2816        "LET requires a value".to_string(),
2817        &span,
2818    ))
2819}
2820
2821fn parse_await_statement_from_pair(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<StepKind> {
2822    let span = refine_span(ctx, &pair);
2823    let mut var = None;
2824    for inner in pair.into_inner() {
2825        if inner.as_rule() == Rule::ident {
2826            var = Some(inner.as_str().to_string());
2827        }
2828    }
2829    Ok(StepKind::Await {
2830        var: var.ok_or_else(|| {
2831            ParseError::validation("AWAIT", "AWAIT requires a variable".to_string(), &span)
2832        })?,
2833    })
2834}
2835
2836fn parse_cancel_statement_from_pair(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<StepKind> {
2837    let span = refine_span(ctx, &pair);
2838    let mut var = None;
2839    for inner in pair.into_inner() {
2840        if inner.as_rule() == Rule::ident {
2841            var = Some(inner.as_str().to_string());
2842        }
2843    }
2844    Ok(StepKind::Cancel {
2845        var: var.ok_or_else(|| {
2846            ParseError::validation("CANCEL", "CANCEL requires a variable".to_string(), &span)
2847        })?,
2848    })
2849}
2850
2851/// Build a TIMEOUT duration [`Arg`] from the widened `timeout_duration`
2852/// alternatives. Static literals type-check now via the declared Duration
2853/// arg type; dynamics (`$var`, templates) resolve at runtime.
2854fn parse_timeout_duration_arg(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<Arg> {
2855    let span = refine_span(ctx, &pair);
2856    for inner in pair.into_inner() {
2857        let arg = match inner.as_rule() {
2858            Rule::timeout_literal => Arg::String(inner.as_str().to_string(), false),
2859            Rule::dollar_ident => Arg::Expr(Expr::Var(parse_dollar_ident(inner))),
2860            Rule::quoted_string => Arg::String(
2861                crate::command::strip_surrounding_quotes(inner.as_str()).to_string(),
2862                true,
2863            ),
2864            Rule::templated_arg => Arg::String(inner.as_str().to_string(), false),
2865            _ => continue,
2866        };
2867        ArgType::Duration
2868            .check_arg(&arg)
2869            .map_err(|e| ParseError::validation("TIMEOUT", e.to_string(), &span))?;
2870        return Ok(arg);
2871    }
2872    Err(ParseError::validation(
2873        "TIMEOUT",
2874        "TIMEOUT requires a duration".to_string(),
2875        &span,
2876    ))
2877}
2878
2879/// Lower `ISOLATED { ... }` (or a single command): parse the body, then
2880/// rewrite every nested prelude-shaped `INHERIT_ENV` into
2881/// `IsolatedInheritEnv` so the block allowlist reads the isolated
2882/// snapshot instead of the host. The rewrite runs here, during lowering,
2883/// so later validators only ever see the dedicated node inside `ISOLATED`
2884/// bodies and the prelude rule stays untouched.
2885fn parse_isolated_statement_from_pair(
2886    ctx: &SpanContext,
2887    pair: Pair<Rule>,
2888    lctx: &LowerCtx,
2889) -> ParseResult<StepKind> {
2890    let span = refine_span(ctx, &pair);
2891    let mut body: Option<Vec<Step>> = None;
2892    for inner in pair.into_inner() {
2893        match inner.as_rule() {
2894            Rule::block => {
2895                body = Some(parse_block_elements_with_lower(ctx, inner, lctx)?);
2896            }
2897            Rule::await_statement => {
2898                let kind = parse_await_statement_from_pair(ctx, inner)?;
2899                body = Some(vec![Step {
2900                    guard: None,
2901                    kind,
2902                    scope_enter: 0,
2903                    scope_exit: 0,
2904                }]);
2905            }
2906            Rule::cancel_statement => {
2907                let kind = parse_cancel_statement_from_pair(ctx, inner)?;
2908                body = Some(vec![Step {
2909                    guard: None,
2910                    kind,
2911                    scope_enter: 0,
2912                    scope_exit: 0,
2913                }]);
2914            }
2915            Rule::with_io_command
2916            | Rule::inherit_env_command
2917            | Rule::async_statement
2918            | Rule::async_statement_block
2919            | Rule::call_statement
2920            | Rule::while_statement
2921            | Rule::func_def
2922            | Rule::return_statement
2923            | Rule::break_statement
2924            | Rule::continue_statement
2925            | Rule::timeout_statement
2926            | Rule::isolated_statement
2927            | Rule::remote_statement => {
2928                let kind = parse_structural_command_with_lower(ctx, inner, lctx)?;
2929                body = Some(vec![Step {
2930                    guard: None,
2931                    kind,
2932                    scope_enter: 0,
2933                    scope_exit: 0,
2934                }]);
2935            }
2936            Rule::instruction | Rule::instruction_inner => {
2937                let kind = lower_instruction_pair(ctx, inner, lctx)?;
2938                body = Some(vec![Step {
2939                    guard: None,
2940                    kind,
2941                    scope_enter: 0,
2942                    scope_exit: 0,
2943                }]);
2944            }
2945            Rule::run_exec_statement | Rule::run_exec_inner => {
2946                let kind = lower_run_exec_pair(ctx, inner, lctx)?;
2947                body = Some(vec![Step {
2948                    guard: None,
2949                    kind,
2950                    scope_enter: 0,
2951                    scope_exit: 0,
2952                }]);
2953            }
2954            _ => {}
2955        }
2956    }
2957    let mut body = body.ok_or_else(|| {
2958        ParseError::validation(
2959            "ISOLATED",
2960            "ISOLATED requires a command or block".to_string(),
2961            &span,
2962        )
2963    })?;
2964    rewrite_isolated_inherit(&mut body);
2965    Ok(StepKind::Isolated { body })
2966}
2967
2968fn parse_timeout_statement_from_pair(
2969    ctx: &SpanContext,
2970    pair: Pair<Rule>,
2971    lctx: &LowerCtx,
2972) -> ParseResult<StepKind> {
2973    let span = refine_span(ctx, &pair);
2974    let mut duration: Option<Arg> = None;
2975    let mut body: Option<Vec<Step>> = None;
2976    for inner in pair.into_inner() {
2977        match inner.as_rule() {
2978            Rule::timeout_duration => {
2979                duration = Some(parse_timeout_duration_arg(ctx, inner)?);
2980            }
2981            Rule::block => {
2982                body = Some(parse_block_elements_with_lower(ctx, inner, lctx)?);
2983            }
2984            Rule::await_statement => {
2985                let kind = parse_await_statement_from_pair(ctx, inner)?;
2986                body = Some(vec![Step {
2987                    guard: None,
2988                    kind,
2989                    scope_enter: 0,
2990                    scope_exit: 0,
2991                }]);
2992            }
2993            Rule::cancel_statement => {
2994                let kind = parse_cancel_statement_from_pair(ctx, inner)?;
2995                body = Some(vec![Step {
2996                    guard: None,
2997                    kind,
2998                    scope_enter: 0,
2999                    scope_exit: 0,
3000                }]);
3001            }
3002            Rule::with_io_command
3003            | Rule::inherit_env_command
3004            | Rule::async_statement
3005            | Rule::async_statement_block
3006            | Rule::call_statement
3007            | Rule::while_statement
3008            | Rule::func_def
3009            | Rule::return_statement
3010            | Rule::break_statement
3011            | Rule::continue_statement
3012            | Rule::timeout_statement
3013            | Rule::isolated_statement
3014            | Rule::remote_statement => {
3015                let kind = parse_structural_command_with_lower(ctx, inner, lctx)?;
3016                body = Some(vec![Step {
3017                    guard: None,
3018                    kind,
3019                    scope_enter: 0,
3020                    scope_exit: 0,
3021                }]);
3022            }
3023            Rule::instruction | Rule::instruction_inner => {
3024                let kind = lower_instruction_pair(ctx, inner, lctx)?;
3025                body = Some(vec![Step {
3026                    guard: None,
3027                    kind,
3028                    scope_enter: 0,
3029                    scope_exit: 0,
3030                }]);
3031            }
3032            Rule::run_exec_statement | Rule::run_exec_inner => {
3033                let kind = lower_run_exec_pair(ctx, inner, lctx)?;
3034                body = Some(vec![Step {
3035                    guard: None,
3036                    kind,
3037                    scope_enter: 0,
3038                    scope_exit: 0,
3039                }]);
3040            }
3041            _ => {}
3042        }
3043    }
3044    Ok(StepKind::Timeout {
3045        duration: duration.ok_or_else(|| {
3046            ParseError::validation("TIMEOUT", "TIMEOUT requires a duration".to_string(), &span)
3047        })?,
3048        body: body.ok_or_else(|| {
3049            ParseError::validation(
3050                "TIMEOUT",
3051                "TIMEOUT requires a command or block".to_string(),
3052                &span,
3053            )
3054        })?,
3055    })
3056}
3057
3058/// True when any step in the slice (transitively, through nested bodies)
3059/// is a `REMOTE` block. `REMOTE` blocks never nest: the inner block would
3060/// have no session, no inventory, and no defined sync boundary.
3061fn contains_remote_block(steps: &[Step]) -> bool {
3062    steps.iter().any(|step| contains_remote_kind(&step.kind))
3063}
3064
3065/// Rewrite prelude-shaped `INHERIT_ENV` nodes anywhere inside an `ISOLATED`
3066/// body into `IsolatedInheritEnv`: the nested allowlist reads the isolated
3067/// snapshot, never the host. Distinct node, distinct read rule, so the
3068/// prelude validator (which only knows `InheritEnv`) never fires here and
3069/// diagnostics stay unambiguous.
3070fn rewrite_isolated_inherit(body: &mut [Step]) {
3071    for step in body {
3072        rewrite_isolated_inherit_kind(&mut step.kind);
3073    }
3074}
3075
3076/// Single-kind half of [`rewrite_isolated_inherit`]: rewrite the node
3077/// itself, then recurse through whatever it contains (`WITH_IO` wraps and
3078/// `LET`-capture nest one boxed command; every other body is a step
3079/// slice with the same treatment). `FUNC` and `REMOTE` bodies are
3080/// deliberately skipped: function bodies execute at call time (possibly
3081/// after the block exits and its snapshot is gone) and remote bodies ship
3082/// to guests under their own bridging, so a nested `INHERIT_ENV` there
3083/// keeps the standard prelude-nesting rejection instead of silently
3084/// changing read rules.
3085fn rewrite_isolated_inherit_kind(kind: &mut StepKind) {
3086    if let StepKind::InheritEnv { keys } = kind {
3087        *kind = StepKind::IsolatedInheritEnv { keys: keys.clone() };
3088    }
3089    match kind {
3090        StepKind::For { body, .. }
3091        | StepKind::While { body, .. }
3092        | StepKind::Timeout { body, .. }
3093        | StepKind::Isolated { body }
3094        | StepKind::AssignAsync { body, .. }
3095        | StepKind::AsyncBlock { body } => rewrite_isolated_inherit(body),
3096        StepKind::If {
3097            then_body,
3098            else_ifs,
3099            else_body,
3100            ..
3101        } => {
3102            rewrite_isolated_inherit(then_body);
3103            for (_, branch) in else_ifs {
3104                rewrite_isolated_inherit(branch);
3105            }
3106            if let Some(else_body) = else_body {
3107                rewrite_isolated_inherit(else_body);
3108            }
3109        }
3110        StepKind::WithIo { cmd, .. } | StepKind::AssignCapture { cmd, .. } => {
3111            rewrite_isolated_inherit_kind(cmd);
3112        }
3113        _ => {}
3114    }
3115}
3116
3117fn contains_remote_kind(kind: &StepKind) -> bool {
3118    if matches!(kind, StepKind::RemoteBlock { .. }) {
3119        return true;
3120    }
3121    let mut found = false;
3122    kind.walk_child_kinds(&mut |child| {
3123        found = found || contains_remote_kind(child);
3124    });
3125    found
3126}
3127
3128/// Collect transitively defined `FUNC` names and invoked call names from a
3129/// `REMOTE` body. Statement calls, expression calls (including compiled
3130/// math ops and inline blocks), and calls nested in any sub-body are all
3131/// covered through the uniform [`StepKind`] walkers. Only user-defined
3132/// `SCRIPT` symbols matter downstream: qualified module calls pass through.
3133fn collect_remote_body_symbols(
3134    steps: &[Step],
3135    defs: &mut HashSet<String>,
3136    calls: &mut Vec<String>,
3137) {
3138    for step in steps {
3139        collect_remote_kind_symbols(&step.kind, defs, calls);
3140    }
3141}
3142
3143fn collect_remote_kind_symbols(
3144    kind: &StepKind,
3145    defs: &mut HashSet<String>,
3146    calls: &mut Vec<String>,
3147) {
3148    if let StepKind::FuncDef { name, .. } = kind {
3149        defs.insert(name.clone());
3150    }
3151    if let StepKind::Call { name, .. } = kind {
3152        calls.push(name.clone());
3153    }
3154    kind.walk_step_exprs(&mut |expr| match expr {
3155        Expr::Call { name, .. } => calls.push(name.clone()),
3156        Expr::CompiledMath(ops) => {
3157            for op in ops {
3158                if let MathOp::Call { name, .. } = op {
3159                    calls.push(name.clone());
3160                }
3161            }
3162        }
3163        Expr::Block(steps) => collect_remote_body_symbols(steps, defs, calls),
3164        _ => {}
3165    });
3166}
3167
3168fn parse_remote_statement_from_pair(
3169    ctx: &SpanContext,
3170    pair: Pair<Rule>,
3171    lctx: &LowerCtx,
3172) -> ParseResult<StepKind> {
3173    let span = refine_span(ctx, &pair);
3174    let mut target: Option<String> = None;
3175    let mut vars: Vec<String> = Vec::new();
3176    let mut env: Vec<String> = Vec::new();
3177    let mut body: Option<Vec<Step>> = None;
3178    for inner in pair.into_inner() {
3179        match inner.as_rule() {
3180            Rule::remote_target => {
3181                target = Some(inner.as_str().to_string());
3182            }
3183            Rule::remote_bindings => {
3184                for binding in inner.into_inner() {
3185                    // Direct children are `remote_binding` wrappers (commas
3186                    // and gaps are silent); unwrap one level leniently.
3187                    let entry = if binding.as_rule() == Rule::remote_binding {
3188                        binding.into_inner().next()
3189                    } else {
3190                        Some(binding)
3191                    };
3192                    let Some(entry) = entry else {
3193                        continue;
3194                    };
3195                    match entry.as_rule() {
3196                        Rule::remote_var_binding => {
3197                            let mut name = None;
3198                            for part in entry.into_inner() {
3199                                if part.as_rule() == Rule::ident {
3200                                    name = Some(part.as_str().to_string());
3201                                }
3202                            }
3203                            vars.push(name.ok_or_else(|| {
3204                                ParseError::validation(
3205                                    "REMOTE",
3206                                    "REMOTE header entries must be `$var` or `env:NAME`"
3207                                        .to_string(),
3208                                    &span,
3209                                )
3210                            })?);
3211                        }
3212                        Rule::remote_env_binding => {
3213                            let mut name = None;
3214                            for part in entry.into_inner() {
3215                                if part.as_rule() == Rule::env_read_key {
3216                                    name = Some(part.as_str().to_string());
3217                                }
3218                            }
3219                            env.push(name.ok_or_else(|| {
3220                                ParseError::validation(
3221                                    "REMOTE",
3222                                    "REMOTE header entries must be `$var` or `env:NAME`"
3223                                        .to_string(),
3224                                    &span,
3225                                )
3226                            })?);
3227                        }
3228                        _ => {}
3229                    }
3230                }
3231            }
3232            Rule::block => {
3233                body = Some(parse_block_elements_with_lower(ctx, inner, lctx)?);
3234            }
3235            _ => {}
3236        }
3237    }
3238    let target = target.ok_or_else(|| {
3239        ParseError::validation("REMOTE", "REMOTE requires a target".to_string(), &span)
3240    })?;
3241    if !crate::commands::is_valid_remote_target(&target) {
3242        return Err(ParseError::validation(
3243            "REMOTE",
3244            format!(
3245                "invalid REMOTE target `{target}`: start alphanumeric, then alphanumeric, `_`, or `-`, max 64 chars, never SNAPSHOT, LOCAL, CACHE, SYSTEM, or REMOTE"
3246            ),
3247            &span,
3248        ));
3249    }
3250    let body = body.ok_or_else(|| {
3251        ParseError::validation(
3252            "REMOTE",
3253            "REMOTE requires a braced block, e.g. `REMOTE prod [$version] { ... }`".to_string(),
3254            &span,
3255        )
3256    })?;
3257    if body.is_empty() {
3258        return Err(ParseError::validation(
3259            "REMOTE",
3260            "REMOTE requires a non-empty braced block".to_string(),
3261            &span,
3262        ));
3263    }
3264    if contains_remote_block(&body) {
3265        return Err(ParseError::validation(
3266            "REMOTE",
3267            format!("REMOTE blocks cannot nest (target `{target}` contains another REMOTE block)"),
3268            &span,
3269        ));
3270    }
3271    if body.iter().any(|s| contains_inherit_env(&s.kind)) {
3272        return Err(ParseError::validation(
3273            "REMOTE",
3274            "INHERIT_ENV cannot appear inside a REMOTE block: the guest inherits its own process environment".to_string(),
3275            &span,
3276        ));
3277    }
3278    let mut inner_defs = HashSet::new();
3279    let mut calls = Vec::new();
3280    collect_remote_body_symbols(&body, &mut inner_defs, &mut calls);
3281    let outer_defs = lctx.visible_func_names();
3282    for call in &calls {
3283        let bare = crate::base_name(call);
3284        let is_script_call = match crate::split_qualified(call) {
3285            Some((module, _)) => module == crate::constants::SCRIPT_MODULE_NAME,
3286            None => true,
3287        };
3288        if is_script_call && outer_defs.contains(bare) && !inner_defs.contains(bare) {
3289            return Err(ParseError::validation(
3290                "REMOTE",
3291                format!(
3292                    "REMOTE '{target}' calls outer function '{bare}' (functions must be defined inside the block)"
3293                ),
3294                &span,
3295            ));
3296        }
3297    }
3298    Ok(StepKind::RemoteBlock {
3299        target,
3300        vars,
3301        env,
3302        body,
3303    })
3304}
3305
3306fn parse_if_statement_from_pair(
3307    ctx: &SpanContext,
3308    pair: Pair<Rule>,
3309    lctx: &LowerCtx,
3310) -> ParseResult<StepKind> {
3311    let span = refine_span(ctx, &pair);
3312    let mut cond = None;
3313    let mut then_body = Vec::new();
3314    let mut else_ifs = Vec::new();
3315    let mut else_body = None;
3316
3317    for inner in pair.into_inner() {
3318        match inner.as_rule() {
3319            Rule::expr => {
3320                if cond.is_none() {
3321                    cond = Some(parse_expr(ctx, lctx, inner)?);
3322                }
3323            }
3324            Rule::block => {
3325                if then_body.is_empty() {
3326                    then_body = parse_block_elements_with_lower(ctx, inner, lctx)?;
3327                }
3328            }
3329            Rule::else_if_clause => {
3330                let (eif_cond, eif_body) = parse_else_if_clause(ctx, inner, lctx)?;
3331                else_ifs.push((eif_cond, eif_body));
3332            }
3333            Rule::else_clause => {
3334                else_body = Some(parse_else_clause(ctx, inner, lctx)?);
3335            }
3336            _ => {}
3337        }
3338    }
3339    Ok(StepKind::If {
3340        cond: Box::new(cond.ok_or_else(|| {
3341            ParseError::structural("if", "IF requires a condition".to_string(), &span)
3342        })?),
3343        then_body,
3344        else_ifs,
3345        else_body,
3346    })
3347}
3348
3349fn parse_else_if_clause(
3350    ctx: &SpanContext,
3351    pair: Pair<Rule>,
3352    lctx: &LowerCtx,
3353) -> ParseResult<(Box<Expr>, Vec<Step>)> {
3354    let span = refine_span(ctx, &pair);
3355    let mut cond = None;
3356    let mut body = Vec::new();
3357    for inner in pair.into_inner() {
3358        match inner.as_rule() {
3359            Rule::expr => cond = Some(parse_expr(ctx, lctx, inner)?),
3360            Rule::block => body = parse_block_elements_with_lower(ctx, inner, lctx)?,
3361            _ => {}
3362        }
3363    }
3364    Ok((
3365        Box::new(cond.ok_or_else(|| {
3366            ParseError::structural("if", "ELSE IF requires a condition".to_string(), &span)
3367        })?),
3368        body,
3369    ))
3370}
3371
3372fn parse_else_clause(
3373    ctx: &SpanContext,
3374    pair: Pair<Rule>,
3375    lctx: &LowerCtx,
3376) -> ParseResult<Vec<Step>> {
3377    for inner in pair.into_inner() {
3378        if let Rule::block = inner.as_rule() {
3379            return parse_block_elements_with_lower(ctx, inner, lctx);
3380        }
3381    }
3382    Ok(Vec::new())
3383}
3384
3385fn parse_async_statement_from_pair(
3386    ctx: &SpanContext,
3387    pair: Pair<Rule>,
3388    lctx: &LowerCtx,
3389) -> ParseResult<StepKind> {
3390    let span = refine_span(ctx, &pair);
3391    let mut inner_cmd = None;
3392    let mut block_body = None;
3393    for inner in pair.into_inner() {
3394        match inner.as_rule() {
3395            Rule::command => {
3396                // command is _{} = silent, so its children aren't visible as pairs
3397                // when nested inside compound-atomic async_statement.
3398                // Parse the command text directly, seeding the snippet with
3399                // this point's visible scope so calls resolve identically.
3400                let cmd_text = inner.as_str();
3401                let (preseed_funcs, preseed_imports) = lctx.visible_snapshot();
3402                let steps = parse_script_with_preseed(
3403                    cmd_text,
3404                    |name, args| (lctx.lower)(name, args),
3405                    lctx.reserved_names.clone(),
3406                    lctx.modules.clone(),
3407                    preseed_funcs,
3408                    preseed_imports,
3409                )?;
3410                if steps.len() == 1 {
3411                    inner_cmd = Some(steps.into_iter().next().unwrap().kind);
3412                } else {
3413                    return Err(ParseError::structural(
3414                        "async",
3415                        "unexpected multiple steps in async inner command".to_string(),
3416                        &span,
3417                    ));
3418                }
3419            }
3420            Rule::command_inner => {
3421                // command_inner = { inherit_env_command | async_statement | async_statement_block | instruction }
3422                let child = inner.into_inner().next().ok_or_else(|| {
3423                    ParseError::structural("async", "empty command_inner".to_string(), &span)
3424                })?;
3425                match child.as_rule() {
3426                    Rule::inherit_env_command => {
3427                        inner_cmd = Some(parse_structural_command_with_lower(ctx, child, lctx)?);
3428                    }
3429                    Rule::async_statement | Rule::async_statement_block => {
3430                        inner_cmd = Some(parse_structural_command_with_lower(ctx, child, lctx)?);
3431                    }
3432                    Rule::timeout_statement | Rule::cancel_statement => {
3433                        inner_cmd = Some(parse_structural_command_with_lower(ctx, child, lctx)?);
3434                    }
3435                    Rule::isolated_statement => {
3436                        inner_cmd = Some(parse_structural_command_with_lower(ctx, child, lctx)?);
3437                    }
3438                    Rule::remote_statement => {
3439                        inner_cmd = Some(parse_structural_command_with_lower(ctx, child, lctx)?);
3440                    }
3441                    Rule::call_statement | Rule::while_statement => {
3442                        inner_cmd = Some(parse_structural_command_with_lower(ctx, child, lctx)?);
3443                    }
3444                    Rule::func_def
3445                    | Rule::return_statement
3446                    | Rule::break_statement
3447                    | Rule::continue_statement => {
3448                        return Err(ParseError::structural(
3449                            "async",
3450                            format!(
3451                                "{:?} cannot run as a lone ASYNC command; use ASYNC {{ ... }} block form if needed",
3452                                child.as_rule()
3453                            ),
3454                            &span,
3455                        ));
3456                    }
3457                    Rule::instruction => {
3458                        inner_cmd = Some(lower_instruction_pair(ctx, child, lctx)?);
3459                    }
3460                    Rule::run_exec_statement | Rule::run_exec_inner => {
3461                        inner_cmd = Some(lower_run_exec_pair(ctx, child, lctx)?);
3462                    }
3463                    other => {
3464                        return Err(ParseError::structural(
3465                            "async",
3466                            format!("unexpected command_inner child: {:?}", other),
3467                            &span,
3468                        ));
3469                    }
3470                }
3471            }
3472            Rule::instruction | Rule::instruction_inner => {
3473                inner_cmd = Some(lower_instruction_pair(ctx, inner, lctx)?);
3474            }
3475            Rule::run_exec_statement | Rule::run_exec_inner => {
3476                inner_cmd = Some(lower_run_exec_pair(ctx, inner, lctx)?);
3477            }
3478            Rule::block => {
3479                block_body = Some(parse_block_elements_with_lower(ctx, inner, lctx)?);
3480            }
3481            _ => {}
3482        }
3483    }
3484    if let Some(body) = block_body {
3485        for step in &body {
3486            if matches!(&step.kind, StepKind::WithIo { .. }) {
3487                return Err(ParseError::structural("async", "WITH_IO cannot be placed inside ASYNC. Place WITH_IO outside ASYNC instead (e.g. WITH_IO [...] ASYNC RUN ...)".to_string(), &span));
3488            }
3489        }
3490        Ok(StepKind::AsyncBlock { body })
3491    } else if let Some(cmd) = inner_cmd {
3492        if matches!(&cmd, StepKind::WithIo { .. }) {
3493            return Err(ParseError::structural("async", "WITH_IO cannot be placed inside ASYNC. Place WITH_IO outside ASYNC instead (e.g. WITH_IO [...] ASYNC RUN ...)".to_string(), &span));
3494        }
3495        Ok(StepKind::AsyncBlock {
3496            body: vec![Step {
3497                guard: None,
3498                kind: cmd,
3499                scope_enter: 0,
3500                scope_exit: 0,
3501            }],
3502        })
3503    } else {
3504        Err(ParseError::structural(
3505            "async",
3506            "ASYNC requires either a command or a block".to_string(),
3507            &span,
3508        ))
3509    }
3510}
3511
3512fn parse_async_statement_block_from_pair(
3513    ctx: &SpanContext,
3514    pair: Pair<Rule>,
3515    lctx: &LowerCtx,
3516) -> ParseResult<StepKind> {
3517    let span = refine_span(ctx, &pair);
3518    let mut block_body = None;
3519    for inner in pair.into_inner() {
3520        if inner.as_rule() == Rule::block {
3521            block_body = Some(parse_block_elements_with_lower(ctx, inner, lctx)?);
3522        }
3523    }
3524    let body = block_body.ok_or_else(|| {
3525        ParseError::structural(
3526            "async",
3527            "async_statement_block requires a block".to_string(),
3528            &span,
3529        )
3530    })?;
3531    for step in &body {
3532        if matches!(&step.kind, StepKind::WithIo { .. }) {
3533            return Err(ParseError::structural("async", "WITH_IO cannot be placed inside ASYNC. Place WITH_IO outside ASYNC instead (e.g. WITH_IO [...] ASYNC RUN ...)".to_string(), &span));
3534        }
3535    }
3536    Ok(StepKind::AsyncBlock { body })
3537}
3538
3539/// Lower an `IMPORT` statement: update the import frames, emit nothing.
3540fn lower_import_statement(ctx: &SpanContext, pair: Pair<Rule>, lctx: &LowerCtx) -> ParseResult<()> {
3541    let mut modules = Vec::new();
3542    for inner in pair.into_inner() {
3543        match inner.as_rule() {
3544            Rule::import_list => {
3545                for module in inner.into_inner() {
3546                    if module.as_rule() == Rule::import_module {
3547                        modules.push(module.as_str().to_string());
3548                    }
3549                }
3550            }
3551            Rule::import_module => modules.push(inner.as_str().to_string()),
3552            _ => {}
3553        }
3554    }
3555    lctx.import_modules(ctx, &modules)
3556}
3557
3558fn parse_block_elements_with_lower(
3559    ctx: &SpanContext,
3560    block_pair: Pair<Rule>,
3561    lctx: &LowerCtx,
3562) -> ParseResult<Vec<Step>> {
3563    // One function scope per braced body, mirroring the runtime
3564    // `push_scope`/`pop_scope` boundary: same-block `FUNC` redefinition
3565    // errors, nested shadowing stays allowed.
3566    lctx.enter_scope();
3567    let mut steps = Vec::new();
3568    // Bare guard lines inside blocks attach to the next step parsed here.
3569    // Previously they fell into the catch-all and vanished, so inner
3570    // guards never reached the engine; block bodies now honor them exactly
3571    // like top-level lines (a dangling guard at `}` is a structural error).
3572    let mut pending_guard: Option<GuardExpr> = None;
3573    for elem in block_pair.into_inner() {
3574        match elem.as_rule() {
3575            Rule::guard_line => {
3576                let guard = parse_guard_line(ctx, elem)?;
3577                pending_guard = Some(match pending_guard.take() {
3578                    Some(existing) => GuardExpr::all(vec![existing, guard]),
3579                    None => guard,
3580                });
3581                continue;
3582            }
3583            Rule::for_statement
3584            | Rule::while_statement
3585            | Rule::func_def
3586            | Rule::call_statement
3587            | Rule::return_statement
3588            | Rule::break_statement
3589            | Rule::continue_statement
3590            | Rule::let_statement
3591            | Rule::mutate_statement
3592            | Rule::let_async_statement
3593            | Rule::let_capture_statement
3594            | Rule::await_statement
3595            | Rule::cancel_statement
3596            | Rule::if_statement
3597            | Rule::async_statement
3598            | Rule::timeout_statement
3599            | Rule::isolated_statement
3600            | Rule::remote_statement
3601            | Rule::async_statement_block => {
3602                let step_kind = parse_structural_command_with_lower(ctx, elem, lctx)?;
3603                steps.push(Step {
3604                    guard: pending_guard.take(),
3605                    kind: step_kind,
3606                    scope_enter: 0,
3607                    scope_exit: 0,
3608                });
3609            }
3610            Rule::type_statement => {
3611                return Err(ParseError::structural(
3612                    KEYWORD_TYPE,
3613                    "TYPE must appear at top level".to_string(),
3614                    ctx,
3615                ));
3616            }
3617            Rule::guard_block => {
3618                let mut guard_pair = None;
3619                let mut inner_block = None;
3620                for inner in elem.into_inner() {
3621                    match inner.as_rule() {
3622                        Rule::guard_line => guard_pair = Some(inner),
3623                        Rule::block => inner_block = Some(inner),
3624                        _ => {}
3625                    }
3626                }
3627                if let (Some(gp), Some(bp)) = (guard_pair, inner_block) {
3628                    let guard_expr = parse_guard_line(ctx, gp)?;
3629                    let mut inner_steps = parse_block_elements_with_lower(ctx, bp, lctx)?;
3630                    for step in &mut inner_steps {
3631                        let inner = step.guard.take();
3632                        step.guard = Some(match (pending_guard.clone(), inner) {
3633                            (Some(pending), Some(existing)) => {
3634                                GuardExpr::all(vec![pending, existing])
3635                            }
3636                            (Some(pending), None) => {
3637                                GuardExpr::all(vec![pending, guard_expr.clone()])
3638                            }
3639                            (None, Some(existing)) => existing,
3640                            (None, None) => guard_expr.clone(),
3641                        });
3642                    }
3643                    // A bare guard line composes into the braced block that
3644                    // follows it and is consumed, like an inline guard.
3645                    pending_guard = None;
3646                    steps.extend(inner_steps);
3647                }
3648            }
3649            Rule::instruction | Rule::instruction_inner => {
3650                let kind = lower_instruction_pair(ctx, elem, lctx)?;
3651                steps.push(Step {
3652                    guard: pending_guard.take(),
3653                    kind,
3654                    scope_enter: 0,
3655                    scope_exit: 0,
3656                });
3657            }
3658            Rule::run_exec_statement | Rule::run_exec_inner => {
3659                let kind = lower_run_exec_pair(ctx, elem, lctx)?;
3660                steps.push(Step {
3661                    guard: pending_guard.take(),
3662                    kind,
3663                    scope_enter: 0,
3664                    scope_exit: 0,
3665                });
3666            }
3667            Rule::with_io_command => {
3668                let step_kind = parse_structural_command_with_lower(ctx, elem, lctx)?;
3669                steps.push(Step {
3670                    guard: pending_guard.take(),
3671                    kind: step_kind,
3672                    scope_enter: 0,
3673                    scope_exit: 0,
3674                });
3675            }
3676            Rule::inherit_env_command => {
3677                let step_kind = parse_structural_command_with_lower(ctx, elem, lctx)?;
3678                steps.push(Step {
3679                    guard: pending_guard.take(),
3680                    kind: step_kind,
3681                    scope_enter: 0,
3682                    scope_exit: 0,
3683                });
3684            }
3685            Rule::import_statement => {
3686                // Lowering directive: updates import frames, emits no step.
3687                // A guard block wrapping only IMPORTs yields no steps, so
3688                // its guard binds nothing; IMPORT itself stays static.
3689                lower_import_statement(ctx, elem, lctx)?;
3690            }
3691            Rule::export_statement => {
3692                return Err(ParseError::structural(
3693                    KEYWORD_EXPORT,
3694                    "EXPORT is only allowed at the top level".to_string(),
3695                    ctx,
3696                ));
3697            }
3698            _ => {} // blank, hash_comment, semicolon, etc.
3699        }
3700    }
3701    if pending_guard.is_some() {
3702        return Err(ParseError::structural(
3703            "guard",
3704            "guard declared immediately before '}' without a command".to_string(),
3705            ctx,
3706        ));
3707    }
3708    lctx.exit_scope();
3709    Ok(steps)
3710}
3711
3712fn parse_argument(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Vec<Arg>> {
3713    let inners: Vec<_> = pair.into_inner().collect();
3714    // An `expr` fragment can swallow its trailing separator through inner
3715    // `gap` rules, gluing following text into one argument pair
3716    // (`ECHO $x hello` lexes as `[expr("$x "), unquoted("hello")]`). Split
3717    // groups there so expressions survive as typed `Arg::Expr`; every other
3718    // fragment kind is whitespace-tight by construction.
3719    let mut groups: Vec<Vec<Pair<Rule>>> = vec![Vec::new()];
3720    for fragment in inners {
3721        let glued = fragment.as_rule() == Rule::expr
3722            && fragment.as_str().ends_with(|c: char| c.is_whitespace());
3723        groups
3724            .last_mut()
3725            .expect("argument always holds a group")
3726            .push(fragment);
3727        if glued {
3728            groups.push(Vec::new());
3729        }
3730    }
3731    let mut args = Vec::new();
3732    for group in groups {
3733        if group.is_empty() {
3734            continue;
3735        }
3736        // Single expression : preserve as Arg::Expr for runtime evaluation
3737        if group.len() == 1 && group[0].as_rule() == Rule::expr {
3738            args.push(Arg::Expr(parse_expr(
3739                ctx,
3740                lctx,
3741                group.into_iter().next().expect("group holds one pair"),
3742            )?));
3743            continue;
3744        }
3745        // Single quoted string: preserve quote status and process escapes
3746        if group.len() == 1 && group[0].as_rule() == Rule::string_literal {
3747            args.push(Arg::String(parse_fragments(&group)?, true));
3748            continue;
3749        }
3750        args.push(Arg::String(parse_fragments(&group)?, false));
3751    }
3752    Ok(args)
3753}
3754
3755fn parse_quoted_string(pair: Pair<Rule>) -> ParseResult<String> {
3756    let s = pair.as_str();
3757    let content = &s[1..s.len() - 1];
3758    // Pass contents verbatim : all escape processing deferred to runtime expand_string
3759    Ok(content.to_string())
3760}
3761
3762/// Concatenate fragment pairs (string_literal, templated_arg, unquoted_arg, expr)
3763/// into a single String. Adjacent fragments without whitespace are joined directly;
3764/// fragments separated by whitespace get a space inserted.
3765fn parse_fragments(parts: &[Pair<Rule>]) -> ParseResult<String> {
3766    // Single quoted string: unquote unconditionally
3767    if parts.len() == 1 && parts[0].as_rule() == Rule::string_literal {
3768        let s = parts[0].as_str();
3769        return Ok(s[1..s.len() - 1].to_string());
3770    }
3771
3772    let mut body = String::new();
3773    let mut last_end = None;
3774    for part in parts {
3775        let span = part.as_span();
3776        if let Some(end) = last_end
3777            && span.start() > end
3778        {
3779            body.push(' ');
3780        }
3781        match part.as_rule() {
3782            Rule::string_literal => {
3783                let s = part.as_str();
3784                let unquoted = &s[1..s.len() - 1];
3785                body.push_str(unquoted);
3786            }
3787            Rule::templated_arg | Rule::unquoted_arg => {
3788                body.push_str(part.as_str());
3789            }
3790            Rule::expr => body.push_str(part.as_str()),
3791            _ => {}
3792        }
3793        last_end = Some(span.end());
3794    }
3795    Ok(body)
3796}
3797
3798fn parse_guard_line(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
3799    let span = refine_span(ctx, &pair);
3800    for inner in pair.into_inner() {
3801        if inner.as_rule() == Rule::guard_expr {
3802            return parse_guard_expr(ctx, inner);
3803        }
3804    }
3805    Err(ParseError::structural(
3806        "guard",
3807        "guard line missing expression".to_string(),
3808        &span,
3809    ))
3810}
3811
3812fn parse_io_binding(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<IoBinding> {
3813    let span = refine_span(ctx, &pair);
3814    let mut stream = None;
3815    let mut pipe = None;
3816    for inner in pair.into_inner() {
3817        match inner.as_rule() {
3818            Rule::io_stream => stream = Some(parse_io_stream(inner.as_str())),
3819            Rule::pipe_binding => pipe = Some(parse_pipe_binding(ctx, inner)?),
3820            _ => {}
3821        }
3822    }
3823    let stream = stream.ok_or_else(|| {
3824        ParseError::structural("with_io", "missing IO stream in WITH_IO".to_string(), &span)
3825    })?;
3826    Ok(IoBinding { stream, pipe })
3827}
3828
3829fn parse_io_stream(text: &str) -> IoStream {
3830    match text {
3831        "stdin" => IoStream::Stdin,
3832        "stdout" => IoStream::Stdout,
3833        "stderr" => IoStream::Stderr,
3834        _ => unreachable!("parser produced invalid io_stream token"),
3835    }
3836}
3837
3838fn parse_pipe_binding(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<PipeTarget> {
3839    let span = refine_span(ctx, &pair);
3840    for inner in pair.into_inner() {
3841        if inner.as_rule() == Rule::dollar_ident {
3842            return Ok(PipeTarget::Var(parse_dollar_ident(inner)));
3843        }
3844    }
3845    Err(ParseError::structural(
3846        "with_io",
3847        "missing pipe identifier in WITH_IO binding".to_string(),
3848        &span,
3849    ))
3850}
3851
3852fn parse_guard_expr(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
3853    let span = refine_span(ctx, &pair);
3854    match pair.as_rule() {
3855        Rule::guard_expr => {
3856            let next = pair.into_inner().next().ok_or_else(|| {
3857                ParseError::structural("guard", "guard expression missing body".to_string(), &span)
3858            })?;
3859            parse_guard_expr(ctx, next)
3860        }
3861        Rule::guard_seq => parse_guard_seq(ctx, pair),
3862        Rule::guard_factor => parse_guard_factor(ctx, pair),
3863        Rule::guard_not => {
3864            // guard_not is silent, so its inner pairs are the actual content
3865            Err(ParseError::structural(
3866                "guard",
3867                "guard_not should not create a pair".to_string(),
3868                &span,
3869            ))
3870        }
3871        Rule::guard_primary => parse_guard_primary(ctx, pair),
3872        Rule::guard_group => parse_guard_group(ctx, pair),
3873        Rule::guard_any_call => parse_guard_any_call(ctx, pair),
3874        Rule::guard_all_call => parse_guard_all_call(ctx, pair),
3875        Rule::not_call => parse_not_call(ctx, pair),
3876        Rule::guard_term => parse_guard_term(ctx, pair),
3877        _ => Err(ParseError::structural(
3878            "guard",
3879            format!("unexpected guard expression rule: {:?}", pair.as_rule()),
3880            &span,
3881        )),
3882    }
3883}
3884
3885fn parse_guard_seq(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
3886    let span = refine_span(ctx, &pair);
3887    let mut exprs = Vec::new();
3888    for inner in pair.into_inner() {
3889        if inner.as_rule() == Rule::guard_factor {
3890            exprs.push(parse_guard_factor(ctx, inner)?);
3891        }
3892    }
3893    match exprs.len() {
3894        0 => Err(ParseError::structural(
3895            "guard",
3896            "guard list requires at least one entry".to_string(),
3897            &span,
3898        )),
3899        1 => Ok(exprs.pop().unwrap()),
3900        _ => Ok(GuardExpr::all(exprs)),
3901    }
3902}
3903
3904fn parse_guard_factor(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
3905    let span = refine_span(ctx, &pair);
3906    let inner = pair.into_inner().next().ok_or_else(|| {
3907        ParseError::structural(
3908            "guard",
3909            "guard factor missing expression".to_string(),
3910            &span,
3911        )
3912    })?;
3913    parse_guard_expr(ctx, inner)
3914}
3915
3916fn parse_not_call(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
3917    let span = refine_span(ctx, &pair);
3918    for inner in pair.into_inner() {
3919        if inner.as_rule() == Rule::guard_expr {
3920            return parse_guard_expr(ctx, inner).map(|e| GuardExpr::Not(Box::new(e)));
3921        }
3922    }
3923    Err(ParseError::structural(
3924        "guard",
3925        "not() missing expression".to_string(),
3926        &span,
3927    ))
3928}
3929
3930fn parse_guard_primary(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
3931    let span = refine_span(ctx, &pair);
3932    match pair.as_rule() {
3933        Rule::guard_primary => {
3934            let inner = pair.into_inner().next().ok_or_else(|| {
3935                ParseError::structural("guard", "guard primary missing body".to_string(), &span)
3936            })?;
3937            parse_guard_primary(ctx, inner)
3938        }
3939        Rule::guard_group => parse_guard_group(ctx, pair),
3940        Rule::guard_any_call => parse_guard_any_call(ctx, pair),
3941        Rule::guard_all_call => parse_guard_all_call(ctx, pair),
3942        Rule::not_call => parse_not_call(ctx, pair),
3943        Rule::guard_term => parse_guard_term(ctx, pair),
3944        _ => Err(ParseError::structural(
3945            "guard",
3946            format!("unexpected guard primary rule: {:?}", pair.as_rule()),
3947            &span,
3948        )),
3949    }
3950}
3951
3952fn parse_guard_group(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
3953    let span = refine_span(ctx, &pair);
3954    for inner in pair.into_inner() {
3955        if inner.as_rule() == Rule::guard_expr {
3956            return parse_guard_expr(ctx, inner);
3957        }
3958    }
3959    Err(ParseError::structural(
3960        "guard",
3961        "grouped guard missing expression".to_string(),
3962        &span,
3963    ))
3964}
3965
3966fn parse_guard_any_call(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
3967    let span = refine_span(ctx, &pair);
3968    let mut args = Vec::new();
3969    for inner in pair.into_inner() {
3970        if inner.as_rule() == Rule::guard_expr_list {
3971            args = parse_guard_expr_list(ctx, inner)?;
3972        }
3973    }
3974    if args.len() < 2 {
3975        return Err(ParseError::structural(
3976            "guard",
3977            "any(...) requires at least two guard expressions".to_string(),
3978            &span,
3979        ));
3980    }
3981    Ok(GuardExpr::or(args))
3982}
3983
3984fn parse_guard_all_call(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
3985    let span = refine_span(ctx, &pair);
3986    let mut args = Vec::new();
3987    for inner in pair.into_inner() {
3988        if inner.as_rule() == Rule::guard_expr_list {
3989            args = parse_guard_expr_list(ctx, inner)?;
3990        }
3991    }
3992    if args.is_empty() {
3993        return Err(ParseError::structural(
3994            "guard",
3995            "all(...) requires at least one guard expression".to_string(),
3996            &span,
3997        ));
3998    }
3999    Ok(GuardExpr::all(args))
4000}
4001
4002fn parse_guard_expr_list(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<Vec<GuardExpr>> {
4003    let mut exprs = Vec::new();
4004    for inner in pair.into_inner() {
4005        if inner.as_rule() == Rule::guard_expr {
4006            push_guard_or_args_from_expr(ctx, inner, &mut exprs)?;
4007        }
4008    }
4009    Ok(exprs)
4010}
4011
4012fn push_guard_or_args_from_expr(
4013    ctx: &SpanContext,
4014    expr_pair: Pair<Rule>,
4015    exprs: &mut Vec<GuardExpr>,
4016) -> ParseResult<()> {
4017    if let Some(seq_pair) = expr_pair
4018        .clone()
4019        .into_inner()
4020        .find(|inner| inner.as_rule() == Rule::guard_seq)
4021    {
4022        let factors: Vec<Pair<Rule>> = seq_pair
4023            .into_inner()
4024            .filter(|inner| inner.as_rule() == Rule::guard_factor)
4025            .collect();
4026        if factors.len() > 1 {
4027            for factor in factors {
4028                exprs.push(parse_guard_factor(ctx, factor)?);
4029            }
4030            return Ok(());
4031        }
4032    }
4033    exprs.push(parse_guard_expr(ctx, expr_pair)?);
4034    Ok(())
4035}
4036
4037fn parse_guard_term(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<GuardExpr> {
4038    let span = refine_span(ctx, &pair);
4039    for inner in pair.into_inner() {
4040        match inner.as_rule() {
4041            Rule::inject_guard => {
4042                return Ok(GuardExpr::Predicate(Guard::Attr {
4043                    ns: Ns::Env,
4044                    key: Some(inner.as_str().to_string()),
4045                    val: None,
4046                }));
4047            }
4048            Rule::eq_guard => {
4049                return Ok(GuardExpr::Predicate(parse_func_guard(inner)?));
4050            }
4051            Rule::neq_guard => {
4052                let guard = parse_func_guard(inner)?;
4053                return Ok(GuardExpr::Not(Box::new(GuardExpr::Predicate(guard))));
4054            }
4055            Rule::bool_guard => {
4056                let val = inner
4057                    .into_inner()
4058                    .find(|p| p.as_rule() == Rule::bool_value)
4059                    .expect("grammar invariant violated: bool_guard missing bool_value")
4060                    .as_str()
4061                    .to_string();
4062                return Ok(GuardExpr::Predicate(Guard::Attr {
4063                    ns: Ns::Bool,
4064                    key: None,
4065                    val: Some(val),
4066                }));
4067            }
4068            Rule::env_guard => {
4069                return Ok(GuardExpr::Predicate(parse_env_guard(inner)?));
4070            }
4071            Rule::ns_guard => {
4072                return parse_ns_guard(inner, &span);
4073            }
4074            _ => {}
4075        }
4076    }
4077    Err(ParseError::structural(
4078        "guard",
4079        "missing guard predicate".to_string(),
4080        &span,
4081    ))
4082}
4083
4084fn parse_func_guard(pair: Pair<Rule>) -> ParseResult<Guard> {
4085    let mut key = String::new();
4086    let mut value = String::new();
4087    let mut saw_env_prefix = false;
4088    for inner in pair.into_inner() {
4089        match inner.as_rule() {
4090            Rule::env_prefix => saw_env_prefix = true,
4091            Rule::env_key if saw_env_prefix => {
4092                key = inner.as_str().trim().to_string();
4093            }
4094            Rule::bare_guard_value | Rule::quoted_string => {
4095                value = unquote(inner.as_str().trim()).to_string();
4096            }
4097            _ => {}
4098        }
4099    }
4100    Ok(Guard::Attr {
4101        ns: Ns::Env,
4102        key: Some(key),
4103        val: Some(value),
4104    })
4105}
4106
4107fn unquote(s: &str) -> &str {
4108    s.strip_prefix('"')
4109        .and_then(|s| s.strip_suffix('"'))
4110        .or_else(|| s.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))
4111        .unwrap_or(s)
4112}
4113
4114fn parse_env_guard(pair: Pair<Rule>) -> ParseResult<Guard> {
4115    let mut key = String::new();
4116    for inner in pair.into_inner() {
4117        if inner.as_rule() == Rule::env_key {
4118            key = inner.as_str().trim().to_string();
4119        }
4120    }
4121    Ok(Guard::Attr {
4122        ns: Ns::Env,
4123        key: Some(key),
4124        val: None,
4125    })
4126}
4127
4128/// Namespaced guard (`[family:unix]`, `[os:macos]`): namespace and
4129/// values validated here with closed lists and custom errors.
4130/// `family:unix` and `family:windows` are accepted aliases lowered
4131/// immediately to `any(os:macos, os:linux)` and `os:windows`, so
4132/// every platform check downstream executes uniformly under `os:`.
4133/// Case-sensitive throughout, matching the language's uppercase
4134/// keywords and tags.
4135fn parse_ns_guard(pair: Pair<Rule>, span: &SpanContext) -> ParseResult<GuardExpr> {
4136    fn os(value: &str) -> GuardExpr {
4137        GuardExpr::Predicate(Guard::Attr {
4138            ns: Ns::Os,
4139            key: None,
4140            val: Some(value.to_string()),
4141        })
4142    }
4143    let mut ns = String::new();
4144    let mut val = String::new();
4145    for inner in pair.into_inner() {
4146        match inner.as_rule() {
4147            Rule::ns_name => ns = inner.as_str().trim().to_string(),
4148            Rule::ns_value => val = inner.as_str().trim().to_string(),
4149            _ => {}
4150        }
4151    }
4152    match ns.as_str() {
4153        "family" => match val.as_str() {
4154            "unix" => Ok(GuardExpr::or(vec![os("macos"), os("linux")])),
4155            "windows" => Ok(os("windows")),
4156            _ => Err(ParseError::structural(
4157                "guard",
4158                format!("unknown family '{val}'; known values: unix, windows"),
4159                span,
4160            )),
4161        },
4162        "os" => match val.as_str() {
4163            "macos" | "linux" | "windows" => Ok(os(val.as_str())),
4164            _ => Err(ParseError::structural(
4165                "guard",
4166                format!("unknown os '{val}'; known values: macos, linux, windows"),
4167                span,
4168            )),
4169        },
4170        "arch" => {
4171            if ARCH_VALUES.contains(&val.as_str()) {
4172                Ok(GuardExpr::Predicate(Guard::Attr {
4173                    ns: Ns::Arch,
4174                    key: None,
4175                    val: Some(val),
4176                }))
4177            } else {
4178                Err(ParseError::structural(
4179                    "guard",
4180                    format!(
4181                        "unknown arch '{val}'; known values: {}",
4182                        ARCH_VALUES.join(", ")
4183                    ),
4184                    span,
4185                ))
4186            }
4187        }
4188        _ => Err(ParseError::structural(
4189            "guard",
4190            format!(
4191                "unknown guard namespace '{ns}'; known namespaces: family, os, arch, env, bool"
4192            ),
4193            span,
4194        )),
4195    }
4196}
4197
4198fn parse_dollar_ident(pair: Pair<Rule>) -> String {
4199    // Strip the leading '$' from the identifier
4200    let s = pair.as_str();
4201    s.strip_prefix('$').unwrap_or(s).to_string()
4202}
4203
4204use crate::ast::{ArithOp, CompareOp, LogicalOp, Value};
4205
4206fn parse_expr(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
4207    let span = refine_span(ctx, &pair);
4208    let expr = parse_expr_inner(ctx, lctx, pair)?;
4209    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
4210        return Err(ParseError::structural(
4211            "expr",
4212            "integer overflow: 9223372036854775808 exceeds i64::MAX".to_string(),
4213            &span,
4214        ));
4215    }
4216    Ok(expr)
4217}
4218
4219fn parse_expr_inner(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
4220    let span = refine_span(ctx, &pair);
4221    let inner = pair.into_inner().next().unwrap();
4222    match inner.as_rule() {
4223        Rule::expr_logical_or => parse_expr_logical_or(ctx, lctx, inner),
4224        _ => Err(ParseError::structural(
4225            "expr",
4226            format!("unexpected expr rule: {:?}", inner.as_rule()),
4227            &span,
4228        )),
4229    }
4230}
4231
4232fn parse_expr_logical_or(
4233    ctx: &SpanContext,
4234    lctx: &LowerCtx,
4235    pair: Pair<Rule>,
4236) -> ParseResult<Expr> {
4237    let span = refine_span(ctx, &pair);
4238    let mut inner = pair.into_inner();
4239    let mut left = parse_expr_logical_and(ctx, lctx, inner.next().unwrap())?;
4240    while let Some(op_pair) = inner.next() {
4241        let op = match op_pair.as_rule() {
4242            Rule::or_op => LogicalOp::Or,
4243            _ => {
4244                return Err(ParseError::structural(
4245                    "expr",
4246                    format!("unexpected operator in logical-or: {:?}", op_pair.as_rule()),
4247                    &span,
4248                ));
4249            }
4250        };
4251        let right = parse_expr_logical_and(ctx, lctx, inner.next().unwrap())?;
4252        left = Expr::Logical {
4253            op,
4254            left: Box::new(left),
4255            right: Box::new(right),
4256        };
4257    }
4258    Ok(left)
4259}
4260
4261fn parse_expr_logical_and(
4262    ctx: &SpanContext,
4263    lctx: &LowerCtx,
4264    pair: Pair<Rule>,
4265) -> ParseResult<Expr> {
4266    let span = refine_span(ctx, &pair);
4267    let mut inner = pair.into_inner();
4268    let mut left = parse_expr_comparison(ctx, lctx, inner.next().unwrap())?;
4269    while let Some(op_pair) = inner.next() {
4270        let op = match op_pair.as_rule() {
4271            Rule::and_op => LogicalOp::And,
4272            _ => {
4273                return Err(ParseError::structural(
4274                    "expr",
4275                    format!(
4276                        "unexpected operator in logical-and: {:?}",
4277                        op_pair.as_rule()
4278                    ),
4279                    &span,
4280                ));
4281            }
4282        };
4283        let right = parse_expr_comparison(ctx, lctx, inner.next().unwrap())?;
4284        reject_boundary(ctx, &left)?;
4285        reject_boundary(ctx, &right)?;
4286        left = Expr::Logical {
4287            op,
4288            left: Box::new(left),
4289            right: Box::new(right),
4290        };
4291    }
4292    Ok(left)
4293}
4294
4295fn parse_expr_comparison(
4296    ctx: &SpanContext,
4297    lctx: &LowerCtx,
4298    pair: Pair<Rule>,
4299) -> ParseResult<Expr> {
4300    let span = refine_span(ctx, &pair);
4301    let mut inner = pair.into_inner();
4302    let left = parse_expr_ordering(ctx, lctx, inner.next().unwrap())?;
4303    if let Some(op_pair) = inner.next() {
4304        let op = match op_pair.as_rule() {
4305            Rule::eq_op => CompareOp::Eq,
4306            Rule::neq_op => CompareOp::Ne,
4307            _ => {
4308                return Err(ParseError::structural(
4309                    "expr",
4310                    format!("unexpected comparison operator: {:?}", op_pair.as_rule()),
4311                    &span,
4312                ));
4313            }
4314        };
4315        let right = parse_expr_ordering(ctx, lctx, inner.next().unwrap())?;
4316        return make_compare(ctx, op, left, right);
4317    }
4318    Ok(left)
4319}
4320
4321fn parse_expr_ordering(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
4322    let span = refine_span(ctx, &pair);
4323    let mut inner = pair.into_inner();
4324    let left = parse_expr_add_sub(ctx, lctx, inner.next().unwrap())?;
4325    if let Some(op_pair) = inner.next() {
4326        let op = match op_pair.as_rule() {
4327            Rule::lt_op => CompareOp::Lt,
4328            Rule::le_op => CompareOp::Le,
4329            Rule::gt_op => CompareOp::Gt,
4330            Rule::ge_op => CompareOp::Ge,
4331            _ => {
4332                return Err(ParseError::structural(
4333                    "expr",
4334                    format!("unexpected ordering operator: {:?}", op_pair.as_rule()),
4335                    &span,
4336                ));
4337            }
4338        };
4339        let right = parse_expr_add_sub(ctx, lctx, inner.next().unwrap())?;
4340        return make_compare(ctx, op, left, right);
4341    }
4342    Ok(left)
4343}
4344
4345fn parse_expr_add_sub(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
4346    let span = refine_span(ctx, &pair);
4347    let mut inner = pair.into_inner();
4348    let mut left = parse_expr_mul_div(ctx, lctx, inner.next().unwrap())?;
4349    while let Some(op_pair) = inner.next() {
4350        let op = match op_pair.as_rule() {
4351            Rule::plus_op => ArithOp::Add,
4352            Rule::minus_op => ArithOp::Sub,
4353            _ => {
4354                return Err(ParseError::structural(
4355                    "expr",
4356                    format!("unexpected additive operator: {:?}", op_pair.as_rule()),
4357                    &span,
4358                ));
4359            }
4360        };
4361        let right = parse_expr_mul_div(ctx, lctx, inner.next().unwrap())?;
4362        left = make_arith(ctx, op, left, right)?;
4363    }
4364    Ok(left)
4365}
4366
4367fn parse_expr_mul_div(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
4368    let span = refine_span(ctx, &pair);
4369    let mut inner = pair.into_inner();
4370    let mut left = parse_expr_unary(ctx, lctx, inner.next().unwrap())?;
4371    while let Some(op_pair) = inner.next() {
4372        let op = match op_pair.as_rule() {
4373            Rule::star_op => ArithOp::Mul,
4374            Rule::slash_op => ArithOp::Div,
4375            _ => {
4376                return Err(ParseError::structural(
4377                    "expr",
4378                    format!(
4379                        "unexpected multiplicative operator: {:?}",
4380                        op_pair.as_rule()
4381                    ),
4382                    &span,
4383                ));
4384            }
4385        };
4386        let right = parse_expr_unary(ctx, lctx, inner.next().unwrap())?;
4387        left = make_arith(ctx, op, left, right)?;
4388    }
4389    Ok(left)
4390}
4391
4392fn parse_expr_unary(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
4393    let span = refine_span(ctx, &pair);
4394    let mut prefixes = Vec::new();
4395    let mut atom = None;
4396    for inner in pair.into_inner() {
4397        match inner.as_rule() {
4398            Rule::not_op => prefixes.push(false),
4399            Rule::neg_op => prefixes.push(true),
4400            Rule::expr_atom => atom = Some(parse_expr_atom(ctx, lctx, inner)?),
4401            _ => {
4402                return Err(ParseError::structural(
4403                    "expr",
4404                    format!("unexpected unary operand rule: {:?}", inner.as_rule()),
4405                    &span,
4406                ));
4407            }
4408        }
4409    }
4410    let mut expr = atom.ok_or_else(|| {
4411        ParseError::structural(
4412            "expr",
4413            "'!'/'-' requires an expression operand".to_string(),
4414            &span,
4415        )
4416    })?;
4417    // Innermost prefix is closest to the atom: apply in reverse order.
4418    for is_neg in prefixes.into_iter().rev() {
4419        if is_neg {
4420            expr = apply_unary_neg(ctx, expr)?;
4421        } else {
4422            reject_boundary(ctx, &expr)?;
4423            expr = Expr::Not(Box::new(expr));
4424        }
4425    }
4426    Ok(expr)
4427}
4428
4429/// Reject a staged `UnsignedIntBoundary` in any position where unary `-`
4430/// cannot consume it (every composite constructor calls this on children).
4431fn reject_boundary(ctx: &SpanContext, expr: &Expr) -> ParseResult<()> {
4432    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
4433        return Err(ParseError::structural(
4434            "expr",
4435            "integer overflow: 9223372036854775808 exceeds i64::MAX".to_string(),
4436            ctx,
4437        ));
4438    }
4439    Ok(())
4440}
4441
4442/// Apply unary `-`: fold literals, consume the `i64::MIN` boundary, else
4443/// compile to RPN `Neg` (or AST `0 - x` fallback for non-math operands).
4444fn apply_unary_neg(ctx: &SpanContext, expr: Expr) -> ParseResult<Expr> {
4445    match expr {
4446        Expr::Literal(v) => match (v.as_i64(), v.as_f64()) {
4447            (Some(n), _) => match n.checked_neg() {
4448                Some(neg) => Ok(Expr::Literal(Value::int(neg))),
4449                None => Ok(Expr::CompiledMath(vec![MathOp::PushConst(v), MathOp::Neg])),
4450            },
4451            (None, Some(f)) => Ok(Expr::Literal(Value::float(-f))),
4452            (None, None) => {
4453                let other = Expr::Literal(v);
4454                if let Some(mut ops) = expr_to_rpn(&other) {
4455                    ops.push(MathOp::Neg);
4456                    Ok(Expr::CompiledMath(ops))
4457                } else {
4458                    // Non-math operand (list/map/logical): `0 - x` evaluates via
4459                    // the shared arithmetic helper to a runtime Type Error.
4460                    Ok(Expr::Arithmetic {
4461                        op: ArithOp::Sub,
4462                        left: Box::new(Expr::Literal(Value::int(0))),
4463                        right: Box::new(other),
4464                    })
4465                }
4466            }
4467        },
4468        Expr::UnsignedIntBoundary(n) => {
4469            if n == i64::MAX as u64 + 1 {
4470                Ok(Expr::Literal(Value::int(i64::MIN)))
4471            } else {
4472                Err(ParseError::structural(
4473                    "expr",
4474                    format!("integer overflow: {} exceeds i64::MAX", n),
4475                    ctx,
4476                ))
4477            }
4478        }
4479        other => {
4480            if let Some(mut ops) = expr_to_rpn(&other) {
4481                ops.push(MathOp::Neg);
4482                Ok(Expr::CompiledMath(ops))
4483            } else {
4484                // Non-math operand (list/map/logical): `0 - x` evaluates via
4485                // the shared arithmetic helper to a runtime Type Error.
4486                Ok(Expr::Arithmetic {
4487                    op: ArithOp::Sub,
4488                    left: Box::new(Expr::Literal(Value::int(0))),
4489                    right: Box::new(other),
4490                })
4491            }
4492        }
4493    }
4494}
4495
4496/// Try parse-time constant folding for binary arithmetic/comparison.
4497/// Returns `Some(literal)` on success, `None` when not both literals or
4498/// when the op would error at runtime (div-zero/overflow/non-finite:
4499/// leave for the RPN evaluator so the error surfaces at runtime).
4500fn try_fold_arith(op: ArithOp, left: &Expr, right: &Expr) -> Option<Expr> {
4501    let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
4502        return None;
4503    };
4504    fold_arith_values(op, lv, rv).map(Expr::Literal)
4505}
4506
4507fn fold_arith_values(op: ArithOp, left: &Value, right: &Value) -> Option<Value> {
4508    match (left.as_i64(), right.as_i64()) {
4509        (Some(a), Some(b)) => {
4510            let v = match op {
4511                ArithOp::Add => a.checked_add(b)?,
4512                ArithOp::Sub => a.checked_sub(b)?,
4513                ArithOp::Mul => a.checked_mul(b)?,
4514                ArithOp::Div => a.checked_div(b)?,
4515            };
4516            Some(Value::int(v))
4517        }
4518        _ => {
4519            let (af, bf) = (as_f64(left)?, as_f64(right)?);
4520            fold_float(op, af, bf)
4521        }
4522    }
4523}
4524
4525fn fold_float(op: ArithOp, a: f64, b: f64) -> Option<Value> {
4526    if !a.is_finite() || !b.is_finite() {
4527        return None;
4528    }
4529    let v = match op {
4530        ArithOp::Add => a + b,
4531        ArithOp::Sub => a - b,
4532        ArithOp::Mul => a * b,
4533        ArithOp::Div => {
4534            if b == 0.0 {
4535                return None;
4536            }
4537            a / b
4538        }
4539    };
4540    if v.is_finite() {
4541        Some(Value::float(v))
4542    } else {
4543        None
4544    }
4545}
4546
4547fn try_fold_compare(op: CompareOp, left: &Expr, right: &Expr) -> Option<Expr> {
4548    let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
4549        return None;
4550    };
4551    match (lv.as_i64(), rv.as_i64()) {
4552        (Some(a), Some(b)) => {
4553            let r = match op {
4554                CompareOp::Eq => a == b,
4555                CompareOp::Ne => a != b,
4556                CompareOp::Lt => a < b,
4557                CompareOp::Le => a <= b,
4558                CompareOp::Gt => a > b,
4559                CompareOp::Ge => a >= b,
4560            };
4561            Some(Expr::Literal(Value::bool(r)))
4562        }
4563        _ => {
4564            if let (Some(a), Some(b)) = (lv.as_bool(), rv.as_bool()) {
4565                return match op {
4566                    CompareOp::Eq => Some(Expr::Literal(Value::bool(a == b))),
4567                    CompareOp::Ne => Some(Expr::Literal(Value::bool(a != b))),
4568                    _ => None,
4569                };
4570            }
4571            let (af, bf) = (as_f64(lv)?, as_f64(rv)?);
4572            let r = match op {
4573                CompareOp::Eq => af == bf,
4574                CompareOp::Ne => af != bf,
4575                CompareOp::Lt => af < bf,
4576                CompareOp::Le => af <= bf,
4577                CompareOp::Gt => af > bf,
4578                CompareOp::Ge => af >= bf,
4579            };
4580            Some(Expr::Literal(Value::bool(r)))
4581        }
4582    }
4583}
4584
4585fn as_f64(v: &Value) -> Option<f64> {
4586    if let Some(n) = v.as_i64() {
4587        return Some(n as f64);
4588    }
4589    match v.as_f64() {
4590        Some(f) if f.is_finite() => Some(f),
4591        _ => None,
4592    }
4593}
4594
4595fn make_arith(ctx: &SpanContext, op: ArithOp, left: Expr, right: Expr) -> ParseResult<Expr> {
4596    reject_boundary(ctx, &left)?;
4597    reject_boundary(ctx, &right)?;
4598    if let Some(folded) = try_fold_arith(op, &left, &right) {
4599        return Ok(folded);
4600    }
4601    if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
4602        lops.append(&mut rops);
4603        lops.push(match op {
4604            ArithOp::Add => MathOp::Add,
4605            ArithOp::Sub => MathOp::Sub,
4606            ArithOp::Mul => MathOp::Mul,
4607            ArithOp::Div => MathOp::Div,
4608        });
4609        return Ok(Expr::CompiledMath(lops));
4610    }
4611    Ok(Expr::Arithmetic {
4612        op,
4613        left: Box::new(left),
4614        right: Box::new(right),
4615    })
4616}
4617
4618fn make_compare(ctx: &SpanContext, op: CompareOp, left: Expr, right: Expr) -> ParseResult<Expr> {
4619    reject_boundary(ctx, &left)?;
4620    reject_boundary(ctx, &right)?;
4621    if let Some(folded) = try_fold_compare(op, &left, &right) {
4622        return Ok(folded);
4623    }
4624    if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
4625        lops.append(&mut rops);
4626        lops.push(match op {
4627            CompareOp::Eq => MathOp::Eq,
4628            CompareOp::Ne => MathOp::Ne,
4629            CompareOp::Lt => MathOp::Lt,
4630            CompareOp::Le => MathOp::Le,
4631            CompareOp::Gt => MathOp::Gt,
4632            CompareOp::Ge => MathOp::Ge,
4633        });
4634        return Ok(Expr::CompiledMath(lops));
4635    }
4636    Ok(Expr::Compare {
4637        op,
4638        left: Box::new(left),
4639        right: Box::new(right),
4640    })
4641}
4642
4643/// Convert an operand subtree to flat RPN. Returns `None` for shapes with
4644/// no RPN encoding (`Not`/`Logical`/`List`/`Map`/`FreshPipe`/stray boundary): callers
4645/// fall back to AST nodes evaluated recursively.
4646fn expr_to_rpn(expr: &Expr) -> Option<Vec<MathOp>> {
4647    match expr {
4648        Expr::Literal(v) => Some(vec![MathOp::PushConst(v.clone())]),
4649        Expr::Var(name) => Some(vec![MathOp::LoadVar(name.clone())]),
4650        Expr::Env(key) => Some(vec![MathOp::LoadEnv(key.clone())]),
4651        Expr::KeyPath { base, keys } => Some(vec![MathOp::LoadKeyPath {
4652            base: base.clone(),
4653            keys: keys.clone(),
4654        }]),
4655        Expr::Call { name, args } => {
4656            let mut ops = Vec::new();
4657            for arg in args {
4658                ops.extend(expr_to_rpn(arg)?);
4659            }
4660            ops.push(MathOp::Call {
4661                name: name.clone(),
4662                arity: args.len(),
4663            });
4664            Some(ops)
4665        }
4666        Expr::Inspect(var) => Some(vec![MathOp::Inspect(var.clone())]),
4667        Expr::Arithmetic { op, left, right } => {
4668            let mut ops = expr_to_rpn(left)?;
4669            ops.extend(expr_to_rpn(right)?);
4670            ops.push(match op {
4671                ArithOp::Add => MathOp::Add,
4672                ArithOp::Sub => MathOp::Sub,
4673                ArithOp::Mul => MathOp::Mul,
4674                ArithOp::Div => MathOp::Div,
4675            });
4676            Some(ops)
4677        }
4678        Expr::Compare { op, left, right } => {
4679            let mut ops = expr_to_rpn(left)?;
4680            ops.extend(expr_to_rpn(right)?);
4681            ops.push(match op {
4682                CompareOp::Eq => MathOp::Eq,
4683                CompareOp::Ne => MathOp::Ne,
4684                CompareOp::Lt => MathOp::Lt,
4685                CompareOp::Le => MathOp::Le,
4686                CompareOp::Gt => MathOp::Gt,
4687                CompareOp::Ge => MathOp::Ge,
4688            });
4689            Some(ops)
4690        }
4691        Expr::CompiledMath(ops) => Some(ops.clone()),
4692        Expr::FreshPipe => None,
4693        Expr::Not(_) | Expr::Logical { .. } | Expr::List(_) | Expr::Map(_) | Expr::Block(_) => None,
4694        Expr::UnsignedIntBoundary(_) => None,
4695    }
4696}
4697
4698fn parse_expr_atom(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
4699    let span = refine_span(ctx, &pair);
4700    let inner = pair.into_inner().next().unwrap();
4701    match inner.as_rule() {
4702        Rule::parenthesized_expr => parse_expr_inner(ctx, lctx, inner.into_inner().next().unwrap()),
4703        Rule::func_call => parse_func_call(ctx, lctx, inner),
4704        Rule::key_path => parse_key_path(ctx, inner),
4705        Rule::variable => {
4706            let name = inner.as_str();
4707            let name = name.strip_prefix('$').unwrap_or(name).to_string();
4708            Ok(Expr::Var(name))
4709        }
4710        Rule::env_read => parse_env_read(ctx, inner).map(Expr::Env),
4711        Rule::list_literal => parse_list_literal(ctx, lctx, inner),
4712        Rule::map_literal => parse_map_literal(ctx, lctx, inner),
4713        Rule::block => Ok(Expr::Block(parse_block_elements_with_lower(
4714            ctx, inner, lctx,
4715        )?)),
4716        Rule::string_literal | Rule::quoted_string => {
4717            let s = parse_quoted_string(inner)?;
4718            Ok(Expr::Literal(Value::string(s)))
4719        }
4720        Rule::numeric_literal => parse_numeric_literal(ctx, inner),
4721        Rule::bare_word => {
4722            let s = inner.as_str().to_string();
4723            match s.as_str() {
4724                "true" => Ok(Expr::Literal(Value::bool(true))),
4725                "false" => Ok(Expr::Literal(Value::bool(false))),
4726                _ => Ok(Expr::Literal(Value::string(s))),
4727            }
4728        }
4729        _ => Err(ParseError::structural(
4730            "expr",
4731            format!("unexpected expression atom rule: {:?}", inner.as_rule()),
4732            &span,
4733        )),
4734    }
4735}
4736
4737/// Lower an unsigned `numeric_literal` token. Floats (containing `.`) parse
4738/// as `f64` (non-finite/overflow bails); integers parse as `u64` so the
4739/// unsigned half of `i64::MIN` (`9223372036854775808`) stages as
4740/// `UnsignedIntBoundary` for unary `-` to consume. Larger values bail.
4741/// `_` separators strip first: the grammar only admits them between
4742/// digits, so the cleaned text always parses when the shape is right.
4743fn parse_numeric_literal(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<Expr> {
4744    let span = refine_span(ctx, &pair);
4745    let text = pair.as_str();
4746    let clean = text.replace('_', "");
4747    if clean.contains('.') {
4748        let parsed: f64 = clean.parse().map_err(|_| {
4749            ParseError::structural("expr", format!("invalid float literal {text:?}"), &span)
4750        })?;
4751        if !parsed.is_finite() {
4752            return Err(ParseError::structural(
4753                "expr",
4754                format!("invalid float literal {text:?}"),
4755                &span,
4756            ));
4757        }
4758        return Ok(Expr::Literal(Value::float(parsed)));
4759    }
4760    let digits: u64 = clean.parse().map_err(|_| {
4761        ParseError::structural(
4762            "expr",
4763            format!("integer overflow: {text:?} exceeds i64::MAX"),
4764            &span,
4765        )
4766    })?;
4767    if digits <= i64::MAX as u64 {
4768        Ok(Expr::Literal(Value::int(digits as i64)))
4769    } else if digits == i64::MAX as u64 + 1 {
4770        Ok(Expr::UnsignedIntBoundary(digits))
4771    } else {
4772        Err(ParseError::structural(
4773            "expr",
4774            format!("integer overflow: {text:?} exceeds i64::MAX"),
4775            &span,
4776        ))
4777    }
4778}
4779
4780fn parse_env_read(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<String> {
4781    let span = refine_span(ctx, &pair);
4782    for inner in pair.into_inner() {
4783        if inner.as_rule() == Rule::env_read_key {
4784            return Ok(inner.as_str().trim().to_string());
4785        }
4786    }
4787    Err(ParseError::structural(
4788        "expr",
4789        "env read requires a key: env:KEY".to_string(),
4790        &span,
4791    ))
4792}
4793
4794fn parse_key_path(ctx: &SpanContext, pair: Pair<Rule>) -> ParseResult<Expr> {
4795    let span = refine_span(ctx, &pair);
4796    let mut base = None;
4797    let mut keys = Vec::new();
4798    for inner in pair.into_inner() {
4799        match inner.as_rule() {
4800            Rule::ident => {
4801                if base.is_none() {
4802                    base = Some(inner.as_str().to_string());
4803                }
4804            }
4805            Rule::key_path_segment => {
4806                keys.push(inner.as_str().to_string());
4807            }
4808            _ => {}
4809        }
4810    }
4811    Ok(Expr::KeyPath {
4812        base: base.ok_or_else(|| {
4813            ParseError::structural(
4814                "expr",
4815                "key path requires a base identifier".to_string(),
4816                &span,
4817            )
4818        })?,
4819        keys,
4820    })
4821}
4822
4823fn parse_func_call(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
4824    let span = refine_span(ctx, &pair);
4825    let mut name = None;
4826    let mut args = Vec::new();
4827    for inner in pair.into_inner() {
4828        match inner.as_rule() {
4829            Rule::qualified_func_name => {
4830                name = Some(inner.as_str().to_string());
4831            }
4832            Rule::expr => {
4833                let arg = parse_expr_inner(ctx, lctx, inner)?;
4834                reject_boundary(ctx, &arg)?;
4835                args.push(arg);
4836            }
4837            _ => {}
4838        }
4839    }
4840    let name = name.ok_or_else(|| {
4841        ParseError::structural("expr", "function call requires a name".to_string(), &span)
4842    })?;
4843    // `INSPECT` lowers to its own node carrying the variable unevaluated:
4844    // pre-evaluating to a `Value` would lose the binding name. Anything else
4845    // resolves statically to `MODULE::NAME` against SCRIPT definitions and
4846    // `IMPORT`ed modules; the runtime registry is keyed the same way.
4847    if name == KEYWORD_INSPECT {
4848        let [arg] = args.as_slice() else {
4849            return Err(ParseError::structural(
4850                "expr",
4851                "INSPECT requires exactly one argument: INSPECT($var)".to_string(),
4852                &span,
4853            ));
4854        };
4855        if let Expr::Var(var) = arg {
4856            return Ok(Expr::Inspect(var.clone()));
4857        }
4858        return Err(ParseError::structural(
4859            "expr",
4860            format!("INSPECT requires a $variable argument, found {arg:?}"),
4861            &span,
4862        ));
4863    }
4864    let qualified = lctx.resolve_call(&span, &name)?;
4865    Ok(Expr::Call {
4866        name: qualified,
4867        args,
4868    })
4869}
4870
4871fn parse_list_literal(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
4872    let mut items = Vec::new();
4873    for inner in pair.into_inner() {
4874        if inner.as_rule() == Rule::expr {
4875            let item = parse_expr_inner(ctx, lctx, inner)?;
4876            reject_boundary(ctx, &item)?;
4877            items.push(item);
4878        }
4879    }
4880    Ok(Expr::List(items))
4881}
4882
4883fn parse_map_literal(ctx: &SpanContext, lctx: &LowerCtx, pair: Pair<Rule>) -> ParseResult<Expr> {
4884    let span = refine_span(ctx, &pair);
4885    let mut entries = Vec::new();
4886    for inner in pair.into_inner() {
4887        if inner.as_rule() == Rule::map_entry {
4888            let mut key = String::new();
4889            let mut value = None;
4890            for entry_inner in inner.into_inner() {
4891                match entry_inner.as_rule() {
4892                    Rule::quoted_string => {
4893                        key = parse_quoted_string(entry_inner)?;
4894                    }
4895                    Rule::bare_word => {
4896                        key = entry_inner.as_str().to_string();
4897                    }
4898                    Rule::expr => {
4899                        let val = parse_expr_inner(ctx, lctx, entry_inner)?;
4900                        reject_boundary(ctx, &val)?;
4901                        value = Some(val);
4902                    }
4903                    _ => {}
4904                }
4905            }
4906            let val = value.ok_or_else(|| {
4907                ParseError::structural("expr", "map entry missing value".to_string(), &span)
4908            })?;
4909            entries.push((key, val));
4910        }
4911    }
4912    Ok(Expr::Map(entries))
4913}