1use std::collections::{HashMap, HashSet};
2use std::fmt;
3use std::sync::Arc;
4
5pub use crate::commands::{AssertTarget, StepKind};
6use crate::constants::{
7 KEYWORD_APPEND, KEYWORD_APPEND_LINE, KEYWORD_ARCHIVE, KEYWORD_ASSERT_CONTAINS,
8 KEYWORD_ASSERT_EQ, KEYWORD_ASSERT_NE, KEYWORD_ASYNC, KEYWORD_AWAIT, KEYWORD_BREAK,
9 KEYWORD_CANCEL, KEYWORD_CASE, KEYWORD_CONTINUE, KEYWORD_COPY, KEYWORD_COPY_GIT,
10 KEYWORD_DEFAULT, KEYWORD_ECHO, KEYWORD_ELSE, KEYWORD_ENV, KEYWORD_EXIT, KEYWORD_EXPAND,
11 KEYWORD_EXPORT, KEYWORD_FAIL, KEYWORD_FOR, KEYWORD_FUNC, KEYWORD_IF, KEYWORD_IMPORT,
12 KEYWORD_IN, KEYWORD_INHERIT_ENV, KEYWORD_INSTALL, KEYWORD_ISOLATED, KEYWORD_LET,
13 KEYWORD_LIST_APPEND, KEYWORD_LS, KEYWORD_MKDIR, KEYWORD_PROMPT, KEYWORD_READ,
14 KEYWORD_READ_LINE, KEYWORD_REMOTE, KEYWORD_REMOVE, KEYWORD_RETURN, KEYWORD_RUN,
15 KEYWORD_SET_EXECUTABLE, KEYWORD_SLEEP, KEYWORD_SWITCH, KEYWORD_SYMLINK, KEYWORD_TIMEOUT,
16 KEYWORD_TYPE, KEYWORD_UNARCHIVE, KEYWORD_WHILE, KEYWORD_WITH_IO, KEYWORD_WORKDIR,
17 KEYWORD_WORKSPACE, KEYWORD_WRITE,
18};
19
20#[derive(Debug, Clone, Default)]
24pub struct ModuleFuncs {
25 pub func_names: HashSet<String>,
27}
28
29#[derive(Debug, Clone, Default)]
34pub struct ModuleTable {
35 pub modules: HashMap<String, Option<ModuleFuncs>>,
36}
37
38impl ModuleTable {
39 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#[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
132pub 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 pub(crate) fn is_statement_keyword(s: &str) -> bool {
277 Command::parse(s).is_some() || STRUCTURAL_KEYWORDS.contains(&s)
278 }
279}
280
281pub const STRUCTURAL_KEYWORDS: &[&str] = &[
287 KEYWORD_LET,
288 KEYWORD_FOR,
289 KEYWORD_IF,
290 KEYWORD_ELSE,
291 KEYWORD_SWITCH,
292 KEYWORD_CASE,
293 KEYWORD_DEFAULT,
294 KEYWORD_ASYNC,
295 KEYWORD_AWAIT,
296 KEYWORD_CANCEL,
297 KEYWORD_FUNC,
298 KEYWORD_RETURN,
299 KEYWORD_WHILE,
300 KEYWORD_BREAK,
301 KEYWORD_CONTINUE,
302 KEYWORD_REMOTE,
303 KEYWORD_IMPORT,
304 KEYWORD_EXPORT,
305 KEYWORD_TYPE,
306];
307
308pub const CLAUSE_KEYWORDS: &[&str] = &[KEYWORD_IN];
313
314#[derive(Debug, Clone, Eq, PartialEq)]
327pub enum Guard {
328 Attr {
329 ns: Ns,
330 key: Option<String>,
331 val: Option<String>,
332 },
333}
334
335#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
339pub enum Ns {
340 Os,
341 Arch,
342 Bool,
343 Env,
344}
345
346impl fmt::Display for Ns {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 match self {
349 Ns::Os => write!(f, "os"),
350 Ns::Arch => write!(f, "arch"),
351 Ns::Bool => write!(f, "bool"),
352 Ns::Env => write!(f, "env"),
353 }
354 }
355}
356
357pub const ARCH_VALUES: &[&str] = &[
361 "aarch64",
362 "arm",
363 "arm64ec",
364 "avr",
365 "bpf",
366 "csky",
367 "hexagon",
368 "loongarch32",
369 "loongarch64",
370 "mips",
371 "mips32r6",
372 "mips64",
373 "mips64r6",
374 "msp430",
375 "nvptx64",
376 "powerpc",
377 "powerpc64",
378 "riscv32",
379 "riscv64",
380 "s390x",
381 "sparc",
382 "sparc64",
383 "wasm32",
384 "wasm64",
385 "x86",
386 "x86_64",
387 "xtensa",
388];
389
390#[derive(Debug, Clone, Eq, PartialEq)]
391pub enum GuardExpr {
392 Predicate(Guard),
393 All(Vec<GuardExpr>),
394 Or(Vec<GuardExpr>),
395 Not(Box<GuardExpr>),
396}
397
398impl GuardExpr {
399 pub fn all(exprs: Vec<GuardExpr>) -> GuardExpr {
400 let mut flat = Vec::new();
401 for expr in exprs {
402 match expr {
403 GuardExpr::All(children) => flat.extend(children),
404 other => flat.push(other),
405 }
406 }
407 match flat.len() {
408 0 => panic!("GuardExpr::all requires at least one expression"),
409 1 => flat.into_iter().next().unwrap(),
410 _ => GuardExpr::All(flat),
411 }
412 }
413
414 pub fn or(exprs: Vec<GuardExpr>) -> GuardExpr {
415 let mut flat = Vec::new();
416 for expr in exprs {
417 match expr {
418 GuardExpr::Or(children) => flat.extend(children),
419 other => flat.push(other),
420 }
421 }
422 match flat.len() {
423 0 => panic!("GuardExpr::or requires at least one expression"),
424 1 => flat.into_iter().next().unwrap(),
425 _ => GuardExpr::Or(flat),
426 }
427 }
428
429 pub fn invert(expr: GuardExpr) -> GuardExpr {
430 match expr {
431 GuardExpr::Not(inner) => *inner,
432 other => GuardExpr::Not(Box::new(other)),
433 }
434 }
435}
436
437impl std::ops::Not for GuardExpr {
438 type Output = GuardExpr;
439
440 fn not(self) -> GuardExpr {
441 match self {
442 GuardExpr::Not(inner) => *inner,
443 other => GuardExpr::Not(Box::new(other)),
444 }
445 }
446}
447
448impl From<Guard> for GuardExpr {
449 fn from(guard: Guard) -> Self {
450 GuardExpr::Predicate(guard)
451 }
452}
453
454#[derive(Debug, Clone, PartialEq)]
456pub enum Arg {
457 String(String, bool),
461 Expr(Expr),
463 Parts(Vec<ArgPart>),
467}
468
469#[derive(Debug, Clone, PartialEq)]
471pub enum ArgPart {
472 Text(String, bool),
475 Expr(Expr),
477}
478
479impl Arg {
480 pub fn as_str(&self) -> &str {
481 match self {
482 Arg::String(s, _) => s,
483 Arg::Expr(_) | Arg::Parts(_) => "",
486 }
487 }
488
489 pub fn render(&self) -> String {
493 match self {
494 Arg::String(s, _) => s.clone(),
495 Arg::Expr(e) => e.to_string(),
496 Arg::Parts(parts) => parts.iter().map(ArgPart::render).collect(),
497 }
498 }
499
500 pub fn is_quoted(&self) -> bool {
501 matches!(self, Arg::String(_, true))
502 }
503}
504
505impl ArgPart {
506 pub fn render(&self) -> String {
507 match self {
508 ArgPart::Text(s, _) => s.clone(),
509 ArgPart::Expr(e) => e.to_string(),
510 }
511 }
512}
513
514impl From<String> for Arg {
515 fn from(s: String) -> Self {
516 Arg::String(s, false)
517 }
518}
519
520impl From<&str> for Arg {
521 fn from(s: &str) -> Self {
522 Arg::String(s.to_string(), false)
523 }
524}
525
526impl std::fmt::Display for Arg {
527 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
528 match self {
529 Arg::String(s, _) => write!(f, "{}", s),
530 Arg::Expr(e) => write!(f, "{}", e),
531 Arg::Parts(parts) => {
532 for part in parts {
533 match part {
534 ArgPart::Text(s, _) => write!(f, "{}", s)?,
535 ArgPart::Expr(e) => write!(f, "{}", e)?,
536 }
537 }
538 Ok(())
539 }
540 }
541 }
542}
543
544impl AsRef<str> for Arg {
545 fn as_ref(&self) -> &str {
546 self.as_str()
547 }
548}
549
550impl PartialEq<str> for Arg {
551 fn eq(&self, other: &str) -> bool {
552 self.as_str() == other
553 }
554}
555
556impl PartialEq<&str> for Arg {
557 fn eq(&self, other: &&str) -> bool {
558 self.as_str() == *other
559 }
560}
561
562#[derive(Debug, Clone, Copy, Eq, PartialEq)]
563pub enum IoStream {
564 Stdin,
565 Stdout,
566 Stderr,
567 Tty,
571 Rows(u16),
573 Cols(u16),
575}
576
577#[derive(Debug, Clone, Eq, PartialEq)]
578pub struct IoBinding {
579 pub stream: IoStream,
580 pub pipe: Option<PipeTarget>,
581}
582
583#[derive(Debug, Clone, Eq, PartialEq)]
586pub enum PipeTarget {
587 Var(String),
588}
589
590pub use crate::value::{
594 OxDockType, SemaphoreState, TypeDescriptor, Value, ValuePayload, clone_boxed, clone_copy,
595 clone_shared, drop_boxed, drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed,
596 fmt_inline, fmt_shared, load_inline, startup_descriptors, store_inline, type_anchor,
597 unshare_boxed, unshare_inline, unshare_shared,
598};
599
600#[derive(Debug, Clone, Copy, Eq, PartialEq)]
601pub enum CompareOp {
602 Eq,
603 Ne,
604 Lt,
605 Le,
606 Gt,
607 Ge,
608}
609
610#[derive(Debug, Clone, Copy, Eq, PartialEq)]
611pub enum ArithOp {
612 Add,
613 Sub,
614 Mul,
615 Div,
616}
617
618#[derive(Debug, Clone, PartialEq)]
627pub enum MathOp {
628 PushConst(Value),
629 LoadVar(String),
630 LoadEnv(String),
631 LoadKeyPath { base: String, keys: Vec<String> },
632 Call { name: String, arity: usize },
633 Inspect(String),
634 Neg,
635 Add,
636 Sub,
637 Mul,
638 Div,
639 Lt,
640 Le,
641 Gt,
642 Ge,
643 Eq,
644 Ne,
645}
646
647#[derive(Debug, Clone, Copy, Eq, PartialEq)]
648pub enum LogicalOp {
649 And,
650 Or,
651}
652
653#[derive(Debug, Clone, PartialEq)]
654pub enum Expr {
655 Literal(Value),
656 Var(String),
657 Env(String),
660 KeyPath {
661 base: String,
662 keys: Vec<String>,
663 },
664 List(Vec<Expr>),
665 Map(Vec<(String, Expr)>),
666 Block(Vec<Step>),
671 Call {
672 name: String,
673 args: Vec<Expr>,
674 },
675 Inspect(String),
680 Compare {
681 op: CompareOp,
682 left: Box<Expr>,
683 right: Box<Expr>,
684 },
685 Arithmetic {
686 op: ArithOp,
687 left: Box<Expr>,
688 right: Box<Expr>,
689 },
690 CompiledMath(Vec<MathOp>),
693 FreshPipe,
699 UnsignedIntBoundary(u64),
703 Not(Box<Expr>),
704 Logical {
705 op: LogicalOp,
706 left: Box<Expr>,
707 right: Box<Expr>,
708 },
709}
710
711#[derive(Debug, Clone)]
712pub struct Step {
713 pub guard: Option<GuardExpr>,
714 pub kind: StepKind,
715 pub scope_enter: usize,
716 pub scope_exit: usize,
717 pub line: usize,
724 pub col: usize,
728}
729
730impl PartialEq for Step {
731 fn eq(&self, other: &Self) -> bool {
732 self.guard == other.guard
733 && self.kind == other.kind
734 && self.scope_enter == other.scope_enter
735 && self.scope_exit == other.scope_exit
736 }
737}
738
739impl Eq for Step {}
740
741impl Expr {
742 pub fn walk(&self, f: &mut impl FnMut(&Expr)) {
749 f(self);
750 match self {
751 Expr::Literal(_)
752 | Expr::Var(_)
753 | Expr::Env(_)
754 | Expr::KeyPath { .. }
755 | Expr::Inspect(_)
756 | Expr::FreshPipe
757 | Expr::UnsignedIntBoundary(_) => {}
758 Expr::Call { args, .. } => {
759 for arg in args {
760 arg.walk(f);
761 }
762 }
763 Expr::List(items) => {
764 for item in items {
765 item.walk(f);
766 }
767 }
768 Expr::Map(entries) => {
769 for (_, value) in entries {
770 value.walk(f);
771 }
772 }
773 Expr::Block(steps) => {
774 for step in steps {
775 step.kind.walk_step_exprs(f);
776 }
777 }
778 Expr::Compare { left, right, .. }
779 | Expr::Arithmetic { left, right, .. }
780 | Expr::Logical { left, right, .. } => {
781 left.walk(f);
782 right.walk(f);
783 }
784 Expr::CompiledMath(_) => {}
785 Expr::Not(inner) => inner.walk(f),
786 }
787 }
788
789 pub fn walk_mut(&mut self, f: &mut impl FnMut(&mut Expr)) {
796 f(self);
797 match self {
798 Expr::Literal(_)
799 | Expr::Var(_)
800 | Expr::Env(_)
801 | Expr::KeyPath { .. }
802 | Expr::Inspect(_)
803 | Expr::FreshPipe
804 | Expr::UnsignedIntBoundary(_) => {}
805 Expr::Call { args, .. } => {
806 for arg in args {
807 arg.walk_mut(f);
808 }
809 }
810 Expr::List(items) => {
811 for item in items {
812 item.walk_mut(f);
813 }
814 }
815 Expr::Map(entries) => {
816 for (_, value) in entries {
817 value.walk_mut(f);
818 }
819 }
820 Expr::Block(_) => {}
821 Expr::Compare { left, right, .. }
822 | Expr::Arithmetic { left, right, .. }
823 | Expr::Logical { left, right, .. } => {
824 left.walk_mut(f);
825 right.walk_mut(f);
826 }
827 Expr::CompiledMath(_) => {}
828 Expr::Not(inner) => inner.walk_mut(f),
829 }
830 }
831}
832
833#[derive(Debug, Clone, Eq, PartialEq)]
834pub enum WorkspaceTarget {
835 Snapshot,
836 Local,
837 Cache { local: bool },
838 System,
839}
840
841pub trait EnvLookup {
842 fn get_env(&self, key: &str) -> Option<&str>;
843}
844
845impl EnvLookup for HashMap<String, String> {
846 fn get_env(&self, key: &str) -> Option<&str> {
847 self.get(key).map(|s| s.as_str())
848 }
849}
850
851impl EnvLookup for Arc<HashMap<String, String>> {
852 fn get_env(&self, key: &str) -> Option<&str> {
853 (**self).get_env(key)
854 }
855}
856
857pub fn guard_allows(guard: &Guard, env: &impl EnvLookup) -> bool {
858 let Guard::Attr { ns, key, val } = guard;
859 match ns {
860 Ns::Os => match val.as_deref() {
861 Some("macos") => platform_is_macos(),
862 Some("linux") => platform_is_linux(),
863 Some("windows") => platform_is_windows(),
864 _ => false,
865 },
866 Ns::Arch => match val.as_deref() {
867 Some(want) => ARCH_TARGET == want,
868 None => false,
869 },
870 Ns::Bool => val
871 .as_deref()
872 .map(|v| v.parse::<bool>().unwrap_or(false))
873 .unwrap_or(false),
874 Ns::Env => match key.as_deref() {
875 Some(var) => match val {
876 None => env.get_env(var).map(|v| !v.is_empty()).unwrap_or(false),
877 Some(want) => env
878 .get_env(var)
879 .map(|v| v == want.as_str())
880 .unwrap_or(false),
881 },
882 None => false,
884 },
885 }
886}
887
888#[allow(clippy::disallowed_macros)]
891fn platform_is_windows() -> bool {
892 cfg!(windows)
893}
894
895#[allow(clippy::disallowed_macros)]
897fn platform_is_macos() -> bool {
898 cfg!(target_os = "macos")
899}
900
901#[allow(clippy::disallowed_macros)]
903fn platform_is_linux() -> bool {
904 cfg!(target_os = "linux")
905}
906
907const ARCH_TARGET: &str = std::env::consts::ARCH;
910
911pub fn guard_expr_allows(expr: &GuardExpr, env: &impl EnvLookup) -> bool {
912 match expr {
913 GuardExpr::Predicate(guard) => guard_allows(guard, env),
914 GuardExpr::All(children) => children.iter().all(|g| guard_expr_allows(g, env)),
915 GuardExpr::Or(children) => children.iter().any(|g| guard_expr_allows(g, env)),
916 GuardExpr::Not(child) => !guard_expr_allows(child, env),
917 }
918}
919
920pub fn guard_option_allows(expr: Option<&GuardExpr>, env: &impl EnvLookup) -> bool {
921 match expr {
922 Some(e) => guard_expr_allows(e, env),
923 None => true,
924 }
925}
926
927impl Guard {
928 pub fn is_disjoint_from(&self, other: &Self) -> bool {
937 match (self, other) {
938 (
939 Guard::Attr {
940 ns: n1,
941 key: k1,
942 val: Some(v1),
943 },
944 Guard::Attr {
945 ns: n2,
946 key: k2,
947 val: Some(v2),
948 },
949 ) => n1 == n2 && k1 == k2 && v1 != v2,
950 _ => false,
951 }
952 }
953}
954
955impl GuardExpr {
956 pub fn is_disjoint_from(&self, other: &Self) -> bool {
962 match (self, other) {
963 (x, GuardExpr::Not(inner)) | (GuardExpr::Not(inner), x) => {
971 x == inner.as_ref() || unset_excludes(x, inner.as_ref())
972 }
973 (GuardExpr::Predicate(p1), GuardExpr::Predicate(p2)) => p1.is_disjoint_from(p2),
975 (GuardExpr::Or(arms), other) | (other, GuardExpr::Or(arms)) => {
977 arms.iter().all(|arm| arm.is_disjoint_from(other))
978 }
979 (GuardExpr::All(arms), other) | (other, GuardExpr::All(arms)) => {
981 arms.iter().any(|arm| arm.is_disjoint_from(other))
982 }
983 }
984 }
985}
986
987fn conjuncts(expr: &GuardExpr) -> Vec<&GuardExpr> {
991 match expr {
992 GuardExpr::All(items) => items.iter().collect(),
993 single => vec![single],
994 }
995}
996
997fn closed_domain_values(ns: Ns, key: Option<&str>) -> Option<&'static [&'static str]> {
1004 match (ns, key) {
1005 (Ns::Bool, None) => Some(&["true", "false"]),
1006 (Ns::Os, None) => Some(&["macos", "linux", "windows"]),
1007 (Ns::Arch, None) => Some(ARCH_VALUES),
1008 _ => None,
1009 }
1010}
1011
1012#[derive(Clone)]
1015enum DnfLit {
1016 Pos(Guard),
1017 Neg(Guard),
1018}
1019
1020impl DnfLit {
1021 fn as_expr(&self) -> GuardExpr {
1022 match self {
1023 DnfLit::Pos(guard) => GuardExpr::Predicate(guard.clone()),
1024 DnfLit::Neg(guard) => GuardExpr::Not(Box::new(GuardExpr::Predicate(guard.clone()))),
1025 }
1026 }
1027}
1028
1029const MAX_DNF_DISJUNCTS: usize = 64;
1034
1035fn dnf_push(expr: &GuardExpr, polarity: bool, out: &mut Vec<Vec<DnfLit>>) -> bool {
1040 match (expr, polarity) {
1041 (GuardExpr::Predicate(guard), true) => {
1042 for disjunct in out.iter_mut() {
1043 disjunct.push(DnfLit::Pos(guard.clone()));
1044 }
1045 true
1046 }
1047 (GuardExpr::Predicate(guard), false) => {
1048 for disjunct in out.iter_mut() {
1049 disjunct.push(DnfLit::Neg(guard.clone()));
1050 }
1051 true
1052 }
1053 (GuardExpr::All(children), true) | (GuardExpr::Or(children), false) => {
1054 for child in children {
1056 if !dnf_push(child, polarity, out) {
1057 return false;
1058 }
1059 }
1060 true
1061 }
1062 (GuardExpr::Or(children), true) | (GuardExpr::All(children), false) => {
1063 let mut forked = Vec::new();
1065 for disjunct in out.drain(..) {
1066 for child in children {
1067 let mut branch = vec![disjunct.clone()];
1068 if !dnf_push(child, polarity, &mut branch) {
1069 return false;
1070 }
1071 forked.extend(branch);
1072 if forked.len() > MAX_DNF_DISJUNCTS {
1073 return false;
1074 }
1075 }
1076 }
1077 *out = forked;
1078 true
1079 }
1080 (GuardExpr::Not(inner), _) => dnf_push(inner, !polarity, out),
1081 }
1082}
1083
1084fn disjunct_satisfiable(lits: &[DnfLit]) -> bool {
1088 for lit in lits {
1092 match lit {
1093 DnfLit::Pos(Guard::Attr {
1094 ns: Ns::Bool, val, ..
1095 }) if val.as_deref() != Some("true") => return false,
1096 DnfLit::Neg(Guard::Attr {
1097 ns: Ns::Bool,
1098 key: None,
1099 val: Some(value),
1100 }) if value == "true" => return false,
1101 _ => {}
1102 }
1103 }
1104 for (index, first) in lits.iter().enumerate() {
1107 for second in &lits[index + 1..] {
1108 if first.as_expr().is_disjoint_from(&second.as_expr()) {
1109 return false;
1110 }
1111 }
1112 }
1113 for lit in lits {
1117 let (ns, key) = match lit {
1118 DnfLit::Neg(Guard::Attr {
1119 ns,
1120 key,
1121 val: Some(_),
1122 }) => (*ns, key.as_deref()),
1123 _ => continue,
1124 };
1125 let Some(domain) = closed_domain_values(ns, key) else {
1126 continue;
1127 };
1128 let exhausted = domain.iter().all(|value| {
1129 lits.iter().any(|other| match other {
1130 DnfLit::Neg(Guard::Attr {
1131 ns: other_ns,
1132 key: other_key,
1133 val: Some(other_val),
1134 }) => *other_ns == ns && other_key.as_deref() == key && other_val == value,
1135 _ => false,
1136 })
1137 });
1138 if exhausted {
1139 return false;
1140 }
1141 }
1142 true
1143}
1144
1145fn conjunction_dead(atoms: &[&GuardExpr]) -> bool {
1152 if atoms.is_empty() {
1153 return false;
1154 }
1155 let mut disjuncts = vec![Vec::new()];
1156 for atom in atoms {
1157 if !dnf_push(atom, true, &mut disjuncts) {
1158 return false;
1159 }
1160 }
1161 !disjuncts
1162 .iter()
1163 .any(|disjunct| disjunct_satisfiable(disjunct))
1164}
1165
1166pub fn guard_satisfiable(expr: &GuardExpr) -> bool {
1168 !conjunction_dead(&conjuncts(expr))
1169}
1170
1171pub fn guard_valid(expr: &GuardExpr) -> bool {
1174 match expr {
1175 GuardExpr::Predicate(Guard::Attr {
1176 ns: Ns::Bool,
1177 val: Some(value),
1178 ..
1179 }) => value.as_str() == "true",
1180 GuardExpr::All(items) => items.iter().all(guard_valid),
1181 GuardExpr::Not(inner) => !guard_satisfiable(inner),
1182 _ => false,
1183 }
1184}
1185
1186pub fn guards_overlap(a: Option<&GuardExpr>, b: Option<&GuardExpr>) -> bool {
1189 match (a, b) {
1190 (None, None) => true,
1191 (Some(x), None) | (None, Some(x)) => guard_satisfiable(x),
1192 (Some(x), Some(y)) => {
1193 let mut atoms = conjuncts(x);
1194 atoms.extend(conjuncts(y));
1195 !conjunction_dead(&atoms)
1196 }
1197 }
1198}
1199
1200fn unset_excludes(x: &GuardExpr, inner: &GuardExpr) -> bool {
1203 match (x, inner) {
1204 (
1205 GuardExpr::Predicate(Guard::Attr {
1206 ns: n2, key: k2, ..
1207 }),
1208 GuardExpr::Predicate(Guard::Attr {
1209 ns: n1,
1210 key: k1,
1211 val: None,
1212 }),
1213 ) => n1 == n2 && k1 == k2,
1214 _ => false,
1215 }
1216}
1217
1218impl fmt::Display for Guard {
1219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1225 match self {
1226 Guard::Attr {
1227 ns: Ns::Env,
1228 key: Some(var),
1229 val: None,
1230 } => write!(f, "env:{var}"),
1231 Guard::Attr {
1232 ns: Ns::Env,
1233 key: Some(var),
1234 val: Some(want),
1235 } => write!(f, "eq(env:{var}, {want})"),
1236 Guard::Attr {
1237 ns,
1238 key: _,
1239 val: Some(value),
1240 } => write!(f, "{ns}:{value}"),
1241 Guard::Attr { ns, key, val: None } => match key {
1242 Some(subject) => write!(f, "{ns}:{subject}"),
1243 None => write!(f, "{ns}"),
1244 },
1245 }
1246 }
1247}
1248
1249impl fmt::Display for WorkspaceTarget {
1250 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1251 match self {
1252 WorkspaceTarget::Snapshot => write!(f, "SNAPSHOT"),
1253 WorkspaceTarget::Local => write!(f, "LOCAL"),
1254 WorkspaceTarget::Cache { local: false } => write!(f, "CACHE"),
1255 WorkspaceTarget::Cache { local: true } => write!(f, "CACHE --local"),
1256 WorkspaceTarget::System => write!(f, "SYSTEM"),
1257 }
1258 }
1259}
1260
1261impl fmt::Display for Expr {
1262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1263 match self {
1264 Expr::Literal(v) => write!(f, "{}", v),
1265 Expr::Var(name) => write!(f, "${}", name),
1266 Expr::Env(key) => write!(f, "env:{}", key),
1267 Expr::KeyPath { base, keys } => {
1268 write!(f, "${}", base)?;
1269 for key in keys {
1270 write!(f, ".{}", key)?;
1271 }
1272 Ok(())
1273 }
1274 Expr::Call { name, args } => {
1275 write!(f, "{}(", name)?;
1276 for (i, arg) in args.iter().enumerate() {
1277 if i > 0 {
1278 write!(f, ", ")?;
1279 }
1280 write!(f, "{}", arg)?;
1281 }
1282 write!(f, ")")
1283 }
1284 Expr::Inspect(var) => write!(f, "INSPECT(${})", var),
1285 Expr::List(items) => {
1286 write!(f, "[")?;
1287 for (i, item) in items.iter().enumerate() {
1288 if i > 0 {
1289 write!(f, ", ")?;
1290 }
1291 write!(f, "{}", item)?;
1292 }
1293 write!(f, "]")
1294 }
1295 Expr::Map(entries) => {
1296 write!(f, "{{")?;
1297 for (i, (key, val)) in entries.iter().enumerate() {
1298 if i > 0 {
1299 write!(f, ", ")?;
1300 }
1301 write!(f, "\"{}\": {}", key, val)?;
1302 }
1303 write!(f, "}}")
1304 }
1305 Expr::Block(steps) => {
1306 write!(f, "{{ ")?;
1307 for (i, step) in steps.iter().enumerate() {
1308 if i > 0 {
1309 write!(f, "; ")?;
1310 }
1311 write!(f, "{}", step.kind)?;
1312 }
1313 write!(f, " }}")
1314 }
1315 Expr::Compare { op, left, right } => {
1316 write!(f, "({} {} {})", left, op, right)
1320 }
1321 Expr::Arithmetic { op, left, right } => {
1322 write!(f, "({} {} {})", left, op, right)
1323 }
1324 Expr::CompiledMath(ops) => {
1325 write!(f, "{}", format_compiled_math(ops))
1326 }
1327 Expr::FreshPipe => write!(f, "<fresh pipe>"),
1331 Expr::UnsignedIntBoundary(n) => write!(f, "{}", n),
1332 Expr::Not(inner) => {
1333 match inner.as_ref() {
1336 Expr::Compare { .. } | Expr::Arithmetic { .. } | Expr::CompiledMath(_) => {
1337 write!(f, "!({})", inner)
1338 }
1339 _ => write!(f, "!{}", inner),
1340 }
1341 }
1342 Expr::Logical { op, left, right } => {
1343 write!(f, "({} {} {})", left, op, right)
1344 }
1345 }
1346 }
1347}
1348
1349impl fmt::Display for CompareOp {
1350 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1351 match self {
1352 CompareOp::Eq => write!(f, "=="),
1353 CompareOp::Ne => write!(f, "!="),
1354 CompareOp::Lt => write!(f, "<"),
1355 CompareOp::Le => write!(f, "<="),
1356 CompareOp::Gt => write!(f, ">"),
1357 CompareOp::Ge => write!(f, ">="),
1358 }
1359 }
1360}
1361
1362impl fmt::Display for ArithOp {
1363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1364 match self {
1365 ArithOp::Add => write!(f, "+"),
1366 ArithOp::Sub => write!(f, "-"),
1367 ArithOp::Mul => write!(f, "*"),
1368 ArithOp::Div => write!(f, "/"),
1369 }
1370 }
1371}
1372
1373fn format_compiled_math(ops: &[MathOp]) -> String {
1378 let mut stack: Vec<String> = Vec::new();
1379 for op in ops {
1380 match op {
1381 MathOp::PushConst(v) => stack.push(format!("{}", v)),
1382 MathOp::LoadVar(name) => stack.push(format!("${}", name)),
1383 MathOp::LoadEnv(key) => stack.push(format!("env:{}", key)),
1384 MathOp::LoadKeyPath { base, keys } => {
1385 let mut s = format!("${}", base);
1386 for key in keys {
1387 s.push('.');
1388 s.push_str(key);
1389 }
1390 stack.push(s);
1391 }
1392 MathOp::Call { name, arity } => {
1393 let mut args = Vec::new();
1394 for _ in 0..*arity {
1395 args.push(stack.pop().unwrap_or_else(|| "<underflow>".to_string()));
1396 }
1397 args.reverse();
1398 stack.push(format!("{}({})", name, args.join(", ")));
1399 }
1400 MathOp::Inspect(name) => stack.push(format!("INSPECT(${})", name)),
1401 MathOp::Neg => {
1402 let inner = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1403 stack.push(format!("(-{})", inner));
1404 }
1405 MathOp::Add => push_bin(&mut stack, "+"),
1406 MathOp::Sub => push_bin(&mut stack, "-"),
1407 MathOp::Mul => push_bin(&mut stack, "*"),
1408 MathOp::Div => push_bin(&mut stack, "/"),
1409 MathOp::Lt => push_bin(&mut stack, "<"),
1410 MathOp::Le => push_bin(&mut stack, "<="),
1411 MathOp::Gt => push_bin(&mut stack, ">"),
1412 MathOp::Ge => push_bin(&mut stack, ">="),
1413 MathOp::Eq => push_bin(&mut stack, "=="),
1414 MathOp::Ne => push_bin(&mut stack, "!="),
1415 }
1416 }
1417 if stack.len() == 1 {
1418 let mut items = stack;
1419 items.pop().unwrap_or_else(|| "<empty>".to_string())
1420 } else {
1421 stack.join(" ")
1422 }
1423}
1424
1425fn push_bin(stack: &mut Vec<String>, op: &str) {
1426 let right = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1427 let left = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1428 stack.push(format!("({} {} {})", left, op, right));
1429}
1430
1431impl fmt::Display for LogicalOp {
1432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1433 match self {
1434 LogicalOp::And => write!(f, "&&"),
1435 LogicalOp::Or => write!(f, "||"),
1436 }
1437 }
1438}
1439
1440enum GuardDisplayContext {
1441 Root,
1442 InAnyArg,
1443 InNot,
1444 InAll,
1445}
1446
1447impl GuardExpr {
1448 fn fmt_with_ctx(&self, f: &mut fmt::Formatter<'_>, ctx: GuardDisplayContext) -> fmt::Result {
1449 match self {
1450 GuardExpr::Predicate(guard) => write!(f, "{}", guard),
1451 GuardExpr::All(children) => {
1452 let wrap = matches!(
1453 ctx,
1454 GuardDisplayContext::InAnyArg | GuardDisplayContext::InNot
1455 ) && children.len() > 1;
1456 if wrap {
1457 write!(f, "(")?;
1458 }
1459 for (i, child) in children.iter().enumerate() {
1460 if i > 0 {
1461 write!(f, ", ")?;
1462 }
1463 child.fmt_with_ctx(f, GuardDisplayContext::InAll)?;
1464 }
1465 if wrap {
1466 write!(f, ")")?;
1467 }
1468 Ok(())
1469 }
1470 GuardExpr::Or(children) => {
1471 write!(f, "any(")?;
1472 for (i, child) in children.iter().enumerate() {
1473 if i > 0 {
1474 write!(f, ", ")?;
1475 }
1476 child.fmt_with_ctx(f, GuardDisplayContext::InAnyArg)?;
1477 }
1478 write!(f, ")")
1479 }
1480 GuardExpr::Not(child) => {
1481 write!(f, "not(")?;
1482 child.fmt_with_ctx(f, GuardDisplayContext::InNot)?;
1483 write!(f, ")")
1484 }
1485 }
1486 }
1487}
1488
1489impl fmt::Display for GuardExpr {
1490 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1491 self.fmt_with_ctx(f, GuardDisplayContext::Root)
1492 }
1493}
1494
1495impl fmt::Display for Step {
1496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1497 if let Some(expr) = &self.guard {
1498 write!(f, "[{}] ", expr)?;
1499 }
1500 write!(f, "{}", self.kind)
1501 }
1502}
1503
1504#[cfg(test)]
1505mod tests {
1506 use super::*;
1507 #[test]
1515 fn statement_keywords_match_backend() {
1516 for kw in STRUCTURAL_KEYWORDS {
1524 let via_backend = crate::parse_script(kw, crate::commands::lower_command);
1525 let via_lowering =
1526 crate::commands::lower_command(kw, Vec::new()).map(|kind| crate::Step {
1527 guard: None,
1528 kind,
1529 scope_enter: 0,
1530 scope_exit: 0,
1531 line: 0,
1532 col: 0,
1533 });
1534 match (via_backend, via_lowering) {
1535 (Ok(_), _) => {}
1536 (Err(a), Err(b)) => {
1537 assert_eq!(
1538 a.kind(),
1539 b.kind(),
1540 "backend kind drift for bare keyword {kw}: {a} vs {b}"
1541 );
1542 }
1543 (Err(a), Ok(_)) => {
1544 panic!("backend rejects bare keyword {kw} that lowering accepts: {a}")
1545 }
1546 }
1547 }
1548 for head in [
1552 "LET",
1553 "RETURN",
1554 "BREAK",
1555 "CONTINUE",
1556 "IF",
1557 "FOR",
1558 "WHILE",
1559 "FUNC",
1560 "REMOTE",
1561 "INHERIT_ENV",
1562 "WITH_IO",
1563 "ASYNC",
1564 "TIMEOUT",
1565 "ISOLATED",
1566 "AWAIT",
1567 "CANCEL",
1568 "RUN",
1569 "IMPORT",
1570 "EXPORT",
1571 "TYPE",
1572 ] {
1573 assert!(
1574 STRUCTURAL_KEYWORDS.contains(&head)
1575 || crate::all_metadata().iter().any(|m| m.name == head),
1576 "structural head {head} is not registered"
1577 );
1578 }
1579 }
1580
1581 #[test]
1585 fn command_names_group_by_category() {
1586 for command in COMMANDS {
1587 let name = command.as_str();
1588 let Some((prefix, _)) = name.split_once('_') else {
1589 continue;
1590 };
1591 assert!(
1592 COMMAND_CATEGORIES.contains(&prefix),
1593 "command {name} introduces unregistered category {prefix}; add it to COMMAND_CATEGORIES"
1594 );
1595 }
1596 }
1597
1598 #[test]
1606 fn registry_commands_all_parse() {
1607 for meta in crate::all_metadata() {
1608 if !meta.in_index || STRUCTURAL_KEYWORDS.contains(&meta.name) {
1609 continue;
1610 }
1611 assert!(
1612 Command::parse(meta.name).is_some(),
1613 "registry command {} has no Command::parse arm",
1614 meta.name
1615 );
1616 }
1617 }
1618}
1619
1620#[cfg(test)]
1621mod guard_analysis_tests {
1622 use super::*;
1623
1624 fn attr(ns: Ns, key: Option<&str>, val: Option<&str>) -> GuardExpr {
1625 GuardExpr::Predicate(Guard::Attr {
1626 ns,
1627 key: key.map(str::to_string),
1628 val: val.map(str::to_string),
1629 })
1630 }
1631
1632 fn os(value: &str) -> GuardExpr {
1633 attr(Ns::Os, None, Some(value))
1634 }
1635
1636 fn arch(value: &str) -> GuardExpr {
1637 attr(Ns::Arch, None, Some(value))
1638 }
1639
1640 fn unix() -> GuardExpr {
1643 GuardExpr::Or(vec![os("macos"), os("linux")])
1644 }
1645
1646 fn windows() -> GuardExpr {
1647 os("windows")
1648 }
1649
1650 fn env_eq(var: &str, value: &str) -> GuardExpr {
1651 attr(Ns::Env, Some(var), Some(value))
1652 }
1653
1654 fn not(expr: GuardExpr) -> GuardExpr {
1655 GuardExpr::Not(Box::new(expr))
1656 }
1657
1658 #[test]
1662 fn partition_negations_are_jointly_dead() {
1663 let os_exhausted = GuardExpr::All(vec![not(os("macos")), not(os("linux")), not(windows())]);
1664 assert!(
1665 !guard_satisfiable(&os_exhausted),
1666 "no host is outside `macos`/`linux`/`windows`"
1667 );
1668 let os_partial = GuardExpr::All(vec![not(os("macos")), not(os("linux"))]);
1670 assert!(guard_satisfiable(&os_partial), "`windows` is still open");
1671 let bool_exhausted = GuardExpr::All(vec![
1673 not(attr(Ns::Bool, None, Some("true"))),
1674 not(attr(Ns::Bool, None, Some("false"))),
1675 ]);
1676 assert!(!guard_satisfiable(&bool_exhausted));
1677 let env_open = GuardExpr::All(vec![
1679 not(env_eq("MODE", "dev")),
1680 not(env_eq("MODE", "prod")),
1681 ]);
1682 assert!(guard_satisfiable(&env_open), "MODE may hold a third value");
1683 assert!(guard_satisfiable(¬(unix())));
1685 }
1686
1687 #[test]
1690 fn unix_alias_is_os_disjunction() {
1691 assert!(!guards_overlap(Some(&unix()), Some(&windows())));
1692 assert!(guards_overlap(Some(&unix()), Some(&os("macos"))));
1693 let covered = GuardExpr::All(vec![GuardExpr::Not(Box::new(unix())), not(windows())]);
1696 assert!(!guard_satisfiable(&covered));
1697 }
1698
1699 #[test]
1703 fn arch_guards_decide_by_value() {
1704 assert!(!guards_overlap(
1705 Some(&arch("x86_64")),
1706 Some(&arch("aarch64"))
1707 ));
1708 assert!(guards_overlap(Some(&arch("x86_64")), Some(&arch("x86_64"))));
1709 assert!(guards_overlap(Some(&arch("aarch64")), Some(&os("macos"))));
1710 let exhausted = GuardExpr::All(ARCH_VALUES.iter().map(|value| not(arch(value))).collect());
1711 assert!(!guard_satisfiable(&exhausted));
1712 let host = attr(Ns::Arch, None, Some(ARCH_TARGET));
1714 assert!(guard_expr_allows(&host, &HashMap::new()));
1715 }
1716
1717 #[test]
1721 fn platform_overlap_matrix_is_exhaustive() {
1722 let cases = [
1723 ("macos", "macos", true),
1724 ("macos", "linux", false),
1725 ("macos", "windows", false),
1726 ("linux", "linux", true),
1727 ("linux", "windows", false),
1728 ("windows", "windows", true),
1729 ];
1730 for (v1, v2, expected) in cases {
1731 let left = os(v1);
1732 let right = os(v2);
1733 assert_eq!(
1734 guards_overlap(Some(&left), Some(&right)),
1735 expected,
1736 "os:{v1} vs os:{v2}"
1737 );
1738 }
1739 }
1740
1741 #[test]
1744 fn disjoint_pairs_never_cofire_here() {
1745 let macos = os("macos");
1746 let holds = |expr: &GuardExpr| guard_expr_allows(expr, &HashMap::new());
1747 assert!(
1748 !(holds(&macos) && holds(&windows())),
1749 "os:macos and os:windows co-fired"
1750 );
1751 }
1752
1753 #[test]
1754 fn overlap_follows_namespace_semantics() {
1755 assert!(!guards_overlap(Some(&windows()), Some(&unix())));
1757 assert!(!guards_overlap(Some(&os("macos")), Some(&os("linux"))));
1758 assert!(guards_overlap(None, Some(&windows())));
1760 assert!(guards_overlap(None, None));
1761 let dead = GuardExpr::All(vec![os("macos"), windows()]);
1763 assert!(!guard_satisfiable(&dead));
1764 assert!(!guards_overlap(Some(&dead), Some(&os("macos"))));
1765 assert!(guard_valid(&GuardExpr::Predicate(Guard::Attr {
1766 ns: Ns::Bool,
1767 key: None,
1768 val: Some("true".to_string()),
1769 })));
1770 assert!(!guard_valid(&unix()));
1771 }
1772
1773 #[test]
1774 fn env_value_conflicts_decide_without_enumeration() {
1775 let fast = env_eq("MODE", "fast");
1776 let slow = env_eq("MODE", "slow");
1777 assert!(
1778 !guards_overlap(Some(&fast), Some(&slow)),
1779 "same key distinct values are disjoint"
1780 );
1781 let also_fast = env_eq("MODE", "fast");
1782 assert!(guards_overlap(Some(&fast), Some(&also_fast)));
1783 let bare = attr(Ns::Env, Some("MODE"), None);
1785 assert!(guards_overlap(Some(&bare), Some(&fast)));
1786 }
1787}
1788
1789#[cfg(test)]
1790mod guard_algebra_tests {
1791 use super::*;
1792
1793 fn os(value: &str) -> GuardExpr {
1794 GuardExpr::Predicate(Guard::Attr {
1795 ns: Ns::Os,
1796 key: None,
1797 val: Some(value.to_string()),
1798 })
1799 }
1800
1801 #[test]
1802 fn or_distributes_over_disjointness() {
1803 fn env_eq(var: &str, value: &str) -> GuardExpr {
1804 GuardExpr::Predicate(Guard::Attr {
1805 ns: Ns::Env,
1806 key: Some(var.to_string()),
1807 val: Some(value.to_string()),
1808 })
1809 }
1810 let mixed = GuardExpr::Or(vec![env_eq("MODE", "dev"), env_eq("MODE", "prod")]);
1813 assert!(!mixed.is_disjoint_from(&env_eq("MODE", "dev")));
1814 assert!(mixed.is_disjoint_from(&env_eq("MODE", "test")));
1816 let cross = GuardExpr::Or(vec![env_eq("MODE", "dev")]);
1818 let platform = os("windows");
1819 assert!(!cross.is_disjoint_from(&platform));
1820 }
1821
1822 #[test]
1823 fn all_distributes_over_disjointness() {
1824 let stacked = GuardExpr::All(vec![
1825 os("macos"),
1826 GuardExpr::Or(vec![os("macos"), os("linux")]),
1827 os("windows"),
1828 ]);
1829 assert!(stacked.is_disjoint_from(&os("macos")));
1830 let live = GuardExpr::All(vec![
1833 os("macos"),
1834 GuardExpr::Predicate(Guard::Attr {
1835 ns: Ns::Env,
1836 key: Some("MODE".to_string()),
1837 val: Some("dev".to_string()),
1838 }),
1839 ]);
1840 assert!(!live.is_disjoint_from(&os("macos")));
1841 }
1842
1843 #[test]
1844 fn negation_is_structural_not_syntactic() {
1845 let not_win = GuardExpr::Not(Box::new(os("windows")));
1846 assert!(not_win.is_disjoint_from(&os("windows")));
1847 assert!(os("windows").is_disjoint_from(¬_win));
1848 assert!(!not_win.is_disjoint_from(&os("macos")));
1849 }
1850}