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
775#[derive(Debug, Clone, Eq, PartialEq)]
776pub enum WorkspaceTarget {
777    Snapshot,
778    Local,
779    Cache { local: bool },
780    System,
781}
782
783pub trait EnvLookup {
784    fn get_env(&self, key: &str) -> Option<&str>;
785}
786
787impl EnvLookup for HashMap<String, String> {
788    fn get_env(&self, key: &str) -> Option<&str> {
789        self.get(key).map(|s| s.as_str())
790    }
791}
792
793impl EnvLookup for Arc<HashMap<String, String>> {
794    fn get_env(&self, key: &str) -> Option<&str> {
795        (**self).get_env(key)
796    }
797}
798
799pub fn guard_allows(guard: &Guard, env: &impl EnvLookup) -> bool {
800    let Guard::Attr { ns, key, val } = guard;
801    match ns {
802        Ns::Os => match val.as_deref() {
803            Some("macos") => platform_is_macos(),
804            Some("linux") => platform_is_linux(),
805            Some("windows") => platform_is_windows(),
806            _ => false,
807        },
808        Ns::Arch => match val.as_deref() {
809            Some(want) => ARCH_TARGET == want,
810            None => false,
811        },
812        Ns::Bool => val
813            .as_deref()
814            .map(|v| v.parse::<bool>().unwrap_or(false))
815            .unwrap_or(false),
816        Ns::Env => match key.as_deref() {
817            Some(var) => match val {
818                None => env.get_env(var).map(|v| !v.is_empty()).unwrap_or(false),
819                Some(want) => env
820                    .get_env(var)
821                    .map(|v| v == want.as_str())
822                    .unwrap_or(false),
823            },
824            // Parser always supplies the variable; defensive false.
825            None => false,
826        },
827    }
828}
829
830/// One `cfg!` per platform fact, each beside its namespace arm
831/// above. `#[allow]` lives on the helpers, not the dispatch.
832#[allow(clippy::disallowed_macros)]
833fn platform_is_windows() -> bool {
834    cfg!(windows)
835}
836
837/// See `platform_is_windows`.
838#[allow(clippy::disallowed_macros)]
839fn platform_is_macos() -> bool {
840    cfg!(target_os = "macos")
841}
842
843/// See `platform_is_windows`.
844#[allow(clippy::disallowed_macros)]
845fn platform_is_linux() -> bool {
846    cfg!(target_os = "linux")
847}
848
849/// Host target architecture behind `arch:` guards. A plain const
850/// read alongside the platform helpers above.
851const ARCH_TARGET: &str = std::env::consts::ARCH;
852
853pub fn guard_expr_allows(expr: &GuardExpr, env: &impl EnvLookup) -> bool {
854    match expr {
855        GuardExpr::Predicate(guard) => guard_allows(guard, env),
856        GuardExpr::All(children) => children.iter().all(|g| guard_expr_allows(g, env)),
857        GuardExpr::Or(children) => children.iter().any(|g| guard_expr_allows(g, env)),
858        GuardExpr::Not(child) => !guard_expr_allows(child, env),
859    }
860}
861
862pub fn guard_option_allows(expr: Option<&GuardExpr>, env: &impl EnvLookup) -> bool {
863    match expr {
864        Some(e) => guard_expr_allows(e, env),
865        None => true,
866    }
867}
868
869impl Guard {
870    /// The one disjointness rule for the entire guard language:
871    /// same namespace, same subject, both valued, different values.
872    /// Everything else overlaps — different namespaces are
873    /// independent axes, different subjects are independent
874    /// variables, and a missing value is a presence claim compatible
875    /// with any value. No per-domain tables: `os:macos` vs
876    /// `os:linux`, `env:MODE=dev` vs `env:MODE=prod`, and
877    /// `bool:true` vs `bool:false` all decide here.
878    pub fn is_disjoint_from(&self, other: &Self) -> bool {
879        match (self, other) {
880            (
881                Guard::Attr {
882                    ns: n1,
883                    key: k1,
884                    val: Some(v1),
885                },
886                Guard::Attr {
887                    ns: n2,
888                    key: k2,
889                    val: Some(v2),
890                },
891            ) => n1 == n2 && k1 == k2 && v1 != v2,
892            _ => false,
893        }
894    }
895}
896
897impl GuardExpr {
898    /// Structural disjointness over the full combinator language.
899    /// Distribution is exact in both directions (`Or` needs every
900    /// arm disjoint, `All` needs one), so this proves rather than
901    /// assumes; anything without a proof overlaps. Linear, no worlds,
902    /// no enumeration, no cap.
903    pub fn is_disjoint_from(&self, other: &Self) -> bool {
904        match (self, other) {
905            // Complements, either polarity: exact syntactic equality,
906            // or an unset negation against any positive claim on the
907            // same subject (`Not([ns:k])` excludes `[ns:k]` and
908            // `[ns:k=v]` alike — unset is compatible with nothing
909            // valued). Valued negations (`Not([ns:k=v])`) meet only
910            // their exact complement: the subject may hold some other
911            // value.
912            (x, GuardExpr::Not(inner)) | (GuardExpr::Not(inner), x) => {
913                x == inner.as_ref() || unset_excludes(x, inner.as_ref())
914            }
915            // Leaf predicates delegate to domain algebra.
916            (GuardExpr::Predicate(p1), GuardExpr::Predicate(p2)) => p1.is_disjoint_from(p2),
917            // Distribution over `Or`: every arm must exclude `other`.
918            (GuardExpr::Or(arms), other) | (other, GuardExpr::Or(arms)) => {
919                arms.iter().all(|arm| arm.is_disjoint_from(other))
920            }
921            // Distribution over `All`: one excluding arm suffices.
922            (GuardExpr::All(arms), other) | (other, GuardExpr::All(arms)) => {
923                arms.iter().any(|arm| arm.is_disjoint_from(other))
924            }
925        }
926    }
927}
928
929/// Top-level conjuncts of a guard: descend `All` only. The DNF
930/// expansion below distributes anything nested (`Or`/`Not`)
931/// exactly; this split is only the entry point.
932fn conjuncts(expr: &GuardExpr) -> Vec<&GuardExpr> {
933    match expr {
934        GuardExpr::All(items) => items.iter().collect(),
935        single => vec![single],
936    }
937}
938
939/// Closed value domains for coverage reasoning, driven by the
940/// parser's accepted values rather than per-value match arms in the
941/// analyzer: `bool` admits true/false, `os` admits the three known
942/// systems (`family:unix` already lowers to `any(os:macos,
943/// os:linux)`, so unix-family coverage is structural). `env` is
944/// open (any string), so it never exhausts.
945fn closed_domain_values(ns: Ns, key: Option<&str>) -> Option<&'static [&'static str]> {
946    match (ns, key) {
947        (Ns::Bool, None) => Some(&["true", "false"]),
948        (Ns::Os, None) => Some(&["macos", "linux", "windows"]),
949        (Ns::Arch, None) => Some(ARCH_VALUES),
950        _ => None,
951    }
952}
953
954/// One DNF literal: a predicate or its negation. Negations only
955/// ever sit on predicates after NNF pushdown.
956#[derive(Clone)]
957enum DnfLit {
958    Pos(Guard),
959    Neg(Guard),
960}
961
962impl DnfLit {
963    fn as_expr(&self) -> GuardExpr {
964        match self {
965            DnfLit::Pos(guard) => GuardExpr::Predicate(guard.clone()),
966            DnfLit::Neg(guard) => GuardExpr::Not(Box::new(GuardExpr::Predicate(guard.clone()))),
967        }
968    }
969}
970
971/// Cap on DNF disjuncts: guard formulas are a handful of atoms, so
972/// this never fires on real input. Exceeding it falls back to live
973/// (satisfiable), the sound direction — a missed proof only risks a
974/// false coverage error, never a missed one.
975const MAX_DNF_DISJUNCTS: usize = 64;
976
977/// Push one expression into DNF under a polarity: `true` keeps it,
978/// `false` negates it (De Morgan through `All`/`Or`, double
979/// negation cancels). Returns the disjunct list, or `None` when the
980/// cap trips.
981fn dnf_push(expr: &GuardExpr, polarity: bool, out: &mut Vec<Vec<DnfLit>>) -> bool {
982    match (expr, polarity) {
983        (GuardExpr::Predicate(guard), true) => {
984            for disjunct in out.iter_mut() {
985                disjunct.push(DnfLit::Pos(guard.clone()));
986            }
987            true
988        }
989        (GuardExpr::Predicate(guard), false) => {
990            for disjunct in out.iter_mut() {
991                disjunct.push(DnfLit::Neg(guard.clone()));
992            }
993            true
994        }
995        (GuardExpr::All(children), true) | (GuardExpr::Or(children), false) => {
996            // Conjunction: every child constrains every disjunct.
997            for child in children {
998                if !dnf_push(child, polarity, out) {
999                    return false;
1000                }
1001            }
1002            true
1003        }
1004        (GuardExpr::Or(children), true) | (GuardExpr::All(children), false) => {
1005            // Disjunction: each child forks every live disjunct.
1006            let mut forked = Vec::new();
1007            for disjunct in out.drain(..) {
1008                for child in children {
1009                    let mut branch = vec![disjunct.clone()];
1010                    if !dnf_push(child, polarity, &mut branch) {
1011                        return false;
1012                    }
1013                    forked.extend(branch);
1014                    if forked.len() > MAX_DNF_DISJUNCTS {
1015                        return false;
1016                    }
1017                }
1018            }
1019            *out = forked;
1020            true
1021        }
1022        (GuardExpr::Not(inner), _) => dnf_push(inner, !polarity, out),
1023    }
1024}
1025
1026/// True when one DNF disjunct can fire: no statically-false
1027/// literal, no conflicting pair, and no closed domain exhausted by
1028/// negations.
1029fn disjunct_satisfiable(lits: &[DnfLit]) -> bool {
1030    // A statically-false positive (`bool:false`, or any non-`true`
1031    // which `guard_allows` parses as false) kills the disjunct, as
1032    // does the negation of `bool:true` (which always fires).
1033    for lit in lits {
1034        match lit {
1035            DnfLit::Pos(Guard::Attr {
1036                ns: Ns::Bool, val, ..
1037            }) if val.as_deref() != Some("true") => return false,
1038            DnfLit::Neg(Guard::Attr {
1039                ns: Ns::Bool,
1040                key: None,
1041                val: Some(value),
1042            }) if value == "true" => return false,
1043            _ => {}
1044        }
1045    }
1046    // Any conflicting pair kills the disjunct (complements, leaf
1047    // disjointness, and `Or`/`All` distribution decide inside).
1048    for (index, first) in lits.iter().enumerate() {
1049        for second in &lits[index + 1..] {
1050            if first.as_expr().is_disjoint_from(&second.as_expr()) {
1051                return false;
1052            }
1053        }
1054    }
1055    // A closed domain with every value negated has nowhere left to
1056    // fire (`not(os:macos)`, `not(os:linux)`, `not(os:windows)`
1057    // jointly cover no host).
1058    for lit in lits {
1059        let (ns, key) = match lit {
1060            DnfLit::Neg(Guard::Attr {
1061                ns,
1062                key,
1063                val: Some(_),
1064            }) => (*ns, key.as_deref()),
1065            _ => continue,
1066        };
1067        let Some(domain) = closed_domain_values(ns, key) else {
1068            continue;
1069        };
1070        let exhausted = domain.iter().all(|value| {
1071            lits.iter().any(|other| match other {
1072                DnfLit::Neg(Guard::Attr {
1073                    ns: other_ns,
1074                    key: other_key,
1075                    val: Some(other_val),
1076                }) => *other_ns == ns && other_key.as_deref() == key && other_val == value,
1077                _ => false,
1078            })
1079        });
1080        if exhausted {
1081            return false;
1082        }
1083    }
1084    true
1085}
1086
1087/// True when a conjunction list can never fire: its exact DNF has
1088/// no satisfiable disjunct. This proves rather than assumes —
1089/// pairwise conflicts, `bool` falsehood, and complete closed-domain
1090/// partitions (`os:macos`/`os:linux`/`os:windows`,
1091/// `bool:true`/`bool:false`) all decide here with no per-domain
1092/// tables and no hardcoded platform pairs.
1093fn conjunction_dead(atoms: &[&GuardExpr]) -> bool {
1094    if atoms.is_empty() {
1095        return false;
1096    }
1097    let mut disjuncts = vec![Vec::new()];
1098    for atom in atoms {
1099        if !dnf_push(atom, true, &mut disjuncts) {
1100            return false;
1101        }
1102    }
1103    !disjuncts
1104        .iter()
1105        .any(|disjunct| disjunct_satisfiable(disjunct))
1106}
1107
1108/// True when a guard can fire. Anything not provably dead is live.
1109pub fn guard_satisfiable(expr: &GuardExpr) -> bool {
1110    !conjunction_dead(&conjuncts(expr))
1111}
1112
1113/// True when a guard fires unconditionally: a lone `true`, an
1114/// all-valid conjunction, or the negation of a dead conjunction.
1115pub fn guard_valid(expr: &GuardExpr) -> bool {
1116    match expr {
1117        GuardExpr::Predicate(Guard::Attr {
1118            ns: Ns::Bool,
1119            val: Some(value),
1120            ..
1121        }) => value.as_str() == "true",
1122        GuardExpr::All(items) => items.iter().all(guard_valid),
1123        GuardExpr::Not(inner) => !guard_satisfiable(inner),
1124        _ => false,
1125    }
1126}
1127
1128/// True when two declaration guards can fire together. Absent guards
1129/// are unconditional; anything without a provable conflict overlaps.
1130pub fn guards_overlap(a: Option<&GuardExpr>, b: Option<&GuardExpr>) -> bool {
1131    match (a, b) {
1132        (None, None) => true,
1133        (Some(x), None) | (None, Some(x)) => guard_satisfiable(x),
1134        (Some(x), Some(y)) => {
1135            let mut atoms = conjuncts(x);
1136            atoms.extend(conjuncts(y));
1137            !conjunction_dead(&atoms)
1138        }
1139    }
1140}
1141
1142/// Unset exclusion: `Not([ns:k])` (valueless) is disjoint from any
1143/// positive claim on the same subject, valued or not.
1144fn unset_excludes(x: &GuardExpr, inner: &GuardExpr) -> bool {
1145    match (x, inner) {
1146        (
1147            GuardExpr::Predicate(Guard::Attr {
1148                ns: n2, key: k2, ..
1149            }),
1150            GuardExpr::Predicate(Guard::Attr {
1151                ns: n1,
1152                key: k1,
1153                val: None,
1154            }),
1155        ) => n1 == n2 && k1 == k2,
1156        _ => false,
1157    }
1158}
1159
1160impl fmt::Display for Guard {
1161    /// Bare form without brackets (the step renderer adds them):
1162    /// `[os:linux]` prints `os:linux`, `[env:MODE=dev]`
1163    /// prints `eq(env:MODE, dev)`, `[env:MODE]` prints `env:MODE`.
1164    /// The `eq()` spelling roundtrips through the parser; the rest
1165    /// print verbatim. Roundtrips by construction.
1166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1167        match self {
1168            Guard::Attr {
1169                ns: Ns::Env,
1170                key: Some(var),
1171                val: None,
1172            } => write!(f, "env:{var}"),
1173            Guard::Attr {
1174                ns: Ns::Env,
1175                key: Some(var),
1176                val: Some(want),
1177            } => write!(f, "eq(env:{var}, {want})"),
1178            Guard::Attr {
1179                ns,
1180                key: _,
1181                val: Some(value),
1182            } => write!(f, "{ns}:{value}"),
1183            Guard::Attr { ns, key, val: None } => match key {
1184                Some(subject) => write!(f, "{ns}:{subject}"),
1185                None => write!(f, "{ns}"),
1186            },
1187        }
1188    }
1189}
1190
1191impl fmt::Display for WorkspaceTarget {
1192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1193        match self {
1194            WorkspaceTarget::Snapshot => write!(f, "SNAPSHOT"),
1195            WorkspaceTarget::Local => write!(f, "LOCAL"),
1196            WorkspaceTarget::Cache { local: false } => write!(f, "CACHE"),
1197            WorkspaceTarget::Cache { local: true } => write!(f, "CACHE --local"),
1198            WorkspaceTarget::System => write!(f, "SYSTEM"),
1199        }
1200    }
1201}
1202
1203impl fmt::Display for Expr {
1204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1205        match self {
1206            Expr::Literal(v) => write!(f, "{}", v),
1207            Expr::Var(name) => write!(f, "${}", name),
1208            Expr::Env(key) => write!(f, "env:{}", key),
1209            Expr::KeyPath { base, keys } => {
1210                write!(f, "${}", base)?;
1211                for key in keys {
1212                    write!(f, ".{}", key)?;
1213                }
1214                Ok(())
1215            }
1216            Expr::Call { name, args } => {
1217                write!(f, "{}(", name)?;
1218                for (i, arg) in args.iter().enumerate() {
1219                    if i > 0 {
1220                        write!(f, ", ")?;
1221                    }
1222                    write!(f, "{}", arg)?;
1223                }
1224                write!(f, ")")
1225            }
1226            Expr::Inspect(var) => write!(f, "INSPECT(${})", var),
1227            Expr::List(items) => {
1228                write!(f, "[")?;
1229                for (i, item) in items.iter().enumerate() {
1230                    if i > 0 {
1231                        write!(f, ", ")?;
1232                    }
1233                    write!(f, "{}", item)?;
1234                }
1235                write!(f, "]")
1236            }
1237            Expr::Map(entries) => {
1238                write!(f, "{{")?;
1239                for (i, (key, val)) in entries.iter().enumerate() {
1240                    if i > 0 {
1241                        write!(f, ", ")?;
1242                    }
1243                    write!(f, "\"{}\": {}", key, val)?;
1244                }
1245                write!(f, "}}")
1246            }
1247            Expr::Block(steps) => {
1248                write!(f, "{{ ")?;
1249                for (i, step) in steps.iter().enumerate() {
1250                    if i > 0 {
1251                        write!(f, "; ")?;
1252                    }
1253                    write!(f, "{}", step.kind)?;
1254                }
1255                write!(f, " }}")
1256            }
1257            Expr::Compare { op, left, right } => {
1258                // Parenthesized like `Arithmetic`/`Logical` below, so
1259                // nested comparisons round-trip (`(a == b) == c` parses;
1260                // `a == b == c` does not). Found by expression fuzz.
1261                write!(f, "({} {} {})", left, op, right)
1262            }
1263            Expr::Arithmetic { op, left, right } => {
1264                write!(f, "({} {} {})", left, op, right)
1265            }
1266            Expr::CompiledMath(ops) => {
1267                write!(f, "{}", format_compiled_math(ops))
1268            }
1269            // No expression syntax produces this (bare `LET` is a
1270            // statement): render loudly non-round-trippable so a stray
1271            // use fails at re-parse instead of aliasing a named pipe.
1272            Expr::FreshPipe => write!(f, "<fresh pipe>"),
1273            Expr::UnsignedIntBoundary(n) => write!(f, "{}", n),
1274            Expr::Not(inner) => {
1275                // Parenthesize compound operands so Display round-trips:
1276                // `!(a == b)` must not render as `!a == b` (= `(!a) == b`).
1277                match inner.as_ref() {
1278                    Expr::Compare { .. } | Expr::Arithmetic { .. } | Expr::CompiledMath(_) => {
1279                        write!(f, "!({})", inner)
1280                    }
1281                    _ => write!(f, "!{}", inner),
1282                }
1283            }
1284            Expr::Logical { op, left, right } => {
1285                write!(f, "({} {} {})", left, op, right)
1286            }
1287        }
1288    }
1289}
1290
1291impl fmt::Display for CompareOp {
1292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1293        match self {
1294            CompareOp::Eq => write!(f, "=="),
1295            CompareOp::Ne => write!(f, "!="),
1296            CompareOp::Lt => write!(f, "<"),
1297            CompareOp::Le => write!(f, "<="),
1298            CompareOp::Gt => write!(f, ">"),
1299            CompareOp::Ge => write!(f, ">="),
1300        }
1301    }
1302}
1303
1304impl fmt::Display for ArithOp {
1305    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1306        match self {
1307            ArithOp::Add => write!(f, "+"),
1308            ArithOp::Sub => write!(f, "-"),
1309            ArithOp::Mul => write!(f, "*"),
1310            ArithOp::Div => write!(f, "/"),
1311        }
1312    }
1313}
1314
1315/// Render flat RPN back to parenthesized infix so `Display` round-trips
1316/// through the parser with identical semantics. Parentheses are emitted
1317/// unconditionally around binary/unary ops; redundant parens parse to the
1318/// same tree, which is what round-trip requires.
1319fn format_compiled_math(ops: &[MathOp]) -> String {
1320    let mut stack: Vec<String> = Vec::new();
1321    for op in ops {
1322        match op {
1323            MathOp::PushConst(v) => stack.push(format!("{}", v)),
1324            MathOp::LoadVar(name) => stack.push(format!("${}", name)),
1325            MathOp::LoadEnv(key) => stack.push(format!("env:{}", key)),
1326            MathOp::LoadKeyPath { base, keys } => {
1327                let mut s = format!("${}", base);
1328                for key in keys {
1329                    s.push('.');
1330                    s.push_str(key);
1331                }
1332                stack.push(s);
1333            }
1334            MathOp::Call { name, arity } => {
1335                let mut args = Vec::new();
1336                for _ in 0..*arity {
1337                    args.push(stack.pop().unwrap_or_else(|| "<underflow>".to_string()));
1338                }
1339                args.reverse();
1340                stack.push(format!("{}({})", name, args.join(", ")));
1341            }
1342            MathOp::Inspect(name) => stack.push(format!("INSPECT(${})", name)),
1343            MathOp::Neg => {
1344                let inner = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1345                stack.push(format!("(-{})", inner));
1346            }
1347            MathOp::Add => push_bin(&mut stack, "+"),
1348            MathOp::Sub => push_bin(&mut stack, "-"),
1349            MathOp::Mul => push_bin(&mut stack, "*"),
1350            MathOp::Div => push_bin(&mut stack, "/"),
1351            MathOp::Lt => push_bin(&mut stack, "<"),
1352            MathOp::Le => push_bin(&mut stack, "<="),
1353            MathOp::Gt => push_bin(&mut stack, ">"),
1354            MathOp::Ge => push_bin(&mut stack, ">="),
1355            MathOp::Eq => push_bin(&mut stack, "=="),
1356            MathOp::Ne => push_bin(&mut stack, "!="),
1357        }
1358    }
1359    if stack.len() == 1 {
1360        let mut items = stack;
1361        items.pop().unwrap_or_else(|| "<empty>".to_string())
1362    } else {
1363        stack.join(" ")
1364    }
1365}
1366
1367fn push_bin(stack: &mut Vec<String>, op: &str) {
1368    let right = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1369    let left = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1370    stack.push(format!("({} {} {})", left, op, right));
1371}
1372
1373impl fmt::Display for LogicalOp {
1374    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1375        match self {
1376            LogicalOp::And => write!(f, "&&"),
1377            LogicalOp::Or => write!(f, "||"),
1378        }
1379    }
1380}
1381
1382enum GuardDisplayContext {
1383    Root,
1384    InAnyArg,
1385    InNot,
1386    InAll,
1387}
1388
1389impl GuardExpr {
1390    fn fmt_with_ctx(&self, f: &mut fmt::Formatter<'_>, ctx: GuardDisplayContext) -> fmt::Result {
1391        match self {
1392            GuardExpr::Predicate(guard) => write!(f, "{}", guard),
1393            GuardExpr::All(children) => {
1394                let wrap = matches!(
1395                    ctx,
1396                    GuardDisplayContext::InAnyArg | GuardDisplayContext::InNot
1397                ) && children.len() > 1;
1398                if wrap {
1399                    write!(f, "(")?;
1400                }
1401                for (i, child) in children.iter().enumerate() {
1402                    if i > 0 {
1403                        write!(f, ", ")?;
1404                    }
1405                    child.fmt_with_ctx(f, GuardDisplayContext::InAll)?;
1406                }
1407                if wrap {
1408                    write!(f, ")")?;
1409                }
1410                Ok(())
1411            }
1412            GuardExpr::Or(children) => {
1413                write!(f, "any(")?;
1414                for (i, child) in children.iter().enumerate() {
1415                    if i > 0 {
1416                        write!(f, ", ")?;
1417                    }
1418                    child.fmt_with_ctx(f, GuardDisplayContext::InAnyArg)?;
1419                }
1420                write!(f, ")")
1421            }
1422            GuardExpr::Not(child) => {
1423                write!(f, "not(")?;
1424                child.fmt_with_ctx(f, GuardDisplayContext::InNot)?;
1425                write!(f, ")")
1426            }
1427        }
1428    }
1429}
1430
1431impl fmt::Display for GuardExpr {
1432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1433        self.fmt_with_ctx(f, GuardDisplayContext::Root)
1434    }
1435}
1436
1437impl fmt::Display for Step {
1438    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1439        if let Some(expr) = &self.guard {
1440            write!(f, "[{}] ", expr)?;
1441        }
1442        write!(f, "{}", self.kind)
1443    }
1444}
1445
1446#[cfg(test)]
1447mod tests {
1448    use super::*;
1449    /// Bidirectional lock between the token backend and the keyword registry.
1450    /// Fails CI if a statement keyword is renamed or deleted on either side.
1451    /// Every [`STRUCTURAL_KEYWORDS`] entry must be claimed by the backend:
1452    /// parsing it bare either succeeds (operand-less forms like `BREAK`)
1453    /// or fails structurally — never as a bare `unknown command` (issue
1454    /// #143). Conversely every head the element loop treats structurally
1455    /// must be registered here or in the command table.
1456    #[test]
1457    fn statement_keywords_match_backend() {
1458        // Transparency lock: for a bare keyword the backend must never
1459        // invent a failure of its own. Either it claims the shape
1460        // (`BREAK`/`CONTINUE`/operand-less `RETURN` lower directly) or
1461        // it routes straight to lowering and reports lowering's own
1462        // kind (production lowering, which knows every structural
1463        // head). A backend hard-fail shadowing lowering would fire
1464        // here; kind drift between the two would fire too.
1465        for kw in STRUCTURAL_KEYWORDS {
1466            let via_backend = crate::parse_script(kw, crate::commands::lower_command);
1467            let via_lowering =
1468                crate::commands::lower_command(kw, Vec::new()).map(|kind| crate::Step {
1469                    guard: None,
1470                    kind,
1471                    scope_enter: 0,
1472                    scope_exit: 0,
1473                    line: 0,
1474                    col: 0,
1475                });
1476            match (via_backend, via_lowering) {
1477                (Ok(_), _) => {}
1478                (Err(a), Err(b)) => {
1479                    assert_eq!(
1480                        a.kind(),
1481                        b.kind(),
1482                        "backend kind drift for bare keyword {kw}: {a} vs {b}"
1483                    );
1484                }
1485                (Err(a), Ok(_)) => {
1486                    panic!("backend rejects bare keyword {kw} that lowering accepts: {a}")
1487                }
1488            }
1489        }
1490        // Heads the element loop dispatches structurally (not through
1491        // generic lowering) must stay registered; update this list with
1492        // the dispatch when adding a head.
1493        for head in [
1494            "LET",
1495            "RETURN",
1496            "BREAK",
1497            "CONTINUE",
1498            "IF",
1499            "FOR",
1500            "WHILE",
1501            "FUNC",
1502            "REMOTE",
1503            "INHERIT_ENV",
1504            "WITH_IO",
1505            "ASYNC",
1506            "TIMEOUT",
1507            "ISOLATED",
1508            "AWAIT",
1509            "CANCEL",
1510            "RUN",
1511            "IMPORT",
1512            "EXPORT",
1513            "TYPE",
1514        ] {
1515            assert!(
1516                STRUCTURAL_KEYWORDS.contains(&head)
1517                    || crate::all_metadata().iter().any(|m| m.name == head),
1518                "structural head {head} is not registered"
1519            );
1520        }
1521    }
1522
1523    /// Category convention lock: every multi-word command groups under a
1524    /// registered `COMMAND_CATEGORIES` prefix. Adding a command under a
1525    /// new category fails here until the prefix registers (one line).
1526    #[test]
1527    fn command_names_group_by_category() {
1528        for command in COMMANDS {
1529            let name = command.as_str();
1530            let Some((prefix, _)) = name.split_once('_') else {
1531                continue;
1532            };
1533            assert!(
1534                COMMAND_CATEGORIES.contains(&prefix),
1535                "command {name} introduces unregistered category {prefix}; add it to COMMAND_CATEGORIES"
1536            );
1537        }
1538    }
1539
1540    /// Registry/parse parity: every indexed command name must resolve
1541    /// through `Command::parse` (or be a structural keyword). The
1542    /// token-stream splitter consults `parse`, never the metadata
1543    /// table, so a registry-only command glues onto the previous line
1544    /// and its arguments misparse as the neighbor's. Structural names
1545    /// take the keyword path instead, and doc-only entries (`in_index:
1546    /// false`, like `MUTATION`) are not parseable heads by design.
1547    #[test]
1548    fn registry_commands_all_parse() {
1549        for meta in crate::all_metadata() {
1550            if !meta.in_index || STRUCTURAL_KEYWORDS.contains(&meta.name) {
1551                continue;
1552            }
1553            assert!(
1554                Command::parse(meta.name).is_some(),
1555                "registry command {} has no Command::parse arm",
1556                meta.name
1557            );
1558        }
1559    }
1560}
1561
1562#[cfg(test)]
1563mod guard_analysis_tests {
1564    use super::*;
1565
1566    fn attr(ns: Ns, key: Option<&str>, val: Option<&str>) -> GuardExpr {
1567        GuardExpr::Predicate(Guard::Attr {
1568            ns,
1569            key: key.map(str::to_string),
1570            val: val.map(str::to_string),
1571        })
1572    }
1573
1574    fn os(value: &str) -> GuardExpr {
1575        attr(Ns::Os, None, Some(value))
1576    }
1577
1578    fn arch(value: &str) -> GuardExpr {
1579        attr(Ns::Arch, None, Some(value))
1580    }
1581
1582    /// The `family:unix` parse alias, desugared exactly as the
1583    /// parser lowers it.
1584    fn unix() -> GuardExpr {
1585        GuardExpr::Or(vec![os("macos"), os("linux")])
1586    }
1587
1588    fn windows() -> GuardExpr {
1589        os("windows")
1590    }
1591
1592    fn env_eq(var: &str, value: &str) -> GuardExpr {
1593        attr(Ns::Env, Some(var), Some(value))
1594    }
1595
1596    fn not(expr: GuardExpr) -> GuardExpr {
1597        GuardExpr::Not(Box::new(expr))
1598    }
1599
1600    /// Closed domains exhaust: negating every `os:` value (or both
1601    /// `bool:` values) covers no host. Open domains (`env:`) never
1602    /// exhaust — some unmentioned value may hold.
1603    #[test]
1604    fn partition_negations_are_jointly_dead() {
1605        let os_exhausted = GuardExpr::All(vec![not(os("macos")), not(os("linux")), not(windows())]);
1606        assert!(
1607            !guard_satisfiable(&os_exhausted),
1608            "no host is outside `macos`/`linux`/`windows`"
1609        );
1610        // Partial negations stay live.
1611        let os_partial = GuardExpr::All(vec![not(os("macos")), not(os("linux"))]);
1612        assert!(guard_satisfiable(&os_partial), "`windows` is still open");
1613        // The bool domain exhausts the same way.
1614        let bool_exhausted = GuardExpr::All(vec![
1615            not(attr(Ns::Bool, None, Some("true"))),
1616            not(attr(Ns::Bool, None, Some("false"))),
1617        ]);
1618        assert!(!guard_satisfiable(&bool_exhausted));
1619        // Open env domains never exhaust.
1620        let env_open = GuardExpr::All(vec![
1621            not(env_eq("MODE", "dev")),
1622            not(env_eq("MODE", "prod")),
1623        ]);
1624        assert!(guard_satisfiable(&env_open), "MODE may hold a third value");
1625        // Single negations are always live.
1626        assert!(guard_satisfiable(&not(unix())));
1627    }
1628
1629    /// The desugared `unix` alias behaves as a disjunction: it meets
1630    /// `windows` nowhere and covers `macos`/`linux` deployment reads.
1631    #[test]
1632    fn unix_alias_is_os_disjunction() {
1633        assert!(!guards_overlap(Some(&unix()), Some(&windows())));
1634        assert!(guards_overlap(Some(&unix()), Some(&os("macos"))));
1635        // Coverage through the alias: `unix` + `windows` declarations
1636        // cover every host, so their joint negation is dead.
1637        let covered = GuardExpr::All(vec![GuardExpr::Not(Box::new(unix())), not(windows())]);
1638        assert!(!guard_satisfiable(&covered));
1639    }
1640
1641    /// `arch:` decides by value like every namespace; it overlaps
1642    /// `os:` (independent axes: an aarch64 mac exists). Negating
1643    /// the whole closed `ARCH_VALUES` domain covers no host.
1644    #[test]
1645    fn arch_guards_decide_by_value() {
1646        assert!(!guards_overlap(
1647            Some(&arch("x86_64")),
1648            Some(&arch("aarch64"))
1649        ));
1650        assert!(guards_overlap(Some(&arch("x86_64")), Some(&arch("x86_64"))));
1651        assert!(guards_overlap(Some(&arch("aarch64")), Some(&os("macos"))));
1652        let exhausted = GuardExpr::All(ARCH_VALUES.iter().map(|value| not(arch(value))).collect());
1653        assert!(!guard_satisfiable(&exhausted));
1654        // Runtime anchor: this host's own architecture fires here.
1655        let host = attr(Ns::Arch, None, Some(ARCH_TARGET));
1656        assert!(guard_expr_allows(&host, &HashMap::new()));
1657    }
1658
1659    /// The full platform matrix, asserted exhaustively. All three
1660    /// `os:` values are pairwise disjoint; identical values
1661    /// overlap.
1662    #[test]
1663    fn platform_overlap_matrix_is_exhaustive() {
1664        let cases = [
1665            ("macos", "macos", true),
1666            ("macos", "linux", false),
1667            ("macos", "windows", false),
1668            ("linux", "linux", true),
1669            ("linux", "windows", false),
1670            ("windows", "windows", true),
1671        ];
1672        for (v1, v2, expected) in cases {
1673            let left = os(v1);
1674            let right = os(v2);
1675            assert_eq!(
1676                guards_overlap(Some(&left), Some(&right)),
1677                expected,
1678                "os:{v1} vs os:{v2}"
1679            );
1680        }
1681    }
1682
1683    /// Runtime anchor, portable across CI hosts: `os:macos` and
1684    /// `os:windows` never co-fire on the machine running the test.
1685    #[test]
1686    fn disjoint_pairs_never_cofire_here() {
1687        let macos = os("macos");
1688        let holds = |expr: &GuardExpr| guard_expr_allows(expr, &HashMap::new());
1689        assert!(
1690            !(holds(&macos) && holds(&windows())),
1691            "os:macos and os:windows co-fired"
1692        );
1693    }
1694
1695    #[test]
1696    fn overlap_follows_namespace_semantics() {
1697        // Same namespace, distinct values: disjoint.
1698        assert!(!guards_overlap(Some(&windows()), Some(&unix())));
1699        assert!(!guards_overlap(Some(&os("macos")), Some(&os("linux"))));
1700        // Absent guards are unconditional.
1701        assert!(guards_overlap(None, Some(&windows())));
1702        assert!(guards_overlap(None, None));
1703        // Unsatisfiable conjunctions overlap nothing.
1704        let dead = GuardExpr::All(vec![os("macos"), windows()]);
1705        assert!(!guard_satisfiable(&dead));
1706        assert!(!guards_overlap(Some(&dead), Some(&os("macos"))));
1707        assert!(guard_valid(&GuardExpr::Predicate(Guard::Attr {
1708            ns: Ns::Bool,
1709            key: None,
1710            val: Some("true".to_string()),
1711        })));
1712        assert!(!guard_valid(&unix()));
1713    }
1714
1715    #[test]
1716    fn env_value_conflicts_decide_without_enumeration() {
1717        let fast = env_eq("MODE", "fast");
1718        let slow = env_eq("MODE", "slow");
1719        assert!(
1720            !guards_overlap(Some(&fast), Some(&slow)),
1721            "same key distinct values are disjoint"
1722        );
1723        let also_fast = env_eq("MODE", "fast");
1724        assert!(guards_overlap(Some(&fast), Some(&also_fast)));
1725        // Bare presence overlaps any value on the same key.
1726        let bare = attr(Ns::Env, Some("MODE"), None);
1727        assert!(guards_overlap(Some(&bare), Some(&fast)));
1728    }
1729}
1730
1731#[cfg(test)]
1732mod guard_algebra_tests {
1733    use super::*;
1734
1735    fn os(value: &str) -> GuardExpr {
1736        GuardExpr::Predicate(Guard::Attr {
1737            ns: Ns::Os,
1738            key: None,
1739            val: Some(value.to_string()),
1740        })
1741    }
1742
1743    #[test]
1744    fn or_distributes_over_disjointness() {
1745        fn env_eq(var: &str, value: &str) -> GuardExpr {
1746            GuardExpr::Predicate(Guard::Attr {
1747                ns: Ns::Env,
1748                key: Some(var.to_string()),
1749                val: Some(value.to_string()),
1750            })
1751        }
1752        // Every arm must exclude `other`: one overlapping arm keeps
1753        // the whole disjunction live.
1754        let mixed = GuardExpr::Or(vec![env_eq("MODE", "dev"), env_eq("MODE", "prod")]);
1755        assert!(!mixed.is_disjoint_from(&env_eq("MODE", "dev")));
1756        // All arms disjoint: the disjunction is dead against it.
1757        assert!(mixed.is_disjoint_from(&env_eq("MODE", "test")));
1758        // Cross-namespace arms never exclude: different axes overlap.
1759        let cross = GuardExpr::Or(vec![env_eq("MODE", "dev")]);
1760        let platform = os("windows");
1761        assert!(!cross.is_disjoint_from(&platform));
1762    }
1763
1764    #[test]
1765    fn all_distributes_over_disjointness() {
1766        let stacked = GuardExpr::All(vec![
1767            os("macos"),
1768            GuardExpr::Or(vec![os("macos"), os("linux")]),
1769            os("windows"),
1770        ]);
1771        assert!(stacked.is_disjoint_from(&os("macos")));
1772        // One live arm keeps the conjunction overlapping: neither
1773        // arm excludes macos here.
1774        let live = GuardExpr::All(vec![
1775            os("macos"),
1776            GuardExpr::Predicate(Guard::Attr {
1777                ns: Ns::Env,
1778                key: Some("MODE".to_string()),
1779                val: Some("dev".to_string()),
1780            }),
1781        ]);
1782        assert!(!live.is_disjoint_from(&os("macos")));
1783    }
1784
1785    #[test]
1786    fn negation_is_structural_not_syntactic() {
1787        let not_win = GuardExpr::Not(Box::new(os("windows")));
1788        assert!(not_win.is_disjoint_from(&os("windows")));
1789        assert!(os("windows").is_disjoint_from(&not_win));
1790        assert!(!not_win.is_disjoint_from(&os("macos")));
1791    }
1792}