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    KEYWORD_APPEND, KEYWORD_APPEND_LINE, KEYWORD_ARCHIVE, KEYWORD_ASSERT_CONTAINS,
10    KEYWORD_ASSERT_EQ, KEYWORD_ASSERT_NE, KEYWORD_ASYNC, KEYWORD_AWAIT, KEYWORD_BREAK,
11    KEYWORD_CANCEL, KEYWORD_CASE, KEYWORD_CONST, KEYWORD_CONTINUE, KEYWORD_COPY, KEYWORD_COPY_GIT,
12    KEYWORD_DEFAULT, KEYWORD_ECHO, KEYWORD_ELSE, KEYWORD_ENV, KEYWORD_EXIT, KEYWORD_EXPAND,
13    KEYWORD_EXPORT, KEYWORD_FAIL, KEYWORD_FOR, KEYWORD_FUNC, KEYWORD_IF, KEYWORD_IMPORT,
14    KEYWORD_IN, KEYWORD_INHERIT_ENV, KEYWORD_INSPECT, KEYWORD_INSTALL, KEYWORD_ISOLATED,
15    KEYWORD_LET, KEYWORD_LIST_APPEND, KEYWORD_LS, KEYWORD_MKDIR, KEYWORD_PROMPT, KEYWORD_READ,
16    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 { name: String },
650    LoadConstRef { alias: String, name: String },
651    LoadEnv(String),
652    LoadKeyPath { base: String, keys: Vec<String> },
653    Call { name: String, arity: usize },
654    Inspect { name: String },
655    Neg,
656    Add,
657    Sub,
658    Mul,
659    Div,
660    Lt,
661    Le,
662    Gt,
663    Ge,
664    Eq,
665    Ne,
666}
667
668#[derive(Debug, Clone, Copy, Eq, PartialEq)]
669pub enum LogicalOp {
670    And,
671    Or,
672}
673
674#[derive(Debug, Clone, PartialEq)]
675pub enum Expr {
676    Literal(Value),
677    /// Binding read (`$name`): `LET` and `CONST` bindings share one
678    /// namespace and one read syntax. Whether the name is immutable
679    /// is a declaration property, enforced at declare/mutate sites,
680    /// never at the read.
681    Var {
682        name: String,
683    },
684    /// Qualified immutable read (`$ALIAS::NAME`): a `CONST` exported by
685    /// the module imported under `ALIAS`. Evaluation resolves through
686    /// the active unit's alias targets and fails closed on unknown
687    /// aliases, non-exported names, and `LET` bindings (never
688    /// exportable).
689    ConstRef {
690        alias: String,
691        name: String,
692    },
693    /// Environment read (`env:KEY`): resolves against the script
694    /// environment at evaluation time.
695    Env(String),
696    /// Key path traversal (`$base.key`) over either binding family.
697    KeyPath {
698        base: String,
699        keys: Vec<String>,
700    },
701    List(Vec<Expr>),
702    Map(Vec<(String, Expr)>),
703    /// Inline block (`LET $a: STRING = { RETURN "hi" }`): runs its steps in
704    /// a fresh scope when evaluated and yields the `RETURN` value
705    /// (fallthrough yields `""`, mirroring a zero-arg function body).
706    /// Parsed only where `map_literal` fails, so `{k: v}` stays a map.
707    Block(Vec<Step>),
708    Call {
709        name: String,
710        args: Vec<Expr>,
711    },
712    /// Variable inspection (`INSPECT($var)`): carries the variable
713    /// name unevaluated so evaluation can snapshot the binding.
714    /// Produced only by the parser for the exact `INSPECT`
715    /// name; evaluators match on this variant and never on a
716    /// function-name string.
717    Inspect {
718        name: String,
719    },
720    Compare {
721        op: CompareOp,
722        left: Box<Expr>,
723        right: Box<Expr>,
724    },
725    Arithmetic {
726        op: ArithOp,
727        left: Box<Expr>,
728        right: Box<Expr>,
729    },
730    /// Lowering-optimized form: folded literals stay `Literal`, dynamic
731    /// arithmetic/comparison subtrees arrive here as flat RPN.
732    CompiledMath(Vec<MathOp>),
733    /// Fresh anonymous pipe backend (`LET $p: PIPE` with no initializer).
734    /// Evaluates to a pipe value keyed by a generated name that no
735    /// `pipe:` literal can spell, so bare declarations never collide
736    /// with named pipes. Transitional representation until backends
737    /// become owned handles.
738    FreshPipe,
739    /// Lowering-only intermediate staging `9223372036854775808` (the unsigned
740    /// half of `i64::MIN`). Valid only as the direct child of unary `-`;
741    /// any instance reaching lowering completion bails integer overflow.
742    UnsignedIntBoundary(u64),
743    Not(Box<Expr>),
744    Logical {
745        op: LogicalOp,
746        left: Box<Expr>,
747        right: Box<Expr>,
748    },
749}
750
751#[derive(Debug, Clone)]
752pub struct Step {
753    pub guard: Option<GuardExpr>,
754    pub kind: StepKind,
755    pub scope_enter: usize,
756    pub scope_exit: usize,
757    /// 1-based source line of the statement that produced this step
758    /// (`0` when unknown: hand-built steps, synthetic streams). Stamped
759    /// at lower time from the split statement, so runtime errors can
760    /// name the failing line. Never rendered by `Display` (output must
761    /// stay reparse-stable) and never compared by content equality
762    /// (provenance, like quoting flags and scope markers).
763    pub line: usize,
764    /// 1-based column where the statement starts (`0` when unknown).
765    /// Same stamping, same provenance rules as `line`; runtime errors
766    /// render both.
767    pub col: usize,
768}
769
770impl PartialEq for Step {
771    fn eq(&self, other: &Self) -> bool {
772        self.guard == other.guard
773            && self.kind == other.kind
774            && self.scope_enter == other.scope_enter
775            && self.scope_exit == other.scope_exit
776    }
777}
778
779impl Eq for Step {}
780
781impl Step {
782    /// Definition span for this step in the shared transport type.
783    /// Derived from the stamped `line`/`col` provenance (no new data,
784    /// so equality and rendering are untouched): line-only when the
785    /// column is unknown, fully unknown when the line is `0`.
786    pub fn span(&self) -> Span {
787        if self.line == 0 {
788            return Span::default();
789        }
790        if self.col == 0 {
791            return Span::line_only(self.line);
792        }
793        Span::line_col(self.line, self.col)
794    }
795
796    /// Symbol this step defines, with its definition span. Covers
797    /// `TYPE` aliases and `FUNC` definitions only: the go-to-definition
798    /// primitive future symbol tables build on. Returns `None` for
799    /// every other step.
800    pub fn defined_symbol(&self) -> Option<(&str, Span)> {
801        match &self.kind {
802            StepKind::TypeAlias { name, .. } => Some((name.as_str(), self.span())),
803            StepKind::FuncDef { name, .. } => Some((name.as_str(), self.span())),
804            _ => None,
805        }
806    }
807}
808
809impl Expr {
810    /// Visit this expression and every descendant, depth first. `Block`
811    /// steps recurse through [`StepKind::walk_step_exprs`](crate::commands::StepKind::walk_step_exprs),
812    /// so inline bodies are covered; `CompiledMath` ops are opaque here
813    /// (match `MathOp::Call` in the visitor when call names matter).
814    /// Exhaustive over variants: adding an `Expr` shape fails compilation
815    /// here, never silently.
816    pub fn walk(&self, f: &mut impl FnMut(&Expr)) {
817        f(self);
818        match self {
819            Expr::Literal(_)
820            | Expr::Var { .. }
821            | Expr::ConstRef { .. }
822            | Expr::Env(_)
823            | Expr::KeyPath { .. }
824            | Expr::Inspect { .. }
825            | Expr::FreshPipe
826            | Expr::UnsignedIntBoundary(_) => {}
827            Expr::Call { args, .. } => {
828                for arg in args {
829                    arg.walk(f);
830                }
831            }
832            Expr::List(items) => {
833                for item in items {
834                    item.walk(f);
835                }
836            }
837            Expr::Map(entries) => {
838                for (_, value) in entries {
839                    value.walk(f);
840                }
841            }
842            Expr::Block(steps) => {
843                for step in steps {
844                    step.kind.walk_step_exprs(f);
845                }
846            }
847            Expr::Compare { left, right, .. }
848            | Expr::Arithmetic { left, right, .. }
849            | Expr::Logical { left, right, .. } => {
850                left.walk(f);
851                right.walk(f);
852            }
853            Expr::CompiledMath(_) => {}
854            Expr::Not(inner) => inner.walk(f),
855        }
856    }
857
858    /// Mutable twin of [`walk`](Self::walk): visits this expression and
859    /// every descendant depth first. `Block` interiors are skipped:
860    /// inline bodies were lowered as their own statements with their
861    /// own `FUNC`/import frames, so outer-scope qualification must
862    /// never rewrite them. `CompiledMath` stays opaque like above.
863    /// Exhaustive over variants, so new shapes fail compilation here.
864    pub fn walk_mut(&mut self, f: &mut impl FnMut(&mut Expr)) {
865        f(self);
866        match self {
867            Expr::Literal(_)
868            | Expr::Var { .. }
869            | Expr::ConstRef { .. }
870            | Expr::Env(_)
871            | Expr::KeyPath { .. }
872            | Expr::Inspect { .. }
873            | Expr::FreshPipe
874            | Expr::UnsignedIntBoundary(_) => {}
875            Expr::Call { args, .. } => {
876                for arg in args {
877                    arg.walk_mut(f);
878                }
879            }
880            Expr::List(items) => {
881                for item in items {
882                    item.walk_mut(f);
883                }
884            }
885            Expr::Map(entries) => {
886                for (_, value) in entries {
887                    value.walk_mut(f);
888                }
889            }
890            Expr::Block(_) => {}
891            Expr::Compare { left, right, .. }
892            | Expr::Arithmetic { left, right, .. }
893            | Expr::Logical { left, right, .. } => {
894                left.walk_mut(f);
895                right.walk_mut(f);
896            }
897            Expr::CompiledMath(_) => {}
898            Expr::Not(inner) => inner.walk_mut(f),
899        }
900    }
901}
902
903#[derive(Debug, Clone, Eq, PartialEq)]
904pub enum WorkspaceTarget {
905    Snapshot,
906    Local,
907    Cache { local: bool },
908    System,
909}
910
911pub trait EnvLookup {
912    fn get_env(&self, key: &str) -> Option<&str>;
913}
914
915impl EnvLookup for HashMap<String, String> {
916    fn get_env(&self, key: &str) -> Option<&str> {
917        self.get(key).map(|s| s.as_str())
918    }
919}
920
921impl EnvLookup for Arc<HashMap<String, String>> {
922    fn get_env(&self, key: &str) -> Option<&str> {
923        (**self).get_env(key)
924    }
925}
926
927pub fn guard_allows(guard: &Guard, env: &impl EnvLookup) -> bool {
928    let Guard::Attr { ns, key, val } = guard;
929    match ns {
930        Ns::Os => match val.as_deref() {
931            Some("macos") => platform_is_macos(),
932            Some("linux") => platform_is_linux(),
933            Some("windows") => platform_is_windows(),
934            _ => false,
935        },
936        Ns::Arch => match val.as_deref() {
937            Some(want) => ARCH_TARGET == want,
938            None => false,
939        },
940        Ns::Bool => val
941            .as_deref()
942            .map(|v| v.parse::<bool>().unwrap_or(false))
943            .unwrap_or(false),
944        Ns::Env => match key.as_deref() {
945            Some(var) => match val {
946                None => env.get_env(var).map(|v| !v.is_empty()).unwrap_or(false),
947                Some(want) => env
948                    .get_env(var)
949                    .map(|v| v == want.as_str())
950                    .unwrap_or(false),
951            },
952            // Parser always supplies the variable; defensive false.
953            None => false,
954        },
955    }
956}
957
958/// One `cfg!` per platform fact, each beside its namespace arm
959/// above. `#[allow]` lives on the helpers, not the dispatch.
960#[allow(clippy::disallowed_macros)]
961fn platform_is_windows() -> bool {
962    cfg!(windows)
963}
964
965/// See `platform_is_windows`.
966#[allow(clippy::disallowed_macros)]
967fn platform_is_macos() -> bool {
968    cfg!(target_os = "macos")
969}
970
971/// See `platform_is_windows`.
972#[allow(clippy::disallowed_macros)]
973fn platform_is_linux() -> bool {
974    cfg!(target_os = "linux")
975}
976
977/// Host target architecture behind `arch:` guards. A plain const
978/// read alongside the platform helpers above.
979const ARCH_TARGET: &str = std::env::consts::ARCH;
980
981pub fn guard_expr_allows(expr: &GuardExpr, env: &impl EnvLookup) -> bool {
982    match expr {
983        GuardExpr::Predicate(guard) => guard_allows(guard, env),
984        GuardExpr::All(children) => children.iter().all(|g| guard_expr_allows(g, env)),
985        GuardExpr::Or(children) => children.iter().any(|g| guard_expr_allows(g, env)),
986        GuardExpr::Not(child) => !guard_expr_allows(child, env),
987    }
988}
989
990pub fn guard_option_allows(expr: Option<&GuardExpr>, env: &impl EnvLookup) -> bool {
991    match expr {
992        Some(e) => guard_expr_allows(e, env),
993        None => true,
994    }
995}
996
997impl Guard {
998    /// The one disjointness rule for the entire guard language:
999    /// same namespace, same subject, both valued, different values.
1000    /// Everything else overlaps — different namespaces are
1001    /// independent axes, different subjects are independent
1002    /// variables, and a missing value is a presence claim compatible
1003    /// with any value. No per-domain tables: `os:macos` vs
1004    /// `os:linux`, `env:MODE=dev` vs `env:MODE=prod`, and
1005    /// `bool:true` vs `bool:false` all decide here.
1006    pub fn is_disjoint_from(&self, other: &Self) -> bool {
1007        match (self, other) {
1008            (
1009                Guard::Attr {
1010                    ns: n1,
1011                    key: k1,
1012                    val: Some(v1),
1013                },
1014                Guard::Attr {
1015                    ns: n2,
1016                    key: k2,
1017                    val: Some(v2),
1018                },
1019            ) => n1 == n2 && k1 == k2 && v1 != v2,
1020            _ => false,
1021        }
1022    }
1023}
1024
1025impl GuardExpr {
1026    /// Structural disjointness over the full combinator language.
1027    /// Distribution is exact in both directions (`Or` needs every
1028    /// arm disjoint, `All` needs one), so this proves rather than
1029    /// assumes; anything without a proof overlaps. Linear, no worlds,
1030    /// no enumeration, no cap.
1031    pub fn is_disjoint_from(&self, other: &Self) -> bool {
1032        match (self, other) {
1033            // Complements, either polarity: exact syntactic equality,
1034            // or an unset negation against any positive claim on the
1035            // same subject (`Not([ns:k])` excludes `[ns:k]` and
1036            // `[ns:k=v]` alike — unset is compatible with nothing
1037            // valued). Valued negations (`Not([ns:k=v])`) meet only
1038            // their exact complement: the subject may hold some other
1039            // value.
1040            (x, GuardExpr::Not(inner)) | (GuardExpr::Not(inner), x) => {
1041                x == inner.as_ref() || unset_excludes(x, inner.as_ref())
1042            }
1043            // Leaf predicates delegate to domain algebra.
1044            (GuardExpr::Predicate(p1), GuardExpr::Predicate(p2)) => p1.is_disjoint_from(p2),
1045            // Distribution over `Or`: every arm must exclude `other`.
1046            (GuardExpr::Or(arms), other) | (other, GuardExpr::Or(arms)) => {
1047                arms.iter().all(|arm| arm.is_disjoint_from(other))
1048            }
1049            // Distribution over `All`: one excluding arm suffices.
1050            (GuardExpr::All(arms), other) | (other, GuardExpr::All(arms)) => {
1051                arms.iter().any(|arm| arm.is_disjoint_from(other))
1052            }
1053        }
1054    }
1055}
1056
1057/// Top-level conjuncts of a guard: descend `All` only. The DNF
1058/// expansion below distributes anything nested (`Or`/`Not`)
1059/// exactly; this split is only the entry point.
1060fn conjuncts(expr: &GuardExpr) -> Vec<&GuardExpr> {
1061    match expr {
1062        GuardExpr::All(items) => items.iter().collect(),
1063        single => vec![single],
1064    }
1065}
1066
1067/// Closed value domains for coverage reasoning, driven by the
1068/// parser's accepted values rather than per-value match arms in the
1069/// analyzer: `bool` admits true/false, `os` admits the three known
1070/// systems (`family:unix` already lowers to `any(os:macos,
1071/// os:linux)`, so unix-family coverage is structural). `env` is
1072/// open (any string), so it never exhausts.
1073fn closed_domain_values(ns: Ns, key: Option<&str>) -> Option<&'static [&'static str]> {
1074    match (ns, key) {
1075        (Ns::Bool, None) => Some(&["true", "false"]),
1076        (Ns::Os, None) => Some(&["macos", "linux", "windows"]),
1077        (Ns::Arch, None) => Some(ARCH_VALUES),
1078        _ => None,
1079    }
1080}
1081
1082/// One DNF literal: a predicate or its negation. Negations only
1083/// ever sit on predicates after NNF pushdown.
1084#[derive(Clone)]
1085enum DnfLit {
1086    Pos(Guard),
1087    Neg(Guard),
1088}
1089
1090impl DnfLit {
1091    fn as_expr(&self) -> GuardExpr {
1092        match self {
1093            DnfLit::Pos(guard) => GuardExpr::Predicate(guard.clone()),
1094            DnfLit::Neg(guard) => GuardExpr::Not(Box::new(GuardExpr::Predicate(guard.clone()))),
1095        }
1096    }
1097}
1098
1099/// Cap on DNF disjuncts: guard formulas are a handful of atoms, so
1100/// this never fires on real input. Exceeding it falls back to live
1101/// (satisfiable), the sound direction — a missed proof only risks a
1102/// false coverage error, never a missed one.
1103const MAX_DNF_DISJUNCTS: usize = 64;
1104
1105/// Push one expression into DNF under a polarity: `true` keeps it,
1106/// `false` negates it (De Morgan through `All`/`Or`, double
1107/// negation cancels). Returns the disjunct list, or `None` when the
1108/// cap trips.
1109fn dnf_push(expr: &GuardExpr, polarity: bool, out: &mut Vec<Vec<DnfLit>>) -> bool {
1110    match (expr, polarity) {
1111        (GuardExpr::Predicate(guard), true) => {
1112            for disjunct in out.iter_mut() {
1113                disjunct.push(DnfLit::Pos(guard.clone()));
1114            }
1115            true
1116        }
1117        (GuardExpr::Predicate(guard), false) => {
1118            for disjunct in out.iter_mut() {
1119                disjunct.push(DnfLit::Neg(guard.clone()));
1120            }
1121            true
1122        }
1123        (GuardExpr::All(children), true) | (GuardExpr::Or(children), false) => {
1124            // Conjunction: every child constrains every disjunct.
1125            for child in children {
1126                if !dnf_push(child, polarity, out) {
1127                    return false;
1128                }
1129            }
1130            true
1131        }
1132        (GuardExpr::Or(children), true) | (GuardExpr::All(children), false) => {
1133            // Disjunction: each child forks every live disjunct.
1134            let mut forked = Vec::new();
1135            for disjunct in out.drain(..) {
1136                for child in children {
1137                    let mut branch = vec![disjunct.clone()];
1138                    if !dnf_push(child, polarity, &mut branch) {
1139                        return false;
1140                    }
1141                    forked.extend(branch);
1142                    if forked.len() > MAX_DNF_DISJUNCTS {
1143                        return false;
1144                    }
1145                }
1146            }
1147            *out = forked;
1148            true
1149        }
1150        (GuardExpr::Not(inner), _) => dnf_push(inner, !polarity, out),
1151    }
1152}
1153
1154/// True when one DNF disjunct can fire: no statically-false
1155/// literal, no conflicting pair, and no closed domain exhausted by
1156/// negations.
1157fn disjunct_satisfiable(lits: &[DnfLit]) -> bool {
1158    // A statically-false positive (`bool:false`, or any non-`true`
1159    // which `guard_allows` parses as false) kills the disjunct, as
1160    // does the negation of `bool:true` (which always fires).
1161    for lit in lits {
1162        match lit {
1163            DnfLit::Pos(Guard::Attr {
1164                ns: Ns::Bool, val, ..
1165            }) if val.as_deref() != Some("true") => return false,
1166            DnfLit::Neg(Guard::Attr {
1167                ns: Ns::Bool,
1168                key: None,
1169                val: Some(value),
1170            }) if value == "true" => return false,
1171            _ => {}
1172        }
1173    }
1174    // Any conflicting pair kills the disjunct (complements, leaf
1175    // disjointness, and `Or`/`All` distribution decide inside).
1176    for (index, first) in lits.iter().enumerate() {
1177        for second in &lits[index + 1..] {
1178            if first.as_expr().is_disjoint_from(&second.as_expr()) {
1179                return false;
1180            }
1181        }
1182    }
1183    // A closed domain with every value negated has nowhere left to
1184    // fire (`not(os:macos)`, `not(os:linux)`, `not(os:windows)`
1185    // jointly cover no host).
1186    for lit in lits {
1187        let (ns, key) = match lit {
1188            DnfLit::Neg(Guard::Attr {
1189                ns,
1190                key,
1191                val: Some(_),
1192            }) => (*ns, key.as_deref()),
1193            _ => continue,
1194        };
1195        let Some(domain) = closed_domain_values(ns, key) else {
1196            continue;
1197        };
1198        let exhausted = domain.iter().all(|value| {
1199            lits.iter().any(|other| match other {
1200                DnfLit::Neg(Guard::Attr {
1201                    ns: other_ns,
1202                    key: other_key,
1203                    val: Some(other_val),
1204                }) => *other_ns == ns && other_key.as_deref() == key && other_val == value,
1205                _ => false,
1206            })
1207        });
1208        if exhausted {
1209            return false;
1210        }
1211    }
1212    true
1213}
1214
1215/// True when a conjunction list can never fire: its exact DNF has
1216/// no satisfiable disjunct. This proves rather than assumes —
1217/// pairwise conflicts, `bool` falsehood, and complete closed-domain
1218/// partitions (`os:macos`/`os:linux`/`os:windows`,
1219/// `bool:true`/`bool:false`) all decide here with no per-domain
1220/// tables and no hardcoded platform pairs.
1221fn conjunction_dead(atoms: &[&GuardExpr]) -> bool {
1222    if atoms.is_empty() {
1223        return false;
1224    }
1225    let mut disjuncts = vec![Vec::new()];
1226    for atom in atoms {
1227        if !dnf_push(atom, true, &mut disjuncts) {
1228            return false;
1229        }
1230    }
1231    !disjuncts
1232        .iter()
1233        .any(|disjunct| disjunct_satisfiable(disjunct))
1234}
1235
1236/// True when a guard can fire. Anything not provably dead is live.
1237pub fn guard_satisfiable(expr: &GuardExpr) -> bool {
1238    !conjunction_dead(&conjuncts(expr))
1239}
1240
1241/// True when a guard fires unconditionally: a lone `true`, an
1242/// all-valid conjunction, or the negation of a dead conjunction.
1243pub fn guard_valid(expr: &GuardExpr) -> bool {
1244    match expr {
1245        GuardExpr::Predicate(Guard::Attr {
1246            ns: Ns::Bool,
1247            val: Some(value),
1248            ..
1249        }) => value.as_str() == "true",
1250        GuardExpr::All(items) => items.iter().all(guard_valid),
1251        GuardExpr::Not(inner) => !guard_satisfiable(inner),
1252        _ => false,
1253    }
1254}
1255
1256/// True when two declaration guards can fire together. Absent guards
1257/// are unconditional; anything without a provable conflict overlaps.
1258pub fn guards_overlap(a: Option<&GuardExpr>, b: Option<&GuardExpr>) -> bool {
1259    match (a, b) {
1260        (None, None) => true,
1261        (Some(x), None) | (None, Some(x)) => guard_satisfiable(x),
1262        (Some(x), Some(y)) => {
1263            let mut atoms = conjuncts(x);
1264            atoms.extend(conjuncts(y));
1265            !conjunction_dead(&atoms)
1266        }
1267    }
1268}
1269
1270/// Unset exclusion: `Not([ns:k])` (valueless) is disjoint from any
1271/// positive claim on the same subject, valued or not.
1272fn unset_excludes(x: &GuardExpr, inner: &GuardExpr) -> bool {
1273    match (x, inner) {
1274        (
1275            GuardExpr::Predicate(Guard::Attr {
1276                ns: n2, key: k2, ..
1277            }),
1278            GuardExpr::Predicate(Guard::Attr {
1279                ns: n1,
1280                key: k1,
1281                val: None,
1282            }),
1283        ) => n1 == n2 && k1 == k2,
1284        _ => false,
1285    }
1286}
1287
1288impl fmt::Display for Guard {
1289    /// Bare form without brackets (the step renderer adds them):
1290    /// `[os:linux]` prints `os:linux`, `[env:MODE=dev]`
1291    /// prints `eq(env:MODE, dev)`, `[env:MODE]` prints `env:MODE`.
1292    /// The `eq()` spelling roundtrips through the parser; the rest
1293    /// print verbatim. Roundtrips by construction.
1294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1295        match self {
1296            Guard::Attr {
1297                ns: Ns::Env,
1298                key: Some(var),
1299                val: None,
1300            } => write!(f, "env:{var}"),
1301            Guard::Attr {
1302                ns: Ns::Env,
1303                key: Some(var),
1304                val: Some(want),
1305            } => write!(f, "eq(env:{var}, {want})"),
1306            Guard::Attr {
1307                ns,
1308                key: _,
1309                val: Some(value),
1310            } => write!(f, "{ns}:{value}"),
1311            Guard::Attr { ns, key, val: None } => match key {
1312                Some(subject) => write!(f, "{ns}:{subject}"),
1313                None => write!(f, "{ns}"),
1314            },
1315        }
1316    }
1317}
1318
1319impl fmt::Display for WorkspaceTarget {
1320    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1321        match self {
1322            WorkspaceTarget::Snapshot => write!(f, "SNAPSHOT"),
1323            WorkspaceTarget::Local => write!(f, "LOCAL"),
1324            WorkspaceTarget::Cache { local: false } => write!(f, "CACHE"),
1325            WorkspaceTarget::Cache { local: true } => write!(f, "CACHE --local"),
1326            WorkspaceTarget::System => write!(f, "SYSTEM"),
1327        }
1328    }
1329}
1330
1331impl fmt::Display for Expr {
1332    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1333        match self {
1334            Expr::Literal(v) => write!(f, "{}", v),
1335            Expr::Var { name } => {
1336                write!(f, "{VAR_SIGIL}{}", name)
1337            }
1338            Expr::ConstRef { alias, name } => {
1339                write!(f, "{}", sigil_qualified(alias, name))
1340            }
1341            Expr::Env(key) => write!(f, "env:{}", key),
1342            Expr::KeyPath { base, keys } => {
1343                write!(f, "{VAR_SIGIL}{}", base)?;
1344                for key in keys {
1345                    write!(f, ".{}", key)?;
1346                }
1347                Ok(())
1348            }
1349            Expr::Call { name, args } => {
1350                write!(f, "{}(", name)?;
1351                for (i, arg) in args.iter().enumerate() {
1352                    if i > 0 {
1353                        write!(f, ", ")?;
1354                    }
1355                    write!(f, "{}", arg)?;
1356                }
1357                write!(f, ")")
1358            }
1359            Expr::Inspect { name } => {
1360                write!(f, "{KEYWORD_INSPECT}(${})", name)
1361            }
1362            Expr::List(items) => {
1363                write!(f, "[")?;
1364                for (i, item) in items.iter().enumerate() {
1365                    if i > 0 {
1366                        write!(f, ", ")?;
1367                    }
1368                    write!(f, "{}", item)?;
1369                }
1370                write!(f, "]")
1371            }
1372            Expr::Map(entries) => {
1373                write!(f, "{{")?;
1374                for (i, (key, val)) in entries.iter().enumerate() {
1375                    if i > 0 {
1376                        write!(f, ", ")?;
1377                    }
1378                    write!(f, "\"{}\": {}", key, val)?;
1379                }
1380                write!(f, "}}")
1381            }
1382            Expr::Block(steps) => {
1383                write!(f, "{{ ")?;
1384                for (i, step) in steps.iter().enumerate() {
1385                    if i > 0 {
1386                        write!(f, "; ")?;
1387                    }
1388                    write!(f, "{}", step.kind)?;
1389                }
1390                write!(f, " }}")
1391            }
1392            Expr::Compare { op, left, right } => {
1393                // Parenthesized like `Arithmetic`/`Logical` below, so
1394                // nested comparisons round-trip (`(a == b) == c` parses;
1395                // `a == b == c` does not). Found by expression fuzz.
1396                write!(f, "({} {} {})", left, op, right)
1397            }
1398            Expr::Arithmetic { op, left, right } => {
1399                write!(f, "({} {} {})", left, op, right)
1400            }
1401            Expr::CompiledMath(ops) => {
1402                write!(f, "{}", format_compiled_math(ops))
1403            }
1404            // No expression syntax produces this (bare `LET` is a
1405            // statement): render loudly non-round-trippable so a stray
1406            // use fails at re-parse instead of aliasing a named pipe.
1407            Expr::FreshPipe => write!(f, "<fresh pipe>"),
1408            Expr::UnsignedIntBoundary(n) => write!(f, "{}", n),
1409            Expr::Not(inner) => {
1410                // Parenthesize compound operands so Display round-trips:
1411                // `!(a == b)` must not render as `!a == b` (= `(!a) == b`).
1412                match inner.as_ref() {
1413                    Expr::Compare { .. } | Expr::Arithmetic { .. } | Expr::CompiledMath(_) => {
1414                        write!(f, "!({})", inner)
1415                    }
1416                    _ => write!(f, "!{}", inner),
1417                }
1418            }
1419            Expr::Logical { op, left, right } => {
1420                write!(f, "({} {} {})", left, op, right)
1421            }
1422        }
1423    }
1424}
1425
1426impl fmt::Display for CompareOp {
1427    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1428        match self {
1429            CompareOp::Eq => write!(f, "=="),
1430            CompareOp::Ne => write!(f, "!="),
1431            CompareOp::Lt => write!(f, "<"),
1432            CompareOp::Le => write!(f, "<="),
1433            CompareOp::Gt => write!(f, ">"),
1434            CompareOp::Ge => write!(f, ">="),
1435        }
1436    }
1437}
1438
1439impl fmt::Display for ArithOp {
1440    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1441        match self {
1442            ArithOp::Add => write!(f, "+"),
1443            ArithOp::Sub => write!(f, "-"),
1444            ArithOp::Mul => write!(f, "*"),
1445            ArithOp::Div => write!(f, "/"),
1446        }
1447    }
1448}
1449
1450/// Render flat RPN back to parenthesized infix so `Display` round-trips
1451/// through the parser with identical semantics. Parentheses are emitted
1452/// unconditionally around binary/unary ops; redundant parens parse to the
1453/// same tree, which is what round-trip requires.
1454fn format_compiled_math(ops: &[MathOp]) -> String {
1455    let mut stack: Vec<String> = Vec::new();
1456    for op in ops {
1457        match op {
1458            MathOp::PushConst(v) => stack.push(format!("{}", v)),
1459            MathOp::Load { name } => {
1460                stack.push(format!("{VAR_SIGIL}{}", name));
1461            }
1462            MathOp::LoadConstRef { alias, name } => stack.push(sigil_qualified(alias, name)),
1463            MathOp::LoadEnv(key) => stack.push(format!("env:{}", key)),
1464            MathOp::LoadKeyPath { base, keys } => {
1465                let mut s = format!("{VAR_SIGIL}{}", base);
1466                for key in keys {
1467                    s.push('.');
1468                    s.push_str(key);
1469                }
1470                stack.push(s);
1471            }
1472            MathOp::Call { name, arity } => {
1473                let mut args = Vec::new();
1474                for _ in 0..*arity {
1475                    args.push(stack.pop().unwrap_or_else(|| "<underflow>".to_string()));
1476                }
1477                args.reverse();
1478                stack.push(format!("{}({})", name, args.join(", ")));
1479            }
1480            MathOp::Inspect { name } => {
1481                stack.push(format!("{KEYWORD_INSPECT}({VAR_SIGIL}{})", name));
1482            }
1483            MathOp::Neg => {
1484                let inner = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1485                stack.push(format!("(-{})", inner));
1486            }
1487            MathOp::Add => push_bin(&mut stack, "+"),
1488            MathOp::Sub => push_bin(&mut stack, "-"),
1489            MathOp::Mul => push_bin(&mut stack, "*"),
1490            MathOp::Div => push_bin(&mut stack, "/"),
1491            MathOp::Lt => push_bin(&mut stack, "<"),
1492            MathOp::Le => push_bin(&mut stack, "<="),
1493            MathOp::Gt => push_bin(&mut stack, ">"),
1494            MathOp::Ge => push_bin(&mut stack, ">="),
1495            MathOp::Eq => push_bin(&mut stack, "=="),
1496            MathOp::Ne => push_bin(&mut stack, "!="),
1497        }
1498    }
1499    if stack.len() == 1 {
1500        let mut items = stack;
1501        items.pop().unwrap_or_else(|| "<empty>".to_string())
1502    } else {
1503        stack.join(" ")
1504    }
1505}
1506
1507fn push_bin(stack: &mut Vec<String>, op: &str) {
1508    let right = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1509    let left = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1510    stack.push(format!("({} {} {})", left, op, right));
1511}
1512
1513impl fmt::Display for LogicalOp {
1514    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1515        match self {
1516            LogicalOp::And => write!(f, "&&"),
1517            LogicalOp::Or => write!(f, "||"),
1518        }
1519    }
1520}
1521
1522enum GuardDisplayContext {
1523    Root,
1524    InAnyArg,
1525    InNot,
1526    InAll,
1527}
1528
1529impl GuardExpr {
1530    fn fmt_with_ctx(&self, f: &mut fmt::Formatter<'_>, ctx: GuardDisplayContext) -> fmt::Result {
1531        match self {
1532            GuardExpr::Predicate(guard) => write!(f, "{}", guard),
1533            GuardExpr::All(children) => {
1534                let wrap = matches!(
1535                    ctx,
1536                    GuardDisplayContext::InAnyArg | GuardDisplayContext::InNot
1537                ) && children.len() > 1;
1538                if wrap {
1539                    write!(f, "(")?;
1540                }
1541                for (i, child) in children.iter().enumerate() {
1542                    if i > 0 {
1543                        write!(f, ", ")?;
1544                    }
1545                    child.fmt_with_ctx(f, GuardDisplayContext::InAll)?;
1546                }
1547                if wrap {
1548                    write!(f, ")")?;
1549                }
1550                Ok(())
1551            }
1552            GuardExpr::Or(children) => {
1553                write!(f, "any(")?;
1554                for (i, child) in children.iter().enumerate() {
1555                    if i > 0 {
1556                        write!(f, ", ")?;
1557                    }
1558                    child.fmt_with_ctx(f, GuardDisplayContext::InAnyArg)?;
1559                }
1560                write!(f, ")")
1561            }
1562            GuardExpr::Not(child) => {
1563                write!(f, "not(")?;
1564                child.fmt_with_ctx(f, GuardDisplayContext::InNot)?;
1565                write!(f, ")")
1566            }
1567        }
1568    }
1569}
1570
1571impl fmt::Display for GuardExpr {
1572    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1573        self.fmt_with_ctx(f, GuardDisplayContext::Root)
1574    }
1575}
1576
1577impl fmt::Display for Step {
1578    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1579        if let Some(expr) = &self.guard {
1580            write!(f, "[{}] ", expr)?;
1581        }
1582        write!(f, "{}", self.kind)
1583    }
1584}
1585
1586#[cfg(test)]
1587mod tests {
1588    use super::*;
1589    /// Bidirectional lock between the token backend and the keyword registry.
1590    /// Fails CI if a statement keyword is renamed or deleted on either side.
1591    /// Every [`STRUCTURAL_KEYWORDS`] entry must be claimed by the backend:
1592    /// parsing it bare either succeeds (operand-less forms like `BREAK`)
1593    /// or fails structurally — never as a bare `unknown command` (issue
1594    /// #143). Conversely every head the element loop treats structurally
1595    /// must be registered here or in the command table.
1596    #[test]
1597    fn statement_keywords_match_backend() {
1598        // Transparency lock: for a bare keyword the backend must never
1599        // invent a failure of its own. Either it claims the shape
1600        // (`BREAK`/`CONTINUE`/operand-less `RETURN` lower directly) or
1601        // it routes straight to lowering and reports lowering's own
1602        // kind (production lowering, which knows every structural
1603        // head). A backend hard-fail shadowing lowering would fire
1604        // here; kind drift between the two would fire too.
1605        for kw in STRUCTURAL_KEYWORDS {
1606            let via_backend = crate::parse_script(kw, crate::commands::lower_command);
1607            let via_lowering =
1608                crate::commands::lower_command(kw, Vec::new()).map(|kind| crate::Step {
1609                    guard: None,
1610                    kind,
1611                    scope_enter: 0,
1612                    scope_exit: 0,
1613                    line: 0,
1614                    col: 0,
1615                });
1616            match (via_backend, via_lowering) {
1617                (Ok(_), _) => {}
1618                (Err(a), Err(b)) => {
1619                    assert_eq!(
1620                        a.kind(),
1621                        b.kind(),
1622                        "backend kind drift for bare keyword {kw}: {a} vs {b}"
1623                    );
1624                }
1625                (Err(a), Ok(_)) => {
1626                    panic!("backend rejects bare keyword {kw} that lowering accepts: {a}")
1627                }
1628            }
1629        }
1630        // Heads the element loop dispatches structurally (not through
1631        // generic lowering) must stay registered; update this list with
1632        // the dispatch when adding a head.
1633        for head in [
1634            "LET",
1635            "CONST",
1636            "RETURN",
1637            "BREAK",
1638            "CONTINUE",
1639            "IF",
1640            "FOR",
1641            "WHILE",
1642            "FUNC",
1643            "REMOTE",
1644            "INHERIT_ENV",
1645            "WITH_IO",
1646            "ASYNC",
1647            "TIMEOUT",
1648            "ISOLATED",
1649            "AWAIT",
1650            "CANCEL",
1651            "RUN",
1652            "IMPORT",
1653            "EXPORT",
1654            "TYPE",
1655        ] {
1656            assert!(
1657                STRUCTURAL_KEYWORDS.contains(&head)
1658                    || crate::all_metadata().iter().any(|m| m.name == head),
1659                "structural head {head} is not registered"
1660            );
1661        }
1662    }
1663
1664    /// Category convention lock: every multi-word command groups under a
1665    /// registered `COMMAND_CATEGORIES` prefix. Adding a command under a
1666    /// new category fails here until the prefix registers (one line).
1667    #[test]
1668    fn command_names_group_by_category() {
1669        for command in COMMANDS {
1670            let name = command.as_str();
1671            let Some((prefix, _)) = name.split_once('_') else {
1672                continue;
1673            };
1674            assert!(
1675                COMMAND_CATEGORIES.contains(&prefix),
1676                "command {name} introduces unregistered category {prefix}; add it to COMMAND_CATEGORIES"
1677            );
1678        }
1679    }
1680
1681    /// Registry/parse parity: every indexed command name must resolve
1682    /// through `Command::parse` (or be a structural keyword). The
1683    /// token-stream splitter consults `parse`, never the metadata
1684    /// table, so a registry-only command glues onto the previous line
1685    /// and its arguments misparse as the neighbor's. Structural names
1686    /// take the keyword path instead, and doc-only entries (`in_index:
1687    /// false`, like `MUTATION`) are not parseable heads by design.
1688    #[test]
1689    fn registry_commands_all_parse() {
1690        for meta in crate::all_metadata() {
1691            if !meta.in_index || STRUCTURAL_KEYWORDS.contains(&meta.name) {
1692                continue;
1693            }
1694            assert!(
1695                Command::parse(meta.name).is_some(),
1696                "registry command {} has no Command::parse arm",
1697                meta.name
1698            );
1699        }
1700    }
1701
1702    /// Definition spans ride the shared transport type: `TYPE`/`FUNC`
1703    /// steps expose their stamped line/col as a [`Span`], and
1704    /// `defined_symbol` names the symbol. Everything else defines
1705    /// nothing. Unknown positions stay unknown (`line == 0`).
1706    #[test]
1707    fn definition_spans_cover_type_and_func() {
1708        let alias = Step {
1709            guard: None,
1710            kind: StepKind::TypeAlias {
1711                name: "EMP".to_string(),
1712                target: "MAP<n: STRING>".to_string(),
1713            },
1714            scope_enter: 0,
1715            scope_exit: 0,
1716            line: 3,
1717            col: 5,
1718        };
1719        let (name, span) = alias.defined_symbol().expect("alias defines");
1720        assert_eq!(name, "EMP");
1721        assert_eq!(span.line, 3);
1722        assert_eq!(span.col_start, Some(5));
1723
1724        let func = Step {
1725            guard: None,
1726            kind: StepKind::FuncDef {
1727                name: "F".to_string(),
1728                params: Vec::new(),
1729                return_type: "VOID".to_string(),
1730                is_async: false,
1731                body: Vec::new(),
1732                docs: None,
1733            },
1734            scope_enter: 0,
1735            scope_exit: 0,
1736            line: 7,
1737            col: 1,
1738        };
1739        let (name, span) = func.defined_symbol().expect("func defines");
1740        assert_eq!(name, "F");
1741        assert_eq!(span.line, 7);
1742
1743        let plain = Step {
1744            guard: None,
1745            kind: StepKind::Break,
1746            scope_enter: 0,
1747            scope_exit: 0,
1748            line: 9,
1749            col: 1,
1750        };
1751        assert!(plain.defined_symbol().is_none());
1752
1753        let unknown = Step {
1754            guard: None,
1755            kind: StepKind::Break,
1756            scope_enter: 0,
1757            scope_exit: 0,
1758            line: 0,
1759            col: 0,
1760        };
1761        assert_eq!(unknown.span().line, 0);
1762    }
1763
1764    /// End to end: parsed `TYPE`/`FUNC` steps carry definition spans
1765    /// from stamping, so future symbol tables read positions off the
1766    /// AST instead of re-lexing.
1767    #[test]
1768    fn parsed_definitions_carry_spans() {
1769        let steps = crate::parse_script(
1770            indoc::indoc! {r#"
1771                TYPE EMP = MAP<n: STRING>
1772                FUNC F(): VOID {
1773                RETURN
1774                }
1775            "#},
1776            crate::commands::lower_command,
1777        )
1778        .expect("definitions parse");
1779        let mut names: Vec<(&str, usize)> = steps
1780            .iter()
1781            .filter_map(|s| s.defined_symbol().map(|(n, span)| (n, span.line)))
1782            .collect();
1783        names.sort();
1784        assert_eq!(names, vec![("EMP", 1), ("F", 2)]);
1785    }
1786}
1787
1788#[cfg(test)]
1789mod guard_analysis_tests {
1790    use super::*;
1791
1792    fn attr(ns: Ns, key: Option<&str>, val: Option<&str>) -> GuardExpr {
1793        GuardExpr::Predicate(Guard::Attr {
1794            ns,
1795            key: key.map(str::to_string),
1796            val: val.map(str::to_string),
1797        })
1798    }
1799
1800    fn os(value: &str) -> GuardExpr {
1801        attr(Ns::Os, None, Some(value))
1802    }
1803
1804    fn arch(value: &str) -> GuardExpr {
1805        attr(Ns::Arch, None, Some(value))
1806    }
1807
1808    /// The `family:unix` parse alias, desugared exactly as the
1809    /// parser lowers it.
1810    fn unix() -> GuardExpr {
1811        GuardExpr::Or(vec![os("macos"), os("linux")])
1812    }
1813
1814    fn windows() -> GuardExpr {
1815        os("windows")
1816    }
1817
1818    fn env_eq(var: &str, value: &str) -> GuardExpr {
1819        attr(Ns::Env, Some(var), Some(value))
1820    }
1821
1822    fn not(expr: GuardExpr) -> GuardExpr {
1823        GuardExpr::Not(Box::new(expr))
1824    }
1825
1826    /// Closed domains exhaust: negating every `os:` value (or both
1827    /// `bool:` values) covers no host. Open domains (`env:`) never
1828    /// exhaust — some unmentioned value may hold.
1829    #[test]
1830    fn partition_negations_are_jointly_dead() {
1831        let os_exhausted = GuardExpr::All(vec![not(os("macos")), not(os("linux")), not(windows())]);
1832        assert!(
1833            !guard_satisfiable(&os_exhausted),
1834            "no host is outside `macos`/`linux`/`windows`"
1835        );
1836        // Partial negations stay live.
1837        let os_partial = GuardExpr::All(vec![not(os("macos")), not(os("linux"))]);
1838        assert!(guard_satisfiable(&os_partial), "`windows` is still open");
1839        // The bool domain exhausts the same way.
1840        let bool_exhausted = GuardExpr::All(vec![
1841            not(attr(Ns::Bool, None, Some("true"))),
1842            not(attr(Ns::Bool, None, Some("false"))),
1843        ]);
1844        assert!(!guard_satisfiable(&bool_exhausted));
1845        // Open env domains never exhaust.
1846        let env_open = GuardExpr::All(vec![
1847            not(env_eq("MODE", "dev")),
1848            not(env_eq("MODE", "prod")),
1849        ]);
1850        assert!(guard_satisfiable(&env_open), "MODE may hold a third value");
1851        // Single negations are always live.
1852        assert!(guard_satisfiable(&not(unix())));
1853    }
1854
1855    /// The desugared `unix` alias behaves as a disjunction: it meets
1856    /// `windows` nowhere and covers `macos`/`linux` deployment reads.
1857    #[test]
1858    fn unix_alias_is_os_disjunction() {
1859        assert!(!guards_overlap(Some(&unix()), Some(&windows())));
1860        assert!(guards_overlap(Some(&unix()), Some(&os("macos"))));
1861        // Coverage through the alias: `unix` + `windows` declarations
1862        // cover every host, so their joint negation is dead.
1863        let covered = GuardExpr::All(vec![GuardExpr::Not(Box::new(unix())), not(windows())]);
1864        assert!(!guard_satisfiable(&covered));
1865    }
1866
1867    /// `arch:` decides by value like every namespace; it overlaps
1868    /// `os:` (independent axes: an aarch64 mac exists). Negating
1869    /// the whole closed `ARCH_VALUES` domain covers no host.
1870    #[test]
1871    fn arch_guards_decide_by_value() {
1872        assert!(!guards_overlap(
1873            Some(&arch("x86_64")),
1874            Some(&arch("aarch64"))
1875        ));
1876        assert!(guards_overlap(Some(&arch("x86_64")), Some(&arch("x86_64"))));
1877        assert!(guards_overlap(Some(&arch("aarch64")), Some(&os("macos"))));
1878        let exhausted = GuardExpr::All(ARCH_VALUES.iter().map(|value| not(arch(value))).collect());
1879        assert!(!guard_satisfiable(&exhausted));
1880        // Runtime anchor: this host's own architecture fires here.
1881        let host = attr(Ns::Arch, None, Some(ARCH_TARGET));
1882        assert!(guard_expr_allows(&host, &HashMap::new()));
1883    }
1884
1885    /// The full platform matrix, asserted exhaustively. All three
1886    /// `os:` values are pairwise disjoint; identical values
1887    /// overlap.
1888    #[test]
1889    fn platform_overlap_matrix_is_exhaustive() {
1890        let cases = [
1891            ("macos", "macos", true),
1892            ("macos", "linux", false),
1893            ("macos", "windows", false),
1894            ("linux", "linux", true),
1895            ("linux", "windows", false),
1896            ("windows", "windows", true),
1897        ];
1898        for (v1, v2, expected) in cases {
1899            let left = os(v1);
1900            let right = os(v2);
1901            assert_eq!(
1902                guards_overlap(Some(&left), Some(&right)),
1903                expected,
1904                "os:{v1} vs os:{v2}"
1905            );
1906        }
1907    }
1908
1909    /// Runtime anchor, portable across CI hosts: `os:macos` and
1910    /// `os:windows` never co-fire on the machine running the test.
1911    #[test]
1912    fn disjoint_pairs_never_cofire_here() {
1913        let macos = os("macos");
1914        let holds = |expr: &GuardExpr| guard_expr_allows(expr, &HashMap::new());
1915        assert!(
1916            !(holds(&macos) && holds(&windows())),
1917            "os:macos and os:windows co-fired"
1918        );
1919    }
1920
1921    #[test]
1922    fn overlap_follows_namespace_semantics() {
1923        // Same namespace, distinct values: disjoint.
1924        assert!(!guards_overlap(Some(&windows()), Some(&unix())));
1925        assert!(!guards_overlap(Some(&os("macos")), Some(&os("linux"))));
1926        // Absent guards are unconditional.
1927        assert!(guards_overlap(None, Some(&windows())));
1928        assert!(guards_overlap(None, None));
1929        // Unsatisfiable conjunctions overlap nothing.
1930        let dead = GuardExpr::All(vec![os("macos"), windows()]);
1931        assert!(!guard_satisfiable(&dead));
1932        assert!(!guards_overlap(Some(&dead), Some(&os("macos"))));
1933        assert!(guard_valid(&GuardExpr::Predicate(Guard::Attr {
1934            ns: Ns::Bool,
1935            key: None,
1936            val: Some("true".to_string()),
1937        })));
1938        assert!(!guard_valid(&unix()));
1939    }
1940
1941    #[test]
1942    fn env_value_conflicts_decide_without_enumeration() {
1943        let fast = env_eq("MODE", "fast");
1944        let slow = env_eq("MODE", "slow");
1945        assert!(
1946            !guards_overlap(Some(&fast), Some(&slow)),
1947            "same key distinct values are disjoint"
1948        );
1949        let also_fast = env_eq("MODE", "fast");
1950        assert!(guards_overlap(Some(&fast), Some(&also_fast)));
1951        // Bare presence overlaps any value on the same key.
1952        let bare = attr(Ns::Env, Some("MODE"), None);
1953        assert!(guards_overlap(Some(&bare), Some(&fast)));
1954    }
1955}
1956
1957#[cfg(test)]
1958mod guard_algebra_tests {
1959    use super::*;
1960
1961    fn os(value: &str) -> GuardExpr {
1962        GuardExpr::Predicate(Guard::Attr {
1963            ns: Ns::Os,
1964            key: None,
1965            val: Some(value.to_string()),
1966        })
1967    }
1968
1969    #[test]
1970    fn or_distributes_over_disjointness() {
1971        fn env_eq(var: &str, value: &str) -> GuardExpr {
1972            GuardExpr::Predicate(Guard::Attr {
1973                ns: Ns::Env,
1974                key: Some(var.to_string()),
1975                val: Some(value.to_string()),
1976            })
1977        }
1978        // Every arm must exclude `other`: one overlapping arm keeps
1979        // the whole disjunction live.
1980        let mixed = GuardExpr::Or(vec![env_eq("MODE", "dev"), env_eq("MODE", "prod")]);
1981        assert!(!mixed.is_disjoint_from(&env_eq("MODE", "dev")));
1982        // All arms disjoint: the disjunction is dead against it.
1983        assert!(mixed.is_disjoint_from(&env_eq("MODE", "test")));
1984        // Cross-namespace arms never exclude: different axes overlap.
1985        let cross = GuardExpr::Or(vec![env_eq("MODE", "dev")]);
1986        let platform = os("windows");
1987        assert!(!cross.is_disjoint_from(&platform));
1988    }
1989
1990    #[test]
1991    fn all_distributes_over_disjointness() {
1992        let stacked = GuardExpr::All(vec![
1993            os("macos"),
1994            GuardExpr::Or(vec![os("macos"), os("linux")]),
1995            os("windows"),
1996        ]);
1997        assert!(stacked.is_disjoint_from(&os("macos")));
1998        // One live arm keeps the conjunction overlapping: neither
1999        // arm excludes macos here.
2000        let live = GuardExpr::All(vec![
2001            os("macos"),
2002            GuardExpr::Predicate(Guard::Attr {
2003                ns: Ns::Env,
2004                key: Some("MODE".to_string()),
2005                val: Some("dev".to_string()),
2006            }),
2007        ]);
2008        assert!(!live.is_disjoint_from(&os("macos")));
2009    }
2010
2011    #[test]
2012    fn negation_is_structural_not_syntactic() {
2013        let not_win = GuardExpr::Not(Box::new(os("windows")));
2014        assert!(not_win.is_disjoint_from(&os("windows")));
2015        assert!(os("windows").is_disjoint_from(&not_win));
2016        assert!(!not_win.is_disjoint_from(&os("macos")));
2017    }
2018}