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