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