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