Skip to main content

oxdock_parser/
parser.rs

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