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