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