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