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