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 func_names: 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.func_names.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 Symlink,
62 Mkdir,
63 Install,
64 Archive,
65 Unarchive,
66 Ls,
67 Read,
68 ReadLine,
69 Prompt,
70 Write,
71 Append,
72 Remove,
73 Expand,
74 AssertEq,
75 AssertContains,
76 Exit,
77 Async,
78 Timeout,
79 Isolated,
80 Sleep,
81 ListAppend,
82}
83
84pub const COMMANDS: &[Command] = &[
85 Command::InheritEnv,
86 Command::Workdir,
87 Command::Workspace,
88 Command::Env,
89 Command::Echo,
90 Command::Run,
91 Command::Copy,
92 Command::WithIo,
93 Command::CopyGit,
94 Command::Symlink,
95 Command::Mkdir,
96 Command::Install,
97 Command::Archive,
98 Command::Unarchive,
99 Command::Ls,
100 Command::Read,
101 Command::ReadLine,
102 Command::Prompt,
103 Command::Write,
104 Command::Append,
105 Command::Remove,
106 Command::Expand,
107 Command::AssertEq,
108 Command::AssertContains,
109 Command::Exit,
110 Command::Timeout,
111 Command::Isolated,
112 Command::Sleep,
113 Command::ListAppend,
114];
115
116pub const COMMAND_CATEGORIES: &[&str] =
121 &["INHERIT", "WITH", "COPY", "HASH", "READ", "ASSERT", "LIST"];
122
123impl Command {
124 pub const fn as_str(self) -> &'static str {
125 match self {
126 Command::InheritEnv => "INHERIT_ENV",
127 Command::Workdir => "WORKDIR",
128 Command::Workspace => "WORKSPACE",
129 Command::Env => "ENV",
130 Command::Echo => "ECHO",
131 Command::Run => "RUN",
132 Command::Copy => "COPY",
133 Command::WithIo => "WITH_IO",
134 Command::CopyGit => "COPY_GIT",
135 Command::Symlink => "SYMLINK",
136 Command::Mkdir => "MKDIR",
137 Command::Install => "INSTALL",
138 Command::Archive => "ARCHIVE",
139 Command::Unarchive => "UNARCHIVE",
140 Command::Ls => "LS",
141 Command::Read => "READ",
142 Command::ReadLine => "READ_LINE",
143 Command::Prompt => "PROMPT",
144 Command::Write => "WRITE",
145 Command::Append => "APPEND",
146 Command::Remove => "REMOVE",
147 Command::Expand => "EXPAND",
148 Command::AssertEq => "ASSERT_EQ",
149 Command::AssertContains => "ASSERT_CONTAINS",
150 Command::Exit => "EXIT",
151 Command::Async => "ASYNC",
152 Command::Timeout => "TIMEOUT",
153 Command::Isolated => "ISOLATED",
154 Command::Sleep => "SLEEP",
155 Command::ListAppend => "LIST_APPEND",
156 }
157 }
158
159 pub const fn syntax(self) -> &'static str {
160 match self {
161 Command::InheritEnv => "INHERIT_ENV [KEY1, KEY2, ...]",
162 Command::Workdir => "WORKDIR <path>",
163 Command::Workspace => "WORKSPACE SNAPSHOT|LOCAL|CACHE|SYSTEM [--local]",
164 Command::Env => "ENV KEY=value",
165 Command::Echo => "ECHO <message>",
166 Command::Run => "RUN <command...> | RUN [\"exe\", \"arg\", ...]",
167 Command::Copy => "COPY [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>",
168 Command::CopyGit => "COPY_GIT [--include-dirty] <rev> <src> <dst>",
169 Command::WithIo => "WITH_IO [bindings] [command | { block }]",
170 Command::Symlink => {
171 "SYMLINK [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>"
172 }
173 Command::Mkdir => "MKDIR <path>",
174 Command::Install => "INSTALL <source> <dest>",
175 Command::Archive => "ARCHIVE [--raw] <src> <dst>",
176 Command::Unarchive => "UNARCHIVE <src> <dst> [--max-bytes <bytes>]",
177 Command::Ls => "LS [<path>]",
178 Command::Read => "READ [<path>]",
179 Command::ReadLine => "READ_LINE $var",
180 Command::Prompt => "PROMPT $var <message> [<default>]",
181 Command::Write => "WRITE <path> [<contents>]",
182 Command::Append => "APPEND <path> [<contents>]",
183 Command::Remove => "REMOVE [--recursive] <path>",
184 Command::Expand => "EXPAND [<path>] [<KEY=val> ...]",
185 Command::AssertEq => "ASSERT_EQ [--hash <sha256>] <actual> <expected>",
186 Command::AssertContains => "ASSERT_CONTAINS <haystack> <needle>",
187 Command::Exit => "EXIT <code>",
188 Command::Async => "ASYNC <command...> | ASYNC { <commands> }",
189 Command::Timeout => {
190 "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> }"
191 }
192 Command::Isolated => {
193 "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>"
194 }
195 Command::Sleep => "SLEEP <duration>",
196 Command::ListAppend => "LIST_APPEND $list <item>",
197 }
198 }
199
200 pub const fn expects_inner_command(self) -> bool {
201 matches!(
202 self,
203 Command::WithIo | Command::Async | Command::Timeout | Command::Isolated
204 )
205 }
206
207 pub fn parse(s: &str) -> Option<Self> {
208 match s {
209 "INHERIT_ENV" => Some(Command::InheritEnv),
210 "WORKDIR" => Some(Command::Workdir),
211 "WORKSPACE" => Some(Command::Workspace),
212 "ENV" => Some(Command::Env),
213 "ECHO" => Some(Command::Echo),
214 "RUN" => Some(Command::Run),
215 "COPY" => Some(Command::Copy),
216 "WITH_IO" => Some(Command::WithIo),
217 "COPY_GIT" => Some(Command::CopyGit),
218 "SYMLINK" => Some(Command::Symlink),
219 "MKDIR" => Some(Command::Mkdir),
220 "INSTALL" => Some(Command::Install),
221 "ARCHIVE" => Some(Command::Archive),
222 "UNARCHIVE" => Some(Command::Unarchive),
223 "LS" => Some(Command::Ls),
224 "READ" => Some(Command::Read),
225 "READ_LINE" => Some(Command::ReadLine),
226 "PROMPT" => Some(Command::Prompt),
227 "WRITE" => Some(Command::Write),
228 "APPEND" => Some(Command::Append),
229 "REMOVE" => Some(Command::Remove),
230 "EXPAND" => Some(Command::Expand),
231 "ASSERT_EQ" => Some(Command::AssertEq),
232 "ASSERT_CONTAINS" => Some(Command::AssertContains),
233 "EXIT" => Some(Command::Exit),
234 "ASYNC" => Some(Command::Async),
235 "TIMEOUT" => Some(Command::Timeout),
236 "ISOLATED" => Some(Command::Isolated),
237 "SLEEP" => Some(Command::Sleep),
238 "LIST_APPEND" => Some(Command::ListAppend),
239 _ => None,
240 }
241 }
242
243 pub(crate) fn is_statement_keyword(s: &str) -> bool {
248 Command::parse(s).is_some() || STRUCTURAL_KEYWORDS.contains(&s)
249 }
250}
251
252pub const STRUCTURAL_KEYWORDS: &[&str] = &[
258 KEYWORD_LET,
259 KEYWORD_FOR,
260 KEYWORD_IF,
261 KEYWORD_ELSE,
262 KEYWORD_ASYNC,
263 KEYWORD_AWAIT,
264 KEYWORD_CANCEL,
265 KEYWORD_FUNC,
266 KEYWORD_RETURN,
267 KEYWORD_WHILE,
268 KEYWORD_BREAK,
269 KEYWORD_CONTINUE,
270 KEYWORD_REMOTE,
271 KEYWORD_IMPORT,
272 KEYWORD_EXPORT,
273 KEYWORD_TYPE,
274];
275
276pub const CLAUSE_KEYWORDS: &[&str] = &["IN"];
281
282#[derive(Debug, Clone, Eq, PartialEq)]
295pub enum Guard {
296 Attr {
297 ns: Ns,
298 key: Option<String>,
299 val: Option<String>,
300 },
301}
302
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
307pub enum Ns {
308 Os,
309 Arch,
310 Bool,
311 Env,
312}
313
314impl fmt::Display for Ns {
315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316 match self {
317 Ns::Os => write!(f, "os"),
318 Ns::Arch => write!(f, "arch"),
319 Ns::Bool => write!(f, "bool"),
320 Ns::Env => write!(f, "env"),
321 }
322 }
323}
324
325pub const ARCH_VALUES: &[&str] = &[
329 "aarch64",
330 "arm",
331 "arm64ec",
332 "avr",
333 "bpf",
334 "csky",
335 "hexagon",
336 "loongarch32",
337 "loongarch64",
338 "mips",
339 "mips32r6",
340 "mips64",
341 "mips64r6",
342 "msp430",
343 "nvptx64",
344 "powerpc",
345 "powerpc64",
346 "riscv32",
347 "riscv64",
348 "s390x",
349 "sparc",
350 "sparc64",
351 "wasm32",
352 "wasm64",
353 "x86",
354 "x86_64",
355 "xtensa",
356];
357
358#[derive(Debug, Clone, Eq, PartialEq)]
359pub enum GuardExpr {
360 Predicate(Guard),
361 All(Vec<GuardExpr>),
362 Or(Vec<GuardExpr>),
363 Not(Box<GuardExpr>),
364}
365
366impl GuardExpr {
367 pub fn all(exprs: Vec<GuardExpr>) -> GuardExpr {
368 let mut flat = Vec::new();
369 for expr in exprs {
370 match expr {
371 GuardExpr::All(children) => flat.extend(children),
372 other => flat.push(other),
373 }
374 }
375 match flat.len() {
376 0 => panic!("GuardExpr::all requires at least one expression"),
377 1 => flat.into_iter().next().unwrap(),
378 _ => GuardExpr::All(flat),
379 }
380 }
381
382 pub fn or(exprs: Vec<GuardExpr>) -> GuardExpr {
383 let mut flat = Vec::new();
384 for expr in exprs {
385 match expr {
386 GuardExpr::Or(children) => flat.extend(children),
387 other => flat.push(other),
388 }
389 }
390 match flat.len() {
391 0 => panic!("GuardExpr::or requires at least one expression"),
392 1 => flat.into_iter().next().unwrap(),
393 _ => GuardExpr::Or(flat),
394 }
395 }
396
397 pub fn invert(expr: GuardExpr) -> GuardExpr {
398 match expr {
399 GuardExpr::Not(inner) => *inner,
400 other => GuardExpr::Not(Box::new(other)),
401 }
402 }
403}
404
405impl std::ops::Not for GuardExpr {
406 type Output = GuardExpr;
407
408 fn not(self) -> GuardExpr {
409 match self {
410 GuardExpr::Not(inner) => *inner,
411 other => GuardExpr::Not(Box::new(other)),
412 }
413 }
414}
415
416impl From<Guard> for GuardExpr {
417 fn from(guard: Guard) -> Self {
418 GuardExpr::Predicate(guard)
419 }
420}
421
422#[derive(Debug, Clone, PartialEq)]
424pub enum Arg {
425 String(String, bool),
429 Expr(Expr),
431 Parts(Vec<ArgPart>),
435}
436
437#[derive(Debug, Clone, PartialEq)]
439pub enum ArgPart {
440 Text(String, bool),
443 Expr(Expr),
445}
446
447impl Arg {
448 pub fn as_str(&self) -> &str {
449 match self {
450 Arg::String(s, _) => s,
451 Arg::Expr(_) | Arg::Parts(_) => "",
454 }
455 }
456
457 pub fn render(&self) -> String {
461 match self {
462 Arg::String(s, _) => s.clone(),
463 Arg::Expr(e) => e.to_string(),
464 Arg::Parts(parts) => parts.iter().map(ArgPart::render).collect(),
465 }
466 }
467
468 pub fn is_quoted(&self) -> bool {
469 matches!(self, Arg::String(_, true))
470 }
471}
472
473impl ArgPart {
474 pub fn render(&self) -> String {
475 match self {
476 ArgPart::Text(s, _) => s.clone(),
477 ArgPart::Expr(e) => e.to_string(),
478 }
479 }
480}
481
482impl From<String> for Arg {
483 fn from(s: String) -> Self {
484 Arg::String(s, false)
485 }
486}
487
488impl From<&str> for Arg {
489 fn from(s: &str) -> Self {
490 Arg::String(s.to_string(), false)
491 }
492}
493
494impl std::fmt::Display for Arg {
495 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
496 match self {
497 Arg::String(s, _) => write!(f, "{}", s),
498 Arg::Expr(e) => write!(f, "{}", e),
499 Arg::Parts(parts) => {
500 for part in parts {
501 match part {
502 ArgPart::Text(s, _) => write!(f, "{}", s)?,
503 ArgPart::Expr(e) => write!(f, "{}", e)?,
504 }
505 }
506 Ok(())
507 }
508 }
509 }
510}
511
512impl AsRef<str> for Arg {
513 fn as_ref(&self) -> &str {
514 self.as_str()
515 }
516}
517
518impl PartialEq<str> for Arg {
519 fn eq(&self, other: &str) -> bool {
520 self.as_str() == other
521 }
522}
523
524impl PartialEq<&str> for Arg {
525 fn eq(&self, other: &&str) -> bool {
526 self.as_str() == *other
527 }
528}
529
530#[derive(Debug, Clone, Copy, Eq, PartialEq)]
531pub enum IoStream {
532 Stdin,
533 Stdout,
534 Stderr,
535 Tty,
539 Rows(u16),
541 Cols(u16),
543}
544
545#[derive(Debug, Clone, Eq, PartialEq)]
546pub struct IoBinding {
547 pub stream: IoStream,
548 pub pipe: Option<PipeTarget>,
549}
550
551#[derive(Debug, Clone, Eq, PartialEq)]
554pub enum PipeTarget {
555 Var(String),
556}
557
558pub use crate::value::{
562 OxDockType, SemaphoreState, TypeDescriptor, Value, ValuePayload, clone_boxed, clone_copy,
563 clone_shared, drop_boxed, drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed,
564 fmt_inline, fmt_shared, load_inline, startup_descriptors, store_inline, type_anchor,
565 unshare_boxed, unshare_inline, unshare_shared,
566};
567
568#[derive(Debug, Clone, Copy, Eq, PartialEq)]
569pub enum CompareOp {
570 Eq,
571 Ne,
572 Lt,
573 Le,
574 Gt,
575 Ge,
576}
577
578#[derive(Debug, Clone, Copy, Eq, PartialEq)]
579pub enum ArithOp {
580 Add,
581 Sub,
582 Mul,
583 Div,
584}
585
586#[derive(Debug, Clone, PartialEq)]
595pub enum MathOp {
596 PushConst(Value),
597 LoadVar(String),
598 LoadEnv(String),
599 LoadKeyPath { base: String, keys: Vec<String> },
600 Call { name: String, arity: usize },
601 Inspect(String),
602 Neg,
603 Add,
604 Sub,
605 Mul,
606 Div,
607 Lt,
608 Le,
609 Gt,
610 Ge,
611 Eq,
612 Ne,
613}
614
615#[derive(Debug, Clone, Copy, Eq, PartialEq)]
616pub enum LogicalOp {
617 And,
618 Or,
619}
620
621#[derive(Debug, Clone, PartialEq)]
622pub enum Expr {
623 Literal(Value),
624 Var(String),
625 Env(String),
628 KeyPath {
629 base: String,
630 keys: Vec<String>,
631 },
632 List(Vec<Expr>),
633 Map(Vec<(String, Expr)>),
634 Block(Vec<Step>),
639 Call {
640 name: String,
641 args: Vec<Expr>,
642 },
643 Inspect(String),
648 Compare {
649 op: CompareOp,
650 left: Box<Expr>,
651 right: Box<Expr>,
652 },
653 Arithmetic {
654 op: ArithOp,
655 left: Box<Expr>,
656 right: Box<Expr>,
657 },
658 CompiledMath(Vec<MathOp>),
661 FreshPipe,
667 UnsignedIntBoundary(u64),
671 Not(Box<Expr>),
672 Logical {
673 op: LogicalOp,
674 left: Box<Expr>,
675 right: Box<Expr>,
676 },
677}
678
679#[derive(Debug, Clone)]
680pub struct Step {
681 pub guard: Option<GuardExpr>,
682 pub kind: StepKind,
683 pub scope_enter: usize,
684 pub scope_exit: usize,
685 pub line: usize,
692 pub col: usize,
696}
697
698impl PartialEq for Step {
699 fn eq(&self, other: &Self) -> bool {
700 self.guard == other.guard
701 && self.kind == other.kind
702 && self.scope_enter == other.scope_enter
703 && self.scope_exit == other.scope_exit
704 }
705}
706
707impl Eq for Step {}
708
709impl Expr {
710 pub fn walk(&self, f: &mut impl FnMut(&Expr)) {
717 f(self);
718 match self {
719 Expr::Literal(_)
720 | Expr::Var(_)
721 | Expr::Env(_)
722 | Expr::KeyPath { .. }
723 | Expr::Inspect(_)
724 | Expr::FreshPipe
725 | Expr::UnsignedIntBoundary(_) => {}
726 Expr::Call { args, .. } => {
727 for arg in args {
728 arg.walk(f);
729 }
730 }
731 Expr::List(items) => {
732 for item in items {
733 item.walk(f);
734 }
735 }
736 Expr::Map(entries) => {
737 for (_, value) in entries {
738 value.walk(f);
739 }
740 }
741 Expr::Block(steps) => {
742 for step in steps {
743 step.kind.walk_step_exprs(f);
744 }
745 }
746 Expr::Compare { left, right, .. }
747 | Expr::Arithmetic { left, right, .. }
748 | Expr::Logical { left, right, .. } => {
749 left.walk(f);
750 right.walk(f);
751 }
752 Expr::CompiledMath(_) => {}
753 Expr::Not(inner) => inner.walk(f),
754 }
755 }
756}
757
758#[derive(Debug, Clone, Eq, PartialEq)]
759pub enum WorkspaceTarget {
760 Snapshot,
761 Local,
762 Cache { local: bool },
763 System,
764}
765
766pub trait EnvLookup {
767 fn get_env(&self, key: &str) -> Option<&str>;
768}
769
770impl EnvLookup for HashMap<String, String> {
771 fn get_env(&self, key: &str) -> Option<&str> {
772 self.get(key).map(|s| s.as_str())
773 }
774}
775
776impl EnvLookup for Arc<HashMap<String, String>> {
777 fn get_env(&self, key: &str) -> Option<&str> {
778 (**self).get_env(key)
779 }
780}
781
782pub fn guard_allows(guard: &Guard, env: &impl EnvLookup) -> bool {
783 let Guard::Attr { ns, key, val } = guard;
784 match ns {
785 Ns::Os => match val.as_deref() {
786 Some("macos") => platform_is_macos(),
787 Some("linux") => platform_is_linux(),
788 Some("windows") => platform_is_windows(),
789 _ => false,
790 },
791 Ns::Arch => match val.as_deref() {
792 Some(want) => ARCH_TARGET == want,
793 None => false,
794 },
795 Ns::Bool => val
796 .as_deref()
797 .map(|v| v.parse::<bool>().unwrap_or(false))
798 .unwrap_or(false),
799 Ns::Env => match key.as_deref() {
800 Some(var) => match val {
801 None => env.get_env(var).map(|v| !v.is_empty()).unwrap_or(false),
802 Some(want) => env
803 .get_env(var)
804 .map(|v| v == want.as_str())
805 .unwrap_or(false),
806 },
807 None => false,
809 },
810 }
811}
812
813#[allow(clippy::disallowed_macros)]
816fn platform_is_windows() -> bool {
817 cfg!(windows)
818}
819
820#[allow(clippy::disallowed_macros)]
822fn platform_is_macos() -> bool {
823 cfg!(target_os = "macos")
824}
825
826#[allow(clippy::disallowed_macros)]
828fn platform_is_linux() -> bool {
829 cfg!(target_os = "linux")
830}
831
832const ARCH_TARGET: &str = std::env::consts::ARCH;
835
836pub fn guard_expr_allows(expr: &GuardExpr, env: &impl EnvLookup) -> bool {
837 match expr {
838 GuardExpr::Predicate(guard) => guard_allows(guard, env),
839 GuardExpr::All(children) => children.iter().all(|g| guard_expr_allows(g, env)),
840 GuardExpr::Or(children) => children.iter().any(|g| guard_expr_allows(g, env)),
841 GuardExpr::Not(child) => !guard_expr_allows(child, env),
842 }
843}
844
845pub fn guard_option_allows(expr: Option<&GuardExpr>, env: &impl EnvLookup) -> bool {
846 match expr {
847 Some(e) => guard_expr_allows(e, env),
848 None => true,
849 }
850}
851
852impl Guard {
853 pub fn is_disjoint_from(&self, other: &Self) -> bool {
862 match (self, other) {
863 (
864 Guard::Attr {
865 ns: n1,
866 key: k1,
867 val: Some(v1),
868 },
869 Guard::Attr {
870 ns: n2,
871 key: k2,
872 val: Some(v2),
873 },
874 ) => n1 == n2 && k1 == k2 && v1 != v2,
875 _ => false,
876 }
877 }
878}
879
880impl GuardExpr {
881 pub fn is_disjoint_from(&self, other: &Self) -> bool {
887 match (self, other) {
888 (x, GuardExpr::Not(inner)) | (GuardExpr::Not(inner), x) => {
896 x == inner.as_ref() || unset_excludes(x, inner.as_ref())
897 }
898 (GuardExpr::Predicate(p1), GuardExpr::Predicate(p2)) => p1.is_disjoint_from(p2),
900 (GuardExpr::Or(arms), other) | (other, GuardExpr::Or(arms)) => {
902 arms.iter().all(|arm| arm.is_disjoint_from(other))
903 }
904 (GuardExpr::All(arms), other) | (other, GuardExpr::All(arms)) => {
906 arms.iter().any(|arm| arm.is_disjoint_from(other))
907 }
908 }
909 }
910}
911
912fn conjuncts(expr: &GuardExpr) -> Vec<&GuardExpr> {
916 match expr {
917 GuardExpr::All(items) => items.iter().collect(),
918 single => vec![single],
919 }
920}
921
922fn closed_domain_values(ns: Ns, key: Option<&str>) -> Option<&'static [&'static str]> {
929 match (ns, key) {
930 (Ns::Bool, None) => Some(&["true", "false"]),
931 (Ns::Os, None) => Some(&["macos", "linux", "windows"]),
932 (Ns::Arch, None) => Some(ARCH_VALUES),
933 _ => None,
934 }
935}
936
937#[derive(Clone)]
940enum DnfLit {
941 Pos(Guard),
942 Neg(Guard),
943}
944
945impl DnfLit {
946 fn as_expr(&self) -> GuardExpr {
947 match self {
948 DnfLit::Pos(guard) => GuardExpr::Predicate(guard.clone()),
949 DnfLit::Neg(guard) => GuardExpr::Not(Box::new(GuardExpr::Predicate(guard.clone()))),
950 }
951 }
952}
953
954const MAX_DNF_DISJUNCTS: usize = 64;
959
960fn dnf_push(expr: &GuardExpr, polarity: bool, out: &mut Vec<Vec<DnfLit>>) -> bool {
965 match (expr, polarity) {
966 (GuardExpr::Predicate(guard), true) => {
967 for disjunct in out.iter_mut() {
968 disjunct.push(DnfLit::Pos(guard.clone()));
969 }
970 true
971 }
972 (GuardExpr::Predicate(guard), false) => {
973 for disjunct in out.iter_mut() {
974 disjunct.push(DnfLit::Neg(guard.clone()));
975 }
976 true
977 }
978 (GuardExpr::All(children), true) | (GuardExpr::Or(children), false) => {
979 for child in children {
981 if !dnf_push(child, polarity, out) {
982 return false;
983 }
984 }
985 true
986 }
987 (GuardExpr::Or(children), true) | (GuardExpr::All(children), false) => {
988 let mut forked = Vec::new();
990 for disjunct in out.drain(..) {
991 for child in children {
992 let mut branch = vec![disjunct.clone()];
993 if !dnf_push(child, polarity, &mut branch) {
994 return false;
995 }
996 forked.extend(branch);
997 if forked.len() > MAX_DNF_DISJUNCTS {
998 return false;
999 }
1000 }
1001 }
1002 *out = forked;
1003 true
1004 }
1005 (GuardExpr::Not(inner), _) => dnf_push(inner, !polarity, out),
1006 }
1007}
1008
1009fn disjunct_satisfiable(lits: &[DnfLit]) -> bool {
1013 for lit in lits {
1017 match lit {
1018 DnfLit::Pos(Guard::Attr {
1019 ns: Ns::Bool, val, ..
1020 }) if val.as_deref() != Some("true") => return false,
1021 DnfLit::Neg(Guard::Attr {
1022 ns: Ns::Bool,
1023 key: None,
1024 val: Some(value),
1025 }) if value == "true" => return false,
1026 _ => {}
1027 }
1028 }
1029 for (index, first) in lits.iter().enumerate() {
1032 for second in &lits[index + 1..] {
1033 if first.as_expr().is_disjoint_from(&second.as_expr()) {
1034 return false;
1035 }
1036 }
1037 }
1038 for lit in lits {
1042 let (ns, key) = match lit {
1043 DnfLit::Neg(Guard::Attr {
1044 ns,
1045 key,
1046 val: Some(_),
1047 }) => (*ns, key.as_deref()),
1048 _ => continue,
1049 };
1050 let Some(domain) = closed_domain_values(ns, key) else {
1051 continue;
1052 };
1053 let exhausted = domain.iter().all(|value| {
1054 lits.iter().any(|other| match other {
1055 DnfLit::Neg(Guard::Attr {
1056 ns: other_ns,
1057 key: other_key,
1058 val: Some(other_val),
1059 }) => *other_ns == ns && other_key.as_deref() == key && other_val == value,
1060 _ => false,
1061 })
1062 });
1063 if exhausted {
1064 return false;
1065 }
1066 }
1067 true
1068}
1069
1070fn conjunction_dead(atoms: &[&GuardExpr]) -> bool {
1077 if atoms.is_empty() {
1078 return false;
1079 }
1080 let mut disjuncts = vec![Vec::new()];
1081 for atom in atoms {
1082 if !dnf_push(atom, true, &mut disjuncts) {
1083 return false;
1084 }
1085 }
1086 !disjuncts
1087 .iter()
1088 .any(|disjunct| disjunct_satisfiable(disjunct))
1089}
1090
1091pub fn guard_satisfiable(expr: &GuardExpr) -> bool {
1093 !conjunction_dead(&conjuncts(expr))
1094}
1095
1096pub fn guard_valid(expr: &GuardExpr) -> bool {
1099 match expr {
1100 GuardExpr::Predicate(Guard::Attr {
1101 ns: Ns::Bool,
1102 val: Some(value),
1103 ..
1104 }) => value.as_str() == "true",
1105 GuardExpr::All(items) => items.iter().all(guard_valid),
1106 GuardExpr::Not(inner) => !guard_satisfiable(inner),
1107 _ => false,
1108 }
1109}
1110
1111pub fn guards_overlap(a: Option<&GuardExpr>, b: Option<&GuardExpr>) -> bool {
1114 match (a, b) {
1115 (None, None) => true,
1116 (Some(x), None) | (None, Some(x)) => guard_satisfiable(x),
1117 (Some(x), Some(y)) => {
1118 let mut atoms = conjuncts(x);
1119 atoms.extend(conjuncts(y));
1120 !conjunction_dead(&atoms)
1121 }
1122 }
1123}
1124
1125fn unset_excludes(x: &GuardExpr, inner: &GuardExpr) -> bool {
1128 match (x, inner) {
1129 (
1130 GuardExpr::Predicate(Guard::Attr {
1131 ns: n2, key: k2, ..
1132 }),
1133 GuardExpr::Predicate(Guard::Attr {
1134 ns: n1,
1135 key: k1,
1136 val: None,
1137 }),
1138 ) => n1 == n2 && k1 == k2,
1139 _ => false,
1140 }
1141}
1142
1143impl fmt::Display for Guard {
1144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1150 match self {
1151 Guard::Attr {
1152 ns: Ns::Env,
1153 key: Some(var),
1154 val: None,
1155 } => write!(f, "env:{var}"),
1156 Guard::Attr {
1157 ns: Ns::Env,
1158 key: Some(var),
1159 val: Some(want),
1160 } => write!(f, "eq(env:{var}, {want})"),
1161 Guard::Attr {
1162 ns,
1163 key: _,
1164 val: Some(value),
1165 } => write!(f, "{ns}:{value}"),
1166 Guard::Attr { ns, key, val: None } => match key {
1167 Some(subject) => write!(f, "{ns}:{subject}"),
1168 None => write!(f, "{ns}"),
1169 },
1170 }
1171 }
1172}
1173
1174impl fmt::Display for WorkspaceTarget {
1175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1176 match self {
1177 WorkspaceTarget::Snapshot => write!(f, "SNAPSHOT"),
1178 WorkspaceTarget::Local => write!(f, "LOCAL"),
1179 WorkspaceTarget::Cache { local: false } => write!(f, "CACHE"),
1180 WorkspaceTarget::Cache { local: true } => write!(f, "CACHE --local"),
1181 WorkspaceTarget::System => write!(f, "SYSTEM"),
1182 }
1183 }
1184}
1185
1186impl fmt::Display for Expr {
1187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1188 match self {
1189 Expr::Literal(v) => write!(f, "{}", v),
1190 Expr::Var(name) => write!(f, "${}", name),
1191 Expr::Env(key) => write!(f, "env:{}", key),
1192 Expr::KeyPath { base, keys } => {
1193 write!(f, "${}", base)?;
1194 for key in keys {
1195 write!(f, ".{}", key)?;
1196 }
1197 Ok(())
1198 }
1199 Expr::Call { name, args } => {
1200 write!(f, "{}(", name)?;
1201 for (i, arg) in args.iter().enumerate() {
1202 if i > 0 {
1203 write!(f, ", ")?;
1204 }
1205 write!(f, "{}", arg)?;
1206 }
1207 write!(f, ")")
1208 }
1209 Expr::Inspect(var) => write!(f, "INSPECT(${})", var),
1210 Expr::List(items) => {
1211 write!(f, "[")?;
1212 for (i, item) in items.iter().enumerate() {
1213 if i > 0 {
1214 write!(f, ", ")?;
1215 }
1216 write!(f, "{}", item)?;
1217 }
1218 write!(f, "]")
1219 }
1220 Expr::Map(entries) => {
1221 write!(f, "{{")?;
1222 for (i, (key, val)) in entries.iter().enumerate() {
1223 if i > 0 {
1224 write!(f, ", ")?;
1225 }
1226 write!(f, "\"{}\": {}", key, val)?;
1227 }
1228 write!(f, "}}")
1229 }
1230 Expr::Block(steps) => {
1231 write!(f, "{{ ")?;
1232 for (i, step) in steps.iter().enumerate() {
1233 if i > 0 {
1234 write!(f, "; ")?;
1235 }
1236 write!(f, "{}", step.kind)?;
1237 }
1238 write!(f, " }}")
1239 }
1240 Expr::Compare { op, left, right } => {
1241 write!(f, "({} {} {})", left, op, right)
1245 }
1246 Expr::Arithmetic { op, left, right } => {
1247 write!(f, "({} {} {})", left, op, right)
1248 }
1249 Expr::CompiledMath(ops) => {
1250 write!(f, "{}", format_compiled_math(ops))
1251 }
1252 Expr::FreshPipe => write!(f, "<fresh pipe>"),
1256 Expr::UnsignedIntBoundary(n) => write!(f, "{}", n),
1257 Expr::Not(inner) => {
1258 match inner.as_ref() {
1261 Expr::Compare { .. } | Expr::Arithmetic { .. } | Expr::CompiledMath(_) => {
1262 write!(f, "!({})", inner)
1263 }
1264 _ => write!(f, "!{}", inner),
1265 }
1266 }
1267 Expr::Logical { op, left, right } => {
1268 write!(f, "({} {} {})", left, op, right)
1269 }
1270 }
1271 }
1272}
1273
1274impl fmt::Display for CompareOp {
1275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1276 match self {
1277 CompareOp::Eq => write!(f, "=="),
1278 CompareOp::Ne => write!(f, "!="),
1279 CompareOp::Lt => write!(f, "<"),
1280 CompareOp::Le => write!(f, "<="),
1281 CompareOp::Gt => write!(f, ">"),
1282 CompareOp::Ge => write!(f, ">="),
1283 }
1284 }
1285}
1286
1287impl fmt::Display for ArithOp {
1288 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1289 match self {
1290 ArithOp::Add => write!(f, "+"),
1291 ArithOp::Sub => write!(f, "-"),
1292 ArithOp::Mul => write!(f, "*"),
1293 ArithOp::Div => write!(f, "/"),
1294 }
1295 }
1296}
1297
1298fn format_compiled_math(ops: &[MathOp]) -> String {
1303 let mut stack: Vec<String> = Vec::new();
1304 for op in ops {
1305 match op {
1306 MathOp::PushConst(v) => stack.push(format!("{}", v)),
1307 MathOp::LoadVar(name) => stack.push(format!("${}", name)),
1308 MathOp::LoadEnv(key) => stack.push(format!("env:{}", key)),
1309 MathOp::LoadKeyPath { base, keys } => {
1310 let mut s = format!("${}", base);
1311 for key in keys {
1312 s.push('.');
1313 s.push_str(key);
1314 }
1315 stack.push(s);
1316 }
1317 MathOp::Call { name, arity } => {
1318 let mut args = Vec::new();
1319 for _ in 0..*arity {
1320 args.push(stack.pop().unwrap_or_else(|| "<underflow>".to_string()));
1321 }
1322 args.reverse();
1323 stack.push(format!("{}({})", name, args.join(", ")));
1324 }
1325 MathOp::Inspect(name) => stack.push(format!("INSPECT(${})", name)),
1326 MathOp::Neg => {
1327 let inner = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1328 stack.push(format!("(-{})", inner));
1329 }
1330 MathOp::Add => push_bin(&mut stack, "+"),
1331 MathOp::Sub => push_bin(&mut stack, "-"),
1332 MathOp::Mul => push_bin(&mut stack, "*"),
1333 MathOp::Div => push_bin(&mut stack, "/"),
1334 MathOp::Lt => push_bin(&mut stack, "<"),
1335 MathOp::Le => push_bin(&mut stack, "<="),
1336 MathOp::Gt => push_bin(&mut stack, ">"),
1337 MathOp::Ge => push_bin(&mut stack, ">="),
1338 MathOp::Eq => push_bin(&mut stack, "=="),
1339 MathOp::Ne => push_bin(&mut stack, "!="),
1340 }
1341 }
1342 if stack.len() == 1 {
1343 let mut items = stack;
1344 items.pop().unwrap_or_else(|| "<empty>".to_string())
1345 } else {
1346 stack.join(" ")
1347 }
1348}
1349
1350fn push_bin(stack: &mut Vec<String>, op: &str) {
1351 let right = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1352 let left = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1353 stack.push(format!("({} {} {})", left, op, right));
1354}
1355
1356impl fmt::Display for LogicalOp {
1357 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1358 match self {
1359 LogicalOp::And => write!(f, "&&"),
1360 LogicalOp::Or => write!(f, "||"),
1361 }
1362 }
1363}
1364
1365enum GuardDisplayContext {
1366 Root,
1367 InAnyArg,
1368 InNot,
1369 InAll,
1370}
1371
1372impl GuardExpr {
1373 fn fmt_with_ctx(&self, f: &mut fmt::Formatter<'_>, ctx: GuardDisplayContext) -> fmt::Result {
1374 match self {
1375 GuardExpr::Predicate(guard) => write!(f, "{}", guard),
1376 GuardExpr::All(children) => {
1377 let wrap = matches!(
1378 ctx,
1379 GuardDisplayContext::InAnyArg | GuardDisplayContext::InNot
1380 ) && children.len() > 1;
1381 if wrap {
1382 write!(f, "(")?;
1383 }
1384 for (i, child) in children.iter().enumerate() {
1385 if i > 0 {
1386 write!(f, ", ")?;
1387 }
1388 child.fmt_with_ctx(f, GuardDisplayContext::InAll)?;
1389 }
1390 if wrap {
1391 write!(f, ")")?;
1392 }
1393 Ok(())
1394 }
1395 GuardExpr::Or(children) => {
1396 write!(f, "any(")?;
1397 for (i, child) in children.iter().enumerate() {
1398 if i > 0 {
1399 write!(f, ", ")?;
1400 }
1401 child.fmt_with_ctx(f, GuardDisplayContext::InAnyArg)?;
1402 }
1403 write!(f, ")")
1404 }
1405 GuardExpr::Not(child) => {
1406 write!(f, "not(")?;
1407 child.fmt_with_ctx(f, GuardDisplayContext::InNot)?;
1408 write!(f, ")")
1409 }
1410 }
1411 }
1412}
1413
1414impl fmt::Display for GuardExpr {
1415 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1416 self.fmt_with_ctx(f, GuardDisplayContext::Root)
1417 }
1418}
1419
1420impl fmt::Display for Step {
1421 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1422 if let Some(expr) = &self.guard {
1423 write!(f, "[{}] ", expr)?;
1424 }
1425 write!(f, "{}", self.kind)
1426 }
1427}
1428
1429#[cfg(test)]
1430mod tests {
1431 use super::*;
1432 #[test]
1440 fn statement_keywords_match_backend() {
1441 for kw in STRUCTURAL_KEYWORDS {
1449 let via_backend = crate::parse_script(kw, crate::commands::lower_command);
1450 let via_lowering =
1451 crate::commands::lower_command(kw, Vec::new()).map(|kind| crate::Step {
1452 guard: None,
1453 kind,
1454 scope_enter: 0,
1455 scope_exit: 0,
1456 line: 0,
1457 col: 0,
1458 });
1459 match (via_backend, via_lowering) {
1460 (Ok(_), _) => {}
1461 (Err(a), Err(b)) => {
1462 assert_eq!(
1463 a.kind(),
1464 b.kind(),
1465 "backend kind drift for bare keyword {kw}: {a} vs {b}"
1466 );
1467 }
1468 (Err(a), Ok(_)) => {
1469 panic!("backend rejects bare keyword {kw} that lowering accepts: {a}")
1470 }
1471 }
1472 }
1473 for head in [
1477 "LET",
1478 "RETURN",
1479 "BREAK",
1480 "CONTINUE",
1481 "IF",
1482 "FOR",
1483 "WHILE",
1484 "FUNC",
1485 "REMOTE",
1486 "INHERIT_ENV",
1487 "WITH_IO",
1488 "ASYNC",
1489 "TIMEOUT",
1490 "ISOLATED",
1491 "AWAIT",
1492 "CANCEL",
1493 "RUN",
1494 "IMPORT",
1495 "EXPORT",
1496 "TYPE",
1497 ] {
1498 assert!(
1499 STRUCTURAL_KEYWORDS.contains(&head)
1500 || crate::all_metadata().iter().any(|m| m.name == head),
1501 "structural head {head} is not registered"
1502 );
1503 }
1504 }
1505
1506 #[test]
1510 fn command_names_group_by_category() {
1511 for command in COMMANDS {
1512 let name = command.as_str();
1513 let Some((prefix, _)) = name.split_once('_') else {
1514 continue;
1515 };
1516 assert!(
1517 COMMAND_CATEGORIES.contains(&prefix),
1518 "command {name} introduces unregistered category {prefix}; add it to COMMAND_CATEGORIES"
1519 );
1520 }
1521 }
1522}
1523
1524#[cfg(test)]
1525mod guard_analysis_tests {
1526 use super::*;
1527
1528 fn attr(ns: Ns, key: Option<&str>, val: Option<&str>) -> GuardExpr {
1529 GuardExpr::Predicate(Guard::Attr {
1530 ns,
1531 key: key.map(str::to_string),
1532 val: val.map(str::to_string),
1533 })
1534 }
1535
1536 fn os(value: &str) -> GuardExpr {
1537 attr(Ns::Os, None, Some(value))
1538 }
1539
1540 fn arch(value: &str) -> GuardExpr {
1541 attr(Ns::Arch, None, Some(value))
1542 }
1543
1544 fn unix() -> GuardExpr {
1547 GuardExpr::Or(vec![os("macos"), os("linux")])
1548 }
1549
1550 fn windows() -> GuardExpr {
1551 os("windows")
1552 }
1553
1554 fn env_eq(var: &str, value: &str) -> GuardExpr {
1555 attr(Ns::Env, Some(var), Some(value))
1556 }
1557
1558 fn not(expr: GuardExpr) -> GuardExpr {
1559 GuardExpr::Not(Box::new(expr))
1560 }
1561
1562 #[test]
1566 fn partition_negations_are_jointly_dead() {
1567 let os_exhausted = GuardExpr::All(vec![not(os("macos")), not(os("linux")), not(windows())]);
1568 assert!(
1569 !guard_satisfiable(&os_exhausted),
1570 "no host is outside `macos`/`linux`/`windows`"
1571 );
1572 let os_partial = GuardExpr::All(vec![not(os("macos")), not(os("linux"))]);
1574 assert!(guard_satisfiable(&os_partial), "`windows` is still open");
1575 let bool_exhausted = GuardExpr::All(vec![
1577 not(attr(Ns::Bool, None, Some("true"))),
1578 not(attr(Ns::Bool, None, Some("false"))),
1579 ]);
1580 assert!(!guard_satisfiable(&bool_exhausted));
1581 let env_open = GuardExpr::All(vec![
1583 not(env_eq("MODE", "dev")),
1584 not(env_eq("MODE", "prod")),
1585 ]);
1586 assert!(guard_satisfiable(&env_open), "MODE may hold a third value");
1587 assert!(guard_satisfiable(¬(unix())));
1589 }
1590
1591 #[test]
1594 fn unix_alias_is_os_disjunction() {
1595 assert!(!guards_overlap(Some(&unix()), Some(&windows())));
1596 assert!(guards_overlap(Some(&unix()), Some(&os("macos"))));
1597 let covered = GuardExpr::All(vec![GuardExpr::Not(Box::new(unix())), not(windows())]);
1600 assert!(!guard_satisfiable(&covered));
1601 }
1602
1603 #[test]
1607 fn arch_guards_decide_by_value() {
1608 assert!(!guards_overlap(
1609 Some(&arch("x86_64")),
1610 Some(&arch("aarch64"))
1611 ));
1612 assert!(guards_overlap(Some(&arch("x86_64")), Some(&arch("x86_64"))));
1613 assert!(guards_overlap(Some(&arch("aarch64")), Some(&os("macos"))));
1614 let exhausted = GuardExpr::All(ARCH_VALUES.iter().map(|value| not(arch(value))).collect());
1615 assert!(!guard_satisfiable(&exhausted));
1616 let host = attr(Ns::Arch, None, Some(ARCH_TARGET));
1618 assert!(guard_expr_allows(&host, &HashMap::new()));
1619 }
1620
1621 #[test]
1625 fn platform_overlap_matrix_is_exhaustive() {
1626 let cases = [
1627 ("macos", "macos", true),
1628 ("macos", "linux", false),
1629 ("macos", "windows", false),
1630 ("linux", "linux", true),
1631 ("linux", "windows", false),
1632 ("windows", "windows", true),
1633 ];
1634 for (v1, v2, expected) in cases {
1635 let left = os(v1);
1636 let right = os(v2);
1637 assert_eq!(
1638 guards_overlap(Some(&left), Some(&right)),
1639 expected,
1640 "os:{v1} vs os:{v2}"
1641 );
1642 }
1643 }
1644
1645 #[test]
1648 fn disjoint_pairs_never_cofire_here() {
1649 let macos = os("macos");
1650 let holds = |expr: &GuardExpr| guard_expr_allows(expr, &HashMap::new());
1651 assert!(
1652 !(holds(&macos) && holds(&windows())),
1653 "os:macos and os:windows co-fired"
1654 );
1655 }
1656
1657 #[test]
1658 fn overlap_follows_namespace_semantics() {
1659 assert!(!guards_overlap(Some(&windows()), Some(&unix())));
1661 assert!(!guards_overlap(Some(&os("macos")), Some(&os("linux"))));
1662 assert!(guards_overlap(None, Some(&windows())));
1664 assert!(guards_overlap(None, None));
1665 let dead = GuardExpr::All(vec![os("macos"), windows()]);
1667 assert!(!guard_satisfiable(&dead));
1668 assert!(!guards_overlap(Some(&dead), Some(&os("macos"))));
1669 assert!(guard_valid(&GuardExpr::Predicate(Guard::Attr {
1670 ns: Ns::Bool,
1671 key: None,
1672 val: Some("true".to_string()),
1673 })));
1674 assert!(!guard_valid(&unix()));
1675 }
1676
1677 #[test]
1678 fn env_value_conflicts_decide_without_enumeration() {
1679 let fast = env_eq("MODE", "fast");
1680 let slow = env_eq("MODE", "slow");
1681 assert!(
1682 !guards_overlap(Some(&fast), Some(&slow)),
1683 "same key distinct values are disjoint"
1684 );
1685 let also_fast = env_eq("MODE", "fast");
1686 assert!(guards_overlap(Some(&fast), Some(&also_fast)));
1687 let bare = attr(Ns::Env, Some("MODE"), None);
1689 assert!(guards_overlap(Some(&bare), Some(&fast)));
1690 }
1691}
1692
1693#[cfg(test)]
1694mod guard_algebra_tests {
1695 use super::*;
1696
1697 fn os(value: &str) -> GuardExpr {
1698 GuardExpr::Predicate(Guard::Attr {
1699 ns: Ns::Os,
1700 key: None,
1701 val: Some(value.to_string()),
1702 })
1703 }
1704
1705 #[test]
1706 fn or_distributes_over_disjointness() {
1707 fn env_eq(var: &str, value: &str) -> GuardExpr {
1708 GuardExpr::Predicate(Guard::Attr {
1709 ns: Ns::Env,
1710 key: Some(var.to_string()),
1711 val: Some(value.to_string()),
1712 })
1713 }
1714 let mixed = GuardExpr::Or(vec![env_eq("MODE", "dev"), env_eq("MODE", "prod")]);
1717 assert!(!mixed.is_disjoint_from(&env_eq("MODE", "dev")));
1718 assert!(mixed.is_disjoint_from(&env_eq("MODE", "test")));
1720 let cross = GuardExpr::Or(vec![env_eq("MODE", "dev")]);
1722 let platform = os("windows");
1723 assert!(!cross.is_disjoint_from(&platform));
1724 }
1725
1726 #[test]
1727 fn all_distributes_over_disjointness() {
1728 let stacked = GuardExpr::All(vec![
1729 os("macos"),
1730 GuardExpr::Or(vec![os("macos"), os("linux")]),
1731 os("windows"),
1732 ]);
1733 assert!(stacked.is_disjoint_from(&os("macos")));
1734 let live = GuardExpr::All(vec![
1737 os("macos"),
1738 GuardExpr::Predicate(Guard::Attr {
1739 ns: Ns::Env,
1740 key: Some("MODE".to_string()),
1741 val: Some("dev".to_string()),
1742 }),
1743 ]);
1744 assert!(!live.is_disjoint_from(&os("macos")));
1745 }
1746
1747 #[test]
1748 fn negation_is_structural_not_syntactic() {
1749 let not_win = GuardExpr::Not(Box::new(os("windows")));
1750 assert!(not_win.is_disjoint_from(&os("windows")));
1751 assert!(os("windows").is_disjoint_from(¬_win));
1752 assert!(!not_win.is_disjoint_from(&os("macos")));
1753 }
1754}