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    /// Bare `tty` flag: run the wrapped `RUN` step under a pseudo-terminal.
546    /// Takes no pipe (`tty = $x` is a parse error); the master carries one
547    /// interleaved stream, so `stderr` bindings alongside it are rejected.
548    Tty,
549    /// `rows = <int>` terminal height. Requires `tty`; rejected without it.
550    Rows(u16),
551    /// `cols = <int>` terminal width. Requires `tty`; rejected without it.
552    Cols(u16),
553}
554
555#[derive(Debug, Clone, Eq, PartialEq)]
556pub struct IoBinding {
557    pub stream: IoStream,
558    pub pipe: Option<PipeTarget>,
559}
560
561/// A pipe endpoint for a `WITH_IO` binding: a `$var` holding a `PIPE`
562/// value, resolved against the live variable scope when the step runs.
563#[derive(Debug, Clone, Eq, PartialEq)]
564pub enum PipeTarget {
565    Var(String),
566}
567
568/// Value-model re-exports: the word, its payload, type descriptors, and the
569/// export hook live in [`crate::value`], the single representation for
570/// every type.
571pub use crate::value::{
572    OxDockType, SemaphoreState, TypeDescriptor, Value, ValuePayload, clone_boxed, clone_copy,
573    clone_shared, drop_boxed, drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed,
574    fmt_inline, fmt_shared, load_inline, startup_descriptors, store_inline, type_anchor,
575    unshare_boxed, unshare_inline, unshare_shared,
576};
577
578#[derive(Debug, Clone, Copy, Eq, PartialEq)]
579pub enum CompareOp {
580    Eq,
581    Ne,
582    Lt,
583    Le,
584    Gt,
585    Ge,
586}
587
588#[derive(Debug, Clone, Copy, Eq, PartialEq)]
589pub enum ArithOp {
590    Add,
591    Sub,
592    Mul,
593    Div,
594}
595
596/// Flat stack-machine op for expression-local arithmetic/comparison.
597///
598/// Lowering folds constant subtrees to `Expr::Literal` and compiles dynamic
599/// arithmetic/comparison subtrees to post-order `Vec<MathOp>` so the runtime
600/// executes a single instruction loop instead of recursive `Box` walking.
601/// `Call` covers value-semantics functions only (`INT`, `FLOAT`, `GLOB`,
602/// `LOAD_TOML`, `LOAD_JSON`); `INSPECT($var)` uses `Inspect` to preserve the
603/// variable identifier (pre-evaluating to `Value` would lose the name).
604#[derive(Debug, Clone, PartialEq)]
605pub enum MathOp {
606    PushConst(Value),
607    LoadVar(String),
608    LoadEnv(String),
609    LoadKeyPath { base: String, keys: Vec<String> },
610    Call { name: String, arity: usize },
611    Inspect(String),
612    Neg,
613    Add,
614    Sub,
615    Mul,
616    Div,
617    Lt,
618    Le,
619    Gt,
620    Ge,
621    Eq,
622    Ne,
623}
624
625#[derive(Debug, Clone, Copy, Eq, PartialEq)]
626pub enum LogicalOp {
627    And,
628    Or,
629}
630
631#[derive(Debug, Clone, PartialEq)]
632pub enum Expr {
633    Literal(Value),
634    Var(String),
635    /// Environment read (`env:KEY`): resolves against the script
636    /// environment at evaluation time.
637    Env(String),
638    KeyPath {
639        base: String,
640        keys: Vec<String>,
641    },
642    List(Vec<Expr>),
643    Map(Vec<(String, Expr)>),
644    /// Inline block (`LET $a: STRING = { RETURN "hi" }`): runs its steps in
645    /// a fresh scope when evaluated and yields the `RETURN` value
646    /// (fallthrough yields `""`, mirroring a zero-arg function body).
647    /// Parsed only where `map_literal` fails, so `{k: v}` stays a map.
648    Block(Vec<Step>),
649    Call {
650        name: String,
651        args: Vec<Expr>,
652    },
653    /// Variable inspection (`INSPECT($var)`): carries the variable name
654    /// unevaluated so evaluation can snapshot the binding. Produced only by
655    /// the parser for the exact `INSPECT` name; evaluators match on this
656    /// variant and never on a function-name string.
657    Inspect(String),
658    Compare {
659        op: CompareOp,
660        left: Box<Expr>,
661        right: Box<Expr>,
662    },
663    Arithmetic {
664        op: ArithOp,
665        left: Box<Expr>,
666        right: Box<Expr>,
667    },
668    /// Lowering-optimized form: folded literals stay `Literal`, dynamic
669    /// arithmetic/comparison subtrees arrive here as flat RPN.
670    CompiledMath(Vec<MathOp>),
671    /// Fresh anonymous pipe backend (`LET $p: PIPE` with no initializer).
672    /// Evaluates to a pipe value keyed by a generated name that no
673    /// `pipe:` literal can spell, so bare declarations never collide
674    /// with named pipes. Transitional representation until backends
675    /// become owned handles.
676    FreshPipe,
677    /// Lowering-only intermediate staging `9223372036854775808` (the unsigned
678    /// half of `i64::MIN`). Valid only as the direct child of unary `-`;
679    /// any instance reaching lowering completion bails integer overflow.
680    UnsignedIntBoundary(u64),
681    Not(Box<Expr>),
682    Logical {
683        op: LogicalOp,
684        left: Box<Expr>,
685        right: Box<Expr>,
686    },
687}
688
689#[derive(Debug, Clone, PartialEq)]
690pub struct Step {
691    pub guard: Option<GuardExpr>,
692    pub kind: StepKind,
693    pub scope_enter: usize,
694    pub scope_exit: usize,
695}
696
697impl Expr {
698    /// Visit this expression and every descendant, depth first. `Block`
699    /// steps recurse through [`StepKind::walk_step_exprs`](crate::commands::StepKind::walk_step_exprs),
700    /// so inline bodies are covered; `CompiledMath` ops are opaque here
701    /// (match `MathOp::Call` in the visitor when call names matter).
702    /// Exhaustive over variants: adding an `Expr` shape fails compilation
703    /// here, never silently.
704    pub fn walk(&self, f: &mut impl FnMut(&Expr)) {
705        f(self);
706        match self {
707            Expr::Literal(_)
708            | Expr::Var(_)
709            | Expr::Env(_)
710            | Expr::KeyPath { .. }
711            | Expr::Inspect(_)
712            | Expr::FreshPipe
713            | Expr::UnsignedIntBoundary(_) => {}
714            Expr::Call { args, .. } => {
715                for arg in args {
716                    arg.walk(f);
717                }
718            }
719            Expr::List(items) => {
720                for item in items {
721                    item.walk(f);
722                }
723            }
724            Expr::Map(entries) => {
725                for (_, value) in entries {
726                    value.walk(f);
727                }
728            }
729            Expr::Block(steps) => {
730                for step in steps {
731                    step.kind.walk_step_exprs(f);
732                }
733            }
734            Expr::Compare { left, right, .. }
735            | Expr::Arithmetic { left, right, .. }
736            | Expr::Logical { left, right, .. } => {
737                left.walk(f);
738                right.walk(f);
739            }
740            Expr::CompiledMath(_) => {}
741            Expr::Not(inner) => inner.walk(f),
742        }
743    }
744}
745
746#[derive(Debug, Clone, Eq, PartialEq)]
747pub enum WorkspaceTarget {
748    Snapshot,
749    Local,
750    Cache { local: bool },
751    System,
752}
753
754pub trait EnvLookup {
755    fn get_env(&self, key: &str) -> Option<&str>;
756}
757
758impl EnvLookup for HashMap<String, String> {
759    fn get_env(&self, key: &str) -> Option<&str> {
760        self.get(key).map(|s| s.as_str())
761    }
762}
763
764impl EnvLookup for Arc<HashMap<String, String>> {
765    fn get_env(&self, key: &str) -> Option<&str> {
766        (**self).get_env(key)
767    }
768}
769
770pub fn guard_allows(guard: &Guard, env: &impl EnvLookup) -> bool {
771    let Guard::Attr { ns, key, val } = guard;
772    match ns {
773        Ns::Os => match val.as_deref() {
774            Some("macos") => platform_is_macos(),
775            Some("linux") => platform_is_linux(),
776            Some("windows") => platform_is_windows(),
777            _ => false,
778        },
779        Ns::Arch => match val.as_deref() {
780            Some(want) => ARCH_TARGET == want,
781            None => false,
782        },
783        Ns::Bool => val
784            .as_deref()
785            .map(|v| v.parse::<bool>().unwrap_or(false))
786            .unwrap_or(false),
787        Ns::Env => match key.as_deref() {
788            Some(var) => match val {
789                None => env.get_env(var).map(|v| !v.is_empty()).unwrap_or(false),
790                Some(want) => env
791                    .get_env(var)
792                    .map(|v| v == want.as_str())
793                    .unwrap_or(false),
794            },
795            // Parser always supplies the variable; defensive false.
796            None => false,
797        },
798    }
799}
800
801/// One `cfg!` per platform fact, each beside its namespace arm
802/// above. `#[allow]` lives on the helpers, not the dispatch.
803#[allow(clippy::disallowed_macros)]
804fn platform_is_windows() -> bool {
805    cfg!(windows)
806}
807
808/// See `platform_is_windows`.
809#[allow(clippy::disallowed_macros)]
810fn platform_is_macos() -> bool {
811    cfg!(target_os = "macos")
812}
813
814/// See `platform_is_windows`.
815#[allow(clippy::disallowed_macros)]
816fn platform_is_linux() -> bool {
817    cfg!(target_os = "linux")
818}
819
820/// Host target architecture behind `arch:` guards. A plain const
821/// read alongside the platform helpers above.
822const ARCH_TARGET: &str = std::env::consts::ARCH;
823
824pub fn guard_expr_allows(expr: &GuardExpr, env: &impl EnvLookup) -> bool {
825    match expr {
826        GuardExpr::Predicate(guard) => guard_allows(guard, env),
827        GuardExpr::All(children) => children.iter().all(|g| guard_expr_allows(g, env)),
828        GuardExpr::Or(children) => children.iter().any(|g| guard_expr_allows(g, env)),
829        GuardExpr::Not(child) => !guard_expr_allows(child, env),
830    }
831}
832
833pub fn guard_option_allows(expr: Option<&GuardExpr>, env: &impl EnvLookup) -> bool {
834    match expr {
835        Some(e) => guard_expr_allows(e, env),
836        None => true,
837    }
838}
839
840impl Guard {
841    /// The one disjointness rule for the entire guard language:
842    /// same namespace, same subject, both valued, different values.
843    /// Everything else overlaps — different namespaces are
844    /// independent axes, different subjects are independent
845    /// variables, and a missing value is a presence claim compatible
846    /// with any value. No per-domain tables: `os:macos` vs
847    /// `os:linux`, `env:MODE=dev` vs `env:MODE=prod`, and
848    /// `bool:true` vs `bool:false` all decide here.
849    pub fn is_disjoint_from(&self, other: &Self) -> bool {
850        match (self, other) {
851            (
852                Guard::Attr {
853                    ns: n1,
854                    key: k1,
855                    val: Some(v1),
856                },
857                Guard::Attr {
858                    ns: n2,
859                    key: k2,
860                    val: Some(v2),
861                },
862            ) => n1 == n2 && k1 == k2 && v1 != v2,
863            _ => false,
864        }
865    }
866}
867
868impl GuardExpr {
869    /// Structural disjointness over the full combinator language.
870    /// Distribution is exact in both directions (`Or` needs every
871    /// arm disjoint, `All` needs one), so this proves rather than
872    /// assumes; anything without a proof overlaps. Linear, no worlds,
873    /// no enumeration, no cap.
874    pub fn is_disjoint_from(&self, other: &Self) -> bool {
875        match (self, other) {
876            // Complements, either polarity: exact syntactic equality,
877            // or an unset negation against any positive claim on the
878            // same subject (`Not([ns:k])` excludes `[ns:k]` and
879            // `[ns:k=v]` alike — unset is compatible with nothing
880            // valued). Valued negations (`Not([ns:k=v])`) meet only
881            // their exact complement: the subject may hold some other
882            // value.
883            (x, GuardExpr::Not(inner)) | (GuardExpr::Not(inner), x) => {
884                x == inner.as_ref() || unset_excludes(x, inner.as_ref())
885            }
886            // Leaf predicates delegate to domain algebra.
887            (GuardExpr::Predicate(p1), GuardExpr::Predicate(p2)) => p1.is_disjoint_from(p2),
888            // Distribution over `Or`: every arm must exclude `other`.
889            (GuardExpr::Or(arms), other) | (other, GuardExpr::Or(arms)) => {
890                arms.iter().all(|arm| arm.is_disjoint_from(other))
891            }
892            // Distribution over `All`: one excluding arm suffices.
893            (GuardExpr::All(arms), other) | (other, GuardExpr::All(arms)) => {
894                arms.iter().any(|arm| arm.is_disjoint_from(other))
895            }
896        }
897    }
898}
899
900/// Top-level conjuncts of a guard: descend `All` only. The DNF
901/// expansion below distributes anything nested (`Or`/`Not`)
902/// exactly; this split is only the entry point.
903fn conjuncts(expr: &GuardExpr) -> Vec<&GuardExpr> {
904    match expr {
905        GuardExpr::All(items) => items.iter().collect(),
906        single => vec![single],
907    }
908}
909
910/// Closed value domains for coverage reasoning, driven by the
911/// parser's accepted values rather than per-value match arms in the
912/// analyzer: `bool` admits true/false, `os` admits the three known
913/// systems (`family:unix` already lowers to `any(os:macos,
914/// os:linux)`, so unix-family coverage is structural). `env` is
915/// open (any string), so it never exhausts.
916fn closed_domain_values(ns: Ns, key: Option<&str>) -> Option<&'static [&'static str]> {
917    match (ns, key) {
918        (Ns::Bool, None) => Some(&["true", "false"]),
919        (Ns::Os, None) => Some(&["macos", "linux", "windows"]),
920        (Ns::Arch, None) => Some(ARCH_VALUES),
921        _ => None,
922    }
923}
924
925/// One DNF literal: a predicate or its negation. Negations only
926/// ever sit on predicates after NNF pushdown.
927#[derive(Clone)]
928enum DnfLit {
929    Pos(Guard),
930    Neg(Guard),
931}
932
933impl DnfLit {
934    fn as_expr(&self) -> GuardExpr {
935        match self {
936            DnfLit::Pos(guard) => GuardExpr::Predicate(guard.clone()),
937            DnfLit::Neg(guard) => GuardExpr::Not(Box::new(GuardExpr::Predicate(guard.clone()))),
938        }
939    }
940}
941
942/// Cap on DNF disjuncts: guard formulas are a handful of atoms, so
943/// this never fires on real input. Exceeding it falls back to live
944/// (satisfiable), the sound direction — a missed proof only risks a
945/// false coverage error, never a missed one.
946const MAX_DNF_DISJUNCTS: usize = 64;
947
948/// Push one expression into DNF under a polarity: `true` keeps it,
949/// `false` negates it (De Morgan through `All`/`Or`, double
950/// negation cancels). Returns the disjunct list, or `None` when the
951/// cap trips.
952fn dnf_push(expr: &GuardExpr, polarity: bool, out: &mut Vec<Vec<DnfLit>>) -> bool {
953    match (expr, polarity) {
954        (GuardExpr::Predicate(guard), true) => {
955            for disjunct in out.iter_mut() {
956                disjunct.push(DnfLit::Pos(guard.clone()));
957            }
958            true
959        }
960        (GuardExpr::Predicate(guard), false) => {
961            for disjunct in out.iter_mut() {
962                disjunct.push(DnfLit::Neg(guard.clone()));
963            }
964            true
965        }
966        (GuardExpr::All(children), true) | (GuardExpr::Or(children), false) => {
967            // Conjunction: every child constrains every disjunct.
968            for child in children {
969                if !dnf_push(child, polarity, out) {
970                    return false;
971                }
972            }
973            true
974        }
975        (GuardExpr::Or(children), true) | (GuardExpr::All(children), false) => {
976            // Disjunction: each child forks every live disjunct.
977            let mut forked = Vec::new();
978            for disjunct in out.drain(..) {
979                for child in children {
980                    let mut branch = vec![disjunct.clone()];
981                    if !dnf_push(child, polarity, &mut branch) {
982                        return false;
983                    }
984                    forked.extend(branch);
985                    if forked.len() > MAX_DNF_DISJUNCTS {
986                        return false;
987                    }
988                }
989            }
990            *out = forked;
991            true
992        }
993        (GuardExpr::Not(inner), _) => dnf_push(inner, !polarity, out),
994    }
995}
996
997/// True when one DNF disjunct can fire: no statically-false
998/// literal, no conflicting pair, and no closed domain exhausted by
999/// negations.
1000fn disjunct_satisfiable(lits: &[DnfLit]) -> bool {
1001    // A statically-false positive (`bool:false`, or any non-`true`
1002    // which `guard_allows` parses as false) kills the disjunct, as
1003    // does the negation of `bool:true` (which always fires).
1004    for lit in lits {
1005        match lit {
1006            DnfLit::Pos(Guard::Attr {
1007                ns: Ns::Bool, val, ..
1008            }) if val.as_deref() != Some("true") => return false,
1009            DnfLit::Neg(Guard::Attr {
1010                ns: Ns::Bool,
1011                key: None,
1012                val: Some(value),
1013            }) if value == "true" => return false,
1014            _ => {}
1015        }
1016    }
1017    // Any conflicting pair kills the disjunct (complements, leaf
1018    // disjointness, and `Or`/`All` distribution decide inside).
1019    for (index, first) in lits.iter().enumerate() {
1020        for second in &lits[index + 1..] {
1021            if first.as_expr().is_disjoint_from(&second.as_expr()) {
1022                return false;
1023            }
1024        }
1025    }
1026    // A closed domain with every value negated has nowhere left to
1027    // fire (`not(os:macos)`, `not(os:linux)`, `not(os:windows)`
1028    // jointly cover no host).
1029    for lit in lits {
1030        let (ns, key) = match lit {
1031            DnfLit::Neg(Guard::Attr {
1032                ns,
1033                key,
1034                val: Some(_),
1035            }) => (*ns, key.as_deref()),
1036            _ => continue,
1037        };
1038        let Some(domain) = closed_domain_values(ns, key) else {
1039            continue;
1040        };
1041        let exhausted = domain.iter().all(|value| {
1042            lits.iter().any(|other| match other {
1043                DnfLit::Neg(Guard::Attr {
1044                    ns: other_ns,
1045                    key: other_key,
1046                    val: Some(other_val),
1047                }) => *other_ns == ns && other_key.as_deref() == key && other_val == value,
1048                _ => false,
1049            })
1050        });
1051        if exhausted {
1052            return false;
1053        }
1054    }
1055    true
1056}
1057
1058/// True when a conjunction list can never fire: its exact DNF has
1059/// no satisfiable disjunct. This proves rather than assumes —
1060/// pairwise conflicts, `bool` falsehood, and complete closed-domain
1061/// partitions (`os:macos`/`os:linux`/`os:windows`,
1062/// `bool:true`/`bool:false`) all decide here with no per-domain
1063/// tables and no hardcoded platform pairs.
1064fn conjunction_dead(atoms: &[&GuardExpr]) -> bool {
1065    if atoms.is_empty() {
1066        return false;
1067    }
1068    let mut disjuncts = vec![Vec::new()];
1069    for atom in atoms {
1070        if !dnf_push(atom, true, &mut disjuncts) {
1071            return false;
1072        }
1073    }
1074    !disjuncts
1075        .iter()
1076        .any(|disjunct| disjunct_satisfiable(disjunct))
1077}
1078
1079/// True when a guard can fire. Anything not provably dead is live.
1080pub fn guard_satisfiable(expr: &GuardExpr) -> bool {
1081    !conjunction_dead(&conjuncts(expr))
1082}
1083
1084/// True when a guard fires unconditionally: a lone `true`, an
1085/// all-valid conjunction, or the negation of a dead conjunction.
1086pub fn guard_valid(expr: &GuardExpr) -> bool {
1087    match expr {
1088        GuardExpr::Predicate(Guard::Attr {
1089            ns: Ns::Bool,
1090            val: Some(value),
1091            ..
1092        }) => value.as_str() == "true",
1093        GuardExpr::All(items) => items.iter().all(guard_valid),
1094        GuardExpr::Not(inner) => !guard_satisfiable(inner),
1095        _ => false,
1096    }
1097}
1098
1099/// True when two declaration guards can fire together. Absent guards
1100/// are unconditional; anything without a provable conflict overlaps.
1101pub fn guards_overlap(a: Option<&GuardExpr>, b: Option<&GuardExpr>) -> bool {
1102    match (a, b) {
1103        (None, None) => true,
1104        (Some(x), None) | (None, Some(x)) => guard_satisfiable(x),
1105        (Some(x), Some(y)) => {
1106            let mut atoms = conjuncts(x);
1107            atoms.extend(conjuncts(y));
1108            !conjunction_dead(&atoms)
1109        }
1110    }
1111}
1112
1113/// Unset exclusion: `Not([ns:k])` (valueless) is disjoint from any
1114/// positive claim on the same subject, valued or not.
1115fn unset_excludes(x: &GuardExpr, inner: &GuardExpr) -> bool {
1116    match (x, inner) {
1117        (
1118            GuardExpr::Predicate(Guard::Attr {
1119                ns: n2, key: k2, ..
1120            }),
1121            GuardExpr::Predicate(Guard::Attr {
1122                ns: n1,
1123                key: k1,
1124                val: None,
1125            }),
1126        ) => n1 == n2 && k1 == k2,
1127        _ => false,
1128    }
1129}
1130
1131impl fmt::Display for Guard {
1132    /// Bare form without brackets (the step renderer adds them):
1133    /// `[os:linux]` prints `os:linux`, `[env:MODE=dev]`
1134    /// prints `eq(env:MODE, dev)`, `[env:MODE]` prints `env:MODE`.
1135    /// The `eq()` spelling roundtrips through the parser; the rest
1136    /// print verbatim. Roundtrips by construction.
1137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1138        match self {
1139            Guard::Attr {
1140                ns: Ns::Env,
1141                key: Some(var),
1142                val: None,
1143            } => write!(f, "env:{var}"),
1144            Guard::Attr {
1145                ns: Ns::Env,
1146                key: Some(var),
1147                val: Some(want),
1148            } => write!(f, "eq(env:{var}, {want})"),
1149            Guard::Attr {
1150                ns,
1151                key: _,
1152                val: Some(value),
1153            } => write!(f, "{ns}:{value}"),
1154            Guard::Attr { ns, key, val: None } => match key {
1155                Some(subject) => write!(f, "{ns}:{subject}"),
1156                None => write!(f, "{ns}"),
1157            },
1158        }
1159    }
1160}
1161
1162impl fmt::Display for WorkspaceTarget {
1163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1164        match self {
1165            WorkspaceTarget::Snapshot => write!(f, "SNAPSHOT"),
1166            WorkspaceTarget::Local => write!(f, "LOCAL"),
1167            WorkspaceTarget::Cache { local: false } => write!(f, "CACHE"),
1168            WorkspaceTarget::Cache { local: true } => write!(f, "CACHE --local"),
1169            WorkspaceTarget::System => write!(f, "SYSTEM"),
1170        }
1171    }
1172}
1173
1174impl fmt::Display for Expr {
1175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1176        match self {
1177            Expr::Literal(v) => write!(f, "{}", v),
1178            Expr::Var(name) => write!(f, "${}", name),
1179            Expr::Env(key) => write!(f, "env:{}", key),
1180            Expr::KeyPath { base, keys } => {
1181                write!(f, "${}", base)?;
1182                for key in keys {
1183                    write!(f, ".{}", key)?;
1184                }
1185                Ok(())
1186            }
1187            Expr::Call { name, args } => {
1188                write!(f, "{}(", name)?;
1189                for (i, arg) in args.iter().enumerate() {
1190                    if i > 0 {
1191                        write!(f, ", ")?;
1192                    }
1193                    write!(f, "{}", arg)?;
1194                }
1195                write!(f, ")")
1196            }
1197            Expr::Inspect(var) => write!(f, "INSPECT(${})", var),
1198            Expr::List(items) => {
1199                write!(f, "[")?;
1200                for (i, item) in items.iter().enumerate() {
1201                    if i > 0 {
1202                        write!(f, ", ")?;
1203                    }
1204                    write!(f, "{}", item)?;
1205                }
1206                write!(f, "]")
1207            }
1208            Expr::Map(entries) => {
1209                write!(f, "{{")?;
1210                for (i, (key, val)) in entries.iter().enumerate() {
1211                    if i > 0 {
1212                        write!(f, ", ")?;
1213                    }
1214                    write!(f, "\"{}\": {}", key, val)?;
1215                }
1216                write!(f, "}}")
1217            }
1218            Expr::Block(steps) => {
1219                write!(f, "{{ ")?;
1220                for (i, step) in steps.iter().enumerate() {
1221                    if i > 0 {
1222                        write!(f, "; ")?;
1223                    }
1224                    write!(f, "{}", step.kind)?;
1225                }
1226                write!(f, " }}")
1227            }
1228            Expr::Compare { op, left, right } => {
1229                write!(f, "{} {} {}", left, op, right)
1230            }
1231            Expr::Arithmetic { op, left, right } => {
1232                write!(f, "({} {} {})", left, op, right)
1233            }
1234            Expr::CompiledMath(ops) => {
1235                write!(f, "{}", format_compiled_math(ops))
1236            }
1237            // No expression syntax produces this (bare `LET` is a
1238            // statement): render loudly non-round-trippable so a stray
1239            // use fails at re-parse instead of aliasing a named pipe.
1240            Expr::FreshPipe => write!(f, "<fresh pipe>"),
1241            Expr::UnsignedIntBoundary(n) => write!(f, "{}", n),
1242            Expr::Not(inner) => {
1243                // Parenthesize compound operands so Display round-trips:
1244                // `!(a == b)` must not render as `!a == b` (= `(!a) == b`).
1245                match inner.as_ref() {
1246                    Expr::Compare { .. } | Expr::Arithmetic { .. } | Expr::CompiledMath(_) => {
1247                        write!(f, "!({})", inner)
1248                    }
1249                    _ => write!(f, "!{}", inner),
1250                }
1251            }
1252            Expr::Logical { op, left, right } => {
1253                write!(f, "({} {} {})", left, op, right)
1254            }
1255        }
1256    }
1257}
1258
1259impl fmt::Display for CompareOp {
1260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1261        match self {
1262            CompareOp::Eq => write!(f, "=="),
1263            CompareOp::Ne => write!(f, "!="),
1264            CompareOp::Lt => write!(f, "<"),
1265            CompareOp::Le => write!(f, "<="),
1266            CompareOp::Gt => write!(f, ">"),
1267            CompareOp::Ge => write!(f, ">="),
1268        }
1269    }
1270}
1271
1272impl fmt::Display for ArithOp {
1273    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1274        match self {
1275            ArithOp::Add => write!(f, "+"),
1276            ArithOp::Sub => write!(f, "-"),
1277            ArithOp::Mul => write!(f, "*"),
1278            ArithOp::Div => write!(f, "/"),
1279        }
1280    }
1281}
1282
1283/// Render flat RPN back to parenthesized infix so `Display` round-trips
1284/// through the parser with identical semantics. Parentheses are emitted
1285/// unconditionally around binary/unary ops; redundant parens parse to the
1286/// same tree, which is what round-trip requires.
1287fn format_compiled_math(ops: &[MathOp]) -> String {
1288    let mut stack: Vec<String> = Vec::new();
1289    for op in ops {
1290        match op {
1291            MathOp::PushConst(v) => stack.push(format!("{}", v)),
1292            MathOp::LoadVar(name) => stack.push(format!("${}", name)),
1293            MathOp::LoadEnv(key) => stack.push(format!("env:{}", key)),
1294            MathOp::LoadKeyPath { base, keys } => {
1295                let mut s = format!("${}", base);
1296                for key in keys {
1297                    s.push('.');
1298                    s.push_str(key);
1299                }
1300                stack.push(s);
1301            }
1302            MathOp::Call { name, arity } => {
1303                let mut args = Vec::new();
1304                for _ in 0..*arity {
1305                    args.push(stack.pop().unwrap_or_else(|| "<underflow>".to_string()));
1306                }
1307                args.reverse();
1308                stack.push(format!("{}({})", name, args.join(", ")));
1309            }
1310            MathOp::Inspect(name) => stack.push(format!("INSPECT(${})", name)),
1311            MathOp::Neg => {
1312                let inner = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1313                stack.push(format!("(-{})", inner));
1314            }
1315            MathOp::Add => push_bin(&mut stack, "+"),
1316            MathOp::Sub => push_bin(&mut stack, "-"),
1317            MathOp::Mul => push_bin(&mut stack, "*"),
1318            MathOp::Div => push_bin(&mut stack, "/"),
1319            MathOp::Lt => push_bin(&mut stack, "<"),
1320            MathOp::Le => push_bin(&mut stack, "<="),
1321            MathOp::Gt => push_bin(&mut stack, ">"),
1322            MathOp::Ge => push_bin(&mut stack, ">="),
1323            MathOp::Eq => push_bin(&mut stack, "=="),
1324            MathOp::Ne => push_bin(&mut stack, "!="),
1325        }
1326    }
1327    if stack.len() == 1 {
1328        let mut items = stack;
1329        items.pop().unwrap_or_else(|| "<empty>".to_string())
1330    } else {
1331        stack.join(" ")
1332    }
1333}
1334
1335fn push_bin(stack: &mut Vec<String>, op: &str) {
1336    let right = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1337    let left = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1338    stack.push(format!("({} {} {})", left, op, right));
1339}
1340
1341impl fmt::Display for LogicalOp {
1342    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1343        match self {
1344            LogicalOp::And => write!(f, "&&"),
1345            LogicalOp::Or => write!(f, "||"),
1346        }
1347    }
1348}
1349
1350enum GuardDisplayContext {
1351    Root,
1352    InAnyArg,
1353    InNot,
1354    InAll,
1355}
1356
1357impl GuardExpr {
1358    fn fmt_with_ctx(&self, f: &mut fmt::Formatter<'_>, ctx: GuardDisplayContext) -> fmt::Result {
1359        match self {
1360            GuardExpr::Predicate(guard) => write!(f, "{}", guard),
1361            GuardExpr::All(children) => {
1362                let wrap = matches!(
1363                    ctx,
1364                    GuardDisplayContext::InAnyArg | GuardDisplayContext::InNot
1365                ) && children.len() > 1;
1366                if wrap {
1367                    write!(f, "(")?;
1368                }
1369                for (i, child) in children.iter().enumerate() {
1370                    if i > 0 {
1371                        write!(f, ", ")?;
1372                    }
1373                    child.fmt_with_ctx(f, GuardDisplayContext::InAll)?;
1374                }
1375                if wrap {
1376                    write!(f, ")")?;
1377                }
1378                Ok(())
1379            }
1380            GuardExpr::Or(children) => {
1381                write!(f, "any(")?;
1382                for (i, child) in children.iter().enumerate() {
1383                    if i > 0 {
1384                        write!(f, ", ")?;
1385                    }
1386                    child.fmt_with_ctx(f, GuardDisplayContext::InAnyArg)?;
1387                }
1388                write!(f, ")")
1389            }
1390            GuardExpr::Not(child) => {
1391                write!(f, "not(")?;
1392                child.fmt_with_ctx(f, GuardDisplayContext::InNot)?;
1393                write!(f, ")")
1394            }
1395        }
1396    }
1397}
1398
1399impl fmt::Display for GuardExpr {
1400    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1401        self.fmt_with_ctx(f, GuardDisplayContext::Root)
1402    }
1403}
1404
1405impl fmt::Display for Step {
1406    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1407        if let Some(expr) = &self.guard {
1408            write!(f, "[{}] ", expr)?;
1409        }
1410        write!(f, "{}", self.kind)
1411    }
1412}
1413
1414#[cfg(test)]
1415mod tests {
1416    use super::*;
1417    /// Bidirectional lock between `dsl.pest` and the keyword registry.
1418    /// Fails CI if a statement keyword is renamed or deleted on either side.
1419    /// The grammar is parsed with `pest_meta` (no line-format or rule-name
1420    /// conventions): every [`STRUCTURAL_KEYWORDS`] entry must occur as a
1421    /// string literal somewhere in the grammar, and every uppercase literal
1422    /// reachable from the top-level instruction rules (`element`,
1423    /// `block_element`, following rule references transitively) must
1424    /// classify as a statement starter ([`Command::is_statement_keyword`])
1425    /// or a clause keyword ([`CLAUSE_KEYWORDS`]). Type tags, argument
1426    /// enums, and value-level function names validate at lowering time via
1427    /// generic ident rules, so they are outside this test's scope by design
1428    /// rather than via synthetic registries.
1429    #[test]
1430    fn statement_keywords_match_pest_grammar() {
1431        use pest_meta::{ast::Expr, parser};
1432        use std::collections::{HashMap, HashSet};
1433
1434        let pest_src = include_str!("dsl.pest");
1435        let pairs = parser::parse(parser::Rule::grammar_rules, pest_src)
1436            .expect("dsl.pest must parse as a pest grammar");
1437        let rules = parser::consume_rules(pairs).expect("dsl.pest rules must consume");
1438        let by_name: HashMap<&str, &Expr> = rules
1439            .iter()
1440            .map(|rule| (rule.name.as_str(), &rule.expr))
1441            .collect();
1442
1443        let mut all_literals = HashSet::new();
1444        for rule in &rules {
1445            for node in rule.expr.iter_top_down() {
1446                match node {
1447                    Expr::Str(literal) | Expr::Insens(literal) => {
1448                        all_literals.insert(literal.clone());
1449                    }
1450                    _ => {}
1451                }
1452            }
1453        }
1454        for kw in STRUCTURAL_KEYWORDS {
1455            assert!(
1456                all_literals.contains(*kw),
1457                "keyword {kw} in STRUCTURAL_KEYWORDS missing from dsl.pest"
1458            );
1459        }
1460
1461        let mut seen = HashSet::new();
1462        let mut stack = vec!["element".to_string(), "block_element".to_string()];
1463        let mut stmt_literals = HashSet::new();
1464        while let Some(name) = stack.pop() {
1465            if !seen.insert(name.clone()) {
1466                continue;
1467            }
1468            let Some(expr) = by_name.get(name.as_str()) else {
1469                continue;
1470            };
1471            for node in expr.iter_top_down() {
1472                match node {
1473                    Expr::Str(literal) | Expr::Insens(literal) => {
1474                        stmt_literals.insert(literal.clone());
1475                    }
1476                    Expr::Ident(dependency) => stack.push(dependency.clone()),
1477                    _ => {}
1478                }
1479            }
1480        }
1481        assert!(
1482            seen.contains("element") && seen.contains("block_element"),
1483            "grammar must define element and block_element instruction rules"
1484        );
1485        for kw in stmt_literals {
1486            if kw.len() > 1 && kw.chars().all(|c| c.is_ascii_uppercase()) {
1487                assert!(
1488                    crate::Command::is_statement_keyword(&kw)
1489                        || CLAUSE_KEYWORDS.contains(&kw.as_str()),
1490                    "uppercase literal \"{kw}\" reachable from dsl.pest instruction rules is not a registered statement or clause keyword"
1491                );
1492            }
1493        }
1494    }
1495
1496    /// Category convention lock: every multi-word command groups under a
1497    /// registered `COMMAND_CATEGORIES` prefix. Adding a command under a
1498    /// new category fails here until the prefix registers (one line).
1499    #[test]
1500    fn command_names_group_by_category() {
1501        for command in COMMANDS {
1502            let name = command.as_str();
1503            let Some((prefix, _)) = name.split_once('_') else {
1504                continue;
1505            };
1506            assert!(
1507                COMMAND_CATEGORIES.contains(&prefix),
1508                "command {name} introduces unregistered category {prefix}; add it to COMMAND_CATEGORIES"
1509            );
1510        }
1511    }
1512}
1513
1514#[cfg(test)]
1515mod guard_analysis_tests {
1516    use super::*;
1517
1518    fn attr(ns: Ns, key: Option<&str>, val: Option<&str>) -> GuardExpr {
1519        GuardExpr::Predicate(Guard::Attr {
1520            ns,
1521            key: key.map(str::to_string),
1522            val: val.map(str::to_string),
1523        })
1524    }
1525
1526    fn os(value: &str) -> GuardExpr {
1527        attr(Ns::Os, None, Some(value))
1528    }
1529
1530    fn arch(value: &str) -> GuardExpr {
1531        attr(Ns::Arch, None, Some(value))
1532    }
1533
1534    /// The `family:unix` parse alias, desugared exactly as the
1535    /// parser lowers it.
1536    fn unix() -> GuardExpr {
1537        GuardExpr::Or(vec![os("macos"), os("linux")])
1538    }
1539
1540    fn windows() -> GuardExpr {
1541        os("windows")
1542    }
1543
1544    fn env_eq(var: &str, value: &str) -> GuardExpr {
1545        attr(Ns::Env, Some(var), Some(value))
1546    }
1547
1548    fn not(expr: GuardExpr) -> GuardExpr {
1549        GuardExpr::Not(Box::new(expr))
1550    }
1551
1552    /// Closed domains exhaust: negating every `os:` value (or both
1553    /// `bool:` values) covers no host. Open domains (`env:`) never
1554    /// exhaust — some unmentioned value may hold.
1555    #[test]
1556    fn partition_negations_are_jointly_dead() {
1557        let os_exhausted = GuardExpr::All(vec![not(os("macos")), not(os("linux")), not(windows())]);
1558        assert!(
1559            !guard_satisfiable(&os_exhausted),
1560            "no host is outside `macos`/`linux`/`windows`"
1561        );
1562        // Partial negations stay live.
1563        let os_partial = GuardExpr::All(vec![not(os("macos")), not(os("linux"))]);
1564        assert!(guard_satisfiable(&os_partial), "`windows` is still open");
1565        // The bool domain exhausts the same way.
1566        let bool_exhausted = GuardExpr::All(vec![
1567            not(attr(Ns::Bool, None, Some("true"))),
1568            not(attr(Ns::Bool, None, Some("false"))),
1569        ]);
1570        assert!(!guard_satisfiable(&bool_exhausted));
1571        // Open env domains never exhaust.
1572        let env_open = GuardExpr::All(vec![
1573            not(env_eq("MODE", "dev")),
1574            not(env_eq("MODE", "prod")),
1575        ]);
1576        assert!(guard_satisfiable(&env_open), "MODE may hold a third value");
1577        // Single negations are always live.
1578        assert!(guard_satisfiable(&not(unix())));
1579    }
1580
1581    /// The desugared `unix` alias behaves as a disjunction: it meets
1582    /// `windows` nowhere and covers `macos`/`linux` deployment reads.
1583    #[test]
1584    fn unix_alias_is_os_disjunction() {
1585        assert!(!guards_overlap(Some(&unix()), Some(&windows())));
1586        assert!(guards_overlap(Some(&unix()), Some(&os("macos"))));
1587        // Coverage through the alias: `unix` + `windows` declarations
1588        // cover every host, so their joint negation is dead.
1589        let covered = GuardExpr::All(vec![GuardExpr::Not(Box::new(unix())), not(windows())]);
1590        assert!(!guard_satisfiable(&covered));
1591    }
1592
1593    /// `arch:` decides by value like every namespace; it overlaps
1594    /// `os:` (independent axes: an aarch64 mac exists). Negating
1595    /// the whole closed `ARCH_VALUES` domain covers no host.
1596    #[test]
1597    fn arch_guards_decide_by_value() {
1598        assert!(!guards_overlap(
1599            Some(&arch("x86_64")),
1600            Some(&arch("aarch64"))
1601        ));
1602        assert!(guards_overlap(Some(&arch("x86_64")), Some(&arch("x86_64"))));
1603        assert!(guards_overlap(Some(&arch("aarch64")), Some(&os("macos"))));
1604        let exhausted = GuardExpr::All(ARCH_VALUES.iter().map(|value| not(arch(value))).collect());
1605        assert!(!guard_satisfiable(&exhausted));
1606        // Runtime anchor: this host's own architecture fires here.
1607        let host = attr(Ns::Arch, None, Some(ARCH_TARGET));
1608        assert!(guard_expr_allows(&host, &HashMap::new()));
1609    }
1610
1611    /// The full platform matrix, asserted exhaustively. All three
1612    /// `os:` values are pairwise disjoint; identical values
1613    /// overlap.
1614    #[test]
1615    fn platform_overlap_matrix_is_exhaustive() {
1616        let cases = [
1617            ("macos", "macos", true),
1618            ("macos", "linux", false),
1619            ("macos", "windows", false),
1620            ("linux", "linux", true),
1621            ("linux", "windows", false),
1622            ("windows", "windows", true),
1623        ];
1624        for (v1, v2, expected) in cases {
1625            let left = os(v1);
1626            let right = os(v2);
1627            assert_eq!(
1628                guards_overlap(Some(&left), Some(&right)),
1629                expected,
1630                "os:{v1} vs os:{v2}"
1631            );
1632        }
1633    }
1634
1635    /// Runtime anchor, portable across CI hosts: `os:macos` and
1636    /// `os:windows` never co-fire on the machine running the test.
1637    #[test]
1638    fn disjoint_pairs_never_cofire_here() {
1639        let macos = os("macos");
1640        let holds = |expr: &GuardExpr| guard_expr_allows(expr, &HashMap::new());
1641        assert!(
1642            !(holds(&macos) && holds(&windows())),
1643            "os:macos and os:windows co-fired"
1644        );
1645    }
1646
1647    #[test]
1648    fn overlap_follows_namespace_semantics() {
1649        // Same namespace, distinct values: disjoint.
1650        assert!(!guards_overlap(Some(&windows()), Some(&unix())));
1651        assert!(!guards_overlap(Some(&os("macos")), Some(&os("linux"))));
1652        // Absent guards are unconditional.
1653        assert!(guards_overlap(None, Some(&windows())));
1654        assert!(guards_overlap(None, None));
1655        // Unsatisfiable conjunctions overlap nothing.
1656        let dead = GuardExpr::All(vec![os("macos"), windows()]);
1657        assert!(!guard_satisfiable(&dead));
1658        assert!(!guards_overlap(Some(&dead), Some(&os("macos"))));
1659        assert!(guard_valid(&GuardExpr::Predicate(Guard::Attr {
1660            ns: Ns::Bool,
1661            key: None,
1662            val: Some("true".to_string()),
1663        })));
1664        assert!(!guard_valid(&unix()));
1665    }
1666
1667    #[test]
1668    fn env_value_conflicts_decide_without_enumeration() {
1669        let fast = env_eq("MODE", "fast");
1670        let slow = env_eq("MODE", "slow");
1671        assert!(
1672            !guards_overlap(Some(&fast), Some(&slow)),
1673            "same key distinct values are disjoint"
1674        );
1675        let also_fast = env_eq("MODE", "fast");
1676        assert!(guards_overlap(Some(&fast), Some(&also_fast)));
1677        // Bare presence overlaps any value on the same key.
1678        let bare = attr(Ns::Env, Some("MODE"), None);
1679        assert!(guards_overlap(Some(&bare), Some(&fast)));
1680    }
1681}
1682
1683#[cfg(test)]
1684mod guard_algebra_tests {
1685    use super::*;
1686
1687    fn os(value: &str) -> GuardExpr {
1688        GuardExpr::Predicate(Guard::Attr {
1689            ns: Ns::Os,
1690            key: None,
1691            val: Some(value.to_string()),
1692        })
1693    }
1694
1695    #[test]
1696    fn or_distributes_over_disjointness() {
1697        fn env_eq(var: &str, value: &str) -> GuardExpr {
1698            GuardExpr::Predicate(Guard::Attr {
1699                ns: Ns::Env,
1700                key: Some(var.to_string()),
1701                val: Some(value.to_string()),
1702            })
1703        }
1704        // Every arm must exclude `other`: one overlapping arm keeps
1705        // the whole disjunction live.
1706        let mixed = GuardExpr::Or(vec![env_eq("MODE", "dev"), env_eq("MODE", "prod")]);
1707        assert!(!mixed.is_disjoint_from(&env_eq("MODE", "dev")));
1708        // All arms disjoint: the disjunction is dead against it.
1709        assert!(mixed.is_disjoint_from(&env_eq("MODE", "test")));
1710        // Cross-namespace arms never exclude: different axes overlap.
1711        let cross = GuardExpr::Or(vec![env_eq("MODE", "dev")]);
1712        let platform = os("windows");
1713        assert!(!cross.is_disjoint_from(&platform));
1714    }
1715
1716    #[test]
1717    fn all_distributes_over_disjointness() {
1718        let stacked = GuardExpr::All(vec![
1719            os("macos"),
1720            GuardExpr::Or(vec![os("macos"), os("linux")]),
1721            os("windows"),
1722        ]);
1723        assert!(stacked.is_disjoint_from(&os("macos")));
1724        // One live arm keeps the conjunction overlapping: neither
1725        // arm excludes macos here.
1726        let live = GuardExpr::All(vec![
1727            os("macos"),
1728            GuardExpr::Predicate(Guard::Attr {
1729                ns: Ns::Env,
1730                key: Some("MODE".to_string()),
1731                val: Some("dev".to_string()),
1732            }),
1733        ]);
1734        assert!(!live.is_disjoint_from(&os("macos")));
1735    }
1736
1737    #[test]
1738    fn negation_is_structural_not_syntactic() {
1739        let not_win = GuardExpr::Not(Box::new(os("windows")));
1740        assert!(not_win.is_disjoint_from(&os("windows")));
1741        assert!(os("windows").is_disjoint_from(&not_win));
1742        assert!(!not_win.is_disjoint_from(&os("macos")));
1743    }
1744}