1use std::collections::{HashMap, HashSet};
2use std::fmt;
3use std::sync::Arc;
4
5pub use crate::commands::{AssertTarget, StepKind};
6use crate::constants::{
7 KEYWORD_APPEND, KEYWORD_APPEND_LINE, KEYWORD_ARCHIVE, KEYWORD_ASSERT_CONTAINS,
8 KEYWORD_ASSERT_EQ, KEYWORD_ASSERT_NE, KEYWORD_ASYNC, KEYWORD_AWAIT, KEYWORD_BREAK,
9 KEYWORD_CANCEL, KEYWORD_CASE, KEYWORD_CONTINUE, KEYWORD_COPY, KEYWORD_COPY_GIT,
10 KEYWORD_DEFAULT, KEYWORD_ECHO, KEYWORD_ELSE, KEYWORD_ENV, KEYWORD_EXIT, KEYWORD_EXPAND,
11 KEYWORD_EXPORT, KEYWORD_FOR, KEYWORD_FUNC, KEYWORD_IF, KEYWORD_IMPORT, KEYWORD_IN,
12 KEYWORD_INHERIT_ENV, KEYWORD_INSTALL, KEYWORD_ISOLATED, KEYWORD_LET, KEYWORD_LIST_APPEND,
13 KEYWORD_LS, KEYWORD_MKDIR, KEYWORD_PROMPT, KEYWORD_READ, KEYWORD_READ_LINE, KEYWORD_REMOTE,
14 KEYWORD_REMOVE, KEYWORD_RETURN, KEYWORD_RUN, KEYWORD_SET_EXECUTABLE, KEYWORD_SLEEP,
15 KEYWORD_SWITCH, KEYWORD_SYMLINK, KEYWORD_TIMEOUT, KEYWORD_TYPE, KEYWORD_UNARCHIVE,
16 KEYWORD_WHILE, KEYWORD_WITH_IO, KEYWORD_WORKDIR, KEYWORD_WORKSPACE, KEYWORD_WRITE,
17};
18
19#[derive(Debug, Clone, Default)]
23pub struct ModuleFuncs {
24 pub func_names: HashSet<String>,
26}
27
28#[derive(Debug, Clone, Default)]
33pub struct ModuleTable {
34 pub modules: HashMap<String, Option<ModuleFuncs>>,
35}
36
37impl ModuleTable {
38 pub fn reserved_base_names(&self) -> HashSet<String> {
42 let mut out = HashSet::new();
43 for funcs in self.modules.values().flatten() {
44 out.extend(funcs.func_names.iter().cloned());
45 }
46 out
47 }
48}
49
50#[derive(Copy, Clone, Debug, Eq, PartialEq)]
58pub enum Command {
59 InheritEnv,
60 Workdir,
61 Workspace,
62 Env,
63 Echo,
64 Run,
65 Copy,
66 WithIo,
67 CopyGit,
68 Symlink,
69 Mkdir,
70 Install,
71 SetExecutable,
72 Archive,
73 Unarchive,
74 Ls,
75 Read,
76 ReadLine,
77 Prompt,
78 Write,
79 Append,
80 AppendLine,
81 Remove,
82 Expand,
83 AssertEq,
84 AssertNe,
85 AssertContains,
86 Exit,
87 Async,
88 Timeout,
89 Isolated,
90 Sleep,
91 ListAppend,
92}
93
94pub const COMMANDS: &[Command] = &[
95 Command::InheritEnv,
96 Command::Workdir,
97 Command::Workspace,
98 Command::Env,
99 Command::Echo,
100 Command::Run,
101 Command::Copy,
102 Command::WithIo,
103 Command::CopyGit,
104 Command::Symlink,
105 Command::Mkdir,
106 Command::Install,
107 Command::SetExecutable,
108 Command::Archive,
109 Command::Unarchive,
110 Command::Ls,
111 Command::Read,
112 Command::ReadLine,
113 Command::Prompt,
114 Command::Write,
115 Command::Append,
116 Command::AppendLine,
117 Command::Remove,
118 Command::Expand,
119 Command::AssertEq,
120 Command::AssertNe,
121 Command::AssertContains,
122 Command::Exit,
123 Command::Timeout,
124 Command::Isolated,
125 Command::Sleep,
126 Command::ListAppend,
127];
128
129pub const COMMAND_CATEGORIES: &[&str] = &[
134 "INHERIT", "WITH", "COPY", "HASH", "READ", "ASSERT", "LIST", "SET", "APPEND",
135];
136
137impl Command {
138 pub const fn as_str(self) -> &'static str {
139 match self {
140 Command::InheritEnv => KEYWORD_INHERIT_ENV,
141 Command::Workdir => KEYWORD_WORKDIR,
142 Command::Workspace => KEYWORD_WORKSPACE,
143 Command::Env => KEYWORD_ENV,
144 Command::Echo => KEYWORD_ECHO,
145 Command::Run => KEYWORD_RUN,
146 Command::Copy => KEYWORD_COPY,
147 Command::WithIo => KEYWORD_WITH_IO,
148 Command::CopyGit => KEYWORD_COPY_GIT,
149 Command::Symlink => KEYWORD_SYMLINK,
150 Command::Mkdir => KEYWORD_MKDIR,
151 Command::Install => KEYWORD_INSTALL,
152 Command::SetExecutable => KEYWORD_SET_EXECUTABLE,
153 Command::Archive => KEYWORD_ARCHIVE,
154 Command::Unarchive => KEYWORD_UNARCHIVE,
155 Command::Ls => KEYWORD_LS,
156 Command::Read => KEYWORD_READ,
157 Command::ReadLine => KEYWORD_READ_LINE,
158 Command::Prompt => KEYWORD_PROMPT,
159 Command::Write => KEYWORD_WRITE,
160 Command::Append => KEYWORD_APPEND,
161 Command::AppendLine => KEYWORD_APPEND_LINE,
162 Command::Remove => KEYWORD_REMOVE,
163 Command::Expand => KEYWORD_EXPAND,
164 Command::AssertEq => KEYWORD_ASSERT_EQ,
165 Command::AssertNe => KEYWORD_ASSERT_NE,
166 Command::AssertContains => KEYWORD_ASSERT_CONTAINS,
167 Command::Exit => KEYWORD_EXIT,
168 Command::Async => KEYWORD_ASYNC,
169 Command::Timeout => KEYWORD_TIMEOUT,
170 Command::Isolated => KEYWORD_ISOLATED,
171 Command::Sleep => KEYWORD_SLEEP,
172 Command::ListAppend => KEYWORD_LIST_APPEND,
173 }
174 }
175
176 pub const fn syntax(self) -> &'static str {
177 match self {
178 Command::InheritEnv => "INHERIT_ENV [KEY1, KEY2, ...]",
179 Command::Workdir => "WORKDIR <path>",
180 Command::Workspace => "WORKSPACE SNAPSHOT|LOCAL|CACHE|SYSTEM [--local]",
181 Command::Env => "ENV KEY=value",
182 Command::Echo => "ECHO <message>",
183 Command::Run => "RUN <command...> | RUN [\"exe\", \"arg\", ...]",
184 Command::Copy => "COPY [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>",
185 Command::CopyGit => "COPY_GIT [--include-dirty] <rev> <src> <dst>",
186 Command::WithIo => "WITH_IO [bindings] [command | { block }]",
187 Command::Symlink => {
188 "SYMLINK [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>"
189 }
190 Command::Mkdir => "MKDIR <path>",
191 Command::Install => "INSTALL <source> <dest>",
192 Command::SetExecutable => "SET_EXECUTABLE <path>",
193 Command::Archive => "ARCHIVE [--raw] <src> <dst>",
194 Command::Unarchive => "UNARCHIVE <src> <dst> [--max-bytes <bytes>]",
195 Command::Ls => "LS [<path>]",
196 Command::Read => "READ [<path>]",
197 Command::ReadLine => "READ_LINE $var",
198 Command::Prompt => "PROMPT $var <message> [<default>]",
199 Command::Write => "WRITE <path> [<contents>]",
200 Command::Append => "APPEND <path> [<contents>]",
201 Command::AppendLine => "APPEND_LINE <path> <contents>",
202 Command::Remove => "REMOVE [--recursive] <path>",
203 Command::Expand => "EXPAND [<path>] [<KEY=val> ...]",
204 Command::AssertEq => "ASSERT_EQ [--hash <sha256>] <actual> <expected>",
205 Command::AssertNe => "ASSERT_NE [--hash <sha256>] <actual> <expected>",
206 Command::AssertContains => "ASSERT_CONTAINS <haystack> <needle>",
207 Command::Exit => "EXIT <code>",
208 Command::Async => "ASYNC <command...> | ASYNC { <commands> }",
209 Command::Timeout => {
210 "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> }"
211 }
212 Command::Isolated => {
213 "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>"
214 }
215 Command::Sleep => "SLEEP <duration>",
216 Command::ListAppend => "LIST_APPEND $list <item>",
217 }
218 }
219
220 pub const fn expects_inner_command(self) -> bool {
221 matches!(
222 self,
223 Command::WithIo | Command::Async | Command::Timeout | Command::Isolated
224 )
225 }
226
227 pub fn parse(s: &str) -> Option<Self> {
228 match s {
229 KEYWORD_INHERIT_ENV => Some(Command::InheritEnv),
230 KEYWORD_WORKDIR => Some(Command::Workdir),
231 KEYWORD_WORKSPACE => Some(Command::Workspace),
232 KEYWORD_ENV => Some(Command::Env),
233 KEYWORD_ECHO => Some(Command::Echo),
234 KEYWORD_RUN => Some(Command::Run),
235 KEYWORD_COPY => Some(Command::Copy),
236 KEYWORD_WITH_IO => Some(Command::WithIo),
237 KEYWORD_COPY_GIT => Some(Command::CopyGit),
238 KEYWORD_SYMLINK => Some(Command::Symlink),
239 KEYWORD_MKDIR => Some(Command::Mkdir),
240 KEYWORD_INSTALL => Some(Command::Install),
241 KEYWORD_SET_EXECUTABLE => Some(Command::SetExecutable),
242 KEYWORD_ARCHIVE => Some(Command::Archive),
243 KEYWORD_UNARCHIVE => Some(Command::Unarchive),
244 KEYWORD_LS => Some(Command::Ls),
245 KEYWORD_READ => Some(Command::Read),
246 KEYWORD_READ_LINE => Some(Command::ReadLine),
247 KEYWORD_PROMPT => Some(Command::Prompt),
248 KEYWORD_WRITE => Some(Command::Write),
249 KEYWORD_APPEND => Some(Command::Append),
250 KEYWORD_APPEND_LINE => Some(Command::AppendLine),
251 KEYWORD_REMOVE => Some(Command::Remove),
252 KEYWORD_EXPAND => Some(Command::Expand),
253 KEYWORD_ASSERT_EQ => Some(Command::AssertEq),
254 KEYWORD_ASSERT_NE => Some(Command::AssertNe),
255 KEYWORD_ASSERT_CONTAINS => Some(Command::AssertContains),
256 KEYWORD_EXIT => Some(Command::Exit),
257 KEYWORD_ASYNC => Some(Command::Async),
258 KEYWORD_TIMEOUT => Some(Command::Timeout),
259 KEYWORD_ISOLATED => Some(Command::Isolated),
260 KEYWORD_SLEEP => Some(Command::Sleep),
261 KEYWORD_LIST_APPEND => Some(Command::ListAppend),
262 _ => None,
263 }
264 }
265
266 pub(crate) fn is_statement_keyword(s: &str) -> bool {
271 Command::parse(s).is_some() || STRUCTURAL_KEYWORDS.contains(&s)
272 }
273}
274
275pub const STRUCTURAL_KEYWORDS: &[&str] = &[
281 KEYWORD_LET,
282 KEYWORD_FOR,
283 KEYWORD_IF,
284 KEYWORD_ELSE,
285 KEYWORD_SWITCH,
286 KEYWORD_CASE,
287 KEYWORD_DEFAULT,
288 KEYWORD_ASYNC,
289 KEYWORD_AWAIT,
290 KEYWORD_CANCEL,
291 KEYWORD_FUNC,
292 KEYWORD_RETURN,
293 KEYWORD_WHILE,
294 KEYWORD_BREAK,
295 KEYWORD_CONTINUE,
296 KEYWORD_REMOTE,
297 KEYWORD_IMPORT,
298 KEYWORD_EXPORT,
299 KEYWORD_TYPE,
300];
301
302pub const CLAUSE_KEYWORDS: &[&str] = &[KEYWORD_IN];
307
308#[derive(Debug, Clone, Eq, PartialEq)]
321pub enum Guard {
322 Attr {
323 ns: Ns,
324 key: Option<String>,
325 val: Option<String>,
326 },
327}
328
329#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
333pub enum Ns {
334 Os,
335 Arch,
336 Bool,
337 Env,
338}
339
340impl fmt::Display for Ns {
341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342 match self {
343 Ns::Os => write!(f, "os"),
344 Ns::Arch => write!(f, "arch"),
345 Ns::Bool => write!(f, "bool"),
346 Ns::Env => write!(f, "env"),
347 }
348 }
349}
350
351pub const ARCH_VALUES: &[&str] = &[
355 "aarch64",
356 "arm",
357 "arm64ec",
358 "avr",
359 "bpf",
360 "csky",
361 "hexagon",
362 "loongarch32",
363 "loongarch64",
364 "mips",
365 "mips32r6",
366 "mips64",
367 "mips64r6",
368 "msp430",
369 "nvptx64",
370 "powerpc",
371 "powerpc64",
372 "riscv32",
373 "riscv64",
374 "s390x",
375 "sparc",
376 "sparc64",
377 "wasm32",
378 "wasm64",
379 "x86",
380 "x86_64",
381 "xtensa",
382];
383
384#[derive(Debug, Clone, Eq, PartialEq)]
385pub enum GuardExpr {
386 Predicate(Guard),
387 All(Vec<GuardExpr>),
388 Or(Vec<GuardExpr>),
389 Not(Box<GuardExpr>),
390}
391
392impl GuardExpr {
393 pub fn all(exprs: Vec<GuardExpr>) -> GuardExpr {
394 let mut flat = Vec::new();
395 for expr in exprs {
396 match expr {
397 GuardExpr::All(children) => flat.extend(children),
398 other => flat.push(other),
399 }
400 }
401 match flat.len() {
402 0 => panic!("GuardExpr::all requires at least one expression"),
403 1 => flat.into_iter().next().unwrap(),
404 _ => GuardExpr::All(flat),
405 }
406 }
407
408 pub fn or(exprs: Vec<GuardExpr>) -> GuardExpr {
409 let mut flat = Vec::new();
410 for expr in exprs {
411 match expr {
412 GuardExpr::Or(children) => flat.extend(children),
413 other => flat.push(other),
414 }
415 }
416 match flat.len() {
417 0 => panic!("GuardExpr::or requires at least one expression"),
418 1 => flat.into_iter().next().unwrap(),
419 _ => GuardExpr::Or(flat),
420 }
421 }
422
423 pub fn invert(expr: GuardExpr) -> GuardExpr {
424 match expr {
425 GuardExpr::Not(inner) => *inner,
426 other => GuardExpr::Not(Box::new(other)),
427 }
428 }
429}
430
431impl std::ops::Not for GuardExpr {
432 type Output = GuardExpr;
433
434 fn not(self) -> GuardExpr {
435 match self {
436 GuardExpr::Not(inner) => *inner,
437 other => GuardExpr::Not(Box::new(other)),
438 }
439 }
440}
441
442impl From<Guard> for GuardExpr {
443 fn from(guard: Guard) -> Self {
444 GuardExpr::Predicate(guard)
445 }
446}
447
448#[derive(Debug, Clone, PartialEq)]
450pub enum Arg {
451 String(String, bool),
455 Expr(Expr),
457 Parts(Vec<ArgPart>),
461}
462
463#[derive(Debug, Clone, PartialEq)]
465pub enum ArgPart {
466 Text(String, bool),
469 Expr(Expr),
471}
472
473impl Arg {
474 pub fn as_str(&self) -> &str {
475 match self {
476 Arg::String(s, _) => s,
477 Arg::Expr(_) | Arg::Parts(_) => "",
480 }
481 }
482
483 pub fn render(&self) -> String {
487 match self {
488 Arg::String(s, _) => s.clone(),
489 Arg::Expr(e) => e.to_string(),
490 Arg::Parts(parts) => parts.iter().map(ArgPart::render).collect(),
491 }
492 }
493
494 pub fn is_quoted(&self) -> bool {
495 matches!(self, Arg::String(_, true))
496 }
497}
498
499impl ArgPart {
500 pub fn render(&self) -> String {
501 match self {
502 ArgPart::Text(s, _) => s.clone(),
503 ArgPart::Expr(e) => e.to_string(),
504 }
505 }
506}
507
508impl From<String> for Arg {
509 fn from(s: String) -> Self {
510 Arg::String(s, false)
511 }
512}
513
514impl From<&str> for Arg {
515 fn from(s: &str) -> Self {
516 Arg::String(s.to_string(), false)
517 }
518}
519
520impl std::fmt::Display for Arg {
521 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
522 match self {
523 Arg::String(s, _) => write!(f, "{}", s),
524 Arg::Expr(e) => write!(f, "{}", e),
525 Arg::Parts(parts) => {
526 for part in parts {
527 match part {
528 ArgPart::Text(s, _) => write!(f, "{}", s)?,
529 ArgPart::Expr(e) => write!(f, "{}", e)?,
530 }
531 }
532 Ok(())
533 }
534 }
535 }
536}
537
538impl AsRef<str> for Arg {
539 fn as_ref(&self) -> &str {
540 self.as_str()
541 }
542}
543
544impl PartialEq<str> for Arg {
545 fn eq(&self, other: &str) -> bool {
546 self.as_str() == other
547 }
548}
549
550impl PartialEq<&str> for Arg {
551 fn eq(&self, other: &&str) -> bool {
552 self.as_str() == *other
553 }
554}
555
556#[derive(Debug, Clone, Copy, Eq, PartialEq)]
557pub enum IoStream {
558 Stdin,
559 Stdout,
560 Stderr,
561 Tty,
565 Rows(u16),
567 Cols(u16),
569}
570
571#[derive(Debug, Clone, Eq, PartialEq)]
572pub struct IoBinding {
573 pub stream: IoStream,
574 pub pipe: Option<PipeTarget>,
575}
576
577#[derive(Debug, Clone, Eq, PartialEq)]
580pub enum PipeTarget {
581 Var(String),
582}
583
584pub use crate::value::{
588 OxDockType, SemaphoreState, TypeDescriptor, Value, ValuePayload, clone_boxed, clone_copy,
589 clone_shared, drop_boxed, drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed,
590 fmt_inline, fmt_shared, load_inline, startup_descriptors, store_inline, type_anchor,
591 unshare_boxed, unshare_inline, unshare_shared,
592};
593
594#[derive(Debug, Clone, Copy, Eq, PartialEq)]
595pub enum CompareOp {
596 Eq,
597 Ne,
598 Lt,
599 Le,
600 Gt,
601 Ge,
602}
603
604#[derive(Debug, Clone, Copy, Eq, PartialEq)]
605pub enum ArithOp {
606 Add,
607 Sub,
608 Mul,
609 Div,
610}
611
612#[derive(Debug, Clone, PartialEq)]
621pub enum MathOp {
622 PushConst(Value),
623 LoadVar(String),
624 LoadEnv(String),
625 LoadKeyPath { base: String, keys: Vec<String> },
626 Call { name: String, arity: usize },
627 Inspect(String),
628 Neg,
629 Add,
630 Sub,
631 Mul,
632 Div,
633 Lt,
634 Le,
635 Gt,
636 Ge,
637 Eq,
638 Ne,
639}
640
641#[derive(Debug, Clone, Copy, Eq, PartialEq)]
642pub enum LogicalOp {
643 And,
644 Or,
645}
646
647#[derive(Debug, Clone, PartialEq)]
648pub enum Expr {
649 Literal(Value),
650 Var(String),
651 Env(String),
654 KeyPath {
655 base: String,
656 keys: Vec<String>,
657 },
658 List(Vec<Expr>),
659 Map(Vec<(String, Expr)>),
660 Block(Vec<Step>),
665 Call {
666 name: String,
667 args: Vec<Expr>,
668 },
669 Inspect(String),
674 Compare {
675 op: CompareOp,
676 left: Box<Expr>,
677 right: Box<Expr>,
678 },
679 Arithmetic {
680 op: ArithOp,
681 left: Box<Expr>,
682 right: Box<Expr>,
683 },
684 CompiledMath(Vec<MathOp>),
687 FreshPipe,
693 UnsignedIntBoundary(u64),
697 Not(Box<Expr>),
698 Logical {
699 op: LogicalOp,
700 left: Box<Expr>,
701 right: Box<Expr>,
702 },
703}
704
705#[derive(Debug, Clone)]
706pub struct Step {
707 pub guard: Option<GuardExpr>,
708 pub kind: StepKind,
709 pub scope_enter: usize,
710 pub scope_exit: usize,
711 pub line: usize,
718 pub col: usize,
722}
723
724impl PartialEq for Step {
725 fn eq(&self, other: &Self) -> bool {
726 self.guard == other.guard
727 && self.kind == other.kind
728 && self.scope_enter == other.scope_enter
729 && self.scope_exit == other.scope_exit
730 }
731}
732
733impl Eq for Step {}
734
735impl Expr {
736 pub fn walk(&self, f: &mut impl FnMut(&Expr)) {
743 f(self);
744 match self {
745 Expr::Literal(_)
746 | Expr::Var(_)
747 | Expr::Env(_)
748 | Expr::KeyPath { .. }
749 | Expr::Inspect(_)
750 | Expr::FreshPipe
751 | Expr::UnsignedIntBoundary(_) => {}
752 Expr::Call { args, .. } => {
753 for arg in args {
754 arg.walk(f);
755 }
756 }
757 Expr::List(items) => {
758 for item in items {
759 item.walk(f);
760 }
761 }
762 Expr::Map(entries) => {
763 for (_, value) in entries {
764 value.walk(f);
765 }
766 }
767 Expr::Block(steps) => {
768 for step in steps {
769 step.kind.walk_step_exprs(f);
770 }
771 }
772 Expr::Compare { left, right, .. }
773 | Expr::Arithmetic { left, right, .. }
774 | Expr::Logical { left, right, .. } => {
775 left.walk(f);
776 right.walk(f);
777 }
778 Expr::CompiledMath(_) => {}
779 Expr::Not(inner) => inner.walk(f),
780 }
781 }
782
783 pub fn walk_mut(&mut self, f: &mut impl FnMut(&mut Expr)) {
790 f(self);
791 match self {
792 Expr::Literal(_)
793 | Expr::Var(_)
794 | Expr::Env(_)
795 | Expr::KeyPath { .. }
796 | Expr::Inspect(_)
797 | Expr::FreshPipe
798 | Expr::UnsignedIntBoundary(_) => {}
799 Expr::Call { args, .. } => {
800 for arg in args {
801 arg.walk_mut(f);
802 }
803 }
804 Expr::List(items) => {
805 for item in items {
806 item.walk_mut(f);
807 }
808 }
809 Expr::Map(entries) => {
810 for (_, value) in entries {
811 value.walk_mut(f);
812 }
813 }
814 Expr::Block(_) => {}
815 Expr::Compare { left, right, .. }
816 | Expr::Arithmetic { left, right, .. }
817 | Expr::Logical { left, right, .. } => {
818 left.walk_mut(f);
819 right.walk_mut(f);
820 }
821 Expr::CompiledMath(_) => {}
822 Expr::Not(inner) => inner.walk_mut(f),
823 }
824 }
825}
826
827#[derive(Debug, Clone, Eq, PartialEq)]
828pub enum WorkspaceTarget {
829 Snapshot,
830 Local,
831 Cache { local: bool },
832 System,
833}
834
835pub trait EnvLookup {
836 fn get_env(&self, key: &str) -> Option<&str>;
837}
838
839impl EnvLookup for HashMap<String, String> {
840 fn get_env(&self, key: &str) -> Option<&str> {
841 self.get(key).map(|s| s.as_str())
842 }
843}
844
845impl EnvLookup for Arc<HashMap<String, String>> {
846 fn get_env(&self, key: &str) -> Option<&str> {
847 (**self).get_env(key)
848 }
849}
850
851pub fn guard_allows(guard: &Guard, env: &impl EnvLookup) -> bool {
852 let Guard::Attr { ns, key, val } = guard;
853 match ns {
854 Ns::Os => match val.as_deref() {
855 Some("macos") => platform_is_macos(),
856 Some("linux") => platform_is_linux(),
857 Some("windows") => platform_is_windows(),
858 _ => false,
859 },
860 Ns::Arch => match val.as_deref() {
861 Some(want) => ARCH_TARGET == want,
862 None => false,
863 },
864 Ns::Bool => val
865 .as_deref()
866 .map(|v| v.parse::<bool>().unwrap_or(false))
867 .unwrap_or(false),
868 Ns::Env => match key.as_deref() {
869 Some(var) => match val {
870 None => env.get_env(var).map(|v| !v.is_empty()).unwrap_or(false),
871 Some(want) => env
872 .get_env(var)
873 .map(|v| v == want.as_str())
874 .unwrap_or(false),
875 },
876 None => false,
878 },
879 }
880}
881
882#[allow(clippy::disallowed_macros)]
885fn platform_is_windows() -> bool {
886 cfg!(windows)
887}
888
889#[allow(clippy::disallowed_macros)]
891fn platform_is_macos() -> bool {
892 cfg!(target_os = "macos")
893}
894
895#[allow(clippy::disallowed_macros)]
897fn platform_is_linux() -> bool {
898 cfg!(target_os = "linux")
899}
900
901const ARCH_TARGET: &str = std::env::consts::ARCH;
904
905pub fn guard_expr_allows(expr: &GuardExpr, env: &impl EnvLookup) -> bool {
906 match expr {
907 GuardExpr::Predicate(guard) => guard_allows(guard, env),
908 GuardExpr::All(children) => children.iter().all(|g| guard_expr_allows(g, env)),
909 GuardExpr::Or(children) => children.iter().any(|g| guard_expr_allows(g, env)),
910 GuardExpr::Not(child) => !guard_expr_allows(child, env),
911 }
912}
913
914pub fn guard_option_allows(expr: Option<&GuardExpr>, env: &impl EnvLookup) -> bool {
915 match expr {
916 Some(e) => guard_expr_allows(e, env),
917 None => true,
918 }
919}
920
921impl Guard {
922 pub fn is_disjoint_from(&self, other: &Self) -> bool {
931 match (self, other) {
932 (
933 Guard::Attr {
934 ns: n1,
935 key: k1,
936 val: Some(v1),
937 },
938 Guard::Attr {
939 ns: n2,
940 key: k2,
941 val: Some(v2),
942 },
943 ) => n1 == n2 && k1 == k2 && v1 != v2,
944 _ => false,
945 }
946 }
947}
948
949impl GuardExpr {
950 pub fn is_disjoint_from(&self, other: &Self) -> bool {
956 match (self, other) {
957 (x, GuardExpr::Not(inner)) | (GuardExpr::Not(inner), x) => {
965 x == inner.as_ref() || unset_excludes(x, inner.as_ref())
966 }
967 (GuardExpr::Predicate(p1), GuardExpr::Predicate(p2)) => p1.is_disjoint_from(p2),
969 (GuardExpr::Or(arms), other) | (other, GuardExpr::Or(arms)) => {
971 arms.iter().all(|arm| arm.is_disjoint_from(other))
972 }
973 (GuardExpr::All(arms), other) | (other, GuardExpr::All(arms)) => {
975 arms.iter().any(|arm| arm.is_disjoint_from(other))
976 }
977 }
978 }
979}
980
981fn conjuncts(expr: &GuardExpr) -> Vec<&GuardExpr> {
985 match expr {
986 GuardExpr::All(items) => items.iter().collect(),
987 single => vec![single],
988 }
989}
990
991fn closed_domain_values(ns: Ns, key: Option<&str>) -> Option<&'static [&'static str]> {
998 match (ns, key) {
999 (Ns::Bool, None) => Some(&["true", "false"]),
1000 (Ns::Os, None) => Some(&["macos", "linux", "windows"]),
1001 (Ns::Arch, None) => Some(ARCH_VALUES),
1002 _ => None,
1003 }
1004}
1005
1006#[derive(Clone)]
1009enum DnfLit {
1010 Pos(Guard),
1011 Neg(Guard),
1012}
1013
1014impl DnfLit {
1015 fn as_expr(&self) -> GuardExpr {
1016 match self {
1017 DnfLit::Pos(guard) => GuardExpr::Predicate(guard.clone()),
1018 DnfLit::Neg(guard) => GuardExpr::Not(Box::new(GuardExpr::Predicate(guard.clone()))),
1019 }
1020 }
1021}
1022
1023const MAX_DNF_DISJUNCTS: usize = 64;
1028
1029fn dnf_push(expr: &GuardExpr, polarity: bool, out: &mut Vec<Vec<DnfLit>>) -> bool {
1034 match (expr, polarity) {
1035 (GuardExpr::Predicate(guard), true) => {
1036 for disjunct in out.iter_mut() {
1037 disjunct.push(DnfLit::Pos(guard.clone()));
1038 }
1039 true
1040 }
1041 (GuardExpr::Predicate(guard), false) => {
1042 for disjunct in out.iter_mut() {
1043 disjunct.push(DnfLit::Neg(guard.clone()));
1044 }
1045 true
1046 }
1047 (GuardExpr::All(children), true) | (GuardExpr::Or(children), false) => {
1048 for child in children {
1050 if !dnf_push(child, polarity, out) {
1051 return false;
1052 }
1053 }
1054 true
1055 }
1056 (GuardExpr::Or(children), true) | (GuardExpr::All(children), false) => {
1057 let mut forked = Vec::new();
1059 for disjunct in out.drain(..) {
1060 for child in children {
1061 let mut branch = vec![disjunct.clone()];
1062 if !dnf_push(child, polarity, &mut branch) {
1063 return false;
1064 }
1065 forked.extend(branch);
1066 if forked.len() > MAX_DNF_DISJUNCTS {
1067 return false;
1068 }
1069 }
1070 }
1071 *out = forked;
1072 true
1073 }
1074 (GuardExpr::Not(inner), _) => dnf_push(inner, !polarity, out),
1075 }
1076}
1077
1078fn disjunct_satisfiable(lits: &[DnfLit]) -> bool {
1082 for lit in lits {
1086 match lit {
1087 DnfLit::Pos(Guard::Attr {
1088 ns: Ns::Bool, val, ..
1089 }) if val.as_deref() != Some("true") => return false,
1090 DnfLit::Neg(Guard::Attr {
1091 ns: Ns::Bool,
1092 key: None,
1093 val: Some(value),
1094 }) if value == "true" => return false,
1095 _ => {}
1096 }
1097 }
1098 for (index, first) in lits.iter().enumerate() {
1101 for second in &lits[index + 1..] {
1102 if first.as_expr().is_disjoint_from(&second.as_expr()) {
1103 return false;
1104 }
1105 }
1106 }
1107 for lit in lits {
1111 let (ns, key) = match lit {
1112 DnfLit::Neg(Guard::Attr {
1113 ns,
1114 key,
1115 val: Some(_),
1116 }) => (*ns, key.as_deref()),
1117 _ => continue,
1118 };
1119 let Some(domain) = closed_domain_values(ns, key) else {
1120 continue;
1121 };
1122 let exhausted = domain.iter().all(|value| {
1123 lits.iter().any(|other| match other {
1124 DnfLit::Neg(Guard::Attr {
1125 ns: other_ns,
1126 key: other_key,
1127 val: Some(other_val),
1128 }) => *other_ns == ns && other_key.as_deref() == key && other_val == value,
1129 _ => false,
1130 })
1131 });
1132 if exhausted {
1133 return false;
1134 }
1135 }
1136 true
1137}
1138
1139fn conjunction_dead(atoms: &[&GuardExpr]) -> bool {
1146 if atoms.is_empty() {
1147 return false;
1148 }
1149 let mut disjuncts = vec![Vec::new()];
1150 for atom in atoms {
1151 if !dnf_push(atom, true, &mut disjuncts) {
1152 return false;
1153 }
1154 }
1155 !disjuncts
1156 .iter()
1157 .any(|disjunct| disjunct_satisfiable(disjunct))
1158}
1159
1160pub fn guard_satisfiable(expr: &GuardExpr) -> bool {
1162 !conjunction_dead(&conjuncts(expr))
1163}
1164
1165pub fn guard_valid(expr: &GuardExpr) -> bool {
1168 match expr {
1169 GuardExpr::Predicate(Guard::Attr {
1170 ns: Ns::Bool,
1171 val: Some(value),
1172 ..
1173 }) => value.as_str() == "true",
1174 GuardExpr::All(items) => items.iter().all(guard_valid),
1175 GuardExpr::Not(inner) => !guard_satisfiable(inner),
1176 _ => false,
1177 }
1178}
1179
1180pub fn guards_overlap(a: Option<&GuardExpr>, b: Option<&GuardExpr>) -> bool {
1183 match (a, b) {
1184 (None, None) => true,
1185 (Some(x), None) | (None, Some(x)) => guard_satisfiable(x),
1186 (Some(x), Some(y)) => {
1187 let mut atoms = conjuncts(x);
1188 atoms.extend(conjuncts(y));
1189 !conjunction_dead(&atoms)
1190 }
1191 }
1192}
1193
1194fn unset_excludes(x: &GuardExpr, inner: &GuardExpr) -> bool {
1197 match (x, inner) {
1198 (
1199 GuardExpr::Predicate(Guard::Attr {
1200 ns: n2, key: k2, ..
1201 }),
1202 GuardExpr::Predicate(Guard::Attr {
1203 ns: n1,
1204 key: k1,
1205 val: None,
1206 }),
1207 ) => n1 == n2 && k1 == k2,
1208 _ => false,
1209 }
1210}
1211
1212impl fmt::Display for Guard {
1213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1219 match self {
1220 Guard::Attr {
1221 ns: Ns::Env,
1222 key: Some(var),
1223 val: None,
1224 } => write!(f, "env:{var}"),
1225 Guard::Attr {
1226 ns: Ns::Env,
1227 key: Some(var),
1228 val: Some(want),
1229 } => write!(f, "eq(env:{var}, {want})"),
1230 Guard::Attr {
1231 ns,
1232 key: _,
1233 val: Some(value),
1234 } => write!(f, "{ns}:{value}"),
1235 Guard::Attr { ns, key, val: None } => match key {
1236 Some(subject) => write!(f, "{ns}:{subject}"),
1237 None => write!(f, "{ns}"),
1238 },
1239 }
1240 }
1241}
1242
1243impl fmt::Display for WorkspaceTarget {
1244 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1245 match self {
1246 WorkspaceTarget::Snapshot => write!(f, "SNAPSHOT"),
1247 WorkspaceTarget::Local => write!(f, "LOCAL"),
1248 WorkspaceTarget::Cache { local: false } => write!(f, "CACHE"),
1249 WorkspaceTarget::Cache { local: true } => write!(f, "CACHE --local"),
1250 WorkspaceTarget::System => write!(f, "SYSTEM"),
1251 }
1252 }
1253}
1254
1255impl fmt::Display for Expr {
1256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1257 match self {
1258 Expr::Literal(v) => write!(f, "{}", v),
1259 Expr::Var(name) => write!(f, "${}", name),
1260 Expr::Env(key) => write!(f, "env:{}", key),
1261 Expr::KeyPath { base, keys } => {
1262 write!(f, "${}", base)?;
1263 for key in keys {
1264 write!(f, ".{}", key)?;
1265 }
1266 Ok(())
1267 }
1268 Expr::Call { name, args } => {
1269 write!(f, "{}(", name)?;
1270 for (i, arg) in args.iter().enumerate() {
1271 if i > 0 {
1272 write!(f, ", ")?;
1273 }
1274 write!(f, "{}", arg)?;
1275 }
1276 write!(f, ")")
1277 }
1278 Expr::Inspect(var) => write!(f, "INSPECT(${})", var),
1279 Expr::List(items) => {
1280 write!(f, "[")?;
1281 for (i, item) in items.iter().enumerate() {
1282 if i > 0 {
1283 write!(f, ", ")?;
1284 }
1285 write!(f, "{}", item)?;
1286 }
1287 write!(f, "]")
1288 }
1289 Expr::Map(entries) => {
1290 write!(f, "{{")?;
1291 for (i, (key, val)) in entries.iter().enumerate() {
1292 if i > 0 {
1293 write!(f, ", ")?;
1294 }
1295 write!(f, "\"{}\": {}", key, val)?;
1296 }
1297 write!(f, "}}")
1298 }
1299 Expr::Block(steps) => {
1300 write!(f, "{{ ")?;
1301 for (i, step) in steps.iter().enumerate() {
1302 if i > 0 {
1303 write!(f, "; ")?;
1304 }
1305 write!(f, "{}", step.kind)?;
1306 }
1307 write!(f, " }}")
1308 }
1309 Expr::Compare { op, left, right } => {
1310 write!(f, "({} {} {})", left, op, right)
1314 }
1315 Expr::Arithmetic { op, left, right } => {
1316 write!(f, "({} {} {})", left, op, right)
1317 }
1318 Expr::CompiledMath(ops) => {
1319 write!(f, "{}", format_compiled_math(ops))
1320 }
1321 Expr::FreshPipe => write!(f, "<fresh pipe>"),
1325 Expr::UnsignedIntBoundary(n) => write!(f, "{}", n),
1326 Expr::Not(inner) => {
1327 match inner.as_ref() {
1330 Expr::Compare { .. } | Expr::Arithmetic { .. } | Expr::CompiledMath(_) => {
1331 write!(f, "!({})", inner)
1332 }
1333 _ => write!(f, "!{}", inner),
1334 }
1335 }
1336 Expr::Logical { op, left, right } => {
1337 write!(f, "({} {} {})", left, op, right)
1338 }
1339 }
1340 }
1341}
1342
1343impl fmt::Display for CompareOp {
1344 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1345 match self {
1346 CompareOp::Eq => write!(f, "=="),
1347 CompareOp::Ne => write!(f, "!="),
1348 CompareOp::Lt => write!(f, "<"),
1349 CompareOp::Le => write!(f, "<="),
1350 CompareOp::Gt => write!(f, ">"),
1351 CompareOp::Ge => write!(f, ">="),
1352 }
1353 }
1354}
1355
1356impl fmt::Display for ArithOp {
1357 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1358 match self {
1359 ArithOp::Add => write!(f, "+"),
1360 ArithOp::Sub => write!(f, "-"),
1361 ArithOp::Mul => write!(f, "*"),
1362 ArithOp::Div => write!(f, "/"),
1363 }
1364 }
1365}
1366
1367fn format_compiled_math(ops: &[MathOp]) -> String {
1372 let mut stack: Vec<String> = Vec::new();
1373 for op in ops {
1374 match op {
1375 MathOp::PushConst(v) => stack.push(format!("{}", v)),
1376 MathOp::LoadVar(name) => stack.push(format!("${}", name)),
1377 MathOp::LoadEnv(key) => stack.push(format!("env:{}", key)),
1378 MathOp::LoadKeyPath { base, keys } => {
1379 let mut s = format!("${}", base);
1380 for key in keys {
1381 s.push('.');
1382 s.push_str(key);
1383 }
1384 stack.push(s);
1385 }
1386 MathOp::Call { name, arity } => {
1387 let mut args = Vec::new();
1388 for _ in 0..*arity {
1389 args.push(stack.pop().unwrap_or_else(|| "<underflow>".to_string()));
1390 }
1391 args.reverse();
1392 stack.push(format!("{}({})", name, args.join(", ")));
1393 }
1394 MathOp::Inspect(name) => stack.push(format!("INSPECT(${})", name)),
1395 MathOp::Neg => {
1396 let inner = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1397 stack.push(format!("(-{})", inner));
1398 }
1399 MathOp::Add => push_bin(&mut stack, "+"),
1400 MathOp::Sub => push_bin(&mut stack, "-"),
1401 MathOp::Mul => push_bin(&mut stack, "*"),
1402 MathOp::Div => push_bin(&mut stack, "/"),
1403 MathOp::Lt => push_bin(&mut stack, "<"),
1404 MathOp::Le => push_bin(&mut stack, "<="),
1405 MathOp::Gt => push_bin(&mut stack, ">"),
1406 MathOp::Ge => push_bin(&mut stack, ">="),
1407 MathOp::Eq => push_bin(&mut stack, "=="),
1408 MathOp::Ne => push_bin(&mut stack, "!="),
1409 }
1410 }
1411 if stack.len() == 1 {
1412 let mut items = stack;
1413 items.pop().unwrap_or_else(|| "<empty>".to_string())
1414 } else {
1415 stack.join(" ")
1416 }
1417}
1418
1419fn push_bin(stack: &mut Vec<String>, op: &str) {
1420 let right = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1421 let left = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1422 stack.push(format!("({} {} {})", left, op, right));
1423}
1424
1425impl fmt::Display for LogicalOp {
1426 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1427 match self {
1428 LogicalOp::And => write!(f, "&&"),
1429 LogicalOp::Or => write!(f, "||"),
1430 }
1431 }
1432}
1433
1434enum GuardDisplayContext {
1435 Root,
1436 InAnyArg,
1437 InNot,
1438 InAll,
1439}
1440
1441impl GuardExpr {
1442 fn fmt_with_ctx(&self, f: &mut fmt::Formatter<'_>, ctx: GuardDisplayContext) -> fmt::Result {
1443 match self {
1444 GuardExpr::Predicate(guard) => write!(f, "{}", guard),
1445 GuardExpr::All(children) => {
1446 let wrap = matches!(
1447 ctx,
1448 GuardDisplayContext::InAnyArg | GuardDisplayContext::InNot
1449 ) && children.len() > 1;
1450 if wrap {
1451 write!(f, "(")?;
1452 }
1453 for (i, child) in children.iter().enumerate() {
1454 if i > 0 {
1455 write!(f, ", ")?;
1456 }
1457 child.fmt_with_ctx(f, GuardDisplayContext::InAll)?;
1458 }
1459 if wrap {
1460 write!(f, ")")?;
1461 }
1462 Ok(())
1463 }
1464 GuardExpr::Or(children) => {
1465 write!(f, "any(")?;
1466 for (i, child) in children.iter().enumerate() {
1467 if i > 0 {
1468 write!(f, ", ")?;
1469 }
1470 child.fmt_with_ctx(f, GuardDisplayContext::InAnyArg)?;
1471 }
1472 write!(f, ")")
1473 }
1474 GuardExpr::Not(child) => {
1475 write!(f, "not(")?;
1476 child.fmt_with_ctx(f, GuardDisplayContext::InNot)?;
1477 write!(f, ")")
1478 }
1479 }
1480 }
1481}
1482
1483impl fmt::Display for GuardExpr {
1484 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1485 self.fmt_with_ctx(f, GuardDisplayContext::Root)
1486 }
1487}
1488
1489impl fmt::Display for Step {
1490 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1491 if let Some(expr) = &self.guard {
1492 write!(f, "[{}] ", expr)?;
1493 }
1494 write!(f, "{}", self.kind)
1495 }
1496}
1497
1498#[cfg(test)]
1499mod tests {
1500 use super::*;
1501 #[test]
1509 fn statement_keywords_match_backend() {
1510 for kw in STRUCTURAL_KEYWORDS {
1518 let via_backend = crate::parse_script(kw, crate::commands::lower_command);
1519 let via_lowering =
1520 crate::commands::lower_command(kw, Vec::new()).map(|kind| crate::Step {
1521 guard: None,
1522 kind,
1523 scope_enter: 0,
1524 scope_exit: 0,
1525 line: 0,
1526 col: 0,
1527 });
1528 match (via_backend, via_lowering) {
1529 (Ok(_), _) => {}
1530 (Err(a), Err(b)) => {
1531 assert_eq!(
1532 a.kind(),
1533 b.kind(),
1534 "backend kind drift for bare keyword {kw}: {a} vs {b}"
1535 );
1536 }
1537 (Err(a), Ok(_)) => {
1538 panic!("backend rejects bare keyword {kw} that lowering accepts: {a}")
1539 }
1540 }
1541 }
1542 for head in [
1546 "LET",
1547 "RETURN",
1548 "BREAK",
1549 "CONTINUE",
1550 "IF",
1551 "FOR",
1552 "WHILE",
1553 "FUNC",
1554 "REMOTE",
1555 "INHERIT_ENV",
1556 "WITH_IO",
1557 "ASYNC",
1558 "TIMEOUT",
1559 "ISOLATED",
1560 "AWAIT",
1561 "CANCEL",
1562 "RUN",
1563 "IMPORT",
1564 "EXPORT",
1565 "TYPE",
1566 ] {
1567 assert!(
1568 STRUCTURAL_KEYWORDS.contains(&head)
1569 || crate::all_metadata().iter().any(|m| m.name == head),
1570 "structural head {head} is not registered"
1571 );
1572 }
1573 }
1574
1575 #[test]
1579 fn command_names_group_by_category() {
1580 for command in COMMANDS {
1581 let name = command.as_str();
1582 let Some((prefix, _)) = name.split_once('_') else {
1583 continue;
1584 };
1585 assert!(
1586 COMMAND_CATEGORIES.contains(&prefix),
1587 "command {name} introduces unregistered category {prefix}; add it to COMMAND_CATEGORIES"
1588 );
1589 }
1590 }
1591
1592 #[test]
1600 fn registry_commands_all_parse() {
1601 for meta in crate::all_metadata() {
1602 if !meta.in_index || STRUCTURAL_KEYWORDS.contains(&meta.name) {
1603 continue;
1604 }
1605 assert!(
1606 Command::parse(meta.name).is_some(),
1607 "registry command {} has no Command::parse arm",
1608 meta.name
1609 );
1610 }
1611 }
1612}
1613
1614#[cfg(test)]
1615mod guard_analysis_tests {
1616 use super::*;
1617
1618 fn attr(ns: Ns, key: Option<&str>, val: Option<&str>) -> GuardExpr {
1619 GuardExpr::Predicate(Guard::Attr {
1620 ns,
1621 key: key.map(str::to_string),
1622 val: val.map(str::to_string),
1623 })
1624 }
1625
1626 fn os(value: &str) -> GuardExpr {
1627 attr(Ns::Os, None, Some(value))
1628 }
1629
1630 fn arch(value: &str) -> GuardExpr {
1631 attr(Ns::Arch, None, Some(value))
1632 }
1633
1634 fn unix() -> GuardExpr {
1637 GuardExpr::Or(vec![os("macos"), os("linux")])
1638 }
1639
1640 fn windows() -> GuardExpr {
1641 os("windows")
1642 }
1643
1644 fn env_eq(var: &str, value: &str) -> GuardExpr {
1645 attr(Ns::Env, Some(var), Some(value))
1646 }
1647
1648 fn not(expr: GuardExpr) -> GuardExpr {
1649 GuardExpr::Not(Box::new(expr))
1650 }
1651
1652 #[test]
1656 fn partition_negations_are_jointly_dead() {
1657 let os_exhausted = GuardExpr::All(vec![not(os("macos")), not(os("linux")), not(windows())]);
1658 assert!(
1659 !guard_satisfiable(&os_exhausted),
1660 "no host is outside `macos`/`linux`/`windows`"
1661 );
1662 let os_partial = GuardExpr::All(vec![not(os("macos")), not(os("linux"))]);
1664 assert!(guard_satisfiable(&os_partial), "`windows` is still open");
1665 let bool_exhausted = GuardExpr::All(vec![
1667 not(attr(Ns::Bool, None, Some("true"))),
1668 not(attr(Ns::Bool, None, Some("false"))),
1669 ]);
1670 assert!(!guard_satisfiable(&bool_exhausted));
1671 let env_open = GuardExpr::All(vec![
1673 not(env_eq("MODE", "dev")),
1674 not(env_eq("MODE", "prod")),
1675 ]);
1676 assert!(guard_satisfiable(&env_open), "MODE may hold a third value");
1677 assert!(guard_satisfiable(¬(unix())));
1679 }
1680
1681 #[test]
1684 fn unix_alias_is_os_disjunction() {
1685 assert!(!guards_overlap(Some(&unix()), Some(&windows())));
1686 assert!(guards_overlap(Some(&unix()), Some(&os("macos"))));
1687 let covered = GuardExpr::All(vec![GuardExpr::Not(Box::new(unix())), not(windows())]);
1690 assert!(!guard_satisfiable(&covered));
1691 }
1692
1693 #[test]
1697 fn arch_guards_decide_by_value() {
1698 assert!(!guards_overlap(
1699 Some(&arch("x86_64")),
1700 Some(&arch("aarch64"))
1701 ));
1702 assert!(guards_overlap(Some(&arch("x86_64")), Some(&arch("x86_64"))));
1703 assert!(guards_overlap(Some(&arch("aarch64")), Some(&os("macos"))));
1704 let exhausted = GuardExpr::All(ARCH_VALUES.iter().map(|value| not(arch(value))).collect());
1705 assert!(!guard_satisfiable(&exhausted));
1706 let host = attr(Ns::Arch, None, Some(ARCH_TARGET));
1708 assert!(guard_expr_allows(&host, &HashMap::new()));
1709 }
1710
1711 #[test]
1715 fn platform_overlap_matrix_is_exhaustive() {
1716 let cases = [
1717 ("macos", "macos", true),
1718 ("macos", "linux", false),
1719 ("macos", "windows", false),
1720 ("linux", "linux", true),
1721 ("linux", "windows", false),
1722 ("windows", "windows", true),
1723 ];
1724 for (v1, v2, expected) in cases {
1725 let left = os(v1);
1726 let right = os(v2);
1727 assert_eq!(
1728 guards_overlap(Some(&left), Some(&right)),
1729 expected,
1730 "os:{v1} vs os:{v2}"
1731 );
1732 }
1733 }
1734
1735 #[test]
1738 fn disjoint_pairs_never_cofire_here() {
1739 let macos = os("macos");
1740 let holds = |expr: &GuardExpr| guard_expr_allows(expr, &HashMap::new());
1741 assert!(
1742 !(holds(&macos) && holds(&windows())),
1743 "os:macos and os:windows co-fired"
1744 );
1745 }
1746
1747 #[test]
1748 fn overlap_follows_namespace_semantics() {
1749 assert!(!guards_overlap(Some(&windows()), Some(&unix())));
1751 assert!(!guards_overlap(Some(&os("macos")), Some(&os("linux"))));
1752 assert!(guards_overlap(None, Some(&windows())));
1754 assert!(guards_overlap(None, None));
1755 let dead = GuardExpr::All(vec![os("macos"), windows()]);
1757 assert!(!guard_satisfiable(&dead));
1758 assert!(!guards_overlap(Some(&dead), Some(&os("macos"))));
1759 assert!(guard_valid(&GuardExpr::Predicate(Guard::Attr {
1760 ns: Ns::Bool,
1761 key: None,
1762 val: Some("true".to_string()),
1763 })));
1764 assert!(!guard_valid(&unix()));
1765 }
1766
1767 #[test]
1768 fn env_value_conflicts_decide_without_enumeration() {
1769 let fast = env_eq("MODE", "fast");
1770 let slow = env_eq("MODE", "slow");
1771 assert!(
1772 !guards_overlap(Some(&fast), Some(&slow)),
1773 "same key distinct values are disjoint"
1774 );
1775 let also_fast = env_eq("MODE", "fast");
1776 assert!(guards_overlap(Some(&fast), Some(&also_fast)));
1777 let bare = attr(Ns::Env, Some("MODE"), None);
1779 assert!(guards_overlap(Some(&bare), Some(&fast)));
1780 }
1781}
1782
1783#[cfg(test)]
1784mod guard_algebra_tests {
1785 use super::*;
1786
1787 fn os(value: &str) -> GuardExpr {
1788 GuardExpr::Predicate(Guard::Attr {
1789 ns: Ns::Os,
1790 key: None,
1791 val: Some(value.to_string()),
1792 })
1793 }
1794
1795 #[test]
1796 fn or_distributes_over_disjointness() {
1797 fn env_eq(var: &str, value: &str) -> GuardExpr {
1798 GuardExpr::Predicate(Guard::Attr {
1799 ns: Ns::Env,
1800 key: Some(var.to_string()),
1801 val: Some(value.to_string()),
1802 })
1803 }
1804 let mixed = GuardExpr::Or(vec![env_eq("MODE", "dev"), env_eq("MODE", "prod")]);
1807 assert!(!mixed.is_disjoint_from(&env_eq("MODE", "dev")));
1808 assert!(mixed.is_disjoint_from(&env_eq("MODE", "test")));
1810 let cross = GuardExpr::Or(vec![env_eq("MODE", "dev")]);
1812 let platform = os("windows");
1813 assert!(!cross.is_disjoint_from(&platform));
1814 }
1815
1816 #[test]
1817 fn all_distributes_over_disjointness() {
1818 let stacked = GuardExpr::All(vec![
1819 os("macos"),
1820 GuardExpr::Or(vec![os("macos"), os("linux")]),
1821 os("windows"),
1822 ]);
1823 assert!(stacked.is_disjoint_from(&os("macos")));
1824 let live = GuardExpr::All(vec![
1827 os("macos"),
1828 GuardExpr::Predicate(Guard::Attr {
1829 ns: Ns::Env,
1830 key: Some("MODE".to_string()),
1831 val: Some("dev".to_string()),
1832 }),
1833 ]);
1834 assert!(!live.is_disjoint_from(&os("macos")));
1835 }
1836
1837 #[test]
1838 fn negation_is_structural_not_syntactic() {
1839 let not_win = GuardExpr::Not(Box::new(os("windows")));
1840 assert!(not_win.is_disjoint_from(&os("windows")));
1841 assert!(os("windows").is_disjoint_from(¬_win));
1842 assert!(!not_win.is_disjoint_from(&os("macos")));
1843 }
1844}