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 pub fn walk_mut(&mut self, f: &mut impl FnMut(&mut Expr)) {
781 f(self);
782 match self {
783 Expr::Literal(_)
784 | Expr::Var(_)
785 | Expr::Env(_)
786 | Expr::KeyPath { .. }
787 | Expr::Inspect(_)
788 | Expr::FreshPipe
789 | Expr::UnsignedIntBoundary(_) => {}
790 Expr::Call { args, .. } => {
791 for arg in args {
792 arg.walk_mut(f);
793 }
794 }
795 Expr::List(items) => {
796 for item in items {
797 item.walk_mut(f);
798 }
799 }
800 Expr::Map(entries) => {
801 for (_, value) in entries {
802 value.walk_mut(f);
803 }
804 }
805 Expr::Block(_) => {}
806 Expr::Compare { left, right, .. }
807 | Expr::Arithmetic { left, right, .. }
808 | Expr::Logical { left, right, .. } => {
809 left.walk_mut(f);
810 right.walk_mut(f);
811 }
812 Expr::CompiledMath(_) => {}
813 Expr::Not(inner) => inner.walk_mut(f),
814 }
815 }
816}
817
818#[derive(Debug, Clone, Eq, PartialEq)]
819pub enum WorkspaceTarget {
820 Snapshot,
821 Local,
822 Cache { local: bool },
823 System,
824}
825
826pub trait EnvLookup {
827 fn get_env(&self, key: &str) -> Option<&str>;
828}
829
830impl EnvLookup for HashMap<String, String> {
831 fn get_env(&self, key: &str) -> Option<&str> {
832 self.get(key).map(|s| s.as_str())
833 }
834}
835
836impl EnvLookup for Arc<HashMap<String, String>> {
837 fn get_env(&self, key: &str) -> Option<&str> {
838 (**self).get_env(key)
839 }
840}
841
842pub fn guard_allows(guard: &Guard, env: &impl EnvLookup) -> bool {
843 let Guard::Attr { ns, key, val } = guard;
844 match ns {
845 Ns::Os => match val.as_deref() {
846 Some("macos") => platform_is_macos(),
847 Some("linux") => platform_is_linux(),
848 Some("windows") => platform_is_windows(),
849 _ => false,
850 },
851 Ns::Arch => match val.as_deref() {
852 Some(want) => ARCH_TARGET == want,
853 None => false,
854 },
855 Ns::Bool => val
856 .as_deref()
857 .map(|v| v.parse::<bool>().unwrap_or(false))
858 .unwrap_or(false),
859 Ns::Env => match key.as_deref() {
860 Some(var) => match val {
861 None => env.get_env(var).map(|v| !v.is_empty()).unwrap_or(false),
862 Some(want) => env
863 .get_env(var)
864 .map(|v| v == want.as_str())
865 .unwrap_or(false),
866 },
867 None => false,
869 },
870 }
871}
872
873#[allow(clippy::disallowed_macros)]
876fn platform_is_windows() -> bool {
877 cfg!(windows)
878}
879
880#[allow(clippy::disallowed_macros)]
882fn platform_is_macos() -> bool {
883 cfg!(target_os = "macos")
884}
885
886#[allow(clippy::disallowed_macros)]
888fn platform_is_linux() -> bool {
889 cfg!(target_os = "linux")
890}
891
892const ARCH_TARGET: &str = std::env::consts::ARCH;
895
896pub fn guard_expr_allows(expr: &GuardExpr, env: &impl EnvLookup) -> bool {
897 match expr {
898 GuardExpr::Predicate(guard) => guard_allows(guard, env),
899 GuardExpr::All(children) => children.iter().all(|g| guard_expr_allows(g, env)),
900 GuardExpr::Or(children) => children.iter().any(|g| guard_expr_allows(g, env)),
901 GuardExpr::Not(child) => !guard_expr_allows(child, env),
902 }
903}
904
905pub fn guard_option_allows(expr: Option<&GuardExpr>, env: &impl EnvLookup) -> bool {
906 match expr {
907 Some(e) => guard_expr_allows(e, env),
908 None => true,
909 }
910}
911
912impl Guard {
913 pub fn is_disjoint_from(&self, other: &Self) -> bool {
922 match (self, other) {
923 (
924 Guard::Attr {
925 ns: n1,
926 key: k1,
927 val: Some(v1),
928 },
929 Guard::Attr {
930 ns: n2,
931 key: k2,
932 val: Some(v2),
933 },
934 ) => n1 == n2 && k1 == k2 && v1 != v2,
935 _ => false,
936 }
937 }
938}
939
940impl GuardExpr {
941 pub fn is_disjoint_from(&self, other: &Self) -> bool {
947 match (self, other) {
948 (x, GuardExpr::Not(inner)) | (GuardExpr::Not(inner), x) => {
956 x == inner.as_ref() || unset_excludes(x, inner.as_ref())
957 }
958 (GuardExpr::Predicate(p1), GuardExpr::Predicate(p2)) => p1.is_disjoint_from(p2),
960 (GuardExpr::Or(arms), other) | (other, GuardExpr::Or(arms)) => {
962 arms.iter().all(|arm| arm.is_disjoint_from(other))
963 }
964 (GuardExpr::All(arms), other) | (other, GuardExpr::All(arms)) => {
966 arms.iter().any(|arm| arm.is_disjoint_from(other))
967 }
968 }
969 }
970}
971
972fn conjuncts(expr: &GuardExpr) -> Vec<&GuardExpr> {
976 match expr {
977 GuardExpr::All(items) => items.iter().collect(),
978 single => vec![single],
979 }
980}
981
982fn closed_domain_values(ns: Ns, key: Option<&str>) -> Option<&'static [&'static str]> {
989 match (ns, key) {
990 (Ns::Bool, None) => Some(&["true", "false"]),
991 (Ns::Os, None) => Some(&["macos", "linux", "windows"]),
992 (Ns::Arch, None) => Some(ARCH_VALUES),
993 _ => None,
994 }
995}
996
997#[derive(Clone)]
1000enum DnfLit {
1001 Pos(Guard),
1002 Neg(Guard),
1003}
1004
1005impl DnfLit {
1006 fn as_expr(&self) -> GuardExpr {
1007 match self {
1008 DnfLit::Pos(guard) => GuardExpr::Predicate(guard.clone()),
1009 DnfLit::Neg(guard) => GuardExpr::Not(Box::new(GuardExpr::Predicate(guard.clone()))),
1010 }
1011 }
1012}
1013
1014const MAX_DNF_DISJUNCTS: usize = 64;
1019
1020fn dnf_push(expr: &GuardExpr, polarity: bool, out: &mut Vec<Vec<DnfLit>>) -> bool {
1025 match (expr, polarity) {
1026 (GuardExpr::Predicate(guard), true) => {
1027 for disjunct in out.iter_mut() {
1028 disjunct.push(DnfLit::Pos(guard.clone()));
1029 }
1030 true
1031 }
1032 (GuardExpr::Predicate(guard), false) => {
1033 for disjunct in out.iter_mut() {
1034 disjunct.push(DnfLit::Neg(guard.clone()));
1035 }
1036 true
1037 }
1038 (GuardExpr::All(children), true) | (GuardExpr::Or(children), false) => {
1039 for child in children {
1041 if !dnf_push(child, polarity, out) {
1042 return false;
1043 }
1044 }
1045 true
1046 }
1047 (GuardExpr::Or(children), true) | (GuardExpr::All(children), false) => {
1048 let mut forked = Vec::new();
1050 for disjunct in out.drain(..) {
1051 for child in children {
1052 let mut branch = vec![disjunct.clone()];
1053 if !dnf_push(child, polarity, &mut branch) {
1054 return false;
1055 }
1056 forked.extend(branch);
1057 if forked.len() > MAX_DNF_DISJUNCTS {
1058 return false;
1059 }
1060 }
1061 }
1062 *out = forked;
1063 true
1064 }
1065 (GuardExpr::Not(inner), _) => dnf_push(inner, !polarity, out),
1066 }
1067}
1068
1069fn disjunct_satisfiable(lits: &[DnfLit]) -> bool {
1073 for lit in lits {
1077 match lit {
1078 DnfLit::Pos(Guard::Attr {
1079 ns: Ns::Bool, val, ..
1080 }) if val.as_deref() != Some("true") => return false,
1081 DnfLit::Neg(Guard::Attr {
1082 ns: Ns::Bool,
1083 key: None,
1084 val: Some(value),
1085 }) if value == "true" => return false,
1086 _ => {}
1087 }
1088 }
1089 for (index, first) in lits.iter().enumerate() {
1092 for second in &lits[index + 1..] {
1093 if first.as_expr().is_disjoint_from(&second.as_expr()) {
1094 return false;
1095 }
1096 }
1097 }
1098 for lit in lits {
1102 let (ns, key) = match lit {
1103 DnfLit::Neg(Guard::Attr {
1104 ns,
1105 key,
1106 val: Some(_),
1107 }) => (*ns, key.as_deref()),
1108 _ => continue,
1109 };
1110 let Some(domain) = closed_domain_values(ns, key) else {
1111 continue;
1112 };
1113 let exhausted = domain.iter().all(|value| {
1114 lits.iter().any(|other| match other {
1115 DnfLit::Neg(Guard::Attr {
1116 ns: other_ns,
1117 key: other_key,
1118 val: Some(other_val),
1119 }) => *other_ns == ns && other_key.as_deref() == key && other_val == value,
1120 _ => false,
1121 })
1122 });
1123 if exhausted {
1124 return false;
1125 }
1126 }
1127 true
1128}
1129
1130fn conjunction_dead(atoms: &[&GuardExpr]) -> bool {
1137 if atoms.is_empty() {
1138 return false;
1139 }
1140 let mut disjuncts = vec![Vec::new()];
1141 for atom in atoms {
1142 if !dnf_push(atom, true, &mut disjuncts) {
1143 return false;
1144 }
1145 }
1146 !disjuncts
1147 .iter()
1148 .any(|disjunct| disjunct_satisfiable(disjunct))
1149}
1150
1151pub fn guard_satisfiable(expr: &GuardExpr) -> bool {
1153 !conjunction_dead(&conjuncts(expr))
1154}
1155
1156pub fn guard_valid(expr: &GuardExpr) -> bool {
1159 match expr {
1160 GuardExpr::Predicate(Guard::Attr {
1161 ns: Ns::Bool,
1162 val: Some(value),
1163 ..
1164 }) => value.as_str() == "true",
1165 GuardExpr::All(items) => items.iter().all(guard_valid),
1166 GuardExpr::Not(inner) => !guard_satisfiable(inner),
1167 _ => false,
1168 }
1169}
1170
1171pub fn guards_overlap(a: Option<&GuardExpr>, b: Option<&GuardExpr>) -> bool {
1174 match (a, b) {
1175 (None, None) => true,
1176 (Some(x), None) | (None, Some(x)) => guard_satisfiable(x),
1177 (Some(x), Some(y)) => {
1178 let mut atoms = conjuncts(x);
1179 atoms.extend(conjuncts(y));
1180 !conjunction_dead(&atoms)
1181 }
1182 }
1183}
1184
1185fn unset_excludes(x: &GuardExpr, inner: &GuardExpr) -> bool {
1188 match (x, inner) {
1189 (
1190 GuardExpr::Predicate(Guard::Attr {
1191 ns: n2, key: k2, ..
1192 }),
1193 GuardExpr::Predicate(Guard::Attr {
1194 ns: n1,
1195 key: k1,
1196 val: None,
1197 }),
1198 ) => n1 == n2 && k1 == k2,
1199 _ => false,
1200 }
1201}
1202
1203impl fmt::Display for Guard {
1204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1210 match self {
1211 Guard::Attr {
1212 ns: Ns::Env,
1213 key: Some(var),
1214 val: None,
1215 } => write!(f, "env:{var}"),
1216 Guard::Attr {
1217 ns: Ns::Env,
1218 key: Some(var),
1219 val: Some(want),
1220 } => write!(f, "eq(env:{var}, {want})"),
1221 Guard::Attr {
1222 ns,
1223 key: _,
1224 val: Some(value),
1225 } => write!(f, "{ns}:{value}"),
1226 Guard::Attr { ns, key, val: None } => match key {
1227 Some(subject) => write!(f, "{ns}:{subject}"),
1228 None => write!(f, "{ns}"),
1229 },
1230 }
1231 }
1232}
1233
1234impl fmt::Display for WorkspaceTarget {
1235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1236 match self {
1237 WorkspaceTarget::Snapshot => write!(f, "SNAPSHOT"),
1238 WorkspaceTarget::Local => write!(f, "LOCAL"),
1239 WorkspaceTarget::Cache { local: false } => write!(f, "CACHE"),
1240 WorkspaceTarget::Cache { local: true } => write!(f, "CACHE --local"),
1241 WorkspaceTarget::System => write!(f, "SYSTEM"),
1242 }
1243 }
1244}
1245
1246impl fmt::Display for Expr {
1247 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1248 match self {
1249 Expr::Literal(v) => write!(f, "{}", v),
1250 Expr::Var(name) => write!(f, "${}", name),
1251 Expr::Env(key) => write!(f, "env:{}", key),
1252 Expr::KeyPath { base, keys } => {
1253 write!(f, "${}", base)?;
1254 for key in keys {
1255 write!(f, ".{}", key)?;
1256 }
1257 Ok(())
1258 }
1259 Expr::Call { name, args } => {
1260 write!(f, "{}(", name)?;
1261 for (i, arg) in args.iter().enumerate() {
1262 if i > 0 {
1263 write!(f, ", ")?;
1264 }
1265 write!(f, "{}", arg)?;
1266 }
1267 write!(f, ")")
1268 }
1269 Expr::Inspect(var) => write!(f, "INSPECT(${})", var),
1270 Expr::List(items) => {
1271 write!(f, "[")?;
1272 for (i, item) in items.iter().enumerate() {
1273 if i > 0 {
1274 write!(f, ", ")?;
1275 }
1276 write!(f, "{}", item)?;
1277 }
1278 write!(f, "]")
1279 }
1280 Expr::Map(entries) => {
1281 write!(f, "{{")?;
1282 for (i, (key, val)) in entries.iter().enumerate() {
1283 if i > 0 {
1284 write!(f, ", ")?;
1285 }
1286 write!(f, "\"{}\": {}", key, val)?;
1287 }
1288 write!(f, "}}")
1289 }
1290 Expr::Block(steps) => {
1291 write!(f, "{{ ")?;
1292 for (i, step) in steps.iter().enumerate() {
1293 if i > 0 {
1294 write!(f, "; ")?;
1295 }
1296 write!(f, "{}", step.kind)?;
1297 }
1298 write!(f, " }}")
1299 }
1300 Expr::Compare { op, left, right } => {
1301 write!(f, "({} {} {})", left, op, right)
1305 }
1306 Expr::Arithmetic { op, left, right } => {
1307 write!(f, "({} {} {})", left, op, right)
1308 }
1309 Expr::CompiledMath(ops) => {
1310 write!(f, "{}", format_compiled_math(ops))
1311 }
1312 Expr::FreshPipe => write!(f, "<fresh pipe>"),
1316 Expr::UnsignedIntBoundary(n) => write!(f, "{}", n),
1317 Expr::Not(inner) => {
1318 match inner.as_ref() {
1321 Expr::Compare { .. } | Expr::Arithmetic { .. } | Expr::CompiledMath(_) => {
1322 write!(f, "!({})", inner)
1323 }
1324 _ => write!(f, "!{}", inner),
1325 }
1326 }
1327 Expr::Logical { op, left, right } => {
1328 write!(f, "({} {} {})", left, op, right)
1329 }
1330 }
1331 }
1332}
1333
1334impl fmt::Display for CompareOp {
1335 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1336 match self {
1337 CompareOp::Eq => write!(f, "=="),
1338 CompareOp::Ne => write!(f, "!="),
1339 CompareOp::Lt => write!(f, "<"),
1340 CompareOp::Le => write!(f, "<="),
1341 CompareOp::Gt => write!(f, ">"),
1342 CompareOp::Ge => write!(f, ">="),
1343 }
1344 }
1345}
1346
1347impl fmt::Display for ArithOp {
1348 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1349 match self {
1350 ArithOp::Add => write!(f, "+"),
1351 ArithOp::Sub => write!(f, "-"),
1352 ArithOp::Mul => write!(f, "*"),
1353 ArithOp::Div => write!(f, "/"),
1354 }
1355 }
1356}
1357
1358fn format_compiled_math(ops: &[MathOp]) -> String {
1363 let mut stack: Vec<String> = Vec::new();
1364 for op in ops {
1365 match op {
1366 MathOp::PushConst(v) => stack.push(format!("{}", v)),
1367 MathOp::LoadVar(name) => stack.push(format!("${}", name)),
1368 MathOp::LoadEnv(key) => stack.push(format!("env:{}", key)),
1369 MathOp::LoadKeyPath { base, keys } => {
1370 let mut s = format!("${}", base);
1371 for key in keys {
1372 s.push('.');
1373 s.push_str(key);
1374 }
1375 stack.push(s);
1376 }
1377 MathOp::Call { name, arity } => {
1378 let mut args = Vec::new();
1379 for _ in 0..*arity {
1380 args.push(stack.pop().unwrap_or_else(|| "<underflow>".to_string()));
1381 }
1382 args.reverse();
1383 stack.push(format!("{}({})", name, args.join(", ")));
1384 }
1385 MathOp::Inspect(name) => stack.push(format!("INSPECT(${})", name)),
1386 MathOp::Neg => {
1387 let inner = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1388 stack.push(format!("(-{})", inner));
1389 }
1390 MathOp::Add => push_bin(&mut stack, "+"),
1391 MathOp::Sub => push_bin(&mut stack, "-"),
1392 MathOp::Mul => push_bin(&mut stack, "*"),
1393 MathOp::Div => push_bin(&mut stack, "/"),
1394 MathOp::Lt => push_bin(&mut stack, "<"),
1395 MathOp::Le => push_bin(&mut stack, "<="),
1396 MathOp::Gt => push_bin(&mut stack, ">"),
1397 MathOp::Ge => push_bin(&mut stack, ">="),
1398 MathOp::Eq => push_bin(&mut stack, "=="),
1399 MathOp::Ne => push_bin(&mut stack, "!="),
1400 }
1401 }
1402 if stack.len() == 1 {
1403 let mut items = stack;
1404 items.pop().unwrap_or_else(|| "<empty>".to_string())
1405 } else {
1406 stack.join(" ")
1407 }
1408}
1409
1410fn push_bin(stack: &mut Vec<String>, op: &str) {
1411 let right = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1412 let left = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1413 stack.push(format!("({} {} {})", left, op, right));
1414}
1415
1416impl fmt::Display for LogicalOp {
1417 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1418 match self {
1419 LogicalOp::And => write!(f, "&&"),
1420 LogicalOp::Or => write!(f, "||"),
1421 }
1422 }
1423}
1424
1425enum GuardDisplayContext {
1426 Root,
1427 InAnyArg,
1428 InNot,
1429 InAll,
1430}
1431
1432impl GuardExpr {
1433 fn fmt_with_ctx(&self, f: &mut fmt::Formatter<'_>, ctx: GuardDisplayContext) -> fmt::Result {
1434 match self {
1435 GuardExpr::Predicate(guard) => write!(f, "{}", guard),
1436 GuardExpr::All(children) => {
1437 let wrap = matches!(
1438 ctx,
1439 GuardDisplayContext::InAnyArg | GuardDisplayContext::InNot
1440 ) && children.len() > 1;
1441 if wrap {
1442 write!(f, "(")?;
1443 }
1444 for (i, child) in children.iter().enumerate() {
1445 if i > 0 {
1446 write!(f, ", ")?;
1447 }
1448 child.fmt_with_ctx(f, GuardDisplayContext::InAll)?;
1449 }
1450 if wrap {
1451 write!(f, ")")?;
1452 }
1453 Ok(())
1454 }
1455 GuardExpr::Or(children) => {
1456 write!(f, "any(")?;
1457 for (i, child) in children.iter().enumerate() {
1458 if i > 0 {
1459 write!(f, ", ")?;
1460 }
1461 child.fmt_with_ctx(f, GuardDisplayContext::InAnyArg)?;
1462 }
1463 write!(f, ")")
1464 }
1465 GuardExpr::Not(child) => {
1466 write!(f, "not(")?;
1467 child.fmt_with_ctx(f, GuardDisplayContext::InNot)?;
1468 write!(f, ")")
1469 }
1470 }
1471 }
1472}
1473
1474impl fmt::Display for GuardExpr {
1475 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1476 self.fmt_with_ctx(f, GuardDisplayContext::Root)
1477 }
1478}
1479
1480impl fmt::Display for Step {
1481 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1482 if let Some(expr) = &self.guard {
1483 write!(f, "[{}] ", expr)?;
1484 }
1485 write!(f, "{}", self.kind)
1486 }
1487}
1488
1489#[cfg(test)]
1490mod tests {
1491 use super::*;
1492 #[test]
1500 fn statement_keywords_match_backend() {
1501 for kw in STRUCTURAL_KEYWORDS {
1509 let via_backend = crate::parse_script(kw, crate::commands::lower_command);
1510 let via_lowering =
1511 crate::commands::lower_command(kw, Vec::new()).map(|kind| crate::Step {
1512 guard: None,
1513 kind,
1514 scope_enter: 0,
1515 scope_exit: 0,
1516 line: 0,
1517 col: 0,
1518 });
1519 match (via_backend, via_lowering) {
1520 (Ok(_), _) => {}
1521 (Err(a), Err(b)) => {
1522 assert_eq!(
1523 a.kind(),
1524 b.kind(),
1525 "backend kind drift for bare keyword {kw}: {a} vs {b}"
1526 );
1527 }
1528 (Err(a), Ok(_)) => {
1529 panic!("backend rejects bare keyword {kw} that lowering accepts: {a}")
1530 }
1531 }
1532 }
1533 for head in [
1537 "LET",
1538 "RETURN",
1539 "BREAK",
1540 "CONTINUE",
1541 "IF",
1542 "FOR",
1543 "WHILE",
1544 "FUNC",
1545 "REMOTE",
1546 "INHERIT_ENV",
1547 "WITH_IO",
1548 "ASYNC",
1549 "TIMEOUT",
1550 "ISOLATED",
1551 "AWAIT",
1552 "CANCEL",
1553 "RUN",
1554 "IMPORT",
1555 "EXPORT",
1556 "TYPE",
1557 ] {
1558 assert!(
1559 STRUCTURAL_KEYWORDS.contains(&head)
1560 || crate::all_metadata().iter().any(|m| m.name == head),
1561 "structural head {head} is not registered"
1562 );
1563 }
1564 }
1565
1566 #[test]
1570 fn command_names_group_by_category() {
1571 for command in COMMANDS {
1572 let name = command.as_str();
1573 let Some((prefix, _)) = name.split_once('_') else {
1574 continue;
1575 };
1576 assert!(
1577 COMMAND_CATEGORIES.contains(&prefix),
1578 "command {name} introduces unregistered category {prefix}; add it to COMMAND_CATEGORIES"
1579 );
1580 }
1581 }
1582
1583 #[test]
1591 fn registry_commands_all_parse() {
1592 for meta in crate::all_metadata() {
1593 if !meta.in_index || STRUCTURAL_KEYWORDS.contains(&meta.name) {
1594 continue;
1595 }
1596 assert!(
1597 Command::parse(meta.name).is_some(),
1598 "registry command {} has no Command::parse arm",
1599 meta.name
1600 );
1601 }
1602 }
1603}
1604
1605#[cfg(test)]
1606mod guard_analysis_tests {
1607 use super::*;
1608
1609 fn attr(ns: Ns, key: Option<&str>, val: Option<&str>) -> GuardExpr {
1610 GuardExpr::Predicate(Guard::Attr {
1611 ns,
1612 key: key.map(str::to_string),
1613 val: val.map(str::to_string),
1614 })
1615 }
1616
1617 fn os(value: &str) -> GuardExpr {
1618 attr(Ns::Os, None, Some(value))
1619 }
1620
1621 fn arch(value: &str) -> GuardExpr {
1622 attr(Ns::Arch, None, Some(value))
1623 }
1624
1625 fn unix() -> GuardExpr {
1628 GuardExpr::Or(vec![os("macos"), os("linux")])
1629 }
1630
1631 fn windows() -> GuardExpr {
1632 os("windows")
1633 }
1634
1635 fn env_eq(var: &str, value: &str) -> GuardExpr {
1636 attr(Ns::Env, Some(var), Some(value))
1637 }
1638
1639 fn not(expr: GuardExpr) -> GuardExpr {
1640 GuardExpr::Not(Box::new(expr))
1641 }
1642
1643 #[test]
1647 fn partition_negations_are_jointly_dead() {
1648 let os_exhausted = GuardExpr::All(vec![not(os("macos")), not(os("linux")), not(windows())]);
1649 assert!(
1650 !guard_satisfiable(&os_exhausted),
1651 "no host is outside `macos`/`linux`/`windows`"
1652 );
1653 let os_partial = GuardExpr::All(vec![not(os("macos")), not(os("linux"))]);
1655 assert!(guard_satisfiable(&os_partial), "`windows` is still open");
1656 let bool_exhausted = GuardExpr::All(vec![
1658 not(attr(Ns::Bool, None, Some("true"))),
1659 not(attr(Ns::Bool, None, Some("false"))),
1660 ]);
1661 assert!(!guard_satisfiable(&bool_exhausted));
1662 let env_open = GuardExpr::All(vec![
1664 not(env_eq("MODE", "dev")),
1665 not(env_eq("MODE", "prod")),
1666 ]);
1667 assert!(guard_satisfiable(&env_open), "MODE may hold a third value");
1668 assert!(guard_satisfiable(¬(unix())));
1670 }
1671
1672 #[test]
1675 fn unix_alias_is_os_disjunction() {
1676 assert!(!guards_overlap(Some(&unix()), Some(&windows())));
1677 assert!(guards_overlap(Some(&unix()), Some(&os("macos"))));
1678 let covered = GuardExpr::All(vec![GuardExpr::Not(Box::new(unix())), not(windows())]);
1681 assert!(!guard_satisfiable(&covered));
1682 }
1683
1684 #[test]
1688 fn arch_guards_decide_by_value() {
1689 assert!(!guards_overlap(
1690 Some(&arch("x86_64")),
1691 Some(&arch("aarch64"))
1692 ));
1693 assert!(guards_overlap(Some(&arch("x86_64")), Some(&arch("x86_64"))));
1694 assert!(guards_overlap(Some(&arch("aarch64")), Some(&os("macos"))));
1695 let exhausted = GuardExpr::All(ARCH_VALUES.iter().map(|value| not(arch(value))).collect());
1696 assert!(!guard_satisfiable(&exhausted));
1697 let host = attr(Ns::Arch, None, Some(ARCH_TARGET));
1699 assert!(guard_expr_allows(&host, &HashMap::new()));
1700 }
1701
1702 #[test]
1706 fn platform_overlap_matrix_is_exhaustive() {
1707 let cases = [
1708 ("macos", "macos", true),
1709 ("macos", "linux", false),
1710 ("macos", "windows", false),
1711 ("linux", "linux", true),
1712 ("linux", "windows", false),
1713 ("windows", "windows", true),
1714 ];
1715 for (v1, v2, expected) in cases {
1716 let left = os(v1);
1717 let right = os(v2);
1718 assert_eq!(
1719 guards_overlap(Some(&left), Some(&right)),
1720 expected,
1721 "os:{v1} vs os:{v2}"
1722 );
1723 }
1724 }
1725
1726 #[test]
1729 fn disjoint_pairs_never_cofire_here() {
1730 let macos = os("macos");
1731 let holds = |expr: &GuardExpr| guard_expr_allows(expr, &HashMap::new());
1732 assert!(
1733 !(holds(&macos) && holds(&windows())),
1734 "os:macos and os:windows co-fired"
1735 );
1736 }
1737
1738 #[test]
1739 fn overlap_follows_namespace_semantics() {
1740 assert!(!guards_overlap(Some(&windows()), Some(&unix())));
1742 assert!(!guards_overlap(Some(&os("macos")), Some(&os("linux"))));
1743 assert!(guards_overlap(None, Some(&windows())));
1745 assert!(guards_overlap(None, None));
1746 let dead = GuardExpr::All(vec![os("macos"), windows()]);
1748 assert!(!guard_satisfiable(&dead));
1749 assert!(!guards_overlap(Some(&dead), Some(&os("macos"))));
1750 assert!(guard_valid(&GuardExpr::Predicate(Guard::Attr {
1751 ns: Ns::Bool,
1752 key: None,
1753 val: Some("true".to_string()),
1754 })));
1755 assert!(!guard_valid(&unix()));
1756 }
1757
1758 #[test]
1759 fn env_value_conflicts_decide_without_enumeration() {
1760 let fast = env_eq("MODE", "fast");
1761 let slow = env_eq("MODE", "slow");
1762 assert!(
1763 !guards_overlap(Some(&fast), Some(&slow)),
1764 "same key distinct values are disjoint"
1765 );
1766 let also_fast = env_eq("MODE", "fast");
1767 assert!(guards_overlap(Some(&fast), Some(&also_fast)));
1768 let bare = attr(Ns::Env, Some("MODE"), None);
1770 assert!(guards_overlap(Some(&bare), Some(&fast)));
1771 }
1772}
1773
1774#[cfg(test)]
1775mod guard_algebra_tests {
1776 use super::*;
1777
1778 fn os(value: &str) -> GuardExpr {
1779 GuardExpr::Predicate(Guard::Attr {
1780 ns: Ns::Os,
1781 key: None,
1782 val: Some(value.to_string()),
1783 })
1784 }
1785
1786 #[test]
1787 fn or_distributes_over_disjointness() {
1788 fn env_eq(var: &str, value: &str) -> GuardExpr {
1789 GuardExpr::Predicate(Guard::Attr {
1790 ns: Ns::Env,
1791 key: Some(var.to_string()),
1792 val: Some(value.to_string()),
1793 })
1794 }
1795 let mixed = GuardExpr::Or(vec![env_eq("MODE", "dev"), env_eq("MODE", "prod")]);
1798 assert!(!mixed.is_disjoint_from(&env_eq("MODE", "dev")));
1799 assert!(mixed.is_disjoint_from(&env_eq("MODE", "test")));
1801 let cross = GuardExpr::Or(vec![env_eq("MODE", "dev")]);
1803 let platform = os("windows");
1804 assert!(!cross.is_disjoint_from(&platform));
1805 }
1806
1807 #[test]
1808 fn all_distributes_over_disjointness() {
1809 let stacked = GuardExpr::All(vec![
1810 os("macos"),
1811 GuardExpr::Or(vec![os("macos"), os("linux")]),
1812 os("windows"),
1813 ]);
1814 assert!(stacked.is_disjoint_from(&os("macos")));
1815 let live = GuardExpr::All(vec![
1818 os("macos"),
1819 GuardExpr::Predicate(Guard::Attr {
1820 ns: Ns::Env,
1821 key: Some("MODE".to_string()),
1822 val: Some("dev".to_string()),
1823 }),
1824 ]);
1825 assert!(!live.is_disjoint_from(&os("macos")));
1826 }
1827
1828 #[test]
1829 fn negation_is_structural_not_syntactic() {
1830 let not_win = GuardExpr::Not(Box::new(os("windows")));
1831 assert!(not_win.is_disjoint_from(&os("windows")));
1832 assert!(os("windows").is_disjoint_from(¬_win));
1833 assert!(!not_win.is_disjoint_from(&os("macos")));
1834 }
1835}