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