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 KEY_PATH_SEPARATOR, KEY_PATH_SEPARATOR_CHAR, KEYWORD_APPEND, KEYWORD_APPEND_LINE,
10 KEYWORD_ARCHIVE, KEYWORD_ASSERT_CONTAINS, KEYWORD_ASSERT_EQ, KEYWORD_ASSERT_NE, KEYWORD_ASYNC,
11 KEYWORD_AWAIT, KEYWORD_BREAK, KEYWORD_CANCEL, KEYWORD_CASE, KEYWORD_CONST, KEYWORD_CONTINUE,
12 KEYWORD_COPY, KEYWORD_COPY_GIT, KEYWORD_DEFAULT, KEYWORD_ECHO, KEYWORD_ELSE, KEYWORD_ENV,
13 KEYWORD_EXIT, KEYWORD_EXPAND, KEYWORD_EXPORT, KEYWORD_FAIL, KEYWORD_FOR, KEYWORD_FUNC,
14 KEYWORD_IF, KEYWORD_IMPORT, KEYWORD_IN, KEYWORD_INHERIT_ENV, KEYWORD_INSPECT, KEYWORD_INSTALL,
15 KEYWORD_ISOLATED, KEYWORD_LET, KEYWORD_LIST_APPEND, KEYWORD_LS, KEYWORD_MKDIR, KEYWORD_PROMPT,
16 KEYWORD_READ, 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 {
650 name: String,
651 },
652 LoadConstRef {
653 alias: String,
654 name: String,
655 keys: Vec<String>,
656 },
657 LoadEnv(String),
658 LoadKeyPath {
659 base: String,
660 keys: Vec<String>,
661 },
662 Call {
663 name: String,
664 arity: usize,
665 },
666 Inspect {
667 name: String,
668 },
669 Neg,
670 Add,
671 Sub,
672 Mul,
673 Div,
674 Lt,
675 Le,
676 Gt,
677 Ge,
678 Eq,
679 Ne,
680}
681
682#[derive(Debug, Clone, Copy, Eq, PartialEq)]
683pub enum LogicalOp {
684 And,
685 Or,
686}
687
688#[derive(Debug, Clone, PartialEq)]
689pub enum Expr {
690 Literal(Value),
691 Var {
696 name: String,
697 },
698 ConstRef {
705 alias: String,
706 name: String,
707 keys: Vec<String>,
708 },
709 Env(String),
712 KeyPath {
714 base: String,
715 keys: Vec<String>,
716 },
717 List(Vec<Expr>),
718 Map(Vec<(String, Expr)>),
719 Block(Vec<Step>),
724 Call {
725 name: String,
726 args: Vec<Expr>,
727 },
728 Inspect {
734 name: String,
735 },
736 Compare {
737 op: CompareOp,
738 left: Box<Expr>,
739 right: Box<Expr>,
740 },
741 Arithmetic {
742 op: ArithOp,
743 left: Box<Expr>,
744 right: Box<Expr>,
745 },
746 CompiledMath(Vec<MathOp>),
749 FreshPipe,
755 UnsignedIntBoundary(u64),
759 Not(Box<Expr>),
760 Logical {
761 op: LogicalOp,
762 left: Box<Expr>,
763 right: Box<Expr>,
764 },
765}
766
767#[derive(Debug, Clone)]
768pub struct Step {
769 pub guard: Option<GuardExpr>,
770 pub kind: StepKind,
771 pub scope_enter: usize,
772 pub scope_exit: usize,
773 pub line: usize,
780 pub col: usize,
784}
785
786impl PartialEq for Step {
787 fn eq(&self, other: &Self) -> bool {
788 self.guard == other.guard
789 && self.kind == other.kind
790 && self.scope_enter == other.scope_enter
791 && self.scope_exit == other.scope_exit
792 }
793}
794
795impl Eq for Step {}
796
797impl Step {
798 pub fn span(&self) -> Span {
803 if self.line == 0 {
804 return Span::default();
805 }
806 if self.col == 0 {
807 return Span::line_only(self.line);
808 }
809 Span::line_col(self.line, self.col)
810 }
811
812 pub fn defined_symbol(&self) -> Option<(&str, Span)> {
817 match &self.kind {
818 StepKind::TypeAlias { name, .. } => Some((name.as_str(), self.span())),
819 StepKind::FuncDef { name, .. } => Some((name.as_str(), self.span())),
820 _ => None,
821 }
822 }
823}
824
825impl Expr {
826 pub fn walk(&self, f: &mut impl FnMut(&Expr)) {
833 f(self);
834 match self {
835 Expr::Literal(_)
836 | Expr::Var { .. }
837 | Expr::ConstRef { .. }
838 | Expr::Env(_)
839 | Expr::KeyPath { .. }
840 | Expr::Inspect { .. }
841 | Expr::FreshPipe
842 | Expr::UnsignedIntBoundary(_) => {}
843 Expr::Call { args, .. } => {
844 for arg in args {
845 arg.walk(f);
846 }
847 }
848 Expr::List(items) => {
849 for item in items {
850 item.walk(f);
851 }
852 }
853 Expr::Map(entries) => {
854 for (_, value) in entries {
855 value.walk(f);
856 }
857 }
858 Expr::Block(steps) => {
859 for step in steps {
860 step.kind.walk_step_exprs(f);
861 }
862 }
863 Expr::Compare { left, right, .. }
864 | Expr::Arithmetic { left, right, .. }
865 | Expr::Logical { left, right, .. } => {
866 left.walk(f);
867 right.walk(f);
868 }
869 Expr::CompiledMath(_) => {}
870 Expr::Not(inner) => inner.walk(f),
871 }
872 }
873
874 pub fn walk_mut(&mut self, f: &mut impl FnMut(&mut Expr)) {
881 f(self);
882 match self {
883 Expr::Literal(_)
884 | Expr::Var { .. }
885 | Expr::ConstRef { .. }
886 | Expr::Env(_)
887 | Expr::KeyPath { .. }
888 | Expr::Inspect { .. }
889 | Expr::FreshPipe
890 | Expr::UnsignedIntBoundary(_) => {}
891 Expr::Call { args, .. } => {
892 for arg in args {
893 arg.walk_mut(f);
894 }
895 }
896 Expr::List(items) => {
897 for item in items {
898 item.walk_mut(f);
899 }
900 }
901 Expr::Map(entries) => {
902 for (_, value) in entries {
903 value.walk_mut(f);
904 }
905 }
906 Expr::Block(_) => {}
907 Expr::Compare { left, right, .. }
908 | Expr::Arithmetic { left, right, .. }
909 | Expr::Logical { left, right, .. } => {
910 left.walk_mut(f);
911 right.walk_mut(f);
912 }
913 Expr::CompiledMath(_) => {}
914 Expr::Not(inner) => inner.walk_mut(f),
915 }
916 }
917}
918
919#[derive(Debug, Clone, Eq, PartialEq)]
920pub enum WorkspaceTarget {
921 Snapshot,
922 Local,
923 Cache { local: bool },
924 System,
925}
926
927pub trait EnvLookup {
928 fn get_env(&self, key: &str) -> Option<&str>;
929}
930
931impl EnvLookup for HashMap<String, String> {
932 fn get_env(&self, key: &str) -> Option<&str> {
933 self.get(key).map(|s| s.as_str())
934 }
935}
936
937impl EnvLookup for Arc<HashMap<String, String>> {
938 fn get_env(&self, key: &str) -> Option<&str> {
939 (**self).get_env(key)
940 }
941}
942
943pub fn guard_allows(guard: &Guard, env: &impl EnvLookup) -> bool {
944 let Guard::Attr { ns, key, val } = guard;
945 match ns {
946 Ns::Os => match val.as_deref() {
947 Some("macos") => platform_is_macos(),
948 Some("linux") => platform_is_linux(),
949 Some("windows") => platform_is_windows(),
950 _ => false,
951 },
952 Ns::Arch => match val.as_deref() {
953 Some(want) => ARCH_TARGET == want,
954 None => false,
955 },
956 Ns::Bool => val
957 .as_deref()
958 .map(|v| v.parse::<bool>().unwrap_or(false))
959 .unwrap_or(false),
960 Ns::Env => match key.as_deref() {
961 Some(var) => match val {
962 None => env.get_env(var).map(|v| !v.is_empty()).unwrap_or(false),
963 Some(want) => env
964 .get_env(var)
965 .map(|v| v == want.as_str())
966 .unwrap_or(false),
967 },
968 None => false,
970 },
971 }
972}
973
974#[allow(clippy::disallowed_macros)]
977fn platform_is_windows() -> bool {
978 cfg!(windows)
979}
980
981#[allow(clippy::disallowed_macros)]
983fn platform_is_macos() -> bool {
984 cfg!(target_os = "macos")
985}
986
987#[allow(clippy::disallowed_macros)]
989fn platform_is_linux() -> bool {
990 cfg!(target_os = "linux")
991}
992
993const ARCH_TARGET: &str = std::env::consts::ARCH;
996
997pub fn guard_expr_allows(expr: &GuardExpr, env: &impl EnvLookup) -> bool {
998 match expr {
999 GuardExpr::Predicate(guard) => guard_allows(guard, env),
1000 GuardExpr::All(children) => children.iter().all(|g| guard_expr_allows(g, env)),
1001 GuardExpr::Or(children) => children.iter().any(|g| guard_expr_allows(g, env)),
1002 GuardExpr::Not(child) => !guard_expr_allows(child, env),
1003 }
1004}
1005
1006pub fn guard_option_allows(expr: Option<&GuardExpr>, env: &impl EnvLookup) -> bool {
1007 match expr {
1008 Some(e) => guard_expr_allows(e, env),
1009 None => true,
1010 }
1011}
1012
1013impl Guard {
1014 pub fn is_disjoint_from(&self, other: &Self) -> bool {
1023 match (self, other) {
1024 (
1025 Guard::Attr {
1026 ns: n1,
1027 key: k1,
1028 val: Some(v1),
1029 },
1030 Guard::Attr {
1031 ns: n2,
1032 key: k2,
1033 val: Some(v2),
1034 },
1035 ) => n1 == n2 && k1 == k2 && v1 != v2,
1036 _ => false,
1037 }
1038 }
1039}
1040
1041impl GuardExpr {
1042 pub fn is_disjoint_from(&self, other: &Self) -> bool {
1048 match (self, other) {
1049 (x, GuardExpr::Not(inner)) | (GuardExpr::Not(inner), x) => {
1057 x == inner.as_ref() || unset_excludes(x, inner.as_ref())
1058 }
1059 (GuardExpr::Predicate(p1), GuardExpr::Predicate(p2)) => p1.is_disjoint_from(p2),
1061 (GuardExpr::Or(arms), other) | (other, GuardExpr::Or(arms)) => {
1063 arms.iter().all(|arm| arm.is_disjoint_from(other))
1064 }
1065 (GuardExpr::All(arms), other) | (other, GuardExpr::All(arms)) => {
1067 arms.iter().any(|arm| arm.is_disjoint_from(other))
1068 }
1069 }
1070 }
1071}
1072
1073fn conjuncts(expr: &GuardExpr) -> Vec<&GuardExpr> {
1077 match expr {
1078 GuardExpr::All(items) => items.iter().collect(),
1079 single => vec![single],
1080 }
1081}
1082
1083fn closed_domain_values(ns: Ns, key: Option<&str>) -> Option<&'static [&'static str]> {
1090 match (ns, key) {
1091 (Ns::Bool, None) => Some(&["true", "false"]),
1092 (Ns::Os, None) => Some(&["macos", "linux", "windows"]),
1093 (Ns::Arch, None) => Some(ARCH_VALUES),
1094 _ => None,
1095 }
1096}
1097
1098#[derive(Clone)]
1101enum DnfLit {
1102 Pos(Guard),
1103 Neg(Guard),
1104}
1105
1106impl DnfLit {
1107 fn as_expr(&self) -> GuardExpr {
1108 match self {
1109 DnfLit::Pos(guard) => GuardExpr::Predicate(guard.clone()),
1110 DnfLit::Neg(guard) => GuardExpr::Not(Box::new(GuardExpr::Predicate(guard.clone()))),
1111 }
1112 }
1113}
1114
1115const MAX_DNF_DISJUNCTS: usize = 64;
1120
1121fn dnf_push(expr: &GuardExpr, polarity: bool, out: &mut Vec<Vec<DnfLit>>) -> bool {
1126 match (expr, polarity) {
1127 (GuardExpr::Predicate(guard), true) => {
1128 for disjunct in out.iter_mut() {
1129 disjunct.push(DnfLit::Pos(guard.clone()));
1130 }
1131 true
1132 }
1133 (GuardExpr::Predicate(guard), false) => {
1134 for disjunct in out.iter_mut() {
1135 disjunct.push(DnfLit::Neg(guard.clone()));
1136 }
1137 true
1138 }
1139 (GuardExpr::All(children), true) | (GuardExpr::Or(children), false) => {
1140 for child in children {
1142 if !dnf_push(child, polarity, out) {
1143 return false;
1144 }
1145 }
1146 true
1147 }
1148 (GuardExpr::Or(children), true) | (GuardExpr::All(children), false) => {
1149 let mut forked = Vec::new();
1151 for disjunct in out.drain(..) {
1152 for child in children {
1153 let mut branch = vec![disjunct.clone()];
1154 if !dnf_push(child, polarity, &mut branch) {
1155 return false;
1156 }
1157 forked.extend(branch);
1158 if forked.len() > MAX_DNF_DISJUNCTS {
1159 return false;
1160 }
1161 }
1162 }
1163 *out = forked;
1164 true
1165 }
1166 (GuardExpr::Not(inner), _) => dnf_push(inner, !polarity, out),
1167 }
1168}
1169
1170fn disjunct_satisfiable(lits: &[DnfLit]) -> bool {
1174 for lit in lits {
1178 match lit {
1179 DnfLit::Pos(Guard::Attr {
1180 ns: Ns::Bool, val, ..
1181 }) if val.as_deref() != Some("true") => return false,
1182 DnfLit::Neg(Guard::Attr {
1183 ns: Ns::Bool,
1184 key: None,
1185 val: Some(value),
1186 }) if value == "true" => return false,
1187 _ => {}
1188 }
1189 }
1190 for (index, first) in lits.iter().enumerate() {
1193 for second in &lits[index + 1..] {
1194 if first.as_expr().is_disjoint_from(&second.as_expr()) {
1195 return false;
1196 }
1197 }
1198 }
1199 for lit in lits {
1203 let (ns, key) = match lit {
1204 DnfLit::Neg(Guard::Attr {
1205 ns,
1206 key,
1207 val: Some(_),
1208 }) => (*ns, key.as_deref()),
1209 _ => continue,
1210 };
1211 let Some(domain) = closed_domain_values(ns, key) else {
1212 continue;
1213 };
1214 let exhausted = domain.iter().all(|value| {
1215 lits.iter().any(|other| match other {
1216 DnfLit::Neg(Guard::Attr {
1217 ns: other_ns,
1218 key: other_key,
1219 val: Some(other_val),
1220 }) => *other_ns == ns && other_key.as_deref() == key && other_val == value,
1221 _ => false,
1222 })
1223 });
1224 if exhausted {
1225 return false;
1226 }
1227 }
1228 true
1229}
1230
1231fn conjunction_dead(atoms: &[&GuardExpr]) -> bool {
1238 if atoms.is_empty() {
1239 return false;
1240 }
1241 let mut disjuncts = vec![Vec::new()];
1242 for atom in atoms {
1243 if !dnf_push(atom, true, &mut disjuncts) {
1244 return false;
1245 }
1246 }
1247 !disjuncts
1248 .iter()
1249 .any(|disjunct| disjunct_satisfiable(disjunct))
1250}
1251
1252pub fn guard_satisfiable(expr: &GuardExpr) -> bool {
1254 !conjunction_dead(&conjuncts(expr))
1255}
1256
1257pub fn guard_valid(expr: &GuardExpr) -> bool {
1260 match expr {
1261 GuardExpr::Predicate(Guard::Attr {
1262 ns: Ns::Bool,
1263 val: Some(value),
1264 ..
1265 }) => value.as_str() == "true",
1266 GuardExpr::All(items) => items.iter().all(guard_valid),
1267 GuardExpr::Not(inner) => !guard_satisfiable(inner),
1268 _ => false,
1269 }
1270}
1271
1272pub fn guards_overlap(a: Option<&GuardExpr>, b: Option<&GuardExpr>) -> bool {
1275 match (a, b) {
1276 (None, None) => true,
1277 (Some(x), None) | (None, Some(x)) => guard_satisfiable(x),
1278 (Some(x), Some(y)) => {
1279 let mut atoms = conjuncts(x);
1280 atoms.extend(conjuncts(y));
1281 !conjunction_dead(&atoms)
1282 }
1283 }
1284}
1285
1286fn unset_excludes(x: &GuardExpr, inner: &GuardExpr) -> bool {
1289 match (x, inner) {
1290 (
1291 GuardExpr::Predicate(Guard::Attr {
1292 ns: n2, key: k2, ..
1293 }),
1294 GuardExpr::Predicate(Guard::Attr {
1295 ns: n1,
1296 key: k1,
1297 val: None,
1298 }),
1299 ) => n1 == n2 && k1 == k2,
1300 _ => false,
1301 }
1302}
1303
1304impl fmt::Display for Guard {
1305 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1311 match self {
1312 Guard::Attr {
1313 ns: Ns::Env,
1314 key: Some(var),
1315 val: None,
1316 } => write!(f, "env:{var}"),
1317 Guard::Attr {
1318 ns: Ns::Env,
1319 key: Some(var),
1320 val: Some(want),
1321 } => write!(f, "eq(env:{var}, {want})"),
1322 Guard::Attr {
1323 ns,
1324 key: _,
1325 val: Some(value),
1326 } => write!(f, "{ns}:{value}"),
1327 Guard::Attr { ns, key, val: None } => match key {
1328 Some(subject) => write!(f, "{ns}:{subject}"),
1329 None => write!(f, "{ns}"),
1330 },
1331 }
1332 }
1333}
1334
1335impl fmt::Display for WorkspaceTarget {
1336 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1337 match self {
1338 WorkspaceTarget::Snapshot => write!(f, "SNAPSHOT"),
1339 WorkspaceTarget::Local => write!(f, "LOCAL"),
1340 WorkspaceTarget::Cache { local: false } => write!(f, "CACHE"),
1341 WorkspaceTarget::Cache { local: true } => write!(f, "CACHE --local"),
1342 WorkspaceTarget::System => write!(f, "SYSTEM"),
1343 }
1344 }
1345}
1346
1347impl fmt::Display for Expr {
1348 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1349 match self {
1350 Expr::Literal(v) => write!(f, "{}", v),
1351 Expr::Var { name } => {
1352 write!(f, "{VAR_SIGIL}{}", name)
1353 }
1354 Expr::ConstRef { alias, name, keys } => {
1355 write!(f, "{}", sigil_qualified(alias, name))?;
1356 for key in keys {
1357 write!(f, "{KEY_PATH_SEPARATOR}{key}")?;
1358 }
1359 Ok(())
1360 }
1361 Expr::Env(key) => write!(f, "env:{}", key),
1362 Expr::KeyPath { base, keys } => {
1363 write!(f, "{VAR_SIGIL}{}", base)?;
1364 for key in keys {
1365 write!(f, "{KEY_PATH_SEPARATOR}{key}")?;
1366 }
1367 Ok(())
1368 }
1369 Expr::Call { name, args } => {
1370 write!(f, "{}(", name)?;
1371 for (i, arg) in args.iter().enumerate() {
1372 if i > 0 {
1373 write!(f, ", ")?;
1374 }
1375 write!(f, "{}", arg)?;
1376 }
1377 write!(f, ")")
1378 }
1379 Expr::Inspect { name } => {
1380 write!(f, "{KEYWORD_INSPECT}(${})", name)
1381 }
1382 Expr::List(items) => {
1383 write!(f, "[")?;
1384 for (i, item) in items.iter().enumerate() {
1385 if i > 0 {
1386 write!(f, ", ")?;
1387 }
1388 write!(f, "{}", item)?;
1389 }
1390 write!(f, "]")
1391 }
1392 Expr::Map(entries) => {
1393 write!(f, "{{")?;
1394 for (i, (key, val)) in entries.iter().enumerate() {
1395 if i > 0 {
1396 write!(f, ", ")?;
1397 }
1398 write!(f, "\"{}\": {}", key, val)?;
1399 }
1400 write!(f, "}}")
1401 }
1402 Expr::Block(steps) => {
1403 write!(f, "{{ ")?;
1404 for (i, step) in steps.iter().enumerate() {
1405 if i > 0 {
1406 write!(f, "; ")?;
1407 }
1408 write!(f, "{}", step.kind)?;
1409 }
1410 write!(f, " }}")
1411 }
1412 Expr::Compare { op, left, right } => {
1413 write!(f, "({} {} {})", left, op, right)
1417 }
1418 Expr::Arithmetic { op, left, right } => {
1419 write!(f, "({} {} {})", left, op, right)
1420 }
1421 Expr::CompiledMath(ops) => {
1422 write!(f, "{}", format_compiled_math(ops))
1423 }
1424 Expr::FreshPipe => write!(f, "<fresh pipe>"),
1428 Expr::UnsignedIntBoundary(n) => write!(f, "{}", n),
1429 Expr::Not(inner) => {
1430 match inner.as_ref() {
1433 Expr::Compare { .. } | Expr::Arithmetic { .. } | Expr::CompiledMath(_) => {
1434 write!(f, "!({})", inner)
1435 }
1436 _ => write!(f, "!{}", inner),
1437 }
1438 }
1439 Expr::Logical { op, left, right } => {
1440 write!(f, "({} {} {})", left, op, right)
1441 }
1442 }
1443 }
1444}
1445
1446impl fmt::Display for CompareOp {
1447 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1448 match self {
1449 CompareOp::Eq => write!(f, "=="),
1450 CompareOp::Ne => write!(f, "!="),
1451 CompareOp::Lt => write!(f, "<"),
1452 CompareOp::Le => write!(f, "<="),
1453 CompareOp::Gt => write!(f, ">"),
1454 CompareOp::Ge => write!(f, ">="),
1455 }
1456 }
1457}
1458
1459impl fmt::Display for ArithOp {
1460 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1461 match self {
1462 ArithOp::Add => write!(f, "+"),
1463 ArithOp::Sub => write!(f, "-"),
1464 ArithOp::Mul => write!(f, "*"),
1465 ArithOp::Div => write!(f, "/"),
1466 }
1467 }
1468}
1469
1470fn format_compiled_math(ops: &[MathOp]) -> String {
1475 let mut stack: Vec<String> = Vec::new();
1476 for op in ops {
1477 match op {
1478 MathOp::PushConst(v) => stack.push(format!("{}", v)),
1479 MathOp::Load { name } => {
1480 stack.push(format!("{VAR_SIGIL}{}", name));
1481 }
1482 MathOp::LoadConstRef { alias, name, keys } => {
1483 let mut s = sigil_qualified(alias, name);
1484 for key in keys {
1485 s.push(KEY_PATH_SEPARATOR_CHAR);
1486 s.push_str(key);
1487 }
1488 stack.push(s)
1489 }
1490 MathOp::LoadEnv(key) => stack.push(format!("env:{}", key)),
1491 MathOp::LoadKeyPath { base, keys } => {
1492 let mut s = format!("{VAR_SIGIL}{}", base);
1493 for key in keys {
1494 s.push(KEY_PATH_SEPARATOR_CHAR);
1495 s.push_str(key);
1496 }
1497 stack.push(s);
1498 }
1499 MathOp::Call { name, arity } => {
1500 let mut args = Vec::new();
1501 for _ in 0..*arity {
1502 args.push(stack.pop().unwrap_or_else(|| "<underflow>".to_string()));
1503 }
1504 args.reverse();
1505 stack.push(format!("{}({})", name, args.join(", ")));
1506 }
1507 MathOp::Inspect { name } => {
1508 stack.push(format!("{KEYWORD_INSPECT}({VAR_SIGIL}{})", name));
1509 }
1510 MathOp::Neg => {
1511 let inner = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1512 stack.push(format!("(-{})", inner));
1513 }
1514 MathOp::Add => push_bin(&mut stack, "+"),
1515 MathOp::Sub => push_bin(&mut stack, "-"),
1516 MathOp::Mul => push_bin(&mut stack, "*"),
1517 MathOp::Div => push_bin(&mut stack, "/"),
1518 MathOp::Lt => push_bin(&mut stack, "<"),
1519 MathOp::Le => push_bin(&mut stack, "<="),
1520 MathOp::Gt => push_bin(&mut stack, ">"),
1521 MathOp::Ge => push_bin(&mut stack, ">="),
1522 MathOp::Eq => push_bin(&mut stack, "=="),
1523 MathOp::Ne => push_bin(&mut stack, "!="),
1524 }
1525 }
1526 if stack.len() == 1 {
1527 let mut items = stack;
1528 items.pop().unwrap_or_else(|| "<empty>".to_string())
1529 } else {
1530 stack.join(" ")
1531 }
1532}
1533
1534fn push_bin(stack: &mut Vec<String>, op: &str) {
1535 let right = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1536 let left = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1537 stack.push(format!("({} {} {})", left, op, right));
1538}
1539
1540impl fmt::Display for LogicalOp {
1541 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1542 match self {
1543 LogicalOp::And => write!(f, "&&"),
1544 LogicalOp::Or => write!(f, "||"),
1545 }
1546 }
1547}
1548
1549enum GuardDisplayContext {
1550 Root,
1551 InAnyArg,
1552 InNot,
1553 InAll,
1554}
1555
1556impl GuardExpr {
1557 fn fmt_with_ctx(&self, f: &mut fmt::Formatter<'_>, ctx: GuardDisplayContext) -> fmt::Result {
1558 match self {
1559 GuardExpr::Predicate(guard) => write!(f, "{}", guard),
1560 GuardExpr::All(children) => {
1561 let wrap = matches!(
1562 ctx,
1563 GuardDisplayContext::InAnyArg | GuardDisplayContext::InNot
1564 ) && children.len() > 1;
1565 if wrap {
1566 write!(f, "(")?;
1567 }
1568 for (i, child) in children.iter().enumerate() {
1569 if i > 0 {
1570 write!(f, ", ")?;
1571 }
1572 child.fmt_with_ctx(f, GuardDisplayContext::InAll)?;
1573 }
1574 if wrap {
1575 write!(f, ")")?;
1576 }
1577 Ok(())
1578 }
1579 GuardExpr::Or(children) => {
1580 write!(f, "any(")?;
1581 for (i, child) in children.iter().enumerate() {
1582 if i > 0 {
1583 write!(f, ", ")?;
1584 }
1585 child.fmt_with_ctx(f, GuardDisplayContext::InAnyArg)?;
1586 }
1587 write!(f, ")")
1588 }
1589 GuardExpr::Not(child) => {
1590 write!(f, "not(")?;
1591 child.fmt_with_ctx(f, GuardDisplayContext::InNot)?;
1592 write!(f, ")")
1593 }
1594 }
1595 }
1596}
1597
1598impl fmt::Display for GuardExpr {
1599 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1600 self.fmt_with_ctx(f, GuardDisplayContext::Root)
1601 }
1602}
1603
1604impl fmt::Display for Step {
1605 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1606 if let Some(expr) = &self.guard {
1607 write!(f, "[{}] ", expr)?;
1608 }
1609 write!(f, "{}", self.kind)
1610 }
1611}
1612
1613#[cfg(test)]
1614mod tests {
1615 use super::*;
1616 #[test]
1624 fn statement_keywords_match_backend() {
1625 for kw in STRUCTURAL_KEYWORDS {
1633 let via_backend = crate::parse_script(kw, crate::commands::lower_command);
1634 let via_lowering =
1635 crate::commands::lower_command(kw, Vec::new()).map(|kind| crate::Step {
1636 guard: None,
1637 kind,
1638 scope_enter: 0,
1639 scope_exit: 0,
1640 line: 0,
1641 col: 0,
1642 });
1643 match (via_backend, via_lowering) {
1644 (Ok(_), _) => {}
1645 (Err(a), Err(b)) => {
1646 assert_eq!(
1647 a.kind(),
1648 b.kind(),
1649 "backend kind drift for bare keyword {kw}: {a} vs {b}"
1650 );
1651 }
1652 (Err(a), Ok(_)) => {
1653 panic!("backend rejects bare keyword {kw} that lowering accepts: {a}")
1654 }
1655 }
1656 }
1657 for head in [
1661 "LET",
1662 "CONST",
1663 "RETURN",
1664 "BREAK",
1665 "CONTINUE",
1666 "IF",
1667 "FOR",
1668 "WHILE",
1669 "FUNC",
1670 "REMOTE",
1671 "INHERIT_ENV",
1672 "WITH_IO",
1673 "ASYNC",
1674 "TIMEOUT",
1675 "ISOLATED",
1676 "AWAIT",
1677 "CANCEL",
1678 "RUN",
1679 "IMPORT",
1680 "EXPORT",
1681 "TYPE",
1682 ] {
1683 assert!(
1684 STRUCTURAL_KEYWORDS.contains(&head)
1685 || crate::all_metadata().iter().any(|m| m.name == head),
1686 "structural head {head} is not registered"
1687 );
1688 }
1689 }
1690
1691 #[test]
1695 fn command_names_group_by_category() {
1696 for command in COMMANDS {
1697 let name = command.as_str();
1698 let Some((prefix, _)) = name.split_once('_') else {
1699 continue;
1700 };
1701 assert!(
1702 COMMAND_CATEGORIES.contains(&prefix),
1703 "command {name} introduces unregistered category {prefix}; add it to COMMAND_CATEGORIES"
1704 );
1705 }
1706 }
1707
1708 #[test]
1716 fn registry_commands_all_parse() {
1717 for meta in crate::all_metadata() {
1718 if !meta.in_index || STRUCTURAL_KEYWORDS.contains(&meta.name) {
1719 continue;
1720 }
1721 assert!(
1722 Command::parse(meta.name).is_some(),
1723 "registry command {} has no Command::parse arm",
1724 meta.name
1725 );
1726 }
1727 }
1728
1729 #[test]
1734 fn definition_spans_cover_type_and_func() {
1735 let alias = Step {
1736 guard: None,
1737 kind: StepKind::TypeAlias {
1738 name: "EMP".to_string(),
1739 target: "MAP<n: STRING>".to_string(),
1740 },
1741 scope_enter: 0,
1742 scope_exit: 0,
1743 line: 3,
1744 col: 5,
1745 };
1746 let (name, span) = alias.defined_symbol().expect("alias defines");
1747 assert_eq!(name, "EMP");
1748 assert_eq!(span.line, 3);
1749 assert_eq!(span.col_start, Some(5));
1750
1751 let func = Step {
1752 guard: None,
1753 kind: StepKind::FuncDef {
1754 name: "F".to_string(),
1755 params: Vec::new(),
1756 return_type: "VOID".to_string(),
1757 is_async: false,
1758 body: Vec::new(),
1759 docs: None,
1760 },
1761 scope_enter: 0,
1762 scope_exit: 0,
1763 line: 7,
1764 col: 1,
1765 };
1766 let (name, span) = func.defined_symbol().expect("func defines");
1767 assert_eq!(name, "F");
1768 assert_eq!(span.line, 7);
1769
1770 let plain = Step {
1771 guard: None,
1772 kind: StepKind::Break,
1773 scope_enter: 0,
1774 scope_exit: 0,
1775 line: 9,
1776 col: 1,
1777 };
1778 assert!(plain.defined_symbol().is_none());
1779
1780 let unknown = Step {
1781 guard: None,
1782 kind: StepKind::Break,
1783 scope_enter: 0,
1784 scope_exit: 0,
1785 line: 0,
1786 col: 0,
1787 };
1788 assert_eq!(unknown.span().line, 0);
1789 }
1790
1791 #[test]
1795 fn parsed_definitions_carry_spans() {
1796 let steps = crate::parse_script(
1797 indoc::indoc! {r#"
1798 TYPE EMP = MAP<n: STRING>
1799 FUNC F(): VOID {
1800 RETURN
1801 }
1802 "#},
1803 crate::commands::lower_command,
1804 )
1805 .expect("definitions parse");
1806 let mut names: Vec<(&str, usize)> = steps
1807 .iter()
1808 .filter_map(|s| s.defined_symbol().map(|(n, span)| (n, span.line)))
1809 .collect();
1810 names.sort();
1811 assert_eq!(names, vec![("EMP", 1), ("F", 2)]);
1812 }
1813}
1814
1815#[cfg(test)]
1816mod guard_analysis_tests {
1817 use super::*;
1818
1819 fn attr(ns: Ns, key: Option<&str>, val: Option<&str>) -> GuardExpr {
1820 GuardExpr::Predicate(Guard::Attr {
1821 ns,
1822 key: key.map(str::to_string),
1823 val: val.map(str::to_string),
1824 })
1825 }
1826
1827 fn os(value: &str) -> GuardExpr {
1828 attr(Ns::Os, None, Some(value))
1829 }
1830
1831 fn arch(value: &str) -> GuardExpr {
1832 attr(Ns::Arch, None, Some(value))
1833 }
1834
1835 fn unix() -> GuardExpr {
1838 GuardExpr::Or(vec![os("macos"), os("linux")])
1839 }
1840
1841 fn windows() -> GuardExpr {
1842 os("windows")
1843 }
1844
1845 fn env_eq(var: &str, value: &str) -> GuardExpr {
1846 attr(Ns::Env, Some(var), Some(value))
1847 }
1848
1849 fn not(expr: GuardExpr) -> GuardExpr {
1850 GuardExpr::Not(Box::new(expr))
1851 }
1852
1853 #[test]
1857 fn partition_negations_are_jointly_dead() {
1858 let os_exhausted = GuardExpr::All(vec![not(os("macos")), not(os("linux")), not(windows())]);
1859 assert!(
1860 !guard_satisfiable(&os_exhausted),
1861 "no host is outside `macos`/`linux`/`windows`"
1862 );
1863 let os_partial = GuardExpr::All(vec![not(os("macos")), not(os("linux"))]);
1865 assert!(guard_satisfiable(&os_partial), "`windows` is still open");
1866 let bool_exhausted = GuardExpr::All(vec![
1868 not(attr(Ns::Bool, None, Some("true"))),
1869 not(attr(Ns::Bool, None, Some("false"))),
1870 ]);
1871 assert!(!guard_satisfiable(&bool_exhausted));
1872 let env_open = GuardExpr::All(vec![
1874 not(env_eq("MODE", "dev")),
1875 not(env_eq("MODE", "prod")),
1876 ]);
1877 assert!(guard_satisfiable(&env_open), "MODE may hold a third value");
1878 assert!(guard_satisfiable(¬(unix())));
1880 }
1881
1882 #[test]
1885 fn unix_alias_is_os_disjunction() {
1886 assert!(!guards_overlap(Some(&unix()), Some(&windows())));
1887 assert!(guards_overlap(Some(&unix()), Some(&os("macos"))));
1888 let covered = GuardExpr::All(vec![GuardExpr::Not(Box::new(unix())), not(windows())]);
1891 assert!(!guard_satisfiable(&covered));
1892 }
1893
1894 #[test]
1898 fn arch_guards_decide_by_value() {
1899 assert!(!guards_overlap(
1900 Some(&arch("x86_64")),
1901 Some(&arch("aarch64"))
1902 ));
1903 assert!(guards_overlap(Some(&arch("x86_64")), Some(&arch("x86_64"))));
1904 assert!(guards_overlap(Some(&arch("aarch64")), Some(&os("macos"))));
1905 let exhausted = GuardExpr::All(ARCH_VALUES.iter().map(|value| not(arch(value))).collect());
1906 assert!(!guard_satisfiable(&exhausted));
1907 let host = attr(Ns::Arch, None, Some(ARCH_TARGET));
1909 assert!(guard_expr_allows(&host, &HashMap::new()));
1910 }
1911
1912 #[test]
1916 fn platform_overlap_matrix_is_exhaustive() {
1917 let cases = [
1918 ("macos", "macos", true),
1919 ("macos", "linux", false),
1920 ("macos", "windows", false),
1921 ("linux", "linux", true),
1922 ("linux", "windows", false),
1923 ("windows", "windows", true),
1924 ];
1925 for (v1, v2, expected) in cases {
1926 let left = os(v1);
1927 let right = os(v2);
1928 assert_eq!(
1929 guards_overlap(Some(&left), Some(&right)),
1930 expected,
1931 "os:{v1} vs os:{v2}"
1932 );
1933 }
1934 }
1935
1936 #[test]
1939 fn disjoint_pairs_never_cofire_here() {
1940 let macos = os("macos");
1941 let holds = |expr: &GuardExpr| guard_expr_allows(expr, &HashMap::new());
1942 assert!(
1943 !(holds(&macos) && holds(&windows())),
1944 "os:macos and os:windows co-fired"
1945 );
1946 }
1947
1948 #[test]
1949 fn overlap_follows_namespace_semantics() {
1950 assert!(!guards_overlap(Some(&windows()), Some(&unix())));
1952 assert!(!guards_overlap(Some(&os("macos")), Some(&os("linux"))));
1953 assert!(guards_overlap(None, Some(&windows())));
1955 assert!(guards_overlap(None, None));
1956 let dead = GuardExpr::All(vec![os("macos"), windows()]);
1958 assert!(!guard_satisfiable(&dead));
1959 assert!(!guards_overlap(Some(&dead), Some(&os("macos"))));
1960 assert!(guard_valid(&GuardExpr::Predicate(Guard::Attr {
1961 ns: Ns::Bool,
1962 key: None,
1963 val: Some("true".to_string()),
1964 })));
1965 assert!(!guard_valid(&unix()));
1966 }
1967
1968 #[test]
1969 fn env_value_conflicts_decide_without_enumeration() {
1970 let fast = env_eq("MODE", "fast");
1971 let slow = env_eq("MODE", "slow");
1972 assert!(
1973 !guards_overlap(Some(&fast), Some(&slow)),
1974 "same key distinct values are disjoint"
1975 );
1976 let also_fast = env_eq("MODE", "fast");
1977 assert!(guards_overlap(Some(&fast), Some(&also_fast)));
1978 let bare = attr(Ns::Env, Some("MODE"), None);
1980 assert!(guards_overlap(Some(&bare), Some(&fast)));
1981 }
1982}
1983
1984#[cfg(test)]
1985mod guard_algebra_tests {
1986 use super::*;
1987
1988 fn os(value: &str) -> GuardExpr {
1989 GuardExpr::Predicate(Guard::Attr {
1990 ns: Ns::Os,
1991 key: None,
1992 val: Some(value.to_string()),
1993 })
1994 }
1995
1996 #[test]
1997 fn or_distributes_over_disjointness() {
1998 fn env_eq(var: &str, value: &str) -> GuardExpr {
1999 GuardExpr::Predicate(Guard::Attr {
2000 ns: Ns::Env,
2001 key: Some(var.to_string()),
2002 val: Some(value.to_string()),
2003 })
2004 }
2005 let mixed = GuardExpr::Or(vec![env_eq("MODE", "dev"), env_eq("MODE", "prod")]);
2008 assert!(!mixed.is_disjoint_from(&env_eq("MODE", "dev")));
2009 assert!(mixed.is_disjoint_from(&env_eq("MODE", "test")));
2011 let cross = GuardExpr::Or(vec![env_eq("MODE", "dev")]);
2013 let platform = os("windows");
2014 assert!(!cross.is_disjoint_from(&platform));
2015 }
2016
2017 #[test]
2018 fn all_distributes_over_disjointness() {
2019 let stacked = GuardExpr::All(vec![
2020 os("macos"),
2021 GuardExpr::Or(vec![os("macos"), os("linux")]),
2022 os("windows"),
2023 ]);
2024 assert!(stacked.is_disjoint_from(&os("macos")));
2025 let live = GuardExpr::All(vec![
2028 os("macos"),
2029 GuardExpr::Predicate(Guard::Attr {
2030 ns: Ns::Env,
2031 key: Some("MODE".to_string()),
2032 val: Some("dev".to_string()),
2033 }),
2034 ]);
2035 assert!(!live.is_disjoint_from(&os("macos")));
2036 }
2037
2038 #[test]
2039 fn negation_is_structural_not_syntactic() {
2040 let not_win = GuardExpr::Not(Box::new(os("windows")));
2041 assert!(not_win.is_disjoint_from(&os("windows")));
2042 assert!(os("windows").is_disjoint_from(¬_win));
2043 assert!(!not_win.is_disjoint_from(&os("macos")));
2044 }
2045}