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