1use std::collections::{HashMap, HashSet};
2use std::fmt;
3use std::sync::Arc;
4
5use oxdock_diagnostics::Span;
6
7pub use crate::commands::{AssertTarget, BindRhs, StepKind};
8use crate::constants::{
9 KEYWORD_APPEND, KEYWORD_APPEND_LINE, KEYWORD_ARCHIVE, KEYWORD_ASSERT_CONTAINS,
10 KEYWORD_ASSERT_EQ, KEYWORD_ASSERT_NE, KEYWORD_ASYNC, KEYWORD_AWAIT, KEYWORD_BREAK,
11 KEYWORD_CANCEL, KEYWORD_CASE, KEYWORD_CONST, KEYWORD_CONTINUE, KEYWORD_COPY, KEYWORD_COPY_GIT,
12 KEYWORD_DEFAULT, KEYWORD_ECHO, KEYWORD_ELSE, KEYWORD_ENV, KEYWORD_EXIT, KEYWORD_EXPAND,
13 KEYWORD_EXPORT, KEYWORD_FAIL, KEYWORD_FOR, KEYWORD_FUNC, KEYWORD_IF, KEYWORD_IMPORT,
14 KEYWORD_IN, KEYWORD_INHERIT_ENV, KEYWORD_INSPECT, KEYWORD_INSTALL, KEYWORD_ISOLATED,
15 KEYWORD_LET, KEYWORD_LIST_APPEND, KEYWORD_LS, KEYWORD_MKDIR, KEYWORD_PROMPT, KEYWORD_READ,
16 KEYWORD_READ_LINE, KEYWORD_REMOTE, KEYWORD_REMOVE, KEYWORD_RETURN, KEYWORD_RUN,
17 KEYWORD_SET_EXECUTABLE, KEYWORD_SLEEP, KEYWORD_SWITCH, KEYWORD_SYMLINK, KEYWORD_TIMEOUT,
18 KEYWORD_TYPE, KEYWORD_UNARCHIVE, KEYWORD_WHILE, KEYWORD_WITH_IO, KEYWORD_WORKDIR,
19 KEYWORD_WORKSPACE, KEYWORD_WRITE, VAR_SIGIL, sigil_qualified,
20};
21
22#[derive(Debug, Clone, Default)]
26pub struct ModuleFuncs {
27 pub func_names: HashSet<String>,
29}
30
31#[derive(Debug, Clone, Default)]
36pub struct ModuleTable {
37 pub modules: HashMap<String, Option<ModuleFuncs>>,
38}
39
40impl ModuleTable {
41 pub fn reserved_base_names(&self) -> HashSet<String> {
45 let mut out = HashSet::new();
46 for funcs in self.modules.values().flatten() {
47 out.extend(funcs.func_names.iter().cloned());
48 }
49 out
50 }
51}
52
53#[derive(Copy, Clone, Debug, Eq, PartialEq)]
61pub enum Command {
62 InheritEnv,
63 Workdir,
64 Workspace,
65 Env,
66 Echo,
67 Run,
68 Copy,
69 WithIo,
70 CopyGit,
71 Symlink,
72 Mkdir,
73 Install,
74 SetExecutable,
75 Archive,
76 Unarchive,
77 Ls,
78 Read,
79 ReadLine,
80 Prompt,
81 Write,
82 Append,
83 AppendLine,
84 Remove,
85 Expand,
86 AssertEq,
87 AssertNe,
88 AssertContains,
89 Exit,
90 Fail,
91 Async,
92 Timeout,
93 Isolated,
94 Sleep,
95 ListAppend,
96}
97
98pub const COMMANDS: &[Command] = &[
99 Command::InheritEnv,
100 Command::Workdir,
101 Command::Workspace,
102 Command::Env,
103 Command::Echo,
104 Command::Run,
105 Command::Copy,
106 Command::WithIo,
107 Command::CopyGit,
108 Command::Symlink,
109 Command::Mkdir,
110 Command::Install,
111 Command::SetExecutable,
112 Command::Archive,
113 Command::Unarchive,
114 Command::Ls,
115 Command::Read,
116 Command::ReadLine,
117 Command::Prompt,
118 Command::Write,
119 Command::Append,
120 Command::AppendLine,
121 Command::Remove,
122 Command::Expand,
123 Command::AssertEq,
124 Command::AssertNe,
125 Command::AssertContains,
126 Command::Exit,
127 Command::Fail,
128 Command::Timeout,
129 Command::Isolated,
130 Command::Sleep,
131 Command::ListAppend,
132];
133
134pub const COMMAND_CATEGORIES: &[&str] = &[
139 "INHERIT", "WITH", "COPY", "HASH", "READ", "ASSERT", "LIST", "SET", "APPEND",
140];
141
142impl Command {
143 pub const fn as_str(self) -> &'static str {
144 match self {
145 Command::InheritEnv => KEYWORD_INHERIT_ENV,
146 Command::Workdir => KEYWORD_WORKDIR,
147 Command::Workspace => KEYWORD_WORKSPACE,
148 Command::Env => KEYWORD_ENV,
149 Command::Echo => KEYWORD_ECHO,
150 Command::Run => KEYWORD_RUN,
151 Command::Copy => KEYWORD_COPY,
152 Command::WithIo => KEYWORD_WITH_IO,
153 Command::CopyGit => KEYWORD_COPY_GIT,
154 Command::Symlink => KEYWORD_SYMLINK,
155 Command::Mkdir => KEYWORD_MKDIR,
156 Command::Install => KEYWORD_INSTALL,
157 Command::SetExecutable => KEYWORD_SET_EXECUTABLE,
158 Command::Archive => KEYWORD_ARCHIVE,
159 Command::Unarchive => KEYWORD_UNARCHIVE,
160 Command::Ls => KEYWORD_LS,
161 Command::Read => KEYWORD_READ,
162 Command::ReadLine => KEYWORD_READ_LINE,
163 Command::Prompt => KEYWORD_PROMPT,
164 Command::Write => KEYWORD_WRITE,
165 Command::Append => KEYWORD_APPEND,
166 Command::AppendLine => KEYWORD_APPEND_LINE,
167 Command::Remove => KEYWORD_REMOVE,
168 Command::Expand => KEYWORD_EXPAND,
169 Command::AssertEq => KEYWORD_ASSERT_EQ,
170 Command::AssertNe => KEYWORD_ASSERT_NE,
171 Command::AssertContains => KEYWORD_ASSERT_CONTAINS,
172 Command::Exit => KEYWORD_EXIT,
173 Command::Fail => KEYWORD_FAIL,
174 Command::Async => KEYWORD_ASYNC,
175 Command::Timeout => KEYWORD_TIMEOUT,
176 Command::Isolated => KEYWORD_ISOLATED,
177 Command::Sleep => KEYWORD_SLEEP,
178 Command::ListAppend => KEYWORD_LIST_APPEND,
179 }
180 }
181
182 pub const fn syntax(self) -> &'static str {
183 match self {
184 Command::InheritEnv => "INHERIT_ENV [KEY1, KEY2, ...]",
185 Command::Workdir => "WORKDIR <path>",
186 Command::Workspace => "WORKSPACE SNAPSHOT|LOCAL|CACHE|SYSTEM [--local]",
187 Command::Env => "ENV KEY=value",
188 Command::Echo => "ECHO <message>",
189 Command::Run => "RUN <command...> | RUN [\"exe\", \"arg\", ...]",
190 Command::Copy => "COPY [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>",
191 Command::CopyGit => "COPY_GIT [--include-dirty] <rev> <src> <dst>",
192 Command::WithIo => "WITH_IO [bindings] [command | { block }]",
193 Command::Symlink => {
194 "SYMLINK [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>"
195 }
196 Command::Mkdir => "MKDIR <path>",
197 Command::Install => "INSTALL <source> <dest>",
198 Command::SetExecutable => "SET_EXECUTABLE <path>",
199 Command::Archive => "ARCHIVE [--raw] <src> <dst>",
200 Command::Unarchive => "UNARCHIVE <src> <dst> [--max-bytes <bytes>]",
201 Command::Ls => "LS [<path>]",
202 Command::Read => "READ [<path>]",
203 Command::ReadLine => "READ_LINE $var",
204 Command::Prompt => "PROMPT $var <message> [<default>]",
205 Command::Write => "WRITE <path> [<contents>]",
206 Command::Append => "APPEND <path> [<contents>]",
207 Command::AppendLine => "APPEND_LINE <path> <contents>",
208 Command::Remove => "REMOVE [--recursive] <path>",
209 Command::Expand => "EXPAND [<path>] [<KEY=val> ...]",
210 Command::AssertEq => "ASSERT_EQ [--hash <sha256>] <actual> <expected>",
211 Command::AssertNe => "ASSERT_NE [--hash <sha256>] <actual> <expected>",
212 Command::AssertContains => "ASSERT_CONTAINS <haystack> <needle>",
213 Command::Exit => "EXIT <code>",
214 Command::Fail => "FAIL [<code>] [<message>] [{ <commands> }]",
215 Command::Async => "ASYNC <command...> | ASYNC { <commands> }",
216 Command::Timeout => {
217 "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> }"
218 }
219 Command::Isolated => {
220 "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>"
221 }
222 Command::Sleep => "SLEEP <duration>",
223 Command::ListAppend => "LIST_APPEND $list <item>",
224 }
225 }
226
227 pub const fn expects_inner_command(self) -> bool {
228 matches!(
229 self,
230 Command::WithIo | Command::Async | Command::Timeout | Command::Isolated
231 )
232 }
233
234 pub fn parse(s: &str) -> Option<Self> {
235 match s {
236 KEYWORD_INHERIT_ENV => Some(Command::InheritEnv),
237 KEYWORD_WORKDIR => Some(Command::Workdir),
238 KEYWORD_WORKSPACE => Some(Command::Workspace),
239 KEYWORD_ENV => Some(Command::Env),
240 KEYWORD_ECHO => Some(Command::Echo),
241 KEYWORD_RUN => Some(Command::Run),
242 KEYWORD_COPY => Some(Command::Copy),
243 KEYWORD_WITH_IO => Some(Command::WithIo),
244 KEYWORD_COPY_GIT => Some(Command::CopyGit),
245 KEYWORD_SYMLINK => Some(Command::Symlink),
246 KEYWORD_MKDIR => Some(Command::Mkdir),
247 KEYWORD_INSTALL => Some(Command::Install),
248 KEYWORD_SET_EXECUTABLE => Some(Command::SetExecutable),
249 KEYWORD_ARCHIVE => Some(Command::Archive),
250 KEYWORD_UNARCHIVE => Some(Command::Unarchive),
251 KEYWORD_LS => Some(Command::Ls),
252 KEYWORD_READ => Some(Command::Read),
253 KEYWORD_READ_LINE => Some(Command::ReadLine),
254 KEYWORD_PROMPT => Some(Command::Prompt),
255 KEYWORD_WRITE => Some(Command::Write),
256 KEYWORD_APPEND => Some(Command::Append),
257 KEYWORD_APPEND_LINE => Some(Command::AppendLine),
258 KEYWORD_REMOVE => Some(Command::Remove),
259 KEYWORD_EXPAND => Some(Command::Expand),
260 KEYWORD_ASSERT_EQ => Some(Command::AssertEq),
261 KEYWORD_ASSERT_NE => Some(Command::AssertNe),
262 KEYWORD_ASSERT_CONTAINS => Some(Command::AssertContains),
263 KEYWORD_EXIT => Some(Command::Exit),
264 KEYWORD_FAIL => Some(Command::Fail),
265 KEYWORD_ASYNC => Some(Command::Async),
266 KEYWORD_TIMEOUT => Some(Command::Timeout),
267 KEYWORD_ISOLATED => Some(Command::Isolated),
268 KEYWORD_SLEEP => Some(Command::Sleep),
269 KEYWORD_LIST_APPEND => Some(Command::ListAppend),
270 _ => None,
271 }
272 }
273
274 pub(crate) fn is_statement_keyword(s: &str) -> bool {
279 Command::parse(s).is_some() || STRUCTURAL_KEYWORDS.contains(&s)
280 }
281}
282
283pub const STRUCTURAL_KEYWORDS: &[&str] = &[
289 KEYWORD_LET,
290 KEYWORD_CONST,
291 KEYWORD_FOR,
292 KEYWORD_IF,
293 KEYWORD_ELSE,
294 KEYWORD_SWITCH,
295 KEYWORD_CASE,
296 KEYWORD_DEFAULT,
297 KEYWORD_ASYNC,
298 KEYWORD_AWAIT,
299 KEYWORD_CANCEL,
300 KEYWORD_FUNC,
301 KEYWORD_RETURN,
302 KEYWORD_WHILE,
303 KEYWORD_BREAK,
304 KEYWORD_CONTINUE,
305 KEYWORD_REMOTE,
306 KEYWORD_IMPORT,
307 KEYWORD_EXPORT,
308 KEYWORD_TYPE,
309];
310
311pub const CLAUSE_KEYWORDS: &[&str] = &[KEYWORD_IN];
316
317#[derive(Debug, Clone, Eq, PartialEq)]
330pub enum Guard {
331 Attr {
332 ns: Ns,
333 key: Option<String>,
334 val: Option<String>,
335 },
336}
337
338#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
342pub enum Ns {
343 Os,
344 Arch,
345 Bool,
346 Env,
347}
348
349impl fmt::Display for Ns {
350 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351 match self {
352 Ns::Os => write!(f, "os"),
353 Ns::Arch => write!(f, "arch"),
354 Ns::Bool => write!(f, "bool"),
355 Ns::Env => write!(f, "env"),
356 }
357 }
358}
359
360pub const ARCH_VALUES: &[&str] = &[
364 "aarch64",
365 "arm",
366 "arm64ec",
367 "avr",
368 "bpf",
369 "csky",
370 "hexagon",
371 "loongarch32",
372 "loongarch64",
373 "mips",
374 "mips32r6",
375 "mips64",
376 "mips64r6",
377 "msp430",
378 "nvptx64",
379 "powerpc",
380 "powerpc64",
381 "riscv32",
382 "riscv64",
383 "s390x",
384 "sparc",
385 "sparc64",
386 "wasm32",
387 "wasm64",
388 "x86",
389 "x86_64",
390 "xtensa",
391];
392
393#[derive(Debug, Clone, Eq, PartialEq)]
394pub enum GuardExpr {
395 Predicate(Guard),
396 All(Vec<GuardExpr>),
397 Or(Vec<GuardExpr>),
398 Not(Box<GuardExpr>),
399}
400
401impl GuardExpr {
402 pub fn all(exprs: Vec<GuardExpr>) -> GuardExpr {
403 let mut flat = Vec::new();
404 for expr in exprs {
405 match expr {
406 GuardExpr::All(children) => flat.extend(children),
407 other => flat.push(other),
408 }
409 }
410 match flat.len() {
411 0 => panic!("GuardExpr::all requires at least one expression"),
412 1 => flat.into_iter().next().unwrap(),
413 _ => GuardExpr::All(flat),
414 }
415 }
416
417 pub fn or(exprs: Vec<GuardExpr>) -> GuardExpr {
418 let mut flat = Vec::new();
419 for expr in exprs {
420 match expr {
421 GuardExpr::Or(children) => flat.extend(children),
422 other => flat.push(other),
423 }
424 }
425 match flat.len() {
426 0 => panic!("GuardExpr::or requires at least one expression"),
427 1 => flat.into_iter().next().unwrap(),
428 _ => GuardExpr::Or(flat),
429 }
430 }
431
432 pub fn invert(expr: GuardExpr) -> GuardExpr {
433 match expr {
434 GuardExpr::Not(inner) => *inner,
435 other => GuardExpr::Not(Box::new(other)),
436 }
437 }
438}
439
440impl std::ops::Not for GuardExpr {
441 type Output = GuardExpr;
442
443 fn not(self) -> GuardExpr {
444 match self {
445 GuardExpr::Not(inner) => *inner,
446 other => GuardExpr::Not(Box::new(other)),
447 }
448 }
449}
450
451impl From<Guard> for GuardExpr {
452 fn from(guard: Guard) -> Self {
453 GuardExpr::Predicate(guard)
454 }
455}
456
457#[derive(Debug, Clone, PartialEq)]
459pub enum Arg {
460 String(String, bool),
464 Expr(Expr),
466 Parts(Vec<ArgPart>),
470}
471
472#[derive(Debug, Clone, PartialEq)]
474pub enum ArgPart {
475 Text(String, bool),
478 Expr(Expr),
480}
481
482impl Arg {
483 pub fn as_str(&self) -> &str {
484 match self {
485 Arg::String(s, _) => s,
486 Arg::Expr(_) | Arg::Parts(_) => "",
489 }
490 }
491
492 pub fn render(&self) -> String {
496 match self {
497 Arg::String(s, _) => s.clone(),
498 Arg::Expr(e) => e.to_string(),
499 Arg::Parts(parts) => parts.iter().map(ArgPart::render).collect(),
500 }
501 }
502
503 pub fn is_quoted(&self) -> bool {
504 matches!(self, Arg::String(_, true))
505 }
506}
507
508impl ArgPart {
509 pub fn render(&self) -> String {
510 match self {
511 ArgPart::Text(s, _) => s.clone(),
512 ArgPart::Expr(e) => e.to_string(),
513 }
514 }
515}
516
517impl From<String> for Arg {
518 fn from(s: String) -> Self {
519 Arg::String(s, false)
520 }
521}
522
523impl From<&str> for Arg {
524 fn from(s: &str) -> Self {
525 Arg::String(s.to_string(), false)
526 }
527}
528
529impl std::fmt::Display for Arg {
530 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
531 match self {
532 Arg::String(s, _) => write!(f, "{}", s),
533 Arg::Expr(e) => write!(f, "{}", e),
534 Arg::Parts(parts) => {
535 for part in parts {
536 match part {
537 ArgPart::Text(s, _) => write!(f, "{}", s)?,
538 ArgPart::Expr(e) => write!(f, "{}", e)?,
539 }
540 }
541 Ok(())
542 }
543 }
544 }
545}
546
547impl AsRef<str> for Arg {
548 fn as_ref(&self) -> &str {
549 self.as_str()
550 }
551}
552
553impl PartialEq<str> for Arg {
554 fn eq(&self, other: &str) -> bool {
555 self.as_str() == other
556 }
557}
558
559impl PartialEq<&str> for Arg {
560 fn eq(&self, other: &&str) -> bool {
561 self.as_str() == *other
562 }
563}
564
565#[derive(Debug, Clone, Copy, Eq, PartialEq)]
566pub enum IoStream {
567 Stdin,
568 Stdout,
569 Stderr,
570 Tty,
574 Rows(u16),
576 Cols(u16),
578}
579
580impl IoStream {
581 pub fn name(&self) -> &'static str {
586 match self {
587 IoStream::Stdin => "stdin",
588 IoStream::Stdout => "stdout",
589 IoStream::Stderr => "stderr",
590 IoStream::Tty => "tty",
591 IoStream::Rows(_) => "rows",
592 IoStream::Cols(_) => "cols",
593 }
594 }
595}
596
597#[derive(Debug, Clone, Eq, PartialEq)]
598pub struct IoBinding {
599 pub stream: IoStream,
600 pub pipe: Option<PipeTarget>,
601}
602
603#[derive(Debug, Clone, Eq, PartialEq)]
606pub enum PipeTarget {
607 Var { name: String },
608}
609
610pub use crate::value::{
614 OxDockType, SemaphoreState, TypeDescriptor, Value, ValuePayload, clone_boxed, clone_copy,
615 clone_shared, drop_boxed, drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed,
616 fmt_inline, fmt_shared, load_inline, startup_descriptors, store_inline, type_anchor,
617 unshare_boxed, unshare_inline, unshare_shared,
618};
619
620#[derive(Debug, Clone, Copy, Eq, PartialEq)]
621pub enum CompareOp {
622 Eq,
623 Ne,
624 Lt,
625 Le,
626 Gt,
627 Ge,
628}
629
630#[derive(Debug, Clone, Copy, Eq, PartialEq)]
631pub enum ArithOp {
632 Add,
633 Sub,
634 Mul,
635 Div,
636}
637
638#[derive(Debug, Clone, PartialEq)]
647pub enum MathOp {
648 PushConst(Value),
649 Load { name: String },
650 LoadConstRef { alias: String, name: String },
651 LoadEnv(String),
652 LoadKeyPath { base: String, keys: Vec<String> },
653 Call { name: String, arity: usize },
654 Inspect { name: String },
655 Neg,
656 Add,
657 Sub,
658 Mul,
659 Div,
660 Lt,
661 Le,
662 Gt,
663 Ge,
664 Eq,
665 Ne,
666}
667
668#[derive(Debug, Clone, Copy, Eq, PartialEq)]
669pub enum LogicalOp {
670 And,
671 Or,
672}
673
674#[derive(Debug, Clone, PartialEq)]
675pub enum Expr {
676 Literal(Value),
677 Var {
682 name: String,
683 },
684 ConstRef {
690 alias: String,
691 name: String,
692 },
693 Env(String),
696 KeyPath {
698 base: String,
699 keys: Vec<String>,
700 },
701 List(Vec<Expr>),
702 Map(Vec<(String, Expr)>),
703 Block(Vec<Step>),
708 Call {
709 name: String,
710 args: Vec<Expr>,
711 },
712 Inspect {
718 name: String,
719 },
720 Compare {
721 op: CompareOp,
722 left: Box<Expr>,
723 right: Box<Expr>,
724 },
725 Arithmetic {
726 op: ArithOp,
727 left: Box<Expr>,
728 right: Box<Expr>,
729 },
730 CompiledMath(Vec<MathOp>),
733 FreshPipe,
739 UnsignedIntBoundary(u64),
743 Not(Box<Expr>),
744 Logical {
745 op: LogicalOp,
746 left: Box<Expr>,
747 right: Box<Expr>,
748 },
749}
750
751#[derive(Debug, Clone)]
752pub struct Step {
753 pub guard: Option<GuardExpr>,
754 pub kind: StepKind,
755 pub scope_enter: usize,
756 pub scope_exit: usize,
757 pub line: usize,
764 pub col: usize,
768}
769
770impl PartialEq for Step {
771 fn eq(&self, other: &Self) -> bool {
772 self.guard == other.guard
773 && self.kind == other.kind
774 && self.scope_enter == other.scope_enter
775 && self.scope_exit == other.scope_exit
776 }
777}
778
779impl Eq for Step {}
780
781impl Step {
782 pub fn span(&self) -> Span {
787 if self.line == 0 {
788 return Span::default();
789 }
790 if self.col == 0 {
791 return Span::line_only(self.line);
792 }
793 Span::line_col(self.line, self.col)
794 }
795
796 pub fn defined_symbol(&self) -> Option<(&str, Span)> {
801 match &self.kind {
802 StepKind::TypeAlias { name, .. } => Some((name.as_str(), self.span())),
803 StepKind::FuncDef { name, .. } => Some((name.as_str(), self.span())),
804 _ => None,
805 }
806 }
807}
808
809impl Expr {
810 pub fn walk(&self, f: &mut impl FnMut(&Expr)) {
817 f(self);
818 match self {
819 Expr::Literal(_)
820 | Expr::Var { .. }
821 | Expr::ConstRef { .. }
822 | Expr::Env(_)
823 | Expr::KeyPath { .. }
824 | Expr::Inspect { .. }
825 | Expr::FreshPipe
826 | Expr::UnsignedIntBoundary(_) => {}
827 Expr::Call { args, .. } => {
828 for arg in args {
829 arg.walk(f);
830 }
831 }
832 Expr::List(items) => {
833 for item in items {
834 item.walk(f);
835 }
836 }
837 Expr::Map(entries) => {
838 for (_, value) in entries {
839 value.walk(f);
840 }
841 }
842 Expr::Block(steps) => {
843 for step in steps {
844 step.kind.walk_step_exprs(f);
845 }
846 }
847 Expr::Compare { left, right, .. }
848 | Expr::Arithmetic { left, right, .. }
849 | Expr::Logical { left, right, .. } => {
850 left.walk(f);
851 right.walk(f);
852 }
853 Expr::CompiledMath(_) => {}
854 Expr::Not(inner) => inner.walk(f),
855 }
856 }
857
858 pub fn walk_mut(&mut self, f: &mut impl FnMut(&mut Expr)) {
865 f(self);
866 match self {
867 Expr::Literal(_)
868 | Expr::Var { .. }
869 | Expr::ConstRef { .. }
870 | Expr::Env(_)
871 | Expr::KeyPath { .. }
872 | Expr::Inspect { .. }
873 | Expr::FreshPipe
874 | Expr::UnsignedIntBoundary(_) => {}
875 Expr::Call { args, .. } => {
876 for arg in args {
877 arg.walk_mut(f);
878 }
879 }
880 Expr::List(items) => {
881 for item in items {
882 item.walk_mut(f);
883 }
884 }
885 Expr::Map(entries) => {
886 for (_, value) in entries {
887 value.walk_mut(f);
888 }
889 }
890 Expr::Block(_) => {}
891 Expr::Compare { left, right, .. }
892 | Expr::Arithmetic { left, right, .. }
893 | Expr::Logical { left, right, .. } => {
894 left.walk_mut(f);
895 right.walk_mut(f);
896 }
897 Expr::CompiledMath(_) => {}
898 Expr::Not(inner) => inner.walk_mut(f),
899 }
900 }
901}
902
903#[derive(Debug, Clone, Eq, PartialEq)]
904pub enum WorkspaceTarget {
905 Snapshot,
906 Local,
907 Cache { local: bool },
908 System,
909}
910
911pub trait EnvLookup {
912 fn get_env(&self, key: &str) -> Option<&str>;
913}
914
915impl EnvLookup for HashMap<String, String> {
916 fn get_env(&self, key: &str) -> Option<&str> {
917 self.get(key).map(|s| s.as_str())
918 }
919}
920
921impl EnvLookup for Arc<HashMap<String, String>> {
922 fn get_env(&self, key: &str) -> Option<&str> {
923 (**self).get_env(key)
924 }
925}
926
927pub fn guard_allows(guard: &Guard, env: &impl EnvLookup) -> bool {
928 let Guard::Attr { ns, key, val } = guard;
929 match ns {
930 Ns::Os => match val.as_deref() {
931 Some("macos") => platform_is_macos(),
932 Some("linux") => platform_is_linux(),
933 Some("windows") => platform_is_windows(),
934 _ => false,
935 },
936 Ns::Arch => match val.as_deref() {
937 Some(want) => ARCH_TARGET == want,
938 None => false,
939 },
940 Ns::Bool => val
941 .as_deref()
942 .map(|v| v.parse::<bool>().unwrap_or(false))
943 .unwrap_or(false),
944 Ns::Env => match key.as_deref() {
945 Some(var) => match val {
946 None => env.get_env(var).map(|v| !v.is_empty()).unwrap_or(false),
947 Some(want) => env
948 .get_env(var)
949 .map(|v| v == want.as_str())
950 .unwrap_or(false),
951 },
952 None => false,
954 },
955 }
956}
957
958#[allow(clippy::disallowed_macros)]
961fn platform_is_windows() -> bool {
962 cfg!(windows)
963}
964
965#[allow(clippy::disallowed_macros)]
967fn platform_is_macos() -> bool {
968 cfg!(target_os = "macos")
969}
970
971#[allow(clippy::disallowed_macros)]
973fn platform_is_linux() -> bool {
974 cfg!(target_os = "linux")
975}
976
977const ARCH_TARGET: &str = std::env::consts::ARCH;
980
981pub fn guard_expr_allows(expr: &GuardExpr, env: &impl EnvLookup) -> bool {
982 match expr {
983 GuardExpr::Predicate(guard) => guard_allows(guard, env),
984 GuardExpr::All(children) => children.iter().all(|g| guard_expr_allows(g, env)),
985 GuardExpr::Or(children) => children.iter().any(|g| guard_expr_allows(g, env)),
986 GuardExpr::Not(child) => !guard_expr_allows(child, env),
987 }
988}
989
990pub fn guard_option_allows(expr: Option<&GuardExpr>, env: &impl EnvLookup) -> bool {
991 match expr {
992 Some(e) => guard_expr_allows(e, env),
993 None => true,
994 }
995}
996
997impl Guard {
998 pub fn is_disjoint_from(&self, other: &Self) -> bool {
1007 match (self, other) {
1008 (
1009 Guard::Attr {
1010 ns: n1,
1011 key: k1,
1012 val: Some(v1),
1013 },
1014 Guard::Attr {
1015 ns: n2,
1016 key: k2,
1017 val: Some(v2),
1018 },
1019 ) => n1 == n2 && k1 == k2 && v1 != v2,
1020 _ => false,
1021 }
1022 }
1023}
1024
1025impl GuardExpr {
1026 pub fn is_disjoint_from(&self, other: &Self) -> bool {
1032 match (self, other) {
1033 (x, GuardExpr::Not(inner)) | (GuardExpr::Not(inner), x) => {
1041 x == inner.as_ref() || unset_excludes(x, inner.as_ref())
1042 }
1043 (GuardExpr::Predicate(p1), GuardExpr::Predicate(p2)) => p1.is_disjoint_from(p2),
1045 (GuardExpr::Or(arms), other) | (other, GuardExpr::Or(arms)) => {
1047 arms.iter().all(|arm| arm.is_disjoint_from(other))
1048 }
1049 (GuardExpr::All(arms), other) | (other, GuardExpr::All(arms)) => {
1051 arms.iter().any(|arm| arm.is_disjoint_from(other))
1052 }
1053 }
1054 }
1055}
1056
1057fn conjuncts(expr: &GuardExpr) -> Vec<&GuardExpr> {
1061 match expr {
1062 GuardExpr::All(items) => items.iter().collect(),
1063 single => vec![single],
1064 }
1065}
1066
1067fn closed_domain_values(ns: Ns, key: Option<&str>) -> Option<&'static [&'static str]> {
1074 match (ns, key) {
1075 (Ns::Bool, None) => Some(&["true", "false"]),
1076 (Ns::Os, None) => Some(&["macos", "linux", "windows"]),
1077 (Ns::Arch, None) => Some(ARCH_VALUES),
1078 _ => None,
1079 }
1080}
1081
1082#[derive(Clone)]
1085enum DnfLit {
1086 Pos(Guard),
1087 Neg(Guard),
1088}
1089
1090impl DnfLit {
1091 fn as_expr(&self) -> GuardExpr {
1092 match self {
1093 DnfLit::Pos(guard) => GuardExpr::Predicate(guard.clone()),
1094 DnfLit::Neg(guard) => GuardExpr::Not(Box::new(GuardExpr::Predicate(guard.clone()))),
1095 }
1096 }
1097}
1098
1099const MAX_DNF_DISJUNCTS: usize = 64;
1104
1105fn dnf_push(expr: &GuardExpr, polarity: bool, out: &mut Vec<Vec<DnfLit>>) -> bool {
1110 match (expr, polarity) {
1111 (GuardExpr::Predicate(guard), true) => {
1112 for disjunct in out.iter_mut() {
1113 disjunct.push(DnfLit::Pos(guard.clone()));
1114 }
1115 true
1116 }
1117 (GuardExpr::Predicate(guard), false) => {
1118 for disjunct in out.iter_mut() {
1119 disjunct.push(DnfLit::Neg(guard.clone()));
1120 }
1121 true
1122 }
1123 (GuardExpr::All(children), true) | (GuardExpr::Or(children), false) => {
1124 for child in children {
1126 if !dnf_push(child, polarity, out) {
1127 return false;
1128 }
1129 }
1130 true
1131 }
1132 (GuardExpr::Or(children), true) | (GuardExpr::All(children), false) => {
1133 let mut forked = Vec::new();
1135 for disjunct in out.drain(..) {
1136 for child in children {
1137 let mut branch = vec![disjunct.clone()];
1138 if !dnf_push(child, polarity, &mut branch) {
1139 return false;
1140 }
1141 forked.extend(branch);
1142 if forked.len() > MAX_DNF_DISJUNCTS {
1143 return false;
1144 }
1145 }
1146 }
1147 *out = forked;
1148 true
1149 }
1150 (GuardExpr::Not(inner), _) => dnf_push(inner, !polarity, out),
1151 }
1152}
1153
1154fn disjunct_satisfiable(lits: &[DnfLit]) -> bool {
1158 for lit in lits {
1162 match lit {
1163 DnfLit::Pos(Guard::Attr {
1164 ns: Ns::Bool, val, ..
1165 }) if val.as_deref() != Some("true") => return false,
1166 DnfLit::Neg(Guard::Attr {
1167 ns: Ns::Bool,
1168 key: None,
1169 val: Some(value),
1170 }) if value == "true" => return false,
1171 _ => {}
1172 }
1173 }
1174 for (index, first) in lits.iter().enumerate() {
1177 for second in &lits[index + 1..] {
1178 if first.as_expr().is_disjoint_from(&second.as_expr()) {
1179 return false;
1180 }
1181 }
1182 }
1183 for lit in lits {
1187 let (ns, key) = match lit {
1188 DnfLit::Neg(Guard::Attr {
1189 ns,
1190 key,
1191 val: Some(_),
1192 }) => (*ns, key.as_deref()),
1193 _ => continue,
1194 };
1195 let Some(domain) = closed_domain_values(ns, key) else {
1196 continue;
1197 };
1198 let exhausted = domain.iter().all(|value| {
1199 lits.iter().any(|other| match other {
1200 DnfLit::Neg(Guard::Attr {
1201 ns: other_ns,
1202 key: other_key,
1203 val: Some(other_val),
1204 }) => *other_ns == ns && other_key.as_deref() == key && other_val == value,
1205 _ => false,
1206 })
1207 });
1208 if exhausted {
1209 return false;
1210 }
1211 }
1212 true
1213}
1214
1215fn conjunction_dead(atoms: &[&GuardExpr]) -> bool {
1222 if atoms.is_empty() {
1223 return false;
1224 }
1225 let mut disjuncts = vec![Vec::new()];
1226 for atom in atoms {
1227 if !dnf_push(atom, true, &mut disjuncts) {
1228 return false;
1229 }
1230 }
1231 !disjuncts
1232 .iter()
1233 .any(|disjunct| disjunct_satisfiable(disjunct))
1234}
1235
1236pub fn guard_satisfiable(expr: &GuardExpr) -> bool {
1238 !conjunction_dead(&conjuncts(expr))
1239}
1240
1241pub fn guard_valid(expr: &GuardExpr) -> bool {
1244 match expr {
1245 GuardExpr::Predicate(Guard::Attr {
1246 ns: Ns::Bool,
1247 val: Some(value),
1248 ..
1249 }) => value.as_str() == "true",
1250 GuardExpr::All(items) => items.iter().all(guard_valid),
1251 GuardExpr::Not(inner) => !guard_satisfiable(inner),
1252 _ => false,
1253 }
1254}
1255
1256pub fn guards_overlap(a: Option<&GuardExpr>, b: Option<&GuardExpr>) -> bool {
1259 match (a, b) {
1260 (None, None) => true,
1261 (Some(x), None) | (None, Some(x)) => guard_satisfiable(x),
1262 (Some(x), Some(y)) => {
1263 let mut atoms = conjuncts(x);
1264 atoms.extend(conjuncts(y));
1265 !conjunction_dead(&atoms)
1266 }
1267 }
1268}
1269
1270fn unset_excludes(x: &GuardExpr, inner: &GuardExpr) -> bool {
1273 match (x, inner) {
1274 (
1275 GuardExpr::Predicate(Guard::Attr {
1276 ns: n2, key: k2, ..
1277 }),
1278 GuardExpr::Predicate(Guard::Attr {
1279 ns: n1,
1280 key: k1,
1281 val: None,
1282 }),
1283 ) => n1 == n2 && k1 == k2,
1284 _ => false,
1285 }
1286}
1287
1288impl fmt::Display for Guard {
1289 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1295 match self {
1296 Guard::Attr {
1297 ns: Ns::Env,
1298 key: Some(var),
1299 val: None,
1300 } => write!(f, "env:{var}"),
1301 Guard::Attr {
1302 ns: Ns::Env,
1303 key: Some(var),
1304 val: Some(want),
1305 } => write!(f, "eq(env:{var}, {want})"),
1306 Guard::Attr {
1307 ns,
1308 key: _,
1309 val: Some(value),
1310 } => write!(f, "{ns}:{value}"),
1311 Guard::Attr { ns, key, val: None } => match key {
1312 Some(subject) => write!(f, "{ns}:{subject}"),
1313 None => write!(f, "{ns}"),
1314 },
1315 }
1316 }
1317}
1318
1319impl fmt::Display for WorkspaceTarget {
1320 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1321 match self {
1322 WorkspaceTarget::Snapshot => write!(f, "SNAPSHOT"),
1323 WorkspaceTarget::Local => write!(f, "LOCAL"),
1324 WorkspaceTarget::Cache { local: false } => write!(f, "CACHE"),
1325 WorkspaceTarget::Cache { local: true } => write!(f, "CACHE --local"),
1326 WorkspaceTarget::System => write!(f, "SYSTEM"),
1327 }
1328 }
1329}
1330
1331impl fmt::Display for Expr {
1332 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1333 match self {
1334 Expr::Literal(v) => write!(f, "{}", v),
1335 Expr::Var { name } => {
1336 write!(f, "{VAR_SIGIL}{}", name)
1337 }
1338 Expr::ConstRef { alias, name } => {
1339 write!(f, "{}", sigil_qualified(alias, name))
1340 }
1341 Expr::Env(key) => write!(f, "env:{}", key),
1342 Expr::KeyPath { base, keys } => {
1343 write!(f, "{VAR_SIGIL}{}", base)?;
1344 for key in keys {
1345 write!(f, ".{}", key)?;
1346 }
1347 Ok(())
1348 }
1349 Expr::Call { name, args } => {
1350 write!(f, "{}(", name)?;
1351 for (i, arg) in args.iter().enumerate() {
1352 if i > 0 {
1353 write!(f, ", ")?;
1354 }
1355 write!(f, "{}", arg)?;
1356 }
1357 write!(f, ")")
1358 }
1359 Expr::Inspect { name } => {
1360 write!(f, "{KEYWORD_INSPECT}(${})", name)
1361 }
1362 Expr::List(items) => {
1363 write!(f, "[")?;
1364 for (i, item) in items.iter().enumerate() {
1365 if i > 0 {
1366 write!(f, ", ")?;
1367 }
1368 write!(f, "{}", item)?;
1369 }
1370 write!(f, "]")
1371 }
1372 Expr::Map(entries) => {
1373 write!(f, "{{")?;
1374 for (i, (key, val)) in entries.iter().enumerate() {
1375 if i > 0 {
1376 write!(f, ", ")?;
1377 }
1378 write!(f, "\"{}\": {}", key, val)?;
1379 }
1380 write!(f, "}}")
1381 }
1382 Expr::Block(steps) => {
1383 write!(f, "{{ ")?;
1384 for (i, step) in steps.iter().enumerate() {
1385 if i > 0 {
1386 write!(f, "; ")?;
1387 }
1388 write!(f, "{}", step.kind)?;
1389 }
1390 write!(f, " }}")
1391 }
1392 Expr::Compare { op, left, right } => {
1393 write!(f, "({} {} {})", left, op, right)
1397 }
1398 Expr::Arithmetic { op, left, right } => {
1399 write!(f, "({} {} {})", left, op, right)
1400 }
1401 Expr::CompiledMath(ops) => {
1402 write!(f, "{}", format_compiled_math(ops))
1403 }
1404 Expr::FreshPipe => write!(f, "<fresh pipe>"),
1408 Expr::UnsignedIntBoundary(n) => write!(f, "{}", n),
1409 Expr::Not(inner) => {
1410 match inner.as_ref() {
1413 Expr::Compare { .. } | Expr::Arithmetic { .. } | Expr::CompiledMath(_) => {
1414 write!(f, "!({})", inner)
1415 }
1416 _ => write!(f, "!{}", inner),
1417 }
1418 }
1419 Expr::Logical { op, left, right } => {
1420 write!(f, "({} {} {})", left, op, right)
1421 }
1422 }
1423 }
1424}
1425
1426impl fmt::Display for CompareOp {
1427 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1428 match self {
1429 CompareOp::Eq => write!(f, "=="),
1430 CompareOp::Ne => write!(f, "!="),
1431 CompareOp::Lt => write!(f, "<"),
1432 CompareOp::Le => write!(f, "<="),
1433 CompareOp::Gt => write!(f, ">"),
1434 CompareOp::Ge => write!(f, ">="),
1435 }
1436 }
1437}
1438
1439impl fmt::Display for ArithOp {
1440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1441 match self {
1442 ArithOp::Add => write!(f, "+"),
1443 ArithOp::Sub => write!(f, "-"),
1444 ArithOp::Mul => write!(f, "*"),
1445 ArithOp::Div => write!(f, "/"),
1446 }
1447 }
1448}
1449
1450fn format_compiled_math(ops: &[MathOp]) -> String {
1455 let mut stack: Vec<String> = Vec::new();
1456 for op in ops {
1457 match op {
1458 MathOp::PushConst(v) => stack.push(format!("{}", v)),
1459 MathOp::Load { name } => {
1460 stack.push(format!("{VAR_SIGIL}{}", name));
1461 }
1462 MathOp::LoadConstRef { alias, name } => stack.push(sigil_qualified(alias, name)),
1463 MathOp::LoadEnv(key) => stack.push(format!("env:{}", key)),
1464 MathOp::LoadKeyPath { base, keys } => {
1465 let mut s = format!("{VAR_SIGIL}{}", base);
1466 for key in keys {
1467 s.push('.');
1468 s.push_str(key);
1469 }
1470 stack.push(s);
1471 }
1472 MathOp::Call { name, arity } => {
1473 let mut args = Vec::new();
1474 for _ in 0..*arity {
1475 args.push(stack.pop().unwrap_or_else(|| "<underflow>".to_string()));
1476 }
1477 args.reverse();
1478 stack.push(format!("{}({})", name, args.join(", ")));
1479 }
1480 MathOp::Inspect { name } => {
1481 stack.push(format!("{KEYWORD_INSPECT}({VAR_SIGIL}{})", name));
1482 }
1483 MathOp::Neg => {
1484 let inner = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1485 stack.push(format!("(-{})", inner));
1486 }
1487 MathOp::Add => push_bin(&mut stack, "+"),
1488 MathOp::Sub => push_bin(&mut stack, "-"),
1489 MathOp::Mul => push_bin(&mut stack, "*"),
1490 MathOp::Div => push_bin(&mut stack, "/"),
1491 MathOp::Lt => push_bin(&mut stack, "<"),
1492 MathOp::Le => push_bin(&mut stack, "<="),
1493 MathOp::Gt => push_bin(&mut stack, ">"),
1494 MathOp::Ge => push_bin(&mut stack, ">="),
1495 MathOp::Eq => push_bin(&mut stack, "=="),
1496 MathOp::Ne => push_bin(&mut stack, "!="),
1497 }
1498 }
1499 if stack.len() == 1 {
1500 let mut items = stack;
1501 items.pop().unwrap_or_else(|| "<empty>".to_string())
1502 } else {
1503 stack.join(" ")
1504 }
1505}
1506
1507fn push_bin(stack: &mut Vec<String>, op: &str) {
1508 let right = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1509 let left = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1510 stack.push(format!("({} {} {})", left, op, right));
1511}
1512
1513impl fmt::Display for LogicalOp {
1514 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1515 match self {
1516 LogicalOp::And => write!(f, "&&"),
1517 LogicalOp::Or => write!(f, "||"),
1518 }
1519 }
1520}
1521
1522enum GuardDisplayContext {
1523 Root,
1524 InAnyArg,
1525 InNot,
1526 InAll,
1527}
1528
1529impl GuardExpr {
1530 fn fmt_with_ctx(&self, f: &mut fmt::Formatter<'_>, ctx: GuardDisplayContext) -> fmt::Result {
1531 match self {
1532 GuardExpr::Predicate(guard) => write!(f, "{}", guard),
1533 GuardExpr::All(children) => {
1534 let wrap = matches!(
1535 ctx,
1536 GuardDisplayContext::InAnyArg | GuardDisplayContext::InNot
1537 ) && children.len() > 1;
1538 if wrap {
1539 write!(f, "(")?;
1540 }
1541 for (i, child) in children.iter().enumerate() {
1542 if i > 0 {
1543 write!(f, ", ")?;
1544 }
1545 child.fmt_with_ctx(f, GuardDisplayContext::InAll)?;
1546 }
1547 if wrap {
1548 write!(f, ")")?;
1549 }
1550 Ok(())
1551 }
1552 GuardExpr::Or(children) => {
1553 write!(f, "any(")?;
1554 for (i, child) in children.iter().enumerate() {
1555 if i > 0 {
1556 write!(f, ", ")?;
1557 }
1558 child.fmt_with_ctx(f, GuardDisplayContext::InAnyArg)?;
1559 }
1560 write!(f, ")")
1561 }
1562 GuardExpr::Not(child) => {
1563 write!(f, "not(")?;
1564 child.fmt_with_ctx(f, GuardDisplayContext::InNot)?;
1565 write!(f, ")")
1566 }
1567 }
1568 }
1569}
1570
1571impl fmt::Display for GuardExpr {
1572 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1573 self.fmt_with_ctx(f, GuardDisplayContext::Root)
1574 }
1575}
1576
1577impl fmt::Display for Step {
1578 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1579 if let Some(expr) = &self.guard {
1580 write!(f, "[{}] ", expr)?;
1581 }
1582 write!(f, "{}", self.kind)
1583 }
1584}
1585
1586#[cfg(test)]
1587mod tests {
1588 use super::*;
1589 #[test]
1597 fn statement_keywords_match_backend() {
1598 for kw in STRUCTURAL_KEYWORDS {
1606 let via_backend = crate::parse_script(kw, crate::commands::lower_command);
1607 let via_lowering =
1608 crate::commands::lower_command(kw, Vec::new()).map(|kind| crate::Step {
1609 guard: None,
1610 kind,
1611 scope_enter: 0,
1612 scope_exit: 0,
1613 line: 0,
1614 col: 0,
1615 });
1616 match (via_backend, via_lowering) {
1617 (Ok(_), _) => {}
1618 (Err(a), Err(b)) => {
1619 assert_eq!(
1620 a.kind(),
1621 b.kind(),
1622 "backend kind drift for bare keyword {kw}: {a} vs {b}"
1623 );
1624 }
1625 (Err(a), Ok(_)) => {
1626 panic!("backend rejects bare keyword {kw} that lowering accepts: {a}")
1627 }
1628 }
1629 }
1630 for head in [
1634 "LET",
1635 "CONST",
1636 "RETURN",
1637 "BREAK",
1638 "CONTINUE",
1639 "IF",
1640 "FOR",
1641 "WHILE",
1642 "FUNC",
1643 "REMOTE",
1644 "INHERIT_ENV",
1645 "WITH_IO",
1646 "ASYNC",
1647 "TIMEOUT",
1648 "ISOLATED",
1649 "AWAIT",
1650 "CANCEL",
1651 "RUN",
1652 "IMPORT",
1653 "EXPORT",
1654 "TYPE",
1655 ] {
1656 assert!(
1657 STRUCTURAL_KEYWORDS.contains(&head)
1658 || crate::all_metadata().iter().any(|m| m.name == head),
1659 "structural head {head} is not registered"
1660 );
1661 }
1662 }
1663
1664 #[test]
1668 fn command_names_group_by_category() {
1669 for command in COMMANDS {
1670 let name = command.as_str();
1671 let Some((prefix, _)) = name.split_once('_') else {
1672 continue;
1673 };
1674 assert!(
1675 COMMAND_CATEGORIES.contains(&prefix),
1676 "command {name} introduces unregistered category {prefix}; add it to COMMAND_CATEGORIES"
1677 );
1678 }
1679 }
1680
1681 #[test]
1689 fn registry_commands_all_parse() {
1690 for meta in crate::all_metadata() {
1691 if !meta.in_index || STRUCTURAL_KEYWORDS.contains(&meta.name) {
1692 continue;
1693 }
1694 assert!(
1695 Command::parse(meta.name).is_some(),
1696 "registry command {} has no Command::parse arm",
1697 meta.name
1698 );
1699 }
1700 }
1701
1702 #[test]
1707 fn definition_spans_cover_type_and_func() {
1708 let alias = Step {
1709 guard: None,
1710 kind: StepKind::TypeAlias {
1711 name: "EMP".to_string(),
1712 target: "MAP<n: STRING>".to_string(),
1713 },
1714 scope_enter: 0,
1715 scope_exit: 0,
1716 line: 3,
1717 col: 5,
1718 };
1719 let (name, span) = alias.defined_symbol().expect("alias defines");
1720 assert_eq!(name, "EMP");
1721 assert_eq!(span.line, 3);
1722 assert_eq!(span.col_start, Some(5));
1723
1724 let func = Step {
1725 guard: None,
1726 kind: StepKind::FuncDef {
1727 name: "F".to_string(),
1728 params: Vec::new(),
1729 return_type: "VOID".to_string(),
1730 is_async: false,
1731 body: Vec::new(),
1732 docs: None,
1733 },
1734 scope_enter: 0,
1735 scope_exit: 0,
1736 line: 7,
1737 col: 1,
1738 };
1739 let (name, span) = func.defined_symbol().expect("func defines");
1740 assert_eq!(name, "F");
1741 assert_eq!(span.line, 7);
1742
1743 let plain = Step {
1744 guard: None,
1745 kind: StepKind::Break,
1746 scope_enter: 0,
1747 scope_exit: 0,
1748 line: 9,
1749 col: 1,
1750 };
1751 assert!(plain.defined_symbol().is_none());
1752
1753 let unknown = Step {
1754 guard: None,
1755 kind: StepKind::Break,
1756 scope_enter: 0,
1757 scope_exit: 0,
1758 line: 0,
1759 col: 0,
1760 };
1761 assert_eq!(unknown.span().line, 0);
1762 }
1763
1764 #[test]
1768 fn parsed_definitions_carry_spans() {
1769 let steps = crate::parse_script(
1770 indoc::indoc! {r#"
1771 TYPE EMP = MAP<n: STRING>
1772 FUNC F(): VOID {
1773 RETURN
1774 }
1775 "#},
1776 crate::commands::lower_command,
1777 )
1778 .expect("definitions parse");
1779 let mut names: Vec<(&str, usize)> = steps
1780 .iter()
1781 .filter_map(|s| s.defined_symbol().map(|(n, span)| (n, span.line)))
1782 .collect();
1783 names.sort();
1784 assert_eq!(names, vec![("EMP", 1), ("F", 2)]);
1785 }
1786}
1787
1788#[cfg(test)]
1789mod guard_analysis_tests {
1790 use super::*;
1791
1792 fn attr(ns: Ns, key: Option<&str>, val: Option<&str>) -> GuardExpr {
1793 GuardExpr::Predicate(Guard::Attr {
1794 ns,
1795 key: key.map(str::to_string),
1796 val: val.map(str::to_string),
1797 })
1798 }
1799
1800 fn os(value: &str) -> GuardExpr {
1801 attr(Ns::Os, None, Some(value))
1802 }
1803
1804 fn arch(value: &str) -> GuardExpr {
1805 attr(Ns::Arch, None, Some(value))
1806 }
1807
1808 fn unix() -> GuardExpr {
1811 GuardExpr::Or(vec![os("macos"), os("linux")])
1812 }
1813
1814 fn windows() -> GuardExpr {
1815 os("windows")
1816 }
1817
1818 fn env_eq(var: &str, value: &str) -> GuardExpr {
1819 attr(Ns::Env, Some(var), Some(value))
1820 }
1821
1822 fn not(expr: GuardExpr) -> GuardExpr {
1823 GuardExpr::Not(Box::new(expr))
1824 }
1825
1826 #[test]
1830 fn partition_negations_are_jointly_dead() {
1831 let os_exhausted = GuardExpr::All(vec![not(os("macos")), not(os("linux")), not(windows())]);
1832 assert!(
1833 !guard_satisfiable(&os_exhausted),
1834 "no host is outside `macos`/`linux`/`windows`"
1835 );
1836 let os_partial = GuardExpr::All(vec![not(os("macos")), not(os("linux"))]);
1838 assert!(guard_satisfiable(&os_partial), "`windows` is still open");
1839 let bool_exhausted = GuardExpr::All(vec![
1841 not(attr(Ns::Bool, None, Some("true"))),
1842 not(attr(Ns::Bool, None, Some("false"))),
1843 ]);
1844 assert!(!guard_satisfiable(&bool_exhausted));
1845 let env_open = GuardExpr::All(vec![
1847 not(env_eq("MODE", "dev")),
1848 not(env_eq("MODE", "prod")),
1849 ]);
1850 assert!(guard_satisfiable(&env_open), "MODE may hold a third value");
1851 assert!(guard_satisfiable(¬(unix())));
1853 }
1854
1855 #[test]
1858 fn unix_alias_is_os_disjunction() {
1859 assert!(!guards_overlap(Some(&unix()), Some(&windows())));
1860 assert!(guards_overlap(Some(&unix()), Some(&os("macos"))));
1861 let covered = GuardExpr::All(vec![GuardExpr::Not(Box::new(unix())), not(windows())]);
1864 assert!(!guard_satisfiable(&covered));
1865 }
1866
1867 #[test]
1871 fn arch_guards_decide_by_value() {
1872 assert!(!guards_overlap(
1873 Some(&arch("x86_64")),
1874 Some(&arch("aarch64"))
1875 ));
1876 assert!(guards_overlap(Some(&arch("x86_64")), Some(&arch("x86_64"))));
1877 assert!(guards_overlap(Some(&arch("aarch64")), Some(&os("macos"))));
1878 let exhausted = GuardExpr::All(ARCH_VALUES.iter().map(|value| not(arch(value))).collect());
1879 assert!(!guard_satisfiable(&exhausted));
1880 let host = attr(Ns::Arch, None, Some(ARCH_TARGET));
1882 assert!(guard_expr_allows(&host, &HashMap::new()));
1883 }
1884
1885 #[test]
1889 fn platform_overlap_matrix_is_exhaustive() {
1890 let cases = [
1891 ("macos", "macos", true),
1892 ("macos", "linux", false),
1893 ("macos", "windows", false),
1894 ("linux", "linux", true),
1895 ("linux", "windows", false),
1896 ("windows", "windows", true),
1897 ];
1898 for (v1, v2, expected) in cases {
1899 let left = os(v1);
1900 let right = os(v2);
1901 assert_eq!(
1902 guards_overlap(Some(&left), Some(&right)),
1903 expected,
1904 "os:{v1} vs os:{v2}"
1905 );
1906 }
1907 }
1908
1909 #[test]
1912 fn disjoint_pairs_never_cofire_here() {
1913 let macos = os("macos");
1914 let holds = |expr: &GuardExpr| guard_expr_allows(expr, &HashMap::new());
1915 assert!(
1916 !(holds(&macos) && holds(&windows())),
1917 "os:macos and os:windows co-fired"
1918 );
1919 }
1920
1921 #[test]
1922 fn overlap_follows_namespace_semantics() {
1923 assert!(!guards_overlap(Some(&windows()), Some(&unix())));
1925 assert!(!guards_overlap(Some(&os("macos")), Some(&os("linux"))));
1926 assert!(guards_overlap(None, Some(&windows())));
1928 assert!(guards_overlap(None, None));
1929 let dead = GuardExpr::All(vec![os("macos"), windows()]);
1931 assert!(!guard_satisfiable(&dead));
1932 assert!(!guards_overlap(Some(&dead), Some(&os("macos"))));
1933 assert!(guard_valid(&GuardExpr::Predicate(Guard::Attr {
1934 ns: Ns::Bool,
1935 key: None,
1936 val: Some("true".to_string()),
1937 })));
1938 assert!(!guard_valid(&unix()));
1939 }
1940
1941 #[test]
1942 fn env_value_conflicts_decide_without_enumeration() {
1943 let fast = env_eq("MODE", "fast");
1944 let slow = env_eq("MODE", "slow");
1945 assert!(
1946 !guards_overlap(Some(&fast), Some(&slow)),
1947 "same key distinct values are disjoint"
1948 );
1949 let also_fast = env_eq("MODE", "fast");
1950 assert!(guards_overlap(Some(&fast), Some(&also_fast)));
1951 let bare = attr(Ns::Env, Some("MODE"), None);
1953 assert!(guards_overlap(Some(&bare), Some(&fast)));
1954 }
1955}
1956
1957#[cfg(test)]
1958mod guard_algebra_tests {
1959 use super::*;
1960
1961 fn os(value: &str) -> GuardExpr {
1962 GuardExpr::Predicate(Guard::Attr {
1963 ns: Ns::Os,
1964 key: None,
1965 val: Some(value.to_string()),
1966 })
1967 }
1968
1969 #[test]
1970 fn or_distributes_over_disjointness() {
1971 fn env_eq(var: &str, value: &str) -> GuardExpr {
1972 GuardExpr::Predicate(Guard::Attr {
1973 ns: Ns::Env,
1974 key: Some(var.to_string()),
1975 val: Some(value.to_string()),
1976 })
1977 }
1978 let mixed = GuardExpr::Or(vec![env_eq("MODE", "dev"), env_eq("MODE", "prod")]);
1981 assert!(!mixed.is_disjoint_from(&env_eq("MODE", "dev")));
1982 assert!(mixed.is_disjoint_from(&env_eq("MODE", "test")));
1984 let cross = GuardExpr::Or(vec![env_eq("MODE", "dev")]);
1986 let platform = os("windows");
1987 assert!(!cross.is_disjoint_from(&platform));
1988 }
1989
1990 #[test]
1991 fn all_distributes_over_disjointness() {
1992 let stacked = GuardExpr::All(vec![
1993 os("macos"),
1994 GuardExpr::Or(vec![os("macos"), os("linux")]),
1995 os("windows"),
1996 ]);
1997 assert!(stacked.is_disjoint_from(&os("macos")));
1998 let live = GuardExpr::All(vec![
2001 os("macos"),
2002 GuardExpr::Predicate(Guard::Attr {
2003 ns: Ns::Env,
2004 key: Some("MODE".to_string()),
2005 val: Some("dev".to_string()),
2006 }),
2007 ]);
2008 assert!(!live.is_disjoint_from(&os("macos")));
2009 }
2010
2011 #[test]
2012 fn negation_is_structural_not_syntactic() {
2013 let not_win = GuardExpr::Not(Box::new(os("windows")));
2014 assert!(not_win.is_disjoint_from(&os("windows")));
2015 assert!(os("windows").is_disjoint_from(¬_win));
2016 assert!(!not_win.is_disjoint_from(&os("macos")));
2017 }
2018}