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