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