1use std::collections::{HashMap, HashSet};
2use std::fmt;
3use std::sync::Arc;
4
5pub use crate::commands::{AssertTarget, StepKind};
6use crate::constants::{
7 KEYWORD_ASYNC, KEYWORD_AWAIT, KEYWORD_BREAK, KEYWORD_CANCEL, KEYWORD_CONTINUE, KEYWORD_ELSE,
8 KEYWORD_EXPORT, KEYWORD_FOR, KEYWORD_FUNC, KEYWORD_IF, KEYWORD_IMPORT, KEYWORD_LET,
9 KEYWORD_REMOTE, KEYWORD_RETURN, KEYWORD_TYPE, KEYWORD_WHILE,
10};
11
12#[derive(Debug, Clone, Default)]
16pub struct ModuleFuncs {
17 pub functions: HashSet<String>,
19}
20
21#[derive(Debug, Clone, Default)]
26pub struct ModuleTable {
27 pub modules: HashMap<String, Option<ModuleFuncs>>,
28}
29
30impl ModuleTable {
31 pub fn reserved_base_names(&self) -> HashSet<String> {
35 let mut out = HashSet::new();
36 for funcs in self.modules.values().flatten() {
37 out.extend(funcs.functions.iter().cloned());
38 }
39 out
40 }
41}
42
43#[derive(Copy, Clone, Debug, Eq, PartialEq)]
51pub enum Command {
52 InheritEnv,
53 Workdir,
54 Workspace,
55 Env,
56 Echo,
57 Run,
58 Copy,
59 WithIo,
60 CopyGit,
61 HashSha256,
62 Symlink,
63 Mkdir,
64 Install,
65 Archive,
66 Unarchive,
67 Ls,
68 Cwd,
69 Read,
70 ReadLine,
71 Prompt,
72 Write,
73 Append,
74 Remove,
75 Expand,
76 AssertEq,
77 AssertContains,
78 Exit,
79 Async,
80 Timeout,
81 Isolated,
82 Sleep,
83 ListAppend,
84}
85
86pub const COMMANDS: &[Command] = &[
87 Command::InheritEnv,
88 Command::Workdir,
89 Command::Workspace,
90 Command::Env,
91 Command::Echo,
92 Command::Run,
93 Command::Copy,
94 Command::WithIo,
95 Command::CopyGit,
96 Command::HashSha256,
97 Command::Symlink,
98 Command::Mkdir,
99 Command::Install,
100 Command::Archive,
101 Command::Unarchive,
102 Command::Ls,
103 Command::Cwd,
104 Command::Read,
105 Command::ReadLine,
106 Command::Prompt,
107 Command::Write,
108 Command::Append,
109 Command::Remove,
110 Command::Expand,
111 Command::AssertEq,
112 Command::AssertContains,
113 Command::Exit,
114 Command::Timeout,
115 Command::Isolated,
116 Command::Sleep,
117 Command::ListAppend,
118];
119
120pub const COMMAND_CATEGORIES: &[&str] =
125 &["INHERIT", "WITH", "COPY", "HASH", "READ", "ASSERT", "LIST"];
126
127impl Command {
128 pub const fn as_str(self) -> &'static str {
129 match self {
130 Command::InheritEnv => "INHERIT_ENV",
131 Command::Workdir => "WORKDIR",
132 Command::Workspace => "WORKSPACE",
133 Command::Env => "ENV",
134 Command::Echo => "ECHO",
135 Command::Run => "RUN",
136 Command::Copy => "COPY",
137 Command::WithIo => "WITH_IO",
138 Command::CopyGit => "COPY_GIT",
139 Command::HashSha256 => "HASH_SHA256",
140 Command::Symlink => "SYMLINK",
141 Command::Mkdir => "MKDIR",
142 Command::Install => "INSTALL",
143 Command::Archive => "ARCHIVE",
144 Command::Unarchive => "UNARCHIVE",
145 Command::Ls => "LS",
146 Command::Cwd => "CWD",
147 Command::Read => "READ",
148 Command::ReadLine => "READ_LINE",
149 Command::Prompt => "PROMPT",
150 Command::Write => "WRITE",
151 Command::Append => "APPEND",
152 Command::Remove => "REMOVE",
153 Command::Expand => "EXPAND",
154 Command::AssertEq => "ASSERT_EQ",
155 Command::AssertContains => "ASSERT_CONTAINS",
156 Command::Exit => "EXIT",
157 Command::Async => "ASYNC",
158 Command::Timeout => "TIMEOUT",
159 Command::Isolated => "ISOLATED",
160 Command::Sleep => "SLEEP",
161 Command::ListAppend => "LIST_APPEND",
162 }
163 }
164
165 pub const fn syntax(self) -> &'static str {
166 match self {
167 Command::InheritEnv => "INHERIT_ENV [KEY1, KEY2, ...]",
168 Command::Workdir => "WORKDIR <path>",
169 Command::Workspace => "WORKSPACE SNAPSHOT|LOCAL|CACHE|SYSTEM [--local]",
170 Command::Env => "ENV KEY=value",
171 Command::Echo => "ECHO <message>",
172 Command::Run => "RUN <command...> | RUN [\"exe\", \"arg\", ...]",
173 Command::Copy => "COPY [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>",
174 Command::CopyGit => "COPY_GIT [--include-dirty] <rev> <src> <dst>",
175 Command::WithIo => "WITH_IO [bindings] [command | { block }]",
176 Command::HashSha256 => "HASH_SHA256 <path>",
177 Command::Symlink => {
178 "SYMLINK [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>"
179 }
180 Command::Mkdir => "MKDIR <path>",
181 Command::Install => "INSTALL <source> <dest>",
182 Command::Archive => "ARCHIVE [--raw] <src> <dst>",
183 Command::Unarchive => "UNARCHIVE <src> <dst> [--max-bytes <bytes>]",
184 Command::Ls => "LS [<path>]",
185 Command::Cwd => "CWD",
186 Command::Read => "READ [<path>]",
187 Command::ReadLine => "READ_LINE $var",
188 Command::Prompt => "PROMPT $var <message> [<default>]",
189 Command::Write => "WRITE <path> [<contents>]",
190 Command::Append => "APPEND <path> [<contents>]",
191 Command::Remove => "REMOVE [--recursive] <path>",
192 Command::Expand => "EXPAND [<path>] [<KEY=val> ...]",
193 Command::AssertEq => "ASSERT_EQ [--hash <sha256>] <actual> <expected>",
194 Command::AssertContains => "ASSERT_CONTAINS <haystack> <needle>",
195 Command::Exit => "EXIT <code>",
196 Command::Async => "ASYNC <command...> | ASYNC { <commands> }",
197 Command::Timeout => {
198 "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> }"
199 }
200 Command::Isolated => {
201 "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>"
202 }
203 Command::Sleep => "SLEEP <duration>",
204 Command::ListAppend => "LIST_APPEND $list <item>",
205 }
206 }
207
208 pub const fn expects_inner_command(self) -> bool {
209 matches!(
210 self,
211 Command::WithIo | Command::Async | Command::Timeout | Command::Isolated
212 )
213 }
214
215 pub fn parse(s: &str) -> Option<Self> {
216 match s {
217 "INHERIT_ENV" => Some(Command::InheritEnv),
218 "WORKDIR" => Some(Command::Workdir),
219 "WORKSPACE" => Some(Command::Workspace),
220 "ENV" => Some(Command::Env),
221 "ECHO" => Some(Command::Echo),
222 "RUN" => Some(Command::Run),
223 "COPY" => Some(Command::Copy),
224 "WITH_IO" => Some(Command::WithIo),
225 "COPY_GIT" => Some(Command::CopyGit),
226 "HASH_SHA256" => Some(Command::HashSha256),
227 "SYMLINK" => Some(Command::Symlink),
228 "MKDIR" => Some(Command::Mkdir),
229 "INSTALL" => Some(Command::Install),
230 "ARCHIVE" => Some(Command::Archive),
231 "UNARCHIVE" => Some(Command::Unarchive),
232 "LS" => Some(Command::Ls),
233 "CWD" => Some(Command::Cwd),
234 "READ" => Some(Command::Read),
235 "READ_LINE" => Some(Command::ReadLine),
236 "PROMPT" => Some(Command::Prompt),
237 "WRITE" => Some(Command::Write),
238 "APPEND" => Some(Command::Append),
239 "REMOVE" => Some(Command::Remove),
240 "EXPAND" => Some(Command::Expand),
241 "ASSERT_EQ" => Some(Command::AssertEq),
242 "ASSERT_CONTAINS" => Some(Command::AssertContains),
243 "EXIT" => Some(Command::Exit),
244 "ASYNC" => Some(Command::Async),
245 "TIMEOUT" => Some(Command::Timeout),
246 "ISOLATED" => Some(Command::Isolated),
247 "SLEEP" => Some(Command::Sleep),
248 "LIST_APPEND" => Some(Command::ListAppend),
249 _ => None,
250 }
251 }
252
253 pub(crate) fn is_statement_keyword(s: &str) -> bool {
258 Command::parse(s).is_some() || STRUCTURAL_KEYWORDS.contains(&s)
259 }
260}
261
262pub const STRUCTURAL_KEYWORDS: &[&str] = &[
268 KEYWORD_LET,
269 KEYWORD_FOR,
270 KEYWORD_IF,
271 KEYWORD_ELSE,
272 KEYWORD_ASYNC,
273 KEYWORD_AWAIT,
274 KEYWORD_CANCEL,
275 KEYWORD_FUNC,
276 KEYWORD_RETURN,
277 KEYWORD_WHILE,
278 KEYWORD_BREAK,
279 KEYWORD_CONTINUE,
280 KEYWORD_REMOTE,
281 KEYWORD_IMPORT,
282 KEYWORD_EXPORT,
283 KEYWORD_TYPE,
284];
285
286pub const CLAUSE_KEYWORDS: &[&str] = &["IN"];
291
292#[derive(Debug, Clone, Eq, PartialEq)]
305pub enum Guard {
306 Attr {
307 ns: Ns,
308 key: Option<String>,
309 val: Option<String>,
310 },
311}
312
313#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
317pub enum Ns {
318 Os,
319 Arch,
320 Bool,
321 Env,
322}
323
324impl fmt::Display for Ns {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 match self {
327 Ns::Os => write!(f, "os"),
328 Ns::Arch => write!(f, "arch"),
329 Ns::Bool => write!(f, "bool"),
330 Ns::Env => write!(f, "env"),
331 }
332 }
333}
334
335pub const ARCH_VALUES: &[&str] = &[
339 "aarch64",
340 "arm",
341 "arm64ec",
342 "avr",
343 "bpf",
344 "csky",
345 "hexagon",
346 "loongarch32",
347 "loongarch64",
348 "mips",
349 "mips32r6",
350 "mips64",
351 "mips64r6",
352 "msp430",
353 "nvptx64",
354 "powerpc",
355 "powerpc64",
356 "riscv32",
357 "riscv64",
358 "s390x",
359 "sparc",
360 "sparc64",
361 "wasm32",
362 "wasm64",
363 "x86",
364 "x86_64",
365 "xtensa",
366];
367
368#[derive(Debug, Clone, Eq, PartialEq)]
369pub enum GuardExpr {
370 Predicate(Guard),
371 All(Vec<GuardExpr>),
372 Or(Vec<GuardExpr>),
373 Not(Box<GuardExpr>),
374}
375
376impl GuardExpr {
377 pub fn all(exprs: Vec<GuardExpr>) -> GuardExpr {
378 let mut flat = Vec::new();
379 for expr in exprs {
380 match expr {
381 GuardExpr::All(children) => flat.extend(children),
382 other => flat.push(other),
383 }
384 }
385 match flat.len() {
386 0 => panic!("GuardExpr::all requires at least one expression"),
387 1 => flat.into_iter().next().unwrap(),
388 _ => GuardExpr::All(flat),
389 }
390 }
391
392 pub fn or(exprs: Vec<GuardExpr>) -> GuardExpr {
393 let mut flat = Vec::new();
394 for expr in exprs {
395 match expr {
396 GuardExpr::Or(children) => flat.extend(children),
397 other => flat.push(other),
398 }
399 }
400 match flat.len() {
401 0 => panic!("GuardExpr::or requires at least one expression"),
402 1 => flat.into_iter().next().unwrap(),
403 _ => GuardExpr::Or(flat),
404 }
405 }
406
407 pub fn invert(expr: GuardExpr) -> GuardExpr {
408 match expr {
409 GuardExpr::Not(inner) => *inner,
410 other => GuardExpr::Not(Box::new(other)),
411 }
412 }
413}
414
415impl std::ops::Not for GuardExpr {
416 type Output = GuardExpr;
417
418 fn not(self) -> GuardExpr {
419 match self {
420 GuardExpr::Not(inner) => *inner,
421 other => GuardExpr::Not(Box::new(other)),
422 }
423 }
424}
425
426impl From<Guard> for GuardExpr {
427 fn from(guard: Guard) -> Self {
428 GuardExpr::Predicate(guard)
429 }
430}
431
432#[derive(Debug, Clone, PartialEq)]
434pub enum Arg {
435 String(String, bool),
439 Expr(Expr),
441 Parts(Vec<ArgPart>),
445}
446
447#[derive(Debug, Clone, PartialEq)]
449pub enum ArgPart {
450 Text(String, bool),
453 Expr(Expr),
455}
456
457impl Arg {
458 pub fn as_str(&self) -> &str {
459 match self {
460 Arg::String(s, _) => s,
461 Arg::Expr(_) | Arg::Parts(_) => "",
464 }
465 }
466
467 pub fn render(&self) -> String {
471 match self {
472 Arg::String(s, _) => s.clone(),
473 Arg::Expr(e) => e.to_string(),
474 Arg::Parts(parts) => parts.iter().map(ArgPart::render).collect(),
475 }
476 }
477
478 pub fn is_quoted(&self) -> bool {
479 matches!(self, Arg::String(_, true))
480 }
481}
482
483impl ArgPart {
484 pub fn render(&self) -> String {
485 match self {
486 ArgPart::Text(s, _) => s.clone(),
487 ArgPart::Expr(e) => e.to_string(),
488 }
489 }
490}
491
492impl From<String> for Arg {
493 fn from(s: String) -> Self {
494 Arg::String(s, false)
495 }
496}
497
498impl From<&str> for Arg {
499 fn from(s: &str) -> Self {
500 Arg::String(s.to_string(), false)
501 }
502}
503
504impl std::fmt::Display for Arg {
505 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
506 match self {
507 Arg::String(s, _) => write!(f, "{}", s),
508 Arg::Expr(e) => write!(f, "{}", e),
509 Arg::Parts(parts) => {
510 for part in parts {
511 match part {
512 ArgPart::Text(s, _) => write!(f, "{}", s)?,
513 ArgPart::Expr(e) => write!(f, "{}", e)?,
514 }
515 }
516 Ok(())
517 }
518 }
519 }
520}
521
522impl AsRef<str> for Arg {
523 fn as_ref(&self) -> &str {
524 self.as_str()
525 }
526}
527
528impl PartialEq<str> for Arg {
529 fn eq(&self, other: &str) -> bool {
530 self.as_str() == other
531 }
532}
533
534impl PartialEq<&str> for Arg {
535 fn eq(&self, other: &&str) -> bool {
536 self.as_str() == *other
537 }
538}
539
540#[derive(Debug, Clone, Copy, Eq, PartialEq)]
541pub enum IoStream {
542 Stdin,
543 Stdout,
544 Stderr,
545}
546
547#[derive(Debug, Clone, Eq, PartialEq)]
548pub struct IoBinding {
549 pub stream: IoStream,
550 pub pipe: Option<PipeTarget>,
551}
552
553#[derive(Debug, Clone, Eq, PartialEq)]
556pub enum PipeTarget {
557 Var(String),
558}
559
560pub use crate::value::{
564 OxDockType, SemaphoreState, TypeDescriptor, Value, ValuePayload, clone_boxed, clone_copy,
565 clone_shared, drop_boxed, drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed,
566 fmt_inline, fmt_shared, load_inline, startup_descriptors, store_inline, type_anchor,
567 unshare_boxed, unshare_inline, unshare_shared,
568};
569
570#[derive(Debug, Clone, Copy, Eq, PartialEq)]
571pub enum CompareOp {
572 Eq,
573 Ne,
574 Lt,
575 Le,
576 Gt,
577 Ge,
578}
579
580#[derive(Debug, Clone, Copy, Eq, PartialEq)]
581pub enum ArithOp {
582 Add,
583 Sub,
584 Mul,
585 Div,
586}
587
588#[derive(Debug, Clone, PartialEq)]
597pub enum MathOp {
598 PushConst(Value),
599 LoadVar(String),
600 LoadEnv(String),
601 LoadKeyPath { base: String, keys: Vec<String> },
602 Call { name: String, arity: usize },
603 Inspect(String),
604 Neg,
605 Add,
606 Sub,
607 Mul,
608 Div,
609 Lt,
610 Le,
611 Gt,
612 Ge,
613 Eq,
614 Ne,
615}
616
617#[derive(Debug, Clone, Copy, Eq, PartialEq)]
618pub enum LogicalOp {
619 And,
620 Or,
621}
622
623#[derive(Debug, Clone, PartialEq)]
624pub enum Expr {
625 Literal(Value),
626 Var(String),
627 Env(String),
630 KeyPath {
631 base: String,
632 keys: Vec<String>,
633 },
634 List(Vec<Expr>),
635 Map(Vec<(String, Expr)>),
636 Block(Vec<Step>),
641 Call {
642 name: String,
643 args: Vec<Expr>,
644 },
645 Inspect(String),
650 Compare {
651 op: CompareOp,
652 left: Box<Expr>,
653 right: Box<Expr>,
654 },
655 Arithmetic {
656 op: ArithOp,
657 left: Box<Expr>,
658 right: Box<Expr>,
659 },
660 CompiledMath(Vec<MathOp>),
663 FreshPipe,
669 UnsignedIntBoundary(u64),
673 Not(Box<Expr>),
674 Logical {
675 op: LogicalOp,
676 left: Box<Expr>,
677 right: Box<Expr>,
678 },
679}
680
681#[derive(Debug, Clone, PartialEq)]
682pub struct Step {
683 pub guard: Option<GuardExpr>,
684 pub kind: StepKind,
685 pub scope_enter: usize,
686 pub scope_exit: usize,
687}
688
689impl Expr {
690 pub fn walk(&self, f: &mut impl FnMut(&Expr)) {
697 f(self);
698 match self {
699 Expr::Literal(_)
700 | Expr::Var(_)
701 | Expr::Env(_)
702 | Expr::KeyPath { .. }
703 | Expr::Inspect(_)
704 | Expr::FreshPipe
705 | Expr::UnsignedIntBoundary(_) => {}
706 Expr::Call { args, .. } => {
707 for arg in args {
708 arg.walk(f);
709 }
710 }
711 Expr::List(items) => {
712 for item in items {
713 item.walk(f);
714 }
715 }
716 Expr::Map(entries) => {
717 for (_, value) in entries {
718 value.walk(f);
719 }
720 }
721 Expr::Block(steps) => {
722 for step in steps {
723 step.kind.walk_step_exprs(f);
724 }
725 }
726 Expr::Compare { left, right, .. }
727 | Expr::Arithmetic { left, right, .. }
728 | Expr::Logical { left, right, .. } => {
729 left.walk(f);
730 right.walk(f);
731 }
732 Expr::CompiledMath(_) => {}
733 Expr::Not(inner) => inner.walk(f),
734 }
735 }
736}
737
738#[derive(Debug, Clone, Eq, PartialEq)]
739pub enum WorkspaceTarget {
740 Snapshot,
741 Local,
742 Cache { local: bool },
743 System,
744}
745
746pub trait EnvLookup {
747 fn get_env(&self, key: &str) -> Option<&str>;
748}
749
750impl EnvLookup for HashMap<String, String> {
751 fn get_env(&self, key: &str) -> Option<&str> {
752 self.get(key).map(|s| s.as_str())
753 }
754}
755
756impl EnvLookup for Arc<HashMap<String, String>> {
757 fn get_env(&self, key: &str) -> Option<&str> {
758 (**self).get_env(key)
759 }
760}
761
762pub fn guard_allows(guard: &Guard, env: &impl EnvLookup) -> bool {
763 let Guard::Attr { ns, key, val } = guard;
764 match ns {
765 Ns::Os => match val.as_deref() {
766 Some("macos") => platform_is_macos(),
767 Some("linux") => platform_is_linux(),
768 Some("windows") => platform_is_windows(),
769 _ => false,
770 },
771 Ns::Arch => match val.as_deref() {
772 Some(want) => ARCH_TARGET == want,
773 None => false,
774 },
775 Ns::Bool => val
776 .as_deref()
777 .map(|v| v.parse::<bool>().unwrap_or(false))
778 .unwrap_or(false),
779 Ns::Env => match key.as_deref() {
780 Some(var) => match val {
781 None => env.get_env(var).map(|v| !v.is_empty()).unwrap_or(false),
782 Some(want) => env
783 .get_env(var)
784 .map(|v| v == want.as_str())
785 .unwrap_or(false),
786 },
787 None => false,
789 },
790 }
791}
792
793#[allow(clippy::disallowed_macros)]
796fn platform_is_windows() -> bool {
797 cfg!(windows)
798}
799
800#[allow(clippy::disallowed_macros)]
802fn platform_is_macos() -> bool {
803 cfg!(target_os = "macos")
804}
805
806#[allow(clippy::disallowed_macros)]
808fn platform_is_linux() -> bool {
809 cfg!(target_os = "linux")
810}
811
812const ARCH_TARGET: &str = std::env::consts::ARCH;
815
816pub fn guard_expr_allows(expr: &GuardExpr, env: &impl EnvLookup) -> bool {
817 match expr {
818 GuardExpr::Predicate(guard) => guard_allows(guard, env),
819 GuardExpr::All(children) => children.iter().all(|g| guard_expr_allows(g, env)),
820 GuardExpr::Or(children) => children.iter().any(|g| guard_expr_allows(g, env)),
821 GuardExpr::Not(child) => !guard_expr_allows(child, env),
822 }
823}
824
825pub fn guard_option_allows(expr: Option<&GuardExpr>, env: &impl EnvLookup) -> bool {
826 match expr {
827 Some(e) => guard_expr_allows(e, env),
828 None => true,
829 }
830}
831
832impl Guard {
833 pub fn is_disjoint_from(&self, other: &Self) -> bool {
842 match (self, other) {
843 (
844 Guard::Attr {
845 ns: n1,
846 key: k1,
847 val: Some(v1),
848 },
849 Guard::Attr {
850 ns: n2,
851 key: k2,
852 val: Some(v2),
853 },
854 ) => n1 == n2 && k1 == k2 && v1 != v2,
855 _ => false,
856 }
857 }
858}
859
860impl GuardExpr {
861 pub fn is_disjoint_from(&self, other: &Self) -> bool {
867 match (self, other) {
868 (x, GuardExpr::Not(inner)) | (GuardExpr::Not(inner), x) => {
876 x == inner.as_ref() || unset_excludes(x, inner.as_ref())
877 }
878 (GuardExpr::Predicate(p1), GuardExpr::Predicate(p2)) => p1.is_disjoint_from(p2),
880 (GuardExpr::Or(arms), other) | (other, GuardExpr::Or(arms)) => {
882 arms.iter().all(|arm| arm.is_disjoint_from(other))
883 }
884 (GuardExpr::All(arms), other) | (other, GuardExpr::All(arms)) => {
886 arms.iter().any(|arm| arm.is_disjoint_from(other))
887 }
888 }
889 }
890}
891
892fn conjuncts(expr: &GuardExpr) -> Vec<&GuardExpr> {
896 match expr {
897 GuardExpr::All(items) => items.iter().collect(),
898 single => vec![single],
899 }
900}
901
902fn closed_domain_values(ns: Ns, key: Option<&str>) -> Option<&'static [&'static str]> {
909 match (ns, key) {
910 (Ns::Bool, None) => Some(&["true", "false"]),
911 (Ns::Os, None) => Some(&["macos", "linux", "windows"]),
912 (Ns::Arch, None) => Some(ARCH_VALUES),
913 _ => None,
914 }
915}
916
917#[derive(Clone)]
920enum DnfLit {
921 Pos(Guard),
922 Neg(Guard),
923}
924
925impl DnfLit {
926 fn as_expr(&self) -> GuardExpr {
927 match self {
928 DnfLit::Pos(guard) => GuardExpr::Predicate(guard.clone()),
929 DnfLit::Neg(guard) => GuardExpr::Not(Box::new(GuardExpr::Predicate(guard.clone()))),
930 }
931 }
932}
933
934const MAX_DNF_DISJUNCTS: usize = 64;
939
940fn dnf_push(expr: &GuardExpr, polarity: bool, out: &mut Vec<Vec<DnfLit>>) -> bool {
945 match (expr, polarity) {
946 (GuardExpr::Predicate(guard), true) => {
947 for disjunct in out.iter_mut() {
948 disjunct.push(DnfLit::Pos(guard.clone()));
949 }
950 true
951 }
952 (GuardExpr::Predicate(guard), false) => {
953 for disjunct in out.iter_mut() {
954 disjunct.push(DnfLit::Neg(guard.clone()));
955 }
956 true
957 }
958 (GuardExpr::All(children), true) | (GuardExpr::Or(children), false) => {
959 for child in children {
961 if !dnf_push(child, polarity, out) {
962 return false;
963 }
964 }
965 true
966 }
967 (GuardExpr::Or(children), true) | (GuardExpr::All(children), false) => {
968 let mut forked = Vec::new();
970 for disjunct in out.drain(..) {
971 for child in children {
972 let mut branch = vec![disjunct.clone()];
973 if !dnf_push(child, polarity, &mut branch) {
974 return false;
975 }
976 forked.extend(branch);
977 if forked.len() > MAX_DNF_DISJUNCTS {
978 return false;
979 }
980 }
981 }
982 *out = forked;
983 true
984 }
985 (GuardExpr::Not(inner), _) => dnf_push(inner, !polarity, out),
986 }
987}
988
989fn disjunct_satisfiable(lits: &[DnfLit]) -> bool {
993 for lit in lits {
997 match lit {
998 DnfLit::Pos(Guard::Attr {
999 ns: Ns::Bool, val, ..
1000 }) if val.as_deref() != Some("true") => return false,
1001 DnfLit::Neg(Guard::Attr {
1002 ns: Ns::Bool,
1003 key: None,
1004 val: Some(value),
1005 }) if value == "true" => return false,
1006 _ => {}
1007 }
1008 }
1009 for (index, first) in lits.iter().enumerate() {
1012 for second in &lits[index + 1..] {
1013 if first.as_expr().is_disjoint_from(&second.as_expr()) {
1014 return false;
1015 }
1016 }
1017 }
1018 for lit in lits {
1022 let (ns, key) = match lit {
1023 DnfLit::Neg(Guard::Attr {
1024 ns,
1025 key,
1026 val: Some(_),
1027 }) => (*ns, key.as_deref()),
1028 _ => continue,
1029 };
1030 let Some(domain) = closed_domain_values(ns, key) else {
1031 continue;
1032 };
1033 let exhausted = domain.iter().all(|value| {
1034 lits.iter().any(|other| match other {
1035 DnfLit::Neg(Guard::Attr {
1036 ns: other_ns,
1037 key: other_key,
1038 val: Some(other_val),
1039 }) => *other_ns == ns && other_key.as_deref() == key && other_val == value,
1040 _ => false,
1041 })
1042 });
1043 if exhausted {
1044 return false;
1045 }
1046 }
1047 true
1048}
1049
1050fn conjunction_dead(atoms: &[&GuardExpr]) -> bool {
1057 if atoms.is_empty() {
1058 return false;
1059 }
1060 let mut disjuncts = vec![Vec::new()];
1061 for atom in atoms {
1062 if !dnf_push(atom, true, &mut disjuncts) {
1063 return false;
1064 }
1065 }
1066 !disjuncts
1067 .iter()
1068 .any(|disjunct| disjunct_satisfiable(disjunct))
1069}
1070
1071pub fn guard_satisfiable(expr: &GuardExpr) -> bool {
1073 !conjunction_dead(&conjuncts(expr))
1074}
1075
1076pub fn guard_valid(expr: &GuardExpr) -> bool {
1079 match expr {
1080 GuardExpr::Predicate(Guard::Attr {
1081 ns: Ns::Bool,
1082 val: Some(value),
1083 ..
1084 }) => value.as_str() == "true",
1085 GuardExpr::All(items) => items.iter().all(guard_valid),
1086 GuardExpr::Not(inner) => !guard_satisfiable(inner),
1087 _ => false,
1088 }
1089}
1090
1091pub fn guards_overlap(a: Option<&GuardExpr>, b: Option<&GuardExpr>) -> bool {
1094 match (a, b) {
1095 (None, None) => true,
1096 (Some(x), None) | (None, Some(x)) => guard_satisfiable(x),
1097 (Some(x), Some(y)) => {
1098 let mut atoms = conjuncts(x);
1099 atoms.extend(conjuncts(y));
1100 !conjunction_dead(&atoms)
1101 }
1102 }
1103}
1104
1105fn unset_excludes(x: &GuardExpr, inner: &GuardExpr) -> bool {
1108 match (x, inner) {
1109 (
1110 GuardExpr::Predicate(Guard::Attr {
1111 ns: n2, key: k2, ..
1112 }),
1113 GuardExpr::Predicate(Guard::Attr {
1114 ns: n1,
1115 key: k1,
1116 val: None,
1117 }),
1118 ) => n1 == n2 && k1 == k2,
1119 _ => false,
1120 }
1121}
1122
1123impl fmt::Display for Guard {
1124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1130 match self {
1131 Guard::Attr {
1132 ns: Ns::Env,
1133 key: Some(var),
1134 val: None,
1135 } => write!(f, "env:{var}"),
1136 Guard::Attr {
1137 ns: Ns::Env,
1138 key: Some(var),
1139 val: Some(want),
1140 } => write!(f, "eq(env:{var}, {want})"),
1141 Guard::Attr {
1142 ns,
1143 key: _,
1144 val: Some(value),
1145 } => write!(f, "{ns}:{value}"),
1146 Guard::Attr { ns, key, val: None } => match key {
1147 Some(subject) => write!(f, "{ns}:{subject}"),
1148 None => write!(f, "{ns}"),
1149 },
1150 }
1151 }
1152}
1153
1154impl fmt::Display for WorkspaceTarget {
1155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1156 match self {
1157 WorkspaceTarget::Snapshot => write!(f, "SNAPSHOT"),
1158 WorkspaceTarget::Local => write!(f, "LOCAL"),
1159 WorkspaceTarget::Cache { local: false } => write!(f, "CACHE"),
1160 WorkspaceTarget::Cache { local: true } => write!(f, "CACHE --local"),
1161 WorkspaceTarget::System => write!(f, "SYSTEM"),
1162 }
1163 }
1164}
1165
1166impl fmt::Display for Expr {
1167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1168 match self {
1169 Expr::Literal(v) => write!(f, "{}", v),
1170 Expr::Var(name) => write!(f, "${}", name),
1171 Expr::Env(key) => write!(f, "env:{}", key),
1172 Expr::KeyPath { base, keys } => {
1173 write!(f, "${}", base)?;
1174 for key in keys {
1175 write!(f, ".{}", key)?;
1176 }
1177 Ok(())
1178 }
1179 Expr::Call { name, args } => {
1180 write!(f, "{}(", name)?;
1181 for (i, arg) in args.iter().enumerate() {
1182 if i > 0 {
1183 write!(f, ", ")?;
1184 }
1185 write!(f, "{}", arg)?;
1186 }
1187 write!(f, ")")
1188 }
1189 Expr::Inspect(var) => write!(f, "INSPECT(${})", var),
1190 Expr::List(items) => {
1191 write!(f, "[")?;
1192 for (i, item) in items.iter().enumerate() {
1193 if i > 0 {
1194 write!(f, ", ")?;
1195 }
1196 write!(f, "{}", item)?;
1197 }
1198 write!(f, "]")
1199 }
1200 Expr::Map(entries) => {
1201 write!(f, "{{")?;
1202 for (i, (key, val)) in entries.iter().enumerate() {
1203 if i > 0 {
1204 write!(f, ", ")?;
1205 }
1206 write!(f, "\"{}\": {}", key, val)?;
1207 }
1208 write!(f, "}}")
1209 }
1210 Expr::Block(steps) => {
1211 write!(f, "{{ ")?;
1212 for (i, step) in steps.iter().enumerate() {
1213 if i > 0 {
1214 write!(f, "; ")?;
1215 }
1216 write!(f, "{}", step.kind)?;
1217 }
1218 write!(f, " }}")
1219 }
1220 Expr::Compare { op, left, right } => {
1221 write!(f, "{} {} {}", left, op, right)
1222 }
1223 Expr::Arithmetic { op, left, right } => {
1224 write!(f, "({} {} {})", left, op, right)
1225 }
1226 Expr::CompiledMath(ops) => {
1227 write!(f, "{}", format_compiled_math(ops))
1228 }
1229 Expr::FreshPipe => write!(f, "<fresh pipe>"),
1233 Expr::UnsignedIntBoundary(n) => write!(f, "{}", n),
1234 Expr::Not(inner) => {
1235 match inner.as_ref() {
1238 Expr::Compare { .. } | Expr::Arithmetic { .. } | Expr::CompiledMath(_) => {
1239 write!(f, "!({})", inner)
1240 }
1241 _ => write!(f, "!{}", inner),
1242 }
1243 }
1244 Expr::Logical { op, left, right } => {
1245 write!(f, "({} {} {})", left, op, right)
1246 }
1247 }
1248 }
1249}
1250
1251impl fmt::Display for CompareOp {
1252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1253 match self {
1254 CompareOp::Eq => write!(f, "=="),
1255 CompareOp::Ne => write!(f, "!="),
1256 CompareOp::Lt => write!(f, "<"),
1257 CompareOp::Le => write!(f, "<="),
1258 CompareOp::Gt => write!(f, ">"),
1259 CompareOp::Ge => write!(f, ">="),
1260 }
1261 }
1262}
1263
1264impl fmt::Display for ArithOp {
1265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1266 match self {
1267 ArithOp::Add => write!(f, "+"),
1268 ArithOp::Sub => write!(f, "-"),
1269 ArithOp::Mul => write!(f, "*"),
1270 ArithOp::Div => write!(f, "/"),
1271 }
1272 }
1273}
1274
1275fn format_compiled_math(ops: &[MathOp]) -> String {
1280 let mut stack: Vec<String> = Vec::new();
1281 for op in ops {
1282 match op {
1283 MathOp::PushConst(v) => stack.push(format!("{}", v)),
1284 MathOp::LoadVar(name) => stack.push(format!("${}", name)),
1285 MathOp::LoadEnv(key) => stack.push(format!("env:{}", key)),
1286 MathOp::LoadKeyPath { base, keys } => {
1287 let mut s = format!("${}", base);
1288 for key in keys {
1289 s.push('.');
1290 s.push_str(key);
1291 }
1292 stack.push(s);
1293 }
1294 MathOp::Call { name, arity } => {
1295 let mut args = Vec::new();
1296 for _ in 0..*arity {
1297 args.push(stack.pop().unwrap_or_else(|| "<underflow>".to_string()));
1298 }
1299 args.reverse();
1300 stack.push(format!("{}({})", name, args.join(", ")));
1301 }
1302 MathOp::Inspect(name) => stack.push(format!("INSPECT(${})", name)),
1303 MathOp::Neg => {
1304 let inner = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1305 stack.push(format!("(-{})", inner));
1306 }
1307 MathOp::Add => push_bin(&mut stack, "+"),
1308 MathOp::Sub => push_bin(&mut stack, "-"),
1309 MathOp::Mul => push_bin(&mut stack, "*"),
1310 MathOp::Div => push_bin(&mut stack, "/"),
1311 MathOp::Lt => push_bin(&mut stack, "<"),
1312 MathOp::Le => push_bin(&mut stack, "<="),
1313 MathOp::Gt => push_bin(&mut stack, ">"),
1314 MathOp::Ge => push_bin(&mut stack, ">="),
1315 MathOp::Eq => push_bin(&mut stack, "=="),
1316 MathOp::Ne => push_bin(&mut stack, "!="),
1317 }
1318 }
1319 if stack.len() == 1 {
1320 let mut items = stack;
1321 items.pop().unwrap_or_else(|| "<empty>".to_string())
1322 } else {
1323 stack.join(" ")
1324 }
1325}
1326
1327fn push_bin(stack: &mut Vec<String>, op: &str) {
1328 let right = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1329 let left = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1330 stack.push(format!("({} {} {})", left, op, right));
1331}
1332
1333impl fmt::Display for LogicalOp {
1334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1335 match self {
1336 LogicalOp::And => write!(f, "&&"),
1337 LogicalOp::Or => write!(f, "||"),
1338 }
1339 }
1340}
1341
1342enum GuardDisplayContext {
1343 Root,
1344 InAnyArg,
1345 InNot,
1346 InAll,
1347}
1348
1349impl GuardExpr {
1350 fn fmt_with_ctx(&self, f: &mut fmt::Formatter<'_>, ctx: GuardDisplayContext) -> fmt::Result {
1351 match self {
1352 GuardExpr::Predicate(guard) => write!(f, "{}", guard),
1353 GuardExpr::All(children) => {
1354 let wrap = matches!(
1355 ctx,
1356 GuardDisplayContext::InAnyArg | GuardDisplayContext::InNot
1357 ) && children.len() > 1;
1358 if wrap {
1359 write!(f, "(")?;
1360 }
1361 for (i, child) in children.iter().enumerate() {
1362 if i > 0 {
1363 write!(f, ", ")?;
1364 }
1365 child.fmt_with_ctx(f, GuardDisplayContext::InAll)?;
1366 }
1367 if wrap {
1368 write!(f, ")")?;
1369 }
1370 Ok(())
1371 }
1372 GuardExpr::Or(children) => {
1373 write!(f, "any(")?;
1374 for (i, child) in children.iter().enumerate() {
1375 if i > 0 {
1376 write!(f, ", ")?;
1377 }
1378 child.fmt_with_ctx(f, GuardDisplayContext::InAnyArg)?;
1379 }
1380 write!(f, ")")
1381 }
1382 GuardExpr::Not(child) => {
1383 write!(f, "not(")?;
1384 child.fmt_with_ctx(f, GuardDisplayContext::InNot)?;
1385 write!(f, ")")
1386 }
1387 }
1388 }
1389}
1390
1391impl fmt::Display for GuardExpr {
1392 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1393 self.fmt_with_ctx(f, GuardDisplayContext::Root)
1394 }
1395}
1396
1397impl fmt::Display for Step {
1398 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1399 if let Some(expr) = &self.guard {
1400 write!(f, "[{}] ", expr)?;
1401 }
1402 write!(f, "{}", self.kind)
1403 }
1404}
1405
1406#[cfg(test)]
1407mod tests {
1408 use super::*;
1409 #[test]
1422 fn statement_keywords_match_pest_grammar() {
1423 use pest_meta::{ast::Expr, parser};
1424 use std::collections::{HashMap, HashSet};
1425
1426 let pest_src = include_str!("dsl.pest");
1427 let pairs = parser::parse(parser::Rule::grammar_rules, pest_src)
1428 .expect("dsl.pest must parse as a pest grammar");
1429 let rules = parser::consume_rules(pairs).expect("dsl.pest rules must consume");
1430 let by_name: HashMap<&str, &Expr> = rules
1431 .iter()
1432 .map(|rule| (rule.name.as_str(), &rule.expr))
1433 .collect();
1434
1435 let mut all_literals = HashSet::new();
1436 for rule in &rules {
1437 for node in rule.expr.iter_top_down() {
1438 match node {
1439 Expr::Str(literal) | Expr::Insens(literal) => {
1440 all_literals.insert(literal.clone());
1441 }
1442 _ => {}
1443 }
1444 }
1445 }
1446 for kw in STRUCTURAL_KEYWORDS {
1447 assert!(
1448 all_literals.contains(*kw),
1449 "keyword {kw} in STRUCTURAL_KEYWORDS missing from dsl.pest"
1450 );
1451 }
1452
1453 let mut seen = HashSet::new();
1454 let mut stack = vec!["element".to_string(), "block_element".to_string()];
1455 let mut stmt_literals = HashSet::new();
1456 while let Some(name) = stack.pop() {
1457 if !seen.insert(name.clone()) {
1458 continue;
1459 }
1460 let Some(expr) = by_name.get(name.as_str()) else {
1461 continue;
1462 };
1463 for node in expr.iter_top_down() {
1464 match node {
1465 Expr::Str(literal) | Expr::Insens(literal) => {
1466 stmt_literals.insert(literal.clone());
1467 }
1468 Expr::Ident(dependency) => stack.push(dependency.clone()),
1469 _ => {}
1470 }
1471 }
1472 }
1473 assert!(
1474 seen.contains("element") && seen.contains("block_element"),
1475 "grammar must define element and block_element instruction rules"
1476 );
1477 for kw in stmt_literals {
1478 if kw.len() > 1 && kw.chars().all(|c| c.is_ascii_uppercase()) {
1479 assert!(
1480 crate::Command::is_statement_keyword(&kw)
1481 || CLAUSE_KEYWORDS.contains(&kw.as_str()),
1482 "uppercase literal \"{kw}\" reachable from dsl.pest instruction rules is not a registered statement or clause keyword"
1483 );
1484 }
1485 }
1486 }
1487
1488 #[test]
1492 fn command_names_group_by_category() {
1493 for command in COMMANDS {
1494 let name = command.as_str();
1495 let Some((prefix, _)) = name.split_once('_') else {
1496 continue;
1497 };
1498 assert!(
1499 COMMAND_CATEGORIES.contains(&prefix),
1500 "command {name} introduces unregistered category {prefix}; add it to COMMAND_CATEGORIES"
1501 );
1502 }
1503 }
1504}
1505
1506#[cfg(test)]
1507mod guard_analysis_tests {
1508 use super::*;
1509
1510 fn attr(ns: Ns, key: Option<&str>, val: Option<&str>) -> GuardExpr {
1511 GuardExpr::Predicate(Guard::Attr {
1512 ns,
1513 key: key.map(str::to_string),
1514 val: val.map(str::to_string),
1515 })
1516 }
1517
1518 fn os(value: &str) -> GuardExpr {
1519 attr(Ns::Os, None, Some(value))
1520 }
1521
1522 fn arch(value: &str) -> GuardExpr {
1523 attr(Ns::Arch, None, Some(value))
1524 }
1525
1526 fn unix() -> GuardExpr {
1529 GuardExpr::Or(vec![os("macos"), os("linux")])
1530 }
1531
1532 fn windows() -> GuardExpr {
1533 os("windows")
1534 }
1535
1536 fn env_eq(var: &str, value: &str) -> GuardExpr {
1537 attr(Ns::Env, Some(var), Some(value))
1538 }
1539
1540 fn not(expr: GuardExpr) -> GuardExpr {
1541 GuardExpr::Not(Box::new(expr))
1542 }
1543
1544 #[test]
1548 fn partition_negations_are_jointly_dead() {
1549 let os_exhausted = GuardExpr::All(vec![not(os("macos")), not(os("linux")), not(windows())]);
1550 assert!(
1551 !guard_satisfiable(&os_exhausted),
1552 "no host is outside `macos`/`linux`/`windows`"
1553 );
1554 let os_partial = GuardExpr::All(vec![not(os("macos")), not(os("linux"))]);
1556 assert!(guard_satisfiable(&os_partial), "`windows` is still open");
1557 let bool_exhausted = GuardExpr::All(vec![
1559 not(attr(Ns::Bool, None, Some("true"))),
1560 not(attr(Ns::Bool, None, Some("false"))),
1561 ]);
1562 assert!(!guard_satisfiable(&bool_exhausted));
1563 let env_open = GuardExpr::All(vec![
1565 not(env_eq("MODE", "dev")),
1566 not(env_eq("MODE", "prod")),
1567 ]);
1568 assert!(guard_satisfiable(&env_open), "MODE may hold a third value");
1569 assert!(guard_satisfiable(¬(unix())));
1571 }
1572
1573 #[test]
1576 fn unix_alias_is_os_disjunction() {
1577 assert!(!guards_overlap(Some(&unix()), Some(&windows())));
1578 assert!(guards_overlap(Some(&unix()), Some(&os("macos"))));
1579 let covered = GuardExpr::All(vec![GuardExpr::Not(Box::new(unix())), not(windows())]);
1582 assert!(!guard_satisfiable(&covered));
1583 }
1584
1585 #[test]
1589 fn arch_guards_decide_by_value() {
1590 assert!(!guards_overlap(
1591 Some(&arch("x86_64")),
1592 Some(&arch("aarch64"))
1593 ));
1594 assert!(guards_overlap(Some(&arch("x86_64")), Some(&arch("x86_64"))));
1595 assert!(guards_overlap(Some(&arch("aarch64")), Some(&os("macos"))));
1596 let exhausted = GuardExpr::All(ARCH_VALUES.iter().map(|value| not(arch(value))).collect());
1597 assert!(!guard_satisfiable(&exhausted));
1598 let host = attr(Ns::Arch, None, Some(ARCH_TARGET));
1600 assert!(guard_expr_allows(&host, &HashMap::new()));
1601 }
1602
1603 #[test]
1607 fn platform_overlap_matrix_is_exhaustive() {
1608 let cases = [
1609 ("macos", "macos", true),
1610 ("macos", "linux", false),
1611 ("macos", "windows", false),
1612 ("linux", "linux", true),
1613 ("linux", "windows", false),
1614 ("windows", "windows", true),
1615 ];
1616 for (v1, v2, expected) in cases {
1617 let left = os(v1);
1618 let right = os(v2);
1619 assert_eq!(
1620 guards_overlap(Some(&left), Some(&right)),
1621 expected,
1622 "os:{v1} vs os:{v2}"
1623 );
1624 }
1625 }
1626
1627 #[test]
1630 fn disjoint_pairs_never_cofire_here() {
1631 let macos = os("macos");
1632 let holds = |expr: &GuardExpr| guard_expr_allows(expr, &HashMap::new());
1633 assert!(
1634 !(holds(&macos) && holds(&windows())),
1635 "os:macos and os:windows co-fired"
1636 );
1637 }
1638
1639 #[test]
1640 fn overlap_follows_namespace_semantics() {
1641 assert!(!guards_overlap(Some(&windows()), Some(&unix())));
1643 assert!(!guards_overlap(Some(&os("macos")), Some(&os("linux"))));
1644 assert!(guards_overlap(None, Some(&windows())));
1646 assert!(guards_overlap(None, None));
1647 let dead = GuardExpr::All(vec![os("macos"), windows()]);
1649 assert!(!guard_satisfiable(&dead));
1650 assert!(!guards_overlap(Some(&dead), Some(&os("macos"))));
1651 assert!(guard_valid(&GuardExpr::Predicate(Guard::Attr {
1652 ns: Ns::Bool,
1653 key: None,
1654 val: Some("true".to_string()),
1655 })));
1656 assert!(!guard_valid(&unix()));
1657 }
1658
1659 #[test]
1660 fn env_value_conflicts_decide_without_enumeration() {
1661 let fast = env_eq("MODE", "fast");
1662 let slow = env_eq("MODE", "slow");
1663 assert!(
1664 !guards_overlap(Some(&fast), Some(&slow)),
1665 "same key distinct values are disjoint"
1666 );
1667 let also_fast = env_eq("MODE", "fast");
1668 assert!(guards_overlap(Some(&fast), Some(&also_fast)));
1669 let bare = attr(Ns::Env, Some("MODE"), None);
1671 assert!(guards_overlap(Some(&bare), Some(&fast)));
1672 }
1673}
1674
1675#[cfg(test)]
1676mod guard_algebra_tests {
1677 use super::*;
1678
1679 fn os(value: &str) -> GuardExpr {
1680 GuardExpr::Predicate(Guard::Attr {
1681 ns: Ns::Os,
1682 key: None,
1683 val: Some(value.to_string()),
1684 })
1685 }
1686
1687 #[test]
1688 fn or_distributes_over_disjointness() {
1689 fn env_eq(var: &str, value: &str) -> GuardExpr {
1690 GuardExpr::Predicate(Guard::Attr {
1691 ns: Ns::Env,
1692 key: Some(var.to_string()),
1693 val: Some(value.to_string()),
1694 })
1695 }
1696 let mixed = GuardExpr::Or(vec![env_eq("MODE", "dev"), env_eq("MODE", "prod")]);
1699 assert!(!mixed.is_disjoint_from(&env_eq("MODE", "dev")));
1700 assert!(mixed.is_disjoint_from(&env_eq("MODE", "test")));
1702 let cross = GuardExpr::Or(vec![env_eq("MODE", "dev")]);
1704 let platform = os("windows");
1705 assert!(!cross.is_disjoint_from(&platform));
1706 }
1707
1708 #[test]
1709 fn all_distributes_over_disjointness() {
1710 let stacked = GuardExpr::All(vec![
1711 os("macos"),
1712 GuardExpr::Or(vec![os("macos"), os("linux")]),
1713 os("windows"),
1714 ]);
1715 assert!(stacked.is_disjoint_from(&os("macos")));
1716 let live = GuardExpr::All(vec![
1719 os("macos"),
1720 GuardExpr::Predicate(Guard::Attr {
1721 ns: Ns::Env,
1722 key: Some("MODE".to_string()),
1723 val: Some("dev".to_string()),
1724 }),
1725 ]);
1726 assert!(!live.is_disjoint_from(&os("macos")));
1727 }
1728
1729 #[test]
1730 fn negation_is_structural_not_syntactic() {
1731 let not_win = GuardExpr::Not(Box::new(os("windows")));
1732 assert!(not_win.is_disjoint_from(&os("windows")));
1733 assert!(os("windows").is_disjoint_from(¬_win));
1734 assert!(!not_win.is_disjoint_from(&os("macos")));
1735 }
1736}