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_IN,
9 KEYWORD_ISOLATED, KEYWORD_LET, KEYWORD_REMOTE, KEYWORD_RETURN, KEYWORD_TIMEOUT, KEYWORD_TYPE,
10 KEYWORD_WHILE, KEYWORD_WITH_IO,
11};
12
13#[derive(Debug, Clone, Default)]
17pub struct ModuleFuncs {
18 pub func_names: HashSet<String>,
20}
21
22#[derive(Debug, Clone, Default)]
27pub struct ModuleTable {
28 pub modules: HashMap<String, Option<ModuleFuncs>>,
29}
30
31impl ModuleTable {
32 pub fn reserved_base_names(&self) -> HashSet<String> {
36 let mut out = HashSet::new();
37 for funcs in self.modules.values().flatten() {
38 out.extend(funcs.func_names.iter().cloned());
39 }
40 out
41 }
42}
43
44#[derive(Copy, Clone, Debug, Eq, PartialEq)]
52pub enum Command {
53 InheritEnv,
54 Workdir,
55 Workspace,
56 Env,
57 Echo,
58 Run,
59 Copy,
60 WithIo,
61 CopyGit,
62 Symlink,
63 Mkdir,
64 Install,
65 SetExecutable,
66 Archive,
67 Unarchive,
68 Ls,
69 Read,
70 ReadLine,
71 Prompt,
72 Write,
73 Append,
74 AppendLine,
75 Remove,
76 Expand,
77 AssertEq,
78 AssertNe,
79 AssertContains,
80 Exit,
81 Async,
82 Timeout,
83 Isolated,
84 Sleep,
85 ListAppend,
86}
87
88pub const COMMANDS: &[Command] = &[
89 Command::InheritEnv,
90 Command::Workdir,
91 Command::Workspace,
92 Command::Env,
93 Command::Echo,
94 Command::Run,
95 Command::Copy,
96 Command::WithIo,
97 Command::CopyGit,
98 Command::Symlink,
99 Command::Mkdir,
100 Command::Install,
101 Command::SetExecutable,
102 Command::Archive,
103 Command::Unarchive,
104 Command::Ls,
105 Command::Read,
106 Command::ReadLine,
107 Command::Prompt,
108 Command::Write,
109 Command::Append,
110 Command::AppendLine,
111 Command::Remove,
112 Command::Expand,
113 Command::AssertEq,
114 Command::AssertNe,
115 Command::AssertContains,
116 Command::Exit,
117 Command::Timeout,
118 Command::Isolated,
119 Command::Sleep,
120 Command::ListAppend,
121];
122
123pub const COMMAND_CATEGORIES: &[&str] = &[
128 "INHERIT", "WITH", "COPY", "HASH", "READ", "ASSERT", "LIST", "SET", "APPEND",
129];
130
131impl Command {
132 pub const fn as_str(self) -> &'static str {
133 match self {
134 Command::InheritEnv => "INHERIT_ENV",
135 Command::Workdir => "WORKDIR",
136 Command::Workspace => "WORKSPACE",
137 Command::Env => "ENV",
138 Command::Echo => "ECHO",
139 Command::Run => "RUN",
140 Command::Copy => "COPY",
141 Command::WithIo => KEYWORD_WITH_IO,
142 Command::CopyGit => "COPY_GIT",
143 Command::Symlink => "SYMLINK",
144 Command::Mkdir => "MKDIR",
145 Command::Install => "INSTALL",
146 Command::SetExecutable => "SET_EXECUTABLE",
147 Command::Archive => "ARCHIVE",
148 Command::Unarchive => "UNARCHIVE",
149 Command::Ls => "LS",
150 Command::Read => "READ",
151 Command::ReadLine => "READ_LINE",
152 Command::Prompt => "PROMPT",
153 Command::Write => "WRITE",
154 Command::Append => "APPEND",
155 Command::AppendLine => "APPEND_LINE",
156 Command::Remove => "REMOVE",
157 Command::Expand => "EXPAND",
158 Command::AssertEq => "ASSERT_EQ",
159 Command::AssertNe => "ASSERT_NE",
160 Command::AssertContains => "ASSERT_CONTAINS",
161 Command::Exit => "EXIT",
162 Command::Async => KEYWORD_ASYNC,
163 Command::Timeout => KEYWORD_TIMEOUT,
164 Command::Isolated => KEYWORD_ISOLATED,
165 Command::Sleep => "SLEEP",
166 Command::ListAppend => "LIST_APPEND",
167 }
168 }
169
170 pub const fn syntax(self) -> &'static str {
171 match self {
172 Command::InheritEnv => "INHERIT_ENV [KEY1, KEY2, ...]",
173 Command::Workdir => "WORKDIR <path>",
174 Command::Workspace => "WORKSPACE SNAPSHOT|LOCAL|CACHE|SYSTEM [--local]",
175 Command::Env => "ENV KEY=value",
176 Command::Echo => "ECHO <message>",
177 Command::Run => "RUN <command...> | RUN [\"exe\", \"arg\", ...]",
178 Command::Copy => "COPY [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>",
179 Command::CopyGit => "COPY_GIT [--include-dirty] <rev> <src> <dst>",
180 Command::WithIo => "WITH_IO [bindings] [command | { block }]",
181 Command::Symlink => {
182 "SYMLINK [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>"
183 }
184 Command::Mkdir => "MKDIR <path>",
185 Command::Install => "INSTALL <source> <dest>",
186 Command::SetExecutable => "SET_EXECUTABLE <path>",
187 Command::Archive => "ARCHIVE [--raw] <src> <dst>",
188 Command::Unarchive => "UNARCHIVE <src> <dst> [--max-bytes <bytes>]",
189 Command::Ls => "LS [<path>]",
190 Command::Read => "READ [<path>]",
191 Command::ReadLine => "READ_LINE $var",
192 Command::Prompt => "PROMPT $var <message> [<default>]",
193 Command::Write => "WRITE <path> [<contents>]",
194 Command::Append => "APPEND <path> [<contents>]",
195 Command::AppendLine => "APPEND_LINE <path> <contents>",
196 Command::Remove => "REMOVE [--recursive] <path>",
197 Command::Expand => "EXPAND [<path>] [<KEY=val> ...]",
198 Command::AssertEq => "ASSERT_EQ [--hash <sha256>] <actual> <expected>",
199 Command::AssertNe => "ASSERT_NE [--hash <sha256>] <actual> <expected>",
200 Command::AssertContains => "ASSERT_CONTAINS <haystack> <needle>",
201 Command::Exit => "EXIT <code>",
202 Command::Async => "ASYNC <command...> | ASYNC { <commands> }",
203 Command::Timeout => {
204 "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> }"
205 }
206 Command::Isolated => {
207 "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>"
208 }
209 Command::Sleep => "SLEEP <duration>",
210 Command::ListAppend => "LIST_APPEND $list <item>",
211 }
212 }
213
214 pub const fn expects_inner_command(self) -> bool {
215 matches!(
216 self,
217 Command::WithIo | Command::Async | Command::Timeout | Command::Isolated
218 )
219 }
220
221 pub fn parse(s: &str) -> Option<Self> {
222 match s {
223 "INHERIT_ENV" => Some(Command::InheritEnv),
224 "WORKDIR" => Some(Command::Workdir),
225 "WORKSPACE" => Some(Command::Workspace),
226 "ENV" => Some(Command::Env),
227 "ECHO" => Some(Command::Echo),
228 "RUN" => Some(Command::Run),
229 "COPY" => Some(Command::Copy),
230 KEYWORD_WITH_IO => Some(Command::WithIo),
231 "COPY_GIT" => Some(Command::CopyGit),
232 "SYMLINK" => Some(Command::Symlink),
233 "MKDIR" => Some(Command::Mkdir),
234 "INSTALL" => Some(Command::Install),
235 "SET_EXECUTABLE" => Some(Command::SetExecutable),
236 "ARCHIVE" => Some(Command::Archive),
237 "UNARCHIVE" => Some(Command::Unarchive),
238 "LS" => Some(Command::Ls),
239 "READ" => Some(Command::Read),
240 "READ_LINE" => Some(Command::ReadLine),
241 "PROMPT" => Some(Command::Prompt),
242 "WRITE" => Some(Command::Write),
243 "APPEND" => Some(Command::Append),
244 "APPEND_LINE" => Some(Command::AppendLine),
245 "REMOVE" => Some(Command::Remove),
246 "EXPAND" => Some(Command::Expand),
247 "ASSERT_EQ" => Some(Command::AssertEq),
248 "ASSERT_NE" => Some(Command::AssertNe),
249 "ASSERT_CONTAINS" => Some(Command::AssertContains),
250 "EXIT" => Some(Command::Exit),
251 KEYWORD_ASYNC => Some(Command::Async),
252 KEYWORD_TIMEOUT => Some(Command::Timeout),
253 KEYWORD_ISOLATED => Some(Command::Isolated),
254 "SLEEP" => Some(Command::Sleep),
255 "LIST_APPEND" => Some(Command::ListAppend),
256 _ => None,
257 }
258 }
259
260 pub(crate) fn is_statement_keyword(s: &str) -> bool {
265 Command::parse(s).is_some() || STRUCTURAL_KEYWORDS.contains(&s)
266 }
267}
268
269pub const STRUCTURAL_KEYWORDS: &[&str] = &[
275 KEYWORD_LET,
276 KEYWORD_FOR,
277 KEYWORD_IF,
278 KEYWORD_ELSE,
279 KEYWORD_ASYNC,
280 KEYWORD_AWAIT,
281 KEYWORD_CANCEL,
282 KEYWORD_FUNC,
283 KEYWORD_RETURN,
284 KEYWORD_WHILE,
285 KEYWORD_BREAK,
286 KEYWORD_CONTINUE,
287 KEYWORD_REMOTE,
288 KEYWORD_IMPORT,
289 KEYWORD_EXPORT,
290 KEYWORD_TYPE,
291];
292
293pub const CLAUSE_KEYWORDS: &[&str] = &[KEYWORD_IN];
298
299#[derive(Debug, Clone, Eq, PartialEq)]
312pub enum Guard {
313 Attr {
314 ns: Ns,
315 key: Option<String>,
316 val: Option<String>,
317 },
318}
319
320#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
324pub enum Ns {
325 Os,
326 Arch,
327 Bool,
328 Env,
329}
330
331impl fmt::Display for Ns {
332 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333 match self {
334 Ns::Os => write!(f, "os"),
335 Ns::Arch => write!(f, "arch"),
336 Ns::Bool => write!(f, "bool"),
337 Ns::Env => write!(f, "env"),
338 }
339 }
340}
341
342pub const ARCH_VALUES: &[&str] = &[
346 "aarch64",
347 "arm",
348 "arm64ec",
349 "avr",
350 "bpf",
351 "csky",
352 "hexagon",
353 "loongarch32",
354 "loongarch64",
355 "mips",
356 "mips32r6",
357 "mips64",
358 "mips64r6",
359 "msp430",
360 "nvptx64",
361 "powerpc",
362 "powerpc64",
363 "riscv32",
364 "riscv64",
365 "s390x",
366 "sparc",
367 "sparc64",
368 "wasm32",
369 "wasm64",
370 "x86",
371 "x86_64",
372 "xtensa",
373];
374
375#[derive(Debug, Clone, Eq, PartialEq)]
376pub enum GuardExpr {
377 Predicate(Guard),
378 All(Vec<GuardExpr>),
379 Or(Vec<GuardExpr>),
380 Not(Box<GuardExpr>),
381}
382
383impl GuardExpr {
384 pub fn all(exprs: Vec<GuardExpr>) -> GuardExpr {
385 let mut flat = Vec::new();
386 for expr in exprs {
387 match expr {
388 GuardExpr::All(children) => flat.extend(children),
389 other => flat.push(other),
390 }
391 }
392 match flat.len() {
393 0 => panic!("GuardExpr::all requires at least one expression"),
394 1 => flat.into_iter().next().unwrap(),
395 _ => GuardExpr::All(flat),
396 }
397 }
398
399 pub fn or(exprs: Vec<GuardExpr>) -> GuardExpr {
400 let mut flat = Vec::new();
401 for expr in exprs {
402 match expr {
403 GuardExpr::Or(children) => flat.extend(children),
404 other => flat.push(other),
405 }
406 }
407 match flat.len() {
408 0 => panic!("GuardExpr::or requires at least one expression"),
409 1 => flat.into_iter().next().unwrap(),
410 _ => GuardExpr::Or(flat),
411 }
412 }
413
414 pub fn invert(expr: GuardExpr) -> GuardExpr {
415 match expr {
416 GuardExpr::Not(inner) => *inner,
417 other => GuardExpr::Not(Box::new(other)),
418 }
419 }
420}
421
422impl std::ops::Not for GuardExpr {
423 type Output = GuardExpr;
424
425 fn not(self) -> GuardExpr {
426 match self {
427 GuardExpr::Not(inner) => *inner,
428 other => GuardExpr::Not(Box::new(other)),
429 }
430 }
431}
432
433impl From<Guard> for GuardExpr {
434 fn from(guard: Guard) -> Self {
435 GuardExpr::Predicate(guard)
436 }
437}
438
439#[derive(Debug, Clone, PartialEq)]
441pub enum Arg {
442 String(String, bool),
446 Expr(Expr),
448 Parts(Vec<ArgPart>),
452}
453
454#[derive(Debug, Clone, PartialEq)]
456pub enum ArgPart {
457 Text(String, bool),
460 Expr(Expr),
462}
463
464impl Arg {
465 pub fn as_str(&self) -> &str {
466 match self {
467 Arg::String(s, _) => s,
468 Arg::Expr(_) | Arg::Parts(_) => "",
471 }
472 }
473
474 pub fn render(&self) -> String {
478 match self {
479 Arg::String(s, _) => s.clone(),
480 Arg::Expr(e) => e.to_string(),
481 Arg::Parts(parts) => parts.iter().map(ArgPart::render).collect(),
482 }
483 }
484
485 pub fn is_quoted(&self) -> bool {
486 matches!(self, Arg::String(_, true))
487 }
488}
489
490impl ArgPart {
491 pub fn render(&self) -> String {
492 match self {
493 ArgPart::Text(s, _) => s.clone(),
494 ArgPart::Expr(e) => e.to_string(),
495 }
496 }
497}
498
499impl From<String> for Arg {
500 fn from(s: String) -> Self {
501 Arg::String(s, false)
502 }
503}
504
505impl From<&str> for Arg {
506 fn from(s: &str) -> Self {
507 Arg::String(s.to_string(), false)
508 }
509}
510
511impl std::fmt::Display for Arg {
512 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
513 match self {
514 Arg::String(s, _) => write!(f, "{}", s),
515 Arg::Expr(e) => write!(f, "{}", e),
516 Arg::Parts(parts) => {
517 for part in parts {
518 match part {
519 ArgPart::Text(s, _) => write!(f, "{}", s)?,
520 ArgPart::Expr(e) => write!(f, "{}", e)?,
521 }
522 }
523 Ok(())
524 }
525 }
526 }
527}
528
529impl AsRef<str> for Arg {
530 fn as_ref(&self) -> &str {
531 self.as_str()
532 }
533}
534
535impl PartialEq<str> for Arg {
536 fn eq(&self, other: &str) -> bool {
537 self.as_str() == other
538 }
539}
540
541impl PartialEq<&str> for Arg {
542 fn eq(&self, other: &&str) -> bool {
543 self.as_str() == *other
544 }
545}
546
547#[derive(Debug, Clone, Copy, Eq, PartialEq)]
548pub enum IoStream {
549 Stdin,
550 Stdout,
551 Stderr,
552 Tty,
556 Rows(u16),
558 Cols(u16),
560}
561
562#[derive(Debug, Clone, Eq, PartialEq)]
563pub struct IoBinding {
564 pub stream: IoStream,
565 pub pipe: Option<PipeTarget>,
566}
567
568#[derive(Debug, Clone, Eq, PartialEq)]
571pub enum PipeTarget {
572 Var(String),
573}
574
575pub use crate::value::{
579 OxDockType, SemaphoreState, TypeDescriptor, Value, ValuePayload, clone_boxed, clone_copy,
580 clone_shared, drop_boxed, drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed,
581 fmt_inline, fmt_shared, load_inline, startup_descriptors, store_inline, type_anchor,
582 unshare_boxed, unshare_inline, unshare_shared,
583};
584
585#[derive(Debug, Clone, Copy, Eq, PartialEq)]
586pub enum CompareOp {
587 Eq,
588 Ne,
589 Lt,
590 Le,
591 Gt,
592 Ge,
593}
594
595#[derive(Debug, Clone, Copy, Eq, PartialEq)]
596pub enum ArithOp {
597 Add,
598 Sub,
599 Mul,
600 Div,
601}
602
603#[derive(Debug, Clone, PartialEq)]
612pub enum MathOp {
613 PushConst(Value),
614 LoadVar(String),
615 LoadEnv(String),
616 LoadKeyPath { base: String, keys: Vec<String> },
617 Call { name: String, arity: usize },
618 Inspect(String),
619 Neg,
620 Add,
621 Sub,
622 Mul,
623 Div,
624 Lt,
625 Le,
626 Gt,
627 Ge,
628 Eq,
629 Ne,
630}
631
632#[derive(Debug, Clone, Copy, Eq, PartialEq)]
633pub enum LogicalOp {
634 And,
635 Or,
636}
637
638#[derive(Debug, Clone, PartialEq)]
639pub enum Expr {
640 Literal(Value),
641 Var(String),
642 Env(String),
645 KeyPath {
646 base: String,
647 keys: Vec<String>,
648 },
649 List(Vec<Expr>),
650 Map(Vec<(String, Expr)>),
651 Block(Vec<Step>),
656 Call {
657 name: String,
658 args: Vec<Expr>,
659 },
660 Inspect(String),
665 Compare {
666 op: CompareOp,
667 left: Box<Expr>,
668 right: Box<Expr>,
669 },
670 Arithmetic {
671 op: ArithOp,
672 left: Box<Expr>,
673 right: Box<Expr>,
674 },
675 CompiledMath(Vec<MathOp>),
678 FreshPipe,
684 UnsignedIntBoundary(u64),
688 Not(Box<Expr>),
689 Logical {
690 op: LogicalOp,
691 left: Box<Expr>,
692 right: Box<Expr>,
693 },
694}
695
696#[derive(Debug, Clone)]
697pub struct Step {
698 pub guard: Option<GuardExpr>,
699 pub kind: StepKind,
700 pub scope_enter: usize,
701 pub scope_exit: usize,
702 pub line: usize,
709 pub col: usize,
713}
714
715impl PartialEq for Step {
716 fn eq(&self, other: &Self) -> bool {
717 self.guard == other.guard
718 && self.kind == other.kind
719 && self.scope_enter == other.scope_enter
720 && self.scope_exit == other.scope_exit
721 }
722}
723
724impl Eq for Step {}
725
726impl Expr {
727 pub fn walk(&self, f: &mut impl FnMut(&Expr)) {
734 f(self);
735 match self {
736 Expr::Literal(_)
737 | Expr::Var(_)
738 | Expr::Env(_)
739 | Expr::KeyPath { .. }
740 | Expr::Inspect(_)
741 | Expr::FreshPipe
742 | Expr::UnsignedIntBoundary(_) => {}
743 Expr::Call { args, .. } => {
744 for arg in args {
745 arg.walk(f);
746 }
747 }
748 Expr::List(items) => {
749 for item in items {
750 item.walk(f);
751 }
752 }
753 Expr::Map(entries) => {
754 for (_, value) in entries {
755 value.walk(f);
756 }
757 }
758 Expr::Block(steps) => {
759 for step in steps {
760 step.kind.walk_step_exprs(f);
761 }
762 }
763 Expr::Compare { left, right, .. }
764 | Expr::Arithmetic { left, right, .. }
765 | Expr::Logical { left, right, .. } => {
766 left.walk(f);
767 right.walk(f);
768 }
769 Expr::CompiledMath(_) => {}
770 Expr::Not(inner) => inner.walk(f),
771 }
772 }
773}
774
775#[derive(Debug, Clone, Eq, PartialEq)]
776pub enum WorkspaceTarget {
777 Snapshot,
778 Local,
779 Cache { local: bool },
780 System,
781}
782
783pub trait EnvLookup {
784 fn get_env(&self, key: &str) -> Option<&str>;
785}
786
787impl EnvLookup for HashMap<String, String> {
788 fn get_env(&self, key: &str) -> Option<&str> {
789 self.get(key).map(|s| s.as_str())
790 }
791}
792
793impl EnvLookup for Arc<HashMap<String, String>> {
794 fn get_env(&self, key: &str) -> Option<&str> {
795 (**self).get_env(key)
796 }
797}
798
799pub fn guard_allows(guard: &Guard, env: &impl EnvLookup) -> bool {
800 let Guard::Attr { ns, key, val } = guard;
801 match ns {
802 Ns::Os => match val.as_deref() {
803 Some("macos") => platform_is_macos(),
804 Some("linux") => platform_is_linux(),
805 Some("windows") => platform_is_windows(),
806 _ => false,
807 },
808 Ns::Arch => match val.as_deref() {
809 Some(want) => ARCH_TARGET == want,
810 None => false,
811 },
812 Ns::Bool => val
813 .as_deref()
814 .map(|v| v.parse::<bool>().unwrap_or(false))
815 .unwrap_or(false),
816 Ns::Env => match key.as_deref() {
817 Some(var) => match val {
818 None => env.get_env(var).map(|v| !v.is_empty()).unwrap_or(false),
819 Some(want) => env
820 .get_env(var)
821 .map(|v| v == want.as_str())
822 .unwrap_or(false),
823 },
824 None => false,
826 },
827 }
828}
829
830#[allow(clippy::disallowed_macros)]
833fn platform_is_windows() -> bool {
834 cfg!(windows)
835}
836
837#[allow(clippy::disallowed_macros)]
839fn platform_is_macos() -> bool {
840 cfg!(target_os = "macos")
841}
842
843#[allow(clippy::disallowed_macros)]
845fn platform_is_linux() -> bool {
846 cfg!(target_os = "linux")
847}
848
849const ARCH_TARGET: &str = std::env::consts::ARCH;
852
853pub fn guard_expr_allows(expr: &GuardExpr, env: &impl EnvLookup) -> bool {
854 match expr {
855 GuardExpr::Predicate(guard) => guard_allows(guard, env),
856 GuardExpr::All(children) => children.iter().all(|g| guard_expr_allows(g, env)),
857 GuardExpr::Or(children) => children.iter().any(|g| guard_expr_allows(g, env)),
858 GuardExpr::Not(child) => !guard_expr_allows(child, env),
859 }
860}
861
862pub fn guard_option_allows(expr: Option<&GuardExpr>, env: &impl EnvLookup) -> bool {
863 match expr {
864 Some(e) => guard_expr_allows(e, env),
865 None => true,
866 }
867}
868
869impl Guard {
870 pub fn is_disjoint_from(&self, other: &Self) -> bool {
879 match (self, other) {
880 (
881 Guard::Attr {
882 ns: n1,
883 key: k1,
884 val: Some(v1),
885 },
886 Guard::Attr {
887 ns: n2,
888 key: k2,
889 val: Some(v2),
890 },
891 ) => n1 == n2 && k1 == k2 && v1 != v2,
892 _ => false,
893 }
894 }
895}
896
897impl GuardExpr {
898 pub fn is_disjoint_from(&self, other: &Self) -> bool {
904 match (self, other) {
905 (x, GuardExpr::Not(inner)) | (GuardExpr::Not(inner), x) => {
913 x == inner.as_ref() || unset_excludes(x, inner.as_ref())
914 }
915 (GuardExpr::Predicate(p1), GuardExpr::Predicate(p2)) => p1.is_disjoint_from(p2),
917 (GuardExpr::Or(arms), other) | (other, GuardExpr::Or(arms)) => {
919 arms.iter().all(|arm| arm.is_disjoint_from(other))
920 }
921 (GuardExpr::All(arms), other) | (other, GuardExpr::All(arms)) => {
923 arms.iter().any(|arm| arm.is_disjoint_from(other))
924 }
925 }
926 }
927}
928
929fn conjuncts(expr: &GuardExpr) -> Vec<&GuardExpr> {
933 match expr {
934 GuardExpr::All(items) => items.iter().collect(),
935 single => vec![single],
936 }
937}
938
939fn closed_domain_values(ns: Ns, key: Option<&str>) -> Option<&'static [&'static str]> {
946 match (ns, key) {
947 (Ns::Bool, None) => Some(&["true", "false"]),
948 (Ns::Os, None) => Some(&["macos", "linux", "windows"]),
949 (Ns::Arch, None) => Some(ARCH_VALUES),
950 _ => None,
951 }
952}
953
954#[derive(Clone)]
957enum DnfLit {
958 Pos(Guard),
959 Neg(Guard),
960}
961
962impl DnfLit {
963 fn as_expr(&self) -> GuardExpr {
964 match self {
965 DnfLit::Pos(guard) => GuardExpr::Predicate(guard.clone()),
966 DnfLit::Neg(guard) => GuardExpr::Not(Box::new(GuardExpr::Predicate(guard.clone()))),
967 }
968 }
969}
970
971const MAX_DNF_DISJUNCTS: usize = 64;
976
977fn dnf_push(expr: &GuardExpr, polarity: bool, out: &mut Vec<Vec<DnfLit>>) -> bool {
982 match (expr, polarity) {
983 (GuardExpr::Predicate(guard), true) => {
984 for disjunct in out.iter_mut() {
985 disjunct.push(DnfLit::Pos(guard.clone()));
986 }
987 true
988 }
989 (GuardExpr::Predicate(guard), false) => {
990 for disjunct in out.iter_mut() {
991 disjunct.push(DnfLit::Neg(guard.clone()));
992 }
993 true
994 }
995 (GuardExpr::All(children), true) | (GuardExpr::Or(children), false) => {
996 for child in children {
998 if !dnf_push(child, polarity, out) {
999 return false;
1000 }
1001 }
1002 true
1003 }
1004 (GuardExpr::Or(children), true) | (GuardExpr::All(children), false) => {
1005 let mut forked = Vec::new();
1007 for disjunct in out.drain(..) {
1008 for child in children {
1009 let mut branch = vec![disjunct.clone()];
1010 if !dnf_push(child, polarity, &mut branch) {
1011 return false;
1012 }
1013 forked.extend(branch);
1014 if forked.len() > MAX_DNF_DISJUNCTS {
1015 return false;
1016 }
1017 }
1018 }
1019 *out = forked;
1020 true
1021 }
1022 (GuardExpr::Not(inner), _) => dnf_push(inner, !polarity, out),
1023 }
1024}
1025
1026fn disjunct_satisfiable(lits: &[DnfLit]) -> bool {
1030 for lit in lits {
1034 match lit {
1035 DnfLit::Pos(Guard::Attr {
1036 ns: Ns::Bool, val, ..
1037 }) if val.as_deref() != Some("true") => return false,
1038 DnfLit::Neg(Guard::Attr {
1039 ns: Ns::Bool,
1040 key: None,
1041 val: Some(value),
1042 }) if value == "true" => return false,
1043 _ => {}
1044 }
1045 }
1046 for (index, first) in lits.iter().enumerate() {
1049 for second in &lits[index + 1..] {
1050 if first.as_expr().is_disjoint_from(&second.as_expr()) {
1051 return false;
1052 }
1053 }
1054 }
1055 for lit in lits {
1059 let (ns, key) = match lit {
1060 DnfLit::Neg(Guard::Attr {
1061 ns,
1062 key,
1063 val: Some(_),
1064 }) => (*ns, key.as_deref()),
1065 _ => continue,
1066 };
1067 let Some(domain) = closed_domain_values(ns, key) else {
1068 continue;
1069 };
1070 let exhausted = domain.iter().all(|value| {
1071 lits.iter().any(|other| match other {
1072 DnfLit::Neg(Guard::Attr {
1073 ns: other_ns,
1074 key: other_key,
1075 val: Some(other_val),
1076 }) => *other_ns == ns && other_key.as_deref() == key && other_val == value,
1077 _ => false,
1078 })
1079 });
1080 if exhausted {
1081 return false;
1082 }
1083 }
1084 true
1085}
1086
1087fn conjunction_dead(atoms: &[&GuardExpr]) -> bool {
1094 if atoms.is_empty() {
1095 return false;
1096 }
1097 let mut disjuncts = vec![Vec::new()];
1098 for atom in atoms {
1099 if !dnf_push(atom, true, &mut disjuncts) {
1100 return false;
1101 }
1102 }
1103 !disjuncts
1104 .iter()
1105 .any(|disjunct| disjunct_satisfiable(disjunct))
1106}
1107
1108pub fn guard_satisfiable(expr: &GuardExpr) -> bool {
1110 !conjunction_dead(&conjuncts(expr))
1111}
1112
1113pub fn guard_valid(expr: &GuardExpr) -> bool {
1116 match expr {
1117 GuardExpr::Predicate(Guard::Attr {
1118 ns: Ns::Bool,
1119 val: Some(value),
1120 ..
1121 }) => value.as_str() == "true",
1122 GuardExpr::All(items) => items.iter().all(guard_valid),
1123 GuardExpr::Not(inner) => !guard_satisfiable(inner),
1124 _ => false,
1125 }
1126}
1127
1128pub fn guards_overlap(a: Option<&GuardExpr>, b: Option<&GuardExpr>) -> bool {
1131 match (a, b) {
1132 (None, None) => true,
1133 (Some(x), None) | (None, Some(x)) => guard_satisfiable(x),
1134 (Some(x), Some(y)) => {
1135 let mut atoms = conjuncts(x);
1136 atoms.extend(conjuncts(y));
1137 !conjunction_dead(&atoms)
1138 }
1139 }
1140}
1141
1142fn unset_excludes(x: &GuardExpr, inner: &GuardExpr) -> bool {
1145 match (x, inner) {
1146 (
1147 GuardExpr::Predicate(Guard::Attr {
1148 ns: n2, key: k2, ..
1149 }),
1150 GuardExpr::Predicate(Guard::Attr {
1151 ns: n1,
1152 key: k1,
1153 val: None,
1154 }),
1155 ) => n1 == n2 && k1 == k2,
1156 _ => false,
1157 }
1158}
1159
1160impl fmt::Display for Guard {
1161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1167 match self {
1168 Guard::Attr {
1169 ns: Ns::Env,
1170 key: Some(var),
1171 val: None,
1172 } => write!(f, "env:{var}"),
1173 Guard::Attr {
1174 ns: Ns::Env,
1175 key: Some(var),
1176 val: Some(want),
1177 } => write!(f, "eq(env:{var}, {want})"),
1178 Guard::Attr {
1179 ns,
1180 key: _,
1181 val: Some(value),
1182 } => write!(f, "{ns}:{value}"),
1183 Guard::Attr { ns, key, val: None } => match key {
1184 Some(subject) => write!(f, "{ns}:{subject}"),
1185 None => write!(f, "{ns}"),
1186 },
1187 }
1188 }
1189}
1190
1191impl fmt::Display for WorkspaceTarget {
1192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1193 match self {
1194 WorkspaceTarget::Snapshot => write!(f, "SNAPSHOT"),
1195 WorkspaceTarget::Local => write!(f, "LOCAL"),
1196 WorkspaceTarget::Cache { local: false } => write!(f, "CACHE"),
1197 WorkspaceTarget::Cache { local: true } => write!(f, "CACHE --local"),
1198 WorkspaceTarget::System => write!(f, "SYSTEM"),
1199 }
1200 }
1201}
1202
1203impl fmt::Display for Expr {
1204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1205 match self {
1206 Expr::Literal(v) => write!(f, "{}", v),
1207 Expr::Var(name) => write!(f, "${}", name),
1208 Expr::Env(key) => write!(f, "env:{}", key),
1209 Expr::KeyPath { base, keys } => {
1210 write!(f, "${}", base)?;
1211 for key in keys {
1212 write!(f, ".{}", key)?;
1213 }
1214 Ok(())
1215 }
1216 Expr::Call { name, args } => {
1217 write!(f, "{}(", name)?;
1218 for (i, arg) in args.iter().enumerate() {
1219 if i > 0 {
1220 write!(f, ", ")?;
1221 }
1222 write!(f, "{}", arg)?;
1223 }
1224 write!(f, ")")
1225 }
1226 Expr::Inspect(var) => write!(f, "INSPECT(${})", var),
1227 Expr::List(items) => {
1228 write!(f, "[")?;
1229 for (i, item) in items.iter().enumerate() {
1230 if i > 0 {
1231 write!(f, ", ")?;
1232 }
1233 write!(f, "{}", item)?;
1234 }
1235 write!(f, "]")
1236 }
1237 Expr::Map(entries) => {
1238 write!(f, "{{")?;
1239 for (i, (key, val)) in entries.iter().enumerate() {
1240 if i > 0 {
1241 write!(f, ", ")?;
1242 }
1243 write!(f, "\"{}\": {}", key, val)?;
1244 }
1245 write!(f, "}}")
1246 }
1247 Expr::Block(steps) => {
1248 write!(f, "{{ ")?;
1249 for (i, step) in steps.iter().enumerate() {
1250 if i > 0 {
1251 write!(f, "; ")?;
1252 }
1253 write!(f, "{}", step.kind)?;
1254 }
1255 write!(f, " }}")
1256 }
1257 Expr::Compare { op, left, right } => {
1258 write!(f, "({} {} {})", left, op, right)
1262 }
1263 Expr::Arithmetic { op, left, right } => {
1264 write!(f, "({} {} {})", left, op, right)
1265 }
1266 Expr::CompiledMath(ops) => {
1267 write!(f, "{}", format_compiled_math(ops))
1268 }
1269 Expr::FreshPipe => write!(f, "<fresh pipe>"),
1273 Expr::UnsignedIntBoundary(n) => write!(f, "{}", n),
1274 Expr::Not(inner) => {
1275 match inner.as_ref() {
1278 Expr::Compare { .. } | Expr::Arithmetic { .. } | Expr::CompiledMath(_) => {
1279 write!(f, "!({})", inner)
1280 }
1281 _ => write!(f, "!{}", inner),
1282 }
1283 }
1284 Expr::Logical { op, left, right } => {
1285 write!(f, "({} {} {})", left, op, right)
1286 }
1287 }
1288 }
1289}
1290
1291impl fmt::Display for CompareOp {
1292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1293 match self {
1294 CompareOp::Eq => write!(f, "=="),
1295 CompareOp::Ne => write!(f, "!="),
1296 CompareOp::Lt => write!(f, "<"),
1297 CompareOp::Le => write!(f, "<="),
1298 CompareOp::Gt => write!(f, ">"),
1299 CompareOp::Ge => write!(f, ">="),
1300 }
1301 }
1302}
1303
1304impl fmt::Display for ArithOp {
1305 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1306 match self {
1307 ArithOp::Add => write!(f, "+"),
1308 ArithOp::Sub => write!(f, "-"),
1309 ArithOp::Mul => write!(f, "*"),
1310 ArithOp::Div => write!(f, "/"),
1311 }
1312 }
1313}
1314
1315fn format_compiled_math(ops: &[MathOp]) -> String {
1320 let mut stack: Vec<String> = Vec::new();
1321 for op in ops {
1322 match op {
1323 MathOp::PushConst(v) => stack.push(format!("{}", v)),
1324 MathOp::LoadVar(name) => stack.push(format!("${}", name)),
1325 MathOp::LoadEnv(key) => stack.push(format!("env:{}", key)),
1326 MathOp::LoadKeyPath { base, keys } => {
1327 let mut s = format!("${}", base);
1328 for key in keys {
1329 s.push('.');
1330 s.push_str(key);
1331 }
1332 stack.push(s);
1333 }
1334 MathOp::Call { name, arity } => {
1335 let mut args = Vec::new();
1336 for _ in 0..*arity {
1337 args.push(stack.pop().unwrap_or_else(|| "<underflow>".to_string()));
1338 }
1339 args.reverse();
1340 stack.push(format!("{}({})", name, args.join(", ")));
1341 }
1342 MathOp::Inspect(name) => stack.push(format!("INSPECT(${})", name)),
1343 MathOp::Neg => {
1344 let inner = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1345 stack.push(format!("(-{})", inner));
1346 }
1347 MathOp::Add => push_bin(&mut stack, "+"),
1348 MathOp::Sub => push_bin(&mut stack, "-"),
1349 MathOp::Mul => push_bin(&mut stack, "*"),
1350 MathOp::Div => push_bin(&mut stack, "/"),
1351 MathOp::Lt => push_bin(&mut stack, "<"),
1352 MathOp::Le => push_bin(&mut stack, "<="),
1353 MathOp::Gt => push_bin(&mut stack, ">"),
1354 MathOp::Ge => push_bin(&mut stack, ">="),
1355 MathOp::Eq => push_bin(&mut stack, "=="),
1356 MathOp::Ne => push_bin(&mut stack, "!="),
1357 }
1358 }
1359 if stack.len() == 1 {
1360 let mut items = stack;
1361 items.pop().unwrap_or_else(|| "<empty>".to_string())
1362 } else {
1363 stack.join(" ")
1364 }
1365}
1366
1367fn push_bin(stack: &mut Vec<String>, op: &str) {
1368 let right = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1369 let left = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1370 stack.push(format!("({} {} {})", left, op, right));
1371}
1372
1373impl fmt::Display for LogicalOp {
1374 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1375 match self {
1376 LogicalOp::And => write!(f, "&&"),
1377 LogicalOp::Or => write!(f, "||"),
1378 }
1379 }
1380}
1381
1382enum GuardDisplayContext {
1383 Root,
1384 InAnyArg,
1385 InNot,
1386 InAll,
1387}
1388
1389impl GuardExpr {
1390 fn fmt_with_ctx(&self, f: &mut fmt::Formatter<'_>, ctx: GuardDisplayContext) -> fmt::Result {
1391 match self {
1392 GuardExpr::Predicate(guard) => write!(f, "{}", guard),
1393 GuardExpr::All(children) => {
1394 let wrap = matches!(
1395 ctx,
1396 GuardDisplayContext::InAnyArg | GuardDisplayContext::InNot
1397 ) && children.len() > 1;
1398 if wrap {
1399 write!(f, "(")?;
1400 }
1401 for (i, child) in children.iter().enumerate() {
1402 if i > 0 {
1403 write!(f, ", ")?;
1404 }
1405 child.fmt_with_ctx(f, GuardDisplayContext::InAll)?;
1406 }
1407 if wrap {
1408 write!(f, ")")?;
1409 }
1410 Ok(())
1411 }
1412 GuardExpr::Or(children) => {
1413 write!(f, "any(")?;
1414 for (i, child) in children.iter().enumerate() {
1415 if i > 0 {
1416 write!(f, ", ")?;
1417 }
1418 child.fmt_with_ctx(f, GuardDisplayContext::InAnyArg)?;
1419 }
1420 write!(f, ")")
1421 }
1422 GuardExpr::Not(child) => {
1423 write!(f, "not(")?;
1424 child.fmt_with_ctx(f, GuardDisplayContext::InNot)?;
1425 write!(f, ")")
1426 }
1427 }
1428 }
1429}
1430
1431impl fmt::Display for GuardExpr {
1432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1433 self.fmt_with_ctx(f, GuardDisplayContext::Root)
1434 }
1435}
1436
1437impl fmt::Display for Step {
1438 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1439 if let Some(expr) = &self.guard {
1440 write!(f, "[{}] ", expr)?;
1441 }
1442 write!(f, "{}", self.kind)
1443 }
1444}
1445
1446#[cfg(test)]
1447mod tests {
1448 use super::*;
1449 #[test]
1457 fn statement_keywords_match_backend() {
1458 for kw in STRUCTURAL_KEYWORDS {
1466 let via_backend = crate::parse_script(kw, crate::commands::lower_command);
1467 let via_lowering =
1468 crate::commands::lower_command(kw, Vec::new()).map(|kind| crate::Step {
1469 guard: None,
1470 kind,
1471 scope_enter: 0,
1472 scope_exit: 0,
1473 line: 0,
1474 col: 0,
1475 });
1476 match (via_backend, via_lowering) {
1477 (Ok(_), _) => {}
1478 (Err(a), Err(b)) => {
1479 assert_eq!(
1480 a.kind(),
1481 b.kind(),
1482 "backend kind drift for bare keyword {kw}: {a} vs {b}"
1483 );
1484 }
1485 (Err(a), Ok(_)) => {
1486 panic!("backend rejects bare keyword {kw} that lowering accepts: {a}")
1487 }
1488 }
1489 }
1490 for head in [
1494 "LET",
1495 "RETURN",
1496 "BREAK",
1497 "CONTINUE",
1498 "IF",
1499 "FOR",
1500 "WHILE",
1501 "FUNC",
1502 "REMOTE",
1503 "INHERIT_ENV",
1504 "WITH_IO",
1505 "ASYNC",
1506 "TIMEOUT",
1507 "ISOLATED",
1508 "AWAIT",
1509 "CANCEL",
1510 "RUN",
1511 "IMPORT",
1512 "EXPORT",
1513 "TYPE",
1514 ] {
1515 assert!(
1516 STRUCTURAL_KEYWORDS.contains(&head)
1517 || crate::all_metadata().iter().any(|m| m.name == head),
1518 "structural head {head} is not registered"
1519 );
1520 }
1521 }
1522
1523 #[test]
1527 fn command_names_group_by_category() {
1528 for command in COMMANDS {
1529 let name = command.as_str();
1530 let Some((prefix, _)) = name.split_once('_') else {
1531 continue;
1532 };
1533 assert!(
1534 COMMAND_CATEGORIES.contains(&prefix),
1535 "command {name} introduces unregistered category {prefix}; add it to COMMAND_CATEGORIES"
1536 );
1537 }
1538 }
1539
1540 #[test]
1548 fn registry_commands_all_parse() {
1549 for meta in crate::all_metadata() {
1550 if !meta.in_index || STRUCTURAL_KEYWORDS.contains(&meta.name) {
1551 continue;
1552 }
1553 assert!(
1554 Command::parse(meta.name).is_some(),
1555 "registry command {} has no Command::parse arm",
1556 meta.name
1557 );
1558 }
1559 }
1560}
1561
1562#[cfg(test)]
1563mod guard_analysis_tests {
1564 use super::*;
1565
1566 fn attr(ns: Ns, key: Option<&str>, val: Option<&str>) -> GuardExpr {
1567 GuardExpr::Predicate(Guard::Attr {
1568 ns,
1569 key: key.map(str::to_string),
1570 val: val.map(str::to_string),
1571 })
1572 }
1573
1574 fn os(value: &str) -> GuardExpr {
1575 attr(Ns::Os, None, Some(value))
1576 }
1577
1578 fn arch(value: &str) -> GuardExpr {
1579 attr(Ns::Arch, None, Some(value))
1580 }
1581
1582 fn unix() -> GuardExpr {
1585 GuardExpr::Or(vec![os("macos"), os("linux")])
1586 }
1587
1588 fn windows() -> GuardExpr {
1589 os("windows")
1590 }
1591
1592 fn env_eq(var: &str, value: &str) -> GuardExpr {
1593 attr(Ns::Env, Some(var), Some(value))
1594 }
1595
1596 fn not(expr: GuardExpr) -> GuardExpr {
1597 GuardExpr::Not(Box::new(expr))
1598 }
1599
1600 #[test]
1604 fn partition_negations_are_jointly_dead() {
1605 let os_exhausted = GuardExpr::All(vec![not(os("macos")), not(os("linux")), not(windows())]);
1606 assert!(
1607 !guard_satisfiable(&os_exhausted),
1608 "no host is outside `macos`/`linux`/`windows`"
1609 );
1610 let os_partial = GuardExpr::All(vec![not(os("macos")), not(os("linux"))]);
1612 assert!(guard_satisfiable(&os_partial), "`windows` is still open");
1613 let bool_exhausted = GuardExpr::All(vec![
1615 not(attr(Ns::Bool, None, Some("true"))),
1616 not(attr(Ns::Bool, None, Some("false"))),
1617 ]);
1618 assert!(!guard_satisfiable(&bool_exhausted));
1619 let env_open = GuardExpr::All(vec![
1621 not(env_eq("MODE", "dev")),
1622 not(env_eq("MODE", "prod")),
1623 ]);
1624 assert!(guard_satisfiable(&env_open), "MODE may hold a third value");
1625 assert!(guard_satisfiable(¬(unix())));
1627 }
1628
1629 #[test]
1632 fn unix_alias_is_os_disjunction() {
1633 assert!(!guards_overlap(Some(&unix()), Some(&windows())));
1634 assert!(guards_overlap(Some(&unix()), Some(&os("macos"))));
1635 let covered = GuardExpr::All(vec![GuardExpr::Not(Box::new(unix())), not(windows())]);
1638 assert!(!guard_satisfiable(&covered));
1639 }
1640
1641 #[test]
1645 fn arch_guards_decide_by_value() {
1646 assert!(!guards_overlap(
1647 Some(&arch("x86_64")),
1648 Some(&arch("aarch64"))
1649 ));
1650 assert!(guards_overlap(Some(&arch("x86_64")), Some(&arch("x86_64"))));
1651 assert!(guards_overlap(Some(&arch("aarch64")), Some(&os("macos"))));
1652 let exhausted = GuardExpr::All(ARCH_VALUES.iter().map(|value| not(arch(value))).collect());
1653 assert!(!guard_satisfiable(&exhausted));
1654 let host = attr(Ns::Arch, None, Some(ARCH_TARGET));
1656 assert!(guard_expr_allows(&host, &HashMap::new()));
1657 }
1658
1659 #[test]
1663 fn platform_overlap_matrix_is_exhaustive() {
1664 let cases = [
1665 ("macos", "macos", true),
1666 ("macos", "linux", false),
1667 ("macos", "windows", false),
1668 ("linux", "linux", true),
1669 ("linux", "windows", false),
1670 ("windows", "windows", true),
1671 ];
1672 for (v1, v2, expected) in cases {
1673 let left = os(v1);
1674 let right = os(v2);
1675 assert_eq!(
1676 guards_overlap(Some(&left), Some(&right)),
1677 expected,
1678 "os:{v1} vs os:{v2}"
1679 );
1680 }
1681 }
1682
1683 #[test]
1686 fn disjoint_pairs_never_cofire_here() {
1687 let macos = os("macos");
1688 let holds = |expr: &GuardExpr| guard_expr_allows(expr, &HashMap::new());
1689 assert!(
1690 !(holds(&macos) && holds(&windows())),
1691 "os:macos and os:windows co-fired"
1692 );
1693 }
1694
1695 #[test]
1696 fn overlap_follows_namespace_semantics() {
1697 assert!(!guards_overlap(Some(&windows()), Some(&unix())));
1699 assert!(!guards_overlap(Some(&os("macos")), Some(&os("linux"))));
1700 assert!(guards_overlap(None, Some(&windows())));
1702 assert!(guards_overlap(None, None));
1703 let dead = GuardExpr::All(vec![os("macos"), windows()]);
1705 assert!(!guard_satisfiable(&dead));
1706 assert!(!guards_overlap(Some(&dead), Some(&os("macos"))));
1707 assert!(guard_valid(&GuardExpr::Predicate(Guard::Attr {
1708 ns: Ns::Bool,
1709 key: None,
1710 val: Some("true".to_string()),
1711 })));
1712 assert!(!guard_valid(&unix()));
1713 }
1714
1715 #[test]
1716 fn env_value_conflicts_decide_without_enumeration() {
1717 let fast = env_eq("MODE", "fast");
1718 let slow = env_eq("MODE", "slow");
1719 assert!(
1720 !guards_overlap(Some(&fast), Some(&slow)),
1721 "same key distinct values are disjoint"
1722 );
1723 let also_fast = env_eq("MODE", "fast");
1724 assert!(guards_overlap(Some(&fast), Some(&also_fast)));
1725 let bare = attr(Ns::Env, Some("MODE"), None);
1727 assert!(guards_overlap(Some(&bare), Some(&fast)));
1728 }
1729}
1730
1731#[cfg(test)]
1732mod guard_algebra_tests {
1733 use super::*;
1734
1735 fn os(value: &str) -> GuardExpr {
1736 GuardExpr::Predicate(Guard::Attr {
1737 ns: Ns::Os,
1738 key: None,
1739 val: Some(value.to_string()),
1740 })
1741 }
1742
1743 #[test]
1744 fn or_distributes_over_disjointness() {
1745 fn env_eq(var: &str, value: &str) -> GuardExpr {
1746 GuardExpr::Predicate(Guard::Attr {
1747 ns: Ns::Env,
1748 key: Some(var.to_string()),
1749 val: Some(value.to_string()),
1750 })
1751 }
1752 let mixed = GuardExpr::Or(vec![env_eq("MODE", "dev"), env_eq("MODE", "prod")]);
1755 assert!(!mixed.is_disjoint_from(&env_eq("MODE", "dev")));
1756 assert!(mixed.is_disjoint_from(&env_eq("MODE", "test")));
1758 let cross = GuardExpr::Or(vec![env_eq("MODE", "dev")]);
1760 let platform = os("windows");
1761 assert!(!cross.is_disjoint_from(&platform));
1762 }
1763
1764 #[test]
1765 fn all_distributes_over_disjointness() {
1766 let stacked = GuardExpr::All(vec![
1767 os("macos"),
1768 GuardExpr::Or(vec![os("macos"), os("linux")]),
1769 os("windows"),
1770 ]);
1771 assert!(stacked.is_disjoint_from(&os("macos")));
1772 let live = GuardExpr::All(vec![
1775 os("macos"),
1776 GuardExpr::Predicate(Guard::Attr {
1777 ns: Ns::Env,
1778 key: Some("MODE".to_string()),
1779 val: Some("dev".to_string()),
1780 }),
1781 ]);
1782 assert!(!live.is_disjoint_from(&os("macos")));
1783 }
1784
1785 #[test]
1786 fn negation_is_structural_not_syntactic() {
1787 let not_win = GuardExpr::Not(Box::new(os("windows")));
1788 assert!(not_win.is_disjoint_from(&os("windows")));
1789 assert!(os("windows").is_disjoint_from(¬_win));
1790 assert!(!not_win.is_disjoint_from(&os("macos")));
1791 }
1792}