Skip to main content

oxdock_parser/
ast.rs

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