1use std::collections::HashSet;
16use std::fmt;
17
18use crate::ast::{
19 Arg, ArgPart, ArithOp, Command, CompareOp, Expr, GuardExpr, IoBinding, IoStream, MathOp,
20 ModuleTable, PipeTarget, Step, Value, WorkspaceTarget,
21};
22use crate::command::{
23 ArgSpec, ArgType, CommandMeta, Example, FlagSpec, FlagValueType, IoDirection, Stream,
24 split_assignment,
25};
26use crate::constants::{KEYWORD_EXPORT, KEYWORD_IMPORT};
27use crate::error::{ParseError, ParseResult, SpanContext};
28use indoc::indoc;
29
30pub const REMOTE_RESERVED_WORDS: &[&str] = &["SNAPSHOT", "LOCAL", "CACHE", "SYSTEM", "REMOTE"];
40
41pub fn is_valid_remote_target(target: &str) -> bool {
45 if target.is_empty() || target.len() > 64 {
46 return false;
47 }
48 if REMOTE_RESERVED_WORDS.contains(&target) {
49 return false;
50 }
51 let mut chars = target.chars();
52 match chars.next() {
53 Some(first) if first.is_ascii_alphanumeric() => {}
54 _ => return false,
55 }
56 chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
57}
58
59fn join_value(args: Vec<Arg>, cmd_name: &str) -> ParseResult<Arg> {
64 if args.is_empty() {
65 return Err(ParseError::validation(
66 cmd_name,
67 format!("{cmd_name} requires at least one argument"),
68 &SpanContext::line_only(0),
69 ));
70 }
71 if args.len() == 1 {
72 return Ok(args.into_iter().next().unwrap());
73 }
74 if args.iter().all(|a| matches!(a, Arg::String(..))) {
75 return Ok(Arg::String(
76 args.iter()
77 .map(|a| a.as_str())
78 .collect::<Vec<_>>()
79 .join(" "),
80 false,
81 ));
82 }
83 let mut parts = Vec::new();
84 for (index, arg) in args.into_iter().enumerate() {
85 if index > 0 {
86 parts.push(ArgPart::Text(" ".to_string(), false));
87 }
88 match arg {
89 Arg::String(text, quoted) => parts.push(ArgPart::Text(text, quoted)),
90 Arg::Expr(expr) => parts.push(ArgPart::Expr(expr)),
91 Arg::Parts(inner) => parts.extend(inner),
92 }
93 }
94 Ok(Arg::Parts(parts))
95}
96
97pub fn lower_env_assignment(args: Vec<Arg>) -> ParseResult<StepKind> {
101 let arg = args.into_iter().next().ok_or_else(|| {
102 ParseError::validation(
103 "ENV",
104 "ENV requires KEY=value".to_string(),
105 &SpanContext::line_only(0),
106 )
107 })?;
108 let Some((key, value)) = split_assignment(arg.as_str())
109 .map_err(|e| ParseError::validation("ENV", e.to_string(), &SpanContext::line_only(0)))?
110 else {
111 return Err(ParseError::validation(
112 "ENV",
113 "ENV requires KEY=value format".to_string(),
114 &SpanContext::line_only(0),
115 ));
116 };
117 Ok(StepKind::Env { key, value })
118}
119
120pub(crate) fn canonical_assignment_arg(key: &str, value: &Arg) -> Arg {
125 Arg::String(format!("{key}={}", value.render()), false)
126}
127
128fn fmt_assert_target(target: &AssertTarget) -> String {
131 match target {
132 AssertTarget::Value(arg) => fmt_value(arg, quote_msg),
133 _ => target.render(),
134 }
135}
136
137fn fmt_value(arg: &Arg, quote: fn(&str) -> String) -> String {
142 match arg {
143 Arg::Expr(_) => arg.render(),
144 Arg::String(text, _) => quote(text),
145 Arg::Parts(_) => {
146 let rendered = arg.render();
147 if rendered.contains(';')
148 || rendered.contains('}')
149 || rendered.contains('\n')
150 || rendered.contains('\r')
151 {
152 quote(&rendered)
153 } else {
154 rendered
155 }
156 }
157 }
158}
159
160fn quote_dsl_string(s: &str) -> String {
161 if s.contains('\n') && !s.contains('"') && !s.contains('\r') && !s.trim().is_empty() {
180 let escaped = escape_block_text(s);
181 return format!("\"\"\"\n{escaped}\n\"\"\"");
182 }
183 format!("\"{}\"", escape_inline_text(s))
184}
185
186fn escape_inline_text(s: &str) -> String {
191 let mut out = String::with_capacity(s.len() + 2);
192 let mut chars = s.chars().peekable();
193 while let Some(c) = chars.next() {
194 match c {
195 '"' => out.push_str("\\\""),
196 '\\' => {
197 if matches!(
201 chars.peek(),
202 Some('n' | 't' | 'r' | '\\' | '"' | '\'' | '0')
203 ) {
204 out.push('\\');
205 out.push(chars.next().unwrap_or('\\'));
206 } else {
207 out.push_str("\\\\");
208 }
209 }
210 _ => out.push(c),
211 }
212 }
213 out
214}
215
216fn escape_block_text(s: &str) -> String {
222 let preescaped = s.replace("\"\"\"", "\\\"\\\"\\\"");
223 let mut out = String::with_capacity(preescaped.len());
224 let mut chars = preescaped.chars().peekable();
225 while let Some(c) = chars.next() {
226 if c != '\\' {
227 out.push(c);
228 continue;
229 }
230 let keep = matches!(
231 chars.peek(),
232 Some('n' | 't' | 'r' | '\\' | '"' | '\'' | '0')
233 );
234 out.push('\\');
235 if !keep {
236 out.push('\\');
237 }
238 }
239 out
240}
241
242fn quote_arg(s: &str) -> String {
243 let is_safe = s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
244 && !s.starts_with(|c: char| c.is_ascii_digit() || c == '-' || c == '/' || c == '.')
245 && !crate::Command::is_statement_keyword(s);
246 if is_safe && !s.is_empty() {
247 s.to_string()
248 } else {
249 quote_dsl_string(s)
250 }
251}
252
253fn quote_msg(s: &str) -> String {
254 let safe = s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
255 && !s.starts_with(|c: char| c.is_ascii_digit())
256 && !crate::Command::is_statement_keyword(s);
257 if safe && !s.is_empty() {
258 s.to_string()
259 } else {
260 quote_dsl_string(s)
261 }
262}
263
264fn quote_run(s: &str) -> String {
265 if s.is_empty() || s.chars().any(|c| c == ';' || c == '\n') || s.contains("//") {
266 return quote_dsl_string(s);
267 }
268 s.split(' ')
269 .map(|w| {
270 if w.starts_with(|c: char| c.is_ascii_digit())
271 || w.starts_with(['/', '.', '-', ':', '='])
272 {
273 quote_dsl_string(w)
274 } else {
275 w.to_string()
276 }
277 })
278 .collect::<Vec<_>>()
279 .join(" ")
280}
281
282fn fmt_exec_arg(arg: &Arg) -> String {
288 match arg {
289 Arg::String(text, _) => quote_dsl_string(text),
290 Arg::Expr(_) => arg.render(),
291 Arg::Parts(_) => {
292 let rendered = arg.render();
293 if rendered.contains(';')
294 || rendered.contains('}')
295 || rendered.contains('\n')
296 || rendered.contains('\r')
297 {
298 quote_dsl_string(&rendered)
299 } else {
300 rendered
301 }
302 }
303 }
304}
305
306fn fmt_raw_arg(arg: &Arg) -> String {
310 match arg {
311 Arg::String(s, true) => quote_dsl_string(s),
312 _ => arg.render(),
313 }
314}
315
316fn fmt_io(b: &IoBinding) -> String {
317 let s = match b.stream {
318 IoStream::Stdin => "stdin".to_string(),
319 IoStream::Stdout => "stdout".to_string(),
320 IoStream::Stderr => "stderr".to_string(),
321 IoStream::Tty => "tty".to_string(),
322 IoStream::Rows(rows) => format!("rows={rows}"),
323 IoStream::Cols(cols) => format!("cols={cols}"),
324 };
325 match &b.pipe {
326 Some(PipeTarget::Var(v)) => format!("{}=${}", s, v),
327 None => s,
328 }
329}
330
331pub(crate) fn is_known_command(name: &str) -> bool {
338 if name == "ELSE" {
339 return true;
340 }
341 all_metadata().iter().any(|meta| meta.name == name)
342}
343
344pub(crate) fn invalid_syntax_error(name: &str, raw_args: &[Arg]) -> ParseError {
345 let received = raw_args
346 .iter()
347 .map(Arg::render)
348 .collect::<Vec<_>>()
349 .join(" ");
350 let got = if received.is_empty() {
351 "nothing".to_string()
352 } else {
353 format!("`{received}`")
354 };
355 let found = if received.is_empty() {
356 None
357 } else {
358 Some(received.clone())
359 };
360 let expected = all_metadata()
361 .iter()
362 .find(|meta| meta.name == name)
363 .map(|meta| vec![meta.syntax.to_string()])
364 .unwrap_or_default();
365 let ctx = SpanContext::line_only(0);
366 match structural_hint(name, &received) {
367 Some(hint) => ParseError::invalid_syntax(
368 name,
369 format!("invalid syntax for command {name}: {hint}"),
370 found,
371 expected,
372 Some(hint),
373 &ctx,
374 ),
375 None => ParseError::invalid_syntax(
376 name,
377 format!("invalid syntax for command {name}: got {got}."),
378 found,
379 expected,
380 None,
381 &ctx,
382 ),
383 }
384}
385
386fn unknown_command_error(name: &str, raw_args: &[Arg]) -> ParseError {
387 let received = raw_args
388 .iter()
389 .map(Arg::render)
390 .collect::<Vec<_>>()
391 .join(" ");
392 let hint = structural_hint(name, &received).or_else(|| case_hint(name));
393 let ctx = SpanContext::line_only(0);
394 match hint {
395 Some(hint) => ParseError::unknown_command(
396 name,
397 format!("unknown command: {name}\n{hint}"),
398 Some(hint),
399 &ctx,
400 ),
401 None => ParseError::unknown_command(name, format!("unknown command: {name}"), None, &ctx),
402 }
403}
404
405pub(crate) fn classify(name: &str, raw_args: &[Arg]) -> ParseError {
411 if is_known_command(name) {
412 invalid_syntax_error(name, raw_args)
413 } else {
414 unknown_command_error(name, raw_args)
415 }
416}
417
418fn structural_hint(name: &str, received: &str) -> Option<String> {
419 let got = if received.is_empty() {
420 "nothing".to_string()
421 } else {
422 format!("`{received}`")
423 };
424 match name {
425 "WITH_IO" => Some(with_io_hint(&got, received)),
426 "AWAIT" => Some(format!(
427 "AWAIT waits for a background task variable, e.g. `LET $t: HANDLE = ASYNC ECHO hi` then `AWAIT $t`; got {got}."
428 )),
429 "CANCEL" => Some(format!(
430 "CANCEL stops a background task variable, e.g. `CANCEL $t` (from `LET $t: HANDLE = ASYNC ...`); got {got}."
431 )),
432 "ASYNC" => Some(format!(
433 "ASYNC runs a command in the background, e.g. `ASYNC RUN ...`, `ASYNC {{ ... }}`, or `LET $t: HANDLE = ASYNC ...`; got {got}."
434 )),
435 "FOR" => Some(format!(
436 "FOR loops need `FOR $item: TYPE IN <expr> {{ ... }}` (or `FOR $key: STRING, $value: TYPE IN <expr> {{ ... }}`); got {got}."
437 )),
438 "IF" => Some(format!(
439 "IF needs a condition and a block, e.g. `IF true {{ ECHO yes }}`; got {got}."
440 )),
441 "ELSE" => Some(format!(
442 "ELSE must directly follow an `IF ... {{ ... }}` block, e.g. `IF true {{ ECHO yes }} ELSE {{ ECHO no }}`; got {got}."
443 )),
444 "LET" => Some(format!(
445 "LET assigns a variable, e.g. `LET $name: STRING = <expr>`, `LET $t: HANDLE = ASYNC ...`, `LET $out: STRING = <command>` (capture), `LET $out: STRING = AWAIT $t`, or `LET $var: TYPE = {{ ... }}` (inline block); got {got}."
446 )),
447 "SET" => Some(
448 "`SET` is not a keyword; mutate a declared variable with `$var = <expr>`, e.g. `$count = 2`.".to_string(),
449 ),
450 "TIMEOUT" => Some(format!(
451 "TIMEOUT needs a duration and a command or block, e.g. `TIMEOUT 30s RUN ...`; got {got}."
452 )),
453 "REMOTE" => Some(format!(
454 "REMOTE needs a target and a braced block, e.g. `REMOTE prod [$version, env:DEPLOY_ENV] {{ ... }}`; got {got}."
455 )),
456 "FUNC" => Some(format!(
457 "FUNC defines a function, e.g. `FUNC GREET($name: STRING) {{ RETURN $name }}`; got {got}."
458 )),
459 "RETURN" => Some(format!(
460 "RETURN ends the nearest function, ASYNC task, or inline LET block with a value, e.g. `RETURN $x`; got {got}."
461 )),
462 "WHILE" => Some(format!(
463 "WHILE needs a Bool condition and a block, e.g. `WHILE !$done {{ ... }}`; got {got}."
464 )),
465 "BREAK" => Some(
466 "`BREAK` exits the innermost enclosing FOR/WHILE loop; it must appear inside a loop.".to_string(),
467 ),
468 "CONTINUE" => Some(
469 "`CONTINUE` skips to the next iteration of the innermost enclosing FOR/WHILE loop; it must appear inside a loop.".to_string(),
470 ),
471 "INHERIT_ENV" => Some(format!(
472 "INHERIT_ENV takes a key list, e.g. `INHERIT_ENV [HOME, PATH]`; got {got}."
473 )),
474 name if name == KEYWORD_IMPORT => Some(format!(
475 "IMPORT brings module functions into bare-call scope, e.g. `IMPORT [STD]` or `IMPORT [STD, MOCK]`; file imports take a quoted path with a mandatory alias, e.g. `IMPORT [\"./lib.oxdock\" AS LIB]`, and brackets mix both across lines, e.g. `IMPORT [STD, \"a.oxdock\" AS A]`; got {got}."
476 )),
477 name if name == KEYWORD_EXPORT => Some(
478 "EXPORT marks script FUNCs and qualified host functions as tools, e.g. `EXPORT FOO`, `EXPORT [FOO, STD::INT]`."
479 .to_string(),
480 ),
481 _ => None,
482 }
483}
484
485fn with_io_hint(got: &str, received: &str) -> String {
489 const SYNTAX: &str =
490 "WITH_IO needs `WITH_IO [bindings] <command>` or `WITH_IO [bindings] { <commands> }`";
491 const BINDINGS: &str = "bindings are `stdin`, `stdout`, `stderr`, or `<stream>=$var` with a PIPE-typed variable (e.g. `[stdout=$p]`, `[stdin=$p]`); `tty` is a bare flag for RUN steps, with `rows = <int>` / `cols = <int>` geometry (e.g. `[tty, rows=40, cols=100]`)";
492 if let Some(after_open) = received.strip_prefix('[') {
493 match after_open.split_once(']') {
494 None => {
495 return format!("{SYNTAX}: missing closing `]` in the binding list; got {got}.");
496 }
497 Some((bindings, _)) => {
498 for part in bindings.split(',') {
499 let part = part.trim();
500 if part.is_empty() {
501 continue;
502 }
503 let (stream, binding) = match part.split_once('=') {
504 Some((stream, binding)) => (stream.trim(), Some(binding.trim())),
505 None => (part, None),
506 };
507 if matches!(stream, "rows" | "cols") {
508 let valid = binding.is_some_and(|value| {
509 value
510 .parse::<u64>()
511 .is_ok_and(|dim| (1..=u64::from(u16::MAX)).contains(&dim))
512 });
513 if !valid {
514 return format!(
515 "{SYNTAX}: invalid geometry `{part}`; `rows`/`cols` need a positive integer 1-65535 (e.g. `rows=40`) and require `tty`; got {got}."
516 );
517 }
518 continue;
519 }
520 if stream == "tty" {
521 if binding.is_some() {
522 return format!(
523 "{SYNTAX}: invalid binding `{part}`; `tty` is a bare flag (geometry rides `rows`/`cols`, e.g. `[tty, rows=40]`); got {got}."
524 );
525 }
526 continue;
527 }
528 if !matches!(stream, "stdin" | "stdout" | "stderr") {
529 return format!(
530 "{SYNTAX}: invalid stream `{stream}`; expected `stdin`, `stdout`, `stderr`, or `tty`; got {got}."
531 );
532 }
533 let valid = match binding {
534 None => true,
535 Some(value) => value.strip_prefix('$').is_some_and(|var| {
536 !var.trim().is_empty()
537 && var.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
538 }),
539 };
540 if !valid {
541 return format!(
542 "{SYNTAX}: invalid binding `{part}`; {BINDINGS}; got {got}."
543 );
544 }
545 }
546 }
547 }
548 }
549 format!("{SYNTAX}; got {got}. {BINDINGS}.")
550}
551
552fn case_hint(name: &str) -> Option<String> {
554 let upper = name.to_ascii_uppercase();
555 if upper != name
556 && all_metadata()
557 .iter()
558 .any(|meta| meta.name == upper.as_str())
559 {
560 return Some(format!("did you mean `{upper}`? commands are uppercase."));
561 }
562 None
563}
564
565macro_rules! declare_commands {
566 (
567 structural [
568 $( $sname:ident $( { $( $sfname:ident : $sftype:ty ),* $(,)? } )? ),* $(,)?
569 ]
570
571 $(
572 $cmd_ident:ident => [
573 name: $name:expr,
574 variant: $vname:ident $( { $( $vfname:ident : $vftype:ty ),* $(,)? } )? $( ( $( $ttuple:ty ),* $(,)? ) )?,
575 syntax: $syntax:expr,
576 summary: $summary:expr,
577 description: $desc:expr,
578 args: $args:expr,
579 flags: $flags:expr,
580 default_output: $out:expr,
581 examples: $examples:expr,
582 lower: $lower:expr,
583 ]
584 ),* $(,)?
585 ) => {
586 #[derive(Debug, Clone, PartialEq)]
587 pub enum StepKind {
588 $( $vname $( { $( $vfname : $vftype ),* } )? $( ( $( $ttuple ),* ) )?, )*
589 $( $sname $( { $( $sfname : $sftype ),* } )?, )*
590 }
591
592 pub fn lower_command(name: &str, raw_args: Vec<Arg>) -> ParseResult<StepKind> {
593 match name {
594 $(
595 s if s == $name => {
596 let meta = CommandMeta {
597 name: $name, syntax: $syntax, summary: $summary,
598 description: $desc, args: $args, flags: $flags,
599 default_output: $out, examples: $examples,
600 in_index: true,
601 };
602 let (flags, positional) = crate::strip_flags(raw_args, &meta)?;
603 crate::command::validate_positionals_against_meta(
604 s,
605 &meta.args,
606 &positional,
607 )?;
608 let lower_fn: fn(Vec<(String, Arg)>, Vec<Arg>) -> ParseResult<StepKind> = $lower;
609 lower_fn(flags, positional)
610 }
611 )*
612 _ => {
613 Err(classify(name, &raw_args))
614 }
615 }
616 }
617
618 pub fn all_metadata() -> Vec<CommandMeta> {
619 let mut out = vec![
620 $( CommandMeta {
621 name: $name, syntax: $syntax, summary: $summary,
622 description: $desc, args: $args, flags: $flags,
623 default_output: $out, examples: $examples,
624 in_index: true,
625 }, )*
626 ];
627 out.extend(all_structural_metadata());
631 out
632 }
633 };
634}
635
636impl StepKind {
637 pub fn walk_exprs(&self, f: &mut impl FnMut(&Expr)) {
644 fn walk_arg(arg: &Arg, f: &mut impl FnMut(&Expr)) {
645 match arg {
646 Arg::Expr(expr) => f(expr),
647 Arg::Parts(parts) => {
648 for part in parts {
649 if let ArgPart::Expr(expr) = part {
650 f(expr);
651 }
652 }
653 }
654 Arg::String(..) => {}
655 }
656 }
657 fn walk_opt(arg: &Option<Arg>, f: &mut impl FnMut(&Expr)) {
658 if let Some(arg) = arg {
659 walk_arg(arg, f);
660 }
661 }
662 fn walk_target(target: &AssertTarget, f: &mut impl FnMut(&Expr)) {
663 if let AssertTarget::Value(arg) = target {
664 walk_arg(arg, f);
665 }
666 }
667 match self {
668 StepKind::Assign { expr, .. } | StepKind::Set { expr, .. } => f(expr),
669 StepKind::Return { expr } => f(expr),
670 StepKind::Call { args, .. } => {
671 for arg in args {
672 f(arg);
673 }
674 }
675 StepKind::ImportFile { .. } | StepKind::ImportFuncs { .. } => {}
676 StepKind::For { in_expr, .. } => f(in_expr),
677 StepKind::If { cond, else_ifs, .. } => {
678 f(cond);
679 for (cond, _) in else_ifs {
680 f(cond);
681 }
682 }
683 StepKind::While { cond, .. } => f(cond),
684 StepKind::Timeout { duration, .. } | StepKind::Sleep { duration } => {
685 walk_arg(duration, f);
686 }
687 StepKind::Workdir(arg)
688 | StepKind::Echo(arg)
689 | StepKind::Run(arg)
690 | StepKind::Mkdir(arg)
691 | StepKind::Exit(arg) => walk_arg(arg, f),
692 StepKind::Env { value, .. } => walk_arg(value, f),
693 StepKind::Copy { from, to, .. }
694 | StepKind::Symlink { from, to, .. }
695 | StepKind::Archive {
696 src: from, dst: to, ..
697 }
698 | StepKind::Install { from, to } => {
699 walk_arg(from, f);
700 walk_arg(to, f);
701 }
702 StepKind::Unarchive {
703 src,
704 dst,
705 max_bytes,
706 } => {
707 walk_arg(src, f);
708 walk_arg(dst, f);
709 walk_opt(max_bytes, f);
710 }
711 StepKind::CopyGit { rev, from, to, .. } => {
712 walk_arg(rev, f);
713 walk_arg(from, f);
714 walk_arg(to, f);
715 }
716 StepKind::Ls(arg) | StepKind::Read(arg) => walk_opt(arg, f),
717 StepKind::Remove { path, .. } => walk_arg(path, f),
718 StepKind::Prompt {
719 message, default, ..
720 } => {
721 walk_arg(message, f);
722 walk_opt(default, f);
723 }
724 StepKind::Write { path, contents } | StepKind::Append { path, contents } => {
725 walk_arg(path, f);
726 walk_opt(contents, f);
727 }
728 StepKind::Expand { path, overrides } => {
729 walk_opt(path, f);
730 for (_, value) in overrides {
731 walk_arg(value, f);
732 }
733 }
734 StepKind::AssertEq {
735 actual, expected, ..
736 }
737 | StepKind::AssertNe {
738 actual, expected, ..
739 } => {
740 walk_target(actual, f);
741 walk_opt(expected, f);
742 }
743 StepKind::AssertContains { haystack, needle } => {
744 walk_target(haystack, f);
745 walk_arg(needle, f);
746 }
747 StepKind::ListAppend { item, .. } => walk_arg(item, f),
748 StepKind::RunExec { argv } => {
749 for arg in argv {
750 walk_arg(arg, f);
751 }
752 }
753 StepKind::WithIo { .. }
754 | StepKind::WithIoBlock { .. }
755 | StepKind::TypeAlias { .. }
756 | StepKind::Workspace(_)
757 | StepKind::InheritEnv { .. }
758 | StepKind::Isolated { .. }
759 | StepKind::IsolatedInheritEnv { .. }
760 | StepKind::ReadLine { .. }
761 | StepKind::AssignCapture { .. }
762 | StepKind::AwaitCapture { .. }
763 | StepKind::AsyncBlock { .. }
764 | StepKind::AssignAsync { .. }
765 | StepKind::Await { .. }
766 | StepKind::Cancel { .. }
767 | StepKind::RemoteBlock { .. }
768 | StepKind::FuncDef { .. }
769 | StepKind::Break
770 | StepKind::Continue => {}
771 }
772 }
773
774 pub fn walk_raw_strings(&self, f: &mut impl FnMut(&str)) {
782 fn walk_arg(arg: &Arg, f: &mut impl FnMut(&str)) {
783 match arg {
784 Arg::String(text, _) => f(text),
785 Arg::Expr(_) => {}
786 Arg::Parts(parts) => {
787 for part in parts {
788 if let ArgPart::Text(text, _) = part {
789 f(text);
790 }
791 }
792 }
793 }
794 }
795 fn walk_opt(arg: &Option<Arg>, f: &mut impl FnMut(&str)) {
796 if let Some(arg) = arg {
797 walk_arg(arg, f);
798 }
799 }
800 fn walk_target(target: &AssertTarget, f: &mut impl FnMut(&str)) {
801 if let AssertTarget::Value(arg) = target {
802 walk_arg(arg, f);
803 }
804 }
805 match self {
806 StepKind::Assign { .. }
807 | StepKind::Set { .. }
808 | StepKind::Call { .. }
809 | StepKind::Return { .. }
810 | StepKind::For { .. }
811 | StepKind::If { .. }
812 | StepKind::While { .. } => {}
813 StepKind::Timeout { duration, .. } | StepKind::Sleep { duration } => {
814 walk_arg(duration, f);
815 }
816 StepKind::Workdir(arg)
817 | StepKind::Echo(arg)
818 | StepKind::Run(arg)
819 | StepKind::Mkdir(arg)
820 | StepKind::Exit(arg) => walk_arg(arg, f),
821 StepKind::Env { value, .. } => walk_arg(value, f),
822 StepKind::Copy { from, to, .. }
823 | StepKind::Symlink { from, to, .. }
824 | StepKind::Archive {
825 src: from, dst: to, ..
826 }
827 | StepKind::Install { from, to } => {
828 walk_arg(from, f);
829 walk_arg(to, f);
830 }
831 StepKind::Unarchive {
832 src,
833 dst,
834 max_bytes,
835 } => {
836 walk_arg(src, f);
837 walk_arg(dst, f);
838 walk_opt(max_bytes, f);
839 }
840 StepKind::CopyGit { rev, from, to, .. } => {
841 walk_arg(rev, f);
842 walk_arg(from, f);
843 walk_arg(to, f);
844 }
845 StepKind::Ls(arg) | StepKind::Read(arg) => walk_opt(arg, f),
846 StepKind::Remove { path, .. } => walk_arg(path, f),
847 StepKind::Prompt {
848 message, default, ..
849 } => {
850 walk_arg(message, f);
851 walk_opt(default, f);
852 }
853 StepKind::Write { path, contents } | StepKind::Append { path, contents } => {
854 walk_arg(path, f);
855 walk_opt(contents, f);
856 }
857 StepKind::Expand { path, overrides } => {
858 walk_opt(path, f);
859 for (_, value) in overrides {
860 walk_arg(value, f);
861 }
862 }
863 StepKind::AssertEq {
864 actual, expected, ..
865 }
866 | StepKind::AssertNe {
867 actual, expected, ..
868 } => {
869 walk_target(actual, f);
870 walk_opt(expected, f);
871 }
872 StepKind::AssertContains { haystack, needle } => {
873 walk_target(haystack, f);
874 walk_arg(needle, f);
875 }
876 StepKind::ListAppend { item, .. } => walk_arg(item, f),
877 StepKind::RunExec { argv } => {
878 for arg in argv {
879 walk_arg(arg, f);
880 }
881 }
882 StepKind::WithIo { .. }
883 | StepKind::WithIoBlock { .. }
884 | StepKind::TypeAlias { .. }
885 | StepKind::Workspace(_)
886 | StepKind::ImportFile { .. }
887 | StepKind::ImportFuncs { .. }
888 | StepKind::InheritEnv { .. }
889 | StepKind::Isolated { .. }
890 | StepKind::IsolatedInheritEnv { .. }
891 | StepKind::ReadLine { .. }
892 | StepKind::AssignCapture { .. }
893 | StepKind::AwaitCapture { .. }
894 | StepKind::AsyncBlock { .. }
895 | StepKind::AssignAsync { .. }
896 | StepKind::Await { .. }
897 | StepKind::Cancel { .. }
898 | StepKind::RemoteBlock { .. }
899 | StepKind::FuncDef { .. }
900 | StepKind::Break
901 | StepKind::Continue => {}
902 }
903 }
904
905 pub fn walk_child_kinds(&self, f: &mut impl FnMut(&StepKind)) {
909 fn walk_body(body: &[Step], f: &mut impl FnMut(&StepKind)) {
910 for step in body {
911 f(&step.kind);
912 }
913 }
914 match self {
915 StepKind::WithIo { cmd, .. } => f(cmd),
916 StepKind::AssignCapture { cmd, .. } => f(cmd),
917 StepKind::For { body, .. }
918 | StepKind::While { body, .. }
919 | StepKind::FuncDef { body, .. }
920 | StepKind::Timeout { body, .. }
921 | StepKind::Isolated { body }
922 | StepKind::AssignAsync { body, .. }
923 | StepKind::AsyncBlock { body }
924 | StepKind::RemoteBlock { body, .. } => walk_body(body, f),
925 StepKind::If {
926 then_body,
927 else_ifs,
928 else_body,
929 ..
930 } => {
931 walk_body(then_body, f);
932 for (_, body) in else_ifs {
933 walk_body(body, f);
934 }
935 if let Some(body) = else_body {
936 walk_body(body, f);
937 }
938 }
939 StepKind::InheritEnv { .. }
940 | StepKind::IsolatedInheritEnv { .. }
941 | StepKind::TypeAlias { .. }
942 | StepKind::Workdir(_)
943 | StepKind::Workspace(_)
944 | StepKind::Env { .. }
945 | StepKind::Echo(_)
946 | StepKind::Run(_)
947 | StepKind::RunExec { .. }
948 | StepKind::Copy { .. }
949 | StepKind::CopyGit { .. }
950 | StepKind::Symlink { .. }
951 | StepKind::Archive { .. }
952 | StepKind::Unarchive { .. }
953 | StepKind::Install { .. }
954 | StepKind::Mkdir(_)
955 | StepKind::Ls(_)
956 | StepKind::Read(_)
957 | StepKind::ReadLine { .. }
958 | StepKind::Prompt { .. }
959 | StepKind::Write { .. }
960 | StepKind::Append { .. }
961 | StepKind::Remove { .. }
962 | StepKind::Expand { .. }
963 | StepKind::AssertEq { .. }
964 | StepKind::AssertNe { .. }
965 | StepKind::AssertContains { .. }
966 | StepKind::Exit(_)
967 | StepKind::WithIoBlock { .. }
968 | StepKind::Assign { .. }
969 | StepKind::Set { .. }
970 | StepKind::AwaitCapture { .. }
971 | StepKind::Await { .. }
972 | StepKind::Cancel { .. }
973 | StepKind::Sleep { .. }
974 | StepKind::ListAppend { .. }
975 | StepKind::Call { .. }
976 | StepKind::ImportFile { .. }
977 | StepKind::ImportFuncs { .. }
978 | StepKind::Return { .. }
979 | StepKind::Break
980 | StepKind::Continue => {}
981 }
982 }
983
984 pub fn walk_step_exprs(&self, f: &mut impl FnMut(&Expr)) {
989 self.walk_exprs(&mut |expr| expr.walk(f));
990 self.walk_child_kinds(&mut |kind| kind.walk_step_exprs(f));
991 }
992}
993
994#[derive(Debug, Clone, PartialEq)]
1003pub enum AssertTarget {
1004 Value(Arg),
1005 Stdout,
1006 Stderr,
1007}
1008
1009impl AssertTarget {
1010 pub fn render(&self) -> String {
1011 match self {
1012 AssertTarget::Value(arg) => arg.render(),
1013 AssertTarget::Stdout => "stdout".to_string(),
1014 AssertTarget::Stderr => "stderr".to_string(),
1015 }
1016 }
1017}
1018
1019fn lower_assert_target(arg: Arg) -> ParseResult<AssertTarget> {
1028 match arg {
1029 Arg::Expr(_) => Ok(AssertTarget::Value(arg)),
1030 Arg::String(text, quoted) if !quoted => match text.as_str() {
1031 "stdout" => Ok(AssertTarget::Stdout),
1032 "stderr" => Ok(AssertTarget::Stderr),
1033 _ => Ok(AssertTarget::Value(lower_assert_operand(Arg::String(
1034 text, false,
1035 )))),
1036 },
1037 other => Ok(AssertTarget::Value(lower_assert_operand(other))),
1038 }
1039}
1040
1041fn lower_assert_operand(arg: Arg) -> Arg {
1050 match arg {
1051 Arg::String(text, false) => {
1052 let clean = crate::command::strip_digit_separators(&text);
1057 if let Ok(i) = clean.parse::<i64>() {
1058 Arg::Expr(Expr::Literal(Value::int(i)))
1059 } else if clean.contains('.') && clean.parse::<f64>().is_ok() {
1060 Arg::Expr(Expr::Literal(Value::float(
1061 clean.parse::<f64>().unwrap_or(f64::NAN),
1062 )))
1063 } else if text == "true" {
1064 Arg::Expr(Expr::Literal(Value::bool(true)))
1065 } else if text == "false" {
1066 Arg::Expr(Expr::Literal(Value::bool(false)))
1067 } else {
1068 Arg::String(text, false)
1069 }
1070 }
1071 other => other,
1072 }
1073}
1074
1075fn lower_equality_args(
1080 verb: &str,
1081 flags: Vec<(String, Arg)>,
1082 args: Vec<Arg>,
1083) -> ParseResult<(Option<String>, AssertTarget, Option<Arg>)> {
1084 let hash = flags
1085 .iter()
1086 .find(|(k, _)| k == "hash")
1087 .map(|(_, v)| v.as_str().to_string());
1088 let mut it = args.into_iter();
1089 let actual = lower_assert_target(it.next().ok_or_else(|| {
1090 ParseError::validation(
1091 verb,
1092 format!("{verb} requires a value"),
1093 &SpanContext::line_only(0),
1094 )
1095 })?)?;
1096 let remaining: Vec<Arg> = it.map(lower_assert_operand).collect::<Vec<Arg>>();
1097 let expected = if remaining.is_empty() {
1098 if hash.is_some() {
1099 None
1100 } else {
1101 return Err(ParseError::validation(
1102 verb,
1103 format!("{verb} requires an expected value"),
1104 &SpanContext::line_only(0),
1105 ));
1106 }
1107 } else {
1108 if hash.is_some() {
1109 return Err(ParseError::validation(
1110 verb,
1111 format!("{verb} --hash cannot be combined with an expected value"),
1112 &SpanContext::line_only(0),
1113 ));
1114 }
1115 Some(join_value(remaining, verb)?)
1116 };
1117 Ok((hash, actual, expected))
1118}
1119
1120declare_commands! {
1121 structural [
1122 WithIo { bindings: Vec<IoBinding>, cmd: Box<StepKind> },
1123 WithIoBlock { bindings: Vec<IoBinding> },
1124 TypeAlias { name: String, target: String },
1125 For { key_var: Option<String>, key_type: Option<String>, var: String, var_type: String, in_expr: Expr, body: Vec<Step> },
1126 If { cond: Box<Expr>, then_body: Vec<Step>, else_ifs: Vec<(Box<Expr>, Vec<Step>)>, else_body: Option<Vec<Step>> },
1127 Assign { var: String, decl_type: String, expr: Expr },
1128 Set { var: String, expr: Expr },
1129 AssignCapture { var: String, decl_type: String, cmd: Box<StepKind> },
1130 AwaitCapture { out_var: String, out_type: String, task_var: String },
1131 AsyncBlock { body: Vec<Step> },
1132 AssignAsync { var: String, decl_type: String, body: Vec<Step> },
1133 Await { var: String },
1134 Cancel { var: String },
1135 Timeout { duration: Arg, body: Vec<Step> },
1136 Isolated { body: Vec<Step> },
1137 IsolatedInheritEnv { keys: Vec<String> },
1138 RemoteBlock { target: String, vars: Vec<String>, env: Vec<String>, body: Vec<Step> },
1139 RunExec { argv: Vec<Arg> },
1140 FuncDef { name: String, params: Vec<(String, String)>, body: Vec<Step>, docs: Option<(String, String)> },
1141 Call { name: String, args: Vec<Expr> },
1142 Return { expr: Box<Expr> },
1143 ImportFile { path: String, alias: String },
1144 ImportFuncs {
1145 path: String,
1146 alias: Option<String>,
1147 func_names: Vec<String>,
1148 type_names: Vec<String>,
1149 },
1150 While { cond: Box<Expr>, body: Vec<Step> },
1151 Break,
1152 Continue,
1153 ]
1154
1155 Workdir => [
1156 name: "WORKDIR",
1157 variant: Workdir(Arg),
1158 syntax: "WORKDIR <path>",
1159 summary: "Change the working directory.",
1160 description: indoc! {r#"
1161 Sets the current working directory.
1162
1163 Relative paths resolve against the current directory; `/` resets to
1164 the workspace root. Paths cannot escape the workspace.
1165 "#},
1166 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Directory to change to", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1167 flags: &[],
1168 default_output: None,
1169 examples: &[ Example { name: "change working directory", fence_meta: None, code: indoc! {r#"
1170 # Later relative paths resolve under the new directory.
1171 WORKDIR project/src
1172 WRITE generated.txt generated-under-workdir
1173
1174 LET $body: STRING = READ generated.txt
1175 ASSERT_EQ $body "generated-under-workdir"
1176 "#} }, Example { name: "workdir in a scoped block", fence_meta: None, code: indoc! {r#"
1177 # The block reverts to the starting directory on exit.
1178 LET $outside: STRING = CWD
1179 MKDIR project
1180
1181 [bool:true] {
1182 WORKDIR project
1183 WRITE inner.txt inner
1184 }
1185
1186 LET $back: STRING = CWD
1187 ASSERT_EQ $back $outside
1188 LET $body: STRING = READ project/inner.txt
1189 ASSERT_EQ $body "inner"
1190 "#} } ],
1191 lower: |_flags, args| {
1192 let path = args.into_iter().next().ok_or_else(|| ParseError::validation("WORKDIR", "WORKDIR requires a path".to_string(), &SpanContext::line_only(0)))?;
1193 Ok(StepKind::Workdir(path))
1194 },
1195 ],
1196
1197 Workspace => [
1198 name: "WORKSPACE",
1199 variant: Workspace(WorkspaceTarget),
1200 syntax: "WORKSPACE (SNAPSHOT|LOCAL|CACHE|SYSTEM) [--local]",
1201 summary: "Switch workspace roots.",
1202 description: indoc! {r#"
1203 Switches the workspace root. The selection reverts at scope
1204 exit like `WORKDIR`.
1205
1206 - `SNAPSHOT`: the materialized build snapshot (the default).
1207 One session-shared directory: every selection resolves to
1208 it, in any block.
1209 - `LOCAL`: the local workspace directory.
1210 - `CACHE`: a persistent per-project directory shared across
1211 runs, never evicted. It lives under the OS user cache
1212 (`OXDOCK_CACHE_DIR` pins an exact directory);
1213 `WORKSPACE CACHE --local` keeps it in
1214 `<project>/.cache/workspace` instead.
1215 - `SYSTEM`: full filesystem access. Scripts using it are not
1216 hermetic.
1217 "#},
1218 args: &[ ArgSpec { name: "target", arg_type: ArgType::OneOf(&["SNAPSHOT", "LOCAL", "CACHE", "SYSTEM"]), description: "Target root", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1219 flags: &[ FlagSpec { name: "local", long: "--local", value_type: FlagValueType::Flag, required: false, description: "Use the project-local cache directory instead of the OS user cache (CACHE only)" } ],
1220 default_output: None,
1221 examples: &[ Example { name: "switch roots", fence_meta: None, code: indoc! {r#"
1222 IMPORT [STD]
1223 WORKSPACE LOCAL
1224
1225 LET $t: STRING = PATH_TYPE(".")
1226 ASSERT_EQ $t "dir"
1227 "#} }, Example { name: "workspace cache in a scoped block", fence_meta: None, code: indoc! {r#"
1228 [bool:true] {
1229 WORKSPACE CACHE
1230 WRITE cached.txt cached-content
1231 }
1232
1233 COPY --from-workspace CACHE cached.txt restored.txt
1234 LET $body: STRING = READ restored.txt
1235 ASSERT_EQ $body "cached-content"
1236 "#} } ],
1237 lower: |flags, args| {
1238 let local = flags.iter().any(|(k, _)| k == "local");
1239 let target = args.into_iter().next().ok_or_else(|| ParseError::validation("WORKSPACE", "WORKSPACE requires a target".to_string(), &SpanContext::line_only(0)))?;
1240 match target.as_str() {
1241 "SNAPSHOT" | "LOCAL" | "SYSTEM" if local => Err(ParseError::validation("WORKSPACE", "WORKSPACE --local requires CACHE".to_string(), &SpanContext::line_only(0))),
1242 "SNAPSHOT" => Ok(StepKind::Workspace(WorkspaceTarget::Snapshot)),
1243 "LOCAL" => Ok(StepKind::Workspace(WorkspaceTarget::Local)),
1244 "CACHE" => Ok(StepKind::Workspace(WorkspaceTarget::Cache { local })),
1245 "SYSTEM" => Ok(StepKind::Workspace(WorkspaceTarget::System)),
1246 other => Err(ParseError::validation("WORKSPACE", format!("unknown workspace target: {other}"), &SpanContext::line_only(0))),
1247 }
1248 },
1249 ],
1250
1251 Env => [
1252 name: "ENV",
1253 variant: Env { key: String, value: Arg },
1254 syntax: "ENV KEY=value",
1255 summary: "Set an environment variable.",
1256 description: indoc! {r#"
1257 Inserts or updates an env var.
1258
1259 The value uses the unified string-value rules shared by every command:
1260 `"..."` or `'...'` quotes keep exact bytes (spaces, tabs), a lone `$var`
1261 evaluates that variable, `{{ ... }}` placeholders interpolate, unquoted
1262 words join with single spaces, and the first `=` splits key from value
1263 (`KEY=a=b` stores `a=b`).
1264
1265 A `$var` inside larger text stays literal — write `{{ $var }}` to
1266 interpolate there.
1267 "#},
1268 args: &[ ArgSpec { name: "assignment", arg_type: ArgType::String, description: "KEY=value pair; the value resolves as STRING", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1269 flags: &[],
1270 default_output: None,
1271 examples: &[
1272 Example { name: "set env", fence_meta: None, code: indoc! {r#"
1273 ENV APP_MODE=production
1274 LET $mode: STRING = env:APP_MODE
1275 ASSERT_EQ $mode "production"
1276 "#} },
1277 Example { name: "quoted value with spaces", fence_meta: None, code: indoc! {r#"
1278 # Quotes keep the space: SET_FORTH stores `outer scope`.
1279 ENV SET_FORTH="outer scope"
1280 WRITE out.txt "{{ env:SET_FORTH }}"
1281
1282 LET $body: STRING = READ out.txt
1283 ASSERT_EQ $body "outer scope"
1284 "#} },
1285 Example { name: "variable value", fence_meta: None, code: indoc! {r#"
1286 # A lone $var evaluates, like ECHO $var.
1287 LET $who: STRING = "Alice"
1288 ENV GREETING=$who
1289 WRITE out.txt "{{ env:GREETING }}"
1290
1291 LET $body: STRING = READ out.txt
1292 ASSERT_EQ $body "Alice"
1293 "#} },
1294 Example { name: "all value forms agree", fence_meta: None, code: indoc! {r#"
1295 # A bare variable, a quoted literal, and a template all
1296 # store plain strings through the same value rules.
1297 LET $x: STRING = "Ada"
1298 ENV A=$x
1299 ENV B="hello world"
1300 ENV C="{{ $x }} concatenated"
1301 WRITE check.txt "{{ env:A }}|{{ env:B }}|{{ env:C }}"
1302
1303 LET $body: STRING = READ check.txt
1304 ASSERT_EQ $body "Ada|hello world|Ada concatenated"
1305 "#} },
1306 Example { name: "scoped env reverts", fence_meta: None, code: indoc! {r#"
1307 # ENV inside a braced block reverts when the block exits
1308 ENV MODE=production
1309
1310 [bool:true] {
1311 ENV MODE=staging
1312 WRITE inner.txt "{{ env:MODE }}"
1313 }
1314
1315 WRITE outer.txt "{{ env:MODE }}"
1316
1317 LET $inner_body: STRING = READ inner.txt
1318 ASSERT_EQ $inner_body "staging"
1319
1320 LET $outer_body: STRING = READ outer.txt
1321 ASSERT_EQ $outer_body "production"
1322 "#} },
1323 Example { name: "shell reads env per platform", fence_meta: None, code: indoc! {r#"
1324 # A shell command reads its own environment, with
1325 # per-platform spelling: quoted "$VAR" passes the parser
1326 # through untouched on Unix ...
1327 ENV PROXY_PORT=23791
1328
1329 [family:unix] LET $o: STRING = RUN echo serving on "$PROXY_PORT"
1330
1331 # ... while cmd expands %VAR% on Windows.
1332 [family:windows] LET $o: STRING = RUN echo serving on %PROXY_PORT%
1333
1334 ASSERT_CONTAINS $o "23791"
1335 "#} },
1336 ],
1337 lower: |_flags, args| lower_env_assignment(args),
1338 ],
1339
1340 InheritEnv => [
1341 name: "INHERIT_ENV",
1342 variant: InheritEnv { keys: Vec<String> },
1343 syntax: "INHERIT_ENV [<key>, ...]",
1344 summary: "Inherit env vars from host.",
1345 description: indoc! {r#"
1346 Declares which host environment variables to inherit into the script.
1347
1348 Must appear before any other commands. Several directives may
1349 appear so platform-specific names ride explicit guards
1350 (`[family:windows] INHERIT_ENV [USERPROFILE]`); each guarded
1351 line runs only when its guard passes.
1352
1353 Sandbox defaults need no declaration: loader bindings,
1354 terminal defaults, the host lookup path, and the user's
1355 profile locations seed automatically. See OxDock
1356 Environment Variable Contracts for the exact list, which grows with the
1357 engine.
1358
1359 Secrets and tool config stay opt-in here: a token or a
1360 `CARGO_HOME` override arrives only through this directive.
1361 "#},
1362 args: &[ ArgSpec { name: "keys", arg_type: ArgType::Rest(&ArgType::String), description: "Host variables to inherit", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
1363 flags: &[],
1364 default_output: None,
1365 examples: &[ Example { name: "inherit env", fence_meta: None, code: indoc! {r#"
1366 [family:unix] INHERIT_ENV [HOME]
1367 LET $path: STRING = env:PATH
1368 [family:unix] ASSERT_CONTAINS $path ":"
1369 [family:windows] ASSERT_CONTAINS $path ";"
1370 "#} } ],
1371 lower: |_flags, args| {
1372 let keys = args.into_iter().map(|a| a.as_str().to_string()).collect();
1373 Ok(StepKind::InheritEnv { keys })
1374 },
1375 ],
1376
1377 Echo => [
1378 name: "ECHO",
1379 variant: Echo(Arg),
1380 syntax: "ECHO <message>",
1381 summary: "Print to stdout.",
1382 description: "Outputs message to stdout.",
1383 args: &[ ArgSpec { name: "message", arg_type: ArgType::Rest(&ArgType::String), description: "Text", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1384 flags: &[],
1385 default_output: Some(Stream::Stdout),
1386 examples: &[
1387 Example { name: "echo", fence_meta: None, code: indoc! {r#"
1388 ECHO build-complete
1389 ASSERT_CONTAINS stdout "build-complete"
1390 "#} },
1391 Example { name: "variables", fence_meta: None, code: indoc! {r#"
1392 # {{ }} interpolates inside text; a lone $var evaluates on its own.
1393 LET $x: STRING = "World"
1394 ECHO "braced:{{ $x }}"
1395 ECHO $x
1396 ASSERT_EQ stdout "braced:World\nWorld\n"
1397 "#} },
1398 Example { name: "interpolation", fence_meta: None, code: indoc! {r#"
1399 # `{{ env:KEY }}` reads the script environment; a bare name
1400 # resolves a DSL variable instead. Spelling rules:
1401 # `script_env:` is always case-sensitive; `env:` is
1402 # case-sensitive too, except on Windows where it matches
1403 # case-insensitively. Every read must be declared first:
1404 # KEY here comes from the ENV below.
1405 ENV USER=OxDock
1406 LET $WHO: STRING = "Ada"
1407 ECHO "Hello {{ env:USER }}! Hi {{ WHO }}! Again {{ script_env:USER }}!"
1408 ASSERT_CONTAINS stdout "Hello OxDock! Hi Ada! Again OxDock!"
1409 "#} },
1410 Example { name: "undeclared env read fails", fence_meta: Some("expect_error:\"env:OXDOCK_DOC_NO_SUCH_KEY\""), code: indoc! {r#"
1411 # No declaration anywhere: the whole-closure static gate
1412 # rejects the read before the first step runs. (The
1413 # error names the variable: undeclared environment
1414 # variable `env:OXDOCK_DOC_NO_SUCH_KEY`.)
1415 ECHO "Hello {{ env:OXDOCK_DOC_NO_SUCH_KEY }}!"
1416 "#} },
1417 ],
1418 lower: |_flags, args| Ok(StepKind::Echo(join_value(args, "ECHO")?)),
1419 ],
1420
1421 Run => [
1422 name: "RUN",
1423 variant: Run(Arg),
1424 syntax: "RUN <command...> | RUN [\"exe\", \"arg\", ...]",
1425 summary: "Execute shell command or direct executable.",
1426 description: indoc! {r#"
1427 Shell form (`RUN <command...>`) runs the joined command string in the
1428 batch shell (`sh -c` / `cmd /C`). Never the operator's login
1429 shell: login shells re-pollute scrubbed children from system
1430 profiles and break script portability, so step execution is
1431 pinned to POSIX `sh` (interactive `oxdock --shell` still uses
1432 `$SHELL`).
1433
1434 Exec form (`RUN ["exe", "arg", ...]`) spawns the executable directly
1435 with no shell, so there is no shell expansion, globbing, redirection,
1436 or pipes; use it for portable commands.
1437
1438 Guards and wrappers (`ASYNC`, `TIMEOUT`, `WITH_IO`, `LET`) apply to
1439 both forms.
1440 "#},
1441 args: &[ ArgSpec { name: "command", arg_type: ArgType::Rest(&ArgType::String), description: "Command", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1442 flags: &[],
1443 default_output: None,
1444 examples: &[ Example { name: "run", fence_meta: None, code: indoc! {r#"
1445 # Spawned children resolve through the seeded host PATH:
1446 # closed child env is the default, not ambient inherit.
1447 RUN echo hello
1448
1449 # Captured runs prove the output, not just the exit status.
1450 LET $o: STRING = RUN echo hello
1451 ASSERT_CONTAINS $o "hello"
1452 "#} }, Example { name: "run exec form", fence_meta: None, code: indoc! {r#"
1453 # No shell: `>` stays a literal argument, so no file is created.
1454 # Toolchain spawns bridge the host home explicitly: rustup
1455 # shims resolve toolchains through the host home.
1456 IMPORT [STD]
1457 [family:unix] INHERIT_ENV [HOME]
1458 [family:windows] INHERIT_ENV [USERPROFILE]
1459 RUN ["cargo", "--version", ">", "x.txt"]
1460 ASSERT_CONTAINS stdout "cargo"
1461
1462 LET $t: STRING = PATH_TYPE("x.txt")
1463 ASSERT_EQ $t "absent"
1464 "#} } ],
1465 lower: |_flags, args| match args.as_slice() {
1466 [Arg::Expr(Expr::List(elems))] if elems.is_empty() => {
1467 Err(ParseError::validation("RUN", "RUN requires at least one argument".to_string(), &SpanContext::line_only(0)))
1468 }
1469 [Arg::Expr(Expr::List(elems))] => Ok(StepKind::RunExec {
1470 argv: elems.iter().cloned().map(Arg::Expr).collect(),
1471 }),
1472 _ => Ok(StepKind::Run(join_value(args, "RUN")?)),
1473 },
1474 ],
1475
1476 Copy => [
1477 name: "COPY",
1478 variant: Copy { from_workspace: Option<WorkspaceTarget>, from_host: bool, to_host: bool, from: Arg, to: Arg },
1479 syntax: "COPY [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] [--from-host | --to-host] <from> <to>",
1480 summary: "Copy file into workspace.",
1481 description: "Copies from host (the source is never moved or modified). Docker destination semantics: a file copied onto a directory (an existing one, or a trailing-slash spell like `out/`) is duplicated inside it under its own basename; a directory source duplicates its contents into the destination; any other destination path is created holding the copied bytes.",
1482 args: &[
1483 ArgSpec { name: "from", arg_type: ArgType::Path, description: "Source", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1484 ArgSpec { name: "to", arg_type: ArgType::Path, description: "Dest", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1485 ],
1486 flags: &[ FlagSpec { name: "from_workspace", long: "--from-workspace", value_type: FlagValueType::String, required: false, description: "Copy from the given workspace root instead of the build context" }, FlagSpec { name: "from_host", long: "--from-host", value_type: FlagValueType::Flag, required: false, description: "Fetch from the host workspace into the guest (REMOTE bodies only)" }, FlagSpec { name: "to_host", long: "--to-host", value_type: FlagValueType::Flag, required: false, description: "Push from the guest workspace back to the host (REMOTE bodies only)" } ],
1487 default_output: None,
1488 examples: &[ Example { name: "copy", fence_meta: Some("roots:unified"), code: indoc! {r#"
1489 # Copy to a new name, then read back.
1490 WRITE src.txt content
1491 COPY src.txt dst.txt
1492
1493 LET $body: STRING = READ dst.txt
1494 ASSERT_EQ $body "content"
1495 "#} }, Example { name: "copy from workspace", fence_meta: None, code: indoc! {r#"
1496 # Same name, different contents per root: only LOCAL has ws-content.
1497 WRITE shared.txt from-snapshot
1498 WORKSPACE LOCAL
1499 WRITE shared.txt ws-content
1500
1501 WORKSPACE SNAPSHOT
1502 COPY --from-workspace LOCAL shared.txt ws-copy.txt
1503
1504 LET $body: STRING = READ ws-copy.txt
1505 ASSERT_EQ $body "ws-content"
1506 "#} } ],
1507 lower: |flags, args| {
1508 let from_workspace = flags
1509 .iter()
1510 .find(|(k, _)| k == "from_workspace")
1511 .map(|(_, v)| match v.as_str() {
1512 "SNAPSHOT" => Ok(WorkspaceTarget::Snapshot),
1513 "LOCAL" => Ok(WorkspaceTarget::Local),
1514 "CACHE" => Ok(WorkspaceTarget::Cache { local: false }),
1515 "SYSTEM" => Ok(WorkspaceTarget::System),
1516 other => Err(ParseError::validation("COPY", format!("unknown workspace source: {other}"), &SpanContext::line_only(0))),
1517 })
1518 .transpose()?;
1519 let mut it = args.into_iter();
1520 let from = it.next().ok_or_else(|| ParseError::validation("COPY", "COPY requires a source".to_string(), &SpanContext::line_only(0)))?;
1521 let to = it.next().ok_or_else(|| ParseError::validation("COPY", "COPY requires a destination".to_string(), &SpanContext::line_only(0)))?;
1522 let from_host = flags.iter().any(|(k, _)| k == "from_host");
1523 let to_host = flags.iter().any(|(k, _)| k == "to_host");
1524 if from_host && to_host {
1525 return Err(ParseError::validation("COPY", "COPY --from-host and --to-host are mutually exclusive".to_string(), &SpanContext::line_only(0)));
1526 }
1527 Ok(StepKind::Copy { from_workspace, from_host, to_host, from, to })
1528 },
1529 ],
1530
1531 CopyGit => [
1532 name: "COPY_GIT",
1533 variant: CopyGit { rev: Arg, from: Arg, to: Arg, include_dirty: bool },
1534 syntax: "COPY_GIT [--include-dirty] <rev> <src> <dst>",
1535 summary: "Copy from git revision.",
1536 description: "Checkout and copy.",
1537 args: &[
1538 ArgSpec { name: "rev", arg_type: ArgType::String, description: "Rev", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1539 ArgSpec { name: "src", arg_type: ArgType::Path, description: "Src", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
1540 ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Dst", io: IoDirection::Write, index: 2, required: true, fallback_stream: None },
1541 ],
1542 flags: &[ FlagSpec { name: "dirty", long: "--include-dirty", value_type: FlagValueType::Flag, required: false, description: "Include dirty" } ],
1543 default_output: None,
1544 examples: &[ Example { name: "git copy missing source errors", fence_meta: Some("expect_error:\"COPY source missing\""), code: indoc! {r#"COPY_GIT HEAD src.txt dst.txt"#} } ],
1545 lower: |flags, args| {
1546 let include_dirty = flags.iter().any(|(k, _)| k == "dirty");
1547 let mut it = args.into_iter();
1548 let rev = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a revision".to_string(), &SpanContext::line_only(0)))?;
1549 let from = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a source".to_string(), &SpanContext::line_only(0)))?;
1550 let to = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a destination".to_string(), &SpanContext::line_only(0)))?;
1551 Ok(StepKind::CopyGit { rev, from, to, include_dirty })
1552 },
1553 ],
1554
1555 Symlink => [
1556 name: "SYMLINK",
1557 variant: Symlink { from_workspace: Option<WorkspaceTarget>, from: Arg, to: Arg },
1558 syntax: "SYMLINK [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>",
1559 summary: "Create symlink.",
1560 description: "Creates symlink. A directory destination (existing, or a trailing-slash spell) receives the link under the source basename.",
1561 args: &[
1562 ArgSpec { name: "from", arg_type: ArgType::Path, description: "Target", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1563 ArgSpec { name: "to", arg_type: ArgType::Path, description: "Link", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1564 ],
1565 flags: &[ FlagSpec { name: "from_workspace", long: "--from-workspace", value_type: FlagValueType::String, required: false, description: "Symlink from the given workspace root instead of the build context" } ],
1566 default_output: None,
1567 examples: &[ Example { name: "symlink", fence_meta: Some("roots:unified"), code: indoc! {r#"
1568 # A symlink reads like its target.
1569 WRITE original.txt content
1570 SYMLINK original.txt link.txt
1571
1572 LET $body: STRING = READ link.txt
1573 ASSERT_EQ $body "content"
1574 "#} }, Example { name: "symlink from workspace", fence_meta: None, code: indoc! {r#"
1575 # Same name, different contents per root: only LOCAL has ws-content.
1576 WRITE shared.txt from-snapshot
1577 WORKSPACE LOCAL
1578 WRITE shared.txt ws-content
1579
1580 WORKSPACE SNAPSHOT
1581 SYMLINK --from-workspace LOCAL shared.txt ws-link.txt
1582
1583 LET $body: STRING = READ ws-link.txt
1584 ASSERT_EQ $body "ws-content"
1585 "#} } ],
1586 lower: |flags, args| {
1587 let from_workspace = flags
1588 .iter()
1589 .find(|(k, _)| k == "from_workspace")
1590 .map(|(_, v)| match v.as_str() {
1591 "SNAPSHOT" => Ok(WorkspaceTarget::Snapshot),
1592 "LOCAL" => Ok(WorkspaceTarget::Local),
1593 "CACHE" => Ok(WorkspaceTarget::Cache { local: false }),
1594 "SYSTEM" => Ok(WorkspaceTarget::System),
1595 other => Err(ParseError::validation("SYMLINK", format!("unknown workspace source: {other}"), &SpanContext::line_only(0))),
1596 })
1597 .transpose()?;
1598 let mut it = args.into_iter();
1599 let from = it.next().ok_or_else(|| ParseError::validation("SYMLINK", "SYMLINK requires a source".to_string(), &SpanContext::line_only(0)))?;
1600 let to = it.next().ok_or_else(|| ParseError::validation("SYMLINK", "SYMLINK requires a target".to_string(), &SpanContext::line_only(0)))?;
1601 Ok(StepKind::Symlink { from_workspace, from, to })
1602 },
1603 ],
1604
1605 Mkdir => [
1606 name: "MKDIR",
1607 variant: Mkdir(Arg),
1608 syntax: "MKDIR <path>",
1609 summary: "Create directory.",
1610 description: "Creates dir with parents.",
1611 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Dir path", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1612 flags: &[],
1613 default_output: None,
1614 examples: &[ Example { name: "mkdir", fence_meta: None, code: indoc! {r#"
1615 IMPORT [STD]
1616 MKDIR deeply/nested/tree
1617
1618 LET $t: STRING = PATH_TYPE("deeply/nested/tree")
1619 ASSERT_EQ $t "dir"
1620 "#} } ],
1621 lower: |_flags, args| Ok(StepKind::Mkdir(args.into_iter().next().ok_or_else(|| ParseError::validation("MKDIR", "MKDIR requires a path".to_string(), &SpanContext::line_only(0)))?)),
1622 ],
1623
1624 Install => [
1625 name: "INSTALL",
1626 variant: Install { from: Arg, to: Arg },
1627 syntax: "INSTALL <source> <dest>",
1628 summary: "Atomically install a verified binary as executable.",
1629 description: "Stages the source as a temp file in the dest dir, sets executable mode, then renames into place.",
1630 args: &[
1631 ArgSpec { name: "from", arg_type: ArgType::Path, description: "Source file", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1632 ArgSpec { name: "to", arg_type: ArgType::Path, description: "Dest file", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1633 ],
1634 flags: &[],
1635 default_output: None,
1636 examples: &[ Example { name: "install", fence_meta: Some("roots:unified"), code: indoc! {r#"
1637 # Place a verified binary with executable mode.
1638 IMPORT [STD]
1639 WRITE src.bin payload
1640 INSTALL src.bin dst-bin/tool
1641
1642 LET $t: STRING = PATH_TYPE("dst-bin/tool")
1643 ASSERT_EQ $t "file"
1644 "#} } ],
1645 lower: |_flags, args| {
1646 let mut it = args.into_iter();
1647 let from = it.next().ok_or_else(|| ParseError::validation("INSTALL", "INSTALL requires a source".to_string(), &SpanContext::line_only(0)))?;
1648 let to = it.next().ok_or_else(|| ParseError::validation("INSTALL", "INSTALL requires a destination".to_string(), &SpanContext::line_only(0)))?;
1649 Ok(StepKind::Install { from, to })
1650 },
1651 ],
1652
1653 Archive => [
1654 name: "ARCHIVE",
1655 variant: Archive { src: Arg, dst: Arg, raw: bool },
1656 syntax: "ARCHIVE [--raw] <src> <dst>",
1657 summary: "Pack a file or directory into a tarball.",
1658 description: indoc! {r#"
1659 Packs a file or directory into a tarball, gzip-compressed by
1660 default (`--raw` writes an uncompressed tar instead).
1661
1662 A lone file packs as a single top-level entry under its
1663 basename; a directory recurses, preserving empty dirs. Source
1664 modes ride in the headers on Unix, so system `tar` restores
1665 them elsewhere. Symlink sources refuse: archives cross trust
1666 boundaries, so links never resolve into member bytes. Hashing
1667 stays with `HASH_SHA256`, which reads the finished archive
1668 like any other file.
1669 "#},
1670 args: &[
1671 ArgSpec { name: "src", arg_type: ArgType::Path, description: "File or directory to pack", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1672 ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Archive file to write", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1673 ],
1674 flags: &[ FlagSpec { name: "raw", long: "--raw", value_type: FlagValueType::Flag, required: false, description: "Write an uncompressed tar instead of gzip" } ],
1675 default_output: None,
1676 examples: &[ Example { name: "archive directory", fence_meta: None, code: indoc! {r#"
1677 # Stage a small tree to pack.
1678 WRITE bundle/app.txt bundled-payload
1679 WRITE bundle/nested/deep.txt deep-payload
1680
1681 # ARCHIVE packs it gzip-compressed by default.
1682 ARCHIVE bundle bundle.tar.gz
1683
1684 # UNARCHIVE restores the tree under the destination.
1685 UNARCHIVE bundle.tar.gz restored
1686
1687 # The payloads arrive byte-identical.
1688 LET $body: STRING = READ restored/app.txt
1689 ASSERT_EQ $body "bundled-payload"
1690
1691 LET $deep: STRING = READ restored/nested/deep.txt
1692 ASSERT_EQ $deep "deep-payload"
1693 "#} }, Example { name: "archive raw", fence_meta: None, code: indoc! {r#"
1694 # A lone file packs as a single top-level entry.
1695 WRITE tool.bin tool-payload
1696
1697 # Raw archives skip gzip and stay readable by any tar.
1698 ARCHIVE --raw tool.bin tool.tar
1699 UNARCHIVE tool.tar tool-out
1700
1701 # The entry lands under its basename.
1702 LET $body: STRING = READ tool-out/tool.bin
1703 ASSERT_EQ $body "tool-payload"
1704 "#} } ],
1705 lower: |flags, args| {
1706 let raw = flags.iter().any(|(k, _)| k == "raw");
1707 let mut it = args.into_iter();
1708 let src = it.next().ok_or_else(|| ParseError::validation("ARCHIVE", "ARCHIVE requires a source".to_string(), &SpanContext::line_only(0)))?;
1709 let dst = it.next().ok_or_else(|| ParseError::validation("ARCHIVE", "ARCHIVE requires a destination".to_string(), &SpanContext::line_only(0)))?;
1710 Ok(StepKind::Archive { src, dst, raw })
1711 },
1712 ],
1713
1714 Unarchive => [
1715 name: "UNARCHIVE",
1716 variant: Unarchive { src: Arg, dst: Arg, max_bytes: Option<Arg> },
1717 syntax: "UNARCHIVE <src> <dst> [--max-bytes <bytes>]",
1718 summary: "Unpack a tarball into a directory.",
1719 description: indoc! {r#"
1720 Unpacks a tarball under the destination directory, creating
1721 it first. Gzip and raw (`ARCHIVE --raw`) tarballs
1722 self-identify by magic bytes, so no flag is needed.
1723
1724 Member bytes meter against a 1 GiB default expansion cap
1725 across the whole archive: a decompression bomb trips it
1726 instead of filling the disk, and `--max-bytes` moves the
1727 ceiling either way (plain integer bytes). The tripped member
1728 stays truncated on disk while the step fails loudly.
1729
1730 Symlink and special members refuse naming the entry, and
1731 absolute or escaping paths fail closed before any byte
1732 lands: the member sanitizer plus the destination join check
1733 form two independent walls. Unix modes recorded in the
1734 headers restore on unpack; other platforms land default
1735 modes (confer executability with `INSTALL` there).
1736 "#},
1737 args: &[
1738 ArgSpec { name: "src", arg_type: ArgType::Path, description: "Archive file to unpack", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1739 ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Directory to unpack under", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1740 ],
1741 flags: &[ FlagSpec { name: "max_bytes", long: "--max-bytes", value_type: FlagValueType::String, required: false, description: "Cap total unpacked member bytes: bare digits are bytes (`1_000_000` grouping allowed), suffixes B/KB/MB/GB/TB (decimal) and KIB/MIB/GIB/TIB (binary), any case, one optional space before the unit (defaults to 1 GiB)" } ],
1742 default_output: None,
1743 examples: &[ Example { name: "unarchive", fence_meta: None, code: indoc! {r#"
1744 # Pack a note, then restore it under a fresh destination.
1745 WRITE pack/note.txt packed-note
1746 ARCHIVE pack pack.tar.gz
1747 UNARCHIVE pack.tar.gz unpacked
1748
1749 LET $body: STRING = READ unpacked/note.txt
1750 ASSERT_EQ $body "packed-note"
1751 "#} }, Example { name: "unarchive with a lower cap", fence_meta: None, code: indoc! {r#"
1752 # Small payloads clear even a tight ceiling.
1753 WRITE pack/note.txt packed-note
1754 ARCHIVE pack pack.tar.gz
1755 UNARCHIVE pack.tar.gz capped --max-bytes 100KB
1756
1757 LET $body: STRING = READ capped/note.txt
1758 ASSERT_EQ $body "packed-note"
1759 "#} } ],
1760 lower: |flags, args| {
1761 let mut it = args.into_iter();
1762 let src = it.next().ok_or_else(|| ParseError::validation("UNARCHIVE", "UNARCHIVE requires an archive".to_string(), &SpanContext::line_only(0)))?;
1763 let dst = it.next().ok_or_else(|| ParseError::validation("UNARCHIVE", "UNARCHIVE requires a destination".to_string(), &SpanContext::line_only(0)))?;
1764 let max_bytes = flags
1765 .into_iter()
1766 .find_map(|(k, v)| (k == "max_bytes").then_some(v));
1767 if let Some(Arg::String(text, _)) = max_bytes.as_ref()
1771 && !text.contains("{{")
1772 && let Err(e) = crate::command::parse_byte_count(text)
1773 {
1774 return Err(ParseError::validation(
1775 "UNARCHIVE",
1776 format!("UNARCHIVE --max-bytes {e:#}"),
1777 &SpanContext::line_only(0),
1778 ));
1779 }
1780 Ok(StepKind::Unarchive { src, dst, max_bytes })
1781 },
1782 ],
1783
1784 Ls => [
1785 name: "LS",
1786 variant: Ls(Option<Arg>),
1787 syntax: "LS [<path>]",
1788 summary: "List directory.",
1789 description: "Lists entries.",
1790 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Dir", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
1791 flags: &[],
1792 default_output: Some(Stream::Stdout),
1793 examples: &[ Example { name: "ls", fence_meta: None, code: indoc! {r#"
1794 MKDIR inventory
1795 WRITE inventory/a.txt a
1796 LS inventory
1797 ASSERT_CONTAINS stdout "a.txt"
1798 "#} } ],
1799 lower: |_flags, args| Ok(StepKind::Ls(args.into_iter().next())),
1800 ],
1801
1802 Read => [
1803 name: "READ",
1804 variant: Read(Option<Arg>),
1805 syntax: "READ [<path>]",
1806 summary: "Read file to stdout.",
1807 description: "Outputs file contents.",
1808 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
1809 flags: &[],
1810 default_output: Some(Stream::Stdout),
1811 examples: &[ Example { name: "read", fence_meta: None, code: indoc! {r#"
1812 WRITE note.txt "hello"
1813 READ note.txt
1814
1815 LET $body: STRING = READ note.txt
1816 ASSERT_EQ $body "hello"
1817 "#} } ],
1818 lower: |_flags, args| Ok(StepKind::Read(args.into_iter().next())),
1819 ],
1820
1821 ReadLine => [
1822 name: "READ_LINE",
1823 variant: ReadLine { var: String },
1824 syntax: "READ_LINE $var",
1825 summary: "Read one line from stdin into a variable.",
1826 description: indoc! {r#"
1827 Reads bytes until newline without waiting for EOF, leaving the pipe open.
1828
1829 Trailing newline is stripped (shell-read parity). On premature EOF
1830 assigns accumulated bytes and returns.
1831 "#},
1832 args: &[ ArgSpec { name: "var", arg_type: ArgType::String, description: "Target variable (`$name`); the line binds as STRING", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1833 flags: &[],
1834 default_output: None,
1835 examples: &[ Example { name: "read line", fence_meta: None, code: indoc! {r#"
1836 # The trailing newline is stripped: the variable holds exactly `first`.
1837 LET $lines: PIPE
1838 WITH_IO [stdout=$lines] ECHO "first"
1839 WITH_IO [stdin=$lines] READ_LINE $reply
1840 ASSERT_EQ $reply "first"
1841 "#} } ],
1842 lower: |_flags, args| {
1843 let arg = args.into_iter().next().ok_or_else(|| ParseError::validation("READ_LINE", "READ_LINE requires a variable".to_string(), &SpanContext::line_only(0)))?;
1844 let var = match arg {
1845 Arg::Expr(Expr::Var(name)) => name,
1846 Arg::String(s, _) if s.starts_with('$') || s.contains("{{") => s.trim_start_matches('$').to_string(),
1849 other => return Err(ParseError::validation("READ_LINE", format!("READ_LINE requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
1850 };
1851 if var.is_empty() {
1852 return Err(ParseError::validation("READ_LINE", "READ_LINE requires a variable".to_string(), &SpanContext::line_only(0)))
1853 }
1854 Ok(StepKind::ReadLine { var })
1855 },
1856 ],
1857
1858 Prompt => [
1859 name: "PROMPT",
1860 variant: Prompt { var: String, message: Arg, default: Option<Arg> },
1861 syntax: "PROMPT $var <message> [<default>]",
1862 summary: "Prompt on the terminal into a variable.",
1863 description: indoc! {r#"
1864 Prints `{message} [{default}]: ` (or `{message}: ` with no
1865 default) to stderr and reads one line from the terminal.
1866
1867 Empty input yields the default when one is given, else an
1868 empty string. EOF aborts loudly. Non-TTY stdin never reads:
1869 a default binds with a stderr note, while no default bails.
1870 "#},
1871 args: &[
1872 ArgSpec { name: "var", arg_type: ArgType::String, description: "Target variable (`$name`); the answer binds as STRING", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
1873 ArgSpec { name: "message", arg_type: ArgType::String, description: "Prompt message", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
1874 ArgSpec { name: "default", arg_type: ArgType::String, description: "Default on empty input", io: IoDirection::Read, index: 2, required: false, fallback_stream: None },
1875 ],
1876 flags: &[],
1877 default_output: None,
1878 examples: &[ Example { name: "prompt needs a terminal", fence_meta: Some("expect_error:\"non-TTY\""), code: indoc! {r#"
1879 # A redirected stdin can never answer: without a default the
1880 # prompt fails instead of hanging or reading piped stdin.
1881 LET $p: PIPE
1882 WITH_IO [stdin=$p] PROMPT $dir "Install destination?"
1883 "#} } ],
1884 lower: |_flags, args| {
1885 let mut it = args.into_iter();
1886 let var_arg = it.next().ok_or_else(|| ParseError::validation("PROMPT", "PROMPT requires a variable".to_string(), &SpanContext::line_only(0)))?;
1887 let var = match var_arg {
1888 Arg::Expr(Expr::Var(name)) => name,
1889 Arg::String(s, _) if s.starts_with('$') || s.contains("{{") => s.trim_start_matches('$').to_string(),
1890 other => return Err(ParseError::validation("PROMPT", format!("PROMPT requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
1891 };
1892 if var.is_empty() {
1893 return Err(ParseError::validation("PROMPT", "PROMPT requires a variable".to_string(), &SpanContext::line_only(0)))
1894 }
1895 let message = it.next().ok_or_else(|| ParseError::validation("PROMPT", "PROMPT requires a message".to_string(), &SpanContext::line_only(0)))?;
1896 let default = it.next();
1897 Ok(StepKind::Prompt { var, message, default })
1898 },
1899 ],
1900
1901 Write => [
1902 name: "WRITE",
1903 variant: Write { path: Arg, contents: Option<Arg> },
1904 syntax: "WRITE <path> [<contents>]",
1905 summary: "Write to file.",
1906 description: "Writes contents.",
1907 args: &[
1908 ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
1909 ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Content", io: IoDirection::Write, index: 1, required: false, fallback_stream: Some(Stream::Stdin) },
1910 ],
1911 flags: &[],
1912 default_output: None,
1913 examples: &[ Example { name: "write", fence_meta: None, code: indoc! {r#"
1914 WRITE output.txt hello-world
1915 LET $body: STRING = READ output.txt
1916 ASSERT_EQ $body "hello-world"
1917 "#} } ],
1918 lower: |_flags, args| {
1919 let mut it = args.into_iter();
1920 let path = it.next().ok_or_else(|| ParseError::validation("WRITE", "WRITE requires a path".to_string(), &SpanContext::line_only(0)))?;
1921 let remaining: Vec<Arg> = it.collect();
1922 let contents = if remaining.is_empty() { None } else { Some(join_value(remaining, "WRITE")?) };
1923 Ok(StepKind::Write { path, contents })
1924 },
1925 ],
1926
1927 Append => [
1928 name: "APPEND",
1929 variant: Append { path: Arg, contents: Option<Arg> },
1930 syntax: "APPEND <path> [<contents>]",
1931 summary: "Append to file.",
1932 description: "Appends contents.",
1933 args: &[
1934 ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
1935 ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Content", io: IoDirection::Write, index: 1, required: false, fallback_stream: Some(Stream::Stdin) },
1936 ],
1937 flags: &[],
1938 default_output: None,
1939 examples: &[ Example { name: "append", fence_meta: None, code: indoc! {r#"
1940 WRITE log.txt line1
1941 APPEND log.txt line2
1942
1943 # APPEND concatenates with no separator.
1944 LET $all: STRING = READ log.txt
1945 ASSERT_EQ $all "line1line2"
1946 "#} } ],
1947 lower: |_flags, args| {
1948 let mut it = args.into_iter();
1949 let path = it.next().ok_or_else(|| ParseError::validation("APPEND", "APPEND requires a path".to_string(), &SpanContext::line_only(0)))?;
1950 let remaining: Vec<Arg> = it.collect();
1951 let contents = if remaining.is_empty() { None } else { Some(join_value(remaining, "APPEND")?) };
1952 Ok(StepKind::Append { path, contents })
1953 },
1954 ],
1955
1956 Remove => [
1957 name: "REMOVE",
1958 variant: Remove { path: Arg, recursive: bool },
1959 syntax: "REMOVE [--recursive] <path>",
1960 summary: "Remove a file, symlink, or directory.",
1961 description: "Removes a file, symlink (the link itself), or empty dir. With --recursive removes a directory tree.",
1962 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Path to remove", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1963 flags: &[ FlagSpec { name: "recursive", long: "--recursive", value_type: FlagValueType::Flag, required: false, description: "Remove a directory tree" } ],
1964 default_output: None,
1965 examples: &[ Example { name: "remove", fence_meta: None, code: indoc! {r#"
1966 # WRITE then REMOVE leaves nothing behind.
1967 IMPORT [STD]
1968 WRITE scratch.txt content
1969
1970 # Assert original file is written
1971 LET $o: STRING = PATH_TYPE("scratch.txt")
1972 ASSERT_EQ $o "file"
1973
1974 REMOVE scratch.txt
1975
1976 # Assert file has been removed
1977 LET $t: STRING = PATH_TYPE("scratch.txt")
1978 ASSERT_EQ $t "absent"
1979 "#} } ],
1980 lower: |flags, args| {
1981 let recursive = flags.iter().any(|(k, _)| k == "recursive");
1982 let path = args.into_iter().next().ok_or_else(|| ParseError::validation("REMOVE", "REMOVE requires a path".to_string(), &SpanContext::line_only(0)))?;
1983 Ok(StepKind::Remove { path, recursive })
1984 },
1985 ],
1986
1987 Expand => [
1988 name: "EXPAND",
1989 variant: Expand { path: Option<Arg>, overrides: Vec<(String, Arg)> },
1990 syntax: "EXPAND [<path>] [<KEY=val> ...]",
1991 summary: "Expand a template file (or stdin) to stdout.",
1992 description: indoc! {r#"
1993 A template is any text file — or piped stdin when no path is given —
1994 containing `{{ ... }}` placeholders. EXPAND replaces each placeholder
1995 and prints the result to stdout.
1996
1997 Placeholders: `{{ NAME }}` reads a `KEY=val` override passed on this
1998 command; `{{ env:NAME }}` reads an override, falling back to the
1999 environment; `{{ $var }}` reads a script variable (dotted paths allowed).
2000 A missing key is an error, never a silent empty.
2001
2002 Calls: `{{ MODULE::FUNC(args) }}` invokes a pure registry function
2003 with `$var.path` references and `STRING`, `INT`, `FLOAT`, and `BOOL`
2004 literals as arguments. Arguments check against the registered
2005 signature, so wrong arity or mistyped values fail at the call;
2006 unknown names fail listing the known functions. Only pure
2007 functions resolve here: stateful, script-defined, and pipe-backed
2008 entries fail naming themselves, since placeholder evaluation
2009 carries no step context. The same calls resolve in ordinary
2010 strings, so both paths agree.
2011
2012 Substitution runs in a single pass. `EXPAND` is not recursive and does not
2013 expand nested placeholders: a value that itself contains `{{ ... }}` is
2014 inserted verbatim and never expanded again.
2015
2016 A bare `$var` argument is a template path; `KEY=val` arguments are
2017 overrides whose values follow the unified string-value rules (same as
2018 `ENV`: quotes keep exact bytes, a lone `$var` evaluates,
2019 `{{ ... }}` interpolates).
2020
2021 NOTE: `WRITE` interpolates `{{ ... }}` while writing, so escape it
2022 (`\{{ ... }}`) when writing a template file for a later `EXPAND`.
2023
2024 With no path, the template arrives on stdin through a pipe. When piping
2025 from a shell, single-quote the template (`echo '{{ $x }}'`): double
2026 quotes let the shell swallow `$x`, so oxdock receives an empty `{{ }}`
2027 placeholder and errors.
2028 "#},
2029 args: &[
2030 ArgSpec { name: "path", arg_type: ArgType::Path, description: "Template file to expand; omit to expand stdin", io: IoDirection::Read, index: 0, required: false, fallback_stream: None },
2031 ArgSpec { name: "overrides", arg_type: ArgType::Rest(&ArgType::String), description: "Template overrides shadowing that key (unified string values)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
2032 ],
2033 flags: &[],
2034 default_output: Some(Stream::Stdout),
2035 examples: &[
2036 Example { name: "expand", fence_meta: None, code: indoc! {r#"
2037 # Placeholders read overrides first, then the environment.
2038 ENV NAME="Alice"
2039 WRITE template.md "Hello {{ env:NAME }}!"
2040 EXPAND template.md
2041
2042 ASSERT_CONTAINS stdout "Hello Alice!"
2043 "#} },
2044 Example { name: "override with spaces", fence_meta: None, code: indoc! {r#"
2045 # WRITE would interpolate {{ }} right away, so escape it.
2046 # The file must literally contain {{ env:NAME }} for EXPAND.
2047 WRITE template.md "Hello \{{ env:NAME }}!"
2048 EXPAND template.md NAME="Alice Smith"
2049
2050 ASSERT_CONTAINS stdout "Hello Alice Smith!"
2051 "#} },
2052 Example { name: "variable override", fence_meta: None, code: indoc! {r#"
2053 # Same escaping: keep the placeholder literal until EXPAND.
2054 # A lone $who evaluates, like ECHO $who.
2055 LET $who: STRING = "Bob"
2056 WRITE template.md "Hi \{{ env:WHO }}!"
2057 EXPAND template.md WHO=$who
2058
2059 ASSERT_CONTAINS stdout "Hi Bob!"
2060 "#} },
2061 Example { name: "override forms agree", fence_meta: None, code: indoc! {r#"
2062 # A bare variable and a template-with-tail expand identically.
2063 LET $x: STRING = "Ada"
2064 WRITE template.md "Hi \{{ env:NAME }} and \{{ env:NAME2 }}!"
2065 EXPAND template.md NAME=$x NAME2="{{ $x }} concatenated"
2066
2067 ASSERT_CONTAINS stdout "Hi Ada and Ada concatenated!"
2068 "#} },
2069 Example { name: "expand stdin", fence_meta: None, code: indoc! {r#"
2070 # No path: the template arrives on stdin through a pipe.
2071 LET $tpl: PIPE
2072 WITH_IO [stdout=$tpl] ECHO "Hello \{{ env:NAME }}!"
2073 WITH_IO [stdin=$tpl] EXPAND NAME=Alice
2074
2075 ASSERT_CONTAINS stdout "Hello Alice!"
2076 "#} },
2077 Example { name: "override does not leak", fence_meta: None, code: indoc! {r#"
2078 # KEY=val overrides shadow env for that EXPAND only.
2079 # They never update the environment itself.
2080 ENV NAME="Alice"
2081 WRITE template.md "Hi \{{ env:NAME }}!"
2082
2083 EXPAND template.md NAME="Bob"
2084 ASSERT_CONTAINS stdout "Hi Bob!"
2085
2086 EXPAND template.md
2087 ASSERT_CONTAINS stdout "Hi Alice!"
2088 "#} },
2089 Example { name: "function call", fence_meta: None, code: indoc! {r#"
2090 # Pure registry functions run inside placeholders.
2091 # WRITE would interpolate {{ }} right away, so escape it.
2092 IMPORT [STD]
2093 WRITE template.md "Count: \{{ STD::TEXT_COUNT(\"one two two three\", \"two\") }}!"
2094
2095 EXPAND template.md
2096 ASSERT_CONTAINS stdout "Count: 2!"
2097 "#} },
2098 Example { name: "bare override", fence_meta: None, code: indoc! {r#"
2099 # A bare name reads a KEY=val override with no prefix.
2100 WRITE template.md "Hi \{{ NAME }}!"
2101
2102 EXPAND template.md NAME=Ada
2103 ASSERT_CONTAINS stdout "Hi Ada!"
2104 "#} },
2105 Example { name: "variable placeholder", fence_meta: None, code: indoc! {r#"
2106 # `{{ $var }}` placeholders read script variables, dotted
2107 # paths included. Escape at WRITE so EXPAND sees it.
2108 LET $u: MAP<name: STRING> = {name: "Bo"}
2109 WRITE template.md "Hi \{{ $u.name }}!"
2110
2111 EXPAND template.md
2112 ASSERT_CONTAINS stdout "Hi Bo!"
2113 "#} },
2114 Example { name: "missing key fails", fence_meta: Some("expect_error:\"missing required step override argument\""), code: indoc! {r#"
2115 # A missing key is an error, never a silent empty.
2116 WRITE template.md "Hi \{{ NAME }}!"
2117
2118 EXPAND template.md
2119 "#} },
2120 ],
2121 lower: |_flags, args| {
2122 let mut path = None;
2123 let mut overrides = Vec::new();
2124 for arg in args {
2125 let text = arg.as_str();
2126 if let Some((key, value)) = split_assignment(text).map_err(|e| ParseError::validation("EXPAND", e.to_string(), &SpanContext::line_only(0)))? {
2127 overrides.push((key, value));
2128 } else if path.is_none() { path = Some(arg); }
2129 else { return Err(ParseError::validation("EXPAND", "EXPAND accepts at most one path".to_string(), &SpanContext::line_only(0))) }
2130 }
2131 Ok(StepKind::Expand { path, overrides })
2132 },
2133 ],
2134
2135 AssertEq => [
2136 name: Command::AssertEq.as_str(),
2137 variant: AssertEq { hash: Option<String>, actual: AssertTarget, expected: Option<Arg> },
2138 syntax: Command::AssertEq.syntax(),
2139 summary: "Assert strict equality.",
2140 description: indoc! {r#"
2141 Compares two evaluated values with typed equality (no coercion:
2142 `INT(42)` never equals `STRING("42")`), aborting the pipeline
2143 with a step-numbered error showing expected vs actual otherwise.
2144
2145 Both sides are values: `$var`, literals, templates, and calls
2146 evaluate in memory and never touch disk. Read files explicitly
2147 first (`LET $text: STRING = READ "out.txt"`, then
2148 `ASSERT_EQ $text ...`).
2149 Bare `stdout` / `stderr` observe stream buffers; a `$var`
2150 holding a `PIPE` observes its backend bytes. `--hash` compares
2151 the SHA-256 of a string, pipe, or captured-stdout actual
2152 instead of the raw bytes (`stderr` is unsupported).
2153 "#},
2154 args: &[
2155 ArgSpec { name: "actual", arg_type: ArgType::Any, description: "Value, stdout, stderr, or a $var holding a PIPE", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
2156 ArgSpec { name: "expected", arg_type: ArgType::Rest(&ArgType::Any), description: "Expected (required unless --hash)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
2157 ],
2158 flags: &[ FlagSpec { name: "hash", long: "--hash", value_type: FlagValueType::String, required: false, description: "SHA-256" } ],
2159 default_output: None,
2160 examples: &[ Example { name: "assert eq", fence_meta: None, code: indoc! {r#"
2161 LET $status: INT = 200
2162 ASSERT_EQ $status 200
2163 "#} },
2164 Example { name: "assert eq file", fence_meta: None, code: indoc! {r#"
2165 WRITE payload.bin stable-content
2166 LET $body: STRING = READ payload.bin
2167 ASSERT_EQ $body "stable-content"
2168 "#} },
2169 Example { name: "assert eq hash", fence_meta: None, code: indoc! {r#"
2170 # --hash compares the SHA-256 digest instead of raw bytes.
2171 WRITE payload.bin stable-content
2172 LET $body: STRING = READ payload.bin
2173 ASSERT_EQ --hash 08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c $body
2174 "#} } ],
2175 lower: |flags, args| {
2176 let (hash, actual, expected) = lower_equality_args(Command::AssertEq.as_str(), flags, args)?;
2177 Ok(StepKind::AssertEq { hash, actual, expected })
2178 },
2179 ],
2180
2181 AssertNe => [
2182 name: Command::AssertNe.as_str(),
2183 variant: AssertNe { hash: Option<String>, actual: AssertTarget, expected: Option<Arg> },
2184 syntax: Command::AssertNe.syntax(),
2185 summary: "Assert strict inequality.",
2186 description: indoc! {r#"
2187 Compares two evaluated values with typed inequality (no coercion:
2188 `INT(42)` never equals `STRING("42")`), aborting the pipeline
2189 with a step-numbered error showing expected vs actual when they
2190 are equal; differing values pass silently.
2191
2192 Both sides are values: `$var`, literals, templates, and calls
2193 evaluate in memory and never touch disk. Read files explicitly
2194 first (`LET $text: STRING = READ "out.txt"`, then
2195 `ASSERT_NE $text ...`).
2196 Bare `stdout` / `stderr` observe stream buffers; a `$var`
2197 holding a `PIPE` observes its backend bytes. `--hash` compares
2198 the SHA-256 of a string, pipe, or captured-stdout actual
2199 instead of the raw bytes (`stderr` is unsupported); the digest
2200 must differ from the given hash.
2201 "#},
2202 args: &[
2203 ArgSpec { name: "actual", arg_type: ArgType::Any, description: "Value, stdout, stderr, or a $var holding a PIPE", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
2204 ArgSpec { name: "expected", arg_type: ArgType::Rest(&ArgType::Any), description: "Value the actual must differ from (required unless --hash)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
2205 ],
2206 flags: &[ FlagSpec { name: "hash", long: "--hash", value_type: FlagValueType::String, required: false, description: "SHA-256" } ],
2207 default_output: None,
2208 examples: &[ Example { name: "assert ne", fence_meta: None, code: indoc! {r#"
2209 LET $status: INT = 200
2210 ASSERT_NE $status 404
2211 "#} },
2212 Example { name: "assert ne file", fence_meta: None, code: indoc! {r#"
2213 WRITE payload.bin stable-content
2214 LET $body: STRING = READ payload.bin
2215 ASSERT_NE $body "other-content"
2216 "#} },
2217 Example { name: "assert ne hash", fence_meta: None, code: indoc! {r#"
2218 # --hash compares the SHA-256 digest instead of raw bytes.
2219 WRITE payload.bin stable-content
2220 LET $body: STRING = READ payload.bin
2221 ASSERT_NE --hash 0000000000000000000000000000000000000000000000000000000000000000 $body
2222 "#} } ],
2223 lower: |flags, args| {
2224 let (hash, actual, expected) = lower_equality_args(Command::AssertNe.as_str(), flags, args)?;
2225 Ok(StepKind::AssertNe { hash, actual, expected })
2226 },
2227 ],
2228
2229 AssertContains => [
2230 name: Command::AssertContains.as_str(),
2231 variant: AssertContains { haystack: AssertTarget, needle: Arg },
2232 syntax: Command::AssertContains.syntax(),
2233 summary: "Assert containment.",
2234 description: indoc! {r#"
2235 Checks containment and aborts the pipeline with a step-numbered
2236 error otherwise: substring for strings, element match for lists,
2237 key presence for maps, substring over stream and pipe buffers.
2238
2239 Like `ASSERT_EQ`, both sides are values read without implicit
2240 I/O; read files explicitly first
2241 (`LET $text: STRING = READ "cfg.txt"`).
2242 Bare `stdout` / `stderr` observe stream buffers; a `$var`
2243 holding a `PIPE` observes its backend bytes.
2244 "#},
2245 args: &[
2246 ArgSpec { name: "haystack", arg_type: ArgType::Any, description: "Value, stdout, stderr, or a $var holding a PIPE", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
2247 ArgSpec { name: "needle", arg_type: ArgType::Rest(&ArgType::Any), description: "Substring, element, or key", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
2248 ],
2249 flags: &[],
2250 default_output: None,
2251 examples: &[ Example { name: "assert contains", fence_meta: None, code: indoc! {r#"
2252 ECHO build-complete
2253 ASSERT_CONTAINS stdout "build-complete"
2254 "#} } ],
2255 lower: |flags, args| {
2256 let _ = flags;
2257 let mut it = args.into_iter();
2258 let haystack = lower_assert_target(it.next().ok_or_else(|| ParseError::validation(Command::AssertContains.as_str(), format!("{} requires a value", Command::AssertContains.as_str()), &SpanContext::line_only(0)))?)?;
2259 let remaining: Vec<Arg> = it
2260 .map(lower_assert_operand)
2261 .collect::<Vec<Arg>>();
2262 if remaining.is_empty() {
2263 return Err(ParseError::validation(Command::AssertContains.as_str(), format!("{} requires a needle", Command::AssertContains.as_str()), &SpanContext::line_only(0)))
2264 }
2265 let needle = join_value(remaining, Command::AssertContains.as_str())?;
2266 Ok(StepKind::AssertContains { haystack, needle })
2267 },
2268 ],
2269
2270 Exit => [
2271 name: "EXIT",
2272 variant: Exit(Arg),
2273 syntax: "EXIT <code>",
2274 summary: "Exit pipeline.",
2275 description: indoc! {r#"
2276 Stops the pipeline immediately with an `EXIT requested with code <code>`
2277 error; steps after it never run, at any nesting depth.
2278
2279 Enclosing blocks still unwind their LET/ENV/WORKDIR/WORKSPACE state,
2280 anonymous background tasks are killed synchronously, and files written
2281 before the EXIT persist.
2282
2283 The code reaches the OS: the CLI exits with `<code>` clamped to
2284 0..=255, and a guest EXIT relays through `REMOTE` the same way.
2285 "#},
2286 args: &[ ArgSpec { name: "code", arg_type: ArgType::Int, description: "Code", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
2287 flags: &[],
2288 default_output: None,
2289 examples: &[ Example { name: "exit", fence_meta: Some("expect_error:\"EXIT requested with code 0\""), code: indoc! {r#"EXIT 0"#} } ],
2290 lower: |_flags, args| {
2291 let code = args.into_iter().next().ok_or_else(|| ParseError::validation("EXIT", "EXIT requires a code".to_string(), &SpanContext::line_only(0)))?;
2294 Ok(StepKind::Exit(code))
2295 },
2296 ],
2297
2298 Sleep => [
2299 name: "SLEEP",
2300 variant: Sleep { duration: Arg },
2301 syntax: "SLEEP <duration>",
2302 summary: "Pause execution for a duration.",
2303 description: indoc! {r#"
2304 Parks the step for the duration (e.g. 500ms, 10s, 2m).
2305
2306 Cooperative: checks for cancellation so an enclosing TIMEOUT or task
2307 teardown interrupts the sleep. Cross-platform alternative to shell sleep
2308 for testing time boundaries.
2309 "#},
2310 args: &[ ArgSpec { name: "duration", arg_type: ArgType::Duration, description: "How long to sleep", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
2311 flags: &[],
2312 default_output: None,
2313 examples: &[
2314 Example { name: "sleep", fence_meta: None, code: indoc! {r#"SLEEP 100ms"#} },
2315 Example {
2316 name: "sleep variable duration",
2317 fence_meta: None,
2318 code: indoc! {r#"
2319 # Durations resolve at runtime, so variables work too:
2320 # quoted or bare, both bind the same string.
2321 LET $pause: STRING = "100ms"
2322 SLEEP $pause
2323
2324 LET $bare: STRING = 100ms
2325 SLEEP $bare
2326 "#},
2327 },
2328 ],
2329 lower: |_flags, args| {
2330 let mut it = args.into_iter();
2331 let raw = it
2332 .next()
2333 .ok_or_else(|| ParseError::validation("SLEEP", "SLEEP requires a duration (e.g. SLEEP 500ms)".to_string(), &SpanContext::line_only(0)))?;
2334 if it.next().is_some() {
2335 return Err(ParseError::validation("SLEEP", "SLEEP takes exactly one duration argument".to_string(), &SpanContext::line_only(0)))
2336 }
2337 Ok(StepKind::Sleep { duration: raw })
2340 },
2341 ],
2342
2343 ListAppend => [
2344 name: "LIST_APPEND",
2345 variant: ListAppend { list: String, item: Arg },
2346 syntax: "LIST_APPEND $list <item>",
2347 summary: "Append an item to a LIST variable in place.",
2348 description: indoc! {r#"
2349 Appends the item to the LIST variable in place.
2350
2351 When the binding holds the only reference the push runs in
2352 amortized constant time. Aliased buffers detach first, so
2353 other holders keep their contents.
2354 "#},
2355 args: &[
2356 ArgSpec { name: "list", arg_type: ArgType::List, description: "Target LIST variable (`$name`)", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
2357 ArgSpec { name: "item", arg_type: ArgType::Any, description: "Item to append (any value)", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
2358 ],
2359 flags: &[],
2360 default_output: None,
2361 examples: &[ Example { name: "list append", fence_meta: None, code: indoc! {r#"
2362 # Appends accumulate in order.
2363 LET $items: LIST<STRING> = []
2364 LIST_APPEND $items "first"
2365 LIST_APPEND $items "second"
2366
2367 LET $want: LIST<STRING> = ["first", "second"]
2368 ASSERT_EQ $items $want
2369 "#} } ],
2370 lower: |_flags, args| {
2371 let mut it = args.into_iter();
2372 let raw_list = it
2373 .next()
2374 .ok_or_else(|| ParseError::validation("LIST_APPEND", "LIST_APPEND requires a LIST variable (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))?;
2375 let list = match raw_list {
2376 Arg::Expr(Expr::Var(name)) => name,
2377 Arg::String(s, _) => s.trim_start_matches('$').to_string(),
2378 other => return Err(ParseError::validation("LIST_APPEND", format!("LIST_APPEND requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
2379 };
2380 if list.is_empty() {
2381 return Err(ParseError::validation("LIST_APPEND", "LIST_APPEND requires a LIST variable (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))
2382 }
2383 let item = it
2384 .next()
2385 .ok_or_else(|| ParseError::validation("LIST_APPEND", "LIST_APPEND requires an item to append (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))?;
2386 if it.next().is_some() {
2387 return Err(ParseError::validation("LIST_APPEND", "LIST_APPEND takes exactly two arguments: LIST_APPEND $list <item>".to_string(), &SpanContext::line_only(0)))
2388 }
2389 Ok(StepKind::ListAppend { list, item })
2390 },
2391 ],
2392}
2393
2394pub fn all_structural_metadata() -> Vec<CommandMeta> {
2402 vec![
2403 CommandMeta {
2404 in_index: true,
2405 name: "WITH_IO",
2406 syntax: "WITH_IO [<stream>[=$var], ...] <command> | WITH_IO [bindings] { <commands> } | WITH_IO [tty[, stdin=$p][, rows=<int>][, cols=<int>]] RUN ...",
2407 summary: "Reroute standard streams.",
2408 description: indoc! {r#"
2409 Reroutes the standard streams of the next command or, in block form,
2410 of every enclosed command.
2411
2412 Bindings map streams (`stdin`, `stdout`, `stderr`) to a PIPE-typed
2413 variable (`stdout=$p`, `stdin=$p`), resolved from the variable
2414 when the step runs. Both stdout and stderr pipes capture output
2415 the same way. Declare the handle first with `LET $p: PIPE`.
2416
2417 A `RUN` step can opt into a pseudo-terminal with the bare `tty`
2418 flag instead of a new command: `WITH_IO [tty] RUN [...]`
2419 spawns the child under a pty sized from the host terminal
2420 when it names none (24x80 fallback off-terminal;
2421 `rows = <int>` / `cols = <int>` override each side).
2422 Unnamed sides track the host window while the step runs
2423 (signal-driven on Unix, polled where no window signal
2424 exists); explicit sides stay pinned.
2425
2426 The master carries the child's interleaved stdout and stderr
2427 as one stream, so it routes exclusively to `stdout` (step
2428 capture or a `stdout = $p` pipe): `stderr` bindings alongside
2429 `tty` are rejected, and `tty` outside a `RUN` step is
2430 rejected. Pty-backed descriptors never promote to OS
2431 kernel pipes, even inside `ASYNC` single-`RUN` bodies.
2432
2433 `stdin = $p` feeds the master; bare `[tty]`
2434 with a real terminal stdin feeds host keys the same
2435 way (raw, transparent) and stays closed headless. Host
2436 interrupt keys reach the child instead of cancelling the
2437 step, so bind a step `TIMEOUT` for a guaranteed exit.
2438
2439 Expect pty translation in assertions:
2440 newlines arrive as carriage return plus newline, and prompts
2441 echo input. On Windows, lone line feeds in fed input expand
2442 to carriage-return line feeds for console submission, so
2443 portable scripts need no per-platform line endings.
2444
2445 An input pipe that EOFs contributes a
2446 terminal-echoed end-of-transmission marker on some
2447 platforms: prefer `ASSERT_CONTAINS` over byte-exact
2448 assertions on fed sessions.
2449
2450 Pipes hold bytes in memory and spill to a temp file above 8 MiB, so a
2451 producer can finish before the consumer starts.
2452
2453 If WITH_IO wraps an ASYNC block whose body is a single RUN, guarded or
2454 not, the pipe is a zero copy OS kernel pipe instead: pair it with a
2455 consumer that runs while the producer is alive, since output past the
2456 64 KiB kernel buffer stalls until drained. That promotion never crosses
2457 a function boundary: pipes created, bound, or passed by variable inside FUNC
2458 bodies are always script pipes, even when the surrounding task would
2459 otherwise promote.
2460
2461 A second producer or consumer on a live handle is an explicit
2462 error. A handle bound as output can later feed another
2463 command's `stdin`, connecting commands without touching the
2464 terminal. Binding `stdout` and `stderr` to the same live
2465 handle fails deterministically. Merge streams in shell
2466 via `2>&1` instead.
2467
2468 Nested blocks stack defaults; inline bindings override inherited ones for
2469 their command only; closing a block restores previous wiring.
2470 "#},
2471 args: &[],
2472 flags: &[],
2473 default_output: None,
2474 examples: &[
2475 Example {
2476 name: "with_io block",
2477 fence_meta: None,
2478 code: indoc! {r#"
2479 LET $log: PIPE
2480 WITH_IO [stdout=$log] {
2481 ECHO first
2482 ECHO second
2483 }
2484 WITH_IO [stdin=$log] WRITE captured.txt
2485
2486 # The piped bytes landed in the file.
2487 LET $body: STRING = READ captured.txt
2488 ASSERT_CONTAINS $body "first"
2489 ASSERT_CONTAINS $body "second"
2490 "#},
2491 },
2492 Example {
2493 name: "variable pipe binding",
2494 fence_meta: None,
2495 code: indoc! {r#"
2496 # Declare the pipe first: `LET $p: PIPE` mints a fresh
2497 # backend without touching a stream. A plain string here
2498 # would be a TypeMismatch.
2499 LET $p: PIPE
2500 WITH_IO [stdout=$p] ECHO hello
2501 WITH_IO [stdin=$p] READ_LINE $line
2502 ASSERT_EQ $line "hello"
2503 "#},
2504 },
2505 Example {
2506 name: "pty terminal binding",
2507 fence_meta: None,
2508 code: indoc! {r#"
2509 # A RUN step under bare `tty` sees a terminal: newlines
2510 # arrive translated, so assert with CONTAINS, never EQ.
2511 LET $p: PIPE
2512 WITH_IO [tty, stdout=$p] RUN "echo hello-tty"
2513 WITH_IO [stdin=$p] READ_LINE $line
2514 ASSERT_CONTAINS $line "hello-tty"
2515 "#},
2516 },
2517 ],
2518 },
2519 CommandMeta {
2520 in_index: true,
2521 name: "FOR",
2522 syntax: "FOR $item: TYPE IN <expr> { <commands> } | FOR $key: STRING, $value: TYPE IN <expr> { <commands> }",
2523 summary: "Iterate over a list or map.",
2524 description: indoc! {r#"
2525 The loop variable receives each element (lists) or value (maps); with
2526 two variables, the first receives the key.
2527
2528 Loop variables are declared with explicit types and scoped per iteration;
2529 they do not leak outward. The body may be a braced block
2530 or a single-line `{ ... }` command.
2531
2532 `GLOB("...")` patterns must be quoted (`*` is not a bare word, so
2533 `GLOB(*)` is a parse error); GLOB returns a root-relative sorted list,
2534 empty when nothing matches, and rejects `..` escapes.
2535 "#},
2536 args: &[],
2537 flags: &[],
2538 default_output: None,
2539 examples: &[
2540 Example {
2541 name: "for loop",
2542 fence_meta: None,
2543 code: indoc! {r#"
2544 # Each element binds in turn; the loop body sees every one.
2545 LET $items: LIST<STRING> = ["a", "b"]
2546 FOR $item: STRING IN $items {
2547 ECHO $item
2548 }
2549 ASSERT_CONTAINS stdout "a"
2550 ASSERT_CONTAINS stdout "b"
2551
2552 # Key and value bind together for maps.
2553 LET $map: MAP<x: INT> = {"x": 1}
2554 FOR $k: STRING, $v: INT IN $map {
2555 ECHO "{{ $k }}={{ $v }}"
2556 }
2557 ASSERT_CONTAINS stdout "x=1"
2558 "#},
2559 },
2560 Example {
2561 name: "expand every match",
2562 fence_meta: None,
2563 code: indoc! {r#"
2564 # Single-line body; $x is a template path, WHO an override.
2565 IMPORT [STD]
2566 WRITE a.txt "hi \{{ env:WHO }}!"
2567 FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
2568
2569 ASSERT_CONTAINS stdout "hi World!"
2570 "#},
2571 },
2572 ],
2573 },
2574 CommandMeta {
2575 in_index: true,
2576 name: "IF",
2577 syntax: "IF <expr> { <commands> } [ELSE IF <expr> { <commands> } ...] [ELSE { <commands> }]",
2578 summary: "Conditional execution.",
2579 description: indoc! {r#"
2580 The condition is evaluated as a boolean expression.
2581
2582 Prefix `!` negates (`IF !false`); `&&` binds tighter than
2583 `||`, and both short-circuit, so `IF true || $missing`
2584 never evaluates the right side. Only Bool values are
2585 accepted as conditions.
2586 "#},
2587 args: &[],
2588 flags: &[],
2589 default_output: None,
2590 examples: &[
2591 Example {
2592 name: "if else",
2593 fence_meta: None,
2594 code: indoc! {r#"
2595 IMPORT [STD]
2596
2597 # True branch runs; the false branch is skipped.
2598 IF true {
2599 WRITE yes.txt taken
2600 } ELSE {
2601 WRITE yes.txt skipped
2602 }
2603
2604 # ELSE IF selects the first true branch.
2605 IF false {
2606 WRITE skipped.txt no
2607 } ELSE IF true {
2608 WRITE fallback.txt taken
2609 }
2610
2611 # !false evaluates to true, so this branch runs.
2612 IF !false {
2613 WRITE negated.txt taken
2614 }
2615
2616 LET $yes_body: STRING = READ yes.txt
2617 LET $fallback_body: STRING = READ fallback.txt
2618 LET $negated_body: STRING = READ negated.txt
2619 ASSERT_EQ $yes_body "taken"
2620 ASSERT_EQ $fallback_body "taken"
2621 ASSERT_EQ $negated_body "taken"
2622 LET $t: STRING = PATH_TYPE("skipped.txt")
2623 ASSERT_EQ $t "absent"
2624 "#},
2625 },
2626 Example {
2627 name: "logical condition composition",
2628 fence_meta: None,
2629 code: indoc! {r#"
2630 IMPORT [STD]
2631 LET $role: STRING = "admin"
2632 LET $level: INT = 3
2633
2634 # || is true when either side holds; && needs both.
2635 IF $role == "owner" || $level >= 5 {
2636 WRITE unexpected.txt no
2637 } ELSE {
2638 WRITE fallback.txt or-false
2639 }
2640
2641 LET $fb: STRING = READ fallback.txt
2642 ASSERT_EQ $fb "or-false"
2643 LET $t1: STRING = PATH_TYPE("unexpected.txt")
2644 ASSERT_EQ $t1 "absent"
2645
2646 IF $role == "admin" || $level >= 5 {
2647 WRITE chosen.txt or-true
2648 }
2649
2650 LET $ch: STRING = READ chosen.txt
2651 ASSERT_EQ $ch "or-true"
2652
2653 IF $role == "admin" && $level >= 5 {
2654 WRITE unexpected-too.txt no
2655 } ELSE {
2656 WRITE and.txt and-false
2657 }
2658
2659 LET $an: STRING = READ and.txt
2660 ASSERT_EQ $an "and-false"
2661 LET $t2: STRING = PATH_TYPE("unexpected-too.txt")
2662 ASSERT_EQ $t2 "absent"
2663 "#},
2664 },
2665 ],
2666 },
2667 CommandMeta {
2668 in_index: true,
2669 name: "LET",
2670 syntax: "LET $var: TYPE = <expr> | LET $p: PIPE | LET $var: TYPE = ASYNC { <commands> } | LET $var: TYPE = <command> | LET $var: TYPE = AWAIT $task | LET $var: TYPE = { <commands> }",
2671 summary: "Bind script-local variables.",
2672 description: indoc! {r#"
2673 Declares a script-local variable with an explicit type (STRING, INT,
2674 FLOAT, BOOL, PIPE, LIST, MAP, HANDLE, DURATION, PATH). Duplicate LET
2675 in the same scope frame is a redeclaration error; mutate with
2676 `$var = <expr>`.
2677
2678 Variables are usable in templates (`{{ $var }}`), guards, and
2679 expressions. With `ASYNC`, spawns a background task and stores its
2680 handle (see ASYNC). The `$` sigil on the name is mandatory.
2681
2682 No hoisting: a variable exists only after its LET runs, in
2683 execution order. Reading `$var` before its LET (or after the
2684 block that declared it exits) fails with
2685 `undefined variable $var`. Scopes are a stack of frames and
2686 resolution walks innermost outward, so nothing pre-declares
2687 names. Function bodies read outer variables through the same
2688 walk, but their own LETs never leak out (see FUNC).
2689
2690 The right-hand side is always an expression — literals, lists, maps,
2691 arithmetic (`+ - * /` with `*`/`/` binding tighter, unary `-`,
2692 parentheses), comparisons (`< <= > >=` binding tighter than
2693 `== !=`), logical `&&` (tighter) and `||` with short-circuit,
2694 `!` negation, `env:KEY` reads, `INSPECT($var)` snapshots,
2695 `GLOB("*.md")`, `INT(x)` / `FLOAT(x)` conversions — never a
2696 `{{ ... }}` template; interpolation happens in string values,
2697 not here.
2698 The one exception is pipes: `LET $p: PIPE` with no `=`
2699 and no initializer mints a fresh anonymous backend,
2700 lazily materialized at first binding, so two declarations
2701 never share a channel.
2702
2703 Numbers are numeric literals: `42` binds `INT`, `3.14` binds
2704 `FLOAT`. `Int x Int` stays `INT` (checked, integer division,
2705 so `7 / 2` is `3`); any `Float` operand promotes to `FLOAT`.
2706 Division by zero, overflow, and non-finite results are errors.
2707 Both numeric sides compare numerically (`1 == 1.0` is true);
2708 otherwise `==`/`!=` compare rendered strings and ordering on
2709 non-numerics is a Type Error. Constant subtrees fold at parse
2710 time and dynamic arithmetic compiles to flat RPN with
2711 identical semantics.
2712
2713 Float equality is exact with no epsilon. Floats store decimals
2714 in binary, so a value is exact only when its reduced fraction
2715 has a power-of-2 denominator: 0.5 (1/2), 0.25 (1/4), 0.75
2716 (3/4) are exact, while 0.1 (1/10), 0.2 (1/5), 0.3 (3/10)
2717 repeat forever in binary (like 1/3 in decimal) and truncate,
2718 so `0.1 + 0.2 == 0.3` is false (the sum is
2719 `0.30000000000000004`). Rule of thumb: endings .5, .25, .75,
2720 .125, .625, .875 are exact; .1, .2, .3 and similar are
2721 approximations. Bound approximations instead of comparing
2722 them: `IF $sum > 0.299999 && $sum < 0.300001`.
2723
2724 Comparisons do not chain: `a < b < c` is a parse error, not
2725 `(a < b) < c`. Chaining would compare a `BOOL` against a
2726 number (a runtime Type Error in C-style parsing) or evaluate
2727 the middle term twice (Python-style chaining), so the grammar
2728 accepts exactly one comparison operator per level. Write the
2729 conjunction explicitly: `$a < $b && $b < $c`. The same holds
2730 for equality (`$a == $b == $c` is rejected).
2731
2732 Captured command output is a string, so convert before math:
2733 `LET $total: INT = $total + INT($size_str)` (`INT` trims ASCII
2734 whitespace; `FLOAT` accepts int strings and rejects
2735 non-finite).
2736
2737 Bare words need no quotes: `LET $d: STRING = 30s` binds the same string
2738 as quoted.
2739
2740 When the right-hand side is a synchronous command
2741 (`LET $out: STRING = ECHO hi`), the command runs to completion and its
2742 exact stdout bytes are captured into the variable as a string (no newline
2743 stripping; commands with no stdout capture as `""`; non-UTF8 stdout is
2744 an error). Combining capture with an explicit
2745 `WITH_IO [stdout=$var]` is a parse error.
2746
2747 Coming from Bash, the capture line looks familiar but behaves
2748 strictly:
2749
2750 | | Bash `output=$(...)` | OxDock `LET $out: STRING = ...` |
2751 | --- | --- | --- |
2752 | Trailing newlines | Stripped (all of them) | Preserved byte-exact |
2753 | Variable type | Always an untyped string | Declared: STRING, INT, FLOAT, ... |
2754 | Math on output | Implicit: `$((var + 1))` | Explicit: `INT($out) + 1` |
2755 | Failing command | Continues with empty output unless `set -e` | Step fails immediately, binds nothing |
2756
2757 `LET $out: TYPE = AWAIT $var` binds the background task's
2758 explicit `RETURN` value instead (tasks stream their stdout
2759 live, so there is no output left to capture); a task that
2760 succeeded without `RETURN` yields `INT` 0, like a process
2761 exit status.
2762
2763 An inline block (`LET $var: TYPE = { <commands> }`) runs its
2764 steps in a fresh scope and binds the nearest `RETURN` value,
2765 like a zero-arg function body: fallthrough without `RETURN`
2766 binds `""`, and `BREAK`/`CONTINUE` escaping the block are
2767 errors. Think IIFE: the block executes immediately where it
2768 stands and its value is the result. The block reads outer
2769 variables but its own LETs never leak out. A `{k: v}` shape
2770 still parses as a map literal; anything else in braces is
2771 a block.
2772
2773 The split is deliberate: synchronous commands capture
2774 stdout because they run inline to completion on the same
2775 thread; background tasks never capture stdout because
2776 concurrent output has no well-defined value. Task results
2777 travel only through `RETURN` (or `INT` 0 for void tasks).
2778
2779 `LET $e: STRING = env:FOO` reads the script environment into a plain
2780 string.
2781 "#},
2782 args: &[],
2783 flags: &[],
2784 default_output: None,
2785 examples: &[
2786 Example {
2787 name: "let",
2788 fence_meta: None,
2789 code: indoc! {r#"
2790 LET $name: STRING = "world"
2791 ECHO "hello, {{ $name }}"
2792 ASSERT_CONTAINS stdout "hello, world"
2793
2794 LET $items: LIST<STRING> = ["a", "b"]
2795 ASSERT_CONTAINS $items "a"
2796 ASSERT_CONTAINS $items "b"
2797
2798 LET $count: INT = 42
2799 ASSERT_EQ $count 42
2800 "#},
2801 },
2802 Example {
2803 name: "bool coercion",
2804 fence_meta: None,
2805 code: indoc! {r#"
2806 # BOOL spellings coerce case-insensitively. Empty is
2807 # not a boolean: absent flags state a default through
2808 # BOOL_OR instead of converting here.
2809 LET $t: BOOL = "TRUE"
2810 ASSERT_EQ $t true
2811 LET $f: BOOL = "no"
2812 ASSERT_EQ $f false
2813 "#},
2814 },
2815 Example {
2816 name: "bool coercion rejects empty",
2817 fence_meta: Some("expect_error:\"expected BOOL\""),
2818 code: indoc! {r#"
2819 # Empty never reads as false: an empty string fails
2820 # BOOL coercion instead of picking a polarity.
2821 ENV EMPTY_FLAG=""
2822 LET $e: BOOL = "{{ env:EMPTY_FLAG }}"
2823 "#},
2824 },
2825 Example {
2826 name: "no hoisting",
2827 fence_meta: Some("expect_error:\"undefined variable\""),
2828 code: indoc! {r#"
2829 # Reading before the LET runs is an error, not an empty value.
2830 ECHO $too_early
2831 LET $too_early: STRING = "too late"
2832 "#},
2833 },
2834 Example {
2835 name: "glob binding",
2836 fence_meta: None,
2837 code: indoc! {r#"
2838 # The RHS is an expression: GLOB(...) runs and binds a list.
2839 IMPORT [STD]
2840 WRITE a.txt "x"
2841 LET $files: LIST<STRING> = GLOB("*.txt")
2842 FOR $f: STRING IN $files { ECHO $f }
2843
2844 ASSERT_CONTAINS stdout "a.txt"
2845 "#},
2846 },
2847 Example {
2848 name: "scoped variable reverts",
2849 fence_meta: None,
2850 code: indoc! {r#"
2851 # LET inside a braced block reverts when the block exits.
2852 LET $a: STRING = "outer"
2853
2854 [bool:true] {
2855 LET $a: STRING = "inner"
2856 WRITE inner.txt "{{ $a }}"
2857 }
2858
2859 WRITE outer.txt "{{ $a }}"
2860
2861 LET $in_body: STRING = READ inner.txt
2862 ASSERT_EQ $in_body "inner"
2863
2864 LET $out_body: STRING = READ outer.txt
2865 ASSERT_EQ $out_body "outer"
2866 "#},
2867 },
2868 Example {
2869 name: "capture command output",
2870 fence_meta: None,
2871 code: indoc! {r#"
2872 # Capture keeps the trailing newline.
2873 LET $out: STRING = ECHO hi
2874 ASSERT_EQ $out "hi\n"
2875 "#},
2876 },
2877 Example {
2878 name: "inline block",
2879 fence_meta: None,
2880 code: indoc! {r#"
2881 LET $who: STRING = "ada"
2882
2883 # An inline block binds its RETURN value like a function body.
2884 LET $res: STRING = {
2885 LET $loud: STRING = "{{ $who }}!"
2886 RETURN $loud
2887 }
2888 ASSERT_EQ $res "ada!"
2889
2890 # Any declared type works: the block value checks like any RHS.
2891 LET $n: INT = {
2892 RETURN 40 + 2
2893 }
2894 ASSERT_EQ $n 42
2895 "#},
2896 },
2897 Example {
2898 name: "arithmetic over captured output",
2899 fence_meta: None,
2900 code: indoc! {r#"
2901 # Captured output converts explicitly: INT() then arithmetic.
2902 IMPORT [STD]
2903 LET $size_str: STRING = ECHO 41
2904 LET $total: INT = INT($size_str) + 1
2905 ASSERT_EQ $total 42
2906
2907 # FLOAT() promotes instead of truncating.
2908 LET $ratio: FLOAT = 1 + 2.5
2909 ASSERT_EQ $ratio 3.5
2910
2911 # Int x Int stays INT: integer division truncates.
2912 LET $half: INT = 7 / 2
2913 ASSERT_EQ $half 3
2914 "#},
2915 },
2916 Example {
2917 name: "float equality is exact",
2918 fence_meta: None,
2919 code: indoc! {r#"
2920 # Binary fractions compare cleanly; decimal fractions may not:
2921 # 0.1 + 0.2 is 0.30000000000000004, so == is false.
2922 IMPORT [STD]
2923 LET $exact: BOOL = 0.5 + 0.25 == 0.75
2924 LET $decimal: BOOL = 0.1 + 0.2 == 0.3
2925 IF $exact {
2926 WRITE exact.txt yes
2927 }
2928 IF $decimal {
2929 WRITE unexpected.txt no
2930 }
2931
2932 LET $ok: STRING = READ exact.txt
2933 ASSERT_EQ $ok "yes"
2934
2935 LET $t: STRING = PATH_TYPE("unexpected.txt")
2936 ASSERT_EQ $t "absent"
2937 "#},
2938 },
2939 Example {
2940 name: "bound inexact decimals",
2941 fence_meta: None,
2942 code: indoc! {r#"
2943 # Never test inexact decimals for equality; bound them.
2944 LET $sum: FLOAT = 0.1 + 0.2
2945 IF $sum > 0.299999 && $sum < 0.300001 {
2946 WRITE bounded.txt yes
2947 }
2948
2949 LET $ok: STRING = READ bounded.txt
2950 ASSERT_EQ $ok "yes"
2951 "#},
2952 },
2953 Example {
2954 name: "inspect a variable",
2955 fence_meta: None,
2956 code: indoc! {r#"
2957 # INSPECT($var) snapshots a variable into a MAP: declared
2958 # type plus live details (pipe backend stats here), so
2959 # scripts can branch on engine state.
2960 IMPORT [STD]
2961 LET $p: PIPE
2962 WITH_IO [stdout=$p] ECHO hello
2963 LET $info: MAP<ANY> = INSPECT($p)
2964 IF $info.is_os_pipe {
2965 WRITE unexpected.txt "should be a script pipe"
2966 }
2967
2968 ASSERT_EQ $info.type "PIPE"
2969 LET $t: STRING = PATH_TYPE("unexpected.txt")
2970 ASSERT_EQ $t "absent"
2971 "#},
2972 },
2973 ],
2974 },
2975 CommandMeta {
2976 in_index: false,
2978 name: "MUTATION",
2979 syntax: "$var = <expr>",
2980 summary: "Mutate a declared variable.",
2981 description: indoc! {r#"
2982 Reassigns an existing variable, converting the new value to
2983 the type declared at LET time. The explicit annotation is
2984 what authorizes string-to-number conversion here (`$n = "42"`
2985 binds 42 for an INT); a non-numeric string is an error.
2986 Expressions never convert: `"100" + 1` is a Type Error, use
2987 `INT()` / `FLOAT()` to cross that boundary explicitly.
2988
2989 The leading `$` distinguishes mutation from `KEY=value` command
2990 assignments. Assigning an undeclared variable or a mismatched type is
2991 an error.
2992
2993 Mutation writes through to the scope where the variable was
2994 declared, so it survives block exit: `LET $x` outside a block
2995 followed by `$x = ...` inside still reads back the new value
2996 afterwards, for every type. This is the counterpart to LET
2997 shadowing, where `LET $x` *inside* the block declares a
2998 separate inner variable that reverts on exit.
2999
3000 Reassignment rebinds the variable to a new value: values
3001 captured earlier keep the old word (see the rebinding
3002 example below).
3003 "#},
3004 args: &[],
3005 flags: &[],
3006 default_output: None,
3007 examples: &[
3008 Example {
3009 name: "mutate",
3010 fence_meta: None,
3011 code: indoc! {r#"
3012 # Mutation writes through: the binding holds the new value.
3013 LET $count: INT = 1
3014 $count = 2
3015 ASSERT_EQ $count 2
3016 "#},
3017 },
3018 Example {
3019 name: "rebind keeps earlier captures",
3020 fence_meta: None,
3021 code: indoc! {r#"
3022 # Reassignment rebinds: a map built from `$s` still
3023 # reads the original string after `$s` moves on.
3024 LET $s: STRING = "test"
3025 LET $m: MAP<ANY> = {a: $s}
3026 $s = "changed"
3027 ASSERT_EQ $m.a "test"
3028
3029 # Appending to one list binding never touches its clones.
3030 LET $a: LIST<STRING> = ["1"]
3031 LET $b: LIST<STRING> = $a
3032 LIST_APPEND $a "2"
3033 LET $want: LIST<STRING> = ["1"]
3034 ASSERT_EQ $b $want
3035 "#},
3036 },
3037 Example {
3038 name: "convert before math",
3039 fence_meta: None,
3040 code: indoc! {r#"
3041 # Captured output is a string: `"100" + 1` is a Type Error.
3042 # Convert explicitly, then mutate with arithmetic.
3043 IMPORT [STD]
3044 LET $raw: STRING = ECHO 100
3045 LET $n: INT = INT($raw)
3046 $n = $n + 1
3047
3048 # The declared slot stays strict: strings parse only
3049 # through the explicit converter, never on assignment.
3050 $n = INT("42")
3051 ASSERT_EQ $n 42
3052
3053 # Same crossing for decimals via FLOAT().
3054 LET $frac_str: STRING = ECHO 2.5
3055 LET $f: FLOAT = FLOAT($frac_str) + 0.25
3056 ASSERT_EQ $f 2.75
3057 "#},
3058 },
3059 ],
3060 },
3061 CommandMeta {
3062 in_index: true,
3063 name: "ASYNC",
3064 syntax: "ASYNC <command...> | ASYNC { <commands> } | LET $var: HANDLE = ASYNC { <commands> }",
3065 summary: "Run steps in a background thread.",
3066 description: indoc! {r#"
3067 Runs a command or block of commands in a background thread with
3068 subshell isolation.
3069
3070 Mutations (ENV, WORKDIR) stay within the block. With `LET`, stores a
3071 task handle for `AWAIT`. Task output streams live to the parent
3072 stdout; a task publishes a value with an explicit `RETURN`,
3073 which `LET $out: TYPE = AWAIT $task` binds.
3074
3075 `WITH_IO` must wrap `ASYNC` from the outside (`LET $p: PIPE` first,
3076 then `WITH_IO [stdout=$p] ASYNC ...`) so pipe endpoints allocate on
3077 the main thread before the worker spawns. Placing `WITH_IO` directly
3078 inside `ASYNC` is rejected at parse time.
3079 "#},
3080 args: &[],
3081 flags: &[],
3082 default_output: None,
3083 examples: &[
3084 Example {
3085 name: "async",
3086 fence_meta: None,
3087 code: indoc! {r#"
3088 # Inline and block forms both run in the background; AWAIT joins them.
3089 ASYNC ECHO "warming-up"
3090 LET $a: HANDLE = ASYNC ECHO "first"
3091 LET $b: HANDLE = ASYNC {
3092 ECHO "second"
3093 }
3094 AWAIT $a
3095 AWAIT $b
3096 ASSERT_CONTAINS stdout "first"
3097 ASSERT_CONTAINS stdout "second"
3098 "#},
3099 },
3100 Example {
3101 name: "async task handle",
3102 fence_meta: None,
3103 code: indoc! {r#"
3104 LET $task: HANDLE = ASYNC {
3105 ECHO "built"
3106 }
3107 AWAIT $task
3108 ASSERT_CONTAINS stdout "built"
3109 "#},
3110 },
3111 ],
3112 },
3113 CommandMeta {
3114 in_index: true,
3115 name: "AWAIT",
3116 syntax: "AWAIT $var | LET $out: STRING = AWAIT $var",
3117 summary: "Join a background task.",
3118 description: indoc! {r#"
3119 Blocks until the named task completes. Propagates errors if the task failed.
3120
3121 Task output streams live during the run; joining binds nothing by
3122 itself. `LET $out: TYPE = AWAIT $var` binds the task's explicit
3123 `RETURN` value instead, or `INT` 0 when the task succeeded
3124 without one (add `RETURN <expr>` to the task body to yield
3125 a value).
3126 "#},
3127 args: &[],
3128 flags: &[],
3129 default_output: None,
3130 examples: &[
3131 Example {
3132 name: "await",
3133 fence_meta: None,
3134 code: indoc! {r#"
3135 LET $task: HANDLE = ASYNC ECHO "done"
3136 AWAIT $task
3137 ASSERT_CONTAINS stdout "done"
3138 "#},
3139 },
3140 Example {
3141 name: "await capture",
3142 fence_meta: None,
3143 code: indoc! {r#"
3144 LET $task: HANDLE = ASYNC {
3145 ECHO "logged"
3146 RETURN "returned"
3147 }
3148
3149 # AWAIT binds the RETURN value, not the streamed output.
3150 LET $out: STRING = AWAIT $task
3151 ASSERT_EQ $out "returned"
3152 "#},
3153 },
3154 ],
3155 },
3156 CommandMeta {
3157 in_index: true,
3158 name: "CANCEL",
3159 syntax: "CANCEL $var",
3160 summary: "Synchronously cancel a background task.",
3161 description: indoc! {r#"
3162 Kills the named background task spawned via LET $var: HANDLE = ASYNC ....
3163
3164 Blocking: returns only after the task thread has been joined and its OS
3165 process reaped, so no residual filesystem or stream mutation follows. A
3166 later AWAIT $var reports cancellation. Only named tasks can be cancelled.
3167 "#},
3168 args: &[],
3169 flags: &[],
3170 default_output: None,
3171 examples: &[
3172 Example {
3173 name: "cancel",
3174 fence_meta: None,
3175 code: indoc! {r#"
3176 LET $task: HANDLE = ASYNC SLEEP 30s
3177 CANCEL $task
3178 "#},
3179 },
3180 Example {
3181 name: "await after cancel reports cancellation",
3182 fence_meta: Some("expect_error:\"was cancelled\""),
3183 code: indoc! {r#"
3184 # A cancelled task stays cancelled: joining it reports.
3185 LET $task: HANDLE = ASYNC SLEEP 30s
3186 CANCEL $task
3187 AWAIT $task
3188 "#},
3189 },
3190 ],
3191 },
3192 CommandMeta {
3193 in_index: true,
3194 name: "TIMEOUT",
3195 syntax: "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> } | TIMEOUT <duration> AWAIT $var",
3196 summary: "Enforce an execution deadline.",
3197 description: indoc! {r#"
3198 Aborts the wrapped step or block with a deadline error if it exceeds the
3199 duration (e.g. 500ms, 10s, 2m; a bare number means seconds).
3200
3201 A blocking foreground process is killed.
3202
3203 ASYNC composes in either nesting order with order-dependent deadline
3204 semantics: `LET $task: HANDLE = ASYNC TIMEOUT 30s RUN "build"` enforces
3205 the deadline inside the background thread (a later `AWAIT $task`
3206 surfaces the `TIMEOUT` error), while `TIMEOUT 30s AWAIT $task`
3207 preempts a hung task from the awaiting side.
3208 "#},
3209 args: &[],
3210 flags: &[],
3211 default_output: None,
3212 examples: &[
3213 Example {
3214 name: "timeout",
3215 fence_meta: None,
3216 code: indoc! {r#"
3217 TIMEOUT 30s WRITE heartbeat.txt alive
3218 LET $beat: STRING = READ heartbeat.txt
3219 ASSERT_EQ $beat "alive"
3220 "#},
3221 },
3222 Example {
3223 name: "timeout block",
3224 fence_meta: None,
3225 code: indoc! {r#"
3226 TIMEOUT 30s {
3227 WRITE a.txt one
3228 WRITE b.txt two
3229 }
3230 LET $a: STRING = READ a.txt
3231 LET $b: STRING = READ b.txt
3232 ASSERT_EQ $a "one"
3233 ASSERT_EQ $b "two"
3234 "#},
3235 },
3236 Example {
3237 name: "deadline aborts the step",
3238 fence_meta: Some("expect_error:\"TIMEOUT after\""),
3239 code: indoc! {r#"
3240 # 50ms expires long before the sleep does: the step dies
3241 # with a deadline error instead of running out the clock.
3242 TIMEOUT 50ms SLEEP 30s
3243 "#},
3244 },
3245 Example {
3246 name: "timeout variable duration",
3247 fence_meta: None,
3248 code: indoc! {r#"
3249 # Durations resolve at runtime, so variables work too.
3250 LET $budget: DURATION = "30s"
3251 TIMEOUT $budget WRITE heartbeat.txt alive
3252
3253 LET $beat: STRING = READ heartbeat.txt
3254 ASSERT_EQ $beat "alive"
3255 "#},
3256 },
3257 Example {
3258 name: "timeout await",
3259 fence_meta: None,
3260 code: indoc! {r#"
3261 # AWAIT form bounds a task join instead of a step.
3262 LET $quick: HANDLE = ASYNC {
3263 ECHO hi
3264 }
3265 TIMEOUT 30s AWAIT $quick
3266 "#},
3267 },
3268 ],
3269 },
3270 CommandMeta {
3271 in_index: true,
3272 name: "ISOLATED",
3273 syntax: "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>",
3274 summary: "Run steps with the seeded script environment.",
3275 description: indoc! {r#"
3276 Resets the script environment for the block to the session
3277 seed: spawned children see the sandbox defaults plus names
3278 the block re-adds through its leading `INHERIT_ENV`.
3279
3280 The allowlist resolves against the outer scope, never the
3281 host. Absent names stay absent silently, matching top-level
3282 `INHERIT_ENV`.
3283
3284 Script variables, pipes, and files flow through untouched;
3285 only `env:` is reset. Files share the session workspace:
3286 blocks selecting the same `WORKSPACE` target resolve to the
3287 same directory with no per-block overlay, so one block's
3288 writes are visible to another.
3289
3290 Blocks nest (each level re-seeds from the same seed, so
3291 nesting only narrows through the allowlists) and compose
3292 with `ASYNC` and `FUNC`. Scope exit restores the prior
3293 environment.
3294 "#},
3295 args: &[],
3296 flags: &[],
3297 default_output: None,
3298 examples: &[
3299 Example {
3300 name: "isolated scope",
3301 fence_meta: None,
3302 code: indoc! {r#"
3303 # The block sees a clean env; plain steps still run and
3304 # outer bindings survive untouched.
3305 ENV MODE=outer
3306 ISOLATED {
3307 ENV MODE=inner
3308 WRITE inner.txt "{{ env:MODE }}"
3309 }
3310 LET $back: STRING = "{{ env:MODE }}"
3311 ASSERT_EQ $back "outer"
3312 LET $body: STRING = READ inner.txt
3313 ASSERT_EQ $body "inner"
3314 "#},
3315 },
3316 Example {
3317 name: "reseeded child env",
3318 fence_meta: None,
3319 code: indoc! {r#"
3320 # The block resets to the session seed: plain steps and
3321 # spawns run with zero prelude. PATH needs no
3322 # declaration: contract seed rows are always admitted.
3323 WRITE top-path.txt "{{ env:PATH }}"
3324 ISOLATED {
3325 WRITE inner-path.txt "{{ env:PATH }}"
3326 RUN "echo seed-ok"
3327 }
3328 LET $top: STRING = READ top-path.txt
3329 LET $inner: STRING = READ inner-path.txt
3330 ASSERT_EQ $inner $top
3331 ASSERT_CONTAINS stdout "seed-ok"
3332 "#},
3333 },
3334 Example {
3335 name: "outer customs stay out",
3336 fence_meta: Some("expect_error:\"env:OUTER_CUSTOM\""),
3337 code: indoc! {r#"
3338 # Outer customs never enter the block: without an
3339 # allowlist entry the static gate rejects the read
3340 # before the first step runs.
3341 ENV OUTER_CUSTOM=outer-val
3342 ISOLATED {
3343 WRITE inner-custom.txt "{{ env:OUTER_CUSTOM }}"
3344 }
3345 "#},
3346 },
3347 Example {
3348 name: "absent names stay absent",
3349 fence_meta: None,
3350 code: indoc! {r#"
3351 # Listing a name the outer scope lacks is not an error:
3352 # the block simply runs without it.
3353 ISOLATED {
3354 INHERIT_ENV [OXDOC_DEFINITELY_ABSENT_12345]
3355 ECHO still-runs
3356 }
3357 ASSERT_CONTAINS stdout "still-runs"
3358 "#},
3359 },
3360 Example {
3361 name: "nesting narrows",
3362 fence_meta: None,
3363 code: indoc! {r#"
3364 # Each level snapshots the already-scrubbed parent, so
3365 # an inner block cannot recover what the outer dropped.
3366 ENV KEEP=yes
3367 ISOLATED {
3368 INHERIT_ENV [KEEP]
3369 ISOLATED {
3370 ENV KEEP=inner
3371 WRITE deep.txt "{{ env:KEEP }}"
3372 }
3373 LET $mid: STRING = "{{ env:KEEP }}"
3374 ASSERT_EQ $mid "yes"
3375 }
3376 LET $deep: STRING = READ deep.txt
3377 ASSERT_EQ $deep "inner"
3378 "#},
3379 },
3380 ],
3381 },
3382 CommandMeta {
3383 in_index: true,
3384 name: "REMOTE",
3385 syntax: "REMOTE <target> [[$var, ...] [env:NAME, ...]] { <commands> }",
3386 summary: "Run a sealed block on a remote target.",
3387 description: indoc! {r#"
3388 Runs the braced block on the named remote target, which the
3389 host binds at startup (`--remote`). The block is sealed:
3390 only header-listed `$var` and `env:NAME` entries cross, the
3391 guest starts empty, and results return through declared
3392 transfers or `WITH_IO` pipes.
3393
3394 The target is a static literal, never a variable. Unknown
3395 targets fail before execution starts.
3396
3397 Bodies check twice: the host static pass validates the
3398 body before anything ships, and the guest re-validates on
3399 arrival through the same entry point, so a body type error
3400 fails locally, never mid-run on the remote.
3401
3402 A failing guest fails the host step: EXIT in the body
3403 exits the guest, and the host relays the code to its own
3404 process exit status (see EXIT).
3405 "#},
3406 args: &[],
3407 flags: &[],
3408 default_output: None,
3409 examples: &[
3410 Example {
3411 name: "sealed header values cross, outer scope does not",
3412 fence_meta: Some("mock_remote:prod"),
3413 code: indoc! {r#"
3414 # Only header-listed names arrive: `$version` is visible
3415 # on the guest, `$secret` was never sent.
3416 LET $version: STRING = "1.2.3"
3417 LET $secret: STRING = "host-only"
3418 REMOTE prod [$version] {
3419 WRITE version.txt "{{ $version }}"
3420 COPY --to-host ./version.txt back.txt
3421 }
3422
3423 # The pushed file proves the guest saw the injected value.
3424 LET $back: STRING = READ back.txt
3425 ASSERT_EQ $back "1.2.3"
3426 "#},
3427 },
3428 Example {
3429 name: "background tasks stream through shared pipes",
3430 fence_meta: Some("mock_remote:prod"),
3431 code: indoc! {r#"
3432 # Two background REMOTEs share one capture pipe while a
3433 # WITH_IO block holds the write end open.
3434 IMPORT [STD]
3435 LET $cap: PIPE
3436 WITH_IO [stdout=$cap] {
3437 LET $a: HANDLE = ASYNC REMOTE prod {
3438 ECHO "from-a"
3439 }
3440 LET $b: HANDLE = ASYNC REMOTE prod {
3441 ECHO "from-b"
3442 }
3443 AWAIT $a
3444 AWAIT $b
3445 }
3446
3447 # EOF ends the drain: no sentinel line, no baked-in count.
3448 LET $n: INT = 0
3449 WHILE !EOF($cap) {
3450 WITH_IO [stdin=$cap] READ_LINE $line
3451 $n = $n + 1
3452 }
3453 ASSERT_EQ $n 2
3454 "#},
3455 },
3456 Example {
3457 name: "declared files cross both directions",
3458 fence_meta: Some("mock_remote:prod roots:unified"),
3459 code: indoc! {r#"
3460 # Fetches ride in, pushes ride back. Anything undeclared
3461 # never leaves its side.
3462 WRITE send.txt "payload"
3463 REMOTE prod {
3464 COPY --from-host ./send.txt got.txt
3465 LET $v: STRING = READ got.txt
3466 ASSERT_EQ $v "payload"
3467 WRITE back.txt "returned"
3468 COPY --to-host ./back.txt back.txt
3469 }
3470
3471 # The push landed on the host; guest staging is gone.
3472 LET $b: STRING = READ back.txt
3473 ASSERT_EQ $b "returned"
3474 "#},
3475 },
3476 Example {
3477 name: "guest workspace selection stays on the guest",
3478 fence_meta: Some("mock_remote:prod"),
3479 code: indoc! {r#"
3480 # WORKSPACE switches inside the block resolve against the
3481 # guest staging dir, which serves as both the SNAPSHOT
3482 # root and the LOCAL build context. The host selection
3483 # restores when the block exits.
3484 REMOTE prod {
3485 WORKSPACE SNAPSHOT
3486 WRITE out.txt "from-snapshot"
3487 COPY --to-host ./out.txt snap.txt
3488 }
3489
3490 LET $s: STRING = READ snap.txt
3491 ASSERT_EQ $s "from-snapshot"
3492 "#},
3493 },
3494 Example {
3495 name: "guest cache persists across execs",
3496 fence_meta: Some("mock_remote:prod"),
3497 code: indoc! {r#"
3498 # WORKSPACE CACHE addresses guest-local persistent
3499 # storage: the second block reads what the first wrote,
3500 # while the guest staging starts empty every time.
3501 REMOTE prod {
3502 WORKSPACE CACHE
3503 WRITE marker.txt "run-marker"
3504 }
3505 REMOTE prod {
3506 WORKSPACE CACHE
3507 LET $m: STRING = READ marker.txt
3508 ASSERT_EQ $m "run-marker"
3509 }
3510 "#},
3511 },
3512 Example {
3513 name: "pushes outside staging fail closed",
3514 fence_meta: Some("mock_remote:prod expect_error:\"escapes staging\""),
3515 code: indoc! {r#"
3516 # WORKSPACE SYSTEM exposes the whole guest machine, but
3517 # transfers stay staging scoped: a push source outside
3518 # staging fails loudly instead of crossing.
3519 REMOTE prod {
3520 WORKSPACE SYSTEM
3521 COPY --to-host /no/such/file.txt got.txt
3522 }
3523 "#},
3524 },
3525 Example {
3526 name: "guest exit fails the step, host survives",
3527 fence_meta: Some(
3528 "mock_remote:prod expect_error:\"REMOTE 'prod' exited with code 3\"",
3529 ),
3530 code: indoc! {r#"
3531 # EXIT in the body exits the guest with code 3. The
3532 # host is unaffected: it keeps executing after the
3533 # guest is already dead, and the failure surfaces as
3534 # a host step error carrying the same code. The CLI
3535 # then exits with it, so the guest code reaches the OS.
3536 LET $t: HANDLE = ASYNC REMOTE prod {
3537 EXIT 3
3538 }
3539 WRITE host-alive.txt "still here"
3540 AWAIT $t
3541 "#},
3542 },
3543 Example {
3544 name: "remote block without a runner",
3545 fence_meta: Some("expect_error:\"has no registered session\""),
3546 code: indoc! {r#"
3547 # Without a bound session, the block bails instead of
3548 # executing anywhere unexpected.
3549 REMOTE prod {
3550 ECHO "do something on remote"
3551 }
3552 "#},
3553 },
3554 ],
3555 },
3556 CommandMeta {
3557 in_index: true,
3558 name: "FUNC",
3559 syntax: "FUNC NAME([$param: TYPE, ...]) { <commands> }",
3560 summary: "Define a user function.",
3561 description: indoc! {r#"
3562 Defines a user function with UPPERCASE name and explicitly typed
3563 parameters.
3564
3565 Params bind by position, converting each argument to its
3566 declared parameter type before the body runs.
3567 Bodies run in a fresh variable scope; LETs inside do not leak. A nested
3568 FUNC definition is scoped to its block and reverts on exit. Names share
3569 one namespace with native and host-registered functions, which a FUNC
3570 may never shadow.
3571
3572 Functions resolve like variables: a name is visible from its
3573 definition line, so recursion works but mutual recursion does
3574 not (the second name does not exist while the first body
3575 lowers). Calls name their module (`STD::GLOB(...)`) unless
3576 imported; see IMPORT.
3577
3578 Invoke any function with one syntax: `NAME(...)` as a statement
3579 (discarding the value) or `LET $var: TYPE = NAME(...)` to capture
3580 the RETURN value (fallthrough without RETURN captures as "").
3581 "#},
3582 args: &[],
3583 flags: &[],
3584 default_output: None,
3585 examples: &[
3586 Example {
3587 name: "func def call",
3588 fence_meta: None,
3589 code: indoc! {r#"
3590 FUNC GREET($name: STRING) {
3591 RETURN $name
3592 }
3593
3594 LET $res: STRING = GREET("ada")
3595 ASSERT_EQ $res "ada"
3596
3597 # Statement form: parens stay, the value drops.
3598 GREET("bex")
3599 "#},
3600 },
3601 Example {
3602 name: "call with pipes",
3603 fence_meta: None,
3604 code: indoc! {r#"
3605 # A pipe handle travels into a function as a typed argument
3606 # and is usable as a binding target in both directions.
3607 # `LET $p: PIPE` mints the handle; `$p` passes it on.
3608 FUNC DRAIN($q: PIPE) {
3609 WITH_IO [stdin=$q] READ_LINE $line
3610 RETURN $line
3611 }
3612
3613 LET $p: PIPE
3614 WITH_IO [stdout=$p] ECHO "payload"
3615
3616 LET $got: STRING = DRAIN($p)
3617 ASSERT_EQ $got "payload"
3618 "#},
3619 },
3620 ],
3621 },
3622 CommandMeta {
3623 in_index: true,
3624 name: "RETURN",
3625 syntax: "RETURN [<expr>]",
3626 summary: "Return a value from a function, task, or inline block.",
3627 description: indoc! {r#"
3628 Ends the nearest enclosing boundary with a value: a function
3629 call, an `ASYNC` task (bound by `LET $o = AWAIT $t`), or an
3630 inline `LET` block. Bare `RETURN` with no expression yields
3631 `""`.
3632
3633 Falling off the end without RETURN yields "". RETURN with no
3634 enclosing boundary (including at top level) is an error; use
3635 EXIT or ECHO there.
3636 "#},
3637 args: &[],
3638 flags: &[],
3639 default_output: None,
3640 examples: &[Example {
3641 name: "return",
3642 fence_meta: None,
3643 code: indoc! {r#"
3644 FUNC PICK($flag: BOOL) {
3645 IF $flag {
3646 RETURN "yes"
3647 }
3648 RETURN "no"
3649 }
3650
3651 LET $res: STRING = PICK(true)
3652 ASSERT_EQ $res "yes"
3653
3654 # Fallthrough without RETURN yields its own value.
3655 LET $no: STRING = PICK(false)
3656 ASSERT_EQ $no "no"
3657 "#},
3658 }],
3659 },
3660 CommandMeta {
3661 in_index: true,
3662 name: "WHILE",
3663 syntax: "WHILE <bool-expr> { <commands> }",
3664 summary: "Loop while a condition holds.",
3665 description: indoc! {r#"
3666 Re-evaluates a Bool condition each iteration (same is_truthy rule as IF;
3667 non-Bool is a type error).
3668
3669 Each iteration runs in a fresh scope; mutate outer state with $var = ...
3670 so the next check observes it. BREAK exits the loop; CONTINUE skips to
3671 the next check.
3672 "#},
3673 args: &[],
3674 flags: &[],
3675 default_output: None,
3676 examples: &[Example {
3677 name: "while loop",
3678 fence_meta: None,
3679 code: indoc! {r#"
3680 # The condition re-evaluates every iteration: three passes, then stop.
3681 LET $n: INT = 0
3682 WHILE $n < 3 {
3683 WRITE tick.txt "{{ $n }}"
3684 $n = $n + 1
3685 }
3686
3687 ASSERT_EQ $n 3
3688 LET $tick: STRING = READ tick.txt
3689 ASSERT_EQ $tick "2"
3690 "#},
3691 }],
3692 },
3693 CommandMeta {
3694 in_index: true,
3695 name: "BREAK",
3696 syntax: "BREAK",
3697 summary: "Exit the innermost loop.",
3698 description: indoc! {r#"
3699 Exits the innermost enclosing FOR or WHILE loop.
3700
3701 BREAK outside a loop, or across a FUNC or ASYNC boundary, is an error.
3702 "#},
3703 args: &[],
3704 flags: &[],
3705 default_output: None,
3706 examples: &[Example {
3707 name: "break",
3708 fence_meta: None,
3709 code: indoc! {r#"
3710 # BREAK leaves after the first pass: only "a" is written.
3711 FOR $x: STRING IN ["a", "b"] {
3712 WRITE picked.txt "{{ $x }}"
3713 BREAK
3714 }
3715
3716 LET $body: STRING = READ picked.txt
3717 ASSERT_EQ $body "a"
3718 "#},
3719 }],
3720 },
3721 CommandMeta {
3722 in_index: true,
3723 name: "CONTINUE",
3724 syntax: "CONTINUE",
3725 summary: "Skip to the next loop iteration.",
3726 description: indoc! {r#"
3727 Skips the rest of the innermost enclosing FOR or WHILE body and starts
3728 the next iteration.
3729
3730 CONTINUE outside a loop, or across a FUNC or ASYNC boundary, is an error.
3731 "#},
3732 args: &[],
3733 flags: &[],
3734 default_output: None,
3735 examples: &[Example {
3736 name: "continue",
3737 fence_meta: None,
3738 code: indoc! {r#"
3739 # CONTINUE skips the write on "a": only "b" lands.
3740 FOR $x: STRING IN ["a", "b"] {
3741 IF $x == "a" {
3742 CONTINUE
3743 }
3744 WRITE picked.txt "{{ $x }}"
3745 }
3746
3747 LET $body: STRING = READ picked.txt
3748 ASSERT_EQ $body "b"
3749 "#},
3750 }],
3751 },
3752 CommandMeta {
3753 in_index: true,
3754 name: KEYWORD_IMPORT,
3755 syntax: "IMPORT [<module>, ...] | IMPORT <module> | IMPORT [\"<path>\" AS <ALIAS>] | IMPORT [<module | \"<path>\" AS <ALIAS> | [F, ... FROM (\"<path>\" | <module>) (AS <ALIAS>)?]>, ...]",
3756 summary: "Bring module functions into bare-call scope; import script files and types.",
3757 description: indoc! {r#"
3758 Bare calls:
3759 - Every call names its module (`STD::GLOB(...)`)
3760 unless the module is imported. `IMPORT [STD]` lets
3761 the rest of the scope call `GLOB(...)` bare.
3762 - Calls resolve at parse time: `SCRIPT` definitions
3763 first, then imported modules. Unknown modules,
3764 unknown functions, and unimported bare calls are
3765 parse errors, never runtime surprises.
3766
3767 Scope:
3768 - `IMPORT` is a lowering directive, not a step. It
3769 applies from its line to the enclosing block exit,
3770 then reverts like `LET` scoping, with no runtime
3771 footprint. Guards do not apply to it.
3772 - Two imported modules exporting one name is an
3773 ambiguity error: qualify the call instead.
3774
3775 File imports:
3776 - Form: `IMPORT ["./lib.oxdock" AS LIB]` (any file
3777 extension). The alias is mandatory and becomes the
3778 namespace (`LIB::FOO`), with no filename inference.
3779 - Only `EXPORT`ed top-level `FUNC`s cross the
3780 boundary. Unexported means private; variables are
3781 never exportable.
3782 - Types cross as bare globals (like host types). A
3783 whole-file import persists every exported alias, so
3784 `LET $p: PERSON` works after any import of its file.
3785 - Each file initializes once; every alias shares the
3786 module's top-level bindings.
3787 - The file must exist when the run starts. Generated
3788 imports are rejected before the first step.
3789
3790 Mixed brackets:
3791 - Brackets mix both kinds across lines if needed
3792 (`IMPORT [STD, "a.oxdock" AS A]`). Each module entry
3793 registers in order; each file entry runs in order.
3794 - Without an alias a file entry is a parse error.
3795 - Value positions (`LET`, `ASYNC`,
3796 `WITH_IO`/`TIMEOUT` inners) take exactly one file
3797 entry and no modules.
3798
3799 Selective harvests:
3800 - Form: `IMPORT [[FOO, BAR FROM "x.oxdock"]]`,
3801 optionally `AS ALIAS`. Only the named top-level
3802 functions register, bare or namespaced under the
3803 alias. Harvested names must be `EXPORT`ed.
3804 - Single name needs no inner brackets
3805 (`IMPORT [FOO FROM "x.oxdock"]`); several keep
3806 `[[F, G FROM ...]]`. Several harvests group the
3807 same way (`IMPORT [[TYPE A FROM STD],
3808 [TYPE B FROM STD]]`), file or host alike.
3809 - Types and functions combine in one entry
3810 (`IMPORT [TYPE PERSON, FUNC FOO FROM "x.oxdock"]`).
3811 Harvested types must be `EXPORT TYPE`d and persist
3812 bare globally, so `FUNC` signatures keep working.
3813 - The file body never executes, so harvesting is
3814 side-effect free. The file's own nested imports
3815 still load. Harvests produce no value and never
3816 appear in value positions.
3817
3818 Host library types:
3819 - Form: `IMPORT [TYPE PIPE FROM STD]`. The import
3820 validates the type resolves globally and records no
3821 file. Host types stay global with or without the
3822 harvest; the explicit form only documents the
3823 dependency and fails fast on typos.
3824 - Bare `FROM` names a library; quoted `FROM`
3825 names a file path. Quoted `FROM "STD"` still parses
3826 for backcompat, but bare is preferred.
3827
3828 Paths:
3829 - Workspace-side, against the importing file's
3830 directory (entry parent at top level; off-workspace
3831 entries resolve like stdin against the root).
3832 - Module-owned relative paths resolve against the
3833 module file's own directory, not the caller cwd.
3834 Entry code keeps resolving against the run cwd.
3835 - Missing files fail before the first step runs.
3836 Write-then-import in one script is rejected; check
3837 libraries into the tree, or compose them at runtime
3838 and run a child interpreter (see the child run
3839 examples below).
3840
3841 Module rules (every file import is a module):
3842 - Context: never inherits the caller. Env resets to
3843 the seed plus the module init's own contributions
3844 (declared `INHERIT_ENV` names re-read from the host
3845 on every call), cwd to the defining file's
3846 directory, workspace to the run-initial root.
3847 - Determinism: the same file behaves identically no
3848 matter who imports it.
3849 - State: one init per file, shared by every alias.
3850 Top-level `LET` bindings drain into a single store
3851 visible to all of the module's functions.
3852 - Workspace: declare `WORKSPACE` or `WORKDIR`
3853 in-function to read outside the module directory.
3854 Without it the reset leaves the module on the
3855 run-initial root (snapshot by default), even when
3856 the caller switched away.
3857 - Exports: only `EXPORT`ed top-level `FUNC`s and
3858 `EXPORT TYPE` aliases cross. Variables never cross.
3859 - Imports: whole-file or harvest, only exported
3860 functions and types cross. Stateful harvests are
3861 rejected (import the file to share its module).
3862 Nested imports load automatically.
3863 - Cycles: circular imports and depth over 32 fail
3864 before the first step runs.
3865
3866 Exports and tools:
3867 - `EXPORT` marks top-level `FUNC`s as externally
3868 callable (`EXPORT FOO`, `EXPORT [FOO, BAR]`) and as
3869 the file importable interface. Re-exports promote
3870 an import (`IMPORT ["x.oxdock" AS A]` then `EXPORT
3871 A::FOO`).
3872 - `EXPORT TYPE` marks aliases the same way
3873 (`EXPORT TYPE PERSON`, `EXPORT TYPE [A, B]`, mixed
3874 `EXPORT [TYPE A, FUNC B]`). Only exported aliases
3875 cross, so `FUNC` signatures survive imports.
3876 - Serving resolves re-exports through the registry;
3877 unexported names fail tool setup instead of serving
3878 a dead tool. The MCP server skips `TYPE` exports
3879 when building tools while still resolving imported
3880 types for signatures. Single-file scope otherwise;
3881 see the MCP host for consumption.
3882 "#},
3883 args: &[],
3884 flags: &[],
3885 default_output: None,
3886 examples: &[
3887 Example {
3888 name: "import",
3889 fence_meta: None,
3890 code: indoc! {r#"
3891 # Calls name their module (STD::GLOB); IMPORT [STD] drops the prefix.
3892 WRITE a.txt "hi \{{ env:WHO }}!"
3893 IMPORT [STD]
3894 FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
3895 ASSERT_CONTAINS stdout "hi World!"
3896 "#},
3897 },
3898 Example {
3899 name: "import missing file fails upfront",
3900 fence_meta: Some("expect_error:\"must exist when the run starts\""),
3901 code: indoc! {r#"
3902 # Generated imports are rejected: a file that does not
3903 # exist when the run starts cannot be analyzed, so the
3904 # import fails before the first step runs.
3905 WORKSPACE LOCAL
3906 WRITE lib.oxdock 'FUNC F($x: STRING) { RETURN $x } EXPORT F'
3907 IMPORT ["lib.oxdock" AS LIB]
3908 "#},
3909 },
3910 Example {
3911 name: "import missing alias fails",
3912 fence_meta: Some("expect_error:\"mandatory alias\""),
3913 code: indoc! {r#"
3914 # A file entry without AS is a parse error.
3915 IMPORT ["./lib.oxdock"]
3916 "#},
3917 },
3918 Example {
3919 name: "module cannot export a variable",
3920 fence_meta: Some("expect_error:\"does not match any top-level FUNC\""),
3921 code: indoc! {r#"
3922 # Only top-level FUNCs are exportable, never variables.
3923 LET $FOO: STRING = "x"
3924 EXPORT FOO
3925 "#},
3926 },
3927 Example {
3928 name: "import re-export unknown alias fails",
3929 fence_meta: Some("expect_error:\"does not match any top-level FUNC\""),
3930 code: indoc! {r#"
3931 # Re-exports name a visible import alias.
3932 IMPORT ["x.oxdock" AS A]
3933 EXPORT NOSUCH::FOO
3934 "#},
3935 },
3936 Example {
3937 name: "export type aliases",
3938 fence_meta: None,
3939 code: indoc! {r#"
3940 # TYPE aliases declare shapes once; EXPORT TYPE shares
3941 # them so importing files can use the same spelling.
3942 TYPE PERSON = MAP<name: STRING>
3943
3944 FUNC GREET($p: PERSON) {
3945 RETURN "hi {{ $p.name }}"
3946 }
3947 EXPORT GREET
3948 EXPORT TYPE PERSON
3949
3950 LET $p: PERSON = {name: "Ada"}
3951 LET $greeting: STRING = GREET($p)
3952 ASSERT_EQ $greeting "hi Ada"
3953 "#},
3954 },
3955 Example {
3956 name: "import type from library",
3957 fence_meta: None,
3958 code: indoc! {r#"
3959 # One bracket mixes entry kinds: STD brings functions bare,
3960 # each harvest names a type. Types resolve globally with
3961 # or without the harvests; the explicit form only documents
3962 # the dependency, so this grouping is example only. Bare
3963 # FROM names a library; quoted FROM names a file path.
3964 IMPORT [STD, [TYPE PIPE FROM STD], [TYPE DURATION FROM STD]]
3965
3966 LET $p: PIPE
3967 WITH_IO [stdout=$p] ECHO hello
3968 WITH_IO [stdin=$p] READ_LINE $line
3969 ASSERT_EQ $line "hello"
3970
3971 LET $d: DURATION = "5s"
3972 LET $files: LIST<STRING> = GLOB("*.oxdock")
3973 "#},
3974 },
3975 Example {
3976 name: "run composed modules in a child",
3977 fence_meta: Some("roots:unified"),
3978 code: indoc! {r#"
3979 # Dynamic composition with files: the parent writes a
3980 # library and an entry script, then runs the entry in a
3981 # fresh interpreter. Child-side {{ }} stays escaped so
3982 # the parent does not interpolate it while writing. The
3983 # child runs by path so entry-relative IMPORT resolves.
3984 # Unified roots: the child inherits one workspace, so
3985 # parent and child see the same files.
3986 IMPORT [STD]
3987 WRITE lib.oxfile """
3988 FUNC GREET($x: STRING) { RETURN "hi \{{ $x }}" }
3989 EXPORT GREET
3990 """
3991 WRITE main.oxfile """
3992 IMPORT ["lib.oxfile" AS LIB]
3993 LET $g: STRING = LIB::GREET("Ada")
3994 ECHO "says \{{ $g }}"
3995 """
3996 LET $exe: STRING = INTERPRETER()
3997 LET $out: STRING = RUN [$exe, "main.oxfile"]
3998 ASSERT_CONTAINS $out "says hi Ada"
3999 "#},
4000 },
4001 Example {
4002 name: "dynamic module composition",
4003 fence_meta: Some("roots:unified"),
4004 code: indoc! {r#"
4005 # A function that composes a module: MAKE_GREETER bakes
4006 # its argument into a generated file with a bare {{ }},
4007 # then a child run imports the result. Bare {{ }} injects
4008 # parent values at write time; escaped \{{ }} survives for
4009 # the child to interpolate. Bind imported calls with LET:
4010 # {{ }} placeholders resolve pure functions only.
4011 IMPORT [STD]
4012
4013 # The composer: parent values land in the module source.
4014 FUNC MAKE_GREETER($who: STRING) {
4015 WRITE greeter.oxfile """
4016 FUNC GREET() { RETURN "hi {{ $who }}" }
4017 EXPORT GREET
4018 """
4019 RETURN "greeter.oxfile"
4020 }
4021
4022 # The entry: imports the composed module by its path.
4023 WRITE main.oxfile """
4024 IMPORT ["greeter.oxfile" AS G]
4025 LET $g: STRING = G::GREET()
4026 ECHO "says \{{ $g }}"
4027 """
4028
4029 # Compose, then run the entry in a fresh interpreter.
4030 LET $made: STRING = MAKE_GREETER("Ada")
4031 ASSERT_EQ $made "greeter.oxfile"
4032 LET $exe: STRING = INTERPRETER()
4033 LET $out: STRING = RUN [$exe, "main.oxfile"]
4034 ASSERT_CONTAINS $out "says hi Ada"
4035 "#},
4036 },
4037 Example {
4038 name: "export unknown type fails",
4039 fence_meta: Some("expect_error:\"does not match any top-level TYPE\""),
4040 code: indoc! {r#"
4041 # Only declared TYPE aliases are exportable.
4042 TYPE PERSON = MAP<name: STRING>
4043 EXPORT TYPE ANIMAL
4044 "#},
4045 },
4046 Example {
4047 name: "undeclared type fails",
4048 fence_meta: Some("expect_error:\"unknown type\""),
4049 code: indoc! {r#"
4050 # TYPE names must be declared before use.
4051 LET $p: PERSON = {name: "Ada"}
4052 "#},
4053 },
4054 ],
4055 },
4056 ]
4057}
4058
4059impl fmt::Display for StepKind {
4062 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4063 match self {
4064 StepKind::InheritEnv { keys } => write!(f, "INHERIT_ENV [{}]", keys.join(", ")),
4065 StepKind::Workdir(a) => write!(f, "WORKDIR {}", fmt_value(a, quote_arg)),
4066 StepKind::Workspace(t) => write!(f, "WORKSPACE {}", t),
4067 StepKind::Env { key, value } => {
4068 write!(f, "ENV {}={}", key, fmt_value(value, quote_arg))
4069 }
4070 StepKind::Run(c) => write!(f, "RUN {}", fmt_value(c, quote_run)),
4071 StepKind::RunExec { argv } => {
4072 let parts: Vec<String> = argv.iter().map(fmt_exec_arg).collect();
4073 write!(f, "RUN [{}]", parts.join(", "))
4074 }
4075 StepKind::Echo(m) => write!(f, "ECHO {}", fmt_value(m, quote_msg)),
4076 StepKind::Copy {
4077 from_workspace,
4078 from_host,
4079 to_host,
4080 from,
4081 to,
4082 } => {
4083 let mut head = String::from("COPY");
4084 if let Some(target) = from_workspace {
4085 head.push_str(&format!(" --from-workspace {target}"));
4086 }
4087 if *from_host {
4088 head.push_str(" --from-host");
4089 }
4090 if *to_host {
4091 head.push_str(" --to-host");
4092 }
4093 write!(
4094 f,
4095 "{head} {} {}",
4096 fmt_value(from, quote_arg),
4097 fmt_value(to, quote_arg)
4098 )
4099 }
4100 StepKind::Symlink {
4101 from_workspace,
4102 from,
4103 to,
4104 } => {
4105 if let Some(target) = from_workspace {
4106 write!(
4107 f,
4108 "SYMLINK --from-workspace {} {} {}",
4109 target,
4110 fmt_value(from, quote_arg),
4111 fmt_value(to, quote_arg)
4112 )
4113 } else {
4114 write!(
4115 f,
4116 "SYMLINK {} {}",
4117 fmt_value(from, quote_arg),
4118 fmt_value(to, quote_arg)
4119 )
4120 }
4121 }
4122 StepKind::Mkdir(a) => write!(f, "MKDIR {}", fmt_value(a, quote_arg)),
4123 StepKind::Install { from, to } => write!(
4124 f,
4125 "INSTALL {} {}",
4126 fmt_value(from, quote_arg),
4127 fmt_value(to, quote_arg)
4128 ),
4129 StepKind::Archive { src, dst, raw } => {
4130 if *raw {
4131 write!(
4132 f,
4133 "ARCHIVE --raw {} {}",
4134 fmt_value(src, quote_arg),
4135 fmt_value(dst, quote_arg)
4136 )
4137 } else {
4138 write!(
4139 f,
4140 "ARCHIVE {} {}",
4141 fmt_value(src, quote_arg),
4142 fmt_value(dst, quote_arg)
4143 )
4144 }
4145 }
4146 StepKind::Unarchive {
4147 src,
4148 dst,
4149 max_bytes,
4150 } => {
4151 write!(f, "UNARCHIVE")?;
4152 if let Some(n) = max_bytes {
4153 write!(f, " --max-bytes {}", fmt_value(n, quote_arg))?;
4154 }
4155 write!(
4156 f,
4157 " {} {}",
4158 fmt_value(src, quote_arg),
4159 fmt_value(dst, quote_arg)
4160 )
4161 }
4162 StepKind::Ls(a) => {
4163 write!(f, "LS")?;
4164 if let Some(x) = a {
4165 write!(f, " {}", fmt_value(x, quote_arg))?;
4166 }
4167 Ok(())
4168 }
4169 StepKind::Read(a) => {
4170 write!(f, "READ")?;
4171 if let Some(x) = a {
4172 write!(f, " {}", fmt_value(x, quote_arg))?;
4173 }
4174 Ok(())
4175 }
4176 StepKind::ReadLine { var } => write!(f, "READ_LINE ${}", var),
4177 StepKind::Prompt {
4178 var,
4179 message,
4180 default,
4181 } => {
4182 write!(f, "PROMPT ${} {}", var, fmt_value(message, quote_arg))?;
4183 if let Some(d) = default {
4184 write!(f, " {}", fmt_value(d, quote_arg))?;
4185 }
4186 Ok(())
4187 }
4188 StepKind::Write { path, contents } => {
4189 write!(f, "WRITE {}", fmt_value(path, quote_arg))?;
4190 if let Some(b) = contents {
4191 write!(f, " {}", fmt_value(b, quote_msg))?;
4192 }
4193 Ok(())
4194 }
4195 StepKind::Append { path, contents } => {
4196 write!(f, "APPEND {}", fmt_value(path, quote_arg))?;
4197 if let Some(b) = contents {
4198 write!(f, " {}", fmt_value(b, quote_msg))?;
4199 }
4200 Ok(())
4201 }
4202 StepKind::Remove { path, recursive } => {
4203 if *recursive {
4204 write!(f, "REMOVE --recursive {}", fmt_value(path, quote_arg))
4205 } else {
4206 write!(f, "REMOVE {}", fmt_value(path, quote_arg))
4207 }
4208 }
4209 StepKind::Expand { path, overrides } => {
4210 write!(f, "EXPAND")?;
4211 if let Some(p) = path {
4212 write!(f, " {}", fmt_value(p, quote_arg))?;
4213 }
4214 for (k, v) in overrides {
4215 write!(f, " {}={}", k, fmt_value(v, quote_arg))?;
4216 }
4217 Ok(())
4218 }
4219 StepKind::AssertEq {
4220 hash,
4221 actual,
4222 expected,
4223 }
4224 | StepKind::AssertNe {
4225 hash,
4226 actual,
4227 expected,
4228 } => {
4229 let verb = match self {
4230 StepKind::AssertEq { .. } => Command::AssertEq.as_str(),
4231 _ => Command::AssertNe.as_str(),
4232 };
4233 if let Some(d) = hash {
4234 write!(f, "{verb} --hash {d} {}", fmt_assert_target(actual))?;
4235 } else {
4236 write!(
4237 f,
4238 "{verb} {} {}",
4239 fmt_assert_target(actual),
4240 fmt_value(
4241 expected
4242 .as_ref()
4243 .expect("Display of ASSERT without --hash needs expected"),
4244 quote_msg
4245 )
4246 )?;
4247 }
4248 Ok(())
4249 }
4250 StepKind::AssertContains { haystack, needle } => write!(
4251 f,
4252 "{} {} {}",
4253 Command::AssertContains.as_str(),
4254 fmt_assert_target(haystack),
4255 fmt_value(needle, quote_msg)
4256 ),
4257 StepKind::WithIo { bindings, cmd } => {
4258 let p: Vec<String> = bindings.iter().map(fmt_io).collect();
4259 write!(f, "WITH_IO [{}] {}", p.join(", "), cmd)
4260 }
4261 StepKind::WithIoBlock { bindings } => {
4262 let p: Vec<String> = bindings.iter().map(fmt_io).collect();
4263 write!(f, "WITH_IO [{}] {{...}}", p.join(", "))
4264 }
4265 StepKind::CopyGit {
4266 rev,
4267 from,
4268 to,
4269 include_dirty,
4270 } => {
4271 if *include_dirty {
4272 write!(
4273 f,
4274 "COPY_GIT --include-dirty {} {} {}",
4275 fmt_value(rev, quote_arg),
4276 fmt_value(from, quote_arg),
4277 fmt_value(to, quote_arg)
4278 )
4279 } else {
4280 write!(
4281 f,
4282 "COPY_GIT {} {} {}",
4283 fmt_value(rev, quote_arg),
4284 fmt_value(from, quote_arg),
4285 fmt_value(to, quote_arg)
4286 )
4287 }
4288 }
4289 StepKind::Exit(code) => write!(f, "EXIT {}", fmt_raw_arg(code)),
4290 StepKind::Sleep { duration } => write!(f, "SLEEP {}", fmt_raw_arg(duration)),
4291 StepKind::ListAppend { list, item } => {
4292 write!(f, "LIST_APPEND ${} {}", list, fmt_raw_arg(item))
4293 }
4294 StepKind::For {
4295 key_var,
4296 key_type,
4297 var,
4298 var_type,
4299 in_expr,
4300 body,
4301 } => {
4302 match key_var {
4303 Some(k) => {
4304 let kt = key_type.as_deref().unwrap_or("STRING");
4305 write!(
4306 f,
4307 "FOR ${}: {}, ${}: {} IN {} {{",
4308 k, kt, var, var_type, in_expr
4309 )?
4310 }
4311 None => write!(f, "FOR ${}: {} IN {} {{", var, var_type, in_expr)?,
4312 }
4313 for s in body {
4314 write!(f, "\n {}", s)?;
4315 }
4316 write!(f, "\n}}")
4317 }
4318 StepKind::If {
4319 cond,
4320 then_body,
4321 else_ifs,
4322 else_body,
4323 } => {
4324 write!(f, "IF {} {{", cond)?;
4325 for s in then_body {
4326 write!(f, "\n {}", s)?;
4327 }
4328 write!(f, " }}")?;
4329 for (c, b) in else_ifs {
4330 write!(f, " ELSE IF {} {{", c)?;
4331 for s in b {
4332 write!(f, "\n {}", s)?;
4333 }
4334 write!(f, " }}")?;
4335 }
4336 if let Some(b) = else_body {
4337 write!(f, " ELSE {{")?;
4338 for s in b {
4339 write!(f, "\n {}", s)?;
4340 }
4341 write!(f, " }}")?;
4342 }
4343 Ok(())
4344 }
4345 StepKind::Assign {
4346 var,
4347 decl_type,
4348 expr,
4349 } => {
4350 if matches!(expr, Expr::FreshPipe) {
4352 write!(f, "LET ${}: {}", var, decl_type)
4353 } else {
4354 write!(f, "LET ${}: {} = {}", var, decl_type, expr)
4355 }
4356 }
4357 StepKind::Set { var, expr } => write!(f, "${} = {}", var, expr),
4358 StepKind::AssignCapture {
4359 var,
4360 decl_type,
4361 cmd,
4362 } => {
4363 write!(f, "LET ${}: {} = {}", var, decl_type, cmd)
4364 }
4365 StepKind::AsyncBlock { body } => {
4366 write!(f, "ASYNC {{")?;
4367 for s in body {
4368 write!(f, "\n {}", s)?;
4369 }
4370 write!(f, "\n}}")
4371 }
4372 StepKind::AssignAsync {
4373 var,
4374 decl_type,
4375 body,
4376 } => {
4377 write!(f, "LET ${}: {} = ASYNC {{", var, decl_type)?;
4378 for s in body {
4379 write!(f, "\n {}", s)?;
4380 }
4381 write!(f, "\n}}")
4382 }
4383 StepKind::Await { var } => write!(f, "AWAIT ${}", var),
4384 StepKind::AwaitCapture {
4385 out_var,
4386 out_type,
4387 task_var,
4388 } => {
4389 write!(f, "LET ${}: {} = AWAIT ${}", out_var, out_type, task_var)
4390 }
4391 StepKind::Cancel { var } => write!(f, "CANCEL ${}", var),
4392 StepKind::Timeout { duration, body } => {
4393 let budget = fmt_raw_arg(duration);
4394 if body.len() == 1 && body[0].guard.is_none() {
4398 write!(f, "TIMEOUT {} {}", budget, body[0].kind)
4399 } else {
4400 write!(f, "TIMEOUT {} {{", budget)?;
4401 for s in body {
4402 write!(f, "\n {}", s)?;
4403 }
4404 write!(f, "\n}}")
4405 }
4406 }
4407 StepKind::Isolated { body } => {
4408 if body.len() == 1 && body[0].guard.is_none() {
4409 write!(f, "ISOLATED {}", body[0].kind)
4410 } else {
4411 write!(f, "ISOLATED {{")?;
4412 for s in body {
4413 write!(f, "\n {}", s)?;
4414 }
4415 write!(f, "\n}}")
4416 }
4417 }
4418 StepKind::IsolatedInheritEnv { keys } => {
4419 write!(f, "INHERIT_ENV [{}]", keys.join(", "))
4423 }
4424 StepKind::RemoteBlock {
4425 target,
4426 vars,
4427 env,
4428 body,
4429 } => {
4430 let mut entries: Vec<String> = vars.iter().map(|v| format!("${v}")).collect();
4431 entries.extend(env.iter().map(|e| format!("env:{e}")));
4432 if entries.is_empty() {
4433 write!(f, "REMOTE {target} {{")?;
4434 } else {
4435 write!(f, "REMOTE {target} [{}] {{", entries.join(", "))?;
4436 }
4437 for s in body {
4438 write!(f, "\n {}", s)?;
4439 }
4440 write!(f, "\n}}")
4441 }
4442 StepKind::FuncDef {
4443 name,
4444 params,
4445 body,
4446 docs,
4447 } => {
4448 if let Some((_, full)) = docs {
4452 for doc_line in full.split('\n') {
4453 writeln!(f, "# {doc_line}")?;
4454 }
4455 }
4456 let ps: Vec<String> = params
4457 .iter()
4458 .map(|(p, t)| format!("${}: {}", p, t))
4459 .collect();
4460 write!(f, "FUNC {}({}) {{", name, ps.join(", "))?;
4461 for s in body {
4462 write!(f, "\n {}", s)?;
4463 }
4464 write!(f, "\n}}")
4465 }
4466 StepKind::Call { name, args } => {
4467 let ps: Vec<String> = args.iter().map(|a| format!("{}", a)).collect();
4468 write!(f, "{}({})", name, ps.join(", "))
4469 }
4470 StepKind::ImportFile { path, alias } => {
4471 write!(f, "IMPORT [\"{}\" AS {}]", path, alias)
4472 }
4473 StepKind::ImportFuncs {
4474 path,
4475 alias,
4476 func_names,
4477 type_names,
4478 } => {
4479 let mut parts: Vec<String> = Vec::new();
4480 for t in type_names {
4481 parts.push(format!("TYPE {t}"));
4482 }
4483 for n in func_names {
4484 parts.push(n.clone());
4485 }
4486 match alias {
4487 Some(alias) => write!(
4488 f,
4489 "IMPORT [[{} FROM \"{}\" AS {}]]",
4490 parts.join(", "),
4491 path,
4492 alias
4493 ),
4494 None => write!(f, "IMPORT [[{} FROM \"{}\"]]", parts.join(", "), path),
4495 }
4496 }
4497 StepKind::Return { expr } => write!(f, "RETURN {}", expr),
4498 StepKind::TypeAlias { name, target } => write!(f, "TYPE {} = {}", name, target),
4499 StepKind::While { cond, body } => {
4500 write!(f, "WHILE {} {{", cond)?;
4501 for s in body {
4502 write!(f, "\n {}", s)?;
4503 }
4504 write!(f, "\n}}")
4505 }
4506 StepKind::Break => write!(f, "BREAK"),
4507 StepKind::Continue => write!(f, "CONTINUE"),
4508 }
4509 }
4510}
4511
4512pub(crate) enum InsToken {
4517 Pos(Arg),
4518 Assign(String, Arg),
4519}
4520
4521pub(crate) fn lower_env_tokens(ctx: &SpanContext, tokens: Vec<InsToken>) -> ParseResult<StepKind> {
4522 if tokens.is_empty() {
4523 return Err(ParseError::validation(
4524 "ENV",
4525 "ENV requires KEY=value".to_string(),
4526 ctx,
4527 ));
4528 }
4529 match tokens.as_slice() {
4530 [InsToken::Assign(key, value)] => {
4531 if crate::command::split_assignment(&format!("{key}={}", value.render()))
4534 .map_err(|e| ParseError::validation("ENV", e.to_string(), ctx))?
4535 .is_none()
4536 {
4537 return Err(ParseError::validation(
4538 "ENV",
4539 "ENV requires KEY=value format".to_string(),
4540 ctx,
4541 ));
4542 }
4543 Ok(StepKind::Env {
4544 key: key.clone(),
4545 value: value.clone(),
4546 })
4547 }
4548 [InsToken::Pos(Arg::String(text, _))] => match crate::command::split_assignment(text)
4549 .map_err(|e| ParseError::validation("ENV", e.to_string(), ctx))?
4550 {
4551 Some((key, value)) => Ok(StepKind::Env { key, value }),
4552 None => Err(ParseError::validation(
4553 "ENV",
4554 "ENV requires KEY=value format".to_string(),
4555 ctx,
4556 )),
4557 },
4558 _ => Err(ParseError::validation(
4559 "ENV",
4560 "ENV requires KEY=value format".to_string(),
4561 ctx,
4562 )),
4563 }
4564}
4565
4566pub(crate) fn lower_expand_tokens(
4570 ctx: &SpanContext,
4571 tokens: Vec<InsToken>,
4572) -> ParseResult<StepKind> {
4573 let mut path = None;
4574 let mut overrides = Vec::new();
4575 for token in tokens {
4576 match token {
4577 InsToken::Assign(key, value) => {
4578 if key.is_empty() {
4579 return Err(ParseError::validation(
4580 "EXPAND",
4581 "EXPAND requires KEY=value format for overrides".to_string(),
4582 ctx,
4583 ));
4584 }
4585 overrides.push((key, value));
4586 }
4587 InsToken::Pos(arg) => match &arg {
4588 Arg::String(text, quoted) if !quoted && text.contains('=') => {
4589 let Some((key, value)) = crate::command::split_assignment(text)
4590 .map_err(|e| ParseError::validation("EXPAND", e.to_string(), ctx))?
4591 else {
4592 return Err(ParseError::validation(
4593 "EXPAND",
4594 "EXPAND requires KEY=value format for overrides".to_string(),
4595 ctx,
4596 ));
4597 };
4598 overrides.push((key, value));
4599 }
4600 _ => {
4601 if path.is_none() {
4602 ArgType::Path
4606 .check_arg(&arg)
4607 .map_err(|e| ParseError::validation("EXPAND", e.to_string(), ctx))?;
4608 path = Some(arg);
4609 } else {
4610 return Err(ParseError::validation(
4611 "EXPAND",
4612 "EXPAND accepts at most one path".to_string(),
4613 ctx,
4614 ));
4615 }
4616 }
4617 },
4618 }
4619 }
4620 Ok(StepKind::Expand { path, overrides })
4621}
4622
4623#[derive(Default)]
4627pub(crate) struct IoBindingSet {
4628 stdin: Option<IoBinding>,
4629 stdout: Option<IoBinding>,
4630 stderr: Option<IoBinding>,
4631 tty: Option<IoBinding>,
4632 rows: Option<IoBinding>,
4633 cols: Option<IoBinding>,
4634}
4635
4636impl IoBindingSet {
4637 pub(crate) fn insert(&mut self, binding: IoBinding) {
4638 match binding.stream {
4639 IoStream::Stdin => self.stdin = Some(binding),
4640 IoStream::Stdout => self.stdout = Some(binding),
4641 IoStream::Stderr => self.stderr = Some(binding),
4642 IoStream::Tty => self.tty = Some(binding),
4643 IoStream::Rows(_) => self.rows = Some(binding),
4644 IoStream::Cols(_) => self.cols = Some(binding),
4645 }
4646 }
4647
4648 pub(crate) fn into_vec(self) -> Vec<IoBinding> {
4649 let mut out = Vec::new();
4650 if let Some(binding) = self.stdin {
4651 out.push(binding);
4652 }
4653 if let Some(binding) = self.stdout {
4654 out.push(binding);
4655 }
4656 if let Some(binding) = self.stderr {
4657 out.push(binding);
4658 }
4659 if let Some(binding) = self.tty {
4660 out.push(binding);
4661 }
4662 if let Some(binding) = self.rows {
4663 out.push(binding);
4664 }
4665 if let Some(binding) = self.cols {
4666 out.push(binding);
4667 }
4668 out
4669 }
4670}
4671
4672pub(crate) fn merge_bindings(defaults: &[IoBinding], overrides: &[IoBinding]) -> Vec<IoBinding> {
4673 let mut set = IoBindingSet::default();
4674 for binding in defaults {
4675 set.insert(binding.clone());
4676 }
4677 for binding in overrides {
4678 set.insert(binding.clone());
4679 }
4680 set.into_vec()
4681}
4682
4683pub(crate) fn and_guard_exprs(
4684 left: Option<GuardExpr>,
4685 right: Option<GuardExpr>,
4686) -> Option<GuardExpr> {
4687 match (left, right) {
4688 (None, None) => None,
4689 (Some(expr), None) | (None, Some(expr)) => Some(expr),
4690 (Some(lhs), Some(rhs)) => Some(GuardExpr::all(vec![lhs, rhs])),
4691 }
4692}
4693
4694pub(crate) fn has_stdout_pipe(bindings: &[IoBinding]) -> bool {
4695 bindings
4696 .iter()
4697 .any(|b| b.stream == IoStream::Stdout && b.pipe.is_some())
4698}
4699
4700pub(crate) fn reject_async_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
4703 let bad = match kind {
4704 StepKind::AsyncBlock { .. }
4705 | StepKind::AssignAsync { .. }
4706 | StepKind::Await { .. }
4707 | StepKind::AwaitCapture { .. }
4708 | StepKind::Cancel { .. } => true,
4709 _ => {
4710 let mut bad = false;
4711 kind.walk_child_kinds(&mut |child| {
4712 bad = bad || reject_async_in_capture(ctx, child).is_err();
4713 });
4714 bad
4715 }
4716 };
4717 if bad {
4718 return Err(ParseError::structural("let", "LET capture cannot run ASYNC/AWAIT/CANCEL inline; use LET $t: HANDLE = ASYNC ... then LET $o: STRING = AWAIT $t".to_string(), ctx));
4719 }
4720 Ok(())
4721}
4722
4723pub(crate) fn reject_pipe_stdout_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
4726 if let StepKind::WithIo { bindings, .. } = kind
4727 && has_stdout_pipe(bindings)
4728 {
4729 return Err(ParseError::structural(
4730 "let",
4731 "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
4732 .to_string(),
4733 ctx,
4734 ));
4735 }
4736 let mut result = Ok(());
4737 kind.walk_child_kinds(&mut |child| {
4738 if result.is_ok() {
4739 result = reject_pipe_stdout_in_capture(ctx, child);
4740 }
4741 });
4742 result
4743}
4744
4745pub(crate) fn rewrite_isolated_inherit(body: &mut [Step]) {
4749 for step in body {
4750 rewrite_isolated_inherit_kind(&mut step.kind);
4751 }
4752}
4753
4754pub(crate) fn rewrite_isolated_inherit_kind(kind: &mut StepKind) {
4758 if let StepKind::InheritEnv { keys } = kind {
4759 *kind = StepKind::IsolatedInheritEnv { keys: keys.clone() };
4760 }
4761 match kind {
4762 StepKind::For { body, .. }
4763 | StepKind::While { body, .. }
4764 | StepKind::Timeout { body, .. }
4765 | StepKind::Isolated { body }
4766 | StepKind::AssignAsync { body, .. }
4767 | StepKind::AsyncBlock { body } => rewrite_isolated_inherit(body),
4768 StepKind::If {
4769 then_body,
4770 else_ifs,
4771 else_body,
4772 ..
4773 } => {
4774 rewrite_isolated_inherit(then_body);
4775 for (_, branch) in else_ifs {
4776 rewrite_isolated_inherit(branch);
4777 }
4778 if let Some(else_body) = else_body {
4779 rewrite_isolated_inherit(else_body);
4780 }
4781 }
4782 StepKind::WithIo { cmd, .. } | StepKind::AssignCapture { cmd, .. } => {
4783 rewrite_isolated_inherit_kind(cmd);
4784 }
4785 _ => {}
4786 }
4787}
4788
4789pub(crate) fn contains_inherit_env(kind: &StepKind) -> bool {
4790 if matches!(kind, StepKind::InheritEnv { .. }) {
4791 return true;
4792 }
4793 let mut found = false;
4794 kind.walk_child_kinds(&mut |child| {
4795 found = found || contains_inherit_env(child);
4796 });
4797 found
4798}
4799
4800pub(crate) fn reject_nested_inherit_env(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
4804 if contains_inherit_env(kind) {
4805 return Err(ParseError::structural(
4806 "inherit_env",
4807 "INHERIT_ENV cannot be nested inside other commands".to_string(),
4808 ctx,
4809 ));
4810 }
4811 Ok(())
4812}
4813
4814pub(crate) fn check_tty_wrapping(
4815 bindings: &[IoBinding],
4816 cmd: Option<&StepKind>,
4817 span: &SpanContext,
4818) -> ParseResult<()> {
4819 let has_tty = bindings.iter().any(|b| matches!(b.stream, IoStream::Tty));
4820 let has_geometry = bindings
4821 .iter()
4822 .any(|b| matches!(b.stream, IoStream::Rows(_) | IoStream::Cols(_)));
4823 if has_geometry && !has_tty {
4824 return Err(ParseError::structural(
4825 "with_io",
4826 "WITH_IO [rows]/[cols] need [tty] on the same step: geometry without a terminal has nothing to size".to_string(),
4827 span,
4828 ));
4829 }
4830 if !has_tty {
4831 return Ok(());
4832 }
4833 if bindings
4834 .iter()
4835 .any(|b| matches!(b.stream, IoStream::Stderr))
4836 {
4837 return Err(ParseError::structural(
4838 "with_io",
4839 "WITH_IO [tty] cannot bind stderr: the pty master carries stdout and stderr interleaved, so the two streams cannot demultiplex".to_string(),
4840 span,
4841 ));
4842 }
4843 match cmd {
4844 Some(StepKind::Run(_) | StepKind::RunExec { .. }) | None => Ok(()),
4845 Some(_) => Err(ParseError::structural(
4846 "with_io",
4847 "WITH_IO [tty] only wraps a RUN step: the pty master is one interleaved child stream, so terminal-unaware commands cannot run under it".to_string(),
4848 span,
4849 )),
4850 }
4851}
4852
4853pub(crate) fn reject_with_io_in_async(ctx: &SpanContext, body: &[Step]) -> ParseResult<()> {
4856 for step in body {
4857 if matches!(&step.kind, StepKind::WithIo { .. }) {
4858 return Err(ParseError::structural("async", "WITH_IO cannot be placed inside ASYNC. Place WITH_IO outside ASYNC instead (e.g. WITH_IO [...] ASYNC RUN ...)".to_string(), ctx));
4859 }
4860 }
4861 Ok(())
4862}
4863
4864pub(crate) fn validate_exports(
4872 ctx: &SpanContext,
4873 func_exports: &[String],
4874 type_exports: &[String],
4875 top: &HashSet<String>,
4876 top_types: &HashSet<String>,
4877 modules: &ModuleTable,
4878 top_imports: &[String],
4879) -> ParseResult<()> {
4880 for name in func_exports {
4881 let valid = match name.split_once(crate::constants::MODULE_SEPARATOR) {
4882 None => top.contains(name),
4883 Some((module, base)) if module == crate::constants::SCRIPT_MODULE_NAME => {
4884 top.contains(base)
4885 }
4886 Some((module, _base)) => match modules.modules.get(module) {
4887 None => {
4888 top_imports.iter().any(|m| m == module)
4896 }
4897 Some(None) => true,
4898 Some(Some(funcs)) => funcs.func_names.contains(_base),
4899 },
4900 };
4901 if !valid {
4902 return Err(ParseError::validation(
4903 crate::constants::KEYWORD_EXPORT,
4904 format!("EXPORT `{name}` does not match any top-level FUNC or known module member"),
4905 ctx,
4906 ));
4907 }
4908 }
4909 for name in type_exports {
4910 let valid = match name.split_once(crate::constants::MODULE_SEPARATOR) {
4917 None => top_types.contains(name) || !top_imports.is_empty(),
4918 Some((module, _base)) => {
4919 if module == crate::constants::SCRIPT_MODULE_NAME {
4920 top_types.contains(_base)
4921 } else {
4922 match modules.modules.get(module) {
4923 None => top_imports.iter().any(|m| m == module),
4924 Some(_) => true,
4930 }
4931 }
4932 }
4933 };
4934 if !valid {
4935 return Err(ParseError::validation(
4936 crate::constants::KEYWORD_EXPORT,
4937 format!("EXPORT TYPE `{name}` does not match any top-level TYPE"),
4938 ctx,
4939 ));
4940 }
4941 }
4942 Ok(())
4943}
4944
4945pub(crate) fn validate_remote_copy_placement(steps: &[Step], ctx: &SpanContext) -> ParseResult<()> {
4952 fn visit_kind(kind: &StepKind, in_remote: bool, ctx: &SpanContext) -> ParseResult<()> {
4953 if let StepKind::Copy {
4954 from_host, to_host, ..
4955 } = kind
4956 && (*from_host || *to_host)
4957 && !in_remote
4958 {
4959 return Err(ParseError::structural(
4960 "copy",
4961 "COPY --from-host and --to-host are only valid inside a REMOTE block".to_string(),
4962 ctx,
4963 ));
4964 }
4965 let child_remote = in_remote || matches!(kind, StepKind::RemoteBlock { .. });
4966 let mut result = Ok(());
4967 kind.walk_child_kinds(&mut |child| {
4968 if result.is_ok() {
4969 result = visit_kind(child, child_remote, ctx);
4970 }
4971 });
4972 result
4973 }
4974 for step in steps {
4975 visit_kind(&step.kind, false, ctx)?;
4976 }
4977 Ok(())
4978}
4979
4980pub(crate) fn contains_remote_block(steps: &[Step]) -> bool {
4984 steps.iter().any(|step| contains_remote_kind(&step.kind))
4985}
4986
4987pub(crate) fn contains_remote_kind(kind: &StepKind) -> bool {
4988 if matches!(kind, StepKind::RemoteBlock { .. }) {
4989 return true;
4990 }
4991 let mut found = false;
4992 kind.walk_child_kinds(&mut |child| {
4993 found = found || contains_remote_kind(child);
4994 });
4995 found
4996}
4997
4998pub(crate) fn collect_remote_body_symbols(
5004 steps: &[Step],
5005 defs: &mut HashSet<String>,
5006 calls: &mut Vec<String>,
5007) {
5008 for step in steps {
5009 collect_remote_kind_symbols(&step.kind, defs, calls);
5010 }
5011}
5012
5013pub(crate) fn collect_remote_kind_symbols(
5014 kind: &StepKind,
5015 defs: &mut HashSet<String>,
5016 calls: &mut Vec<String>,
5017) {
5018 if let StepKind::FuncDef { name, .. } = kind {
5019 defs.insert(name.clone());
5020 }
5021 if let StepKind::Call { name, .. } = kind {
5022 calls.push(name.clone());
5023 }
5024 kind.walk_step_exprs(&mut |expr| match expr {
5025 Expr::Call { name, .. } => calls.push(name.clone()),
5026 Expr::CompiledMath(ops) => {
5027 for op in ops {
5028 if let MathOp::Call { name, .. } = op {
5029 calls.push(name.clone());
5030 }
5031 }
5032 }
5033 Expr::Block(steps) => collect_remote_body_symbols(steps, defs, calls),
5034 _ => {}
5035 });
5036}
5037
5038pub(crate) fn reject_boundary(ctx: &SpanContext, expr: &Expr) -> ParseResult<()> {
5047 if matches!(expr, Expr::UnsignedIntBoundary(_)) {
5048 return Err(ParseError::structural(
5049 "expr",
5050 "integer overflow: 9223372036854775808 exceeds i64::MAX".to_string(),
5051 ctx,
5052 ));
5053 }
5054 Ok(())
5055}
5056
5057pub(crate) fn apply_unary_neg(ctx: &SpanContext, expr: Expr) -> ParseResult<Expr> {
5061 match expr {
5062 Expr::Literal(v) => match (v.as_i64(), v.as_f64()) {
5063 (Some(n), _) => match n.checked_neg() {
5064 Some(neg) => Ok(Expr::Literal(Value::int(neg))),
5065 None => Ok(Expr::CompiledMath(vec![MathOp::PushConst(v), MathOp::Neg])),
5066 },
5067 (None, Some(f)) => Ok(Expr::Literal(Value::float(-f))),
5068 (None, None) => {
5069 let other = Expr::Literal(v);
5070 if let Some(mut ops) = expr_to_rpn(&other) {
5071 ops.push(MathOp::Neg);
5072 Ok(Expr::CompiledMath(ops))
5073 } else {
5074 Ok(Expr::Arithmetic {
5077 op: ArithOp::Sub,
5078 left: Box::new(Expr::Literal(Value::int(0))),
5079 right: Box::new(other),
5080 })
5081 }
5082 }
5083 },
5084 Expr::UnsignedIntBoundary(n) => {
5085 if n == i64::MAX as u64 + 1 {
5086 Ok(Expr::Literal(Value::int(i64::MIN)))
5087 } else {
5088 Err(ParseError::structural(
5089 "expr",
5090 format!("integer overflow: {} exceeds i64::MAX", n),
5091 ctx,
5092 ))
5093 }
5094 }
5095 other => {
5096 if let Some(mut ops) = expr_to_rpn(&other) {
5097 ops.push(MathOp::Neg);
5098 Ok(Expr::CompiledMath(ops))
5099 } else {
5100 Ok(Expr::Arithmetic {
5103 op: ArithOp::Sub,
5104 left: Box::new(Expr::Literal(Value::int(0))),
5105 right: Box::new(other),
5106 })
5107 }
5108 }
5109 }
5110}
5111
5112fn try_fold_arith(op: ArithOp, left: &Expr, right: &Expr) -> Option<Expr> {
5117 let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
5118 return None;
5119 };
5120 fold_arith_values(op, lv, rv).map(Expr::Literal)
5121}
5122
5123fn fold_arith_values(op: ArithOp, left: &Value, right: &Value) -> Option<Value> {
5124 match (left.as_i64(), right.as_i64()) {
5125 (Some(a), Some(b)) => {
5126 let v = match op {
5127 ArithOp::Add => a.checked_add(b)?,
5128 ArithOp::Sub => a.checked_sub(b)?,
5129 ArithOp::Mul => a.checked_mul(b)?,
5130 ArithOp::Div => a.checked_div(b)?,
5131 };
5132 Some(Value::int(v))
5133 }
5134 _ => {
5135 let (af, bf) = (as_f64(left)?, as_f64(right)?);
5136 fold_float(op, af, bf)
5137 }
5138 }
5139}
5140
5141fn fold_float(op: ArithOp, a: f64, b: f64) -> Option<Value> {
5142 if !a.is_finite() || !b.is_finite() {
5143 return None;
5144 }
5145 let v = match op {
5146 ArithOp::Add => a + b,
5147 ArithOp::Sub => a - b,
5148 ArithOp::Mul => a * b,
5149 ArithOp::Div => {
5150 if b == 0.0 {
5151 return None;
5152 }
5153 a / b
5154 }
5155 };
5156 if v.is_finite() {
5157 Some(Value::float(v))
5158 } else {
5159 None
5160 }
5161}
5162
5163fn try_fold_compare(op: CompareOp, left: &Expr, right: &Expr) -> Option<Expr> {
5164 let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
5165 return None;
5166 };
5167 match (lv.as_i64(), rv.as_i64()) {
5168 (Some(a), Some(b)) => {
5169 let r = match op {
5170 CompareOp::Eq => a == b,
5171 CompareOp::Ne => a != b,
5172 CompareOp::Lt => a < b,
5173 CompareOp::Le => a <= b,
5174 CompareOp::Gt => a > b,
5175 CompareOp::Ge => a >= b,
5176 };
5177 Some(Expr::Literal(Value::bool(r)))
5178 }
5179 _ => {
5180 if let (Some(a), Some(b)) = (lv.as_bool(), rv.as_bool()) {
5181 return match op {
5182 CompareOp::Eq => Some(Expr::Literal(Value::bool(a == b))),
5183 CompareOp::Ne => Some(Expr::Literal(Value::bool(a != b))),
5184 _ => None,
5185 };
5186 }
5187 let (af, bf) = (as_f64(lv)?, as_f64(rv)?);
5188 let r = match op {
5189 CompareOp::Eq => af == bf,
5190 CompareOp::Ne => af != bf,
5191 CompareOp::Lt => af < bf,
5192 CompareOp::Le => af <= bf,
5193 CompareOp::Gt => af > bf,
5194 CompareOp::Ge => af >= bf,
5195 };
5196 Some(Expr::Literal(Value::bool(r)))
5197 }
5198 }
5199}
5200
5201fn as_f64(v: &Value) -> Option<f64> {
5202 if let Some(n) = v.as_i64() {
5203 return Some(n as f64);
5204 }
5205 match v.as_f64() {
5206 Some(f) if f.is_finite() => Some(f),
5207 _ => None,
5208 }
5209}
5210
5211pub(crate) fn make_arith(
5213 ctx: &SpanContext,
5214 op: ArithOp,
5215 left: Expr,
5216 right: Expr,
5217) -> ParseResult<Expr> {
5218 reject_boundary(ctx, &left)?;
5219 reject_boundary(ctx, &right)?;
5220 if let Some(folded) = try_fold_arith(op, &left, &right) {
5221 return Ok(folded);
5222 }
5223 if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
5224 lops.append(&mut rops);
5225 lops.push(match op {
5226 ArithOp::Add => MathOp::Add,
5227 ArithOp::Sub => MathOp::Sub,
5228 ArithOp::Mul => MathOp::Mul,
5229 ArithOp::Div => MathOp::Div,
5230 });
5231 return Ok(Expr::CompiledMath(lops));
5232 }
5233 Ok(Expr::Arithmetic {
5234 op,
5235 left: Box::new(left),
5236 right: Box::new(right),
5237 })
5238}
5239
5240pub(crate) fn make_compare(
5242 ctx: &SpanContext,
5243 op: CompareOp,
5244 left: Expr,
5245 right: Expr,
5246) -> ParseResult<Expr> {
5247 reject_boundary(ctx, &left)?;
5248 reject_boundary(ctx, &right)?;
5249 if let Some(folded) = try_fold_compare(op, &left, &right) {
5250 return Ok(folded);
5251 }
5252 if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
5253 lops.append(&mut rops);
5254 lops.push(match op {
5255 CompareOp::Eq => MathOp::Eq,
5256 CompareOp::Ne => MathOp::Ne,
5257 CompareOp::Lt => MathOp::Lt,
5258 CompareOp::Le => MathOp::Le,
5259 CompareOp::Gt => MathOp::Gt,
5260 CompareOp::Ge => MathOp::Ge,
5261 });
5262 return Ok(Expr::CompiledMath(lops));
5263 }
5264 Ok(Expr::Compare {
5265 op,
5266 left: Box::new(left),
5267 right: Box::new(right),
5268 })
5269}
5270
5271pub(crate) fn expr_to_rpn(expr: &Expr) -> Option<Vec<MathOp>> {
5277 match expr {
5278 Expr::Literal(v) => Some(vec![MathOp::PushConst(v.clone())]),
5279 Expr::Var(name) => Some(vec![MathOp::LoadVar(name.clone())]),
5280 Expr::Env(key) => Some(vec![MathOp::LoadEnv(key.clone())]),
5281 Expr::KeyPath { base, keys } => Some(vec![MathOp::LoadKeyPath {
5282 base: base.clone(),
5283 keys: keys.clone(),
5284 }]),
5285 Expr::Call { name, args } => {
5286 let mut ops = Vec::new();
5287 for arg in args {
5288 ops.extend(expr_to_rpn(arg)?);
5289 }
5290 ops.push(MathOp::Call {
5291 name: name.clone(),
5292 arity: args.len(),
5293 });
5294 Some(ops)
5295 }
5296 Expr::Inspect(var) => Some(vec![MathOp::Inspect(var.clone())]),
5297 Expr::Arithmetic { op, left, right } => {
5298 let mut ops = expr_to_rpn(left)?;
5299 ops.extend(expr_to_rpn(right)?);
5300 ops.push(match op {
5301 ArithOp::Add => MathOp::Add,
5302 ArithOp::Sub => MathOp::Sub,
5303 ArithOp::Mul => MathOp::Mul,
5304 ArithOp::Div => MathOp::Div,
5305 });
5306 Some(ops)
5307 }
5308 Expr::Compare { op, left, right } => {
5309 let mut ops = expr_to_rpn(left)?;
5310 ops.extend(expr_to_rpn(right)?);
5311 ops.push(match op {
5312 CompareOp::Eq => MathOp::Eq,
5313 CompareOp::Ne => MathOp::Ne,
5314 CompareOp::Lt => MathOp::Lt,
5315 CompareOp::Le => MathOp::Le,
5316 CompareOp::Gt => MathOp::Gt,
5317 CompareOp::Ge => MathOp::Ge,
5318 });
5319 Some(ops)
5320 }
5321 Expr::CompiledMath(ops) => Some(ops.clone()),
5322 Expr::FreshPipe => None,
5323 Expr::Not(_) | Expr::Logical { .. } | Expr::List(_) | Expr::Map(_) | Expr::Block(_) => None,
5324 Expr::UnsignedIntBoundary(_) => None,
5325 }
5326}
5327
5328pub(crate) fn classify_numeric_text(text: &str) -> Result<Expr, String> {
5333 let clean = text.replace('_', "");
5334 if clean.contains('.') {
5335 let parsed: f64 = clean
5336 .parse()
5337 .map_err(|_| format!("invalid float literal {text:?}"))?;
5338 if !parsed.is_finite() {
5339 return Err(format!("invalid float literal {text:?}"));
5340 }
5341 return Ok(Expr::Literal(Value::float(parsed)));
5342 }
5343 let digits: u64 = clean
5344 .parse()
5345 .map_err(|_| format!("integer overflow: {text:?} exceeds i64::MAX"))?;
5346 if digits <= i64::MAX as u64 {
5347 Ok(Expr::Literal(Value::int(digits as i64)))
5348 } else if digits == i64::MAX as u64 + 1 {
5349 Ok(Expr::UnsignedIntBoundary(digits))
5350 } else {
5351 Err(format!("integer overflow: {text:?} exceeds i64::MAX"))
5352 }
5353}
5354
5355#[cfg(test)]
5356mod tests {
5357 use super::*;
5358 use crate::command::{
5359 format_byte_count, format_duration, parse_byte_count, parse_duration,
5360 strip_digit_separators,
5361 };
5362 use crate::parser::parse_script;
5363
5364 fn parse_err(script: &str) -> String {
5365 parse_script(script, lower_command)
5366 .expect_err("script must fail to parse")
5367 .to_string()
5368 }
5369
5370 #[test]
5371 fn malformed_with_io_binding_names_the_bad_binding() {
5372 let err = parse_err("WITH_IO [stdout=discard] ECHO \"test\"\n");
5373 assert!(err.contains("invalid syntax for command WITH_IO"), "{err}");
5374 assert!(!err.contains("unknown command"), "{err}");
5375 assert!(err.contains("stdout=discard"), "{err}");
5376 assert!(err.contains("[stdout=$p]"), "{err}");
5377 }
5378
5379 #[test]
5380 fn connect_is_unknown_command() {
5381 let err = parse_err("CONNECT 127.0.0.1:8080\n");
5384 assert!(err.contains("unknown command"), "{err}");
5385 assert!(err.contains("CONNECT"), "{err}");
5386 }
5387
5388 #[test]
5389 fn listen_is_unknown_command() {
5390 let err = parse_err("LISTEN 127.0.0.1:8080\n");
5393 assert!(err.contains("unknown command"), "{err}");
5394 assert!(err.contains("LISTEN"), "{err}");
5395 }
5396
5397 #[test]
5398 fn await_without_task_variable_points_at_syntax() {
5399 let err = parse_err("AWAIT ECHO \"test\"\n");
5400 assert!(err.contains("invalid syntax for command AWAIT"), "{err}");
5401 assert!(!err.contains("unknown command"), "{err}");
5402 assert!(err.contains("AWAIT $t"), "{err}");
5403 assert!(err.contains("ECHO"), "{err}");
5404 }
5405
5406 #[test]
5407 fn bare_let_without_type_points_at_typed_syntax() {
5408 let err = parse_err("LET $x = 1\n");
5409 assert!(err.contains("invalid syntax for command LET"), "{err}");
5410 assert!(err.contains("LET $name: STRING = <expr>"), "{err}");
5411 }
5412
5413 #[test]
5414 fn workspace_accepts_all_four_targets_uppercase_only() {
5415 for (spelling, target) in [
5418 ("SNAPSHOT", WorkspaceTarget::Snapshot),
5419 ("LOCAL", WorkspaceTarget::Local),
5420 ("CACHE", WorkspaceTarget::Cache { local: false }),
5421 ("SYSTEM", WorkspaceTarget::System),
5422 ] {
5423 let steps =
5424 parse_script(&format!("WORKSPACE {spelling}\n"), lower_command).expect("parses");
5425 assert_eq!(steps.len(), 1);
5426 assert_eq!(steps[0].kind, StepKind::Workspace(target.clone()));
5427 assert_eq!(steps[0].kind.to_string(), format!("WORKSPACE {target}"));
5428 }
5429 for spelling in ["snapshot", "local", "cache", "system"] {
5430 let err = parse_err(&format!("WORKSPACE {spelling}\n"));
5431 assert!(
5432 err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
5433 "{spelling}: {err}"
5434 );
5435 }
5436 let err = parse_err("WORKSPACE REMOTE\n");
5437 assert!(
5438 err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
5439 "{err}"
5440 );
5441
5442 let steps = parse_script("WORKSPACE CACHE --local\n", lower_command).expect("parses");
5445 assert_eq!(
5446 steps[0].kind,
5447 StepKind::Workspace(WorkspaceTarget::Cache { local: true })
5448 );
5449 assert_eq!(steps[0].kind.to_string(), "WORKSPACE CACHE --local");
5450 for bad in [
5451 "WORKSPACE SNAPSHOT --local\n",
5452 "WORKSPACE LOCAL --local\n",
5453 "WORKSPACE SYSTEM --local\n",
5454 ] {
5455 let err = parse_err(bad);
5456 assert!(err.contains("--local requires CACHE"), "{bad}: {err}");
5457 }
5458 }
5459
5460 #[test]
5461 fn archive_unarchive_parse_and_round_trip() {
5462 let steps = parse_script("ARCHIVE bundle bundle.tar.gz\n", lower_command).expect("parses");
5463 match &steps[0].kind {
5464 StepKind::Archive { src, dst, raw } => {
5465 assert_eq!(src.as_str(), "bundle");
5466 assert_eq!(dst.as_str(), "bundle.tar.gz");
5467 assert!(!raw);
5468 }
5469 other => panic!("expected Archive, got {other:?}"),
5470 }
5471 assert_eq!(
5472 steps[0].kind.to_string(),
5473 "ARCHIVE bundle \"bundle.tar.gz\""
5474 );
5475
5476 let steps =
5477 parse_script("ARCHIVE --raw tool.bin tool.tar\n", lower_command).expect("parses");
5478 assert!(
5479 matches!(&steps[0].kind, StepKind::Archive { raw: true, .. }),
5480 "unexpected lowering: {:?}",
5481 steps[0].kind
5482 );
5483 assert_eq!(
5484 steps[0].kind.to_string(),
5485 "ARCHIVE --raw \"tool.bin\" \"tool.tar\""
5486 );
5487
5488 let steps =
5489 parse_script("UNARCHIVE pack.tar.gz unpacked\n", lower_command).expect("parses");
5490 match &steps[0].kind {
5491 StepKind::Unarchive {
5492 src,
5493 dst,
5494 max_bytes,
5495 } => {
5496 assert_eq!(src.as_str(), "pack.tar.gz");
5497 assert_eq!(dst.as_str(), "unpacked");
5498 assert_eq!(max_bytes, &None);
5499 }
5500 other => panic!("expected Unarchive, got {other:?}"),
5501 }
5502 assert_eq!(
5503 steps[0].kind.to_string(),
5504 "UNARCHIVE \"pack.tar.gz\" unpacked"
5505 );
5506
5507 let steps = parse_script(
5508 "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
5509 lower_command,
5510 )
5511 .expect("parses");
5512 match &steps[0].kind {
5513 StepKind::Unarchive {
5514 src,
5515 dst,
5516 max_bytes,
5517 } => {
5518 assert_eq!(src.as_str(), "pack.tar.gz");
5519 assert_eq!(dst.as_str(), "unpacked");
5520 assert_eq!(max_bytes.as_ref().map(|a| a.as_str()), Some("100_000"));
5521 }
5522 other => panic!("expected Unarchive, got {other:?}"),
5523 }
5524 assert_eq!(
5525 steps[0].kind.to_string(),
5526 "UNARCHIVE --max-bytes \"100_000\" \"pack.tar.gz\" unpacked"
5527 );
5528
5529 for script in [
5530 "ARCHIVE bundle bundle.tar.gz\n",
5531 "ARCHIVE --raw tool.bin tool.tar\n",
5532 "UNARCHIVE pack.tar.gz unpacked\n",
5533 "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
5534 ] {
5535 let first = parse_script(script, lower_command).expect("parses");
5536 let rendered = first[0].kind.to_string() + "\n";
5537 let second = parse_script(&rendered, lower_command).expect("reparses");
5538 assert_eq!(
5541 second[0].kind.to_string(),
5542 first[0].kind.to_string(),
5543 "Display must fixpoint for {script:?}"
5544 );
5545 }
5546
5547 for bad in ["ARCHIVE only-src\n", "ARCHIVE\n", "UNARCHIVE only-src\n"] {
5548 let err = parse_err(bad);
5549 assert!(
5550 err.contains("ARCHIVE") || err.contains("UNARCHIVE"),
5551 "{bad}: {err}"
5552 );
5553 }
5554 }
5555
5556 #[test]
5557 fn copy_from_workspace_selects_source_root() {
5558 for (spelling, target) in [
5559 ("SNAPSHOT", WorkspaceTarget::Snapshot),
5560 ("LOCAL", WorkspaceTarget::Local),
5561 ("CACHE", WorkspaceTarget::Cache { local: false }),
5562 ("SYSTEM", WorkspaceTarget::System),
5563 ] {
5564 let steps = parse_script(
5565 &format!("COPY --from-workspace {spelling} a.txt b.txt\n"),
5566 lower_command,
5567 )
5568 .expect("parses");
5569 assert!(
5570 matches!(&steps[0].kind, StepKind::Copy { from_workspace: Some(t), .. } if *t == target),
5571 "unexpected lowering for {spelling}: {:?}",
5572 steps[0].kind
5573 );
5574 }
5575 for script in [
5578 "COPY --from-workspace=CACHE a.txt b.txt\n",
5579 "COPY --from-workspace=\"CACHE\" a.txt b.txt\n",
5580 ] {
5581 let steps = parse_script(script, lower_command).expect("parses");
5582 assert!(
5583 matches!(
5584 &steps[0].kind,
5585 StepKind::Copy {
5586 from_workspace: Some(WorkspaceTarget::Cache { local: false }),
5587 ..
5588 }
5589 ),
5590 "unexpected lowering for {script:?}: {:?}",
5591 steps[0].kind
5592 );
5593 }
5594 let steps = parse_script("COPY a.txt b.txt\n", lower_command).expect("parses");
5596 assert!(
5597 matches!(
5598 &steps[0].kind,
5599 StepKind::Copy {
5600 from_workspace: None,
5601 ..
5602 }
5603 ),
5604 "unexpected lowering: {:?}",
5605 steps[0].kind
5606 );
5607 for bad in ["REMOTE", "local"] {
5609 let err = parse_err(&format!("COPY --from-workspace {bad} a.txt b.txt\n"));
5610 assert!(err.contains("unknown workspace source"), "{bad}: {err}");
5611 }
5612 }
5613
5614 #[test]
5615 fn symlink_from_workspace_selects_source_root() {
5616 for (spelling, target) in [
5617 ("SNAPSHOT", WorkspaceTarget::Snapshot),
5618 ("LOCAL", WorkspaceTarget::Local),
5619 ("CACHE", WorkspaceTarget::Cache { local: false }),
5620 ("SYSTEM", WorkspaceTarget::System),
5621 ] {
5622 let steps = parse_script(
5623 &format!("SYMLINK --from-workspace {spelling} a.txt b.txt\n"),
5624 lower_command,
5625 )
5626 .expect("parses");
5627 assert!(
5628 matches!(&steps[0].kind, StepKind::Symlink { from_workspace: Some(t), .. } if *t == target),
5629 "unexpected lowering for {spelling}: {:?}",
5630 steps[0].kind
5631 );
5632 let roundtrip = steps[0].kind.to_string();
5633 assert!(
5634 roundtrip.contains("--from-workspace"),
5635 "display should round-trip the flag: {roundtrip}"
5636 );
5637 }
5638 let steps = parse_script("SYMLINK a.txt b.txt\n", lower_command).expect("parses");
5639 assert!(
5640 matches!(
5641 &steps[0].kind,
5642 StepKind::Symlink {
5643 from_workspace: None,
5644 ..
5645 }
5646 ),
5647 "unexpected lowering: {:?}",
5648 steps[0].kind
5649 );
5650 for bad in ["REMOTE", "local"] {
5651 let err = parse_err(&format!("SYMLINK --from-workspace {bad} a.txt b.txt\n"));
5652 assert!(err.contains("unknown workspace source"), "{bad}: {err}");
5653 }
5654 let steps = parse_script(
5656 "SYMLINK --from-workspace=LOCAL a.txt b.txt\n",
5657 lower_command,
5658 )
5659 .expect("parses");
5660 assert!(
5661 matches!(
5662 &steps[0].kind,
5663 StepKind::Symlink {
5664 from_workspace: Some(WorkspaceTarget::Local),
5665 ..
5666 }
5667 ),
5668 "unexpected lowering: {:?}",
5669 steps[0].kind
5670 );
5671 }
5672
5673 #[test]
5674 fn dash_dash_equals_tokens_bypass_assignment() {
5675 let steps = parse_script("ENV --foo=bar\n", lower_command).expect("parses");
5678 let StepKind::Env { key, value } = &steps[0].kind else {
5679 panic!("expected Env, got {:?}", steps[0].kind);
5680 };
5681 assert_eq!(key, "--foo");
5682 assert_eq!(value.as_str(), "bar");
5683
5684 let steps = parse_script("RUN echo --foo=bar\n", lower_command).expect("parses");
5685 let StepKind::Run(cmd) = &steps[0].kind else {
5686 panic!("expected Run, got {:?}", steps[0].kind);
5687 };
5688 assert!(
5689 cmd.as_str().contains("--foo=bar"),
5690 "unexpected RUN lowering: {cmd:?}"
5691 );
5692
5693 let digest = "08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c";
5694 let steps = parse_script(&format!("ASSERT_EQ --hash={digest} $body\n"), lower_command)
5695 .expect("parses");
5696 let StepKind::AssertEq { hash, .. } = &steps[0].kind else {
5697 panic!("expected AssertEq, got {:?}", steps[0].kind);
5698 };
5699 assert_eq!(hash.as_deref(), Some(digest));
5700
5701 let steps = parse_script("EXPAND --k=v\n", lower_command).expect("parses");
5703 let StepKind::Expand { path, overrides } = &steps[0].kind else {
5704 panic!("expected Expand, got {:?}", steps[0].kind);
5705 };
5706 assert!(path.is_none());
5707 assert_eq!(overrides.len(), 1);
5708 assert_eq!(overrides[0].0.as_str(), "--k");
5709 }
5710
5711 #[test]
5712 fn assert_ne_lowers_and_round_trips() {
5713 let steps = parse_script("ASSERT_NE $status 404\n", lower_command).expect("parses");
5714 let StepKind::AssertNe {
5715 hash,
5716 actual,
5717 expected,
5718 } = &steps[0].kind
5719 else {
5720 panic!("expected AssertNe, got {:?}", steps[0].kind);
5721 };
5722 assert!(hash.is_none());
5723 assert!(
5724 matches!(actual, AssertTarget::Value(_)),
5725 "unexpected actual: {actual:?}"
5726 );
5727 assert!(
5728 matches!(expected, Some(Arg::Expr(_))),
5729 "numeric expected lowers to an expression: {expected:?}"
5730 );
5731 let roundtrip = steps[0].kind.to_string();
5732 assert!(
5733 roundtrip.contains(Command::AssertNe.as_str()) && roundtrip.contains("404"),
5734 "display should round-trip the command: {roundtrip}"
5735 );
5736
5737 let err = parse_script("ASSERT_NE $status\n", lower_command).expect_err("needs expected");
5738 assert!(
5739 err.to_string().contains("requires an expected value"),
5740 "unexpected error: {err}"
5741 );
5742
5743 let err = parse_script("ASSERT_NE --hash abc123 $status \"junk\"\n", lower_command)
5744 .expect_err("hash plus expected must fail");
5745 assert!(
5746 err.to_string().contains("cannot be combined"),
5747 "unexpected error: {err}"
5748 );
5749
5750 let err = parse_script("ASSERT_EQ --hash abc123 $status \"junk\"\n", lower_command)
5752 .expect_err("hash plus expected must fail");
5753 assert!(
5754 err.to_string().contains("cannot be combined"),
5755 "unexpected error: {err}"
5756 );
5757 }
5758
5759 #[test]
5760 fn space_before_paren_is_not_a_call() {
5761 let steps = parse_script("ECHO (1 + 2)\n", lower_command).expect("parses");
5764 assert_eq!(steps.len(), 1);
5765 assert!(
5766 !matches!(steps[0].kind, crate::ast::StepKind::Call { .. }),
5767 "space before paren must not route to a call: {:?}",
5768 steps[0].kind
5769 );
5770 }
5771
5772 #[test]
5773 fn unknown_type_tag_parses_as_custom() {
5774 let steps = parse_script("LET $x: FOO = 1\n", lower_command).expect("custom tag parses");
5778 let StepKind::Assign { decl_type, .. } = &steps[0].kind else {
5779 panic!("expected Assign, got {:?}", steps[0].kind);
5780 };
5781 assert_eq!(decl_type, "FOO");
5782 }
5783
5784 #[test]
5785 fn bare_for_without_types_is_rejected() {
5786 let err = parse_err("FOR $i IN [1] { ECHO hi }\n");
5787 assert!(err.contains("FOR requires explicit types"), "{err}");
5788 }
5789
5790 #[test]
5791 fn mutate_statement_parses_without_keyword() {
5792 let steps = parse_script("$y = 2\n", lower_command).expect("mutation parses");
5793 assert!(matches!(steps[0].kind, StepKind::Set { .. }));
5794 }
5795
5796 #[test]
5797 fn set_keyword_is_rejected_with_mutation_hint() {
5798 let err = parse_err("SET $y = 2\n");
5799 assert!(err.contains("not a keyword"), "{err}");
5800 assert!(err.contains("$var = <expr>"), "{err}");
5801 }
5802
5803 #[test]
5804 fn structural_fallthrough_commits_per_keyword() {
5805 for (script, cmd) in [
5806 ("CANCEL foo\n", "CANCEL"),
5807 ("TIMEOUT foo\n", "TIMEOUT"),
5808 ("FOR foo\n", "FOR"),
5809 ("IF foo\n", "IF"),
5810 ("LET foo\n", "LET"),
5811 ("ASYNC\n", "ASYNC"),
5815 ("ELSE foo\n", "ELSE"),
5816 ] {
5817 let err = parse_err(script);
5818 assert!(
5819 err.contains(&format!("invalid syntax for command {cmd}")),
5820 "{cmd}: {err}"
5821 );
5822 assert!(!err.contains("unknown command"), "{cmd}: {err}");
5823 }
5824 }
5825
5826 #[test]
5827 fn leaf_arity_errors_carry_invalid_syntax_prefix() {
5828 let err = parse_err("SLEEP 1s 2s\n");
5829 assert!(err.contains("invalid syntax for command SLEEP"), "{err}");
5830 assert!(!err.contains("unknown command"), "{err}");
5831 }
5832
5833 #[test]
5834 fn list_append_lowers_variable_and_item() {
5835 let steps = parse_script("LIST_APPEND $items \"hi\"\n", lower_command).expect("parses");
5836 let StepKind::ListAppend { list, item } = &steps[0].kind else {
5837 panic!("expected ListAppend, got {:?}", steps[0].kind);
5838 };
5839 assert_eq!(list, "items");
5840 assert!(matches!(item, Arg::String(s, _) if s == "hi"));
5841 assert_eq!(steps[0].kind.to_string(), "LIST_APPEND $items \"hi\"");
5842 }
5843
5844 #[test]
5845 fn list_append_rejects_wrong_arity() {
5846 for script in [
5847 "LIST_APPEND\n",
5848 "LIST_APPEND $items\n",
5849 "LIST_APPEND $items \"a\" \"b\"\n",
5850 ] {
5851 let err = parse_err(script);
5852 assert!(
5853 err.contains("invalid syntax for command LIST_APPEND"),
5854 "{script}: {err}"
5855 );
5856 assert!(!err.contains("unknown command"), "{script}: {err}");
5857 }
5858 }
5859
5860 #[test]
5861 fn list_append_rejects_non_variable_target() {
5862 let err = parse_err("LIST_APPEND items \"a\"\n");
5863 assert!(
5864 err.contains("invalid syntax for command LIST_APPEND"),
5865 "{err}"
5866 );
5867 assert!(!err.contains("unknown command"), "{err}");
5868 }
5869
5870 #[test]
5871 fn read_line_rejects_bare_word_target() {
5872 let err = parse_err("READ_LINE reply\n");
5876 assert!(err.contains("READ_LINE requires a $variable"), "{err}");
5877 assert!(!err.contains("unknown command"), "{err}");
5878 }
5879
5880 #[test]
5881 fn genuinely_unknown_command_keeps_bare_message() {
5882 let err = parse_err("FROBNICATE hi\n");
5883 assert!(err.contains("unknown command: FROBNICATE"), "{err}");
5884 assert!(!err.contains("did you mean"), "{err}");
5885 }
5886
5887 #[test]
5888 fn lowercase_command_suggests_uppercase() {
5889 let err = lower_command("echo", vec![Arg::String("hi".to_string(), false)])
5893 .expect_err("must fail")
5894 .to_string();
5895 assert!(err.contains("unknown command: echo"), "{err}");
5896 assert!(err.contains("did you mean `ECHO`"), "{err}");
5897 }
5898
5899 #[test]
5900 fn func_def_requires_typed_uppercase_name() {
5901 let steps = parse_script(
5902 "FUNC GREET($name: STRING) {\n RETURN $name\n}\n",
5903 lower_command,
5904 )
5905 .expect("func def parses");
5906 let StepKind::FuncDef {
5907 name,
5908 params,
5909 body,
5910 docs,
5911 } = &steps[0].kind
5912 else {
5913 panic!("expected FuncDef, got {:?}", steps[0].kind);
5914 };
5915 assert_eq!(name, "GREET");
5916 assert_eq!(
5917 params,
5918 &vec![("name".to_string(), "STRING".to_string())],
5919 "{params:?}"
5920 );
5921 assert!(matches!(body[0].kind, StepKind::Return { .. }));
5922 assert!(docs.is_none(), "undocumented FUNC carries no docs");
5923 }
5924
5925 #[test]
5926 fn lowercase_func_name_is_rejected() {
5927 let err = parse_err("FUNC greet($x: STRING) {\n RETURN $x\n}\n");
5928 assert!(err.contains("FUNC"), "{err}");
5929 }
5930
5931 #[test]
5932 fn call_and_while_lower_correctly() {
5933 let steps = parse_script(
5934 "FUNC GREET($name: STRING) {\n RETURN $name\n}\nGREET(\"ada\")\n",
5935 lower_command,
5936 )
5937 .expect("call parses");
5938 assert!(
5939 matches!(&steps[1].kind, StepKind::Call { name, .. } if name == "SCRIPT::GREET"),
5940 "{:?}",
5941 steps[1].kind
5942 );
5943 let steps = parse_script(
5944 "FUNC GREET($a: STRING, $b: STRING) {\n RETURN $a\n}\nGREET(\"ada\", \"bex\")\n",
5945 lower_command,
5946 )
5947 .expect("spaced call parses");
5948 assert!(
5949 matches!(&steps[1].kind, StepKind::Call { name, args } if name == "SCRIPT::GREET" && args.len() == 2),
5950 "{:?}",
5951 steps[1].kind
5952 );
5953 let steps = parse_script(
5954 indoc! {r#"
5955 WHILE !$done {
5956 BREAK
5957 }
5958 "#},
5959 lower_command,
5960 )
5961 .expect("while parses");
5962 let StepKind::While { body, .. } = &steps[0].kind else {
5963 panic!("expected While, got {:?}", steps[0].kind);
5964 };
5965 assert!(matches!(body[0].kind, StepKind::Break));
5966 }
5967
5968 #[test]
5969 fn let_capture_call_and_async_call_lower() {
5970 let steps = parse_script(
5973 indoc! {r#"
5974 FUNC GREET($name: STRING) {
5975 RETURN $name
5976 }
5977 LET $r: STRING = GREET("ada")
5978 "#},
5979 lower_command,
5980 )
5981 .expect("capture call parses");
5982 let StepKind::Assign { var, expr, .. } = &steps[1].kind else {
5983 panic!("expected Assign, got {:?}", steps[1].kind);
5984 };
5985 assert_eq!(var, "r");
5986 assert!(
5987 matches!(expr, Expr::Call { name, .. } if name == "SCRIPT::GREET"),
5988 "{expr:?}"
5989 );
5990 let steps = parse_script(
5991 "FUNC GREET($name: STRING) {\n RETURN $name\n}\nLET $t: HANDLE = ASYNC GREET(\"a\")\n",
5992 lower_command,
5993 )
5994 .expect("async call parses");
5995 assert!(
5996 matches!(&steps[1].kind, StepKind::AssignAsync { .. }),
5997 "{:?}",
5998 steps[1].kind
5999 );
6000 }
6001
6002 #[test]
6003 fn multiline_call_args_span_lines() {
6004 let steps = parse_script(
6008 "FUNC SERVE($b: STRING, $u: STRING, $p: STRING, $o: MAP) {\n RETURN $b\n}\nLET $m: MAP = SERVE(\n \"127.0.0.1:2241\",\n \"test\",\n \"test123\", {\n key_path: \"test_key\"\n }\n)\n",
6009 lower_command,
6010 )
6011 .expect("multiline call parses");
6012 let StepKind::Assign { expr, .. } = &steps[1].kind else {
6013 panic!("expected Assign, got {:?}", steps[1].kind);
6014 };
6015 let Expr::Call { name, args } = expr else {
6016 panic!("expected Call expr, got {expr:?}");
6017 };
6018 assert_eq!(name, "SCRIPT::SERVE");
6019 assert_eq!(args.len(), 4);
6020 assert!(matches!(&args[3], Expr::Map(entries) if entries.len() == 1));
6021 let rendered = steps[1].to_string();
6023 assert!(!rendered.contains('\n'), "{rendered}");
6024 let script = "FUNC SERVE($b: STRING, $u: STRING, $p: STRING, $o: MAP) {\n RETURN $b\n}\nLET $m: MAP = SERVE(\n \"127.0.0.1:2241\",\n \"test\",\n \"test123\", {\n key_path: \"test_key\"\n }\n)\n";
6025 let again = parse_script(script, lower_command).expect("reparse ok");
6026 assert_eq!(again, steps);
6027 }
6028
6029 #[test]
6030 fn multiline_bare_call_and_list_span_lines() {
6031 let steps = parse_script(
6032 indoc! {r#"
6033 FUNC GREET($a: STRING) {
6034 RETURN $a
6035 }
6036 GREET(
6037 "ada"
6038 )
6039 "#},
6040 lower_command,
6041 )
6042 .expect("multiline bare call parses");
6043 let StepKind::Call { name, args } = &steps[1].kind else {
6044 panic!("expected Call, got {:?}", steps[1].kind);
6045 };
6046 assert_eq!(name, "SCRIPT::GREET");
6047 assert_eq!(args.len(), 1);
6048 let steps = parse_script(
6049 indoc! {r#"
6050 LET $l: LIST = [
6051 "a",
6052 "b"
6053 ]
6054 "#},
6055 lower_command,
6056 )
6057 .expect("multiline list parses");
6058 let StepKind::Assign { expr, .. } = &steps[0].kind else {
6059 panic!("expected Assign, got {:?}", steps[0].kind);
6060 };
6061 assert!(
6062 matches!(expr, Expr::List(items) if items.len() == 2),
6063 "{expr:?}"
6064 );
6065 }
6066
6067 #[test]
6068 fn parse_duration_units() {
6069 use std::time::Duration;
6070 assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
6071 assert_eq!(parse_duration("10s").unwrap(), Duration::from_secs(10));
6072 assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
6073 assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
6074 assert_eq!(parse_duration("30").unwrap(), Duration::from_secs(30));
6075 assert_eq!(parse_duration("30 s").unwrap(), Duration::from_secs(30));
6077 assert_eq!(parse_duration("2 m").unwrap(), Duration::from_secs(120));
6078 }
6079
6080 #[test]
6081 fn parse_duration_rejects_garbage() {
6082 assert!(parse_duration("").is_err());
6083 assert!(parse_duration("banana").is_err());
6084 assert!(parse_duration("10x").is_err());
6085 assert!(parse_duration("0s").is_err());
6086 assert!(parse_duration("0").is_err());
6087 assert!(parse_duration("-5s").is_err());
6088 assert!(parse_duration("30 s s").is_err());
6090 assert!(parse_duration("3 0s").is_err());
6091 }
6092
6093 #[test]
6094 fn parse_byte_count_units() {
6095 assert_eq!(parse_byte_count("500").unwrap(), 500);
6096 assert_eq!(parse_byte_count("500B").unwrap(), 500);
6097 assert_eq!(parse_byte_count("10KB").unwrap(), 10_000);
6098 assert_eq!(parse_byte_count("2MB").unwrap(), 2_000_000);
6099 assert_eq!(parse_byte_count("1GB").unwrap(), 1_000_000_000);
6100 assert_eq!(parse_byte_count("1TB").unwrap(), 1_000_000_000_000);
6101 assert_eq!(parse_byte_count("10KIB").unwrap(), 10 * 1_024);
6102 assert_eq!(parse_byte_count("2MIB").unwrap(), 2 * 1_024 * 1_024);
6103 assert_eq!(parse_byte_count("1GIB").unwrap(), 1_024 * 1_024 * 1_024);
6104 assert_eq!(
6105 parse_byte_count("1TIB").unwrap(),
6106 1_024 * 1_024 * 1_024 * 1_024
6107 );
6108 assert_eq!(parse_byte_count("1gb").unwrap(), 1_000_000_000);
6110 assert_eq!(parse_byte_count("1Gb").unwrap(), 1_000_000_000);
6111 assert_eq!(parse_byte_count("1gib").unwrap(), 1_024 * 1_024 * 1_024);
6112 assert_eq!(parse_byte_count("1Gib").unwrap(), 1_024 * 1_024 * 1_024);
6113 assert_eq!(parse_byte_count("1_000").unwrap(), 1_000);
6115 assert_eq!(
6116 parse_byte_count("1_000_000_000_000").unwrap(),
6117 1_000_000_000_000
6118 );
6119 assert_eq!(parse_byte_count("1_0KB").unwrap(), 10_000);
6120 assert_eq!(
6121 parse_byte_count("1_0GiB").unwrap(),
6122 10 * 1_024 * 1_024 * 1_024
6123 );
6124 assert_eq!(parse_byte_count("1 GB").unwrap(), 1_000_000_000);
6126 assert_eq!(parse_byte_count("10 KiB").unwrap(), 10_240);
6127 assert_eq!(parse_byte_count(" 2MB ").unwrap(), 2_000_000);
6128 assert_eq!(parse_byte_count("+1 GB").unwrap(), 1_000_000_000);
6130 assert!(parse_byte_count("-1 GB").is_err());
6131 }
6132
6133 #[test]
6134 fn parse_byte_count_rejects_garbage() {
6135 for bad in [
6136 "",
6137 "banana",
6138 "10x",
6139 "1G",
6140 "1K",
6141 "1.5GB",
6142 "-5",
6143 "-5GB",
6144 "0",
6145 "0GB",
6146 "_100",
6147 "100_",
6148 "1__000",
6149 "_",
6150 "1_GB",
6151 "1 G B",
6153 "1 2",
6154 "1 0",
6155 "1000000000000000000000000",
6157 "1000000000TB",
6158 ] {
6159 assert!(parse_byte_count(bad).is_err(), "{bad:?} must fail");
6160 }
6161 }
6162
6163 #[test]
6164 fn format_byte_count_round_trips() {
6165 for text in [
6166 "500", "500B", "10KB", "2MB", "1GB", "1TB", "10KIB", "2MIB", "1GIB", "1TIB", "1500B",
6167 ] {
6168 let parsed = parse_byte_count(text).unwrap();
6169 let rendered = format_byte_count(parsed);
6170 assert_eq!(
6171 parse_byte_count(&rendered).unwrap(),
6172 parsed,
6173 "round-trip failed for {text}"
6174 );
6175 }
6176 assert_eq!(format_byte_count(1_024 * 1_024 * 1_024), "1GiB");
6177 assert_eq!(format_byte_count(1_000_000_000), "1GB");
6178 }
6179
6180 #[test]
6181 fn strip_digit_separators_passes_signs_through() {
6182 assert_eq!(strip_digit_separators("-1_000"), "-1000");
6186 assert_eq!(strip_digit_separators("+1_000_000"), "+1000000");
6187 assert_eq!(strip_digit_separators("-1_000.5"), "-1000.5");
6188 assert_eq!(strip_digit_separators("1_000"), "1000");
6189 for untouched in ["+", "-", "", "1__0", "abc", "+-5", "--5"] {
6190 assert_eq!(strip_digit_separators(untouched), untouched);
6191 }
6192 assert!(parse_byte_count("-1_000").is_err());
6195 assert_eq!(parse_byte_count("+1GB").unwrap(), 1_000_000_000);
6196 }
6197
6198 #[test]
6199 fn format_byte_count_is_lossless() {
6200 for n in [
6205 1,
6206 500,
6207 999,
6208 1_000,
6209 1_024,
6210 1_500,
6211 1_000_000,
6212 1_048_576,
6213 1_000_000_000,
6214 1_073_741_824,
6215 1_000_000_000_000,
6216 1_099_511_627_776,
6217 u64::MAX,
6218 ] {
6219 assert_eq!(
6220 parse_byte_count(&format_byte_count(n)).unwrap(),
6221 n,
6222 "lossless round-trip failed for {n}"
6223 );
6224 }
6225 }
6226
6227 #[test]
6228 fn format_duration_round_trips() {
6229 for text in ["500ms", "10s", "2m", "1h", "90s", "1500ms"] {
6230 let parsed = parse_duration(text).unwrap();
6231 let rendered = format_duration(&parsed);
6232 assert_eq!(
6233 parse_duration(&rendered).unwrap(),
6234 parsed,
6235 "round-trip failed for {text}"
6236 );
6237 }
6238 assert_eq!(format_duration(&parse_duration("90s").unwrap()), "90s");
6239 assert_eq!(format_duration(&parse_duration("2m").unwrap()), "2m");
6240 }
6241
6242 #[test]
6243 fn structural_metadata_covers_all_structural_kinds() {
6244 use crate::ast::Value;
6245
6246 fn metadata_name(kind: &StepKind) -> Option<&'static str> {
6250 match kind {
6251 StepKind::WithIo { .. } | StepKind::WithIoBlock { .. } => Some("WITH_IO"),
6252 StepKind::For { .. } => Some("FOR"),
6253 StepKind::If { .. } => Some("IF"),
6254 StepKind::Assign { .. } => Some("LET"),
6255 StepKind::Set { .. } => Some("MUTATION"),
6256 StepKind::AssignCapture { .. } => Some("LET"),
6257 StepKind::AwaitCapture { .. } => Some("AWAIT"),
6258 StepKind::AsyncBlock { .. } | StepKind::AssignAsync { .. } => Some("ASYNC"),
6259 StepKind::Await { .. } => Some("AWAIT"),
6260 StepKind::Cancel { .. } => Some("CANCEL"),
6261 StepKind::Timeout { .. } => Some("TIMEOUT"),
6262 StepKind::Isolated { .. } => Some("ISOLATED"),
6263 StepKind::IsolatedInheritEnv { .. } => Some("ISOLATED"),
6264 StepKind::RemoteBlock { .. } => Some("REMOTE"),
6265 StepKind::FuncDef { .. } => Some("FUNC"),
6266 StepKind::Call { .. } => None,
6269 StepKind::ImportFile { .. } | StepKind::ImportFuncs { .. } => Some("IMPORT"),
6271 StepKind::Return { .. } => Some("RETURN"),
6272 StepKind::While { .. } => Some("WHILE"),
6273 StepKind::Break => Some("BREAK"),
6274 StepKind::Continue => Some("CONTINUE"),
6275 StepKind::TypeAlias { .. } => Some("LET"),
6279 StepKind::RunExec { .. } => None,
6280 StepKind::Workdir(_)
6281 | StepKind::Workspace(_)
6282 | StepKind::Env { .. }
6283 | StepKind::InheritEnv { .. }
6284 | StepKind::Run(_)
6285 | StepKind::Echo(_)
6286 | StepKind::Copy { .. }
6287 | StepKind::Symlink { .. }
6288 | StepKind::Mkdir(_)
6289 | StepKind::Archive { .. }
6290 | StepKind::Unarchive { .. }
6291 | StepKind::Install { .. }
6292 | StepKind::Ls(_)
6293 | StepKind::Read(_)
6294 | StepKind::ReadLine { .. }
6295 | StepKind::Prompt { .. }
6296 | StepKind::Write { .. }
6297 | StepKind::Append { .. }
6298 | StepKind::Remove { .. }
6299 | StepKind::Expand { .. }
6300 | StepKind::AssertEq { .. }
6301 | StepKind::AssertContains { .. }
6302 | StepKind::AssertNe { .. }
6303 | StepKind::CopyGit { .. }
6304 | StepKind::Exit(_)
6305 | StepKind::Sleep { .. }
6306 | StepKind::ListAppend { .. } => None,
6307 }
6308 }
6309
6310 let dummies: Vec<StepKind> = vec![
6313 StepKind::WithIo {
6314 bindings: Vec::new(),
6315 cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
6316 "x".to_string(),
6317 false,
6318 ))),
6319 },
6320 StepKind::For {
6321 key_var: None,
6322 key_type: None,
6323 var: "i".to_string(),
6324 var_type: "STRING".to_string(),
6325 in_expr: Expr::Literal(Value::bool(true)),
6326 body: Vec::new(),
6327 },
6328 StepKind::If {
6329 cond: Box::new(Expr::Literal(Value::bool(true))),
6330 then_body: Vec::new(),
6331 else_ifs: Vec::new(),
6332 else_body: None,
6333 },
6334 StepKind::Assign {
6335 var: "v".to_string(),
6336 decl_type: "BOOL".to_string(),
6337 expr: Expr::Literal(Value::bool(true)),
6338 },
6339 StepKind::Set {
6340 var: "v".to_string(),
6341 expr: Expr::Literal(Value::bool(true)),
6342 },
6343 StepKind::AssignCapture {
6344 var: "v".to_string(),
6345 decl_type: "STRING".to_string(),
6346 cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
6347 "x".to_string(),
6348 false,
6349 ))),
6350 },
6351 StepKind::AwaitCapture {
6352 out_var: "o".to_string(),
6353 out_type: "STRING".to_string(),
6354 task_var: "t".to_string(),
6355 },
6356 StepKind::AsyncBlock { body: Vec::new() },
6357 StepKind::AssignAsync {
6358 var: "t".to_string(),
6359 decl_type: "HANDLE".to_string(),
6360 body: Vec::new(),
6361 },
6362 StepKind::Await {
6363 var: "t".to_string(),
6364 },
6365 StepKind::Cancel {
6366 var: "t".to_string(),
6367 },
6368 StepKind::Timeout {
6369 duration: Arg::String("1s".to_string(), false),
6370 body: Vec::new(),
6371 },
6372 StepKind::Isolated { body: Vec::new() },
6373 StepKind::IsolatedInheritEnv { keys: Vec::new() },
6374 StepKind::RemoteBlock {
6375 target: "prod".to_string(),
6376 vars: Vec::new(),
6377 env: Vec::new(),
6378 body: Vec::new(),
6379 },
6380 StepKind::FuncDef {
6381 name: "F".to_string(),
6382 params: Vec::new(),
6383 body: Vec::new(),
6384 docs: None,
6385 },
6386 StepKind::Call {
6387 name: "F".to_string(),
6388 args: Vec::new(),
6389 },
6390 StepKind::Return {
6391 expr: Box::new(Expr::Literal(Value::bool(true))),
6392 },
6393 StepKind::While {
6394 cond: Box::new(Expr::Literal(Value::bool(true))),
6395 body: Vec::new(),
6396 },
6397 StepKind::Break,
6398 StepKind::Continue,
6399 StepKind::TypeAlias {
6400 name: "PERSON".to_string(),
6401 target: "MAP<name: STRING>".to_string(),
6402 },
6403 ];
6404 let registry = all_structural_metadata();
6405 for kind in &dummies {
6406 let Some(name) = metadata_name(kind) else {
6408 continue;
6409 };
6410 assert!(
6411 registry.iter().any(|meta| meta.name == name),
6412 "no structural metadata entry for {}",
6413 name
6414 );
6415 }
6416 }
6417}