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