Skip to main content

oxdock_parser/
ast.rs

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