1use std::collections::HashSet;
16use std::fmt;
17
18use crate::ast::{
19 Arg, ArgPart, ArithOp, CompareOp, Expr, GuardExpr, IoBinding, IoStream, MathOp, ModuleTable,
20 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]`; 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 };
601 let (flags, positional) = crate::strip_flags(raw_args, &meta)?;
602 crate::command::validate_positionals_against_meta(
603 s,
604 &meta.args,
605 &positional,
606 )?;
607 let lower_fn: fn(Vec<(String, Arg)>, Vec<Arg>) -> ParseResult<StepKind> = $lower;
608 lower_fn(flags, positional)
609 }
610 )*
611 _ => {
612 Err(classify(name, &raw_args))
613 }
614 }
615 }
616
617 pub fn all_metadata() -> Vec<CommandMeta> {
618 let mut out = vec![
619 $( CommandMeta {
620 name: $name, syntax: $syntax, summary: $summary,
621 description: $desc, args: $args, flags: $flags,
622 default_output: $out, examples: $examples,
623 }, )*
624 ];
625 out.extend(all_structural_metadata());
629 out
630 }
631 };
632}
633
634impl StepKind {
635 pub fn walk_exprs(&self, f: &mut impl FnMut(&Expr)) {
642 fn walk_arg(arg: &Arg, f: &mut impl FnMut(&Expr)) {
643 match arg {
644 Arg::Expr(expr) => f(expr),
645 Arg::Parts(parts) => {
646 for part in parts {
647 if let ArgPart::Expr(expr) = part {
648 f(expr);
649 }
650 }
651 }
652 Arg::String(..) => {}
653 }
654 }
655 fn walk_opt(arg: &Option<Arg>, f: &mut impl FnMut(&Expr)) {
656 if let Some(arg) = arg {
657 walk_arg(arg, f);
658 }
659 }
660 fn walk_target(target: &AssertTarget, f: &mut impl FnMut(&Expr)) {
661 if let AssertTarget::Value(arg) = target {
662 walk_arg(arg, f);
663 }
664 }
665 match self {
666 StepKind::Assign { expr, .. } | StepKind::Set { expr, .. } => f(expr),
667 StepKind::Return { expr } => f(expr),
668 StepKind::Call { args, .. } => {
669 for arg in args {
670 f(arg);
671 }
672 }
673 StepKind::For { in_expr, .. } => f(in_expr),
674 StepKind::If { cond, else_ifs, .. } => {
675 f(cond);
676 for (cond, _) in else_ifs {
677 f(cond);
678 }
679 }
680 StepKind::While { cond, .. } => f(cond),
681 StepKind::Timeout { duration, .. } | StepKind::Sleep { duration } => {
682 walk_arg(duration, f);
683 }
684 StepKind::Workdir(arg)
685 | StepKind::Echo(arg)
686 | StepKind::Run(arg)
687 | StepKind::Mkdir(arg)
688 | StepKind::Exit(arg) => walk_arg(arg, f),
689 StepKind::Env { value, .. } => walk_arg(value, f),
690 StepKind::Copy { from, to, .. }
691 | StepKind::Symlink { from, to, .. }
692 | StepKind::Archive {
693 src: from, dst: to, ..
694 }
695 | StepKind::Install { from, to } => {
696 walk_arg(from, f);
697 walk_arg(to, f);
698 }
699 StepKind::Unarchive {
700 src,
701 dst,
702 max_bytes,
703 } => {
704 walk_arg(src, f);
705 walk_arg(dst, f);
706 walk_opt(max_bytes, f);
707 }
708 StepKind::CopyGit { rev, from, to, .. } => {
709 walk_arg(rev, f);
710 walk_arg(from, f);
711 walk_arg(to, f);
712 }
713 StepKind::Ls(arg) | StepKind::Read(arg) => walk_opt(arg, f),
714 StepKind::Remove { path, .. } => walk_arg(path, f),
715 StepKind::Prompt {
716 message, default, ..
717 } => {
718 walk_arg(message, f);
719 walk_opt(default, f);
720 }
721 StepKind::Write { path, contents } | StepKind::Append { path, contents } => {
722 walk_arg(path, f);
723 walk_opt(contents, f);
724 }
725 StepKind::Expand { path, overrides } => {
726 walk_opt(path, f);
727 for (_, value) in overrides {
728 walk_arg(value, f);
729 }
730 }
731 StepKind::AssertEq {
732 actual, expected, ..
733 } => {
734 walk_target(actual, f);
735 walk_opt(expected, f);
736 }
737 StepKind::AssertContains { haystack, needle } => {
738 walk_target(haystack, f);
739 walk_arg(needle, f);
740 }
741 StepKind::ListAppend { item, .. } => walk_arg(item, f),
742 StepKind::RunExec { argv } => {
743 for arg in argv {
744 walk_arg(arg, f);
745 }
746 }
747 StepKind::WithIo { .. }
748 | StepKind::WithIoBlock { .. }
749 | StepKind::TypeAlias { .. }
750 | StepKind::Workspace(_)
751 | StepKind::InheritEnv { .. }
752 | StepKind::Isolated { .. }
753 | StepKind::IsolatedInheritEnv { .. }
754 | StepKind::ReadLine { .. }
755 | StepKind::AssignCapture { .. }
756 | StepKind::AwaitCapture { .. }
757 | StepKind::AsyncBlock { .. }
758 | StepKind::AssignAsync { .. }
759 | StepKind::Await { .. }
760 | StepKind::Cancel { .. }
761 | StepKind::RemoteBlock { .. }
762 | StepKind::FuncDef { .. }
763 | StepKind::Break
764 | StepKind::Continue => {}
765 }
766 }
767
768 pub fn walk_child_kinds(&self, f: &mut impl FnMut(&StepKind)) {
772 fn walk_body(body: &[Step], f: &mut impl FnMut(&StepKind)) {
773 for step in body {
774 f(&step.kind);
775 }
776 }
777 match self {
778 StepKind::WithIo { cmd, .. } => f(cmd),
779 StepKind::AssignCapture { cmd, .. } => f(cmd),
780 StepKind::For { body, .. }
781 | StepKind::While { body, .. }
782 | StepKind::FuncDef { body, .. }
783 | StepKind::Timeout { body, .. }
784 | StepKind::Isolated { body }
785 | StepKind::AssignAsync { body, .. }
786 | StepKind::AsyncBlock { body }
787 | StepKind::RemoteBlock { body, .. } => walk_body(body, f),
788 StepKind::If {
789 then_body,
790 else_ifs,
791 else_body,
792 ..
793 } => {
794 walk_body(then_body, f);
795 for (_, body) in else_ifs {
796 walk_body(body, f);
797 }
798 if let Some(body) = else_body {
799 walk_body(body, f);
800 }
801 }
802 StepKind::InheritEnv { .. }
803 | StepKind::IsolatedInheritEnv { .. }
804 | StepKind::TypeAlias { .. }
805 | StepKind::Workdir(_)
806 | StepKind::Workspace(_)
807 | StepKind::Env { .. }
808 | StepKind::Echo(_)
809 | StepKind::Run(_)
810 | StepKind::RunExec { .. }
811 | StepKind::Copy { .. }
812 | StepKind::CopyGit { .. }
813 | StepKind::Symlink { .. }
814 | StepKind::Archive { .. }
815 | StepKind::Unarchive { .. }
816 | StepKind::Install { .. }
817 | StepKind::Mkdir(_)
818 | StepKind::Ls(_)
819 | StepKind::Read(_)
820 | StepKind::ReadLine { .. }
821 | StepKind::Prompt { .. }
822 | StepKind::Write { .. }
823 | StepKind::Append { .. }
824 | StepKind::Remove { .. }
825 | StepKind::Expand { .. }
826 | StepKind::AssertEq { .. }
827 | StepKind::AssertContains { .. }
828 | StepKind::Exit(_)
829 | StepKind::WithIoBlock { .. }
830 | StepKind::Assign { .. }
831 | StepKind::Set { .. }
832 | StepKind::AwaitCapture { .. }
833 | StepKind::Await { .. }
834 | StepKind::Cancel { .. }
835 | StepKind::Sleep { .. }
836 | StepKind::ListAppend { .. }
837 | StepKind::Call { .. }
838 | StepKind::Return { .. }
839 | StepKind::Break
840 | StepKind::Continue => {}
841 }
842 }
843
844 pub fn walk_step_exprs(&self, f: &mut impl FnMut(&Expr)) {
849 self.walk_exprs(&mut |expr| expr.walk(f));
850 self.walk_child_kinds(&mut |kind| kind.walk_step_exprs(f));
851 }
852}
853
854#[derive(Debug, Clone, PartialEq)]
863pub enum AssertTarget {
864 Value(Arg),
865 Stdout,
866 Stderr,
867}
868
869impl AssertTarget {
870 pub fn render(&self) -> String {
871 match self {
872 AssertTarget::Value(arg) => arg.render(),
873 AssertTarget::Stdout => "stdout".to_string(),
874 AssertTarget::Stderr => "stderr".to_string(),
875 }
876 }
877}
878
879fn lower_assert_target(arg: Arg) -> ParseResult<AssertTarget> {
888 match arg {
889 Arg::Expr(_) => Ok(AssertTarget::Value(arg)),
890 Arg::String(text, quoted) if !quoted => match text.as_str() {
891 "stdout" => Ok(AssertTarget::Stdout),
892 "stderr" => Ok(AssertTarget::Stderr),
893 _ => Ok(AssertTarget::Value(lower_assert_operand(Arg::String(
894 text, false,
895 )))),
896 },
897 other => Ok(AssertTarget::Value(lower_assert_operand(other))),
898 }
899}
900
901fn lower_assert_operand(arg: Arg) -> Arg {
910 match arg {
911 Arg::String(text, false) => {
912 let clean = crate::command::strip_digit_separators(&text);
917 if let Ok(i) = clean.parse::<i64>() {
918 Arg::Expr(Expr::Literal(Value::int(i)))
919 } else if clean.contains('.') && clean.parse::<f64>().is_ok() {
920 Arg::Expr(Expr::Literal(Value::float(
921 clean.parse::<f64>().unwrap_or(f64::NAN),
922 )))
923 } else if text == "true" {
924 Arg::Expr(Expr::Literal(Value::bool(true)))
925 } else if text == "false" {
926 Arg::Expr(Expr::Literal(Value::bool(false)))
927 } else {
928 Arg::String(text, false)
929 }
930 }
931 other => other,
932 }
933}
934
935declare_commands! {
936 structural [
937 WithIo { bindings: Vec<IoBinding>, cmd: Box<StepKind> },
938 WithIoBlock { bindings: Vec<IoBinding> },
939 TypeAlias { name: String, target: String },
940 For { key_var: Option<String>, key_type: Option<String>, var: String, var_type: String, in_expr: Expr, body: Vec<Step> },
941 If { cond: Box<Expr>, then_body: Vec<Step>, else_ifs: Vec<(Box<Expr>, Vec<Step>)>, else_body: Option<Vec<Step>> },
942 Assign { var: String, decl_type: String, expr: Expr },
943 Set { var: String, expr: Expr },
944 AssignCapture { var: String, decl_type: String, cmd: Box<StepKind> },
945 AwaitCapture { out_var: String, out_type: String, task_var: String },
946 AsyncBlock { body: Vec<Step> },
947 AssignAsync { var: String, decl_type: String, body: Vec<Step> },
948 Await { var: String },
949 Cancel { var: String },
950 Timeout { duration: Arg, body: Vec<Step> },
951 Isolated { body: Vec<Step> },
952 IsolatedInheritEnv { keys: Vec<String> },
953 RemoteBlock { target: String, vars: Vec<String>, env: Vec<String>, body: Vec<Step> },
954 RunExec { argv: Vec<Arg> },
955 FuncDef { name: String, params: Vec<(String, String)>, body: Vec<Step>, docs: Option<(String, String)> },
956 Call { name: String, args: Vec<Expr> },
957 Return { expr: Box<Expr> },
958 While { cond: Box<Expr>, body: Vec<Step> },
959 Break,
960 Continue,
961 ]
962
963 Workdir => [
964 name: "WORKDIR",
965 variant: Workdir(Arg),
966 syntax: "WORKDIR <path>",
967 summary: "Change the working directory.",
968 description: indoc! {r#"
969 Sets the current working directory.
970
971 Relative paths resolve against the current directory; `/` resets to
972 the workspace root. Paths cannot escape the workspace.
973 "#},
974 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Directory to change to", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
975 flags: &[],
976 default_output: None,
977 examples: &[ Example { name: "change working directory", fence_meta: None, code: indoc! {r#"
978 # Later relative paths resolve under the new directory.
979 WORKDIR project/src
980 WRITE generated.txt generated-under-workdir
981
982 LET $body: STRING = READ generated.txt
983 ASSERT_EQ $body "generated-under-workdir"
984 "#} }, Example { name: "workdir in a scoped block", fence_meta: None, code: indoc! {r#"
985 # The block reverts to the starting directory on exit.
986 LET $outside: STRING = CWD
987 MKDIR project
988
989 [bool:true] {
990 WORKDIR project
991 WRITE inner.txt inner
992 }
993
994 LET $back: STRING = CWD
995 ASSERT_EQ $back $outside
996 LET $body: STRING = READ project/inner.txt
997 ASSERT_EQ $body "inner"
998 "#} } ],
999 lower: |_flags, args| {
1000 let path = args.into_iter().next().ok_or_else(|| ParseError::validation("WORKDIR", "WORKDIR requires a path".to_string(), &SpanContext::line_only(0)))?;
1001 Ok(StepKind::Workdir(path))
1002 },
1003 ],
1004
1005 Workspace => [
1006 name: "WORKSPACE",
1007 variant: Workspace(WorkspaceTarget),
1008 syntax: "WORKSPACE (SNAPSHOT|LOCAL|CACHE|SYSTEM) [--local]",
1009 summary: "Switch workspace roots.",
1010 description: indoc! {r#"
1011 Switches the workspace root. The selection reverts at scope
1012 exit like `WORKDIR`.
1013
1014 - `SNAPSHOT`: the materialized build snapshot (the default).
1015 One session-shared directory: every selection resolves to
1016 it, in any block.
1017 - `LOCAL`: the local workspace directory.
1018 - `CACHE`: a persistent per-project directory shared across
1019 runs, never evicted. It lives under the OS user cache
1020 (`OXDOCK_CACHE_DIR` pins an exact directory);
1021 `WORKSPACE CACHE --local` keeps it in
1022 `<project>/.cache/workspace` instead.
1023 - `SYSTEM`: full filesystem access. Scripts using it are not
1024 hermetic.
1025 "#},
1026 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 } ],
1027 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)" } ],
1028 default_output: None,
1029 examples: &[ Example { name: "switch roots", fence_meta: None, code: indoc! {r#"
1030 IMPORT [STD]
1031 WORKSPACE LOCAL
1032
1033 LET $t: STRING = PATH_TYPE(".")
1034 ASSERT_EQ $t "dir"
1035 "#} }, Example { name: "workspace cache in a scoped block", fence_meta: None, code: indoc! {r#"
1036 [bool:true] {
1037 WORKSPACE CACHE
1038 WRITE cached.txt cached-content
1039 }
1040
1041 COPY --from-workspace CACHE cached.txt restored.txt
1042 LET $body: STRING = READ restored.txt
1043 ASSERT_EQ $body "cached-content"
1044 "#} } ],
1045 lower: |flags, args| {
1046 let local = flags.iter().any(|(k, _)| k == "local");
1047 let target = args.into_iter().next().ok_or_else(|| ParseError::validation("WORKSPACE", "WORKSPACE requires a target".to_string(), &SpanContext::line_only(0)))?;
1048 match target.as_str() {
1049 "SNAPSHOT" | "LOCAL" | "SYSTEM" if local => Err(ParseError::validation("WORKSPACE", "WORKSPACE --local requires CACHE".to_string(), &SpanContext::line_only(0))),
1050 "SNAPSHOT" => Ok(StepKind::Workspace(WorkspaceTarget::Snapshot)),
1051 "LOCAL" => Ok(StepKind::Workspace(WorkspaceTarget::Local)),
1052 "CACHE" => Ok(StepKind::Workspace(WorkspaceTarget::Cache { local })),
1053 "SYSTEM" => Ok(StepKind::Workspace(WorkspaceTarget::System)),
1054 other => Err(ParseError::validation("WORKSPACE", format!("unknown workspace target: {other}"), &SpanContext::line_only(0))),
1055 }
1056 },
1057 ],
1058
1059 Env => [
1060 name: "ENV",
1061 variant: Env { key: String, value: Arg },
1062 syntax: "ENV KEY=value",
1063 summary: "Set an environment variable.",
1064 description: indoc! {r#"
1065 Inserts or updates an env var.
1066
1067 The value uses the unified string-value rules shared by every command:
1068 `"..."` or `'...'` quotes keep exact bytes (spaces, tabs), a lone `$var`
1069 evaluates that variable, `{{ ... }}` placeholders interpolate, unquoted
1070 words join with single spaces, and the first `=` splits key from value
1071 (`KEY=a=b` stores `a=b`).
1072
1073 A `$var` inside larger text stays literal — write `{{ $var }}` to
1074 interpolate there.
1075 "#},
1076 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 } ],
1077 flags: &[],
1078 default_output: None,
1079 examples: &[
1080 Example { name: "set env", fence_meta: None, code: indoc! {r#"
1081 ENV APP_MODE=production
1082 LET $mode: STRING = env:APP_MODE
1083 ASSERT_EQ $mode "production"
1084 "#} },
1085 Example { name: "quoted value with spaces", fence_meta: None, code: indoc! {r#"
1086 # Quotes keep the space: SET_FORTH stores `outer scope`.
1087 ENV SET_FORTH="outer scope"
1088 WRITE out.txt "{{ env:SET_FORTH }}"
1089
1090 LET $body: STRING = READ out.txt
1091 ASSERT_EQ $body "outer scope"
1092 "#} },
1093 Example { name: "variable value", fence_meta: None, code: indoc! {r#"
1094 # A lone $var evaluates, like ECHO $var.
1095 LET $who: STRING = "Alice"
1096 ENV GREETING=$who
1097 WRITE out.txt "{{ env:GREETING }}"
1098
1099 LET $body: STRING = READ out.txt
1100 ASSERT_EQ $body "Alice"
1101 "#} },
1102 Example { name: "all value forms agree", fence_meta: None, code: indoc! {r#"
1103 # A bare variable, a quoted literal, and a template all
1104 # store plain strings through the same value rules.
1105 LET $x: STRING = "Ada"
1106 ENV A=$x
1107 ENV B="hello world"
1108 ENV C="{{ $x }} concatenated"
1109 WRITE check.txt "{{ env:A }}|{{ env:B }}|{{ env:C }}"
1110
1111 LET $body: STRING = READ check.txt
1112 ASSERT_EQ $body "Ada|hello world|Ada concatenated"
1113 "#} },
1114 Example { name: "scoped env reverts", fence_meta: None, code: indoc! {r#"
1115 # ENV inside a braced block reverts when the block exits
1116 ENV MODE=production
1117
1118 [bool:true] {
1119 ENV MODE=staging
1120 WRITE inner.txt "{{ env:MODE }}"
1121 }
1122
1123 WRITE outer.txt "{{ env:MODE }}"
1124
1125 LET $inner_body: STRING = READ inner.txt
1126 ASSERT_EQ $inner_body "staging"
1127
1128 LET $outer_body: STRING = READ outer.txt
1129 ASSERT_EQ $outer_body "production"
1130 "#} },
1131 Example { name: "shell reads env per platform", fence_meta: None, code: indoc! {r#"
1132 # A shell command reads its own environment, with
1133 # per-platform spelling: quoted "$VAR" passes the parser
1134 # through untouched on Unix ...
1135 ENV PROXY_PORT=23791
1136
1137 [family:unix] LET $o: STRING = RUN echo serving on "$PROXY_PORT"
1138
1139 # ... while cmd expands %VAR% on Windows.
1140 [family:windows] LET $o: STRING = RUN echo serving on %PROXY_PORT%
1141
1142 ASSERT_CONTAINS $o "23791"
1143 "#} },
1144 ],
1145 lower: |_flags, args| lower_env_assignment(args),
1146 ],
1147
1148 InheritEnv => [
1149 name: "INHERIT_ENV",
1150 variant: InheritEnv { keys: Vec<String> },
1151 syntax: "INHERIT_ENV [<key>, ...]",
1152 summary: "Inherit env vars from host.",
1153 description: indoc! {r#"
1154 Declares which host environment variables to inherit into the script.
1155
1156 Must appear before any other commands. Several directives may
1157 appear so platform-specific names ride explicit guards
1158 (`[family:windows] INHERIT_ENV [USERPROFILE]`); each guarded
1159 line runs only when its guard passes.
1160
1161 Sandbox defaults need no declaration: loader bindings,
1162 terminal defaults, the host lookup path, and the user's
1163 profile locations seed automatically. See OxDock
1164 Environment Variable Contracts for the exact list, which grows with the
1165 engine.
1166
1167 Secrets and tool config stay opt-in here: a token or a
1168 `CARGO_HOME` override arrives only through this directive.
1169 "#},
1170 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 } ],
1171 flags: &[],
1172 default_output: None,
1173 examples: &[ Example { name: "inherit env", fence_meta: None, code: indoc! {r#"
1174 [family:unix] INHERIT_ENV [HOME]
1175 LET $path: STRING = env:PATH
1176 [family:unix] ASSERT_CONTAINS $path ":"
1177 [family:windows] ASSERT_CONTAINS $path ";"
1178 "#} } ],
1179 lower: |_flags, args| {
1180 let keys = args.into_iter().map(|a| a.as_str().to_string()).collect();
1181 Ok(StepKind::InheritEnv { keys })
1182 },
1183 ],
1184
1185 Echo => [
1186 name: "ECHO",
1187 variant: Echo(Arg),
1188 syntax: "ECHO <message>",
1189 summary: "Print to stdout.",
1190 description: "Outputs message to stdout.",
1191 args: &[ ArgSpec { name: "message", arg_type: ArgType::Rest(&ArgType::String), description: "Text", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1192 flags: &[],
1193 default_output: Some(Stream::Stdout),
1194 examples: &[
1195 Example { name: "echo", fence_meta: None, code: indoc! {r#"
1196 ECHO build-complete
1197 ASSERT_CONTAINS stdout "build-complete"
1198 "#} },
1199 Example { name: "variables", fence_meta: None, code: indoc! {r#"
1200 # {{ }} interpolates inside text; a lone $var evaluates on its own.
1201 LET $x: STRING = "World"
1202 ECHO "braced:{{ $x }}"
1203 ECHO $x
1204 ASSERT_EQ stdout "braced:World\nWorld\n"
1205 "#} },
1206 Example { name: "interpolation", fence_meta: None, code: indoc! {r#"
1207 # `{{ env:KEY }}` reads the script environment; a bare name
1208 # resolves a DSL variable instead. Unknown keys expand to
1209 # empty with no host fallback.
1210 ENV USER=OxDock
1211 LET $WHO: STRING = "Ada"
1212 ECHO "Hello {{ env:USER }}! Hi {{ WHO }}!{{ env:OXDOCK_DOC_NO_SUCH_KEY }}"
1213 ASSERT_CONTAINS stdout "Hello OxDock! Hi Ada!"
1214 "#} },
1215 ],
1216 lower: |_flags, args| Ok(StepKind::Echo(join_value(args, "ECHO")?)),
1217 ],
1218
1219 Run => [
1220 name: "RUN",
1221 variant: Run(Arg),
1222 syntax: "RUN <command...> | RUN [\"exe\", \"arg\", ...]",
1223 summary: "Execute shell command or direct executable.",
1224 description: indoc! {r#"
1225 Shell form (`RUN <command...>`) runs the joined command string in the
1226 batch shell (`sh -c` / `cmd /C`). Never the operator's login
1227 shell: login shells re-pollute scrubbed children from system
1228 profiles and break script portability, so step execution is
1229 pinned to POSIX `sh` (interactive `oxdock --shell` still uses
1230 `$SHELL`).
1231
1232 Exec form (`RUN ["exe", "arg", ...]`) spawns the executable directly
1233 with no shell, so there is no shell expansion, globbing, redirection,
1234 or pipes; use it for portable commands.
1235
1236 Guards and wrappers (`ASYNC`, `TIMEOUT`, `WITH_IO`, `LET`) apply to
1237 both forms.
1238 "#},
1239 args: &[ ArgSpec { name: "command", arg_type: ArgType::Rest(&ArgType::String), description: "Command", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1240 flags: &[],
1241 default_output: None,
1242 examples: &[ Example { name: "run", fence_meta: None, code: indoc! {r#"
1243 # Spawned children resolve through the seeded host PATH:
1244 # closed child env is the default, not ambient inherit.
1245 RUN echo hello
1246
1247 # Captured runs prove the output, not just the exit status.
1248 LET $o: STRING = RUN echo hello
1249 ASSERT_CONTAINS $o "hello"
1250 "#} }, Example { name: "run exec form", fence_meta: None, code: indoc! {r#"
1251 # No shell: `>` stays a literal argument, so no file is created.
1252 # Toolchain spawns bridge the host home explicitly: rustup
1253 # shims resolve toolchains through the host home.
1254 IMPORT [STD]
1255 [family:unix] INHERIT_ENV [HOME]
1256 [family:windows] INHERIT_ENV [USERPROFILE]
1257 RUN ["cargo", "--version", ">", "x.txt"]
1258 ASSERT_CONTAINS stdout "cargo"
1259
1260 LET $t: STRING = PATH_TYPE("x.txt")
1261 ASSERT_EQ $t "absent"
1262 "#} } ],
1263 lower: |_flags, args| match args.as_slice() {
1264 [Arg::Expr(Expr::List(elems))] if elems.is_empty() => {
1265 Err(ParseError::validation("RUN", "RUN requires at least one argument".to_string(), &SpanContext::line_only(0)))
1266 }
1267 [Arg::Expr(Expr::List(elems))] => Ok(StepKind::RunExec {
1268 argv: elems.iter().cloned().map(Arg::Expr).collect(),
1269 }),
1270 _ => Ok(StepKind::Run(join_value(args, "RUN")?)),
1271 },
1272 ],
1273
1274 Copy => [
1275 name: "COPY",
1276 variant: Copy { from_workspace: Option<WorkspaceTarget>, from_host: bool, to_host: bool, from: Arg, to: Arg },
1277 syntax: "COPY [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] [--from-host | --to-host] <from> <to>",
1278 summary: "Copy file into workspace.",
1279 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.",
1280 args: &[
1281 ArgSpec { name: "from", arg_type: ArgType::Path, description: "Source", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1282 ArgSpec { name: "to", arg_type: ArgType::Path, description: "Dest", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1283 ],
1284 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)" } ],
1285 default_output: None,
1286 examples: &[ Example { name: "copy", fence_meta: Some("roots:unified"), code: indoc! {r#"
1287 # Copy to a new name, then read back.
1288 WRITE src.txt content
1289 COPY src.txt dst.txt
1290
1291 LET $body: STRING = READ dst.txt
1292 ASSERT_EQ $body "content"
1293 "#} }, Example { name: "copy from workspace", fence_meta: None, code: indoc! {r#"
1294 # Same name, different contents per root: only LOCAL has ws-content.
1295 WRITE shared.txt from-snapshot
1296 WORKSPACE LOCAL
1297 WRITE shared.txt ws-content
1298
1299 WORKSPACE SNAPSHOT
1300 COPY --from-workspace LOCAL shared.txt ws-copy.txt
1301
1302 LET $body: STRING = READ ws-copy.txt
1303 ASSERT_EQ $body "ws-content"
1304 "#} } ],
1305 lower: |flags, args| {
1306 let from_workspace = flags
1307 .iter()
1308 .find(|(k, _)| k == "from_workspace")
1309 .map(|(_, v)| match v.as_str() {
1310 "SNAPSHOT" => Ok(WorkspaceTarget::Snapshot),
1311 "LOCAL" => Ok(WorkspaceTarget::Local),
1312 "CACHE" => Ok(WorkspaceTarget::Cache { local: false }),
1313 "SYSTEM" => Ok(WorkspaceTarget::System),
1314 other => Err(ParseError::validation("COPY", format!("unknown workspace source: {other}"), &SpanContext::line_only(0))),
1315 })
1316 .transpose()?;
1317 let mut it = args.into_iter();
1318 let from = it.next().ok_or_else(|| ParseError::validation("COPY", "COPY requires a source".to_string(), &SpanContext::line_only(0)))?;
1319 let to = it.next().ok_or_else(|| ParseError::validation("COPY", "COPY requires a destination".to_string(), &SpanContext::line_only(0)))?;
1320 let from_host = flags.iter().any(|(k, _)| k == "from_host");
1321 let to_host = flags.iter().any(|(k, _)| k == "to_host");
1322 if from_host && to_host {
1323 return Err(ParseError::validation("COPY", "COPY --from-host and --to-host are mutually exclusive".to_string(), &SpanContext::line_only(0)));
1324 }
1325 Ok(StepKind::Copy { from_workspace, from_host, to_host, from, to })
1326 },
1327 ],
1328
1329 CopyGit => [
1330 name: "COPY_GIT",
1331 variant: CopyGit { rev: Arg, from: Arg, to: Arg, include_dirty: bool },
1332 syntax: "COPY_GIT [--include-dirty] <rev> <src> <dst>",
1333 summary: "Copy from git revision.",
1334 description: "Checkout and copy.",
1335 args: &[
1336 ArgSpec { name: "rev", arg_type: ArgType::String, description: "Rev", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1337 ArgSpec { name: "src", arg_type: ArgType::Path, description: "Src", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
1338 ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Dst", io: IoDirection::Write, index: 2, required: true, fallback_stream: None },
1339 ],
1340 flags: &[ FlagSpec { name: "dirty", long: "--include-dirty", value_type: FlagValueType::Flag, required: false, description: "Include dirty" } ],
1341 default_output: None,
1342 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"#} } ],
1343 lower: |flags, args| {
1344 let include_dirty = flags.iter().any(|(k, _)| k == "dirty");
1345 let mut it = args.into_iter();
1346 let rev = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a revision".to_string(), &SpanContext::line_only(0)))?;
1347 let from = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a source".to_string(), &SpanContext::line_only(0)))?;
1348 let to = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a destination".to_string(), &SpanContext::line_only(0)))?;
1349 Ok(StepKind::CopyGit { rev, from, to, include_dirty })
1350 },
1351 ],
1352
1353 Symlink => [
1354 name: "SYMLINK",
1355 variant: Symlink { from_workspace: Option<WorkspaceTarget>, from: Arg, to: Arg },
1356 syntax: "SYMLINK [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>",
1357 summary: "Create symlink.",
1358 description: "Creates symlink. A directory destination (existing, or a trailing-slash spell) receives the link under the source basename.",
1359 args: &[
1360 ArgSpec { name: "from", arg_type: ArgType::Path, description: "Target", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1361 ArgSpec { name: "to", arg_type: ArgType::Path, description: "Link", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1362 ],
1363 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" } ],
1364 default_output: None,
1365 examples: &[ Example { name: "symlink", fence_meta: Some("roots:unified"), code: indoc! {r#"
1366 # A symlink reads like its target.
1367 WRITE original.txt content
1368 SYMLINK original.txt link.txt
1369
1370 LET $body: STRING = READ link.txt
1371 ASSERT_EQ $body "content"
1372 "#} }, Example { name: "symlink from workspace", fence_meta: None, code: indoc! {r#"
1373 # Same name, different contents per root: only LOCAL has ws-content.
1374 WRITE shared.txt from-snapshot
1375 WORKSPACE LOCAL
1376 WRITE shared.txt ws-content
1377
1378 WORKSPACE SNAPSHOT
1379 SYMLINK --from-workspace LOCAL shared.txt ws-link.txt
1380
1381 LET $body: STRING = READ ws-link.txt
1382 ASSERT_EQ $body "ws-content"
1383 "#} } ],
1384 lower: |flags, args| {
1385 let from_workspace = flags
1386 .iter()
1387 .find(|(k, _)| k == "from_workspace")
1388 .map(|(_, v)| match v.as_str() {
1389 "SNAPSHOT" => Ok(WorkspaceTarget::Snapshot),
1390 "LOCAL" => Ok(WorkspaceTarget::Local),
1391 "CACHE" => Ok(WorkspaceTarget::Cache { local: false }),
1392 "SYSTEM" => Ok(WorkspaceTarget::System),
1393 other => Err(ParseError::validation("SYMLINK", format!("unknown workspace source: {other}"), &SpanContext::line_only(0))),
1394 })
1395 .transpose()?;
1396 let mut it = args.into_iter();
1397 let from = it.next().ok_or_else(|| ParseError::validation("SYMLINK", "SYMLINK requires a source".to_string(), &SpanContext::line_only(0)))?;
1398 let to = it.next().ok_or_else(|| ParseError::validation("SYMLINK", "SYMLINK requires a target".to_string(), &SpanContext::line_only(0)))?;
1399 Ok(StepKind::Symlink { from_workspace, from, to })
1400 },
1401 ],
1402
1403 Mkdir => [
1404 name: "MKDIR",
1405 variant: Mkdir(Arg),
1406 syntax: "MKDIR <path>",
1407 summary: "Create directory.",
1408 description: "Creates dir with parents.",
1409 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Dir path", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1410 flags: &[],
1411 default_output: None,
1412 examples: &[ Example { name: "mkdir", fence_meta: None, code: indoc! {r#"
1413 IMPORT [STD]
1414 MKDIR deeply/nested/tree
1415
1416 LET $t: STRING = PATH_TYPE("deeply/nested/tree")
1417 ASSERT_EQ $t "dir"
1418 "#} } ],
1419 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)))?)),
1420 ],
1421
1422 Install => [
1423 name: "INSTALL",
1424 variant: Install { from: Arg, to: Arg },
1425 syntax: "INSTALL <source> <dest>",
1426 summary: "Atomically install a verified binary as executable.",
1427 description: "Stages the source as a temp file in the dest dir, sets executable mode, then renames into place.",
1428 args: &[
1429 ArgSpec { name: "from", arg_type: ArgType::Path, description: "Source file", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1430 ArgSpec { name: "to", arg_type: ArgType::Path, description: "Dest file", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1431 ],
1432 flags: &[],
1433 default_output: None,
1434 examples: &[ Example { name: "install", fence_meta: Some("roots:unified"), code: indoc! {r#"
1435 # Place a verified binary with executable mode.
1436 IMPORT [STD]
1437 WRITE src.bin payload
1438 INSTALL src.bin dst-bin/tool
1439
1440 LET $t: STRING = PATH_TYPE("dst-bin/tool")
1441 ASSERT_EQ $t "file"
1442 "#} } ],
1443 lower: |_flags, args| {
1444 let mut it = args.into_iter();
1445 let from = it.next().ok_or_else(|| ParseError::validation("INSTALL", "INSTALL requires a source".to_string(), &SpanContext::line_only(0)))?;
1446 let to = it.next().ok_or_else(|| ParseError::validation("INSTALL", "INSTALL requires a destination".to_string(), &SpanContext::line_only(0)))?;
1447 Ok(StepKind::Install { from, to })
1448 },
1449 ],
1450
1451 Archive => [
1452 name: "ARCHIVE",
1453 variant: Archive { src: Arg, dst: Arg, raw: bool },
1454 syntax: "ARCHIVE [--raw] <src> <dst>",
1455 summary: "Pack a file or directory into a tarball.",
1456 description: indoc! {r#"
1457 Packs a file or directory into a tarball, gzip-compressed by
1458 default (`--raw` writes an uncompressed tar instead).
1459
1460 A lone file packs as a single top-level entry under its
1461 basename; a directory recurses, preserving empty dirs. Source
1462 modes ride in the headers on Unix, so system `tar` restores
1463 them elsewhere. Symlink sources refuse: archives cross trust
1464 boundaries, so links never resolve into member bytes. Hashing
1465 stays with `HASH_SHA256`, which reads the finished archive
1466 like any other file.
1467 "#},
1468 args: &[
1469 ArgSpec { name: "src", arg_type: ArgType::Path, description: "File or directory to pack", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1470 ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Archive file to write", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1471 ],
1472 flags: &[ FlagSpec { name: "raw", long: "--raw", value_type: FlagValueType::Flag, required: false, description: "Write an uncompressed tar instead of gzip" } ],
1473 default_output: None,
1474 examples: &[ Example { name: "archive directory", fence_meta: None, code: indoc! {r#"
1475 # Stage a small tree to pack.
1476 WRITE bundle/app.txt bundled-payload
1477 WRITE bundle/nested/deep.txt deep-payload
1478
1479 # ARCHIVE packs it gzip-compressed by default.
1480 ARCHIVE bundle bundle.tar.gz
1481
1482 # UNARCHIVE restores the tree under the destination.
1483 UNARCHIVE bundle.tar.gz restored
1484
1485 # The payloads arrive byte-identical.
1486 LET $body: STRING = READ restored/app.txt
1487 ASSERT_EQ $body "bundled-payload"
1488
1489 LET $deep: STRING = READ restored/nested/deep.txt
1490 ASSERT_EQ $deep "deep-payload"
1491 "#} }, Example { name: "archive raw", fence_meta: None, code: indoc! {r#"
1492 # A lone file packs as a single top-level entry.
1493 WRITE tool.bin tool-payload
1494
1495 # Raw archives skip gzip and stay readable by any tar.
1496 ARCHIVE --raw tool.bin tool.tar
1497 UNARCHIVE tool.tar tool-out
1498
1499 # The entry lands under its basename.
1500 LET $body: STRING = READ tool-out/tool.bin
1501 ASSERT_EQ $body "tool-payload"
1502 "#} } ],
1503 lower: |flags, args| {
1504 let raw = flags.iter().any(|(k, _)| k == "raw");
1505 let mut it = args.into_iter();
1506 let src = it.next().ok_or_else(|| ParseError::validation("ARCHIVE", "ARCHIVE requires a source".to_string(), &SpanContext::line_only(0)))?;
1507 let dst = it.next().ok_or_else(|| ParseError::validation("ARCHIVE", "ARCHIVE requires a destination".to_string(), &SpanContext::line_only(0)))?;
1508 Ok(StepKind::Archive { src, dst, raw })
1509 },
1510 ],
1511
1512 Unarchive => [
1513 name: "UNARCHIVE",
1514 variant: Unarchive { src: Arg, dst: Arg, max_bytes: Option<Arg> },
1515 syntax: "UNARCHIVE <src> <dst> [--max-bytes <bytes>]",
1516 summary: "Unpack a tarball into a directory.",
1517 description: indoc! {r#"
1518 Unpacks a tarball under the destination directory, creating
1519 it first. Gzip and raw (`ARCHIVE --raw`) tarballs
1520 self-identify by magic bytes, so no flag is needed.
1521
1522 Member bytes meter against a 1 GiB default expansion cap
1523 across the whole archive: a decompression bomb trips it
1524 instead of filling the disk, and `--max-bytes` moves the
1525 ceiling either way (plain integer bytes). The tripped member
1526 stays truncated on disk while the step fails loudly.
1527
1528 Symlink and special members refuse naming the entry, and
1529 absolute or escaping paths fail closed before any byte
1530 lands: the member sanitizer plus the destination join check
1531 form two independent walls. Unix modes recorded in the
1532 headers restore on unpack; other platforms land default
1533 modes (confer executability with `INSTALL` there).
1534 "#},
1535 args: &[
1536 ArgSpec { name: "src", arg_type: ArgType::Path, description: "Archive file to unpack", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1537 ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Directory to unpack under", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1538 ],
1539 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)" } ],
1540 default_output: None,
1541 examples: &[ Example { name: "unarchive", fence_meta: None, code: indoc! {r#"
1542 # Pack a note, then restore it under a fresh destination.
1543 WRITE pack/note.txt packed-note
1544 ARCHIVE pack pack.tar.gz
1545 UNARCHIVE pack.tar.gz unpacked
1546
1547 LET $body: STRING = READ unpacked/note.txt
1548 ASSERT_EQ $body "packed-note"
1549 "#} }, Example { name: "unarchive with a lower cap", fence_meta: None, code: indoc! {r#"
1550 # Small payloads clear even a tight ceiling.
1551 WRITE pack/note.txt packed-note
1552 ARCHIVE pack pack.tar.gz
1553 UNARCHIVE pack.tar.gz capped --max-bytes 100KB
1554
1555 LET $body: STRING = READ capped/note.txt
1556 ASSERT_EQ $body "packed-note"
1557 "#} } ],
1558 lower: |flags, args| {
1559 let mut it = args.into_iter();
1560 let src = it.next().ok_or_else(|| ParseError::validation("UNARCHIVE", "UNARCHIVE requires an archive".to_string(), &SpanContext::line_only(0)))?;
1561 let dst = it.next().ok_or_else(|| ParseError::validation("UNARCHIVE", "UNARCHIVE requires a destination".to_string(), &SpanContext::line_only(0)))?;
1562 let max_bytes = flags
1563 .into_iter()
1564 .find_map(|(k, v)| (k == "max_bytes").then_some(v));
1565 if let Some(Arg::String(text, _)) = max_bytes.as_ref()
1569 && !text.contains("{{")
1570 && let Err(e) = crate::command::parse_byte_count(text)
1571 {
1572 return Err(ParseError::validation(
1573 "UNARCHIVE",
1574 format!("UNARCHIVE --max-bytes {e:#}"),
1575 &SpanContext::line_only(0),
1576 ));
1577 }
1578 Ok(StepKind::Unarchive { src, dst, max_bytes })
1579 },
1580 ],
1581
1582 Ls => [
1583 name: "LS",
1584 variant: Ls(Option<Arg>),
1585 syntax: "LS [<path>]",
1586 summary: "List directory.",
1587 description: "Lists entries.",
1588 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Dir", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
1589 flags: &[],
1590 default_output: Some(Stream::Stdout),
1591 examples: &[ Example { name: "ls", fence_meta: None, code: indoc! {r#"
1592 MKDIR inventory
1593 WRITE inventory/a.txt a
1594 LS inventory
1595 ASSERT_CONTAINS stdout "a.txt"
1596 "#} } ],
1597 lower: |_flags, args| Ok(StepKind::Ls(args.into_iter().next())),
1598 ],
1599
1600 Read => [
1601 name: "READ",
1602 variant: Read(Option<Arg>),
1603 syntax: "READ [<path>]",
1604 summary: "Read file to stdout.",
1605 description: "Outputs file contents.",
1606 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
1607 flags: &[],
1608 default_output: Some(Stream::Stdout),
1609 examples: &[ Example { name: "read", fence_meta: None, code: indoc! {r#"
1610 WRITE note.txt "hello"
1611 READ note.txt
1612
1613 LET $body: STRING = READ note.txt
1614 ASSERT_EQ $body "hello"
1615 "#} } ],
1616 lower: |_flags, args| Ok(StepKind::Read(args.into_iter().next())),
1617 ],
1618
1619 ReadLine => [
1620 name: "READ_LINE",
1621 variant: ReadLine { var: String },
1622 syntax: "READ_LINE $var",
1623 summary: "Read one line from stdin into a variable.",
1624 description: indoc! {r#"
1625 Reads bytes until newline without waiting for EOF, leaving the pipe open.
1626
1627 Trailing newline is stripped (shell-read parity). On premature EOF
1628 assigns accumulated bytes and returns.
1629 "#},
1630 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 } ],
1631 flags: &[],
1632 default_output: None,
1633 examples: &[ Example { name: "read line", fence_meta: None, code: indoc! {r#"
1634 # The trailing newline is stripped: the variable holds exactly `first`.
1635 LET $lines: PIPE
1636 WITH_IO [stdout=$lines] ECHO "first"
1637 WITH_IO [stdin=$lines] READ_LINE $reply
1638 ASSERT_EQ $reply "first"
1639 "#} } ],
1640 lower: |_flags, args| {
1641 let arg = args.into_iter().next().ok_or_else(|| ParseError::validation("READ_LINE", "READ_LINE requires a variable".to_string(), &SpanContext::line_only(0)))?;
1642 let var = match arg {
1643 Arg::Expr(Expr::Var(name)) => name,
1644 Arg::String(s, _) if s.starts_with('$') || s.contains("{{") => s.trim_start_matches('$').to_string(),
1647 other => return Err(ParseError::validation("READ_LINE", format!("READ_LINE requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
1648 };
1649 if var.is_empty() {
1650 return Err(ParseError::validation("READ_LINE", "READ_LINE requires a variable".to_string(), &SpanContext::line_only(0)))
1651 }
1652 Ok(StepKind::ReadLine { var })
1653 },
1654 ],
1655
1656 Prompt => [
1657 name: "PROMPT",
1658 variant: Prompt { var: String, message: Arg, default: Option<Arg> },
1659 syntax: "PROMPT $var <message> [<default>]",
1660 summary: "Prompt on the terminal into a variable.",
1661 description: indoc! {r#"
1662 Prints `{message} [{default}]: ` (or `{message}: ` with no
1663 default) to stderr and reads one line from the terminal.
1664
1665 Empty input yields the default when one is given, else an
1666 empty string. EOF aborts loudly. Non-TTY stdin never reads:
1667 a default binds with a stderr note, while no default bails.
1668 "#},
1669 args: &[
1670 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 },
1671 ArgSpec { name: "message", arg_type: ArgType::String, description: "Prompt message", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
1672 ArgSpec { name: "default", arg_type: ArgType::String, description: "Default on empty input", io: IoDirection::Read, index: 2, required: false, fallback_stream: None },
1673 ],
1674 flags: &[],
1675 default_output: None,
1676 examples: &[ Example { name: "prompt needs a terminal", fence_meta: Some("expect_error:\"non-TTY\""), code: indoc! {r#"
1677 # A redirected stdin can never answer: without a default the
1678 # prompt fails instead of hanging or reading piped stdin.
1679 LET $p: PIPE
1680 WITH_IO [stdin=$p] PROMPT $dir "Install destination?"
1681 "#} } ],
1682 lower: |_flags, args| {
1683 let mut it = args.into_iter();
1684 let var_arg = it.next().ok_or_else(|| ParseError::validation("PROMPT", "PROMPT requires a variable".to_string(), &SpanContext::line_only(0)))?;
1685 let var = match var_arg {
1686 Arg::Expr(Expr::Var(name)) => name,
1687 Arg::String(s, _) if s.starts_with('$') || s.contains("{{") => s.trim_start_matches('$').to_string(),
1688 other => return Err(ParseError::validation("PROMPT", format!("PROMPT requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
1689 };
1690 if var.is_empty() {
1691 return Err(ParseError::validation("PROMPT", "PROMPT requires a variable".to_string(), &SpanContext::line_only(0)))
1692 }
1693 let message = it.next().ok_or_else(|| ParseError::validation("PROMPT", "PROMPT requires a message".to_string(), &SpanContext::line_only(0)))?;
1694 let default = it.next();
1695 Ok(StepKind::Prompt { var, message, default })
1696 },
1697 ],
1698
1699 Write => [
1700 name: "WRITE",
1701 variant: Write { path: Arg, contents: Option<Arg> },
1702 syntax: "WRITE <path> [<contents>]",
1703 summary: "Write to file.",
1704 description: "Writes contents.",
1705 args: &[
1706 ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
1707 ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Content", io: IoDirection::Write, index: 1, required: false, fallback_stream: Some(Stream::Stdin) },
1708 ],
1709 flags: &[],
1710 default_output: None,
1711 examples: &[ Example { name: "write", fence_meta: None, code: indoc! {r#"
1712 WRITE output.txt hello-world
1713 LET $body: STRING = READ output.txt
1714 ASSERT_EQ $body "hello-world"
1715 "#} } ],
1716 lower: |_flags, args| {
1717 let mut it = args.into_iter();
1718 let path = it.next().ok_or_else(|| ParseError::validation("WRITE", "WRITE requires a path".to_string(), &SpanContext::line_only(0)))?;
1719 let remaining: Vec<Arg> = it.collect();
1720 let contents = if remaining.is_empty() { None } else { Some(join_value(remaining, "WRITE")?) };
1721 Ok(StepKind::Write { path, contents })
1722 },
1723 ],
1724
1725 Append => [
1726 name: "APPEND",
1727 variant: Append { path: Arg, contents: Option<Arg> },
1728 syntax: "APPEND <path> [<contents>]",
1729 summary: "Append to file.",
1730 description: "Appends contents.",
1731 args: &[
1732 ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
1733 ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Content", io: IoDirection::Write, index: 1, required: false, fallback_stream: Some(Stream::Stdin) },
1734 ],
1735 flags: &[],
1736 default_output: None,
1737 examples: &[ Example { name: "append", fence_meta: None, code: indoc! {r#"
1738 WRITE log.txt line1
1739 APPEND log.txt line2
1740
1741 # APPEND concatenates with no separator.
1742 LET $all: STRING = READ log.txt
1743 ASSERT_EQ $all "line1line2"
1744 "#} } ],
1745 lower: |_flags, args| {
1746 let mut it = args.into_iter();
1747 let path = it.next().ok_or_else(|| ParseError::validation("APPEND", "APPEND requires a path".to_string(), &SpanContext::line_only(0)))?;
1748 let remaining: Vec<Arg> = it.collect();
1749 let contents = if remaining.is_empty() { None } else { Some(join_value(remaining, "APPEND")?) };
1750 Ok(StepKind::Append { path, contents })
1751 },
1752 ],
1753
1754 Remove => [
1755 name: "REMOVE",
1756 variant: Remove { path: Arg, recursive: bool },
1757 syntax: "REMOVE [--recursive] <path>",
1758 summary: "Remove a file, symlink, or directory.",
1759 description: "Removes a file, symlink (the link itself), or empty dir. With --recursive removes a directory tree.",
1760 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Path to remove", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1761 flags: &[ FlagSpec { name: "recursive", long: "--recursive", value_type: FlagValueType::Flag, required: false, description: "Remove a directory tree" } ],
1762 default_output: None,
1763 examples: &[ Example { name: "remove", fence_meta: None, code: indoc! {r#"
1764 # WRITE then REMOVE leaves nothing behind.
1765 IMPORT [STD]
1766 WRITE scratch.txt content
1767
1768 # Assert original file is written
1769 LET $o: STRING = PATH_TYPE("scratch.txt")
1770 ASSERT_EQ $o "file"
1771
1772 REMOVE scratch.txt
1773
1774 # Assert file has been removed
1775 LET $t: STRING = PATH_TYPE("scratch.txt")
1776 ASSERT_EQ $t "absent"
1777 "#} } ],
1778 lower: |flags, args| {
1779 let recursive = flags.iter().any(|(k, _)| k == "recursive");
1780 let path = args.into_iter().next().ok_or_else(|| ParseError::validation("REMOVE", "REMOVE requires a path".to_string(), &SpanContext::line_only(0)))?;
1781 Ok(StepKind::Remove { path, recursive })
1782 },
1783 ],
1784
1785 Expand => [
1786 name: "EXPAND",
1787 variant: Expand { path: Option<Arg>, overrides: Vec<(String, Arg)> },
1788 syntax: "EXPAND [<path>] [<KEY=val> ...]",
1789 summary: "Expand a template file (or stdin) to stdout.",
1790 description: indoc! {r#"
1791 A template is any text file — or piped stdin when no path is given —
1792 containing `{{ ... }}` placeholders. EXPAND replaces each placeholder
1793 and prints the result to stdout.
1794
1795 Placeholders: `{{ NAME }}` reads a `KEY=val` override passed on this
1796 command; `{{ env:NAME }}` reads an override, falling back to the
1797 environment; `{{ $var }}` reads a script variable (dotted paths allowed).
1798 A missing key is an error, never a silent empty.
1799
1800 Calls: `{{ MODULE::FUNC(args) }}` invokes a pure registry function
1801 with `$var.path` references and `STRING`, `INT`, `FLOAT`, and `BOOL`
1802 literals as arguments. Arguments check against the registered
1803 signature, so wrong arity or mistyped values fail at the call;
1804 unknown names fail listing the known functions. Only pure
1805 functions resolve here: stateful, script-defined, and pipe-backed
1806 entries fail naming themselves, since placeholder evaluation
1807 carries no step context. The same calls resolve in ordinary
1808 strings, so both paths agree.
1809
1810 Substitution runs in a single pass. `EXPAND` is not recursive and does not
1811 expand nested placeholders: a value that itself contains `{{ ... }}` is
1812 inserted verbatim and never expanded again.
1813
1814 A bare `$var` argument is a template path; `KEY=val` arguments are
1815 overrides whose values follow the unified string-value rules (same as
1816 `ENV`: quotes keep exact bytes, a lone `$var` evaluates,
1817 `{{ ... }}` interpolates).
1818
1819 NOTE: `WRITE` interpolates `{{ ... }}` while writing, so escape it
1820 (`\{{ ... }}`) when writing a template file for a later `EXPAND`.
1821
1822 With no path, the template arrives on stdin through a pipe. When piping
1823 from a shell, single-quote the template (`echo '{{ $x }}'`): double
1824 quotes let the shell swallow `$x`, so oxdock receives an empty `{{ }}`
1825 placeholder and errors.
1826 "#},
1827 args: &[
1828 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 },
1829 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 },
1830 ],
1831 flags: &[],
1832 default_output: Some(Stream::Stdout),
1833 examples: &[
1834 Example { name: "expand", fence_meta: None, code: indoc! {r#"
1835 # Placeholders read overrides first, then the environment.
1836 ENV NAME="Alice"
1837 WRITE template.md "Hello {{ env:NAME }}!"
1838 EXPAND template.md
1839
1840 ASSERT_CONTAINS stdout "Hello Alice!"
1841 "#} },
1842 Example { name: "override with spaces", fence_meta: None, code: indoc! {r#"
1843 # WRITE would interpolate {{ }} right away, so escape it.
1844 # The file must literally contain {{ env:NAME }} for EXPAND.
1845 WRITE template.md "Hello \{{ env:NAME }}!"
1846 EXPAND template.md NAME="Alice Smith"
1847
1848 ASSERT_CONTAINS stdout "Hello Alice Smith!"
1849 "#} },
1850 Example { name: "variable override", fence_meta: None, code: indoc! {r#"
1851 # Same escaping: keep the placeholder literal until EXPAND.
1852 # A lone $who evaluates, like ECHO $who.
1853 LET $who: STRING = "Bob"
1854 WRITE template.md "Hi \{{ env:WHO }}!"
1855 EXPAND template.md WHO=$who
1856
1857 ASSERT_CONTAINS stdout "Hi Bob!"
1858 "#} },
1859 Example { name: "override forms agree", fence_meta: None, code: indoc! {r#"
1860 # A bare variable and a template-with-tail expand identically.
1861 LET $x: STRING = "Ada"
1862 WRITE template.md "Hi \{{ env:NAME }} and \{{ env:NAME2 }}!"
1863 EXPAND template.md NAME=$x NAME2="{{ $x }} concatenated"
1864
1865 ASSERT_CONTAINS stdout "Hi Ada and Ada concatenated!"
1866 "#} },
1867 Example { name: "expand stdin", fence_meta: None, code: indoc! {r#"
1868 # No path: the template arrives on stdin through a pipe.
1869 LET $tpl: PIPE
1870 WITH_IO [stdout=$tpl] ECHO "Hello \{{ env:NAME }}!"
1871 WITH_IO [stdin=$tpl] EXPAND NAME=Alice
1872
1873 ASSERT_CONTAINS stdout "Hello Alice!"
1874 "#} },
1875 Example { name: "override does not leak", fence_meta: None, code: indoc! {r#"
1876 # KEY=val overrides shadow env for that EXPAND only.
1877 # They never update the environment itself.
1878 ENV NAME="Alice"
1879 WRITE template.md "Hi \{{ env:NAME }}!"
1880
1881 EXPAND template.md NAME="Bob"
1882 ASSERT_CONTAINS stdout "Hi Bob!"
1883
1884 EXPAND template.md
1885 ASSERT_CONTAINS stdout "Hi Alice!"
1886 "#} },
1887 Example { name: "function call", fence_meta: None, code: indoc! {r#"
1888 # Pure registry functions run inside placeholders.
1889 # WRITE would interpolate {{ }} right away, so escape it.
1890 IMPORT [STD]
1891 WRITE template.md "Count: \{{ STD::TEXT_COUNT(\"one two two three\", \"two\") }}!"
1892
1893 EXPAND template.md
1894 ASSERT_CONTAINS stdout "Count: 2!"
1895 "#} },
1896 ],
1897 lower: |_flags, args| {
1898 let mut path = None;
1899 let mut overrides = Vec::new();
1900 for arg in args {
1901 let text = arg.as_str();
1902 if let Some((key, value)) = split_assignment(text).map_err(|e| ParseError::validation("EXPAND", e.to_string(), &SpanContext::line_only(0)))? {
1903 overrides.push((key, value));
1904 } else if path.is_none() { path = Some(arg); }
1905 else { return Err(ParseError::validation("EXPAND", "EXPAND accepts at most one path".to_string(), &SpanContext::line_only(0))) }
1906 }
1907 Ok(StepKind::Expand { path, overrides })
1908 },
1909 ],
1910
1911 AssertEq => [
1912 name: "ASSERT_EQ",
1913 variant: AssertEq { hash: Option<String>, actual: AssertTarget, expected: Option<Arg> },
1914 syntax: "ASSERT_EQ <actual> <expected> | ASSERT_EQ --hash <sha256> <actual>",
1915 summary: "Assert strict equality.",
1916 description: indoc! {r#"
1917 Compares two evaluated values with typed equality (no coercion:
1918 `INT(42)` never equals `STRING("42")`), aborting the pipeline
1919 with a step-numbered error showing expected vs actual otherwise.
1920
1921 Both sides are values: `$var`, literals, templates, and calls
1922 evaluate in memory and never touch disk. Read files explicitly
1923 first (`LET $text: STRING = READ "out.txt"`, then
1924 `ASSERT_EQ $text ...`).
1925 Bare `stdout` / `stderr` observe stream buffers; a `$var`
1926 holding a `PIPE` observes its backend bytes. `--hash` compares
1927 the SHA-256 of a string, pipe, or captured-stdout actual
1928 instead of the raw bytes (`stderr` is unsupported).
1929 "#},
1930 args: &[
1931 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 },
1932 ArgSpec { name: "expected", arg_type: ArgType::Rest(&ArgType::Any), description: "Expected (required unless --hash)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
1933 ],
1934 flags: &[ FlagSpec { name: "hash", long: "--hash", value_type: FlagValueType::String, required: false, description: "SHA-256" } ],
1935 default_output: None,
1936 examples: &[ Example { name: "assert eq", fence_meta: None, code: indoc! {r#"
1937 LET $status: INT = 200
1938 ASSERT_EQ $status 200
1939 "#} },
1940 Example { name: "assert eq file", fence_meta: None, code: indoc! {r#"
1941 WRITE payload.bin stable-content
1942 LET $body: STRING = READ payload.bin
1943 ASSERT_EQ $body "stable-content"
1944 "#} },
1945 Example { name: "assert eq hash", fence_meta: None, code: indoc! {r#"
1946 # --hash compares the SHA-256 digest instead of raw bytes.
1947 WRITE payload.bin stable-content
1948 LET $body: STRING = READ payload.bin
1949 ASSERT_EQ --hash 08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c $body
1950 "#} } ],
1951 lower: |flags, args| {
1952 let hash = flags.iter().find(|(k, _)| k == "hash").map(|(_, v)| v.as_str().to_string());
1953 let mut it = args.into_iter();
1954 let actual = lower_assert_target(it.next().ok_or_else(|| ParseError::validation("ASSERT_EQ", "ASSERT_EQ requires a value".to_string(), &SpanContext::line_only(0)))?)?;
1955 let remaining: Vec<Arg> = it
1956 .map(lower_assert_operand)
1957 .collect::<Vec<Arg>>();
1958 let expected = if remaining.is_empty() {
1961 if hash.is_some() {
1962 None
1963 } else {
1964 return Err(ParseError::validation("ASSERT_EQ", "ASSERT_EQ requires an expected value".to_string(), &SpanContext::line_only(0)))
1965 }
1966 } else {
1967 Some(join_value(remaining, "ASSERT_EQ")?)
1968 };
1969 Ok(StepKind::AssertEq { hash, actual, expected })
1970 },
1971 ],
1972
1973 AssertContains => [
1974 name: "ASSERT_CONTAINS",
1975 variant: AssertContains { haystack: AssertTarget, needle: Arg },
1976 syntax: "ASSERT_CONTAINS <haystack> <needle>",
1977 summary: "Assert containment.",
1978 description: indoc! {r#"
1979 Checks containment and aborts the pipeline with a step-numbered
1980 error otherwise: substring for strings, element match for lists,
1981 key presence for maps, substring over stream and pipe buffers.
1982
1983 Like `ASSERT_EQ`, both sides are values read without implicit
1984 I/O; read files explicitly first
1985 (`LET $text: STRING = READ "cfg.txt"`).
1986 Bare `stdout` / `stderr` observe stream buffers; a `$var`
1987 holding a `PIPE` observes its backend bytes.
1988 "#},
1989 args: &[
1990 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 },
1991 ArgSpec { name: "needle", arg_type: ArgType::Rest(&ArgType::Any), description: "Substring, element, or key", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
1992 ],
1993 flags: &[],
1994 default_output: None,
1995 examples: &[ Example { name: "assert contains", fence_meta: None, code: indoc! {r#"
1996 ECHO build-complete
1997 ASSERT_CONTAINS stdout "build-complete"
1998 "#} } ],
1999 lower: |flags, args| {
2000 let _ = flags;
2001 let mut it = args.into_iter();
2002 let haystack = lower_assert_target(it.next().ok_or_else(|| ParseError::validation("ASSERT_CONTAINS", "ASSERT_CONTAINS requires a value".to_string(), &SpanContext::line_only(0)))?)?;
2003 let remaining: Vec<Arg> = it
2004 .map(lower_assert_operand)
2005 .collect::<Vec<Arg>>();
2006 if remaining.is_empty() {
2007 return Err(ParseError::validation("ASSERT_CONTAINS", "ASSERT_CONTAINS requires a needle".to_string(), &SpanContext::line_only(0)))
2008 }
2009 let needle = join_value(remaining, "ASSERT_CONTAINS")?;
2010 Ok(StepKind::AssertContains { haystack, needle })
2011 },
2012 ],
2013
2014 Exit => [
2015 name: "EXIT",
2016 variant: Exit(Arg),
2017 syntax: "EXIT <code>",
2018 summary: "Exit pipeline.",
2019 description: indoc! {r#"
2020 Stops the pipeline immediately with an `EXIT requested with code <code>`
2021 error; steps after it never run, at any nesting depth.
2022
2023 Enclosing blocks still unwind their LET/ENV/WORKDIR/WORKSPACE state,
2024 anonymous background tasks are killed synchronously, and files written
2025 before the EXIT persist.
2026
2027 The code reaches the OS: the CLI exits with `<code>` clamped to
2028 0..=255, and a guest EXIT relays through `REMOTE` the same way.
2029 "#},
2030 args: &[ ArgSpec { name: "code", arg_type: ArgType::Int, description: "Code", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
2031 flags: &[],
2032 default_output: None,
2033 examples: &[ Example { name: "exit", fence_meta: Some("expect_error:\"EXIT requested with code 0\""), code: indoc! {r#"EXIT 0"#} } ],
2034 lower: |_flags, args| {
2035 let code = args.into_iter().next().ok_or_else(|| ParseError::validation("EXIT", "EXIT requires a code".to_string(), &SpanContext::line_only(0)))?;
2038 Ok(StepKind::Exit(code))
2039 },
2040 ],
2041
2042 Sleep => [
2043 name: "SLEEP",
2044 variant: Sleep { duration: Arg },
2045 syntax: "SLEEP <duration>",
2046 summary: "Pause execution for a duration.",
2047 description: indoc! {r#"
2048 Parks the step for the duration (e.g. 500ms, 10s, 2m).
2049
2050 Cooperative: checks for cancellation so an enclosing TIMEOUT or task
2051 teardown interrupts the sleep. Cross-platform alternative to shell sleep
2052 for testing time boundaries.
2053 "#},
2054 args: &[ ArgSpec { name: "duration", arg_type: ArgType::Duration, description: "How long to sleep", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
2055 flags: &[],
2056 default_output: None,
2057 examples: &[
2058 Example { name: "sleep", fence_meta: None, code: indoc! {r#"SLEEP 100ms"#} },
2059 Example {
2060 name: "sleep variable duration",
2061 fence_meta: None,
2062 code: indoc! {r#"
2063 # Durations resolve at runtime, so variables work too:
2064 # quoted or bare, both bind the same string.
2065 LET $pause: STRING = "100ms"
2066 SLEEP $pause
2067
2068 LET $bare: STRING = 100ms
2069 SLEEP $bare
2070 "#},
2071 },
2072 ],
2073 lower: |_flags, args| {
2074 let mut it = args.into_iter();
2075 let raw = it
2076 .next()
2077 .ok_or_else(|| ParseError::validation("SLEEP", "SLEEP requires a duration (e.g. SLEEP 500ms)".to_string(), &SpanContext::line_only(0)))?;
2078 if it.next().is_some() {
2079 return Err(ParseError::validation("SLEEP", "SLEEP takes exactly one duration argument".to_string(), &SpanContext::line_only(0)))
2080 }
2081 Ok(StepKind::Sleep { duration: raw })
2084 },
2085 ],
2086
2087 ListAppend => [
2088 name: "LIST_APPEND",
2089 variant: ListAppend { list: String, item: Arg },
2090 syntax: "LIST_APPEND $list <item>",
2091 summary: "Append an item to a LIST variable in place.",
2092 description: indoc! {r#"
2093 Appends the item to the LIST variable in place.
2094
2095 When the binding holds the only reference the push runs in
2096 amortized constant time. Aliased buffers detach first, so
2097 other holders keep their contents.
2098 "#},
2099 args: &[
2100 ArgSpec { name: "list", arg_type: ArgType::List, description: "Target LIST variable (`$name`)", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
2101 ArgSpec { name: "item", arg_type: ArgType::Any, description: "Item to append (any value)", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
2102 ],
2103 flags: &[],
2104 default_output: None,
2105 examples: &[ Example { name: "list append", fence_meta: None, code: indoc! {r#"
2106 # Appends accumulate in order.
2107 LET $items: LIST<STRING> = []
2108 LIST_APPEND $items "first"
2109 LIST_APPEND $items "second"
2110
2111 LET $want: LIST<STRING> = ["first", "second"]
2112 ASSERT_EQ $items $want
2113 "#} } ],
2114 lower: |_flags, args| {
2115 let mut it = args.into_iter();
2116 let raw_list = it
2117 .next()
2118 .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)))?;
2119 let list = match raw_list {
2120 Arg::Expr(Expr::Var(name)) => name,
2121 Arg::String(s, _) => s.trim_start_matches('$').to_string(),
2122 other => return Err(ParseError::validation("LIST_APPEND", format!("LIST_APPEND requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
2123 };
2124 if list.is_empty() {
2125 return Err(ParseError::validation("LIST_APPEND", "LIST_APPEND requires a LIST variable (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))
2126 }
2127 let item = it
2128 .next()
2129 .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)))?;
2130 if it.next().is_some() {
2131 return Err(ParseError::validation("LIST_APPEND", "LIST_APPEND takes exactly two arguments: LIST_APPEND $list <item>".to_string(), &SpanContext::line_only(0)))
2132 }
2133 Ok(StepKind::ListAppend { list, item })
2134 },
2135 ],
2136}
2137
2138pub fn all_structural_metadata() -> Vec<CommandMeta> {
2146 vec![
2147 CommandMeta {
2148 name: "WITH_IO",
2149 syntax: "WITH_IO [<stream>[=$var], ...] <command> | WITH_IO [bindings] { <commands> } | WITH_IO [tty[, stdin=$p][, rows=<int>][, cols=<int>]] RUN ...",
2150 summary: "Reroute standard streams.",
2151 description: indoc! {r#"
2152 Reroutes the standard streams of the next command or, in block form,
2153 of every enclosed command.
2154
2155 Bindings map streams (`stdin`, `stdout`, `stderr`) to a PIPE-typed
2156 variable (`stdout=$p`, `stdin=$p`), resolved from the variable
2157 when the step runs. Both stdout and stderr pipes capture output
2158 the same way. Declare the handle first with `LET $p: PIPE`.
2159
2160 A `RUN` step can opt into a pseudo-terminal with the bare `tty`
2161 flag instead of a new command: `WITH_IO [tty] RUN [...]`
2162 spawns the child under a pty sized from the host terminal
2163 when it names none (24x80 fallback off-terminal;
2164 `rows = <int>` / `cols = <int>` override each side).
2165 Unnamed sides track the host window while the step runs
2166 (signal-driven on Unix, polled where no window signal
2167 exists); explicit sides stay pinned.
2168
2169 The master carries the child's interleaved stdout and stderr
2170 as one stream, so it routes exclusively to `stdout` (step
2171 capture or a `stdout = $p` pipe): `stderr` bindings alongside
2172 `tty` are rejected, and `tty` outside a `RUN` step is
2173 rejected. Pty-backed descriptors never promote to OS
2174 kernel pipes, even inside `ASYNC` single-`RUN` bodies.
2175
2176 `stdin = $p` feeds the master; bare `[tty]`
2177 with a real terminal stdin feeds host keys the same
2178 way (raw, transparent) and stays closed headless. Host
2179 interrupt keys reach the child instead of cancelling the
2180 step, so bind a step `TIMEOUT` for a guaranteed exit.
2181
2182 Expect pty translation in assertions:
2183 newlines arrive as carriage return plus newline, and prompts
2184 echo input. On Windows, lone line feeds in fed input expand
2185 to carriage-return line feeds for console submission, so
2186 portable scripts need no per-platform line endings.
2187
2188 An input pipe that EOFs contributes a
2189 terminal-echoed end-of-transmission marker on some
2190 platforms: prefer `ASSERT_CONTAINS` over byte-exact
2191 assertions on fed sessions.
2192
2193 Pipes hold bytes in memory and spill to a temp file above 8 MiB, so a
2194 producer can finish before the consumer starts.
2195
2196 If WITH_IO wraps an ASYNC block whose body is a single RUN, guarded or
2197 not, the pipe is a zero copy OS kernel pipe instead: pair it with a
2198 consumer that runs while the producer is alive, since output past the
2199 64 KiB kernel buffer stalls until drained. That promotion never crosses
2200 a function boundary: pipes created, bound, or passed by variable inside FUNC
2201 bodies are always script pipes, even when the surrounding task would
2202 otherwise promote.
2203
2204 A second producer or consumer on a live handle is an explicit
2205 error. A handle bound as output can later feed another
2206 command's `stdin`, connecting commands without touching the
2207 terminal. Binding `stdout` and `stderr` to the same live
2208 handle fails deterministically. Merge streams in shell
2209 via `2>&1` instead.
2210
2211 Nested blocks stack defaults; inline bindings override inherited ones for
2212 their command only; closing a block restores previous wiring.
2213 "#},
2214 args: &[],
2215 flags: &[],
2216 default_output: None,
2217 examples: &[
2218 Example {
2219 name: "with_io block",
2220 fence_meta: None,
2221 code: indoc! {r#"
2222 LET $log: PIPE
2223 WITH_IO [stdout=$log] {
2224 ECHO first
2225 ECHO second
2226 }
2227 WITH_IO [stdin=$log] WRITE captured.txt
2228
2229 # The piped bytes landed in the file.
2230 LET $body: STRING = READ captured.txt
2231 ASSERT_CONTAINS $body "first"
2232 ASSERT_CONTAINS $body "second"
2233 "#},
2234 },
2235 Example {
2236 name: "variable pipe binding",
2237 fence_meta: None,
2238 code: indoc! {r#"
2239 # Declare the pipe first: `LET $p: PIPE` mints a fresh
2240 # backend without touching a stream. A plain string here
2241 # would be a TypeMismatch.
2242 LET $p: PIPE
2243 WITH_IO [stdout=$p] ECHO hello
2244 WITH_IO [stdin=$p] READ_LINE $line
2245 ASSERT_EQ $line "hello"
2246 "#},
2247 },
2248 Example {
2249 name: "pty terminal binding",
2250 fence_meta: None,
2251 code: indoc! {r#"
2252 # A RUN step under bare `tty` sees a terminal: newlines
2253 # arrive translated, so assert with CONTAINS, never EQ.
2254 LET $p: PIPE
2255 WITH_IO [tty, stdout=$p] RUN "echo hello-tty"
2256 WITH_IO [stdin=$p] READ_LINE $line
2257 ASSERT_CONTAINS $line "hello-tty"
2258 "#},
2259 },
2260 ],
2261 },
2262 CommandMeta {
2263 name: "FOR",
2264 syntax: "FOR $item: TYPE IN <expr> { <commands> } | FOR $key: STRING, $value: TYPE IN <expr> { <commands> }",
2265 summary: "Iterate over a list or map.",
2266 description: indoc! {r#"
2267 The loop variable receives each element (lists) or value (maps); with
2268 two variables, the first receives the key.
2269
2270 Loop variables are declared with explicit types and scoped per iteration;
2271 they do not leak outward. The body may be a braced block
2272 or a single-line `{ ... }` command.
2273
2274 `GLOB("...")` patterns must be quoted (`*` is not a bare word, so
2275 `GLOB(*)` is a parse error); GLOB returns a root-relative sorted list,
2276 empty when nothing matches, and rejects `..` escapes.
2277 "#},
2278 args: &[],
2279 flags: &[],
2280 default_output: None,
2281 examples: &[
2282 Example {
2283 name: "for loop",
2284 fence_meta: None,
2285 code: indoc! {r#"
2286 # Each element binds in turn; the loop body sees every one.
2287 LET $items: LIST<STRING> = ["a", "b"]
2288 FOR $item: STRING IN $items {
2289 ECHO $item
2290 }
2291 ASSERT_CONTAINS stdout "a"
2292 ASSERT_CONTAINS stdout "b"
2293
2294 # Key and value bind together for maps.
2295 LET $map: MAP<x: INT> = {"x": 1}
2296 FOR $k: STRING, $v: INT IN $map {
2297 ECHO "{{ $k }}={{ $v }}"
2298 }
2299 ASSERT_CONTAINS stdout "x=1"
2300 "#},
2301 },
2302 Example {
2303 name: "expand every match",
2304 fence_meta: None,
2305 code: indoc! {r#"
2306 # Single-line body; $x is a template path, WHO an override.
2307 IMPORT [STD]
2308 WRITE a.txt "hi \{{ env:WHO }}!"
2309 FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
2310
2311 ASSERT_CONTAINS stdout "hi World!"
2312 "#},
2313 },
2314 ],
2315 },
2316 CommandMeta {
2317 name: "IF",
2318 syntax: "IF <expr> { <commands> } [ELSE IF <expr> { <commands> } ...] [ELSE { <commands> }]",
2319 summary: "Conditional execution.",
2320 description: indoc! {r#"
2321 The condition is evaluated as a boolean expression.
2322
2323 Prefix `!` negates (`IF !false`); `&&` binds tighter than
2324 `||`, and both short-circuit, so `IF true || $missing`
2325 never evaluates the right side. Only Bool values are
2326 accepted as conditions.
2327 "#},
2328 args: &[],
2329 flags: &[],
2330 default_output: None,
2331 examples: &[
2332 Example {
2333 name: "if else",
2334 fence_meta: None,
2335 code: indoc! {r#"
2336 IMPORT [STD]
2337
2338 # True branch runs; the false branch is skipped.
2339 IF true {
2340 WRITE yes.txt taken
2341 } ELSE {
2342 WRITE yes.txt skipped
2343 }
2344
2345 # ELSE IF selects the first true branch.
2346 IF false {
2347 WRITE skipped.txt no
2348 } ELSE IF true {
2349 WRITE fallback.txt taken
2350 }
2351
2352 # !false evaluates to true, so this branch runs.
2353 IF !false {
2354 WRITE negated.txt taken
2355 }
2356
2357 LET $yes_body: STRING = READ yes.txt
2358 LET $fallback_body: STRING = READ fallback.txt
2359 LET $negated_body: STRING = READ negated.txt
2360 ASSERT_EQ $yes_body "taken"
2361 ASSERT_EQ $fallback_body "taken"
2362 ASSERT_EQ $negated_body "taken"
2363 LET $t: STRING = PATH_TYPE("skipped.txt")
2364 ASSERT_EQ $t "absent"
2365 "#},
2366 },
2367 Example {
2368 name: "logical condition composition",
2369 fence_meta: None,
2370 code: indoc! {r#"
2371 IMPORT [STD]
2372 LET $role: STRING = "admin"
2373 LET $level: INT = 3
2374
2375 # || is true when either side holds; && needs both.
2376 IF $role == "owner" || $level >= 5 {
2377 WRITE unexpected.txt no
2378 } ELSE {
2379 WRITE fallback.txt or-false
2380 }
2381
2382 LET $fb: STRING = READ fallback.txt
2383 ASSERT_EQ $fb "or-false"
2384 LET $t1: STRING = PATH_TYPE("unexpected.txt")
2385 ASSERT_EQ $t1 "absent"
2386
2387 IF $role == "admin" || $level >= 5 {
2388 WRITE chosen.txt or-true
2389 }
2390
2391 LET $ch: STRING = READ chosen.txt
2392 ASSERT_EQ $ch "or-true"
2393
2394 IF $role == "admin" && $level >= 5 {
2395 WRITE unexpected-too.txt no
2396 } ELSE {
2397 WRITE and.txt and-false
2398 }
2399
2400 LET $an: STRING = READ and.txt
2401 ASSERT_EQ $an "and-false"
2402 LET $t2: STRING = PATH_TYPE("unexpected-too.txt")
2403 ASSERT_EQ $t2 "absent"
2404 "#},
2405 },
2406 ],
2407 },
2408 CommandMeta {
2409 name: "LET",
2410 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> }",
2411 summary: "Bind script-local variables.",
2412 description: indoc! {r#"
2413 Declares a script-local variable with an explicit type (STRING, INT,
2414 FLOAT, BOOL, PIPE, LIST, MAP, HANDLE, DURATION, PATH). Duplicate LET
2415 in the same scope frame is a redeclaration error; mutate with
2416 `$var = <expr>`.
2417
2418 Variables are usable in templates (`{{ $var }}`), guards, and
2419 expressions. With `ASYNC`, spawns a background task and stores its
2420 handle (see ASYNC). The `$` sigil on the name is mandatory.
2421
2422 No hoisting: a variable exists only after its LET runs, in
2423 execution order. Reading `$var` before its LET (or after the
2424 block that declared it exits) fails with
2425 `undefined variable $var`. Scopes are a stack of frames and
2426 resolution walks innermost outward, so nothing pre-declares
2427 names. Function bodies read outer variables through the same
2428 walk, but their own LETs never leak out (see FUNC).
2429
2430 The right-hand side is always an expression — literals, lists, maps,
2431 arithmetic (`+ - * /` with `*`/`/` binding tighter, unary `-`,
2432 parentheses), comparisons (`< <= > >=` binding tighter than
2433 `== !=`), logical `&&` (tighter) and `||` with short-circuit,
2434 `!` negation, `env:KEY` reads, `INSPECT($var)` snapshots,
2435 `GLOB("*.md")`, `INT(x)` / `FLOAT(x)` conversions — never a
2436 `{{ ... }}` template; interpolation happens in string values,
2437 not here.
2438 The one exception is pipes: `LET $p: PIPE` with no `=`
2439 and no initializer mints a fresh anonymous backend,
2440 lazily materialized at first binding, so two declarations
2441 never share a channel.
2442
2443 Numbers are numeric literals: `42` binds `INT`, `3.14` binds
2444 `FLOAT`. `Int x Int` stays `INT` (checked, integer division,
2445 so `7 / 2` is `3`); any `Float` operand promotes to `FLOAT`.
2446 Division by zero, overflow, and non-finite results are errors.
2447 Both numeric sides compare numerically (`1 == 1.0` is true);
2448 otherwise `==`/`!=` compare rendered strings and ordering on
2449 non-numerics is a Type Error. Constant subtrees fold at parse
2450 time and dynamic arithmetic compiles to flat RPN with
2451 identical semantics.
2452
2453 Float equality is exact with no epsilon. Floats store decimals
2454 in binary, so a value is exact only when its reduced fraction
2455 has a power-of-2 denominator: 0.5 (1/2), 0.25 (1/4), 0.75
2456 (3/4) are exact, while 0.1 (1/10), 0.2 (1/5), 0.3 (3/10)
2457 repeat forever in binary (like 1/3 in decimal) and truncate,
2458 so `0.1 + 0.2 == 0.3` is false (the sum is
2459 `0.30000000000000004`). Rule of thumb: endings .5, .25, .75,
2460 .125, .625, .875 are exact; .1, .2, .3 and similar are
2461 approximations. Bound approximations instead of comparing
2462 them: `IF $sum > 0.299999 && $sum < 0.300001`.
2463
2464 Comparisons do not chain: `a < b < c` is a parse error, not
2465 `(a < b) < c`. Chaining would compare a `BOOL` against a
2466 number (a runtime Type Error in C-style parsing) or evaluate
2467 the middle term twice (Python-style chaining), so the grammar
2468 accepts exactly one comparison operator per level. Write the
2469 conjunction explicitly: `$a < $b && $b < $c`. The same holds
2470 for equality (`$a == $b == $c` is rejected).
2471
2472 Captured command output is a string, so convert before math:
2473 `LET $total: INT = $total + INT($size_str)` (`INT` trims ASCII
2474 whitespace; `FLOAT` accepts int strings and rejects
2475 non-finite).
2476
2477 Bare words need no quotes: `LET $d: STRING = 30s` binds the same string
2478 as quoted.
2479
2480 When the right-hand side is a synchronous command
2481 (`LET $out: STRING = ECHO hi`), the command runs to completion and its
2482 exact stdout bytes are captured into the variable as a string (no newline
2483 stripping; commands with no stdout capture as `""`; non-UTF8 stdout is
2484 an error). Combining capture with an explicit
2485 `WITH_IO [stdout=$var]` is a parse error.
2486
2487 Coming from Bash, the capture line looks familiar but behaves
2488 strictly:
2489
2490 | | Bash `output=$(...)` | OxDock `LET $out: STRING = ...` |
2491 | --- | --- | --- |
2492 | Trailing newlines | Stripped (all of them) | Preserved byte-exact |
2493 | Variable type | Always an untyped string | Declared: STRING, INT, FLOAT, ... |
2494 | Math on output | Implicit: `$((var + 1))` | Explicit: `INT($out) + 1` |
2495 | Failing command | Continues with empty output unless `set -e` | Step fails immediately, binds nothing |
2496
2497 `LET $out: TYPE = AWAIT $var` binds the background task's
2498 explicit `RETURN` value instead (tasks stream their stdout
2499 live, so there is no output left to capture); a task that
2500 succeeded without `RETURN` yields `INT` 0, like a process
2501 exit status.
2502
2503 An inline block (`LET $var: TYPE = { <commands> }`) runs its
2504 steps in a fresh scope and binds the nearest `RETURN` value,
2505 like a zero-arg function body: fallthrough without `RETURN`
2506 binds `""`, and `BREAK`/`CONTINUE` escaping the block are
2507 errors. Think IIFE: the block executes immediately where it
2508 stands and its value is the result. The block reads outer
2509 variables but its own LETs never leak out. A `{k: v}` shape
2510 still parses as a map literal; anything else in braces is
2511 a block.
2512
2513 The split is deliberate: synchronous commands capture
2514 stdout because they run inline to completion on the same
2515 thread; background tasks never capture stdout because
2516 concurrent output has no well-defined value. Task results
2517 travel only through `RETURN` (or `INT` 0 for void tasks).
2518
2519 `LET $e: STRING = env:FOO` reads the script environment into a plain
2520 string.
2521 "#},
2522 args: &[],
2523 flags: &[],
2524 default_output: None,
2525 examples: &[
2526 Example {
2527 name: "let",
2528 fence_meta: None,
2529 code: indoc! {r#"
2530 LET $name: STRING = "world"
2531 ECHO "hello, {{ $name }}"
2532 ASSERT_CONTAINS stdout "hello, world"
2533
2534 LET $items: LIST<STRING> = ["a", "b"]
2535 ASSERT_CONTAINS $items "a"
2536 ASSERT_CONTAINS $items "b"
2537
2538 LET $count: INT = 42
2539 ASSERT_EQ $count 42
2540 "#},
2541 },
2542 Example {
2543 name: "no hoisting",
2544 fence_meta: Some("expect_error:\"undefined variable\""),
2545 code: indoc! {r#"
2546 # Reading before the LET runs is an error, not an empty value.
2547 ECHO $too_early
2548 LET $too_early: STRING = "too late"
2549 "#},
2550 },
2551 Example {
2552 name: "glob binding",
2553 fence_meta: None,
2554 code: indoc! {r#"
2555 # The RHS is an expression: GLOB(...) runs and binds a list.
2556 IMPORT [STD]
2557 WRITE a.txt "x"
2558 LET $files: LIST<STRING> = GLOB("*.txt")
2559 FOR $f: STRING IN $files { ECHO $f }
2560
2561 ASSERT_CONTAINS stdout "a.txt"
2562 "#},
2563 },
2564 Example {
2565 name: "scoped variable reverts",
2566 fence_meta: None,
2567 code: indoc! {r#"
2568 # LET inside a braced block reverts when the block exits.
2569 LET $a: STRING = "outer"
2570
2571 [bool:true] {
2572 LET $a: STRING = "inner"
2573 WRITE inner.txt "{{ $a }}"
2574 }
2575
2576 WRITE outer.txt "{{ $a }}"
2577
2578 LET $in_body: STRING = READ inner.txt
2579 ASSERT_EQ $in_body "inner"
2580
2581 LET $out_body: STRING = READ outer.txt
2582 ASSERT_EQ $out_body "outer"
2583 "#},
2584 },
2585 Example {
2586 name: "capture command output",
2587 fence_meta: None,
2588 code: indoc! {r#"
2589 # Capture keeps the trailing newline.
2590 LET $out: STRING = ECHO hi
2591 ASSERT_EQ $out "hi\n"
2592 "#},
2593 },
2594 Example {
2595 name: "inline block",
2596 fence_meta: None,
2597 code: indoc! {r#"
2598 LET $who: STRING = "ada"
2599
2600 # An inline block binds its RETURN value like a function body.
2601 LET $res: STRING = {
2602 LET $loud: STRING = "{{ $who }}!"
2603 RETURN $loud
2604 }
2605 ASSERT_EQ $res "ada!"
2606
2607 # Any declared type works: the block value checks like any RHS.
2608 LET $n: INT = {
2609 RETURN 40 + 2
2610 }
2611 ASSERT_EQ $n 42
2612 "#},
2613 },
2614 Example {
2615 name: "arithmetic over captured output",
2616 fence_meta: None,
2617 code: indoc! {r#"
2618 # Captured output converts explicitly: INT() then arithmetic.
2619 IMPORT [STD]
2620 LET $size_str: STRING = ECHO 41
2621 LET $total: INT = INT($size_str) + 1
2622 ASSERT_EQ $total 42
2623
2624 # FLOAT() promotes instead of truncating.
2625 LET $ratio: FLOAT = 1 + 2.5
2626 ASSERT_EQ $ratio 3.5
2627
2628 # Int x Int stays INT: integer division truncates.
2629 LET $half: INT = 7 / 2
2630 ASSERT_EQ $half 3
2631 "#},
2632 },
2633 Example {
2634 name: "float equality is exact",
2635 fence_meta: None,
2636 code: indoc! {r#"
2637 # Binary fractions compare cleanly; decimal fractions may not:
2638 # 0.1 + 0.2 is 0.30000000000000004, so == is false.
2639 IMPORT [STD]
2640 LET $exact: BOOL = 0.5 + 0.25 == 0.75
2641 LET $decimal: BOOL = 0.1 + 0.2 == 0.3
2642 IF $exact {
2643 WRITE exact.txt yes
2644 }
2645 IF $decimal {
2646 WRITE unexpected.txt no
2647 }
2648
2649 LET $ok: STRING = READ exact.txt
2650 ASSERT_EQ $ok "yes"
2651
2652 LET $t: STRING = PATH_TYPE("unexpected.txt")
2653 ASSERT_EQ $t "absent"
2654 "#},
2655 },
2656 Example {
2657 name: "bound inexact decimals",
2658 fence_meta: None,
2659 code: indoc! {r#"
2660 # Never test inexact decimals for equality; bound them.
2661 LET $sum: FLOAT = 0.1 + 0.2
2662 IF $sum > 0.299999 && $sum < 0.300001 {
2663 WRITE bounded.txt yes
2664 }
2665
2666 LET $ok: STRING = READ bounded.txt
2667 ASSERT_EQ $ok "yes"
2668 "#},
2669 },
2670 Example {
2671 name: "inspect a variable",
2672 fence_meta: None,
2673 code: indoc! {r#"
2674 # INSPECT($var) snapshots a variable into a MAP: declared
2675 # type plus live details (pipe backend stats here), so
2676 # scripts can branch on engine state.
2677 IMPORT [STD]
2678 LET $p: PIPE
2679 WITH_IO [stdout=$p] ECHO hello
2680 LET $info: MAP<ANY> = INSPECT($p)
2681 IF $info.is_os_pipe {
2682 WRITE unexpected.txt "should be a script pipe"
2683 }
2684
2685 ASSERT_EQ $info.type "PIPE"
2686 LET $t: STRING = PATH_TYPE("unexpected.txt")
2687 ASSERT_EQ $t "absent"
2688 "#},
2689 },
2690 ],
2691 },
2692 CommandMeta {
2693 name: "MUTATION",
2694 syntax: "$var = <expr>",
2695 summary: "Mutate a declared variable.",
2696 description: indoc! {r#"
2697 Reassigns an existing variable, converting the new value to
2698 the type declared at LET time. The explicit annotation is
2699 what authorizes string-to-number conversion here (`$n = "42"`
2700 binds 42 for an INT); a non-numeric string is an error.
2701 Expressions never convert: `"100" + 1` is a Type Error, use
2702 `INT()` / `FLOAT()` to cross that boundary explicitly.
2703
2704 The leading `$` distinguishes mutation from `KEY=value` command
2705 assignments. Assigning an undeclared variable or a mismatched type is
2706 an error.
2707
2708 Mutation writes through to the scope where the variable was
2709 declared, so it survives block exit: `LET $x` outside a block
2710 followed by `$x = ...` inside still reads back the new value
2711 afterwards, for every type. This is the counterpart to LET
2712 shadowing, where `LET $x` *inside* the block declares a
2713 separate inner variable that reverts on exit.
2714
2715 Reassignment rebinds the variable to a new value: values
2716 captured earlier keep the old word (see the rebinding
2717 example below).
2718 "#},
2719 args: &[],
2720 flags: &[],
2721 default_output: None,
2722 examples: &[
2723 Example {
2724 name: "mutate",
2725 fence_meta: None,
2726 code: indoc! {r#"
2727 # Mutation writes through: the binding holds the new value.
2728 LET $count: INT = 1
2729 $count = 2
2730 ASSERT_EQ $count 2
2731 "#},
2732 },
2733 Example {
2734 name: "rebind keeps earlier captures",
2735 fence_meta: None,
2736 code: indoc! {r#"
2737 # Reassignment rebinds: a map built from `$s` still
2738 # reads the original string after `$s` moves on.
2739 LET $s: STRING = "test"
2740 LET $m: MAP<ANY> = {a: $s}
2741 $s = "changed"
2742 ASSERT_EQ $m.a "test"
2743
2744 # Appending to one list binding never touches its clones.
2745 LET $a: LIST<STRING> = ["1"]
2746 LET $b: LIST<STRING> = $a
2747 LIST_APPEND $a "2"
2748 LET $want: LIST<STRING> = ["1"]
2749 ASSERT_EQ $b $want
2750 "#},
2751 },
2752 Example {
2753 name: "convert before math",
2754 fence_meta: None,
2755 code: indoc! {r#"
2756 # Captured output is a string: `"100" + 1` is a Type Error.
2757 # Convert explicitly, then mutate with arithmetic.
2758 IMPORT [STD]
2759 LET $raw: STRING = ECHO 100
2760 LET $n: INT = INT($raw)
2761 $n = $n + 1
2762
2763 # The declared slot stays strict: strings parse only
2764 # through the explicit converter, never on assignment.
2765 $n = INT("42")
2766 ASSERT_EQ $n 42
2767
2768 # Same crossing for decimals via FLOAT().
2769 LET $frac_str: STRING = ECHO 2.5
2770 LET $f: FLOAT = FLOAT($frac_str) + 0.25
2771 ASSERT_EQ $f 2.75
2772 "#},
2773 },
2774 ],
2775 },
2776 CommandMeta {
2777 name: "ASYNC",
2778 syntax: "ASYNC <command...> | ASYNC { <commands> } | LET $var: HANDLE = ASYNC { <commands> }",
2779 summary: "Run steps in a background thread.",
2780 description: indoc! {r#"
2781 Runs a command or block of commands in a background thread with
2782 subshell isolation.
2783
2784 Mutations (ENV, WORKDIR) stay within the block. With `LET`, stores a
2785 task handle for `AWAIT`. Task output streams live to the parent
2786 stdout; a task publishes a value with an explicit `RETURN`,
2787 which `LET $out: TYPE = AWAIT $task` binds.
2788
2789 `WITH_IO` must wrap `ASYNC` from the outside (`LET $p: PIPE` first,
2790 then `WITH_IO [stdout=$p] ASYNC ...`) so pipe endpoints allocate on
2791 the main thread before the worker spawns. Placing `WITH_IO` directly
2792 inside `ASYNC` is rejected at parse time.
2793 "#},
2794 args: &[],
2795 flags: &[],
2796 default_output: None,
2797 examples: &[
2798 Example {
2799 name: "async",
2800 fence_meta: None,
2801 code: indoc! {r#"
2802 # Inline and block forms both run in the background; AWAIT joins them.
2803 ASYNC ECHO "warming-up"
2804 LET $a: HANDLE = ASYNC ECHO "first"
2805 LET $b: HANDLE = ASYNC {
2806 ECHO "second"
2807 }
2808 AWAIT $a
2809 AWAIT $b
2810 ASSERT_CONTAINS stdout "first"
2811 ASSERT_CONTAINS stdout "second"
2812 "#},
2813 },
2814 Example {
2815 name: "async task handle",
2816 fence_meta: None,
2817 code: indoc! {r#"
2818 LET $task: HANDLE = ASYNC {
2819 ECHO "built"
2820 }
2821 AWAIT $task
2822 ASSERT_CONTAINS stdout "built"
2823 "#},
2824 },
2825 ],
2826 },
2827 CommandMeta {
2828 name: "AWAIT",
2829 syntax: "AWAIT $var | LET $out: STRING = AWAIT $var",
2830 summary: "Join a background task.",
2831 description: indoc! {r#"
2832 Blocks until the named task completes. Propagates errors if the task failed.
2833
2834 Task output streams live during the run; joining binds nothing by
2835 itself. `LET $out: TYPE = AWAIT $var` binds the task's explicit
2836 `RETURN` value instead, or `INT` 0 when the task succeeded
2837 without one (add `RETURN <expr>` to the task body to yield
2838 a value).
2839 "#},
2840 args: &[],
2841 flags: &[],
2842 default_output: None,
2843 examples: &[
2844 Example {
2845 name: "await",
2846 fence_meta: None,
2847 code: indoc! {r#"
2848 LET $task: HANDLE = ASYNC ECHO "done"
2849 AWAIT $task
2850 ASSERT_CONTAINS stdout "done"
2851 "#},
2852 },
2853 Example {
2854 name: "await capture",
2855 fence_meta: None,
2856 code: indoc! {r#"
2857 LET $task: HANDLE = ASYNC {
2858 ECHO "logged"
2859 RETURN "returned"
2860 }
2861
2862 # AWAIT binds the RETURN value, not the streamed output.
2863 LET $out: STRING = AWAIT $task
2864 ASSERT_EQ $out "returned"
2865 "#},
2866 },
2867 ],
2868 },
2869 CommandMeta {
2870 name: "CANCEL",
2871 syntax: "CANCEL $var",
2872 summary: "Synchronously cancel a background task.",
2873 description: indoc! {r#"
2874 Kills the named background task spawned via LET $var: HANDLE = ASYNC ....
2875
2876 Blocking: returns only after the task thread has been joined and its OS
2877 process reaped, so no residual filesystem or stream mutation follows. A
2878 later AWAIT $var reports cancellation. Only named tasks can be cancelled.
2879 "#},
2880 args: &[],
2881 flags: &[],
2882 default_output: None,
2883 examples: &[
2884 Example {
2885 name: "cancel",
2886 fence_meta: None,
2887 code: indoc! {r#"
2888 LET $task: HANDLE = ASYNC SLEEP 30s
2889 CANCEL $task
2890 "#},
2891 },
2892 Example {
2893 name: "await after cancel reports cancellation",
2894 fence_meta: Some("expect_error:\"was cancelled\""),
2895 code: indoc! {r#"
2896 # A cancelled task stays cancelled: joining it reports.
2897 LET $task: HANDLE = ASYNC SLEEP 30s
2898 CANCEL $task
2899 AWAIT $task
2900 "#},
2901 },
2902 ],
2903 },
2904 CommandMeta {
2905 name: "TIMEOUT",
2906 syntax: "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> } | TIMEOUT <duration> AWAIT $var",
2907 summary: "Enforce an execution deadline.",
2908 description: indoc! {r#"
2909 Aborts the wrapped step or block with a deadline error if it exceeds the
2910 duration (e.g. 500ms, 10s, 2m; a bare number means seconds).
2911
2912 A blocking foreground process is killed.
2913
2914 ASYNC composes in either nesting order with order-dependent deadline
2915 semantics: `LET $task: HANDLE = ASYNC TIMEOUT 30s RUN "build"` enforces
2916 the deadline inside the background thread (a later `AWAIT $task`
2917 surfaces the `TIMEOUT` error), while `TIMEOUT 30s AWAIT $task`
2918 preempts a hung task from the awaiting side.
2919 "#},
2920 args: &[],
2921 flags: &[],
2922 default_output: None,
2923 examples: &[
2924 Example {
2925 name: "timeout",
2926 fence_meta: None,
2927 code: indoc! {r#"
2928 TIMEOUT 30s WRITE heartbeat.txt alive
2929 LET $beat: STRING = READ heartbeat.txt
2930 ASSERT_EQ $beat "alive"
2931 "#},
2932 },
2933 Example {
2934 name: "timeout block",
2935 fence_meta: None,
2936 code: indoc! {r#"
2937 TIMEOUT 30s {
2938 WRITE a.txt one
2939 WRITE b.txt two
2940 }
2941 LET $a: STRING = READ a.txt
2942 LET $b: STRING = READ b.txt
2943 ASSERT_EQ $a "one"
2944 ASSERT_EQ $b "two"
2945 "#},
2946 },
2947 Example {
2948 name: "deadline aborts the step",
2949 fence_meta: Some("expect_error:\"TIMEOUT after\""),
2950 code: indoc! {r#"
2951 # 50ms expires long before the sleep does: the step dies
2952 # with a deadline error instead of running out the clock.
2953 TIMEOUT 50ms SLEEP 30s
2954 "#},
2955 },
2956 Example {
2957 name: "timeout variable duration",
2958 fence_meta: None,
2959 code: indoc! {r#"
2960 # Durations resolve at runtime, so variables work too.
2961 LET $budget: DURATION = "30s"
2962 TIMEOUT $budget WRITE heartbeat.txt alive
2963
2964 LET $beat: STRING = READ heartbeat.txt
2965 ASSERT_EQ $beat "alive"
2966 "#},
2967 },
2968 Example {
2969 name: "timeout await",
2970 fence_meta: None,
2971 code: indoc! {r#"
2972 # AWAIT form bounds a task join instead of a step.
2973 LET $quick: HANDLE = ASYNC {
2974 ECHO hi
2975 }
2976 TIMEOUT 30s AWAIT $quick
2977 "#},
2978 },
2979 ],
2980 },
2981 CommandMeta {
2982 name: "ISOLATED",
2983 syntax: "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>",
2984 summary: "Run steps with the seeded script environment.",
2985 description: indoc! {r#"
2986 Resets the script environment for the block to the session
2987 seed: spawned children see the sandbox defaults plus names
2988 the block re-adds through its leading `INHERIT_ENV`.
2989
2990 The allowlist resolves against the outer scope, never the
2991 host. Absent names stay absent silently, matching top-level
2992 `INHERIT_ENV`.
2993
2994 Script variables, pipes, and files flow through untouched;
2995 only `env:` is reset. Files share the session workspace:
2996 blocks selecting the same `WORKSPACE` target resolve to the
2997 same directory with no per-block overlay, so one block's
2998 writes are visible to another.
2999
3000 Blocks nest (each level re-seeds from the same seed, so
3001 nesting only narrows through the allowlists) and compose
3002 with `ASYNC` and `FUNC`. Scope exit restores the prior
3003 environment.
3004 "#},
3005 args: &[],
3006 flags: &[],
3007 default_output: None,
3008 examples: &[
3009 Example {
3010 name: "isolated scope",
3011 fence_meta: None,
3012 code: indoc! {r#"
3013 # The block sees a clean env; plain steps still run and
3014 # outer bindings survive untouched.
3015 ENV MODE=outer
3016 ISOLATED {
3017 ENV MODE=inner
3018 WRITE inner.txt "{{ env:MODE }}"
3019 }
3020 LET $back: STRING = "{{ env:MODE }}"
3021 ASSERT_EQ $back "outer"
3022 LET $body: STRING = READ inner.txt
3023 ASSERT_EQ $body "inner"
3024 "#},
3025 },
3026 Example {
3027 name: "reseeded child env",
3028 fence_meta: None,
3029 code: indoc! {r#"
3030 # The block resets to the session seed: plain steps and
3031 # spawns run with zero prelude, while outer customs
3032 # stay out.
3033 ENV OUTER_CUSTOM=outer-val
3034 WRITE top-path.txt "{{ env:PATH }}"
3035 ISOLATED {
3036 WRITE inner-path.txt "{{ env:PATH }}"
3037 WRITE inner-custom.txt "{{ env:OUTER_CUSTOM }}"
3038 RUN "echo seed-ok"
3039 }
3040 LET $top: STRING = READ top-path.txt
3041 LET $inner: STRING = READ inner-path.txt
3042 ASSERT_EQ $inner $top
3043 LET $custom: STRING = READ inner-custom.txt
3044 ASSERT_EQ $custom ""
3045 ASSERT_CONTAINS stdout "seed-ok"
3046 "#},
3047 },
3048 Example {
3049 name: "absent names stay absent",
3050 fence_meta: None,
3051 code: indoc! {r#"
3052 # Listing a name the outer scope lacks is not an error:
3053 # the block simply runs without it.
3054 ISOLATED {
3055 INHERIT_ENV [OXDOC_DEFINITELY_ABSENT_12345]
3056 ECHO still-runs
3057 }
3058 ASSERT_CONTAINS stdout "still-runs"
3059 "#},
3060 },
3061 Example {
3062 name: "nesting narrows",
3063 fence_meta: None,
3064 code: indoc! {r#"
3065 # Each level snapshots the already-scrubbed parent, so
3066 # an inner block cannot recover what the outer dropped.
3067 ENV KEEP=yes
3068 ISOLATED {
3069 INHERIT_ENV [KEEP]
3070 ISOLATED {
3071 ENV KEEP=inner
3072 WRITE deep.txt "{{ env:KEEP }}"
3073 }
3074 LET $mid: STRING = "{{ env:KEEP }}"
3075 ASSERT_EQ $mid "yes"
3076 }
3077 LET $deep: STRING = READ deep.txt
3078 ASSERT_EQ $deep "inner"
3079 "#},
3080 },
3081 ],
3082 },
3083 CommandMeta {
3084 name: "REMOTE",
3085 syntax: "REMOTE <target> [[$var, ...] [env:NAME, ...]] { <commands> }",
3086 summary: "Run a sealed block on a remote target.",
3087 description: indoc! {r#"
3088 Runs the braced block on the named remote target, which the
3089 host binds at startup (`--remote`). The block is sealed:
3090 only header-listed `$var` and `env:NAME` entries cross, the
3091 guest starts empty, and results return through declared
3092 transfers or `WITH_IO` pipes.
3093
3094 The target is a static literal, never a variable. Unknown
3095 targets fail before execution starts.
3096
3097 Bodies check twice: the host static pass validates the
3098 body before anything ships, and the guest re-validates on
3099 arrival through the same entry point, so a body type error
3100 fails locally, never mid-run on the remote.
3101
3102 A failing guest fails the host step: EXIT in the body
3103 exits the guest, and the host relays the code to its own
3104 process exit status (see EXIT).
3105 "#},
3106 args: &[],
3107 flags: &[],
3108 default_output: None,
3109 examples: &[
3110 Example {
3111 name: "sealed header values cross, outer scope does not",
3112 fence_meta: Some("mock_remote:prod"),
3113 code: indoc! {r#"
3114 # Only header-listed names arrive: `$version` is visible
3115 # on the guest, `$secret` was never sent.
3116 LET $version: STRING = "1.2.3"
3117 LET $secret: STRING = "host-only"
3118 REMOTE prod [$version] {
3119 WRITE version.txt "{{ $version }}"
3120 COPY --to-host ./version.txt back.txt
3121 }
3122
3123 # The pushed file proves the guest saw the injected value.
3124 LET $back: STRING = READ back.txt
3125 ASSERT_EQ $back "1.2.3"
3126 "#},
3127 },
3128 Example {
3129 name: "background tasks stream through shared pipes",
3130 fence_meta: Some("mock_remote:prod"),
3131 code: indoc! {r#"
3132 # Two background REMOTEs share one capture pipe while a
3133 # WITH_IO block holds the write end open.
3134 IMPORT [STD]
3135 LET $cap: PIPE
3136 WITH_IO [stdout=$cap] {
3137 LET $a: HANDLE = ASYNC REMOTE prod {
3138 ECHO "from-a"
3139 }
3140 LET $b: HANDLE = ASYNC REMOTE prod {
3141 ECHO "from-b"
3142 }
3143 AWAIT $a
3144 AWAIT $b
3145 }
3146
3147 # EOF ends the drain: no sentinel line, no baked-in count.
3148 LET $n: INT = 0
3149 WHILE !EOF($cap) {
3150 WITH_IO [stdin=$cap] READ_LINE $line
3151 $n = $n + 1
3152 }
3153 ASSERT_EQ $n 2
3154 "#},
3155 },
3156 Example {
3157 name: "declared files cross both directions",
3158 fence_meta: Some("mock_remote:prod roots:unified"),
3159 code: indoc! {r#"
3160 # Fetches ride in, pushes ride back. Anything undeclared
3161 # never leaves its side.
3162 WRITE send.txt "payload"
3163 REMOTE prod {
3164 COPY --from-host ./send.txt got.txt
3165 LET $v: STRING = READ got.txt
3166 ASSERT_EQ $v "payload"
3167 WRITE back.txt "returned"
3168 COPY --to-host ./back.txt back.txt
3169 }
3170
3171 # The push landed on the host; guest staging is gone.
3172 LET $b: STRING = READ back.txt
3173 ASSERT_EQ $b "returned"
3174 "#},
3175 },
3176 Example {
3177 name: "guest workspace selection stays on the guest",
3178 fence_meta: Some("mock_remote:prod"),
3179 code: indoc! {r#"
3180 # WORKSPACE switches inside the block resolve against the
3181 # guest staging dir, which serves as both the SNAPSHOT
3182 # root and the LOCAL build context. The host selection
3183 # restores when the block exits.
3184 REMOTE prod {
3185 WORKSPACE SNAPSHOT
3186 WRITE out.txt "from-snapshot"
3187 COPY --to-host ./out.txt snap.txt
3188 }
3189
3190 LET $s: STRING = READ snap.txt
3191 ASSERT_EQ $s "from-snapshot"
3192 "#},
3193 },
3194 Example {
3195 name: "guest cache persists across execs",
3196 fence_meta: Some("mock_remote:prod"),
3197 code: indoc! {r#"
3198 # WORKSPACE CACHE addresses guest-local persistent
3199 # storage: the second block reads what the first wrote,
3200 # while the guest staging starts empty every time.
3201 REMOTE prod {
3202 WORKSPACE CACHE
3203 WRITE marker.txt "run-marker"
3204 }
3205 REMOTE prod {
3206 WORKSPACE CACHE
3207 LET $m: STRING = READ marker.txt
3208 ASSERT_EQ $m "run-marker"
3209 }
3210 "#},
3211 },
3212 Example {
3213 name: "pushes outside staging fail closed",
3214 fence_meta: Some("mock_remote:prod expect_error:\"escapes staging\""),
3215 code: indoc! {r#"
3216 # WORKSPACE SYSTEM exposes the whole guest machine, but
3217 # transfers stay staging scoped: a push source outside
3218 # staging fails loudly instead of crossing.
3219 REMOTE prod {
3220 WORKSPACE SYSTEM
3221 COPY --to-host /no/such/file.txt got.txt
3222 }
3223 "#},
3224 },
3225 Example {
3226 name: "guest exit fails the step, host survives",
3227 fence_meta: Some(
3228 "mock_remote:prod expect_error:\"REMOTE 'prod' exited with code 3\"",
3229 ),
3230 code: indoc! {r#"
3231 # EXIT in the body exits the guest with code 3. The
3232 # host is unaffected: it keeps executing after the
3233 # guest is already dead, and the failure surfaces as
3234 # a host step error carrying the same code. The CLI
3235 # then exits with it, so the guest code reaches the OS.
3236 LET $t: HANDLE = ASYNC REMOTE prod {
3237 EXIT 3
3238 }
3239 WRITE host-alive.txt "still here"
3240 AWAIT $t
3241 "#},
3242 },
3243 Example {
3244 name: "remote block without a runner",
3245 fence_meta: Some("expect_error:\"has no registered session\""),
3246 code: indoc! {r#"
3247 # Without a bound session, the block bails instead of
3248 # executing anywhere unexpected.
3249 REMOTE prod {
3250 ECHO "do something on remote"
3251 }
3252 "#},
3253 },
3254 ],
3255 },
3256 CommandMeta {
3257 name: "FUNC",
3258 syntax: "FUNC NAME([$param: TYPE, ...]) { <commands> }",
3259 summary: "Define a user function.",
3260 description: indoc! {r#"
3261 Defines a user function with UPPERCASE name and explicitly typed
3262 parameters.
3263
3264 Params bind by position, converting each argument to its
3265 declared parameter type before the body runs.
3266 Bodies run in a fresh variable scope; LETs inside do not leak. A nested
3267 FUNC definition is scoped to its block and reverts on exit. Names share
3268 one namespace with native and host-registered functions, which a FUNC
3269 may never shadow.
3270
3271 Functions resolve like variables: a name is visible from its
3272 definition line, so recursion works but mutual recursion does
3273 not (the second name does not exist while the first body
3274 lowers). Calls name their module (`STD::GLOB(...)`) unless
3275 imported; see IMPORT.
3276
3277 Invoke any function with one syntax: `NAME(...)` as a statement
3278 (discarding the value) or `LET $var: TYPE = NAME(...)` to capture
3279 the RETURN value (fallthrough without RETURN captures as "").
3280 "#},
3281 args: &[],
3282 flags: &[],
3283 default_output: None,
3284 examples: &[
3285 Example {
3286 name: "func def call",
3287 fence_meta: None,
3288 code: indoc! {r#"
3289 FUNC GREET($name: STRING) {
3290 RETURN $name
3291 }
3292
3293 LET $res: STRING = GREET("ada")
3294 ASSERT_EQ $res "ada"
3295
3296 # Statement form: parens stay, the value drops.
3297 GREET("bex")
3298 "#},
3299 },
3300 Example {
3301 name: "call with pipes",
3302 fence_meta: None,
3303 code: indoc! {r#"
3304 # A pipe handle travels into a function as a typed argument
3305 # and is usable as a binding target in both directions.
3306 # `LET $p: PIPE` mints the handle; `$p` passes it on.
3307 FUNC DRAIN($q: PIPE) {
3308 WITH_IO [stdin=$q] READ_LINE $line
3309 RETURN $line
3310 }
3311
3312 LET $p: PIPE
3313 WITH_IO [stdout=$p] ECHO "payload"
3314
3315 LET $got: STRING = DRAIN($p)
3316 ASSERT_EQ $got "payload"
3317 "#},
3318 },
3319 ],
3320 },
3321 CommandMeta {
3322 name: "RETURN",
3323 syntax: "RETURN [<expr>]",
3324 summary: "Return a value from a function, task, or inline block.",
3325 description: indoc! {r#"
3326 Ends the nearest enclosing boundary with a value: a function
3327 call, an `ASYNC` task (bound by `LET $o = AWAIT $t`), or an
3328 inline `LET` block. Bare `RETURN` with no expression yields
3329 `""`.
3330
3331 Falling off the end without RETURN yields "". RETURN with no
3332 enclosing boundary (including at top level) is an error; use
3333 EXIT or ECHO there.
3334 "#},
3335 args: &[],
3336 flags: &[],
3337 default_output: None,
3338 examples: &[Example {
3339 name: "return",
3340 fence_meta: None,
3341 code: indoc! {r#"
3342 FUNC PICK($flag: BOOL) {
3343 IF $flag {
3344 RETURN "yes"
3345 }
3346 RETURN "no"
3347 }
3348
3349 LET $res: STRING = PICK(true)
3350 ASSERT_EQ $res "yes"
3351
3352 # Fallthrough without RETURN yields its own value.
3353 LET $no: STRING = PICK(false)
3354 ASSERT_EQ $no "no"
3355 "#},
3356 }],
3357 },
3358 CommandMeta {
3359 name: "WHILE",
3360 syntax: "WHILE <bool-expr> { <commands> }",
3361 summary: "Loop while a condition holds.",
3362 description: indoc! {r#"
3363 Re-evaluates a Bool condition each iteration (same is_truthy rule as IF;
3364 non-Bool is a type error).
3365
3366 Each iteration runs in a fresh scope; mutate outer state with $var = ...
3367 so the next check observes it. BREAK exits the loop; CONTINUE skips to
3368 the next check.
3369 "#},
3370 args: &[],
3371 flags: &[],
3372 default_output: None,
3373 examples: &[Example {
3374 name: "while loop",
3375 fence_meta: None,
3376 code: indoc! {r#"
3377 # The condition re-evaluates every iteration: three passes, then stop.
3378 LET $n: INT = 0
3379 WHILE $n < 3 {
3380 WRITE tick.txt "{{ $n }}"
3381 $n = $n + 1
3382 }
3383
3384 ASSERT_EQ $n 3
3385 LET $tick: STRING = READ tick.txt
3386 ASSERT_EQ $tick "2"
3387 "#},
3388 }],
3389 },
3390 CommandMeta {
3391 name: "BREAK",
3392 syntax: "BREAK",
3393 summary: "Exit the innermost loop.",
3394 description: indoc! {r#"
3395 Exits the innermost enclosing FOR or WHILE loop.
3396
3397 BREAK outside a loop, or across a FUNC or ASYNC boundary, is an error.
3398 "#},
3399 args: &[],
3400 flags: &[],
3401 default_output: None,
3402 examples: &[Example {
3403 name: "break",
3404 fence_meta: None,
3405 code: indoc! {r#"
3406 # BREAK leaves after the first pass: only "a" is written.
3407 FOR $x: STRING IN ["a", "b"] {
3408 WRITE picked.txt "{{ $x }}"
3409 BREAK
3410 }
3411
3412 LET $body: STRING = READ picked.txt
3413 ASSERT_EQ $body "a"
3414 "#},
3415 }],
3416 },
3417 CommandMeta {
3418 name: "CONTINUE",
3419 syntax: "CONTINUE",
3420 summary: "Skip to the next loop iteration.",
3421 description: indoc! {r#"
3422 Skips the rest of the innermost enclosing FOR or WHILE body and starts
3423 the next iteration.
3424
3425 CONTINUE outside a loop, or across a FUNC or ASYNC boundary, is an error.
3426 "#},
3427 args: &[],
3428 flags: &[],
3429 default_output: None,
3430 examples: &[Example {
3431 name: "continue",
3432 fence_meta: None,
3433 code: indoc! {r#"
3434 # CONTINUE skips the write on "a": only "b" lands.
3435 FOR $x: STRING IN ["a", "b"] {
3436 IF $x == "a" {
3437 CONTINUE
3438 }
3439 WRITE picked.txt "{{ $x }}"
3440 }
3441
3442 LET $body: STRING = READ picked.txt
3443 ASSERT_EQ $body "b"
3444 "#},
3445 }],
3446 },
3447 CommandMeta {
3448 name: KEYWORD_IMPORT,
3449 syntax: "IMPORT [<module>, ...] | IMPORT <module>",
3450 summary: "Bring module functions into bare-call scope.",
3451 description: indoc! {r#"
3452 Every function call names its module (`STD::GLOB(...)`,
3453 `MOCK::READ_CSV(...)`) unless the module is imported:
3454 `IMPORT [STD]` lets the rest of the scope call `GLOB(...)`
3455 bare. Calls resolve at parse time against `SCRIPT`
3456 definitions first, then imported modules; unknown modules,
3457 unknown functions, and unimported bare calls are parse
3458 errors, never runtime surprises.
3459
3460 IMPORT is a lowering directive, not a step: it applies from
3461 its line to the enclosing block exit, then reverts, exactly
3462 like `LET` scoping but with no runtime footprint. Guards do
3463 not apply to it. Two imported modules exporting one name is
3464 an ambiguity error: qualify the call instead.
3465
3466 `EXPORT` marks top-level script `FUNC`s as externally
3467 callable tools (`EXPORT FOO`, `EXPORT [FOO, BAR]`).
3468 Single-file scope; see the MCP host for consumption.
3469 "#},
3470 args: &[],
3471 flags: &[],
3472 default_output: None,
3473 examples: &[Example {
3474 name: "import",
3475 fence_meta: None,
3476 code: indoc! {r#"
3477 # Calls name their module (STD::GLOB); IMPORT [STD] drops the prefix.
3478 WRITE a.txt "hi \{{ env:WHO }}!"
3479 IMPORT [STD]
3480 FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
3481 ASSERT_CONTAINS stdout "hi World!"
3482 "#},
3483 }],
3484 },
3485 ]
3486}
3487
3488impl fmt::Display for StepKind {
3491 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3492 match self {
3493 StepKind::InheritEnv { keys } => write!(f, "INHERIT_ENV [{}]", keys.join(", ")),
3494 StepKind::Workdir(a) => write!(f, "WORKDIR {}", fmt_value(a, quote_arg)),
3495 StepKind::Workspace(t) => write!(f, "WORKSPACE {}", t),
3496 StepKind::Env { key, value } => {
3497 write!(f, "ENV {}={}", key, fmt_value(value, quote_arg))
3498 }
3499 StepKind::Run(c) => write!(f, "RUN {}", fmt_value(c, quote_run)),
3500 StepKind::RunExec { argv } => {
3501 let parts: Vec<String> = argv.iter().map(fmt_exec_arg).collect();
3502 write!(f, "RUN [{}]", parts.join(", "))
3503 }
3504 StepKind::Echo(m) => write!(f, "ECHO {}", fmt_value(m, quote_msg)),
3505 StepKind::Copy {
3506 from_workspace,
3507 from_host,
3508 to_host,
3509 from,
3510 to,
3511 } => {
3512 let mut head = String::from("COPY");
3513 if let Some(target) = from_workspace {
3514 head.push_str(&format!(" --from-workspace {target}"));
3515 }
3516 if *from_host {
3517 head.push_str(" --from-host");
3518 }
3519 if *to_host {
3520 head.push_str(" --to-host");
3521 }
3522 write!(
3523 f,
3524 "{head} {} {}",
3525 fmt_value(from, quote_arg),
3526 fmt_value(to, quote_arg)
3527 )
3528 }
3529 StepKind::Symlink {
3530 from_workspace,
3531 from,
3532 to,
3533 } => {
3534 if let Some(target) = from_workspace {
3535 write!(
3536 f,
3537 "SYMLINK --from-workspace {} {} {}",
3538 target,
3539 fmt_value(from, quote_arg),
3540 fmt_value(to, quote_arg)
3541 )
3542 } else {
3543 write!(
3544 f,
3545 "SYMLINK {} {}",
3546 fmt_value(from, quote_arg),
3547 fmt_value(to, quote_arg)
3548 )
3549 }
3550 }
3551 StepKind::Mkdir(a) => write!(f, "MKDIR {}", fmt_value(a, quote_arg)),
3552 StepKind::Install { from, to } => write!(
3553 f,
3554 "INSTALL {} {}",
3555 fmt_value(from, quote_arg),
3556 fmt_value(to, quote_arg)
3557 ),
3558 StepKind::Archive { src, dst, raw } => {
3559 if *raw {
3560 write!(
3561 f,
3562 "ARCHIVE --raw {} {}",
3563 fmt_value(src, quote_arg),
3564 fmt_value(dst, quote_arg)
3565 )
3566 } else {
3567 write!(
3568 f,
3569 "ARCHIVE {} {}",
3570 fmt_value(src, quote_arg),
3571 fmt_value(dst, quote_arg)
3572 )
3573 }
3574 }
3575 StepKind::Unarchive {
3576 src,
3577 dst,
3578 max_bytes,
3579 } => {
3580 write!(f, "UNARCHIVE")?;
3581 if let Some(n) = max_bytes {
3582 write!(f, " --max-bytes {}", fmt_value(n, quote_arg))?;
3583 }
3584 write!(
3585 f,
3586 " {} {}",
3587 fmt_value(src, quote_arg),
3588 fmt_value(dst, quote_arg)
3589 )
3590 }
3591 StepKind::Ls(a) => {
3592 write!(f, "LS")?;
3593 if let Some(x) = a {
3594 write!(f, " {}", fmt_value(x, quote_arg))?;
3595 }
3596 Ok(())
3597 }
3598 StepKind::Read(a) => {
3599 write!(f, "READ")?;
3600 if let Some(x) = a {
3601 write!(f, " {}", fmt_value(x, quote_arg))?;
3602 }
3603 Ok(())
3604 }
3605 StepKind::ReadLine { var } => write!(f, "READ_LINE ${}", var),
3606 StepKind::Prompt {
3607 var,
3608 message,
3609 default,
3610 } => {
3611 write!(f, "PROMPT ${} {}", var, fmt_value(message, quote_arg))?;
3612 if let Some(d) = default {
3613 write!(f, " {}", fmt_value(d, quote_arg))?;
3614 }
3615 Ok(())
3616 }
3617 StepKind::Write { path, contents } => {
3618 write!(f, "WRITE {}", fmt_value(path, quote_arg))?;
3619 if let Some(b) = contents {
3620 write!(f, " {}", fmt_value(b, quote_msg))?;
3621 }
3622 Ok(())
3623 }
3624 StepKind::Append { path, contents } => {
3625 write!(f, "APPEND {}", fmt_value(path, quote_arg))?;
3626 if let Some(b) = contents {
3627 write!(f, " {}", fmt_value(b, quote_msg))?;
3628 }
3629 Ok(())
3630 }
3631 StepKind::Remove { path, recursive } => {
3632 if *recursive {
3633 write!(f, "REMOVE --recursive {}", fmt_value(path, quote_arg))
3634 } else {
3635 write!(f, "REMOVE {}", fmt_value(path, quote_arg))
3636 }
3637 }
3638 StepKind::Expand { path, overrides } => {
3639 write!(f, "EXPAND")?;
3640 if let Some(p) = path {
3641 write!(f, " {}", fmt_value(p, quote_arg))?;
3642 }
3643 for (k, v) in overrides {
3644 write!(f, " {}={}", k, fmt_value(v, quote_arg))?;
3645 }
3646 Ok(())
3647 }
3648 StepKind::AssertEq {
3649 hash,
3650 actual,
3651 expected,
3652 } => {
3653 if let Some(d) = hash {
3654 write!(f, "ASSERT_EQ --hash {d} {}", fmt_assert_target(actual))?;
3655 } else {
3656 write!(
3657 f,
3658 "ASSERT_EQ {} {}",
3659 fmt_assert_target(actual),
3660 fmt_value(
3661 expected
3662 .as_ref()
3663 .expect("Display of ASSERT_EQ without --hash needs expected"),
3664 quote_msg
3665 )
3666 )?;
3667 }
3668 Ok(())
3669 }
3670 StepKind::AssertContains { haystack, needle } => write!(
3671 f,
3672 "ASSERT_CONTAINS {} {}",
3673 fmt_assert_target(haystack),
3674 fmt_value(needle, quote_msg)
3675 ),
3676 StepKind::WithIo { bindings, cmd } => {
3677 let p: Vec<String> = bindings.iter().map(fmt_io).collect();
3678 write!(f, "WITH_IO [{}] {}", p.join(", "), cmd)
3679 }
3680 StepKind::WithIoBlock { bindings } => {
3681 let p: Vec<String> = bindings.iter().map(fmt_io).collect();
3682 write!(f, "WITH_IO [{}] {{...}}", p.join(", "))
3683 }
3684 StepKind::CopyGit {
3685 rev,
3686 from,
3687 to,
3688 include_dirty,
3689 } => {
3690 if *include_dirty {
3691 write!(
3692 f,
3693 "COPY_GIT --include-dirty {} {} {}",
3694 fmt_value(rev, quote_arg),
3695 fmt_value(from, quote_arg),
3696 fmt_value(to, quote_arg)
3697 )
3698 } else {
3699 write!(
3700 f,
3701 "COPY_GIT {} {} {}",
3702 fmt_value(rev, quote_arg),
3703 fmt_value(from, quote_arg),
3704 fmt_value(to, quote_arg)
3705 )
3706 }
3707 }
3708 StepKind::Exit(code) => write!(f, "EXIT {}", fmt_raw_arg(code)),
3709 StepKind::Sleep { duration } => write!(f, "SLEEP {}", fmt_raw_arg(duration)),
3710 StepKind::ListAppend { list, item } => {
3711 write!(f, "LIST_APPEND ${} {}", list, fmt_raw_arg(item))
3712 }
3713 StepKind::For {
3714 key_var,
3715 key_type,
3716 var,
3717 var_type,
3718 in_expr,
3719 body,
3720 } => {
3721 match key_var {
3722 Some(k) => {
3723 let kt = key_type.as_deref().unwrap_or("STRING");
3724 write!(
3725 f,
3726 "FOR ${}: {}, ${}: {} IN {} {{",
3727 k, kt, var, var_type, in_expr
3728 )?
3729 }
3730 None => write!(f, "FOR ${}: {} IN {} {{", var, var_type, in_expr)?,
3731 }
3732 for s in body {
3733 write!(f, "\n {}", s)?;
3734 }
3735 write!(f, "\n}}")
3736 }
3737 StepKind::If {
3738 cond,
3739 then_body,
3740 else_ifs,
3741 else_body,
3742 } => {
3743 write!(f, "IF {} {{", cond)?;
3744 for s in then_body {
3745 write!(f, "\n {}", s)?;
3746 }
3747 write!(f, " }}")?;
3748 for (c, b) in else_ifs {
3749 write!(f, " ELSE IF {} {{", c)?;
3750 for s in b {
3751 write!(f, "\n {}", s)?;
3752 }
3753 write!(f, " }}")?;
3754 }
3755 if let Some(b) = else_body {
3756 write!(f, " ELSE {{")?;
3757 for s in b {
3758 write!(f, "\n {}", s)?;
3759 }
3760 write!(f, " }}")?;
3761 }
3762 Ok(())
3763 }
3764 StepKind::Assign {
3765 var,
3766 decl_type,
3767 expr,
3768 } => {
3769 if matches!(expr, Expr::FreshPipe) {
3771 write!(f, "LET ${}: {}", var, decl_type)
3772 } else {
3773 write!(f, "LET ${}: {} = {}", var, decl_type, expr)
3774 }
3775 }
3776 StepKind::Set { var, expr } => write!(f, "${} = {}", var, expr),
3777 StepKind::AssignCapture {
3778 var,
3779 decl_type,
3780 cmd,
3781 } => {
3782 write!(f, "LET ${}: {} = {}", var, decl_type, cmd)
3783 }
3784 StepKind::AsyncBlock { body } => {
3785 write!(f, "ASYNC {{")?;
3786 for s in body {
3787 write!(f, "\n {}", s)?;
3788 }
3789 write!(f, "\n}}")
3790 }
3791 StepKind::AssignAsync {
3792 var,
3793 decl_type,
3794 body,
3795 } => {
3796 write!(f, "LET ${}: {} = ASYNC {{", var, decl_type)?;
3797 for s in body {
3798 write!(f, "\n {}", s)?;
3799 }
3800 write!(f, "\n}}")
3801 }
3802 StepKind::Await { var } => write!(f, "AWAIT ${}", var),
3803 StepKind::AwaitCapture {
3804 out_var,
3805 out_type,
3806 task_var,
3807 } => {
3808 write!(f, "LET ${}: {} = AWAIT ${}", out_var, out_type, task_var)
3809 }
3810 StepKind::Cancel { var } => write!(f, "CANCEL ${}", var),
3811 StepKind::Timeout { duration, body } => {
3812 let budget = fmt_raw_arg(duration);
3813 if body.len() == 1 && body[0].guard.is_none() {
3817 write!(f, "TIMEOUT {} {}", budget, body[0].kind)
3818 } else {
3819 write!(f, "TIMEOUT {} {{", budget)?;
3820 for s in body {
3821 write!(f, "\n {}", s)?;
3822 }
3823 write!(f, "\n}}")
3824 }
3825 }
3826 StepKind::Isolated { body } => {
3827 if body.len() == 1 && body[0].guard.is_none() {
3828 write!(f, "ISOLATED {}", body[0].kind)
3829 } else {
3830 write!(f, "ISOLATED {{")?;
3831 for s in body {
3832 write!(f, "\n {}", s)?;
3833 }
3834 write!(f, "\n}}")
3835 }
3836 }
3837 StepKind::IsolatedInheritEnv { keys } => {
3838 write!(f, "INHERIT_ENV [{}]", keys.join(", "))
3842 }
3843 StepKind::RemoteBlock {
3844 target,
3845 vars,
3846 env,
3847 body,
3848 } => {
3849 let mut entries: Vec<String> = vars.iter().map(|v| format!("${v}")).collect();
3850 entries.extend(env.iter().map(|e| format!("env:{e}")));
3851 if entries.is_empty() {
3852 write!(f, "REMOTE {target} {{")?;
3853 } else {
3854 write!(f, "REMOTE {target} [{}] {{", entries.join(", "))?;
3855 }
3856 for s in body {
3857 write!(f, "\n {}", s)?;
3858 }
3859 write!(f, "\n}}")
3860 }
3861 StepKind::FuncDef {
3862 name,
3863 params,
3864 body,
3865 docs,
3866 } => {
3867 if let Some((_, full)) = docs {
3871 for doc_line in full.split('\n') {
3872 writeln!(f, "# {doc_line}")?;
3873 }
3874 }
3875 let ps: Vec<String> = params
3876 .iter()
3877 .map(|(p, t)| format!("${}: {}", p, t))
3878 .collect();
3879 write!(f, "FUNC {}({}) {{", name, ps.join(", "))?;
3880 for s in body {
3881 write!(f, "\n {}", s)?;
3882 }
3883 write!(f, "\n}}")
3884 }
3885 StepKind::Call { name, args } => {
3886 let ps: Vec<String> = args.iter().map(|a| format!("{}", a)).collect();
3887 write!(f, "{}({})", name, ps.join(", "))
3888 }
3889 StepKind::Return { expr } => write!(f, "RETURN {}", expr),
3890 StepKind::TypeAlias { name, target } => write!(f, "TYPE {} = {}", name, target),
3891 StepKind::While { cond, body } => {
3892 write!(f, "WHILE {} {{", cond)?;
3893 for s in body {
3894 write!(f, "\n {}", s)?;
3895 }
3896 write!(f, "\n}}")
3897 }
3898 StepKind::Break => write!(f, "BREAK"),
3899 StepKind::Continue => write!(f, "CONTINUE"),
3900 }
3901 }
3902}
3903
3904pub(crate) enum InsToken {
3909 Pos(Arg),
3910 Assign(String, Arg),
3911}
3912
3913pub(crate) fn lower_env_tokens(ctx: &SpanContext, tokens: Vec<InsToken>) -> ParseResult<StepKind> {
3914 if tokens.is_empty() {
3915 return Err(ParseError::validation(
3916 "ENV",
3917 "ENV requires KEY=value".to_string(),
3918 ctx,
3919 ));
3920 }
3921 match tokens.as_slice() {
3922 [InsToken::Assign(key, value)] => {
3923 if crate::command::split_assignment(&format!("{key}={}", value.render()))
3926 .map_err(|e| ParseError::validation("ENV", e.to_string(), ctx))?
3927 .is_none()
3928 {
3929 return Err(ParseError::validation(
3930 "ENV",
3931 "ENV requires KEY=value format".to_string(),
3932 ctx,
3933 ));
3934 }
3935 Ok(StepKind::Env {
3936 key: key.clone(),
3937 value: value.clone(),
3938 })
3939 }
3940 [InsToken::Pos(Arg::String(text, _))] => match crate::command::split_assignment(text)
3941 .map_err(|e| ParseError::validation("ENV", e.to_string(), ctx))?
3942 {
3943 Some((key, value)) => Ok(StepKind::Env { key, value }),
3944 None => Err(ParseError::validation(
3945 "ENV",
3946 "ENV requires KEY=value format".to_string(),
3947 ctx,
3948 )),
3949 },
3950 _ => Err(ParseError::validation(
3951 "ENV",
3952 "ENV requires KEY=value format".to_string(),
3953 ctx,
3954 )),
3955 }
3956}
3957
3958pub(crate) fn lower_expand_tokens(
3962 ctx: &SpanContext,
3963 tokens: Vec<InsToken>,
3964) -> ParseResult<StepKind> {
3965 let mut path = None;
3966 let mut overrides = Vec::new();
3967 for token in tokens {
3968 match token {
3969 InsToken::Assign(key, value) => {
3970 if key.is_empty() {
3971 return Err(ParseError::validation(
3972 "EXPAND",
3973 "EXPAND requires KEY=value format for overrides".to_string(),
3974 ctx,
3975 ));
3976 }
3977 overrides.push((key, value));
3978 }
3979 InsToken::Pos(arg) => match &arg {
3980 Arg::String(text, quoted) if !quoted && text.contains('=') => {
3981 let Some((key, value)) = crate::command::split_assignment(text)
3982 .map_err(|e| ParseError::validation("EXPAND", e.to_string(), ctx))?
3983 else {
3984 return Err(ParseError::validation(
3985 "EXPAND",
3986 "EXPAND requires KEY=value format for overrides".to_string(),
3987 ctx,
3988 ));
3989 };
3990 overrides.push((key, value));
3991 }
3992 _ => {
3993 if path.is_none() {
3994 ArgType::Path
3998 .check_arg(&arg)
3999 .map_err(|e| ParseError::validation("EXPAND", e.to_string(), ctx))?;
4000 path = Some(arg);
4001 } else {
4002 return Err(ParseError::validation(
4003 "EXPAND",
4004 "EXPAND accepts at most one path".to_string(),
4005 ctx,
4006 ));
4007 }
4008 }
4009 },
4010 }
4011 }
4012 Ok(StepKind::Expand { path, overrides })
4013}
4014
4015#[derive(Default)]
4019pub(crate) struct IoBindingSet {
4020 stdin: Option<IoBinding>,
4021 stdout: Option<IoBinding>,
4022 stderr: Option<IoBinding>,
4023 tty: Option<IoBinding>,
4024 rows: Option<IoBinding>,
4025 cols: Option<IoBinding>,
4026}
4027
4028impl IoBindingSet {
4029 pub(crate) fn insert(&mut self, binding: IoBinding) {
4030 match binding.stream {
4031 IoStream::Stdin => self.stdin = Some(binding),
4032 IoStream::Stdout => self.stdout = Some(binding),
4033 IoStream::Stderr => self.stderr = Some(binding),
4034 IoStream::Tty => self.tty = Some(binding),
4035 IoStream::Rows(_) => self.rows = Some(binding),
4036 IoStream::Cols(_) => self.cols = Some(binding),
4037 }
4038 }
4039
4040 pub(crate) fn into_vec(self) -> Vec<IoBinding> {
4041 let mut out = Vec::new();
4042 if let Some(binding) = self.stdin {
4043 out.push(binding);
4044 }
4045 if let Some(binding) = self.stdout {
4046 out.push(binding);
4047 }
4048 if let Some(binding) = self.stderr {
4049 out.push(binding);
4050 }
4051 if let Some(binding) = self.tty {
4052 out.push(binding);
4053 }
4054 if let Some(binding) = self.rows {
4055 out.push(binding);
4056 }
4057 if let Some(binding) = self.cols {
4058 out.push(binding);
4059 }
4060 out
4061 }
4062}
4063
4064pub(crate) fn merge_bindings(defaults: &[IoBinding], overrides: &[IoBinding]) -> Vec<IoBinding> {
4065 let mut set = IoBindingSet::default();
4066 for binding in defaults {
4067 set.insert(binding.clone());
4068 }
4069 for binding in overrides {
4070 set.insert(binding.clone());
4071 }
4072 set.into_vec()
4073}
4074
4075pub(crate) fn and_guard_exprs(
4076 left: Option<GuardExpr>,
4077 right: Option<GuardExpr>,
4078) -> Option<GuardExpr> {
4079 match (left, right) {
4080 (None, None) => None,
4081 (Some(expr), None) | (None, Some(expr)) => Some(expr),
4082 (Some(lhs), Some(rhs)) => Some(GuardExpr::all(vec![lhs, rhs])),
4083 }
4084}
4085
4086pub(crate) fn has_stdout_pipe(bindings: &[IoBinding]) -> bool {
4087 bindings
4088 .iter()
4089 .any(|b| b.stream == IoStream::Stdout && b.pipe.is_some())
4090}
4091
4092pub(crate) fn reject_async_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
4095 let bad = match kind {
4096 StepKind::AsyncBlock { .. }
4097 | StepKind::AssignAsync { .. }
4098 | StepKind::Await { .. }
4099 | StepKind::AwaitCapture { .. }
4100 | StepKind::Cancel { .. } => true,
4101 _ => {
4102 let mut bad = false;
4103 kind.walk_child_kinds(&mut |child| {
4104 bad = bad || reject_async_in_capture(ctx, child).is_err();
4105 });
4106 bad
4107 }
4108 };
4109 if bad {
4110 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));
4111 }
4112 Ok(())
4113}
4114
4115pub(crate) fn reject_pipe_stdout_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
4118 if let StepKind::WithIo { bindings, .. } = kind
4119 && has_stdout_pipe(bindings)
4120 {
4121 return Err(ParseError::structural(
4122 "let",
4123 "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
4124 .to_string(),
4125 ctx,
4126 ));
4127 }
4128 let mut result = Ok(());
4129 kind.walk_child_kinds(&mut |child| {
4130 if result.is_ok() {
4131 result = reject_pipe_stdout_in_capture(ctx, child);
4132 }
4133 });
4134 result
4135}
4136
4137pub(crate) fn rewrite_isolated_inherit(body: &mut [Step]) {
4141 for step in body {
4142 rewrite_isolated_inherit_kind(&mut step.kind);
4143 }
4144}
4145
4146pub(crate) fn rewrite_isolated_inherit_kind(kind: &mut StepKind) {
4150 if let StepKind::InheritEnv { keys } = kind {
4151 *kind = StepKind::IsolatedInheritEnv { keys: keys.clone() };
4152 }
4153 match kind {
4154 StepKind::For { body, .. }
4155 | StepKind::While { body, .. }
4156 | StepKind::Timeout { body, .. }
4157 | StepKind::Isolated { body }
4158 | StepKind::AssignAsync { body, .. }
4159 | StepKind::AsyncBlock { body } => rewrite_isolated_inherit(body),
4160 StepKind::If {
4161 then_body,
4162 else_ifs,
4163 else_body,
4164 ..
4165 } => {
4166 rewrite_isolated_inherit(then_body);
4167 for (_, branch) in else_ifs {
4168 rewrite_isolated_inherit(branch);
4169 }
4170 if let Some(else_body) = else_body {
4171 rewrite_isolated_inherit(else_body);
4172 }
4173 }
4174 StepKind::WithIo { cmd, .. } | StepKind::AssignCapture { cmd, .. } => {
4175 rewrite_isolated_inherit_kind(cmd);
4176 }
4177 _ => {}
4178 }
4179}
4180
4181pub(crate) fn contains_inherit_env(kind: &StepKind) -> bool {
4182 if matches!(kind, StepKind::InheritEnv { .. }) {
4183 return true;
4184 }
4185 let mut found = false;
4186 kind.walk_child_kinds(&mut |child| {
4187 found = found || contains_inherit_env(child);
4188 });
4189 found
4190}
4191
4192pub(crate) fn reject_nested_inherit_env(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
4196 if contains_inherit_env(kind) {
4197 return Err(ParseError::structural(
4198 "inherit_env",
4199 "INHERIT_ENV cannot be nested inside other commands".to_string(),
4200 ctx,
4201 ));
4202 }
4203 Ok(())
4204}
4205
4206pub(crate) fn check_tty_wrapping(
4207 bindings: &[IoBinding],
4208 cmd: Option<&StepKind>,
4209 span: &SpanContext,
4210) -> ParseResult<()> {
4211 let has_tty = bindings.iter().any(|b| matches!(b.stream, IoStream::Tty));
4212 let has_geometry = bindings
4213 .iter()
4214 .any(|b| matches!(b.stream, IoStream::Rows(_) | IoStream::Cols(_)));
4215 if has_geometry && !has_tty {
4216 return Err(ParseError::structural(
4217 "with_io",
4218 "WITH_IO [rows]/[cols] need [tty] on the same step: geometry without a terminal has nothing to size".to_string(),
4219 span,
4220 ));
4221 }
4222 if !has_tty {
4223 return Ok(());
4224 }
4225 if bindings
4226 .iter()
4227 .any(|b| matches!(b.stream, IoStream::Stderr))
4228 {
4229 return Err(ParseError::structural(
4230 "with_io",
4231 "WITH_IO [tty] cannot bind stderr: the pty master carries stdout and stderr interleaved, so the two streams cannot demultiplex".to_string(),
4232 span,
4233 ));
4234 }
4235 match cmd {
4236 Some(StepKind::Run(_) | StepKind::RunExec { .. }) | None => Ok(()),
4237 Some(_) => Err(ParseError::structural(
4238 "with_io",
4239 "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(),
4240 span,
4241 )),
4242 }
4243}
4244
4245pub(crate) fn reject_with_io_in_async(ctx: &SpanContext, body: &[Step]) -> ParseResult<()> {
4248 for step in body {
4249 if matches!(&step.kind, StepKind::WithIo { .. }) {
4250 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));
4251 }
4252 }
4253 Ok(())
4254}
4255
4256pub(crate) fn validate_exports(
4264 ctx: &SpanContext,
4265 exports: &[String],
4266 top: &HashSet<String>,
4267 modules: &ModuleTable,
4268) -> ParseResult<()> {
4269 for name in exports {
4270 let valid = match name.split_once("::") {
4271 None => top.contains(name),
4272 Some((module, base)) if module == crate::constants::SCRIPT_MODULE_NAME => {
4273 top.contains(base)
4274 }
4275 Some((module, base)) => match modules.modules.get(module) {
4276 None => false,
4277 Some(None) => true,
4278 Some(Some(funcs)) => funcs.functions.contains(base),
4279 },
4280 };
4281 if !valid {
4282 return Err(ParseError::validation(
4283 crate::constants::KEYWORD_EXPORT,
4284 format!("EXPORT `{name}` does not match any top-level FUNC or known module member"),
4285 ctx,
4286 ));
4287 }
4288 }
4289 Ok(())
4290}
4291
4292pub(crate) fn validate_remote_copy_placement(steps: &[Step], ctx: &SpanContext) -> ParseResult<()> {
4299 fn visit_kind(kind: &StepKind, in_remote: bool, ctx: &SpanContext) -> ParseResult<()> {
4300 if let StepKind::Copy {
4301 from_host, to_host, ..
4302 } = kind
4303 && (*from_host || *to_host)
4304 && !in_remote
4305 {
4306 return Err(ParseError::structural(
4307 "copy",
4308 "COPY --from-host and --to-host are only valid inside a REMOTE block".to_string(),
4309 ctx,
4310 ));
4311 }
4312 let child_remote = in_remote || matches!(kind, StepKind::RemoteBlock { .. });
4313 let mut result = Ok(());
4314 kind.walk_child_kinds(&mut |child| {
4315 if result.is_ok() {
4316 result = visit_kind(child, child_remote, ctx);
4317 }
4318 });
4319 result
4320 }
4321 for step in steps {
4322 visit_kind(&step.kind, false, ctx)?;
4323 }
4324 Ok(())
4325}
4326
4327pub(crate) fn contains_remote_block(steps: &[Step]) -> bool {
4331 steps.iter().any(|step| contains_remote_kind(&step.kind))
4332}
4333
4334pub(crate) fn contains_remote_kind(kind: &StepKind) -> bool {
4335 if matches!(kind, StepKind::RemoteBlock { .. }) {
4336 return true;
4337 }
4338 let mut found = false;
4339 kind.walk_child_kinds(&mut |child| {
4340 found = found || contains_remote_kind(child);
4341 });
4342 found
4343}
4344
4345pub(crate) fn collect_remote_body_symbols(
4351 steps: &[Step],
4352 defs: &mut HashSet<String>,
4353 calls: &mut Vec<String>,
4354) {
4355 for step in steps {
4356 collect_remote_kind_symbols(&step.kind, defs, calls);
4357 }
4358}
4359
4360pub(crate) fn collect_remote_kind_symbols(
4361 kind: &StepKind,
4362 defs: &mut HashSet<String>,
4363 calls: &mut Vec<String>,
4364) {
4365 if let StepKind::FuncDef { name, .. } = kind {
4366 defs.insert(name.clone());
4367 }
4368 if let StepKind::Call { name, .. } = kind {
4369 calls.push(name.clone());
4370 }
4371 kind.walk_step_exprs(&mut |expr| match expr {
4372 Expr::Call { name, .. } => calls.push(name.clone()),
4373 Expr::CompiledMath(ops) => {
4374 for op in ops {
4375 if let MathOp::Call { name, .. } = op {
4376 calls.push(name.clone());
4377 }
4378 }
4379 }
4380 Expr::Block(steps) => collect_remote_body_symbols(steps, defs, calls),
4381 _ => {}
4382 });
4383}
4384
4385pub(crate) fn reject_boundary(ctx: &SpanContext, expr: &Expr) -> ParseResult<()> {
4394 if matches!(expr, Expr::UnsignedIntBoundary(_)) {
4395 return Err(ParseError::structural(
4396 "expr",
4397 "integer overflow: 9223372036854775808 exceeds i64::MAX".to_string(),
4398 ctx,
4399 ));
4400 }
4401 Ok(())
4402}
4403
4404pub(crate) fn apply_unary_neg(ctx: &SpanContext, expr: Expr) -> ParseResult<Expr> {
4408 match expr {
4409 Expr::Literal(v) => match (v.as_i64(), v.as_f64()) {
4410 (Some(n), _) => match n.checked_neg() {
4411 Some(neg) => Ok(Expr::Literal(Value::int(neg))),
4412 None => Ok(Expr::CompiledMath(vec![MathOp::PushConst(v), MathOp::Neg])),
4413 },
4414 (None, Some(f)) => Ok(Expr::Literal(Value::float(-f))),
4415 (None, None) => {
4416 let other = Expr::Literal(v);
4417 if let Some(mut ops) = expr_to_rpn(&other) {
4418 ops.push(MathOp::Neg);
4419 Ok(Expr::CompiledMath(ops))
4420 } else {
4421 Ok(Expr::Arithmetic {
4424 op: ArithOp::Sub,
4425 left: Box::new(Expr::Literal(Value::int(0))),
4426 right: Box::new(other),
4427 })
4428 }
4429 }
4430 },
4431 Expr::UnsignedIntBoundary(n) => {
4432 if n == i64::MAX as u64 + 1 {
4433 Ok(Expr::Literal(Value::int(i64::MIN)))
4434 } else {
4435 Err(ParseError::structural(
4436 "expr",
4437 format!("integer overflow: {} exceeds i64::MAX", n),
4438 ctx,
4439 ))
4440 }
4441 }
4442 other => {
4443 if let Some(mut ops) = expr_to_rpn(&other) {
4444 ops.push(MathOp::Neg);
4445 Ok(Expr::CompiledMath(ops))
4446 } else {
4447 Ok(Expr::Arithmetic {
4450 op: ArithOp::Sub,
4451 left: Box::new(Expr::Literal(Value::int(0))),
4452 right: Box::new(other),
4453 })
4454 }
4455 }
4456 }
4457}
4458
4459fn try_fold_arith(op: ArithOp, left: &Expr, right: &Expr) -> Option<Expr> {
4464 let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
4465 return None;
4466 };
4467 fold_arith_values(op, lv, rv).map(Expr::Literal)
4468}
4469
4470fn fold_arith_values(op: ArithOp, left: &Value, right: &Value) -> Option<Value> {
4471 match (left.as_i64(), right.as_i64()) {
4472 (Some(a), Some(b)) => {
4473 let v = match op {
4474 ArithOp::Add => a.checked_add(b)?,
4475 ArithOp::Sub => a.checked_sub(b)?,
4476 ArithOp::Mul => a.checked_mul(b)?,
4477 ArithOp::Div => a.checked_div(b)?,
4478 };
4479 Some(Value::int(v))
4480 }
4481 _ => {
4482 let (af, bf) = (as_f64(left)?, as_f64(right)?);
4483 fold_float(op, af, bf)
4484 }
4485 }
4486}
4487
4488fn fold_float(op: ArithOp, a: f64, b: f64) -> Option<Value> {
4489 if !a.is_finite() || !b.is_finite() {
4490 return None;
4491 }
4492 let v = match op {
4493 ArithOp::Add => a + b,
4494 ArithOp::Sub => a - b,
4495 ArithOp::Mul => a * b,
4496 ArithOp::Div => {
4497 if b == 0.0 {
4498 return None;
4499 }
4500 a / b
4501 }
4502 };
4503 if v.is_finite() {
4504 Some(Value::float(v))
4505 } else {
4506 None
4507 }
4508}
4509
4510fn try_fold_compare(op: CompareOp, left: &Expr, right: &Expr) -> Option<Expr> {
4511 let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
4512 return None;
4513 };
4514 match (lv.as_i64(), rv.as_i64()) {
4515 (Some(a), Some(b)) => {
4516 let r = match op {
4517 CompareOp::Eq => a == b,
4518 CompareOp::Ne => a != b,
4519 CompareOp::Lt => a < b,
4520 CompareOp::Le => a <= b,
4521 CompareOp::Gt => a > b,
4522 CompareOp::Ge => a >= b,
4523 };
4524 Some(Expr::Literal(Value::bool(r)))
4525 }
4526 _ => {
4527 if let (Some(a), Some(b)) = (lv.as_bool(), rv.as_bool()) {
4528 return match op {
4529 CompareOp::Eq => Some(Expr::Literal(Value::bool(a == b))),
4530 CompareOp::Ne => Some(Expr::Literal(Value::bool(a != b))),
4531 _ => None,
4532 };
4533 }
4534 let (af, bf) = (as_f64(lv)?, as_f64(rv)?);
4535 let r = match op {
4536 CompareOp::Eq => af == bf,
4537 CompareOp::Ne => af != bf,
4538 CompareOp::Lt => af < bf,
4539 CompareOp::Le => af <= bf,
4540 CompareOp::Gt => af > bf,
4541 CompareOp::Ge => af >= bf,
4542 };
4543 Some(Expr::Literal(Value::bool(r)))
4544 }
4545 }
4546}
4547
4548fn as_f64(v: &Value) -> Option<f64> {
4549 if let Some(n) = v.as_i64() {
4550 return Some(n as f64);
4551 }
4552 match v.as_f64() {
4553 Some(f) if f.is_finite() => Some(f),
4554 _ => None,
4555 }
4556}
4557
4558pub(crate) fn make_arith(
4560 ctx: &SpanContext,
4561 op: ArithOp,
4562 left: Expr,
4563 right: Expr,
4564) -> ParseResult<Expr> {
4565 reject_boundary(ctx, &left)?;
4566 reject_boundary(ctx, &right)?;
4567 if let Some(folded) = try_fold_arith(op, &left, &right) {
4568 return Ok(folded);
4569 }
4570 if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
4571 lops.append(&mut rops);
4572 lops.push(match op {
4573 ArithOp::Add => MathOp::Add,
4574 ArithOp::Sub => MathOp::Sub,
4575 ArithOp::Mul => MathOp::Mul,
4576 ArithOp::Div => MathOp::Div,
4577 });
4578 return Ok(Expr::CompiledMath(lops));
4579 }
4580 Ok(Expr::Arithmetic {
4581 op,
4582 left: Box::new(left),
4583 right: Box::new(right),
4584 })
4585}
4586
4587pub(crate) fn make_compare(
4589 ctx: &SpanContext,
4590 op: CompareOp,
4591 left: Expr,
4592 right: Expr,
4593) -> ParseResult<Expr> {
4594 reject_boundary(ctx, &left)?;
4595 reject_boundary(ctx, &right)?;
4596 if let Some(folded) = try_fold_compare(op, &left, &right) {
4597 return Ok(folded);
4598 }
4599 if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
4600 lops.append(&mut rops);
4601 lops.push(match op {
4602 CompareOp::Eq => MathOp::Eq,
4603 CompareOp::Ne => MathOp::Ne,
4604 CompareOp::Lt => MathOp::Lt,
4605 CompareOp::Le => MathOp::Le,
4606 CompareOp::Gt => MathOp::Gt,
4607 CompareOp::Ge => MathOp::Ge,
4608 });
4609 return Ok(Expr::CompiledMath(lops));
4610 }
4611 Ok(Expr::Compare {
4612 op,
4613 left: Box::new(left),
4614 right: Box::new(right),
4615 })
4616}
4617
4618pub(crate) fn expr_to_rpn(expr: &Expr) -> Option<Vec<MathOp>> {
4624 match expr {
4625 Expr::Literal(v) => Some(vec![MathOp::PushConst(v.clone())]),
4626 Expr::Var(name) => Some(vec![MathOp::LoadVar(name.clone())]),
4627 Expr::Env(key) => Some(vec![MathOp::LoadEnv(key.clone())]),
4628 Expr::KeyPath { base, keys } => Some(vec![MathOp::LoadKeyPath {
4629 base: base.clone(),
4630 keys: keys.clone(),
4631 }]),
4632 Expr::Call { name, args } => {
4633 let mut ops = Vec::new();
4634 for arg in args {
4635 ops.extend(expr_to_rpn(arg)?);
4636 }
4637 ops.push(MathOp::Call {
4638 name: name.clone(),
4639 arity: args.len(),
4640 });
4641 Some(ops)
4642 }
4643 Expr::Inspect(var) => Some(vec![MathOp::Inspect(var.clone())]),
4644 Expr::Arithmetic { op, left, right } => {
4645 let mut ops = expr_to_rpn(left)?;
4646 ops.extend(expr_to_rpn(right)?);
4647 ops.push(match op {
4648 ArithOp::Add => MathOp::Add,
4649 ArithOp::Sub => MathOp::Sub,
4650 ArithOp::Mul => MathOp::Mul,
4651 ArithOp::Div => MathOp::Div,
4652 });
4653 Some(ops)
4654 }
4655 Expr::Compare { op, left, right } => {
4656 let mut ops = expr_to_rpn(left)?;
4657 ops.extend(expr_to_rpn(right)?);
4658 ops.push(match op {
4659 CompareOp::Eq => MathOp::Eq,
4660 CompareOp::Ne => MathOp::Ne,
4661 CompareOp::Lt => MathOp::Lt,
4662 CompareOp::Le => MathOp::Le,
4663 CompareOp::Gt => MathOp::Gt,
4664 CompareOp::Ge => MathOp::Ge,
4665 });
4666 Some(ops)
4667 }
4668 Expr::CompiledMath(ops) => Some(ops.clone()),
4669 Expr::FreshPipe => None,
4670 Expr::Not(_) | Expr::Logical { .. } | Expr::List(_) | Expr::Map(_) | Expr::Block(_) => None,
4671 Expr::UnsignedIntBoundary(_) => None,
4672 }
4673}
4674
4675pub(crate) fn classify_numeric_text(text: &str) -> Result<Expr, String> {
4680 let clean = text.replace('_', "");
4681 if clean.contains('.') {
4682 let parsed: f64 = clean
4683 .parse()
4684 .map_err(|_| format!("invalid float literal {text:?}"))?;
4685 if !parsed.is_finite() {
4686 return Err(format!("invalid float literal {text:?}"));
4687 }
4688 return Ok(Expr::Literal(Value::float(parsed)));
4689 }
4690 let digits: u64 = clean
4691 .parse()
4692 .map_err(|_| format!("integer overflow: {text:?} exceeds i64::MAX"))?;
4693 if digits <= i64::MAX as u64 {
4694 Ok(Expr::Literal(Value::int(digits as i64)))
4695 } else if digits == i64::MAX as u64 + 1 {
4696 Ok(Expr::UnsignedIntBoundary(digits))
4697 } else {
4698 Err(format!("integer overflow: {text:?} exceeds i64::MAX"))
4699 }
4700}
4701
4702#[cfg(test)]
4703mod tests {
4704 use super::*;
4705 use crate::command::{
4706 format_byte_count, format_duration, parse_byte_count, parse_duration,
4707 strip_digit_separators,
4708 };
4709 use crate::parser::parse_script;
4710
4711 fn parse_err(script: &str) -> String {
4712 parse_script(script, lower_command)
4713 .expect_err("script must fail to parse")
4714 .to_string()
4715 }
4716
4717 #[test]
4718 fn malformed_with_io_binding_names_the_bad_binding() {
4719 let err = parse_err("WITH_IO [stdout=discard] ECHO \"test\"\n");
4720 assert!(err.contains("invalid syntax for command WITH_IO"), "{err}");
4721 assert!(!err.contains("unknown command"), "{err}");
4722 assert!(err.contains("stdout=discard"), "{err}");
4723 assert!(err.contains("[stdout=$p]"), "{err}");
4724 }
4725
4726 #[test]
4727 fn connect_is_unknown_command() {
4728 let err = parse_err("CONNECT 127.0.0.1:8080\n");
4731 assert!(err.contains("unknown command"), "{err}");
4732 assert!(err.contains("CONNECT"), "{err}");
4733 }
4734
4735 #[test]
4736 fn listen_is_unknown_command() {
4737 let err = parse_err("LISTEN 127.0.0.1:8080\n");
4740 assert!(err.contains("unknown command"), "{err}");
4741 assert!(err.contains("LISTEN"), "{err}");
4742 }
4743
4744 #[test]
4745 fn await_without_task_variable_points_at_syntax() {
4746 let err = parse_err("AWAIT ECHO \"test\"\n");
4747 assert!(err.contains("invalid syntax for command AWAIT"), "{err}");
4748 assert!(!err.contains("unknown command"), "{err}");
4749 assert!(err.contains("AWAIT $t"), "{err}");
4750 assert!(err.contains("ECHO"), "{err}");
4751 }
4752
4753 #[test]
4754 fn bare_let_without_type_points_at_typed_syntax() {
4755 let err = parse_err("LET $x = 1\n");
4756 assert!(err.contains("invalid syntax for command LET"), "{err}");
4757 assert!(err.contains("LET $name: STRING = <expr>"), "{err}");
4758 }
4759
4760 #[test]
4761 fn workspace_accepts_all_four_targets_uppercase_only() {
4762 for (spelling, target) in [
4765 ("SNAPSHOT", WorkspaceTarget::Snapshot),
4766 ("LOCAL", WorkspaceTarget::Local),
4767 ("CACHE", WorkspaceTarget::Cache { local: false }),
4768 ("SYSTEM", WorkspaceTarget::System),
4769 ] {
4770 let steps =
4771 parse_script(&format!("WORKSPACE {spelling}\n"), lower_command).expect("parses");
4772 assert_eq!(steps.len(), 1);
4773 assert_eq!(steps[0].kind, StepKind::Workspace(target.clone()));
4774 assert_eq!(steps[0].kind.to_string(), format!("WORKSPACE {target}"));
4775 }
4776 for spelling in ["snapshot", "local", "cache", "system"] {
4777 let err = parse_err(&format!("WORKSPACE {spelling}\n"));
4778 assert!(
4779 err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
4780 "{spelling}: {err}"
4781 );
4782 }
4783 let err = parse_err("WORKSPACE REMOTE\n");
4784 assert!(
4785 err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
4786 "{err}"
4787 );
4788
4789 let steps = parse_script("WORKSPACE CACHE --local\n", lower_command).expect("parses");
4792 assert_eq!(
4793 steps[0].kind,
4794 StepKind::Workspace(WorkspaceTarget::Cache { local: true })
4795 );
4796 assert_eq!(steps[0].kind.to_string(), "WORKSPACE CACHE --local");
4797 for bad in [
4798 "WORKSPACE SNAPSHOT --local\n",
4799 "WORKSPACE LOCAL --local\n",
4800 "WORKSPACE SYSTEM --local\n",
4801 ] {
4802 let err = parse_err(bad);
4803 assert!(err.contains("--local requires CACHE"), "{bad}: {err}");
4804 }
4805 }
4806
4807 #[test]
4808 fn archive_unarchive_parse_and_round_trip() {
4809 let steps = parse_script("ARCHIVE bundle bundle.tar.gz\n", lower_command).expect("parses");
4810 match &steps[0].kind {
4811 StepKind::Archive { src, dst, raw } => {
4812 assert_eq!(src.as_str(), "bundle");
4813 assert_eq!(dst.as_str(), "bundle.tar.gz");
4814 assert!(!raw);
4815 }
4816 other => panic!("expected Archive, got {other:?}"),
4817 }
4818 assert_eq!(
4819 steps[0].kind.to_string(),
4820 "ARCHIVE bundle \"bundle.tar.gz\""
4821 );
4822
4823 let steps =
4824 parse_script("ARCHIVE --raw tool.bin tool.tar\n", lower_command).expect("parses");
4825 assert!(
4826 matches!(&steps[0].kind, StepKind::Archive { raw: true, .. }),
4827 "unexpected lowering: {:?}",
4828 steps[0].kind
4829 );
4830 assert_eq!(
4831 steps[0].kind.to_string(),
4832 "ARCHIVE --raw \"tool.bin\" \"tool.tar\""
4833 );
4834
4835 let steps =
4836 parse_script("UNARCHIVE pack.tar.gz unpacked\n", lower_command).expect("parses");
4837 match &steps[0].kind {
4838 StepKind::Unarchive {
4839 src,
4840 dst,
4841 max_bytes,
4842 } => {
4843 assert_eq!(src.as_str(), "pack.tar.gz");
4844 assert_eq!(dst.as_str(), "unpacked");
4845 assert_eq!(max_bytes, &None);
4846 }
4847 other => panic!("expected Unarchive, got {other:?}"),
4848 }
4849 assert_eq!(
4850 steps[0].kind.to_string(),
4851 "UNARCHIVE \"pack.tar.gz\" unpacked"
4852 );
4853
4854 let steps = parse_script(
4855 "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
4856 lower_command,
4857 )
4858 .expect("parses");
4859 match &steps[0].kind {
4860 StepKind::Unarchive {
4861 src,
4862 dst,
4863 max_bytes,
4864 } => {
4865 assert_eq!(src.as_str(), "pack.tar.gz");
4866 assert_eq!(dst.as_str(), "unpacked");
4867 assert_eq!(max_bytes.as_ref().map(|a| a.as_str()), Some("100_000"));
4868 }
4869 other => panic!("expected Unarchive, got {other:?}"),
4870 }
4871 assert_eq!(
4872 steps[0].kind.to_string(),
4873 "UNARCHIVE --max-bytes \"100_000\" \"pack.tar.gz\" unpacked"
4874 );
4875
4876 for script in [
4877 "ARCHIVE bundle bundle.tar.gz\n",
4878 "ARCHIVE --raw tool.bin tool.tar\n",
4879 "UNARCHIVE pack.tar.gz unpacked\n",
4880 "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
4881 ] {
4882 let first = parse_script(script, lower_command).expect("parses");
4883 let rendered = first[0].kind.to_string() + "\n";
4884 let second = parse_script(&rendered, lower_command).expect("reparses");
4885 assert_eq!(
4888 second[0].kind.to_string(),
4889 first[0].kind.to_string(),
4890 "Display must fixpoint for {script:?}"
4891 );
4892 }
4893
4894 for bad in ["ARCHIVE only-src\n", "ARCHIVE\n", "UNARCHIVE only-src\n"] {
4895 let err = parse_err(bad);
4896 assert!(
4897 err.contains("ARCHIVE") || err.contains("UNARCHIVE"),
4898 "{bad}: {err}"
4899 );
4900 }
4901 }
4902
4903 #[test]
4904 fn copy_from_workspace_selects_source_root() {
4905 for (spelling, target) in [
4906 ("SNAPSHOT", WorkspaceTarget::Snapshot),
4907 ("LOCAL", WorkspaceTarget::Local),
4908 ("CACHE", WorkspaceTarget::Cache { local: false }),
4909 ("SYSTEM", WorkspaceTarget::System),
4910 ] {
4911 let steps = parse_script(
4912 &format!("COPY --from-workspace {spelling} a.txt b.txt\n"),
4913 lower_command,
4914 )
4915 .expect("parses");
4916 assert!(
4917 matches!(&steps[0].kind, StepKind::Copy { from_workspace: Some(t), .. } if *t == target),
4918 "unexpected lowering for {spelling}: {:?}",
4919 steps[0].kind
4920 );
4921 }
4922 for script in [
4925 "COPY --from-workspace=CACHE a.txt b.txt\n",
4926 "COPY --from-workspace=\"CACHE\" a.txt b.txt\n",
4927 ] {
4928 let steps = parse_script(script, lower_command).expect("parses");
4929 assert!(
4930 matches!(
4931 &steps[0].kind,
4932 StepKind::Copy {
4933 from_workspace: Some(WorkspaceTarget::Cache { local: false }),
4934 ..
4935 }
4936 ),
4937 "unexpected lowering for {script:?}: {:?}",
4938 steps[0].kind
4939 );
4940 }
4941 let steps = parse_script("COPY a.txt b.txt\n", lower_command).expect("parses");
4943 assert!(
4944 matches!(
4945 &steps[0].kind,
4946 StepKind::Copy {
4947 from_workspace: None,
4948 ..
4949 }
4950 ),
4951 "unexpected lowering: {:?}",
4952 steps[0].kind
4953 );
4954 for bad in ["REMOTE", "local"] {
4956 let err = parse_err(&format!("COPY --from-workspace {bad} a.txt b.txt\n"));
4957 assert!(err.contains("unknown workspace source"), "{bad}: {err}");
4958 }
4959 }
4960
4961 #[test]
4962 fn symlink_from_workspace_selects_source_root() {
4963 for (spelling, target) in [
4964 ("SNAPSHOT", WorkspaceTarget::Snapshot),
4965 ("LOCAL", WorkspaceTarget::Local),
4966 ("CACHE", WorkspaceTarget::Cache { local: false }),
4967 ("SYSTEM", WorkspaceTarget::System),
4968 ] {
4969 let steps = parse_script(
4970 &format!("SYMLINK --from-workspace {spelling} a.txt b.txt\n"),
4971 lower_command,
4972 )
4973 .expect("parses");
4974 assert!(
4975 matches!(&steps[0].kind, StepKind::Symlink { from_workspace: Some(t), .. } if *t == target),
4976 "unexpected lowering for {spelling}: {:?}",
4977 steps[0].kind
4978 );
4979 let roundtrip = steps[0].kind.to_string();
4980 assert!(
4981 roundtrip.contains("--from-workspace"),
4982 "display should round-trip the flag: {roundtrip}"
4983 );
4984 }
4985 let steps = parse_script("SYMLINK a.txt b.txt\n", lower_command).expect("parses");
4986 assert!(
4987 matches!(
4988 &steps[0].kind,
4989 StepKind::Symlink {
4990 from_workspace: None,
4991 ..
4992 }
4993 ),
4994 "unexpected lowering: {:?}",
4995 steps[0].kind
4996 );
4997 for bad in ["REMOTE", "local"] {
4998 let err = parse_err(&format!("SYMLINK --from-workspace {bad} a.txt b.txt\n"));
4999 assert!(err.contains("unknown workspace source"), "{bad}: {err}");
5000 }
5001 let steps = parse_script(
5003 "SYMLINK --from-workspace=LOCAL a.txt b.txt\n",
5004 lower_command,
5005 )
5006 .expect("parses");
5007 assert!(
5008 matches!(
5009 &steps[0].kind,
5010 StepKind::Symlink {
5011 from_workspace: Some(WorkspaceTarget::Local),
5012 ..
5013 }
5014 ),
5015 "unexpected lowering: {:?}",
5016 steps[0].kind
5017 );
5018 }
5019
5020 #[test]
5021 fn dash_dash_equals_tokens_bypass_assignment() {
5022 let steps = parse_script("ENV --foo=bar\n", lower_command).expect("parses");
5025 let StepKind::Env { key, value } = &steps[0].kind else {
5026 panic!("expected Env, got {:?}", steps[0].kind);
5027 };
5028 assert_eq!(key, "--foo");
5029 assert_eq!(value.as_str(), "bar");
5030
5031 let steps = parse_script("RUN echo --foo=bar\n", lower_command).expect("parses");
5032 let StepKind::Run(cmd) = &steps[0].kind else {
5033 panic!("expected Run, got {:?}", steps[0].kind);
5034 };
5035 assert!(
5036 cmd.as_str().contains("--foo=bar"),
5037 "unexpected RUN lowering: {cmd:?}"
5038 );
5039
5040 let digest = "08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c";
5041 let steps = parse_script(&format!("ASSERT_EQ --hash={digest} $body\n"), lower_command)
5042 .expect("parses");
5043 let StepKind::AssertEq { hash, .. } = &steps[0].kind else {
5044 panic!("expected AssertEq, got {:?}", steps[0].kind);
5045 };
5046 assert_eq!(hash.as_deref(), Some(digest));
5047
5048 let steps = parse_script("EXPAND --k=v\n", lower_command).expect("parses");
5050 let StepKind::Expand { path, overrides } = &steps[0].kind else {
5051 panic!("expected Expand, got {:?}", steps[0].kind);
5052 };
5053 assert!(path.is_none());
5054 assert_eq!(overrides.len(), 1);
5055 assert_eq!(overrides[0].0.as_str(), "--k");
5056 }
5057
5058 #[test]
5059 fn space_before_paren_is_not_a_call() {
5060 let steps = parse_script("ECHO (1 + 2)\n", lower_command).expect("parses");
5063 assert_eq!(steps.len(), 1);
5064 assert!(
5065 !matches!(steps[0].kind, crate::ast::StepKind::Call { .. }),
5066 "space before paren must not route to a call: {:?}",
5067 steps[0].kind
5068 );
5069 }
5070
5071 #[test]
5072 fn unknown_type_tag_parses_as_custom() {
5073 let steps = parse_script("LET $x: FOO = 1\n", lower_command).expect("custom tag parses");
5077 let StepKind::Assign { decl_type, .. } = &steps[0].kind else {
5078 panic!("expected Assign, got {:?}", steps[0].kind);
5079 };
5080 assert_eq!(decl_type, "FOO");
5081 }
5082
5083 #[test]
5084 fn bare_for_without_types_is_rejected() {
5085 let err = parse_err("FOR $i IN [1] { ECHO hi }\n");
5086 assert!(err.contains("FOR requires explicit types"), "{err}");
5087 }
5088
5089 #[test]
5090 fn mutate_statement_parses_without_keyword() {
5091 let steps = parse_script("$y = 2\n", lower_command).expect("mutation parses");
5092 assert!(matches!(steps[0].kind, StepKind::Set { .. }));
5093 }
5094
5095 #[test]
5096 fn set_keyword_is_rejected_with_mutation_hint() {
5097 let err = parse_err("SET $y = 2\n");
5098 assert!(err.contains("not a keyword"), "{err}");
5099 assert!(err.contains("$var = <expr>"), "{err}");
5100 }
5101
5102 #[test]
5103 fn structural_fallthrough_commits_per_keyword() {
5104 for (script, cmd) in [
5105 ("CANCEL foo\n", "CANCEL"),
5106 ("TIMEOUT foo\n", "TIMEOUT"),
5107 ("FOR foo\n", "FOR"),
5108 ("IF foo\n", "IF"),
5109 ("LET foo\n", "LET"),
5110 ("ASYNC\n", "ASYNC"),
5114 ("ELSE foo\n", "ELSE"),
5115 ] {
5116 let err = parse_err(script);
5117 assert!(
5118 err.contains(&format!("invalid syntax for command {cmd}")),
5119 "{cmd}: {err}"
5120 );
5121 assert!(!err.contains("unknown command"), "{cmd}: {err}");
5122 }
5123 }
5124
5125 #[test]
5126 fn leaf_arity_errors_carry_invalid_syntax_prefix() {
5127 let err = parse_err("SLEEP 1s 2s\n");
5128 assert!(err.contains("invalid syntax for command SLEEP"), "{err}");
5129 assert!(!err.contains("unknown command"), "{err}");
5130 }
5131
5132 #[test]
5133 fn list_append_lowers_variable_and_item() {
5134 let steps = parse_script("LIST_APPEND $items \"hi\"\n", lower_command).expect("parses");
5135 let StepKind::ListAppend { list, item } = &steps[0].kind else {
5136 panic!("expected ListAppend, got {:?}", steps[0].kind);
5137 };
5138 assert_eq!(list, "items");
5139 assert!(matches!(item, Arg::String(s, _) if s == "hi"));
5140 assert_eq!(steps[0].kind.to_string(), "LIST_APPEND $items \"hi\"");
5141 }
5142
5143 #[test]
5144 fn list_append_rejects_wrong_arity() {
5145 for script in [
5146 "LIST_APPEND\n",
5147 "LIST_APPEND $items\n",
5148 "LIST_APPEND $items \"a\" \"b\"\n",
5149 ] {
5150 let err = parse_err(script);
5151 assert!(
5152 err.contains("invalid syntax for command LIST_APPEND"),
5153 "{script}: {err}"
5154 );
5155 assert!(!err.contains("unknown command"), "{script}: {err}");
5156 }
5157 }
5158
5159 #[test]
5160 fn list_append_rejects_non_variable_target() {
5161 let err = parse_err("LIST_APPEND items \"a\"\n");
5162 assert!(
5163 err.contains("invalid syntax for command LIST_APPEND"),
5164 "{err}"
5165 );
5166 assert!(!err.contains("unknown command"), "{err}");
5167 }
5168
5169 #[test]
5170 fn read_line_rejects_bare_word_target() {
5171 let err = parse_err("READ_LINE reply\n");
5175 assert!(err.contains("READ_LINE requires a $variable"), "{err}");
5176 assert!(!err.contains("unknown command"), "{err}");
5177 }
5178
5179 #[test]
5180 fn genuinely_unknown_command_keeps_bare_message() {
5181 let err = parse_err("FROBNICATE hi\n");
5182 assert!(err.contains("unknown command: FROBNICATE"), "{err}");
5183 assert!(!err.contains("did you mean"), "{err}");
5184 }
5185
5186 #[test]
5187 fn lowercase_command_suggests_uppercase() {
5188 let err = lower_command("echo", vec![Arg::String("hi".to_string(), false)])
5192 .expect_err("must fail")
5193 .to_string();
5194 assert!(err.contains("unknown command: echo"), "{err}");
5195 assert!(err.contains("did you mean `ECHO`"), "{err}");
5196 }
5197
5198 #[test]
5199 fn func_def_requires_typed_uppercase_name() {
5200 let steps = parse_script(
5201 "FUNC GREET($name: STRING) {\n RETURN $name\n}\n",
5202 lower_command,
5203 )
5204 .expect("func def parses");
5205 let StepKind::FuncDef {
5206 name,
5207 params,
5208 body,
5209 docs,
5210 } = &steps[0].kind
5211 else {
5212 panic!("expected FuncDef, got {:?}", steps[0].kind);
5213 };
5214 assert_eq!(name, "GREET");
5215 assert_eq!(
5216 params,
5217 &vec![("name".to_string(), "STRING".to_string())],
5218 "{params:?}"
5219 );
5220 assert!(matches!(body[0].kind, StepKind::Return { .. }));
5221 assert!(docs.is_none(), "undocumented FUNC carries no docs");
5222 }
5223
5224 #[test]
5225 fn lowercase_func_name_is_rejected() {
5226 let err = parse_err("FUNC greet($x: STRING) {\n RETURN $x\n}\n");
5227 assert!(err.contains("FUNC"), "{err}");
5228 }
5229
5230 #[test]
5231 fn call_and_while_lower_correctly() {
5232 let steps = parse_script(
5233 "FUNC GREET($name: STRING) {\n RETURN $name\n}\nGREET(\"ada\")\n",
5234 lower_command,
5235 )
5236 .expect("call parses");
5237 assert!(
5238 matches!(&steps[1].kind, StepKind::Call { name, .. } if name == "SCRIPT::GREET"),
5239 "{:?}",
5240 steps[1].kind
5241 );
5242 let steps = parse_script(
5243 "FUNC GREET($a: STRING, $b: STRING) {\n RETURN $a\n}\nGREET(\"ada\", \"bex\")\n",
5244 lower_command,
5245 )
5246 .expect("spaced call parses");
5247 assert!(
5248 matches!(&steps[1].kind, StepKind::Call { name, args } if name == "SCRIPT::GREET" && args.len() == 2),
5249 "{:?}",
5250 steps[1].kind
5251 );
5252 let steps = parse_script(
5253 indoc! {r#"
5254 WHILE !$done {
5255 BREAK
5256 }
5257 "#},
5258 lower_command,
5259 )
5260 .expect("while parses");
5261 let StepKind::While { body, .. } = &steps[0].kind else {
5262 panic!("expected While, got {:?}", steps[0].kind);
5263 };
5264 assert!(matches!(body[0].kind, StepKind::Break));
5265 }
5266
5267 #[test]
5268 fn let_capture_call_and_async_call_lower() {
5269 let steps = parse_script(
5272 indoc! {r#"
5273 FUNC GREET($name: STRING) {
5274 RETURN $name
5275 }
5276 LET $r: STRING = GREET("ada")
5277 "#},
5278 lower_command,
5279 )
5280 .expect("capture call parses");
5281 let StepKind::Assign { var, expr, .. } = &steps[1].kind else {
5282 panic!("expected Assign, got {:?}", steps[1].kind);
5283 };
5284 assert_eq!(var, "r");
5285 assert!(
5286 matches!(expr, Expr::Call { name, .. } if name == "SCRIPT::GREET"),
5287 "{expr:?}"
5288 );
5289 let steps = parse_script(
5290 "FUNC GREET($name: STRING) {\n RETURN $name\n}\nLET $t: HANDLE = ASYNC GREET(\"a\")\n",
5291 lower_command,
5292 )
5293 .expect("async call parses");
5294 assert!(
5295 matches!(&steps[1].kind, StepKind::AssignAsync { .. }),
5296 "{:?}",
5297 steps[1].kind
5298 );
5299 }
5300
5301 #[test]
5302 fn multiline_call_args_span_lines() {
5303 let steps = parse_script(
5307 "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",
5308 lower_command,
5309 )
5310 .expect("multiline call parses");
5311 let StepKind::Assign { expr, .. } = &steps[1].kind else {
5312 panic!("expected Assign, got {:?}", steps[1].kind);
5313 };
5314 let Expr::Call { name, args } = expr else {
5315 panic!("expected Call expr, got {expr:?}");
5316 };
5317 assert_eq!(name, "SCRIPT::SERVE");
5318 assert_eq!(args.len(), 4);
5319 assert!(matches!(&args[3], Expr::Map(entries) if entries.len() == 1));
5320 let rendered = steps[1].to_string();
5322 assert!(!rendered.contains('\n'), "{rendered}");
5323 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";
5324 let again = parse_script(script, lower_command).expect("reparse ok");
5325 assert_eq!(again, steps);
5326 }
5327
5328 #[test]
5329 fn multiline_bare_call_and_list_span_lines() {
5330 let steps = parse_script(
5331 indoc! {r#"
5332 FUNC GREET($a: STRING) {
5333 RETURN $a
5334 }
5335 GREET(
5336 "ada"
5337 )
5338 "#},
5339 lower_command,
5340 )
5341 .expect("multiline bare call parses");
5342 let StepKind::Call { name, args } = &steps[1].kind else {
5343 panic!("expected Call, got {:?}", steps[1].kind);
5344 };
5345 assert_eq!(name, "SCRIPT::GREET");
5346 assert_eq!(args.len(), 1);
5347 let steps = parse_script(
5348 indoc! {r#"
5349 LET $l: LIST = [
5350 "a",
5351 "b"
5352 ]
5353 "#},
5354 lower_command,
5355 )
5356 .expect("multiline list parses");
5357 let StepKind::Assign { expr, .. } = &steps[0].kind else {
5358 panic!("expected Assign, got {:?}", steps[0].kind);
5359 };
5360 assert!(
5361 matches!(expr, Expr::List(items) if items.len() == 2),
5362 "{expr:?}"
5363 );
5364 }
5365
5366 #[test]
5367 fn parse_duration_units() {
5368 use std::time::Duration;
5369 assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
5370 assert_eq!(parse_duration("10s").unwrap(), Duration::from_secs(10));
5371 assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
5372 assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
5373 assert_eq!(parse_duration("30").unwrap(), Duration::from_secs(30));
5374 assert_eq!(parse_duration("30 s").unwrap(), Duration::from_secs(30));
5376 assert_eq!(parse_duration("2 m").unwrap(), Duration::from_secs(120));
5377 }
5378
5379 #[test]
5380 fn parse_duration_rejects_garbage() {
5381 assert!(parse_duration("").is_err());
5382 assert!(parse_duration("banana").is_err());
5383 assert!(parse_duration("10x").is_err());
5384 assert!(parse_duration("0s").is_err());
5385 assert!(parse_duration("0").is_err());
5386 assert!(parse_duration("-5s").is_err());
5387 assert!(parse_duration("30 s s").is_err());
5389 assert!(parse_duration("3 0s").is_err());
5390 }
5391
5392 #[test]
5393 fn parse_byte_count_units() {
5394 assert_eq!(parse_byte_count("500").unwrap(), 500);
5395 assert_eq!(parse_byte_count("500B").unwrap(), 500);
5396 assert_eq!(parse_byte_count("10KB").unwrap(), 10_000);
5397 assert_eq!(parse_byte_count("2MB").unwrap(), 2_000_000);
5398 assert_eq!(parse_byte_count("1GB").unwrap(), 1_000_000_000);
5399 assert_eq!(parse_byte_count("1TB").unwrap(), 1_000_000_000_000);
5400 assert_eq!(parse_byte_count("10KIB").unwrap(), 10 * 1_024);
5401 assert_eq!(parse_byte_count("2MIB").unwrap(), 2 * 1_024 * 1_024);
5402 assert_eq!(parse_byte_count("1GIB").unwrap(), 1_024 * 1_024 * 1_024);
5403 assert_eq!(
5404 parse_byte_count("1TIB").unwrap(),
5405 1_024 * 1_024 * 1_024 * 1_024
5406 );
5407 assert_eq!(parse_byte_count("1gb").unwrap(), 1_000_000_000);
5409 assert_eq!(parse_byte_count("1Gb").unwrap(), 1_000_000_000);
5410 assert_eq!(parse_byte_count("1gib").unwrap(), 1_024 * 1_024 * 1_024);
5411 assert_eq!(parse_byte_count("1Gib").unwrap(), 1_024 * 1_024 * 1_024);
5412 assert_eq!(parse_byte_count("1_000").unwrap(), 1_000);
5414 assert_eq!(
5415 parse_byte_count("1_000_000_000_000").unwrap(),
5416 1_000_000_000_000
5417 );
5418 assert_eq!(parse_byte_count("1_0KB").unwrap(), 10_000);
5419 assert_eq!(
5420 parse_byte_count("1_0GiB").unwrap(),
5421 10 * 1_024 * 1_024 * 1_024
5422 );
5423 assert_eq!(parse_byte_count("1 GB").unwrap(), 1_000_000_000);
5425 assert_eq!(parse_byte_count("10 KiB").unwrap(), 10_240);
5426 assert_eq!(parse_byte_count(" 2MB ").unwrap(), 2_000_000);
5427 assert_eq!(parse_byte_count("+1 GB").unwrap(), 1_000_000_000);
5429 assert!(parse_byte_count("-1 GB").is_err());
5430 }
5431
5432 #[test]
5433 fn parse_byte_count_rejects_garbage() {
5434 for bad in [
5435 "",
5436 "banana",
5437 "10x",
5438 "1G",
5439 "1K",
5440 "1.5GB",
5441 "-5",
5442 "-5GB",
5443 "0",
5444 "0GB",
5445 "_100",
5446 "100_",
5447 "1__000",
5448 "_",
5449 "1_GB",
5450 "1 G B",
5452 "1 2",
5453 "1 0",
5454 "1000000000000000000000000",
5456 "1000000000TB",
5457 ] {
5458 assert!(parse_byte_count(bad).is_err(), "{bad:?} must fail");
5459 }
5460 }
5461
5462 #[test]
5463 fn format_byte_count_round_trips() {
5464 for text in [
5465 "500", "500B", "10KB", "2MB", "1GB", "1TB", "10KIB", "2MIB", "1GIB", "1TIB", "1500B",
5466 ] {
5467 let parsed = parse_byte_count(text).unwrap();
5468 let rendered = format_byte_count(parsed);
5469 assert_eq!(
5470 parse_byte_count(&rendered).unwrap(),
5471 parsed,
5472 "round-trip failed for {text}"
5473 );
5474 }
5475 assert_eq!(format_byte_count(1_024 * 1_024 * 1_024), "1GiB");
5476 assert_eq!(format_byte_count(1_000_000_000), "1GB");
5477 }
5478
5479 #[test]
5480 fn strip_digit_separators_passes_signs_through() {
5481 assert_eq!(strip_digit_separators("-1_000"), "-1000");
5485 assert_eq!(strip_digit_separators("+1_000_000"), "+1000000");
5486 assert_eq!(strip_digit_separators("-1_000.5"), "-1000.5");
5487 assert_eq!(strip_digit_separators("1_000"), "1000");
5488 for untouched in ["+", "-", "", "1__0", "abc", "+-5", "--5"] {
5489 assert_eq!(strip_digit_separators(untouched), untouched);
5490 }
5491 assert!(parse_byte_count("-1_000").is_err());
5494 assert_eq!(parse_byte_count("+1GB").unwrap(), 1_000_000_000);
5495 }
5496
5497 #[test]
5498 fn format_byte_count_is_lossless() {
5499 for n in [
5504 1,
5505 500,
5506 999,
5507 1_000,
5508 1_024,
5509 1_500,
5510 1_000_000,
5511 1_048_576,
5512 1_000_000_000,
5513 1_073_741_824,
5514 1_000_000_000_000,
5515 1_099_511_627_776,
5516 u64::MAX,
5517 ] {
5518 assert_eq!(
5519 parse_byte_count(&format_byte_count(n)).unwrap(),
5520 n,
5521 "lossless round-trip failed for {n}"
5522 );
5523 }
5524 }
5525
5526 #[test]
5527 fn format_duration_round_trips() {
5528 for text in ["500ms", "10s", "2m", "1h", "90s", "1500ms"] {
5529 let parsed = parse_duration(text).unwrap();
5530 let rendered = format_duration(&parsed);
5531 assert_eq!(
5532 parse_duration(&rendered).unwrap(),
5533 parsed,
5534 "round-trip failed for {text}"
5535 );
5536 }
5537 assert_eq!(format_duration(&parse_duration("90s").unwrap()), "90s");
5538 assert_eq!(format_duration(&parse_duration("2m").unwrap()), "2m");
5539 }
5540
5541 #[test]
5542 fn structural_metadata_covers_all_structural_kinds() {
5543 use crate::ast::Value;
5544
5545 fn metadata_name(kind: &StepKind) -> Option<&'static str> {
5549 match kind {
5550 StepKind::WithIo { .. } | StepKind::WithIoBlock { .. } => Some("WITH_IO"),
5551 StepKind::For { .. } => Some("FOR"),
5552 StepKind::If { .. } => Some("IF"),
5553 StepKind::Assign { .. } => Some("LET"),
5554 StepKind::Set { .. } => Some("MUTATION"),
5555 StepKind::AssignCapture { .. } => Some("LET"),
5556 StepKind::AwaitCapture { .. } => Some("AWAIT"),
5557 StepKind::AsyncBlock { .. } | StepKind::AssignAsync { .. } => Some("ASYNC"),
5558 StepKind::Await { .. } => Some("AWAIT"),
5559 StepKind::Cancel { .. } => Some("CANCEL"),
5560 StepKind::Timeout { .. } => Some("TIMEOUT"),
5561 StepKind::Isolated { .. } => Some("ISOLATED"),
5562 StepKind::IsolatedInheritEnv { .. } => Some("ISOLATED"),
5563 StepKind::RemoteBlock { .. } => Some("REMOTE"),
5564 StepKind::FuncDef { .. } => Some("FUNC"),
5565 StepKind::Call { .. } => None,
5568 StepKind::Return { .. } => Some("RETURN"),
5569 StepKind::While { .. } => Some("WHILE"),
5570 StepKind::Break => Some("BREAK"),
5571 StepKind::Continue => Some("CONTINUE"),
5572 StepKind::TypeAlias { .. } => Some("LET"),
5576 StepKind::RunExec { .. } => None,
5577 StepKind::Workdir(_)
5578 | StepKind::Workspace(_)
5579 | StepKind::Env { .. }
5580 | StepKind::InheritEnv { .. }
5581 | StepKind::Run(_)
5582 | StepKind::Echo(_)
5583 | StepKind::Copy { .. }
5584 | StepKind::Symlink { .. }
5585 | StepKind::Mkdir(_)
5586 | StepKind::Archive { .. }
5587 | StepKind::Unarchive { .. }
5588 | StepKind::Install { .. }
5589 | StepKind::Ls(_)
5590 | StepKind::Read(_)
5591 | StepKind::ReadLine { .. }
5592 | StepKind::Prompt { .. }
5593 | StepKind::Write { .. }
5594 | StepKind::Append { .. }
5595 | StepKind::Remove { .. }
5596 | StepKind::Expand { .. }
5597 | StepKind::AssertEq { .. }
5598 | StepKind::AssertContains { .. }
5599 | StepKind::CopyGit { .. }
5600 | StepKind::Exit(_)
5601 | StepKind::Sleep { .. }
5602 | StepKind::ListAppend { .. } => None,
5603 }
5604 }
5605
5606 let dummies: Vec<StepKind> = vec![
5609 StepKind::WithIo {
5610 bindings: Vec::new(),
5611 cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
5612 "x".to_string(),
5613 false,
5614 ))),
5615 },
5616 StepKind::For {
5617 key_var: None,
5618 key_type: None,
5619 var: "i".to_string(),
5620 var_type: "STRING".to_string(),
5621 in_expr: Expr::Literal(Value::bool(true)),
5622 body: Vec::new(),
5623 },
5624 StepKind::If {
5625 cond: Box::new(Expr::Literal(Value::bool(true))),
5626 then_body: Vec::new(),
5627 else_ifs: Vec::new(),
5628 else_body: None,
5629 },
5630 StepKind::Assign {
5631 var: "v".to_string(),
5632 decl_type: "BOOL".to_string(),
5633 expr: Expr::Literal(Value::bool(true)),
5634 },
5635 StepKind::Set {
5636 var: "v".to_string(),
5637 expr: Expr::Literal(Value::bool(true)),
5638 },
5639 StepKind::AssignCapture {
5640 var: "v".to_string(),
5641 decl_type: "STRING".to_string(),
5642 cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
5643 "x".to_string(),
5644 false,
5645 ))),
5646 },
5647 StepKind::AwaitCapture {
5648 out_var: "o".to_string(),
5649 out_type: "STRING".to_string(),
5650 task_var: "t".to_string(),
5651 },
5652 StepKind::AsyncBlock { body: Vec::new() },
5653 StepKind::AssignAsync {
5654 var: "t".to_string(),
5655 decl_type: "HANDLE".to_string(),
5656 body: Vec::new(),
5657 },
5658 StepKind::Await {
5659 var: "t".to_string(),
5660 },
5661 StepKind::Cancel {
5662 var: "t".to_string(),
5663 },
5664 StepKind::Timeout {
5665 duration: Arg::String("1s".to_string(), false),
5666 body: Vec::new(),
5667 },
5668 StepKind::Isolated { body: Vec::new() },
5669 StepKind::IsolatedInheritEnv { keys: Vec::new() },
5670 StepKind::RemoteBlock {
5671 target: "prod".to_string(),
5672 vars: Vec::new(),
5673 env: Vec::new(),
5674 body: Vec::new(),
5675 },
5676 StepKind::FuncDef {
5677 name: "F".to_string(),
5678 params: Vec::new(),
5679 body: Vec::new(),
5680 docs: None,
5681 },
5682 StepKind::Call {
5683 name: "F".to_string(),
5684 args: Vec::new(),
5685 },
5686 StepKind::Return {
5687 expr: Box::new(Expr::Literal(Value::bool(true))),
5688 },
5689 StepKind::While {
5690 cond: Box::new(Expr::Literal(Value::bool(true))),
5691 body: Vec::new(),
5692 },
5693 StepKind::Break,
5694 StepKind::Continue,
5695 StepKind::TypeAlias {
5696 name: "PERSON".to_string(),
5697 target: "MAP<name: STRING>".to_string(),
5698 },
5699 ];
5700 let registry = all_structural_metadata();
5701 for kind in &dummies {
5702 let Some(name) = metadata_name(kind) else {
5704 continue;
5705 };
5706 assert!(
5707 registry.iter().any(|meta| meta.name == name),
5708 "no structural metadata entry for {}",
5709 name
5710 );
5711 }
5712 }
5713}