Skip to main content

oxdock_parser/
ast.rs

1use std::collections::{HashMap, HashSet};
2use std::fmt;
3use std::sync::Arc;
4
5pub use crate::commands::{AssertTarget, StepKind};
6use crate::constants::{
7    KEYWORD_ASYNC, KEYWORD_AWAIT, KEYWORD_BREAK, KEYWORD_CANCEL, KEYWORD_CONTINUE, KEYWORD_ELSE,
8    KEYWORD_EXPORT, KEYWORD_FOR, KEYWORD_FUNC, KEYWORD_IF, KEYWORD_IMPORT, KEYWORD_LET,
9    KEYWORD_REMOTE, KEYWORD_RETURN, KEYWORD_TYPE, KEYWORD_WHILE,
10};
11
12/// One module's function surface for parse-time call resolution: the base
13/// names it exports. RPN eligibility needs no table: calls compile
14/// generically and the runtime registry gates evaluation per entry.
15#[derive(Debug, Clone, Default)]
16pub struct ModuleFuncs {
17    /// Base function names exported by the module.
18    pub func_names: HashSet<String>,
19}
20
21/// Parse-time function provenance: module name to surface. A `None` entry
22/// marks an opaque module (declared but membership unknown, e.g. the
23/// `oxdock!` macro's `modules:` prefix): qualified calls pass through for
24/// runtime checking, and a lone opaque import determines bare-call targets.
25#[derive(Debug, Clone, Default)]
26pub struct ModuleTable {
27    pub modules: HashMap<String, Option<ModuleFuncs>>,
28}
29
30impl ModuleTable {
31    /// Base names exported by every known (non-opaque) module. Backs the
32    /// `FUNC` shadow check: a script definition colliding with any of these
33    /// fails at parse time, exactly like the old flat reserved set.
34    pub fn reserved_base_names(&self) -> HashSet<String> {
35        let mut out = HashSet::new();
36        for funcs in self.modules.values().flatten() {
37            out.extend(funcs.func_names.iter().cloned());
38        }
39        out
40    }
41}
42
43/// Core command vocabulary: every statement keyword the grammar accepts.
44/// Multi-word commands group by domain prefix (`CATEGORY_ACTION`):
45/// `LIST_APPEND`, `READ_LINE`, `ASSERT_EQ`, `COPY_GIT`. The first
46/// underscore-separated segment is the category; introducing a command
47/// under a new category means adding its prefix to
48/// `COMMAND_CATEGORIES` below, so new groupings stay deliberate.
49/// Single-word commands carry no category. Frozen names never change.
50#[derive(Copy, Clone, Debug, Eq, PartialEq)]
51pub enum Command {
52    InheritEnv,
53    Workdir,
54    Workspace,
55    Env,
56    Echo,
57    Run,
58    Copy,
59    WithIo,
60    CopyGit,
61    Symlink,
62    Mkdir,
63    Install,
64    Archive,
65    Unarchive,
66    Ls,
67    Read,
68    ReadLine,
69    Prompt,
70    Write,
71    Append,
72    Remove,
73    Expand,
74    AssertEq,
75    AssertNe,
76    AssertContains,
77    Exit,
78    Async,
79    Timeout,
80    Isolated,
81    Sleep,
82    ListAppend,
83}
84
85pub const COMMANDS: &[Command] = &[
86    Command::InheritEnv,
87    Command::Workdir,
88    Command::Workspace,
89    Command::Env,
90    Command::Echo,
91    Command::Run,
92    Command::Copy,
93    Command::WithIo,
94    Command::CopyGit,
95    Command::Symlink,
96    Command::Mkdir,
97    Command::Install,
98    Command::Archive,
99    Command::Unarchive,
100    Command::Ls,
101    Command::Read,
102    Command::ReadLine,
103    Command::Prompt,
104    Command::Write,
105    Command::Append,
106    Command::Remove,
107    Command::Expand,
108    Command::AssertEq,
109    Command::AssertNe,
110    Command::AssertContains,
111    Command::Exit,
112    Command::Timeout,
113    Command::Isolated,
114    Command::Sleep,
115    Command::ListAppend,
116];
117
118/// Registered multi-word command categories (first underscore-separated
119/// segment). A new `CATEGORY_ACTION` command registers its prefix here;
120/// reusing an existing category needs no change. Single-word commands
121/// carry no category and are unaffected.
122pub const COMMAND_CATEGORIES: &[&str] =
123    &["INHERIT", "WITH", "COPY", "HASH", "READ", "ASSERT", "LIST"];
124
125impl Command {
126    pub const fn as_str(self) -> &'static str {
127        match self {
128            Command::InheritEnv => "INHERIT_ENV",
129            Command::Workdir => "WORKDIR",
130            Command::Workspace => "WORKSPACE",
131            Command::Env => "ENV",
132            Command::Echo => "ECHO",
133            Command::Run => "RUN",
134            Command::Copy => "COPY",
135            Command::WithIo => "WITH_IO",
136            Command::CopyGit => "COPY_GIT",
137            Command::Symlink => "SYMLINK",
138            Command::Mkdir => "MKDIR",
139            Command::Install => "INSTALL",
140            Command::Archive => "ARCHIVE",
141            Command::Unarchive => "UNARCHIVE",
142            Command::Ls => "LS",
143            Command::Read => "READ",
144            Command::ReadLine => "READ_LINE",
145            Command::Prompt => "PROMPT",
146            Command::Write => "WRITE",
147            Command::Append => "APPEND",
148            Command::Remove => "REMOVE",
149            Command::Expand => "EXPAND",
150            Command::AssertEq => "ASSERT_EQ",
151            Command::AssertNe => "ASSERT_NE",
152            Command::AssertContains => "ASSERT_CONTAINS",
153            Command::Exit => "EXIT",
154            Command::Async => "ASYNC",
155            Command::Timeout => "TIMEOUT",
156            Command::Isolated => "ISOLATED",
157            Command::Sleep => "SLEEP",
158            Command::ListAppend => "LIST_APPEND",
159        }
160    }
161
162    pub const fn syntax(self) -> &'static str {
163        match self {
164            Command::InheritEnv => "INHERIT_ENV [KEY1, KEY2, ...]",
165            Command::Workdir => "WORKDIR <path>",
166            Command::Workspace => "WORKSPACE SNAPSHOT|LOCAL|CACHE|SYSTEM [--local]",
167            Command::Env => "ENV KEY=value",
168            Command::Echo => "ECHO <message>",
169            Command::Run => "RUN <command...> | RUN [\"exe\", \"arg\", ...]",
170            Command::Copy => "COPY [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>",
171            Command::CopyGit => "COPY_GIT [--include-dirty] <rev> <src> <dst>",
172            Command::WithIo => "WITH_IO [bindings] [command | { block }]",
173            Command::Symlink => {
174                "SYMLINK [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>"
175            }
176            Command::Mkdir => "MKDIR <path>",
177            Command::Install => "INSTALL <source> <dest>",
178            Command::Archive => "ARCHIVE [--raw] <src> <dst>",
179            Command::Unarchive => "UNARCHIVE <src> <dst> [--max-bytes <bytes>]",
180            Command::Ls => "LS [<path>]",
181            Command::Read => "READ [<path>]",
182            Command::ReadLine => "READ_LINE $var",
183            Command::Prompt => "PROMPT $var <message> [<default>]",
184            Command::Write => "WRITE <path> [<contents>]",
185            Command::Append => "APPEND <path> [<contents>]",
186            Command::Remove => "REMOVE [--recursive] <path>",
187            Command::Expand => "EXPAND [<path>] [<KEY=val> ...]",
188            Command::AssertEq => "ASSERT_EQ [--hash <sha256>] <actual> <expected>",
189            Command::AssertNe => "ASSERT_NE [--hash <sha256>] <actual> <expected>",
190            Command::AssertContains => "ASSERT_CONTAINS <haystack> <needle>",
191            Command::Exit => "EXIT <code>",
192            Command::Async => "ASYNC <command...> | ASYNC { <commands> }",
193            Command::Timeout => {
194                "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> }"
195            }
196            Command::Isolated => {
197                "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>"
198            }
199            Command::Sleep => "SLEEP <duration>",
200            Command::ListAppend => "LIST_APPEND $list <item>",
201        }
202    }
203
204    pub const fn expects_inner_command(self) -> bool {
205        matches!(
206            self,
207            Command::WithIo | Command::Async | Command::Timeout | Command::Isolated
208        )
209    }
210
211    pub fn parse(s: &str) -> Option<Self> {
212        match s {
213            "INHERIT_ENV" => Some(Command::InheritEnv),
214            "WORKDIR" => Some(Command::Workdir),
215            "WORKSPACE" => Some(Command::Workspace),
216            "ENV" => Some(Command::Env),
217            "ECHO" => Some(Command::Echo),
218            "RUN" => Some(Command::Run),
219            "COPY" => Some(Command::Copy),
220            "WITH_IO" => Some(Command::WithIo),
221            "COPY_GIT" => Some(Command::CopyGit),
222            "SYMLINK" => Some(Command::Symlink),
223            "MKDIR" => Some(Command::Mkdir),
224            "INSTALL" => Some(Command::Install),
225            "ARCHIVE" => Some(Command::Archive),
226            "UNARCHIVE" => Some(Command::Unarchive),
227            "LS" => Some(Command::Ls),
228            "READ" => Some(Command::Read),
229            "READ_LINE" => Some(Command::ReadLine),
230            "PROMPT" => Some(Command::Prompt),
231            "WRITE" => Some(Command::Write),
232            "APPEND" => Some(Command::Append),
233            "REMOVE" => Some(Command::Remove),
234            "EXPAND" => Some(Command::Expand),
235            "ASSERT_EQ" => Some(Command::AssertEq),
236            "ASSERT_NE" => Some(Command::AssertNe),
237            "ASSERT_CONTAINS" => Some(Command::AssertContains),
238            "EXIT" => Some(Command::Exit),
239            "ASYNC" => Some(Command::Async),
240            "TIMEOUT" => Some(Command::Timeout),
241            "ISOLATED" => Some(Command::Isolated),
242            "SLEEP" => Some(Command::Sleep),
243            "LIST_APPEND" => Some(Command::ListAppend),
244            _ => None,
245        }
246    }
247
248    /// Whether a bare word opens a new statement in either parse pathway.
249    /// Covers plain commands plus [`STRUCTURAL_KEYWORDS`]. Single source
250    /// of truth for `Display` quoting and token-stream line splitting, which
251    /// must agree or round-trips break.
252    pub(crate) fn is_statement_keyword(s: &str) -> bool {
253        Command::parse(s).is_some() || STRUCTURAL_KEYWORDS.contains(&s)
254    }
255}
256
257/// Statement starters parsed structurally rather than through command
258/// lowering (token-backend dispatch), living outside the [`Command`]
259/// enum. Canonical registry backing `Command::is_statement_keyword`;
260/// iterate this (plus [`crate::all_metadata`] names) instead of
261/// hardcoding keyword lists elsewhere.
262pub const STRUCTURAL_KEYWORDS: &[&str] = &[
263    KEYWORD_LET,
264    KEYWORD_FOR,
265    KEYWORD_IF,
266    KEYWORD_ELSE,
267    KEYWORD_ASYNC,
268    KEYWORD_AWAIT,
269    KEYWORD_CANCEL,
270    KEYWORD_FUNC,
271    KEYWORD_RETURN,
272    KEYWORD_WHILE,
273    KEYWORD_BREAK,
274    KEYWORD_CONTINUE,
275    KEYWORD_REMOTE,
276    KEYWORD_IMPORT,
277    KEYWORD_EXPORT,
278    KEYWORD_TYPE,
279];
280
281/// Clause keywords that open no statement and need no `Display` quoting
282/// (`IN` only heads `FOR` iterations). Declared alongside
283/// [`STRUCTURAL_KEYWORDS`] so grammar-conformance tests never hardcode
284/// exception lists of their own.
285pub const CLAUSE_KEYWORDS: &[&str] = &["IN"];
286
287/// One namespaced guard predicate. Every guard in the language is a
288/// namespace plus an optional subject plus an optional value; the
289/// single disjointness rule compares the whole triple, so no domain
290/// ever needs its own table.
291///
292/// Construction (fixed by the parser, never hand-built):
293/// `os`/`bool` carry the value (`[os:linux]`), `env` carries the
294/// variable as subject (`[env:MODE]`, `[env:MODE=dev]`).
295/// `family:unix` and `family:windows` are accepted aliases lowered
296/// at parse to `any(os:macos, os:linux)` and `os:windows`
297/// respectively, so every platform check executes uniformly under
298/// the `os:` namespace.
299#[derive(Debug, Clone, Eq, PartialEq)]
300pub enum Guard {
301    Attr {
302        ns: Ns,
303        key: Option<String>,
304        val: Option<String>,
305    },
306}
307
308/// Guard namespaces: the closed set the parser accepts. Adding a
309/// namespace forces compile errors at every consumer (parse,
310/// display, evaluation) — never a silent `_` fallback.
311#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
312pub enum Ns {
313    Os,
314    Arch,
315    Bool,
316    Env,
317}
318
319impl fmt::Display for Ns {
320    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
321        match self {
322            Ns::Os => write!(f, "os"),
323            Ns::Arch => write!(f, "arch"),
324            Ns::Bool => write!(f, "bool"),
325            Ns::Env => write!(f, "env"),
326        }
327    }
328}
329
330/// Every documented `std::env::consts::ARCH` value: the closed
331/// `arch:` domain. Shared by parser validation and coverage
332/// reasoning so the two can never disagree on membership.
333pub const ARCH_VALUES: &[&str] = &[
334    "aarch64",
335    "arm",
336    "arm64ec",
337    "avr",
338    "bpf",
339    "csky",
340    "hexagon",
341    "loongarch32",
342    "loongarch64",
343    "mips",
344    "mips32r6",
345    "mips64",
346    "mips64r6",
347    "msp430",
348    "nvptx64",
349    "powerpc",
350    "powerpc64",
351    "riscv32",
352    "riscv64",
353    "s390x",
354    "sparc",
355    "sparc64",
356    "wasm32",
357    "wasm64",
358    "x86",
359    "x86_64",
360    "xtensa",
361];
362
363#[derive(Debug, Clone, Eq, PartialEq)]
364pub enum GuardExpr {
365    Predicate(Guard),
366    All(Vec<GuardExpr>),
367    Or(Vec<GuardExpr>),
368    Not(Box<GuardExpr>),
369}
370
371impl GuardExpr {
372    pub fn all(exprs: Vec<GuardExpr>) -> GuardExpr {
373        let mut flat = Vec::new();
374        for expr in exprs {
375            match expr {
376                GuardExpr::All(children) => flat.extend(children),
377                other => flat.push(other),
378            }
379        }
380        match flat.len() {
381            0 => panic!("GuardExpr::all requires at least one expression"),
382            1 => flat.into_iter().next().unwrap(),
383            _ => GuardExpr::All(flat),
384        }
385    }
386
387    pub fn or(exprs: Vec<GuardExpr>) -> GuardExpr {
388        let mut flat = Vec::new();
389        for expr in exprs {
390            match expr {
391                GuardExpr::Or(children) => flat.extend(children),
392                other => flat.push(other),
393            }
394        }
395        match flat.len() {
396            0 => panic!("GuardExpr::or requires at least one expression"),
397            1 => flat.into_iter().next().unwrap(),
398            _ => GuardExpr::Or(flat),
399        }
400    }
401
402    pub fn invert(expr: GuardExpr) -> GuardExpr {
403        match expr {
404            GuardExpr::Not(inner) => *inner,
405            other => GuardExpr::Not(Box::new(other)),
406        }
407    }
408}
409
410impl std::ops::Not for GuardExpr {
411    type Output = GuardExpr;
412
413    fn not(self) -> GuardExpr {
414        match self {
415            GuardExpr::Not(inner) => *inner,
416            other => GuardExpr::Not(Box::new(other)),
417        }
418    }
419}
420
421impl From<Guard> for GuardExpr {
422    fn from(guard: Guard) -> Self {
423        GuardExpr::Predicate(guard)
424    }
425}
426
427/// A command argument : either an expandable string or an expression.
428#[derive(Debug, Clone, PartialEq)]
429pub enum Arg {
430    /// Expandable string. The `bool` indicates whether the argument was
431    /// quoted in the source (`true`) or unquoted (`false`). Quoted arguments
432    /// that start with `--` are positional, not flags.
433    String(String, bool),
434    /// Expression : resolved at runtime via evaluate_expr.
435    Expr(Expr),
436    /// Mixed literal/expression value (e.g. `KEY={{ $x }} tail`). Fragments
437    /// resolve independently at runtime and concatenate with no added
438    /// separator : inter-fragment gaps are already materialized as `Text`.
439    Parts(Vec<ArgPart>),
440}
441
442/// One fragment of a mixed [`Arg::Parts`] value.
443#[derive(Debug, Clone, PartialEq)]
444pub enum ArgPart {
445    /// Literal text. The `bool` marks source-quoted regions (exact bytes);
446    /// unquoted text carries single-space-normalized gaps.
447    Text(String, bool),
448    /// Typed expression : resolved via evaluate_expr, never stringified.
449    Expr(Expr),
450}
451
452impl Arg {
453    pub fn as_str(&self) -> &str {
454        match self {
455            Arg::String(s, _) => s,
456            // Expressions and mixed values have no single borrowed string;
457            // use `render()` for an owned display form.
458            Arg::Expr(_) | Arg::Parts(_) => "",
459        }
460    }
461
462    /// Owned display form: `String` verbatim, `Expr` as source (`$x`),
463    /// `Parts` as fragment concatenation. Used for diagnostics and Display;
464    /// runtime resolution must match on variants instead (see resolve_arg).
465    pub fn render(&self) -> String {
466        match self {
467            Arg::String(s, _) => s.clone(),
468            Arg::Expr(e) => e.to_string(),
469            Arg::Parts(parts) => parts.iter().map(ArgPart::render).collect(),
470        }
471    }
472
473    pub fn is_quoted(&self) -> bool {
474        matches!(self, Arg::String(_, true))
475    }
476}
477
478impl ArgPart {
479    pub fn render(&self) -> String {
480        match self {
481            ArgPart::Text(s, _) => s.clone(),
482            ArgPart::Expr(e) => e.to_string(),
483        }
484    }
485}
486
487impl From<String> for Arg {
488    fn from(s: String) -> Self {
489        Arg::String(s, false)
490    }
491}
492
493impl From<&str> for Arg {
494    fn from(s: &str) -> Self {
495        Arg::String(s.to_string(), false)
496    }
497}
498
499impl std::fmt::Display for Arg {
500    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
501        match self {
502            Arg::String(s, _) => write!(f, "{}", s),
503            Arg::Expr(e) => write!(f, "{}", e),
504            Arg::Parts(parts) => {
505                for part in parts {
506                    match part {
507                        ArgPart::Text(s, _) => write!(f, "{}", s)?,
508                        ArgPart::Expr(e) => write!(f, "{}", e)?,
509                    }
510                }
511                Ok(())
512            }
513        }
514    }
515}
516
517impl AsRef<str> for Arg {
518    fn as_ref(&self) -> &str {
519        self.as_str()
520    }
521}
522
523impl PartialEq<str> for Arg {
524    fn eq(&self, other: &str) -> bool {
525        self.as_str() == other
526    }
527}
528
529impl PartialEq<&str> for Arg {
530    fn eq(&self, other: &&str) -> bool {
531        self.as_str() == *other
532    }
533}
534
535#[derive(Debug, Clone, Copy, Eq, PartialEq)]
536pub enum IoStream {
537    Stdin,
538    Stdout,
539    Stderr,
540    /// Bare `tty` flag: run the wrapped `RUN` step under a pseudo-terminal.
541    /// Takes no pipe (`tty = $x` is a parse error); the master carries one
542    /// interleaved stream, so `stderr` bindings alongside it are rejected.
543    Tty,
544    /// `rows = <int>` terminal height. Requires `tty`; rejected without it.
545    Rows(u16),
546    /// `cols = <int>` terminal width. Requires `tty`; rejected without it.
547    Cols(u16),
548}
549
550#[derive(Debug, Clone, Eq, PartialEq)]
551pub struct IoBinding {
552    pub stream: IoStream,
553    pub pipe: Option<PipeTarget>,
554}
555
556/// A pipe endpoint for a `WITH_IO` binding: a `$var` holding a `PIPE`
557/// value, resolved against the live variable scope when the step runs.
558#[derive(Debug, Clone, Eq, PartialEq)]
559pub enum PipeTarget {
560    Var(String),
561}
562
563/// Value-model re-exports: the word, its payload, type descriptors, and the
564/// export hook live in [`crate::value`], the single representation for
565/// every type.
566pub use crate::value::{
567    OxDockType, SemaphoreState, TypeDescriptor, Value, ValuePayload, clone_boxed, clone_copy,
568    clone_shared, drop_boxed, drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed,
569    fmt_inline, fmt_shared, load_inline, startup_descriptors, store_inline, type_anchor,
570    unshare_boxed, unshare_inline, unshare_shared,
571};
572
573#[derive(Debug, Clone, Copy, Eq, PartialEq)]
574pub enum CompareOp {
575    Eq,
576    Ne,
577    Lt,
578    Le,
579    Gt,
580    Ge,
581}
582
583#[derive(Debug, Clone, Copy, Eq, PartialEq)]
584pub enum ArithOp {
585    Add,
586    Sub,
587    Mul,
588    Div,
589}
590
591/// Flat stack-machine op for expression-local arithmetic/comparison.
592///
593/// Lowering folds constant subtrees to `Expr::Literal` and compiles dynamic
594/// arithmetic/comparison subtrees to post-order `Vec<MathOp>` so the runtime
595/// executes a single instruction loop instead of recursive `Box` walking.
596/// `Call` covers value-semantics functions only (`INT`, `FLOAT`, `GLOB`,
597/// `LOAD_TOML`, `LOAD_JSON`); `INSPECT($var)` uses `Inspect` to preserve the
598/// variable identifier (pre-evaluating to `Value` would lose the name).
599#[derive(Debug, Clone, PartialEq)]
600pub enum MathOp {
601    PushConst(Value),
602    LoadVar(String),
603    LoadEnv(String),
604    LoadKeyPath { base: String, keys: Vec<String> },
605    Call { name: String, arity: usize },
606    Inspect(String),
607    Neg,
608    Add,
609    Sub,
610    Mul,
611    Div,
612    Lt,
613    Le,
614    Gt,
615    Ge,
616    Eq,
617    Ne,
618}
619
620#[derive(Debug, Clone, Copy, Eq, PartialEq)]
621pub enum LogicalOp {
622    And,
623    Or,
624}
625
626#[derive(Debug, Clone, PartialEq)]
627pub enum Expr {
628    Literal(Value),
629    Var(String),
630    /// Environment read (`env:KEY`): resolves against the script
631    /// environment at evaluation time.
632    Env(String),
633    KeyPath {
634        base: String,
635        keys: Vec<String>,
636    },
637    List(Vec<Expr>),
638    Map(Vec<(String, Expr)>),
639    /// Inline block (`LET $a: STRING = { RETURN "hi" }`): runs its steps in
640    /// a fresh scope when evaluated and yields the `RETURN` value
641    /// (fallthrough yields `""`, mirroring a zero-arg function body).
642    /// Parsed only where `map_literal` fails, so `{k: v}` stays a map.
643    Block(Vec<Step>),
644    Call {
645        name: String,
646        args: Vec<Expr>,
647    },
648    /// Variable inspection (`INSPECT($var)`): carries the variable name
649    /// unevaluated so evaluation can snapshot the binding. Produced only by
650    /// the parser for the exact `INSPECT` name; evaluators match on this
651    /// variant and never on a function-name string.
652    Inspect(String),
653    Compare {
654        op: CompareOp,
655        left: Box<Expr>,
656        right: Box<Expr>,
657    },
658    Arithmetic {
659        op: ArithOp,
660        left: Box<Expr>,
661        right: Box<Expr>,
662    },
663    /// Lowering-optimized form: folded literals stay `Literal`, dynamic
664    /// arithmetic/comparison subtrees arrive here as flat RPN.
665    CompiledMath(Vec<MathOp>),
666    /// Fresh anonymous pipe backend (`LET $p: PIPE` with no initializer).
667    /// Evaluates to a pipe value keyed by a generated name that no
668    /// `pipe:` literal can spell, so bare declarations never collide
669    /// with named pipes. Transitional representation until backends
670    /// become owned handles.
671    FreshPipe,
672    /// Lowering-only intermediate staging `9223372036854775808` (the unsigned
673    /// half of `i64::MIN`). Valid only as the direct child of unary `-`;
674    /// any instance reaching lowering completion bails integer overflow.
675    UnsignedIntBoundary(u64),
676    Not(Box<Expr>),
677    Logical {
678        op: LogicalOp,
679        left: Box<Expr>,
680        right: Box<Expr>,
681    },
682}
683
684#[derive(Debug, Clone)]
685pub struct Step {
686    pub guard: Option<GuardExpr>,
687    pub kind: StepKind,
688    pub scope_enter: usize,
689    pub scope_exit: usize,
690    /// 1-based source line of the statement that produced this step
691    /// (`0` when unknown: hand-built steps, synthetic streams). Stamped
692    /// at lower time from the split statement, so runtime errors can
693    /// name the failing line. Never rendered by `Display` (output must
694    /// stay reparse-stable) and never compared by content equality
695    /// (provenance, like quoting flags and scope markers).
696    pub line: usize,
697    /// 1-based column where the statement starts (`0` when unknown).
698    /// Same stamping, same provenance rules as `line`; runtime errors
699    /// render both.
700    pub col: usize,
701}
702
703impl PartialEq for Step {
704    fn eq(&self, other: &Self) -> bool {
705        self.guard == other.guard
706            && self.kind == other.kind
707            && self.scope_enter == other.scope_enter
708            && self.scope_exit == other.scope_exit
709    }
710}
711
712impl Eq for Step {}
713
714impl Expr {
715    /// Visit this expression and every descendant, depth first. `Block`
716    /// steps recurse through [`StepKind::walk_step_exprs`](crate::commands::StepKind::walk_step_exprs),
717    /// so inline bodies are covered; `CompiledMath` ops are opaque here
718    /// (match `MathOp::Call` in the visitor when call names matter).
719    /// Exhaustive over variants: adding an `Expr` shape fails compilation
720    /// here, never silently.
721    pub fn walk(&self, f: &mut impl FnMut(&Expr)) {
722        f(self);
723        match self {
724            Expr::Literal(_)
725            | Expr::Var(_)
726            | Expr::Env(_)
727            | Expr::KeyPath { .. }
728            | Expr::Inspect(_)
729            | Expr::FreshPipe
730            | Expr::UnsignedIntBoundary(_) => {}
731            Expr::Call { args, .. } => {
732                for arg in args {
733                    arg.walk(f);
734                }
735            }
736            Expr::List(items) => {
737                for item in items {
738                    item.walk(f);
739                }
740            }
741            Expr::Map(entries) => {
742                for (_, value) in entries {
743                    value.walk(f);
744                }
745            }
746            Expr::Block(steps) => {
747                for step in steps {
748                    step.kind.walk_step_exprs(f);
749                }
750            }
751            Expr::Compare { left, right, .. }
752            | Expr::Arithmetic { left, right, .. }
753            | Expr::Logical { left, right, .. } => {
754                left.walk(f);
755                right.walk(f);
756            }
757            Expr::CompiledMath(_) => {}
758            Expr::Not(inner) => inner.walk(f),
759        }
760    }
761}
762
763#[derive(Debug, Clone, Eq, PartialEq)]
764pub enum WorkspaceTarget {
765    Snapshot,
766    Local,
767    Cache { local: bool },
768    System,
769}
770
771pub trait EnvLookup {
772    fn get_env(&self, key: &str) -> Option<&str>;
773}
774
775impl EnvLookup for HashMap<String, String> {
776    fn get_env(&self, key: &str) -> Option<&str> {
777        self.get(key).map(|s| s.as_str())
778    }
779}
780
781impl EnvLookup for Arc<HashMap<String, String>> {
782    fn get_env(&self, key: &str) -> Option<&str> {
783        (**self).get_env(key)
784    }
785}
786
787pub fn guard_allows(guard: &Guard, env: &impl EnvLookup) -> bool {
788    let Guard::Attr { ns, key, val } = guard;
789    match ns {
790        Ns::Os => match val.as_deref() {
791            Some("macos") => platform_is_macos(),
792            Some("linux") => platform_is_linux(),
793            Some("windows") => platform_is_windows(),
794            _ => false,
795        },
796        Ns::Arch => match val.as_deref() {
797            Some(want) => ARCH_TARGET == want,
798            None => false,
799        },
800        Ns::Bool => val
801            .as_deref()
802            .map(|v| v.parse::<bool>().unwrap_or(false))
803            .unwrap_or(false),
804        Ns::Env => match key.as_deref() {
805            Some(var) => match val {
806                None => env.get_env(var).map(|v| !v.is_empty()).unwrap_or(false),
807                Some(want) => env
808                    .get_env(var)
809                    .map(|v| v == want.as_str())
810                    .unwrap_or(false),
811            },
812            // Parser always supplies the variable; defensive false.
813            None => false,
814        },
815    }
816}
817
818/// One `cfg!` per platform fact, each beside its namespace arm
819/// above. `#[allow]` lives on the helpers, not the dispatch.
820#[allow(clippy::disallowed_macros)]
821fn platform_is_windows() -> bool {
822    cfg!(windows)
823}
824
825/// See `platform_is_windows`.
826#[allow(clippy::disallowed_macros)]
827fn platform_is_macos() -> bool {
828    cfg!(target_os = "macos")
829}
830
831/// See `platform_is_windows`.
832#[allow(clippy::disallowed_macros)]
833fn platform_is_linux() -> bool {
834    cfg!(target_os = "linux")
835}
836
837/// Host target architecture behind `arch:` guards. A plain const
838/// read alongside the platform helpers above.
839const ARCH_TARGET: &str = std::env::consts::ARCH;
840
841pub fn guard_expr_allows(expr: &GuardExpr, env: &impl EnvLookup) -> bool {
842    match expr {
843        GuardExpr::Predicate(guard) => guard_allows(guard, env),
844        GuardExpr::All(children) => children.iter().all(|g| guard_expr_allows(g, env)),
845        GuardExpr::Or(children) => children.iter().any(|g| guard_expr_allows(g, env)),
846        GuardExpr::Not(child) => !guard_expr_allows(child, env),
847    }
848}
849
850pub fn guard_option_allows(expr: Option<&GuardExpr>, env: &impl EnvLookup) -> bool {
851    match expr {
852        Some(e) => guard_expr_allows(e, env),
853        None => true,
854    }
855}
856
857impl Guard {
858    /// The one disjointness rule for the entire guard language:
859    /// same namespace, same subject, both valued, different values.
860    /// Everything else overlaps — different namespaces are
861    /// independent axes, different subjects are independent
862    /// variables, and a missing value is a presence claim compatible
863    /// with any value. No per-domain tables: `os:macos` vs
864    /// `os:linux`, `env:MODE=dev` vs `env:MODE=prod`, and
865    /// `bool:true` vs `bool:false` all decide here.
866    pub fn is_disjoint_from(&self, other: &Self) -> bool {
867        match (self, other) {
868            (
869                Guard::Attr {
870                    ns: n1,
871                    key: k1,
872                    val: Some(v1),
873                },
874                Guard::Attr {
875                    ns: n2,
876                    key: k2,
877                    val: Some(v2),
878                },
879            ) => n1 == n2 && k1 == k2 && v1 != v2,
880            _ => false,
881        }
882    }
883}
884
885impl GuardExpr {
886    /// Structural disjointness over the full combinator language.
887    /// Distribution is exact in both directions (`Or` needs every
888    /// arm disjoint, `All` needs one), so this proves rather than
889    /// assumes; anything without a proof overlaps. Linear, no worlds,
890    /// no enumeration, no cap.
891    pub fn is_disjoint_from(&self, other: &Self) -> bool {
892        match (self, other) {
893            // Complements, either polarity: exact syntactic equality,
894            // or an unset negation against any positive claim on the
895            // same subject (`Not([ns:k])` excludes `[ns:k]` and
896            // `[ns:k=v]` alike — unset is compatible with nothing
897            // valued). Valued negations (`Not([ns:k=v])`) meet only
898            // their exact complement: the subject may hold some other
899            // value.
900            (x, GuardExpr::Not(inner)) | (GuardExpr::Not(inner), x) => {
901                x == inner.as_ref() || unset_excludes(x, inner.as_ref())
902            }
903            // Leaf predicates delegate to domain algebra.
904            (GuardExpr::Predicate(p1), GuardExpr::Predicate(p2)) => p1.is_disjoint_from(p2),
905            // Distribution over `Or`: every arm must exclude `other`.
906            (GuardExpr::Or(arms), other) | (other, GuardExpr::Or(arms)) => {
907                arms.iter().all(|arm| arm.is_disjoint_from(other))
908            }
909            // Distribution over `All`: one excluding arm suffices.
910            (GuardExpr::All(arms), other) | (other, GuardExpr::All(arms)) => {
911                arms.iter().any(|arm| arm.is_disjoint_from(other))
912            }
913        }
914    }
915}
916
917/// Top-level conjuncts of a guard: descend `All` only. The DNF
918/// expansion below distributes anything nested (`Or`/`Not`)
919/// exactly; this split is only the entry point.
920fn conjuncts(expr: &GuardExpr) -> Vec<&GuardExpr> {
921    match expr {
922        GuardExpr::All(items) => items.iter().collect(),
923        single => vec![single],
924    }
925}
926
927/// Closed value domains for coverage reasoning, driven by the
928/// parser's accepted values rather than per-value match arms in the
929/// analyzer: `bool` admits true/false, `os` admits the three known
930/// systems (`family:unix` already lowers to `any(os:macos,
931/// os:linux)`, so unix-family coverage is structural). `env` is
932/// open (any string), so it never exhausts.
933fn closed_domain_values(ns: Ns, key: Option<&str>) -> Option<&'static [&'static str]> {
934    match (ns, key) {
935        (Ns::Bool, None) => Some(&["true", "false"]),
936        (Ns::Os, None) => Some(&["macos", "linux", "windows"]),
937        (Ns::Arch, None) => Some(ARCH_VALUES),
938        _ => None,
939    }
940}
941
942/// One DNF literal: a predicate or its negation. Negations only
943/// ever sit on predicates after NNF pushdown.
944#[derive(Clone)]
945enum DnfLit {
946    Pos(Guard),
947    Neg(Guard),
948}
949
950impl DnfLit {
951    fn as_expr(&self) -> GuardExpr {
952        match self {
953            DnfLit::Pos(guard) => GuardExpr::Predicate(guard.clone()),
954            DnfLit::Neg(guard) => GuardExpr::Not(Box::new(GuardExpr::Predicate(guard.clone()))),
955        }
956    }
957}
958
959/// Cap on DNF disjuncts: guard formulas are a handful of atoms, so
960/// this never fires on real input. Exceeding it falls back to live
961/// (satisfiable), the sound direction — a missed proof only risks a
962/// false coverage error, never a missed one.
963const MAX_DNF_DISJUNCTS: usize = 64;
964
965/// Push one expression into DNF under a polarity: `true` keeps it,
966/// `false` negates it (De Morgan through `All`/`Or`, double
967/// negation cancels). Returns the disjunct list, or `None` when the
968/// cap trips.
969fn dnf_push(expr: &GuardExpr, polarity: bool, out: &mut Vec<Vec<DnfLit>>) -> bool {
970    match (expr, polarity) {
971        (GuardExpr::Predicate(guard), true) => {
972            for disjunct in out.iter_mut() {
973                disjunct.push(DnfLit::Pos(guard.clone()));
974            }
975            true
976        }
977        (GuardExpr::Predicate(guard), false) => {
978            for disjunct in out.iter_mut() {
979                disjunct.push(DnfLit::Neg(guard.clone()));
980            }
981            true
982        }
983        (GuardExpr::All(children), true) | (GuardExpr::Or(children), false) => {
984            // Conjunction: every child constrains every disjunct.
985            for child in children {
986                if !dnf_push(child, polarity, out) {
987                    return false;
988                }
989            }
990            true
991        }
992        (GuardExpr::Or(children), true) | (GuardExpr::All(children), false) => {
993            // Disjunction: each child forks every live disjunct.
994            let mut forked = Vec::new();
995            for disjunct in out.drain(..) {
996                for child in children {
997                    let mut branch = vec![disjunct.clone()];
998                    if !dnf_push(child, polarity, &mut branch) {
999                        return false;
1000                    }
1001                    forked.extend(branch);
1002                    if forked.len() > MAX_DNF_DISJUNCTS {
1003                        return false;
1004                    }
1005                }
1006            }
1007            *out = forked;
1008            true
1009        }
1010        (GuardExpr::Not(inner), _) => dnf_push(inner, !polarity, out),
1011    }
1012}
1013
1014/// True when one DNF disjunct can fire: no statically-false
1015/// literal, no conflicting pair, and no closed domain exhausted by
1016/// negations.
1017fn disjunct_satisfiable(lits: &[DnfLit]) -> bool {
1018    // A statically-false positive (`bool:false`, or any non-`true`
1019    // which `guard_allows` parses as false) kills the disjunct, as
1020    // does the negation of `bool:true` (which always fires).
1021    for lit in lits {
1022        match lit {
1023            DnfLit::Pos(Guard::Attr {
1024                ns: Ns::Bool, val, ..
1025            }) if val.as_deref() != Some("true") => return false,
1026            DnfLit::Neg(Guard::Attr {
1027                ns: Ns::Bool,
1028                key: None,
1029                val: Some(value),
1030            }) if value == "true" => return false,
1031            _ => {}
1032        }
1033    }
1034    // Any conflicting pair kills the disjunct (complements, leaf
1035    // disjointness, and `Or`/`All` distribution decide inside).
1036    for (index, first) in lits.iter().enumerate() {
1037        for second in &lits[index + 1..] {
1038            if first.as_expr().is_disjoint_from(&second.as_expr()) {
1039                return false;
1040            }
1041        }
1042    }
1043    // A closed domain with every value negated has nowhere left to
1044    // fire (`not(os:macos)`, `not(os:linux)`, `not(os:windows)`
1045    // jointly cover no host).
1046    for lit in lits {
1047        let (ns, key) = match lit {
1048            DnfLit::Neg(Guard::Attr {
1049                ns,
1050                key,
1051                val: Some(_),
1052            }) => (*ns, key.as_deref()),
1053            _ => continue,
1054        };
1055        let Some(domain) = closed_domain_values(ns, key) else {
1056            continue;
1057        };
1058        let exhausted = domain.iter().all(|value| {
1059            lits.iter().any(|other| match other {
1060                DnfLit::Neg(Guard::Attr {
1061                    ns: other_ns,
1062                    key: other_key,
1063                    val: Some(other_val),
1064                }) => *other_ns == ns && other_key.as_deref() == key && other_val == value,
1065                _ => false,
1066            })
1067        });
1068        if exhausted {
1069            return false;
1070        }
1071    }
1072    true
1073}
1074
1075/// True when a conjunction list can never fire: its exact DNF has
1076/// no satisfiable disjunct. This proves rather than assumes —
1077/// pairwise conflicts, `bool` falsehood, and complete closed-domain
1078/// partitions (`os:macos`/`os:linux`/`os:windows`,
1079/// `bool:true`/`bool:false`) all decide here with no per-domain
1080/// tables and no hardcoded platform pairs.
1081fn conjunction_dead(atoms: &[&GuardExpr]) -> bool {
1082    if atoms.is_empty() {
1083        return false;
1084    }
1085    let mut disjuncts = vec![Vec::new()];
1086    for atom in atoms {
1087        if !dnf_push(atom, true, &mut disjuncts) {
1088            return false;
1089        }
1090    }
1091    !disjuncts
1092        .iter()
1093        .any(|disjunct| disjunct_satisfiable(disjunct))
1094}
1095
1096/// True when a guard can fire. Anything not provably dead is live.
1097pub fn guard_satisfiable(expr: &GuardExpr) -> bool {
1098    !conjunction_dead(&conjuncts(expr))
1099}
1100
1101/// True when a guard fires unconditionally: a lone `true`, an
1102/// all-valid conjunction, or the negation of a dead conjunction.
1103pub fn guard_valid(expr: &GuardExpr) -> bool {
1104    match expr {
1105        GuardExpr::Predicate(Guard::Attr {
1106            ns: Ns::Bool,
1107            val: Some(value),
1108            ..
1109        }) => value.as_str() == "true",
1110        GuardExpr::All(items) => items.iter().all(guard_valid),
1111        GuardExpr::Not(inner) => !guard_satisfiable(inner),
1112        _ => false,
1113    }
1114}
1115
1116/// True when two declaration guards can fire together. Absent guards
1117/// are unconditional; anything without a provable conflict overlaps.
1118pub fn guards_overlap(a: Option<&GuardExpr>, b: Option<&GuardExpr>) -> bool {
1119    match (a, b) {
1120        (None, None) => true,
1121        (Some(x), None) | (None, Some(x)) => guard_satisfiable(x),
1122        (Some(x), Some(y)) => {
1123            let mut atoms = conjuncts(x);
1124            atoms.extend(conjuncts(y));
1125            !conjunction_dead(&atoms)
1126        }
1127    }
1128}
1129
1130/// Unset exclusion: `Not([ns:k])` (valueless) is disjoint from any
1131/// positive claim on the same subject, valued or not.
1132fn unset_excludes(x: &GuardExpr, inner: &GuardExpr) -> bool {
1133    match (x, inner) {
1134        (
1135            GuardExpr::Predicate(Guard::Attr {
1136                ns: n2, key: k2, ..
1137            }),
1138            GuardExpr::Predicate(Guard::Attr {
1139                ns: n1,
1140                key: k1,
1141                val: None,
1142            }),
1143        ) => n1 == n2 && k1 == k2,
1144        _ => false,
1145    }
1146}
1147
1148impl fmt::Display for Guard {
1149    /// Bare form without brackets (the step renderer adds them):
1150    /// `[os:linux]` prints `os:linux`, `[env:MODE=dev]`
1151    /// prints `eq(env:MODE, dev)`, `[env:MODE]` prints `env:MODE`.
1152    /// The `eq()` spelling roundtrips through the parser; the rest
1153    /// print verbatim. Roundtrips by construction.
1154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1155        match self {
1156            Guard::Attr {
1157                ns: Ns::Env,
1158                key: Some(var),
1159                val: None,
1160            } => write!(f, "env:{var}"),
1161            Guard::Attr {
1162                ns: Ns::Env,
1163                key: Some(var),
1164                val: Some(want),
1165            } => write!(f, "eq(env:{var}, {want})"),
1166            Guard::Attr {
1167                ns,
1168                key: _,
1169                val: Some(value),
1170            } => write!(f, "{ns}:{value}"),
1171            Guard::Attr { ns, key, val: None } => match key {
1172                Some(subject) => write!(f, "{ns}:{subject}"),
1173                None => write!(f, "{ns}"),
1174            },
1175        }
1176    }
1177}
1178
1179impl fmt::Display for WorkspaceTarget {
1180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1181        match self {
1182            WorkspaceTarget::Snapshot => write!(f, "SNAPSHOT"),
1183            WorkspaceTarget::Local => write!(f, "LOCAL"),
1184            WorkspaceTarget::Cache { local: false } => write!(f, "CACHE"),
1185            WorkspaceTarget::Cache { local: true } => write!(f, "CACHE --local"),
1186            WorkspaceTarget::System => write!(f, "SYSTEM"),
1187        }
1188    }
1189}
1190
1191impl fmt::Display for Expr {
1192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1193        match self {
1194            Expr::Literal(v) => write!(f, "{}", v),
1195            Expr::Var(name) => write!(f, "${}", name),
1196            Expr::Env(key) => write!(f, "env:{}", key),
1197            Expr::KeyPath { base, keys } => {
1198                write!(f, "${}", base)?;
1199                for key in keys {
1200                    write!(f, ".{}", key)?;
1201                }
1202                Ok(())
1203            }
1204            Expr::Call { name, args } => {
1205                write!(f, "{}(", name)?;
1206                for (i, arg) in args.iter().enumerate() {
1207                    if i > 0 {
1208                        write!(f, ", ")?;
1209                    }
1210                    write!(f, "{}", arg)?;
1211                }
1212                write!(f, ")")
1213            }
1214            Expr::Inspect(var) => write!(f, "INSPECT(${})", var),
1215            Expr::List(items) => {
1216                write!(f, "[")?;
1217                for (i, item) in items.iter().enumerate() {
1218                    if i > 0 {
1219                        write!(f, ", ")?;
1220                    }
1221                    write!(f, "{}", item)?;
1222                }
1223                write!(f, "]")
1224            }
1225            Expr::Map(entries) => {
1226                write!(f, "{{")?;
1227                for (i, (key, val)) in entries.iter().enumerate() {
1228                    if i > 0 {
1229                        write!(f, ", ")?;
1230                    }
1231                    write!(f, "\"{}\": {}", key, val)?;
1232                }
1233                write!(f, "}}")
1234            }
1235            Expr::Block(steps) => {
1236                write!(f, "{{ ")?;
1237                for (i, step) in steps.iter().enumerate() {
1238                    if i > 0 {
1239                        write!(f, "; ")?;
1240                    }
1241                    write!(f, "{}", step.kind)?;
1242                }
1243                write!(f, " }}")
1244            }
1245            Expr::Compare { op, left, right } => {
1246                // Parenthesized like `Arithmetic`/`Logical` below, so
1247                // nested comparisons round-trip (`(a == b) == c` parses;
1248                // `a == b == c` does not). Found by expression fuzz.
1249                write!(f, "({} {} {})", left, op, right)
1250            }
1251            Expr::Arithmetic { op, left, right } => {
1252                write!(f, "({} {} {})", left, op, right)
1253            }
1254            Expr::CompiledMath(ops) => {
1255                write!(f, "{}", format_compiled_math(ops))
1256            }
1257            // No expression syntax produces this (bare `LET` is a
1258            // statement): render loudly non-round-trippable so a stray
1259            // use fails at re-parse instead of aliasing a named pipe.
1260            Expr::FreshPipe => write!(f, "<fresh pipe>"),
1261            Expr::UnsignedIntBoundary(n) => write!(f, "{}", n),
1262            Expr::Not(inner) => {
1263                // Parenthesize compound operands so Display round-trips:
1264                // `!(a == b)` must not render as `!a == b` (= `(!a) == b`).
1265                match inner.as_ref() {
1266                    Expr::Compare { .. } | Expr::Arithmetic { .. } | Expr::CompiledMath(_) => {
1267                        write!(f, "!({})", inner)
1268                    }
1269                    _ => write!(f, "!{}", inner),
1270                }
1271            }
1272            Expr::Logical { op, left, right } => {
1273                write!(f, "({} {} {})", left, op, right)
1274            }
1275        }
1276    }
1277}
1278
1279impl fmt::Display for CompareOp {
1280    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1281        match self {
1282            CompareOp::Eq => write!(f, "=="),
1283            CompareOp::Ne => write!(f, "!="),
1284            CompareOp::Lt => write!(f, "<"),
1285            CompareOp::Le => write!(f, "<="),
1286            CompareOp::Gt => write!(f, ">"),
1287            CompareOp::Ge => write!(f, ">="),
1288        }
1289    }
1290}
1291
1292impl fmt::Display for ArithOp {
1293    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1294        match self {
1295            ArithOp::Add => write!(f, "+"),
1296            ArithOp::Sub => write!(f, "-"),
1297            ArithOp::Mul => write!(f, "*"),
1298            ArithOp::Div => write!(f, "/"),
1299        }
1300    }
1301}
1302
1303/// Render flat RPN back to parenthesized infix so `Display` round-trips
1304/// through the parser with identical semantics. Parentheses are emitted
1305/// unconditionally around binary/unary ops; redundant parens parse to the
1306/// same tree, which is what round-trip requires.
1307fn format_compiled_math(ops: &[MathOp]) -> String {
1308    let mut stack: Vec<String> = Vec::new();
1309    for op in ops {
1310        match op {
1311            MathOp::PushConst(v) => stack.push(format!("{}", v)),
1312            MathOp::LoadVar(name) => stack.push(format!("${}", name)),
1313            MathOp::LoadEnv(key) => stack.push(format!("env:{}", key)),
1314            MathOp::LoadKeyPath { base, keys } => {
1315                let mut s = format!("${}", base);
1316                for key in keys {
1317                    s.push('.');
1318                    s.push_str(key);
1319                }
1320                stack.push(s);
1321            }
1322            MathOp::Call { name, arity } => {
1323                let mut args = Vec::new();
1324                for _ in 0..*arity {
1325                    args.push(stack.pop().unwrap_or_else(|| "<underflow>".to_string()));
1326                }
1327                args.reverse();
1328                stack.push(format!("{}({})", name, args.join(", ")));
1329            }
1330            MathOp::Inspect(name) => stack.push(format!("INSPECT(${})", name)),
1331            MathOp::Neg => {
1332                let inner = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1333                stack.push(format!("(-{})", inner));
1334            }
1335            MathOp::Add => push_bin(&mut stack, "+"),
1336            MathOp::Sub => push_bin(&mut stack, "-"),
1337            MathOp::Mul => push_bin(&mut stack, "*"),
1338            MathOp::Div => push_bin(&mut stack, "/"),
1339            MathOp::Lt => push_bin(&mut stack, "<"),
1340            MathOp::Le => push_bin(&mut stack, "<="),
1341            MathOp::Gt => push_bin(&mut stack, ">"),
1342            MathOp::Ge => push_bin(&mut stack, ">="),
1343            MathOp::Eq => push_bin(&mut stack, "=="),
1344            MathOp::Ne => push_bin(&mut stack, "!="),
1345        }
1346    }
1347    if stack.len() == 1 {
1348        let mut items = stack;
1349        items.pop().unwrap_or_else(|| "<empty>".to_string())
1350    } else {
1351        stack.join(" ")
1352    }
1353}
1354
1355fn push_bin(stack: &mut Vec<String>, op: &str) {
1356    let right = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1357    let left = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1358    stack.push(format!("({} {} {})", left, op, right));
1359}
1360
1361impl fmt::Display for LogicalOp {
1362    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1363        match self {
1364            LogicalOp::And => write!(f, "&&"),
1365            LogicalOp::Or => write!(f, "||"),
1366        }
1367    }
1368}
1369
1370enum GuardDisplayContext {
1371    Root,
1372    InAnyArg,
1373    InNot,
1374    InAll,
1375}
1376
1377impl GuardExpr {
1378    fn fmt_with_ctx(&self, f: &mut fmt::Formatter<'_>, ctx: GuardDisplayContext) -> fmt::Result {
1379        match self {
1380            GuardExpr::Predicate(guard) => write!(f, "{}", guard),
1381            GuardExpr::All(children) => {
1382                let wrap = matches!(
1383                    ctx,
1384                    GuardDisplayContext::InAnyArg | GuardDisplayContext::InNot
1385                ) && children.len() > 1;
1386                if wrap {
1387                    write!(f, "(")?;
1388                }
1389                for (i, child) in children.iter().enumerate() {
1390                    if i > 0 {
1391                        write!(f, ", ")?;
1392                    }
1393                    child.fmt_with_ctx(f, GuardDisplayContext::InAll)?;
1394                }
1395                if wrap {
1396                    write!(f, ")")?;
1397                }
1398                Ok(())
1399            }
1400            GuardExpr::Or(children) => {
1401                write!(f, "any(")?;
1402                for (i, child) in children.iter().enumerate() {
1403                    if i > 0 {
1404                        write!(f, ", ")?;
1405                    }
1406                    child.fmt_with_ctx(f, GuardDisplayContext::InAnyArg)?;
1407                }
1408                write!(f, ")")
1409            }
1410            GuardExpr::Not(child) => {
1411                write!(f, "not(")?;
1412                child.fmt_with_ctx(f, GuardDisplayContext::InNot)?;
1413                write!(f, ")")
1414            }
1415        }
1416    }
1417}
1418
1419impl fmt::Display for GuardExpr {
1420    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1421        self.fmt_with_ctx(f, GuardDisplayContext::Root)
1422    }
1423}
1424
1425impl fmt::Display for Step {
1426    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1427        if let Some(expr) = &self.guard {
1428            write!(f, "[{}] ", expr)?;
1429        }
1430        write!(f, "{}", self.kind)
1431    }
1432}
1433
1434#[cfg(test)]
1435mod tests {
1436    use super::*;
1437    /// Bidirectional lock between the token backend and the keyword registry.
1438    /// Fails CI if a statement keyword is renamed or deleted on either side.
1439    /// Every [`STRUCTURAL_KEYWORDS`] entry must be claimed by the backend:
1440    /// parsing it bare either succeeds (operand-less forms like `BREAK`)
1441    /// or fails structurally — never as a bare `unknown command` (issue
1442    /// #143). Conversely every head the element loop treats structurally
1443    /// must be registered here or in the command table.
1444    #[test]
1445    fn statement_keywords_match_backend() {
1446        // Transparency lock: for a bare keyword the backend must never
1447        // invent a failure of its own. Either it claims the shape
1448        // (`BREAK`/`CONTINUE`/operand-less `RETURN` lower directly) or
1449        // it routes straight to lowering and reports lowering's own
1450        // kind (production lowering, which knows every structural
1451        // head). A backend hard-fail shadowing lowering would fire
1452        // here; kind drift between the two would fire too.
1453        for kw in STRUCTURAL_KEYWORDS {
1454            let via_backend = crate::parse_script(kw, crate::commands::lower_command);
1455            let via_lowering =
1456                crate::commands::lower_command(kw, Vec::new()).map(|kind| crate::Step {
1457                    guard: None,
1458                    kind,
1459                    scope_enter: 0,
1460                    scope_exit: 0,
1461                    line: 0,
1462                    col: 0,
1463                });
1464            match (via_backend, via_lowering) {
1465                (Ok(_), _) => {}
1466                (Err(a), Err(b)) => {
1467                    assert_eq!(
1468                        a.kind(),
1469                        b.kind(),
1470                        "backend kind drift for bare keyword {kw}: {a} vs {b}"
1471                    );
1472                }
1473                (Err(a), Ok(_)) => {
1474                    panic!("backend rejects bare keyword {kw} that lowering accepts: {a}")
1475                }
1476            }
1477        }
1478        // Heads the element loop dispatches structurally (not through
1479        // generic lowering) must stay registered; update this list with
1480        // the dispatch when adding a head.
1481        for head in [
1482            "LET",
1483            "RETURN",
1484            "BREAK",
1485            "CONTINUE",
1486            "IF",
1487            "FOR",
1488            "WHILE",
1489            "FUNC",
1490            "REMOTE",
1491            "INHERIT_ENV",
1492            "WITH_IO",
1493            "ASYNC",
1494            "TIMEOUT",
1495            "ISOLATED",
1496            "AWAIT",
1497            "CANCEL",
1498            "RUN",
1499            "IMPORT",
1500            "EXPORT",
1501            "TYPE",
1502        ] {
1503            assert!(
1504                STRUCTURAL_KEYWORDS.contains(&head)
1505                    || crate::all_metadata().iter().any(|m| m.name == head),
1506                "structural head {head} is not registered"
1507            );
1508        }
1509    }
1510
1511    /// Category convention lock: every multi-word command groups under a
1512    /// registered `COMMAND_CATEGORIES` prefix. Adding a command under a
1513    /// new category fails here until the prefix registers (one line).
1514    #[test]
1515    fn command_names_group_by_category() {
1516        for command in COMMANDS {
1517            let name = command.as_str();
1518            let Some((prefix, _)) = name.split_once('_') else {
1519                continue;
1520            };
1521            assert!(
1522                COMMAND_CATEGORIES.contains(&prefix),
1523                "command {name} introduces unregistered category {prefix}; add it to COMMAND_CATEGORIES"
1524            );
1525        }
1526    }
1527}
1528
1529#[cfg(test)]
1530mod guard_analysis_tests {
1531    use super::*;
1532
1533    fn attr(ns: Ns, key: Option<&str>, val: Option<&str>) -> GuardExpr {
1534        GuardExpr::Predicate(Guard::Attr {
1535            ns,
1536            key: key.map(str::to_string),
1537            val: val.map(str::to_string),
1538        })
1539    }
1540
1541    fn os(value: &str) -> GuardExpr {
1542        attr(Ns::Os, None, Some(value))
1543    }
1544
1545    fn arch(value: &str) -> GuardExpr {
1546        attr(Ns::Arch, None, Some(value))
1547    }
1548
1549    /// The `family:unix` parse alias, desugared exactly as the
1550    /// parser lowers it.
1551    fn unix() -> GuardExpr {
1552        GuardExpr::Or(vec![os("macos"), os("linux")])
1553    }
1554
1555    fn windows() -> GuardExpr {
1556        os("windows")
1557    }
1558
1559    fn env_eq(var: &str, value: &str) -> GuardExpr {
1560        attr(Ns::Env, Some(var), Some(value))
1561    }
1562
1563    fn not(expr: GuardExpr) -> GuardExpr {
1564        GuardExpr::Not(Box::new(expr))
1565    }
1566
1567    /// Closed domains exhaust: negating every `os:` value (or both
1568    /// `bool:` values) covers no host. Open domains (`env:`) never
1569    /// exhaust — some unmentioned value may hold.
1570    #[test]
1571    fn partition_negations_are_jointly_dead() {
1572        let os_exhausted = GuardExpr::All(vec![not(os("macos")), not(os("linux")), not(windows())]);
1573        assert!(
1574            !guard_satisfiable(&os_exhausted),
1575            "no host is outside `macos`/`linux`/`windows`"
1576        );
1577        // Partial negations stay live.
1578        let os_partial = GuardExpr::All(vec![not(os("macos")), not(os("linux"))]);
1579        assert!(guard_satisfiable(&os_partial), "`windows` is still open");
1580        // The bool domain exhausts the same way.
1581        let bool_exhausted = GuardExpr::All(vec![
1582            not(attr(Ns::Bool, None, Some("true"))),
1583            not(attr(Ns::Bool, None, Some("false"))),
1584        ]);
1585        assert!(!guard_satisfiable(&bool_exhausted));
1586        // Open env domains never exhaust.
1587        let env_open = GuardExpr::All(vec![
1588            not(env_eq("MODE", "dev")),
1589            not(env_eq("MODE", "prod")),
1590        ]);
1591        assert!(guard_satisfiable(&env_open), "MODE may hold a third value");
1592        // Single negations are always live.
1593        assert!(guard_satisfiable(&not(unix())));
1594    }
1595
1596    /// The desugared `unix` alias behaves as a disjunction: it meets
1597    /// `windows` nowhere and covers `macos`/`linux` deployment reads.
1598    #[test]
1599    fn unix_alias_is_os_disjunction() {
1600        assert!(!guards_overlap(Some(&unix()), Some(&windows())));
1601        assert!(guards_overlap(Some(&unix()), Some(&os("macos"))));
1602        // Coverage through the alias: `unix` + `windows` declarations
1603        // cover every host, so their joint negation is dead.
1604        let covered = GuardExpr::All(vec![GuardExpr::Not(Box::new(unix())), not(windows())]);
1605        assert!(!guard_satisfiable(&covered));
1606    }
1607
1608    /// `arch:` decides by value like every namespace; it overlaps
1609    /// `os:` (independent axes: an aarch64 mac exists). Negating
1610    /// the whole closed `ARCH_VALUES` domain covers no host.
1611    #[test]
1612    fn arch_guards_decide_by_value() {
1613        assert!(!guards_overlap(
1614            Some(&arch("x86_64")),
1615            Some(&arch("aarch64"))
1616        ));
1617        assert!(guards_overlap(Some(&arch("x86_64")), Some(&arch("x86_64"))));
1618        assert!(guards_overlap(Some(&arch("aarch64")), Some(&os("macos"))));
1619        let exhausted = GuardExpr::All(ARCH_VALUES.iter().map(|value| not(arch(value))).collect());
1620        assert!(!guard_satisfiable(&exhausted));
1621        // Runtime anchor: this host's own architecture fires here.
1622        let host = attr(Ns::Arch, None, Some(ARCH_TARGET));
1623        assert!(guard_expr_allows(&host, &HashMap::new()));
1624    }
1625
1626    /// The full platform matrix, asserted exhaustively. All three
1627    /// `os:` values are pairwise disjoint; identical values
1628    /// overlap.
1629    #[test]
1630    fn platform_overlap_matrix_is_exhaustive() {
1631        let cases = [
1632            ("macos", "macos", true),
1633            ("macos", "linux", false),
1634            ("macos", "windows", false),
1635            ("linux", "linux", true),
1636            ("linux", "windows", false),
1637            ("windows", "windows", true),
1638        ];
1639        for (v1, v2, expected) in cases {
1640            let left = os(v1);
1641            let right = os(v2);
1642            assert_eq!(
1643                guards_overlap(Some(&left), Some(&right)),
1644                expected,
1645                "os:{v1} vs os:{v2}"
1646            );
1647        }
1648    }
1649
1650    /// Runtime anchor, portable across CI hosts: `os:macos` and
1651    /// `os:windows` never co-fire on the machine running the test.
1652    #[test]
1653    fn disjoint_pairs_never_cofire_here() {
1654        let macos = os("macos");
1655        let holds = |expr: &GuardExpr| guard_expr_allows(expr, &HashMap::new());
1656        assert!(
1657            !(holds(&macos) && holds(&windows())),
1658            "os:macos and os:windows co-fired"
1659        );
1660    }
1661
1662    #[test]
1663    fn overlap_follows_namespace_semantics() {
1664        // Same namespace, distinct values: disjoint.
1665        assert!(!guards_overlap(Some(&windows()), Some(&unix())));
1666        assert!(!guards_overlap(Some(&os("macos")), Some(&os("linux"))));
1667        // Absent guards are unconditional.
1668        assert!(guards_overlap(None, Some(&windows())));
1669        assert!(guards_overlap(None, None));
1670        // Unsatisfiable conjunctions overlap nothing.
1671        let dead = GuardExpr::All(vec![os("macos"), windows()]);
1672        assert!(!guard_satisfiable(&dead));
1673        assert!(!guards_overlap(Some(&dead), Some(&os("macos"))));
1674        assert!(guard_valid(&GuardExpr::Predicate(Guard::Attr {
1675            ns: Ns::Bool,
1676            key: None,
1677            val: Some("true".to_string()),
1678        })));
1679        assert!(!guard_valid(&unix()));
1680    }
1681
1682    #[test]
1683    fn env_value_conflicts_decide_without_enumeration() {
1684        let fast = env_eq("MODE", "fast");
1685        let slow = env_eq("MODE", "slow");
1686        assert!(
1687            !guards_overlap(Some(&fast), Some(&slow)),
1688            "same key distinct values are disjoint"
1689        );
1690        let also_fast = env_eq("MODE", "fast");
1691        assert!(guards_overlap(Some(&fast), Some(&also_fast)));
1692        // Bare presence overlaps any value on the same key.
1693        let bare = attr(Ns::Env, Some("MODE"), None);
1694        assert!(guards_overlap(Some(&bare), Some(&fast)));
1695    }
1696}
1697
1698#[cfg(test)]
1699mod guard_algebra_tests {
1700    use super::*;
1701
1702    fn os(value: &str) -> GuardExpr {
1703        GuardExpr::Predicate(Guard::Attr {
1704            ns: Ns::Os,
1705            key: None,
1706            val: Some(value.to_string()),
1707        })
1708    }
1709
1710    #[test]
1711    fn or_distributes_over_disjointness() {
1712        fn env_eq(var: &str, value: &str) -> GuardExpr {
1713            GuardExpr::Predicate(Guard::Attr {
1714                ns: Ns::Env,
1715                key: Some(var.to_string()),
1716                val: Some(value.to_string()),
1717            })
1718        }
1719        // Every arm must exclude `other`: one overlapping arm keeps
1720        // the whole disjunction live.
1721        let mixed = GuardExpr::Or(vec![env_eq("MODE", "dev"), env_eq("MODE", "prod")]);
1722        assert!(!mixed.is_disjoint_from(&env_eq("MODE", "dev")));
1723        // All arms disjoint: the disjunction is dead against it.
1724        assert!(mixed.is_disjoint_from(&env_eq("MODE", "test")));
1725        // Cross-namespace arms never exclude: different axes overlap.
1726        let cross = GuardExpr::Or(vec![env_eq("MODE", "dev")]);
1727        let platform = os("windows");
1728        assert!(!cross.is_disjoint_from(&platform));
1729    }
1730
1731    #[test]
1732    fn all_distributes_over_disjointness() {
1733        let stacked = GuardExpr::All(vec![
1734            os("macos"),
1735            GuardExpr::Or(vec![os("macos"), os("linux")]),
1736            os("windows"),
1737        ]);
1738        assert!(stacked.is_disjoint_from(&os("macos")));
1739        // One live arm keeps the conjunction overlapping: neither
1740        // arm excludes macos here.
1741        let live = GuardExpr::All(vec![
1742            os("macos"),
1743            GuardExpr::Predicate(Guard::Attr {
1744                ns: Ns::Env,
1745                key: Some("MODE".to_string()),
1746                val: Some("dev".to_string()),
1747            }),
1748        ]);
1749        assert!(!live.is_disjoint_from(&os("macos")));
1750    }
1751
1752    #[test]
1753    fn negation_is_structural_not_syntactic() {
1754        let not_win = GuardExpr::Not(Box::new(os("windows")));
1755        assert!(not_win.is_disjoint_from(&os("windows")));
1756        assert!(os("windows").is_disjoint_from(&not_win));
1757        assert!(!not_win.is_disjoint_from(&os("macos")));
1758    }
1759}