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
580#[derive(Debug, Clone, Eq, PartialEq)]
581pub struct IoBinding {
582 pub stream: IoStream,
583 pub pipe: Option<PipeTarget>,
584}
585
586#[derive(Debug, Clone, Eq, PartialEq)]
589pub enum PipeTarget {
590 Var { name: String },
591}
592
593pub use crate::value::{
597 OxDockType, SemaphoreState, TypeDescriptor, Value, ValuePayload, clone_boxed, clone_copy,
598 clone_shared, drop_boxed, drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared, fmt_boxed,
599 fmt_inline, fmt_shared, load_inline, startup_descriptors, store_inline, type_anchor,
600 unshare_boxed, unshare_inline, unshare_shared,
601};
602
603#[derive(Debug, Clone, Copy, Eq, PartialEq)]
604pub enum CompareOp {
605 Eq,
606 Ne,
607 Lt,
608 Le,
609 Gt,
610 Ge,
611}
612
613#[derive(Debug, Clone, Copy, Eq, PartialEq)]
614pub enum ArithOp {
615 Add,
616 Sub,
617 Mul,
618 Div,
619}
620
621#[derive(Debug, Clone, PartialEq)]
630pub enum MathOp {
631 PushConst(Value),
632 Load { name: String },
633 LoadConstRef { alias: String, name: String },
634 LoadEnv(String),
635 LoadKeyPath { base: String, keys: Vec<String> },
636 Call { name: String, arity: usize },
637 Inspect { name: String },
638 Neg,
639 Add,
640 Sub,
641 Mul,
642 Div,
643 Lt,
644 Le,
645 Gt,
646 Ge,
647 Eq,
648 Ne,
649}
650
651#[derive(Debug, Clone, Copy, Eq, PartialEq)]
652pub enum LogicalOp {
653 And,
654 Or,
655}
656
657#[derive(Debug, Clone, PartialEq)]
658pub enum Expr {
659 Literal(Value),
660 Var {
665 name: String,
666 },
667 ConstRef {
673 alias: String,
674 name: String,
675 },
676 Env(String),
679 KeyPath {
681 base: String,
682 keys: Vec<String>,
683 },
684 List(Vec<Expr>),
685 Map(Vec<(String, Expr)>),
686 Block(Vec<Step>),
691 Call {
692 name: String,
693 args: Vec<Expr>,
694 },
695 Inspect {
701 name: String,
702 },
703 Compare {
704 op: CompareOp,
705 left: Box<Expr>,
706 right: Box<Expr>,
707 },
708 Arithmetic {
709 op: ArithOp,
710 left: Box<Expr>,
711 right: Box<Expr>,
712 },
713 CompiledMath(Vec<MathOp>),
716 FreshPipe,
722 UnsignedIntBoundary(u64),
726 Not(Box<Expr>),
727 Logical {
728 op: LogicalOp,
729 left: Box<Expr>,
730 right: Box<Expr>,
731 },
732}
733
734#[derive(Debug, Clone)]
735pub struct Step {
736 pub guard: Option<GuardExpr>,
737 pub kind: StepKind,
738 pub scope_enter: usize,
739 pub scope_exit: usize,
740 pub line: usize,
747 pub col: usize,
751}
752
753impl PartialEq for Step {
754 fn eq(&self, other: &Self) -> bool {
755 self.guard == other.guard
756 && self.kind == other.kind
757 && self.scope_enter == other.scope_enter
758 && self.scope_exit == other.scope_exit
759 }
760}
761
762impl Eq for Step {}
763
764impl Step {
765 pub fn span(&self) -> Span {
770 if self.line == 0 {
771 return Span::default();
772 }
773 if self.col == 0 {
774 return Span::line_only(self.line);
775 }
776 Span::line_col(self.line, self.col)
777 }
778
779 pub fn defined_symbol(&self) -> Option<(&str, Span)> {
784 match &self.kind {
785 StepKind::TypeAlias { name, .. } => Some((name.as_str(), self.span())),
786 StepKind::FuncDef { name, .. } => Some((name.as_str(), self.span())),
787 _ => None,
788 }
789 }
790}
791
792impl Expr {
793 pub fn walk(&self, f: &mut impl FnMut(&Expr)) {
800 f(self);
801 match self {
802 Expr::Literal(_)
803 | Expr::Var { .. }
804 | Expr::ConstRef { .. }
805 | Expr::Env(_)
806 | Expr::KeyPath { .. }
807 | Expr::Inspect { .. }
808 | Expr::FreshPipe
809 | Expr::UnsignedIntBoundary(_) => {}
810 Expr::Call { args, .. } => {
811 for arg in args {
812 arg.walk(f);
813 }
814 }
815 Expr::List(items) => {
816 for item in items {
817 item.walk(f);
818 }
819 }
820 Expr::Map(entries) => {
821 for (_, value) in entries {
822 value.walk(f);
823 }
824 }
825 Expr::Block(steps) => {
826 for step in steps {
827 step.kind.walk_step_exprs(f);
828 }
829 }
830 Expr::Compare { left, right, .. }
831 | Expr::Arithmetic { left, right, .. }
832 | Expr::Logical { left, right, .. } => {
833 left.walk(f);
834 right.walk(f);
835 }
836 Expr::CompiledMath(_) => {}
837 Expr::Not(inner) => inner.walk(f),
838 }
839 }
840
841 pub fn walk_mut(&mut self, f: &mut impl FnMut(&mut Expr)) {
848 f(self);
849 match self {
850 Expr::Literal(_)
851 | Expr::Var { .. }
852 | Expr::ConstRef { .. }
853 | Expr::Env(_)
854 | Expr::KeyPath { .. }
855 | Expr::Inspect { .. }
856 | Expr::FreshPipe
857 | Expr::UnsignedIntBoundary(_) => {}
858 Expr::Call { args, .. } => {
859 for arg in args {
860 arg.walk_mut(f);
861 }
862 }
863 Expr::List(items) => {
864 for item in items {
865 item.walk_mut(f);
866 }
867 }
868 Expr::Map(entries) => {
869 for (_, value) in entries {
870 value.walk_mut(f);
871 }
872 }
873 Expr::Block(_) => {}
874 Expr::Compare { left, right, .. }
875 | Expr::Arithmetic { left, right, .. }
876 | Expr::Logical { left, right, .. } => {
877 left.walk_mut(f);
878 right.walk_mut(f);
879 }
880 Expr::CompiledMath(_) => {}
881 Expr::Not(inner) => inner.walk_mut(f),
882 }
883 }
884}
885
886#[derive(Debug, Clone, Eq, PartialEq)]
887pub enum WorkspaceTarget {
888 Snapshot,
889 Local,
890 Cache { local: bool },
891 System,
892}
893
894pub trait EnvLookup {
895 fn get_env(&self, key: &str) -> Option<&str>;
896}
897
898impl EnvLookup for HashMap<String, String> {
899 fn get_env(&self, key: &str) -> Option<&str> {
900 self.get(key).map(|s| s.as_str())
901 }
902}
903
904impl EnvLookup for Arc<HashMap<String, String>> {
905 fn get_env(&self, key: &str) -> Option<&str> {
906 (**self).get_env(key)
907 }
908}
909
910pub fn guard_allows(guard: &Guard, env: &impl EnvLookup) -> bool {
911 let Guard::Attr { ns, key, val } = guard;
912 match ns {
913 Ns::Os => match val.as_deref() {
914 Some("macos") => platform_is_macos(),
915 Some("linux") => platform_is_linux(),
916 Some("windows") => platform_is_windows(),
917 _ => false,
918 },
919 Ns::Arch => match val.as_deref() {
920 Some(want) => ARCH_TARGET == want,
921 None => false,
922 },
923 Ns::Bool => val
924 .as_deref()
925 .map(|v| v.parse::<bool>().unwrap_or(false))
926 .unwrap_or(false),
927 Ns::Env => match key.as_deref() {
928 Some(var) => match val {
929 None => env.get_env(var).map(|v| !v.is_empty()).unwrap_or(false),
930 Some(want) => env
931 .get_env(var)
932 .map(|v| v == want.as_str())
933 .unwrap_or(false),
934 },
935 None => false,
937 },
938 }
939}
940
941#[allow(clippy::disallowed_macros)]
944fn platform_is_windows() -> bool {
945 cfg!(windows)
946}
947
948#[allow(clippy::disallowed_macros)]
950fn platform_is_macos() -> bool {
951 cfg!(target_os = "macos")
952}
953
954#[allow(clippy::disallowed_macros)]
956fn platform_is_linux() -> bool {
957 cfg!(target_os = "linux")
958}
959
960const ARCH_TARGET: &str = std::env::consts::ARCH;
963
964pub fn guard_expr_allows(expr: &GuardExpr, env: &impl EnvLookup) -> bool {
965 match expr {
966 GuardExpr::Predicate(guard) => guard_allows(guard, env),
967 GuardExpr::All(children) => children.iter().all(|g| guard_expr_allows(g, env)),
968 GuardExpr::Or(children) => children.iter().any(|g| guard_expr_allows(g, env)),
969 GuardExpr::Not(child) => !guard_expr_allows(child, env),
970 }
971}
972
973pub fn guard_option_allows(expr: Option<&GuardExpr>, env: &impl EnvLookup) -> bool {
974 match expr {
975 Some(e) => guard_expr_allows(e, env),
976 None => true,
977 }
978}
979
980impl Guard {
981 pub fn is_disjoint_from(&self, other: &Self) -> bool {
990 match (self, other) {
991 (
992 Guard::Attr {
993 ns: n1,
994 key: k1,
995 val: Some(v1),
996 },
997 Guard::Attr {
998 ns: n2,
999 key: k2,
1000 val: Some(v2),
1001 },
1002 ) => n1 == n2 && k1 == k2 && v1 != v2,
1003 _ => false,
1004 }
1005 }
1006}
1007
1008impl GuardExpr {
1009 pub fn is_disjoint_from(&self, other: &Self) -> bool {
1015 match (self, other) {
1016 (x, GuardExpr::Not(inner)) | (GuardExpr::Not(inner), x) => {
1024 x == inner.as_ref() || unset_excludes(x, inner.as_ref())
1025 }
1026 (GuardExpr::Predicate(p1), GuardExpr::Predicate(p2)) => p1.is_disjoint_from(p2),
1028 (GuardExpr::Or(arms), other) | (other, GuardExpr::Or(arms)) => {
1030 arms.iter().all(|arm| arm.is_disjoint_from(other))
1031 }
1032 (GuardExpr::All(arms), other) | (other, GuardExpr::All(arms)) => {
1034 arms.iter().any(|arm| arm.is_disjoint_from(other))
1035 }
1036 }
1037 }
1038}
1039
1040fn conjuncts(expr: &GuardExpr) -> Vec<&GuardExpr> {
1044 match expr {
1045 GuardExpr::All(items) => items.iter().collect(),
1046 single => vec![single],
1047 }
1048}
1049
1050fn closed_domain_values(ns: Ns, key: Option<&str>) -> Option<&'static [&'static str]> {
1057 match (ns, key) {
1058 (Ns::Bool, None) => Some(&["true", "false"]),
1059 (Ns::Os, None) => Some(&["macos", "linux", "windows"]),
1060 (Ns::Arch, None) => Some(ARCH_VALUES),
1061 _ => None,
1062 }
1063}
1064
1065#[derive(Clone)]
1068enum DnfLit {
1069 Pos(Guard),
1070 Neg(Guard),
1071}
1072
1073impl DnfLit {
1074 fn as_expr(&self) -> GuardExpr {
1075 match self {
1076 DnfLit::Pos(guard) => GuardExpr::Predicate(guard.clone()),
1077 DnfLit::Neg(guard) => GuardExpr::Not(Box::new(GuardExpr::Predicate(guard.clone()))),
1078 }
1079 }
1080}
1081
1082const MAX_DNF_DISJUNCTS: usize = 64;
1087
1088fn dnf_push(expr: &GuardExpr, polarity: bool, out: &mut Vec<Vec<DnfLit>>) -> bool {
1093 match (expr, polarity) {
1094 (GuardExpr::Predicate(guard), true) => {
1095 for disjunct in out.iter_mut() {
1096 disjunct.push(DnfLit::Pos(guard.clone()));
1097 }
1098 true
1099 }
1100 (GuardExpr::Predicate(guard), false) => {
1101 for disjunct in out.iter_mut() {
1102 disjunct.push(DnfLit::Neg(guard.clone()));
1103 }
1104 true
1105 }
1106 (GuardExpr::All(children), true) | (GuardExpr::Or(children), false) => {
1107 for child in children {
1109 if !dnf_push(child, polarity, out) {
1110 return false;
1111 }
1112 }
1113 true
1114 }
1115 (GuardExpr::Or(children), true) | (GuardExpr::All(children), false) => {
1116 let mut forked = Vec::new();
1118 for disjunct in out.drain(..) {
1119 for child in children {
1120 let mut branch = vec![disjunct.clone()];
1121 if !dnf_push(child, polarity, &mut branch) {
1122 return false;
1123 }
1124 forked.extend(branch);
1125 if forked.len() > MAX_DNF_DISJUNCTS {
1126 return false;
1127 }
1128 }
1129 }
1130 *out = forked;
1131 true
1132 }
1133 (GuardExpr::Not(inner), _) => dnf_push(inner, !polarity, out),
1134 }
1135}
1136
1137fn disjunct_satisfiable(lits: &[DnfLit]) -> bool {
1141 for lit in lits {
1145 match lit {
1146 DnfLit::Pos(Guard::Attr {
1147 ns: Ns::Bool, val, ..
1148 }) if val.as_deref() != Some("true") => return false,
1149 DnfLit::Neg(Guard::Attr {
1150 ns: Ns::Bool,
1151 key: None,
1152 val: Some(value),
1153 }) if value == "true" => return false,
1154 _ => {}
1155 }
1156 }
1157 for (index, first) in lits.iter().enumerate() {
1160 for second in &lits[index + 1..] {
1161 if first.as_expr().is_disjoint_from(&second.as_expr()) {
1162 return false;
1163 }
1164 }
1165 }
1166 for lit in lits {
1170 let (ns, key) = match lit {
1171 DnfLit::Neg(Guard::Attr {
1172 ns,
1173 key,
1174 val: Some(_),
1175 }) => (*ns, key.as_deref()),
1176 _ => continue,
1177 };
1178 let Some(domain) = closed_domain_values(ns, key) else {
1179 continue;
1180 };
1181 let exhausted = domain.iter().all(|value| {
1182 lits.iter().any(|other| match other {
1183 DnfLit::Neg(Guard::Attr {
1184 ns: other_ns,
1185 key: other_key,
1186 val: Some(other_val),
1187 }) => *other_ns == ns && other_key.as_deref() == key && other_val == value,
1188 _ => false,
1189 })
1190 });
1191 if exhausted {
1192 return false;
1193 }
1194 }
1195 true
1196}
1197
1198fn conjunction_dead(atoms: &[&GuardExpr]) -> bool {
1205 if atoms.is_empty() {
1206 return false;
1207 }
1208 let mut disjuncts = vec![Vec::new()];
1209 for atom in atoms {
1210 if !dnf_push(atom, true, &mut disjuncts) {
1211 return false;
1212 }
1213 }
1214 !disjuncts
1215 .iter()
1216 .any(|disjunct| disjunct_satisfiable(disjunct))
1217}
1218
1219pub fn guard_satisfiable(expr: &GuardExpr) -> bool {
1221 !conjunction_dead(&conjuncts(expr))
1222}
1223
1224pub fn guard_valid(expr: &GuardExpr) -> bool {
1227 match expr {
1228 GuardExpr::Predicate(Guard::Attr {
1229 ns: Ns::Bool,
1230 val: Some(value),
1231 ..
1232 }) => value.as_str() == "true",
1233 GuardExpr::All(items) => items.iter().all(guard_valid),
1234 GuardExpr::Not(inner) => !guard_satisfiable(inner),
1235 _ => false,
1236 }
1237}
1238
1239pub fn guards_overlap(a: Option<&GuardExpr>, b: Option<&GuardExpr>) -> bool {
1242 match (a, b) {
1243 (None, None) => true,
1244 (Some(x), None) | (None, Some(x)) => guard_satisfiable(x),
1245 (Some(x), Some(y)) => {
1246 let mut atoms = conjuncts(x);
1247 atoms.extend(conjuncts(y));
1248 !conjunction_dead(&atoms)
1249 }
1250 }
1251}
1252
1253fn unset_excludes(x: &GuardExpr, inner: &GuardExpr) -> bool {
1256 match (x, inner) {
1257 (
1258 GuardExpr::Predicate(Guard::Attr {
1259 ns: n2, key: k2, ..
1260 }),
1261 GuardExpr::Predicate(Guard::Attr {
1262 ns: n1,
1263 key: k1,
1264 val: None,
1265 }),
1266 ) => n1 == n2 && k1 == k2,
1267 _ => false,
1268 }
1269}
1270
1271impl fmt::Display for Guard {
1272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1278 match self {
1279 Guard::Attr {
1280 ns: Ns::Env,
1281 key: Some(var),
1282 val: None,
1283 } => write!(f, "env:{var}"),
1284 Guard::Attr {
1285 ns: Ns::Env,
1286 key: Some(var),
1287 val: Some(want),
1288 } => write!(f, "eq(env:{var}, {want})"),
1289 Guard::Attr {
1290 ns,
1291 key: _,
1292 val: Some(value),
1293 } => write!(f, "{ns}:{value}"),
1294 Guard::Attr { ns, key, val: None } => match key {
1295 Some(subject) => write!(f, "{ns}:{subject}"),
1296 None => write!(f, "{ns}"),
1297 },
1298 }
1299 }
1300}
1301
1302impl fmt::Display for WorkspaceTarget {
1303 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1304 match self {
1305 WorkspaceTarget::Snapshot => write!(f, "SNAPSHOT"),
1306 WorkspaceTarget::Local => write!(f, "LOCAL"),
1307 WorkspaceTarget::Cache { local: false } => write!(f, "CACHE"),
1308 WorkspaceTarget::Cache { local: true } => write!(f, "CACHE --local"),
1309 WorkspaceTarget::System => write!(f, "SYSTEM"),
1310 }
1311 }
1312}
1313
1314impl fmt::Display for Expr {
1315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1316 match self {
1317 Expr::Literal(v) => write!(f, "{}", v),
1318 Expr::Var { name } => {
1319 write!(f, "{VAR_SIGIL}{}", name)
1320 }
1321 Expr::ConstRef { alias, name } => {
1322 write!(f, "{}", sigil_qualified(alias, name))
1323 }
1324 Expr::Env(key) => write!(f, "env:{}", key),
1325 Expr::KeyPath { base, keys } => {
1326 write!(f, "{VAR_SIGIL}{}", base)?;
1327 for key in keys {
1328 write!(f, ".{}", key)?;
1329 }
1330 Ok(())
1331 }
1332 Expr::Call { name, args } => {
1333 write!(f, "{}(", name)?;
1334 for (i, arg) in args.iter().enumerate() {
1335 if i > 0 {
1336 write!(f, ", ")?;
1337 }
1338 write!(f, "{}", arg)?;
1339 }
1340 write!(f, ")")
1341 }
1342 Expr::Inspect { name } => {
1343 write!(f, "{KEYWORD_INSPECT}(${})", name)
1344 }
1345 Expr::List(items) => {
1346 write!(f, "[")?;
1347 for (i, item) in items.iter().enumerate() {
1348 if i > 0 {
1349 write!(f, ", ")?;
1350 }
1351 write!(f, "{}", item)?;
1352 }
1353 write!(f, "]")
1354 }
1355 Expr::Map(entries) => {
1356 write!(f, "{{")?;
1357 for (i, (key, val)) in entries.iter().enumerate() {
1358 if i > 0 {
1359 write!(f, ", ")?;
1360 }
1361 write!(f, "\"{}\": {}", key, val)?;
1362 }
1363 write!(f, "}}")
1364 }
1365 Expr::Block(steps) => {
1366 write!(f, "{{ ")?;
1367 for (i, step) in steps.iter().enumerate() {
1368 if i > 0 {
1369 write!(f, "; ")?;
1370 }
1371 write!(f, "{}", step.kind)?;
1372 }
1373 write!(f, " }}")
1374 }
1375 Expr::Compare { op, left, right } => {
1376 write!(f, "({} {} {})", left, op, right)
1380 }
1381 Expr::Arithmetic { op, left, right } => {
1382 write!(f, "({} {} {})", left, op, right)
1383 }
1384 Expr::CompiledMath(ops) => {
1385 write!(f, "{}", format_compiled_math(ops))
1386 }
1387 Expr::FreshPipe => write!(f, "<fresh pipe>"),
1391 Expr::UnsignedIntBoundary(n) => write!(f, "{}", n),
1392 Expr::Not(inner) => {
1393 match inner.as_ref() {
1396 Expr::Compare { .. } | Expr::Arithmetic { .. } | Expr::CompiledMath(_) => {
1397 write!(f, "!({})", inner)
1398 }
1399 _ => write!(f, "!{}", inner),
1400 }
1401 }
1402 Expr::Logical { op, left, right } => {
1403 write!(f, "({} {} {})", left, op, right)
1404 }
1405 }
1406 }
1407}
1408
1409impl fmt::Display for CompareOp {
1410 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1411 match self {
1412 CompareOp::Eq => write!(f, "=="),
1413 CompareOp::Ne => write!(f, "!="),
1414 CompareOp::Lt => write!(f, "<"),
1415 CompareOp::Le => write!(f, "<="),
1416 CompareOp::Gt => write!(f, ">"),
1417 CompareOp::Ge => write!(f, ">="),
1418 }
1419 }
1420}
1421
1422impl fmt::Display for ArithOp {
1423 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1424 match self {
1425 ArithOp::Add => write!(f, "+"),
1426 ArithOp::Sub => write!(f, "-"),
1427 ArithOp::Mul => write!(f, "*"),
1428 ArithOp::Div => write!(f, "/"),
1429 }
1430 }
1431}
1432
1433fn format_compiled_math(ops: &[MathOp]) -> String {
1438 let mut stack: Vec<String> = Vec::new();
1439 for op in ops {
1440 match op {
1441 MathOp::PushConst(v) => stack.push(format!("{}", v)),
1442 MathOp::Load { name } => {
1443 stack.push(format!("{VAR_SIGIL}{}", name));
1444 }
1445 MathOp::LoadConstRef { alias, name } => stack.push(sigil_qualified(alias, name)),
1446 MathOp::LoadEnv(key) => stack.push(format!("env:{}", key)),
1447 MathOp::LoadKeyPath { base, keys } => {
1448 let mut s = format!("{VAR_SIGIL}{}", base);
1449 for key in keys {
1450 s.push('.');
1451 s.push_str(key);
1452 }
1453 stack.push(s);
1454 }
1455 MathOp::Call { name, arity } => {
1456 let mut args = Vec::new();
1457 for _ in 0..*arity {
1458 args.push(stack.pop().unwrap_or_else(|| "<underflow>".to_string()));
1459 }
1460 args.reverse();
1461 stack.push(format!("{}({})", name, args.join(", ")));
1462 }
1463 MathOp::Inspect { name } => {
1464 stack.push(format!("{KEYWORD_INSPECT}({VAR_SIGIL}{})", name));
1465 }
1466 MathOp::Neg => {
1467 let inner = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1468 stack.push(format!("(-{})", inner));
1469 }
1470 MathOp::Add => push_bin(&mut stack, "+"),
1471 MathOp::Sub => push_bin(&mut stack, "-"),
1472 MathOp::Mul => push_bin(&mut stack, "*"),
1473 MathOp::Div => push_bin(&mut stack, "/"),
1474 MathOp::Lt => push_bin(&mut stack, "<"),
1475 MathOp::Le => push_bin(&mut stack, "<="),
1476 MathOp::Gt => push_bin(&mut stack, ">"),
1477 MathOp::Ge => push_bin(&mut stack, ">="),
1478 MathOp::Eq => push_bin(&mut stack, "=="),
1479 MathOp::Ne => push_bin(&mut stack, "!="),
1480 }
1481 }
1482 if stack.len() == 1 {
1483 let mut items = stack;
1484 items.pop().unwrap_or_else(|| "<empty>".to_string())
1485 } else {
1486 stack.join(" ")
1487 }
1488}
1489
1490fn push_bin(stack: &mut Vec<String>, op: &str) {
1491 let right = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1492 let left = stack.pop().unwrap_or_else(|| "<underflow>".to_string());
1493 stack.push(format!("({} {} {})", left, op, right));
1494}
1495
1496impl fmt::Display for LogicalOp {
1497 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1498 match self {
1499 LogicalOp::And => write!(f, "&&"),
1500 LogicalOp::Or => write!(f, "||"),
1501 }
1502 }
1503}
1504
1505enum GuardDisplayContext {
1506 Root,
1507 InAnyArg,
1508 InNot,
1509 InAll,
1510}
1511
1512impl GuardExpr {
1513 fn fmt_with_ctx(&self, f: &mut fmt::Formatter<'_>, ctx: GuardDisplayContext) -> fmt::Result {
1514 match self {
1515 GuardExpr::Predicate(guard) => write!(f, "{}", guard),
1516 GuardExpr::All(children) => {
1517 let wrap = matches!(
1518 ctx,
1519 GuardDisplayContext::InAnyArg | GuardDisplayContext::InNot
1520 ) && children.len() > 1;
1521 if wrap {
1522 write!(f, "(")?;
1523 }
1524 for (i, child) in children.iter().enumerate() {
1525 if i > 0 {
1526 write!(f, ", ")?;
1527 }
1528 child.fmt_with_ctx(f, GuardDisplayContext::InAll)?;
1529 }
1530 if wrap {
1531 write!(f, ")")?;
1532 }
1533 Ok(())
1534 }
1535 GuardExpr::Or(children) => {
1536 write!(f, "any(")?;
1537 for (i, child) in children.iter().enumerate() {
1538 if i > 0 {
1539 write!(f, ", ")?;
1540 }
1541 child.fmt_with_ctx(f, GuardDisplayContext::InAnyArg)?;
1542 }
1543 write!(f, ")")
1544 }
1545 GuardExpr::Not(child) => {
1546 write!(f, "not(")?;
1547 child.fmt_with_ctx(f, GuardDisplayContext::InNot)?;
1548 write!(f, ")")
1549 }
1550 }
1551 }
1552}
1553
1554impl fmt::Display for GuardExpr {
1555 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1556 self.fmt_with_ctx(f, GuardDisplayContext::Root)
1557 }
1558}
1559
1560impl fmt::Display for Step {
1561 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1562 if let Some(expr) = &self.guard {
1563 write!(f, "[{}] ", expr)?;
1564 }
1565 write!(f, "{}", self.kind)
1566 }
1567}
1568
1569#[cfg(test)]
1570mod tests {
1571 use super::*;
1572 #[test]
1580 fn statement_keywords_match_backend() {
1581 for kw in STRUCTURAL_KEYWORDS {
1589 let via_backend = crate::parse_script(kw, crate::commands::lower_command);
1590 let via_lowering =
1591 crate::commands::lower_command(kw, Vec::new()).map(|kind| crate::Step {
1592 guard: None,
1593 kind,
1594 scope_enter: 0,
1595 scope_exit: 0,
1596 line: 0,
1597 col: 0,
1598 });
1599 match (via_backend, via_lowering) {
1600 (Ok(_), _) => {}
1601 (Err(a), Err(b)) => {
1602 assert_eq!(
1603 a.kind(),
1604 b.kind(),
1605 "backend kind drift for bare keyword {kw}: {a} vs {b}"
1606 );
1607 }
1608 (Err(a), Ok(_)) => {
1609 panic!("backend rejects bare keyword {kw} that lowering accepts: {a}")
1610 }
1611 }
1612 }
1613 for head in [
1617 "LET",
1618 "CONST",
1619 "RETURN",
1620 "BREAK",
1621 "CONTINUE",
1622 "IF",
1623 "FOR",
1624 "WHILE",
1625 "FUNC",
1626 "REMOTE",
1627 "INHERIT_ENV",
1628 "WITH_IO",
1629 "ASYNC",
1630 "TIMEOUT",
1631 "ISOLATED",
1632 "AWAIT",
1633 "CANCEL",
1634 "RUN",
1635 "IMPORT",
1636 "EXPORT",
1637 "TYPE",
1638 ] {
1639 assert!(
1640 STRUCTURAL_KEYWORDS.contains(&head)
1641 || crate::all_metadata().iter().any(|m| m.name == head),
1642 "structural head {head} is not registered"
1643 );
1644 }
1645 }
1646
1647 #[test]
1651 fn command_names_group_by_category() {
1652 for command in COMMANDS {
1653 let name = command.as_str();
1654 let Some((prefix, _)) = name.split_once('_') else {
1655 continue;
1656 };
1657 assert!(
1658 COMMAND_CATEGORIES.contains(&prefix),
1659 "command {name} introduces unregistered category {prefix}; add it to COMMAND_CATEGORIES"
1660 );
1661 }
1662 }
1663
1664 #[test]
1672 fn registry_commands_all_parse() {
1673 for meta in crate::all_metadata() {
1674 if !meta.in_index || STRUCTURAL_KEYWORDS.contains(&meta.name) {
1675 continue;
1676 }
1677 assert!(
1678 Command::parse(meta.name).is_some(),
1679 "registry command {} has no Command::parse arm",
1680 meta.name
1681 );
1682 }
1683 }
1684
1685 #[test]
1690 fn definition_spans_cover_type_and_func() {
1691 let alias = Step {
1692 guard: None,
1693 kind: StepKind::TypeAlias {
1694 name: "EMP".to_string(),
1695 target: "MAP<n: STRING>".to_string(),
1696 },
1697 scope_enter: 0,
1698 scope_exit: 0,
1699 line: 3,
1700 col: 5,
1701 };
1702 let (name, span) = alias.defined_symbol().expect("alias defines");
1703 assert_eq!(name, "EMP");
1704 assert_eq!(span.line, 3);
1705 assert_eq!(span.col_start, Some(5));
1706
1707 let func = Step {
1708 guard: None,
1709 kind: StepKind::FuncDef {
1710 name: "F".to_string(),
1711 params: Vec::new(),
1712 return_type: "VOID".to_string(),
1713 is_async: false,
1714 body: Vec::new(),
1715 docs: None,
1716 },
1717 scope_enter: 0,
1718 scope_exit: 0,
1719 line: 7,
1720 col: 1,
1721 };
1722 let (name, span) = func.defined_symbol().expect("func defines");
1723 assert_eq!(name, "F");
1724 assert_eq!(span.line, 7);
1725
1726 let plain = Step {
1727 guard: None,
1728 kind: StepKind::Break,
1729 scope_enter: 0,
1730 scope_exit: 0,
1731 line: 9,
1732 col: 1,
1733 };
1734 assert!(plain.defined_symbol().is_none());
1735
1736 let unknown = Step {
1737 guard: None,
1738 kind: StepKind::Break,
1739 scope_enter: 0,
1740 scope_exit: 0,
1741 line: 0,
1742 col: 0,
1743 };
1744 assert_eq!(unknown.span().line, 0);
1745 }
1746
1747 #[test]
1751 fn parsed_definitions_carry_spans() {
1752 let steps = crate::parse_script(
1753 indoc::indoc! {r#"
1754 TYPE EMP = MAP<n: STRING>
1755 FUNC F(): VOID {
1756 RETURN
1757 }
1758 "#},
1759 crate::commands::lower_command,
1760 )
1761 .expect("definitions parse");
1762 let mut names: Vec<(&str, usize)> = steps
1763 .iter()
1764 .filter_map(|s| s.defined_symbol().map(|(n, span)| (n, span.line)))
1765 .collect();
1766 names.sort();
1767 assert_eq!(names, vec![("EMP", 1), ("F", 2)]);
1768 }
1769}
1770
1771#[cfg(test)]
1772mod guard_analysis_tests {
1773 use super::*;
1774
1775 fn attr(ns: Ns, key: Option<&str>, val: Option<&str>) -> GuardExpr {
1776 GuardExpr::Predicate(Guard::Attr {
1777 ns,
1778 key: key.map(str::to_string),
1779 val: val.map(str::to_string),
1780 })
1781 }
1782
1783 fn os(value: &str) -> GuardExpr {
1784 attr(Ns::Os, None, Some(value))
1785 }
1786
1787 fn arch(value: &str) -> GuardExpr {
1788 attr(Ns::Arch, None, Some(value))
1789 }
1790
1791 fn unix() -> GuardExpr {
1794 GuardExpr::Or(vec![os("macos"), os("linux")])
1795 }
1796
1797 fn windows() -> GuardExpr {
1798 os("windows")
1799 }
1800
1801 fn env_eq(var: &str, value: &str) -> GuardExpr {
1802 attr(Ns::Env, Some(var), Some(value))
1803 }
1804
1805 fn not(expr: GuardExpr) -> GuardExpr {
1806 GuardExpr::Not(Box::new(expr))
1807 }
1808
1809 #[test]
1813 fn partition_negations_are_jointly_dead() {
1814 let os_exhausted = GuardExpr::All(vec![not(os("macos")), not(os("linux")), not(windows())]);
1815 assert!(
1816 !guard_satisfiable(&os_exhausted),
1817 "no host is outside `macos`/`linux`/`windows`"
1818 );
1819 let os_partial = GuardExpr::All(vec![not(os("macos")), not(os("linux"))]);
1821 assert!(guard_satisfiable(&os_partial), "`windows` is still open");
1822 let bool_exhausted = GuardExpr::All(vec![
1824 not(attr(Ns::Bool, None, Some("true"))),
1825 not(attr(Ns::Bool, None, Some("false"))),
1826 ]);
1827 assert!(!guard_satisfiable(&bool_exhausted));
1828 let env_open = GuardExpr::All(vec![
1830 not(env_eq("MODE", "dev")),
1831 not(env_eq("MODE", "prod")),
1832 ]);
1833 assert!(guard_satisfiable(&env_open), "MODE may hold a third value");
1834 assert!(guard_satisfiable(¬(unix())));
1836 }
1837
1838 #[test]
1841 fn unix_alias_is_os_disjunction() {
1842 assert!(!guards_overlap(Some(&unix()), Some(&windows())));
1843 assert!(guards_overlap(Some(&unix()), Some(&os("macos"))));
1844 let covered = GuardExpr::All(vec![GuardExpr::Not(Box::new(unix())), not(windows())]);
1847 assert!(!guard_satisfiable(&covered));
1848 }
1849
1850 #[test]
1854 fn arch_guards_decide_by_value() {
1855 assert!(!guards_overlap(
1856 Some(&arch("x86_64")),
1857 Some(&arch("aarch64"))
1858 ));
1859 assert!(guards_overlap(Some(&arch("x86_64")), Some(&arch("x86_64"))));
1860 assert!(guards_overlap(Some(&arch("aarch64")), Some(&os("macos"))));
1861 let exhausted = GuardExpr::All(ARCH_VALUES.iter().map(|value| not(arch(value))).collect());
1862 assert!(!guard_satisfiable(&exhausted));
1863 let host = attr(Ns::Arch, None, Some(ARCH_TARGET));
1865 assert!(guard_expr_allows(&host, &HashMap::new()));
1866 }
1867
1868 #[test]
1872 fn platform_overlap_matrix_is_exhaustive() {
1873 let cases = [
1874 ("macos", "macos", true),
1875 ("macos", "linux", false),
1876 ("macos", "windows", false),
1877 ("linux", "linux", true),
1878 ("linux", "windows", false),
1879 ("windows", "windows", true),
1880 ];
1881 for (v1, v2, expected) in cases {
1882 let left = os(v1);
1883 let right = os(v2);
1884 assert_eq!(
1885 guards_overlap(Some(&left), Some(&right)),
1886 expected,
1887 "os:{v1} vs os:{v2}"
1888 );
1889 }
1890 }
1891
1892 #[test]
1895 fn disjoint_pairs_never_cofire_here() {
1896 let macos = os("macos");
1897 let holds = |expr: &GuardExpr| guard_expr_allows(expr, &HashMap::new());
1898 assert!(
1899 !(holds(&macos) && holds(&windows())),
1900 "os:macos and os:windows co-fired"
1901 );
1902 }
1903
1904 #[test]
1905 fn overlap_follows_namespace_semantics() {
1906 assert!(!guards_overlap(Some(&windows()), Some(&unix())));
1908 assert!(!guards_overlap(Some(&os("macos")), Some(&os("linux"))));
1909 assert!(guards_overlap(None, Some(&windows())));
1911 assert!(guards_overlap(None, None));
1912 let dead = GuardExpr::All(vec![os("macos"), windows()]);
1914 assert!(!guard_satisfiable(&dead));
1915 assert!(!guards_overlap(Some(&dead), Some(&os("macos"))));
1916 assert!(guard_valid(&GuardExpr::Predicate(Guard::Attr {
1917 ns: Ns::Bool,
1918 key: None,
1919 val: Some("true".to_string()),
1920 })));
1921 assert!(!guard_valid(&unix()));
1922 }
1923
1924 #[test]
1925 fn env_value_conflicts_decide_without_enumeration() {
1926 let fast = env_eq("MODE", "fast");
1927 let slow = env_eq("MODE", "slow");
1928 assert!(
1929 !guards_overlap(Some(&fast), Some(&slow)),
1930 "same key distinct values are disjoint"
1931 );
1932 let also_fast = env_eq("MODE", "fast");
1933 assert!(guards_overlap(Some(&fast), Some(&also_fast)));
1934 let bare = attr(Ns::Env, Some("MODE"), None);
1936 assert!(guards_overlap(Some(&bare), Some(&fast)));
1937 }
1938}
1939
1940#[cfg(test)]
1941mod guard_algebra_tests {
1942 use super::*;
1943
1944 fn os(value: &str) -> GuardExpr {
1945 GuardExpr::Predicate(Guard::Attr {
1946 ns: Ns::Os,
1947 key: None,
1948 val: Some(value.to_string()),
1949 })
1950 }
1951
1952 #[test]
1953 fn or_distributes_over_disjointness() {
1954 fn env_eq(var: &str, value: &str) -> GuardExpr {
1955 GuardExpr::Predicate(Guard::Attr {
1956 ns: Ns::Env,
1957 key: Some(var.to_string()),
1958 val: Some(value.to_string()),
1959 })
1960 }
1961 let mixed = GuardExpr::Or(vec![env_eq("MODE", "dev"), env_eq("MODE", "prod")]);
1964 assert!(!mixed.is_disjoint_from(&env_eq("MODE", "dev")));
1965 assert!(mixed.is_disjoint_from(&env_eq("MODE", "test")));
1967 let cross = GuardExpr::Or(vec![env_eq("MODE", "dev")]);
1969 let platform = os("windows");
1970 assert!(!cross.is_disjoint_from(&platform));
1971 }
1972
1973 #[test]
1974 fn all_distributes_over_disjointness() {
1975 let stacked = GuardExpr::All(vec![
1976 os("macos"),
1977 GuardExpr::Or(vec![os("macos"), os("linux")]),
1978 os("windows"),
1979 ]);
1980 assert!(stacked.is_disjoint_from(&os("macos")));
1981 let live = GuardExpr::All(vec![
1984 os("macos"),
1985 GuardExpr::Predicate(Guard::Attr {
1986 ns: Ns::Env,
1987 key: Some("MODE".to_string()),
1988 val: Some("dev".to_string()),
1989 }),
1990 ]);
1991 assert!(!live.is_disjoint_from(&os("macos")));
1992 }
1993
1994 #[test]
1995 fn negation_is_structural_not_syntactic() {
1996 let not_win = GuardExpr::Not(Box::new(os("windows")));
1997 assert!(not_win.is_disjoint_from(&os("windows")));
1998 assert!(os("windows").is_disjoint_from(¬_win));
1999 assert!(!not_win.is_disjoint_from(&os("macos")));
2000 }
2001}