1use std::fmt;
16
17use crate::ast::{
18 Arg, ArgPart, Expr, IoBinding, IoStream, PipeTarget, Step, Value, WorkspaceTarget,
19};
20use crate::command::{
21 ArgSpec, ArgType, CommandMeta, Example, FlagSpec, FlagValueType, IoDirection, Stream,
22 split_assignment,
23};
24use crate::constants::{KEYWORD_EXPORT, KEYWORD_IMPORT};
25use crate::error::{ParseError, ParseResult, SpanContext};
26use indoc::indoc;
27
28pub const REMOTE_RESERVED_WORDS: &[&str] = &["SNAPSHOT", "LOCAL", "CACHE", "SYSTEM", "REMOTE"];
38
39pub fn is_valid_remote_target(target: &str) -> bool {
43 if target.is_empty() || target.len() > 64 {
44 return false;
45 }
46 if REMOTE_RESERVED_WORDS.contains(&target) {
47 return false;
48 }
49 let mut chars = target.chars();
50 match chars.next() {
51 Some(first) if first.is_ascii_alphanumeric() => {}
52 _ => return false,
53 }
54 chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
55}
56
57fn join_value(args: Vec<Arg>, cmd_name: &str) -> ParseResult<Arg> {
62 if args.is_empty() {
63 return Err(ParseError::validation(
64 cmd_name,
65 format!("{cmd_name} requires at least one argument"),
66 &SpanContext::line_only(0),
67 ));
68 }
69 if args.len() == 1 {
70 return Ok(args.into_iter().next().unwrap());
71 }
72 if args.iter().all(|a| matches!(a, Arg::String(..))) {
73 return Ok(Arg::String(
74 args.iter()
75 .map(|a| a.as_str())
76 .collect::<Vec<_>>()
77 .join(" "),
78 false,
79 ));
80 }
81 let mut parts = Vec::new();
82 for (index, arg) in args.into_iter().enumerate() {
83 if index > 0 {
84 parts.push(ArgPart::Text(" ".to_string(), false));
85 }
86 match arg {
87 Arg::String(text, quoted) => parts.push(ArgPart::Text(text, quoted)),
88 Arg::Expr(expr) => parts.push(ArgPart::Expr(expr)),
89 Arg::Parts(inner) => parts.extend(inner),
90 }
91 }
92 Ok(Arg::Parts(parts))
93}
94
95pub fn lower_env_assignment(args: Vec<Arg>) -> ParseResult<StepKind> {
99 let arg = args.into_iter().next().ok_or_else(|| {
100 ParseError::validation(
101 "ENV",
102 "ENV requires KEY=value".to_string(),
103 &SpanContext::line_only(0),
104 )
105 })?;
106 let Some((key, value)) = split_assignment(arg.as_str())
107 .map_err(|e| ParseError::validation("ENV", e.to_string(), &SpanContext::line_only(0)))?
108 else {
109 return Err(ParseError::validation(
110 "ENV",
111 "ENV requires KEY=value format".to_string(),
112 &SpanContext::line_only(0),
113 ));
114 };
115 Ok(StepKind::Env { key, value })
116}
117
118pub(crate) fn canonical_assignment_arg(key: &str, value: &Arg) -> Arg {
123 Arg::String(format!("{key}={}", value.render()), false)
124}
125
126fn fmt_assert_target(target: &AssertTarget) -> String {
129 match target {
130 AssertTarget::Value(arg) => fmt_value(arg, quote_msg),
131 _ => target.render(),
132 }
133}
134
135fn fmt_value(arg: &Arg, quote: fn(&str) -> String) -> String {
140 match arg {
141 Arg::Expr(_) => arg.render(),
142 Arg::String(text, _) => quote(text),
143 Arg::Parts(_) => {
144 let rendered = arg.render();
145 if rendered.contains(';')
146 || rendered.contains('}')
147 || rendered.contains('\n')
148 || rendered.contains('\r')
149 {
150 quote(&rendered)
151 } else {
152 rendered
153 }
154 }
155 }
156}
157
158fn quote_dsl_string(s: &str) -> String {
159 format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
167}
168
169fn quote_arg(s: &str) -> String {
170 let is_safe = s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
171 && !s.starts_with(|c: char| c.is_ascii_digit() || c == '-' || c == '/' || c == '.')
172 && !crate::Command::is_statement_keyword(s);
173 if is_safe && !s.is_empty() {
174 s.to_string()
175 } else {
176 quote_dsl_string(s)
177 }
178}
179
180fn quote_msg(s: &str) -> String {
181 let safe = s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
182 && !s.starts_with(|c: char| c.is_ascii_digit())
183 && !crate::Command::is_statement_keyword(s);
184 if safe && !s.is_empty() {
185 s.to_string()
186 } else {
187 quote_dsl_string(s)
188 }
189}
190
191fn quote_run(s: &str) -> String {
192 if s.is_empty() || s.chars().any(|c| c == ';' || c == '\n') || s.contains("//") {
193 return quote_dsl_string(s);
194 }
195 s.split(' ')
196 .map(|w| {
197 if w.starts_with(|c: char| c.is_ascii_digit())
198 || w.starts_with(['/', '.', '-', ':', '='])
199 {
200 quote_dsl_string(w)
201 } else {
202 w.to_string()
203 }
204 })
205 .collect::<Vec<_>>()
206 .join(" ")
207}
208
209fn fmt_exec_arg(arg: &Arg) -> String {
215 match arg {
216 Arg::String(text, _) => quote_dsl_string(text),
217 Arg::Expr(_) => arg.render(),
218 Arg::Parts(_) => {
219 let rendered = arg.render();
220 if rendered.contains(';')
221 || rendered.contains('}')
222 || rendered.contains('\n')
223 || rendered.contains('\r')
224 {
225 quote_dsl_string(&rendered)
226 } else {
227 rendered
228 }
229 }
230 }
231}
232
233fn fmt_raw_arg(arg: &Arg) -> String {
237 match arg {
238 Arg::String(s, true) => quote_dsl_string(s),
239 _ => arg.render(),
240 }
241}
242
243fn fmt_io(b: &IoBinding) -> String {
244 let s = match b.stream {
245 IoStream::Stdin => "stdin".to_string(),
246 IoStream::Stdout => "stdout".to_string(),
247 IoStream::Stderr => "stderr".to_string(),
248 IoStream::Tty => "tty".to_string(),
249 IoStream::Rows(rows) => format!("rows={rows}"),
250 IoStream::Cols(cols) => format!("cols={cols}"),
251 };
252 match &b.pipe {
253 Some(PipeTarget::Var(v)) => format!("{}=${}", s, v),
254 None => s,
255 }
256}
257
258pub(crate) fn is_known_command(name: &str) -> bool {
265 if name == "ELSE" {
266 return true;
267 }
268 all_metadata().iter().any(|meta| meta.name == name)
269}
270
271pub(crate) fn invalid_syntax_error(name: &str, raw_args: &[Arg]) -> ParseError {
272 let received = raw_args
273 .iter()
274 .map(Arg::render)
275 .collect::<Vec<_>>()
276 .join(" ");
277 let got = if received.is_empty() {
278 "nothing".to_string()
279 } else {
280 format!("`{received}`")
281 };
282 let found = if received.is_empty() {
283 None
284 } else {
285 Some(received.clone())
286 };
287 let expected = all_metadata()
288 .iter()
289 .find(|meta| meta.name == name)
290 .map(|meta| vec![meta.syntax.to_string()])
291 .unwrap_or_default();
292 let ctx = SpanContext::line_only(0);
293 match structural_hint(name, &received) {
294 Some(hint) => ParseError::invalid_syntax(
295 name,
296 format!("invalid syntax for command {name}: {hint}"),
297 found,
298 expected,
299 Some(hint),
300 &ctx,
301 ),
302 None => ParseError::invalid_syntax(
303 name,
304 format!("invalid syntax for command {name}: got {got}."),
305 found,
306 expected,
307 None,
308 &ctx,
309 ),
310 }
311}
312
313fn unknown_command_error(name: &str, raw_args: &[Arg]) -> ParseError {
314 let received = raw_args
315 .iter()
316 .map(Arg::render)
317 .collect::<Vec<_>>()
318 .join(" ");
319 let hint = structural_hint(name, &received).or_else(|| case_hint(name));
320 let ctx = SpanContext::line_only(0);
321 match hint {
322 Some(hint) => ParseError::unknown_command(
323 name,
324 format!("unknown command: {name}\n{hint}"),
325 Some(hint),
326 &ctx,
327 ),
328 None => ParseError::unknown_command(name, format!("unknown command: {name}"), None, &ctx),
329 }
330}
331
332pub(crate) fn classify(name: &str, raw_args: &[Arg]) -> ParseError {
338 if is_known_command(name) {
339 invalid_syntax_error(name, raw_args)
340 } else {
341 unknown_command_error(name, raw_args)
342 }
343}
344
345fn structural_hint(name: &str, received: &str) -> Option<String> {
346 let got = if received.is_empty() {
347 "nothing".to_string()
348 } else {
349 format!("`{received}`")
350 };
351 match name {
352 "WITH_IO" => Some(with_io_hint(&got, received)),
353 "AWAIT" => Some(format!(
354 "AWAIT waits for a background task variable, e.g. `LET $t: HANDLE = ASYNC ECHO hi` then `AWAIT $t`; got {got}."
355 )),
356 "CANCEL" => Some(format!(
357 "CANCEL stops a background task variable, e.g. `CANCEL $t` (from `LET $t: HANDLE = ASYNC ...`); got {got}."
358 )),
359 "ASYNC" => Some(format!(
360 "ASYNC runs a command in the background, e.g. `ASYNC RUN ...`, `ASYNC {{ ... }}`, or `LET $t: HANDLE = ASYNC ...`; got {got}."
361 )),
362 "FOR" => Some(format!(
363 "FOR loops need `FOR $item: TYPE IN <expr> {{ ... }}` (or `FOR $key: STRING, $value: TYPE IN <expr> {{ ... }}`); got {got}."
364 )),
365 "IF" => Some(format!(
366 "IF needs a condition and a block, e.g. `IF true {{ ECHO yes }}`; got {got}."
367 )),
368 "ELSE" => Some(format!(
369 "ELSE must directly follow an `IF ... {{ ... }}` block, e.g. `IF true {{ ECHO yes }} ELSE {{ ECHO no }}`; got {got}."
370 )),
371 "LET" => Some(format!(
372 "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}."
373 )),
374 "SET" => Some(
375 "`SET` is not a keyword; mutate a declared variable with `$var = <expr>`, e.g. `$count = 2`.".to_string(),
376 ),
377 "TIMEOUT" => Some(format!(
378 "TIMEOUT needs a duration and a command or block, e.g. `TIMEOUT 30s RUN ...`; got {got}."
379 )),
380 "REMOTE" => Some(format!(
381 "REMOTE needs a target and a braced block, e.g. `REMOTE prod [$version, env:DEPLOY_ENV] {{ ... }}`; got {got}."
382 )),
383 "FUNC" => Some(format!(
384 "FUNC defines a function, e.g. `FUNC GREET($name: STRING) {{ RETURN $name }}`; got {got}."
385 )),
386 "RETURN" => Some(format!(
387 "RETURN ends the nearest function, ASYNC task, or inline LET block with a value, e.g. `RETURN $x`; got {got}."
388 )),
389 "WHILE" => Some(format!(
390 "WHILE needs a Bool condition and a block, e.g. `WHILE !$done {{ ... }}`; got {got}."
391 )),
392 "BREAK" => Some(
393 "`BREAK` exits the innermost enclosing FOR/WHILE loop; it must appear inside a loop.".to_string(),
394 ),
395 "CONTINUE" => Some(
396 "`CONTINUE` skips to the next iteration of the innermost enclosing FOR/WHILE loop; it must appear inside a loop.".to_string(),
397 ),
398 "INHERIT_ENV" => Some(format!(
399 "INHERIT_ENV takes a key list, e.g. `INHERIT_ENV [HOME, PATH]`; got {got}."
400 )),
401 name if name == KEYWORD_IMPORT => Some(format!(
402 "IMPORT brings module functions into bare-call scope, e.g. `IMPORT [STD]` or `IMPORT [STD, MOCK]`; got {got}."
403 )),
404 name if name == KEYWORD_EXPORT => Some(
405 "EXPORT marks script FUNCs and qualified host functions as tools, e.g. `EXPORT FOO`, `EXPORT [FOO, STD::INT]`."
406 .to_string(),
407 ),
408 _ => None,
409 }
410}
411
412fn with_io_hint(got: &str, received: &str) -> String {
416 const SYNTAX: &str =
417 "WITH_IO needs `WITH_IO [bindings] <command>` or `WITH_IO [bindings] { <commands> }`";
418 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]`)";
419 if let Some(after_open) = received.strip_prefix('[') {
420 match after_open.split_once(']') {
421 None => {
422 return format!("{SYNTAX}: missing closing `]` in the binding list; got {got}.");
423 }
424 Some((bindings, _)) => {
425 for part in bindings.split(',') {
426 let part = part.trim();
427 if part.is_empty() {
428 continue;
429 }
430 let (stream, binding) = match part.split_once('=') {
431 Some((stream, binding)) => (stream.trim(), Some(binding.trim())),
432 None => (part, None),
433 };
434 if matches!(stream, "rows" | "cols") {
435 let valid = binding.is_some_and(|value| {
436 value
437 .parse::<u64>()
438 .is_ok_and(|dim| (1..=u64::from(u16::MAX)).contains(&dim))
439 });
440 if !valid {
441 return format!(
442 "{SYNTAX}: invalid geometry `{part}`; `rows`/`cols` need a positive integer 1-65535 (e.g. `rows=40`) and require `tty`; got {got}."
443 );
444 }
445 continue;
446 }
447 if stream == "tty" {
448 if binding.is_some() {
449 return format!(
450 "{SYNTAX}: invalid binding `{part}`; `tty` is a bare flag (geometry rides `rows`/`cols`, e.g. `[tty, rows=40]`); got {got}."
451 );
452 }
453 continue;
454 }
455 if !matches!(stream, "stdin" | "stdout" | "stderr") {
456 return format!(
457 "{SYNTAX}: invalid stream `{stream}`; expected `stdin`, `stdout`, `stderr`, or `tty`; got {got}."
458 );
459 }
460 let valid = match binding {
461 None => true,
462 Some(value) => value.strip_prefix('$').is_some_and(|var| {
463 !var.trim().is_empty()
464 && var.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
465 }),
466 };
467 if !valid {
468 return format!(
469 "{SYNTAX}: invalid binding `{part}`; {BINDINGS}; got {got}."
470 );
471 }
472 }
473 }
474 }
475 }
476 format!("{SYNTAX}; got {got}. {BINDINGS}.")
477}
478
479fn case_hint(name: &str) -> Option<String> {
481 let upper = name.to_ascii_uppercase();
482 if upper != name
483 && all_metadata()
484 .iter()
485 .any(|meta| meta.name == upper.as_str())
486 {
487 return Some(format!("did you mean `{upper}`? commands are uppercase."));
488 }
489 None
490}
491
492macro_rules! declare_commands {
493 (
494 structural [
495 $( $sname:ident $( { $( $sfname:ident : $sftype:ty ),* $(,)? } )? ),* $(,)?
496 ]
497
498 $(
499 $cmd_ident:ident => [
500 name: $name:expr,
501 variant: $vname:ident $( { $( $vfname:ident : $vftype:ty ),* $(,)? } )? $( ( $( $ttuple:ty ),* $(,)? ) )?,
502 syntax: $syntax:expr,
503 summary: $summary:expr,
504 description: $desc:expr,
505 args: $args:expr,
506 flags: $flags:expr,
507 default_output: $out:expr,
508 examples: $examples:expr,
509 lower: $lower:expr,
510 ]
511 ),* $(,)?
512 ) => {
513 #[derive(Debug, Clone, PartialEq)]
514 pub enum StepKind {
515 $( $vname $( { $( $vfname : $vftype ),* } )? $( ( $( $ttuple ),* ) )?, )*
516 $( $sname $( { $( $sfname : $sftype ),* } )?, )*
517 }
518
519 pub fn lower_command(name: &str, raw_args: Vec<Arg>) -> ParseResult<StepKind> {
520 match name {
521 $(
522 s if s == $name => {
523 let meta = CommandMeta {
524 name: $name, syntax: $syntax, summary: $summary,
525 description: $desc, args: $args, flags: $flags,
526 default_output: $out, examples: $examples,
527 };
528 let (flags, positional) = crate::strip_flags(raw_args, &meta)?;
529 crate::command::validate_positionals_against_meta(
530 s,
531 &meta.args,
532 &positional,
533 )?;
534 let lower_fn: fn(Vec<(String, Arg)>, Vec<Arg>) -> ParseResult<StepKind> = $lower;
535 lower_fn(flags, positional)
536 }
537 )*
538 _ => {
539 Err(classify(name, &raw_args))
540 }
541 }
542 }
543
544 pub fn all_metadata() -> Vec<CommandMeta> {
545 let mut out = vec![
546 $( CommandMeta {
547 name: $name, syntax: $syntax, summary: $summary,
548 description: $desc, args: $args, flags: $flags,
549 default_output: $out, examples: $examples,
550 }, )*
551 ];
552 out.extend(all_structural_metadata());
556 out
557 }
558 };
559}
560
561impl StepKind {
562 pub fn walk_exprs(&self, f: &mut impl FnMut(&Expr)) {
569 fn walk_arg(arg: &Arg, f: &mut impl FnMut(&Expr)) {
570 match arg {
571 Arg::Expr(expr) => f(expr),
572 Arg::Parts(parts) => {
573 for part in parts {
574 if let ArgPart::Expr(expr) = part {
575 f(expr);
576 }
577 }
578 }
579 Arg::String(..) => {}
580 }
581 }
582 fn walk_opt(arg: &Option<Arg>, f: &mut impl FnMut(&Expr)) {
583 if let Some(arg) = arg {
584 walk_arg(arg, f);
585 }
586 }
587 fn walk_target(target: &AssertTarget, f: &mut impl FnMut(&Expr)) {
588 if let AssertTarget::Value(arg) = target {
589 walk_arg(arg, f);
590 }
591 }
592 match self {
593 StepKind::Assign { expr, .. } | StepKind::Set { expr, .. } => f(expr),
594 StepKind::Return { expr } => f(expr),
595 StepKind::Call { args, .. } => {
596 for arg in args {
597 f(arg);
598 }
599 }
600 StepKind::For { in_expr, .. } => f(in_expr),
601 StepKind::If { cond, else_ifs, .. } => {
602 f(cond);
603 for (cond, _) in else_ifs {
604 f(cond);
605 }
606 }
607 StepKind::While { cond, .. } => f(cond),
608 StepKind::Timeout { duration, .. } | StepKind::Sleep { duration } => {
609 walk_arg(duration, f);
610 }
611 StepKind::Workdir(arg)
612 | StepKind::Echo(arg)
613 | StepKind::Run(arg)
614 | StepKind::Mkdir(arg)
615 | StepKind::HashSha256 { path: arg }
616 | StepKind::Exit(arg) => walk_arg(arg, f),
617 StepKind::Env { value, .. } => walk_arg(value, f),
618 StepKind::Copy { from, to, .. }
619 | StepKind::Symlink { from, to, .. }
620 | StepKind::Archive {
621 src: from, dst: to, ..
622 }
623 | StepKind::Install { from, to } => {
624 walk_arg(from, f);
625 walk_arg(to, f);
626 }
627 StepKind::Unarchive {
628 src,
629 dst,
630 max_bytes,
631 } => {
632 walk_arg(src, f);
633 walk_arg(dst, f);
634 walk_opt(max_bytes, f);
635 }
636 StepKind::CopyGit { rev, from, to, .. } => {
637 walk_arg(rev, f);
638 walk_arg(from, f);
639 walk_arg(to, f);
640 }
641 StepKind::Ls(arg) | StepKind::Read(arg) => walk_opt(arg, f),
642 StepKind::Remove { path, .. } => walk_arg(path, f),
643 StepKind::Prompt {
644 message, default, ..
645 } => {
646 walk_arg(message, f);
647 walk_opt(default, f);
648 }
649 StepKind::Write { path, contents } | StepKind::Append { path, contents } => {
650 walk_arg(path, f);
651 walk_opt(contents, f);
652 }
653 StepKind::Expand { path, overrides } => {
654 walk_opt(path, f);
655 for (_, value) in overrides {
656 walk_arg(value, f);
657 }
658 }
659 StepKind::AssertEq {
660 actual, expected, ..
661 } => {
662 walk_target(actual, f);
663 walk_opt(expected, f);
664 }
665 StepKind::AssertContains { haystack, needle } => {
666 walk_target(haystack, f);
667 walk_arg(needle, f);
668 }
669 StepKind::ListAppend { item, .. } => walk_arg(item, f),
670 StepKind::RunExec { argv } => {
671 for arg in argv {
672 walk_arg(arg, f);
673 }
674 }
675 StepKind::WithIo { .. }
676 | StepKind::WithIoBlock { .. }
677 | StepKind::TypeAlias { .. }
678 | StepKind::Workspace(_)
679 | StepKind::InheritEnv { .. }
680 | StepKind::Isolated { .. }
681 | StepKind::IsolatedInheritEnv { .. }
682 | StepKind::Cwd
683 | StepKind::ReadLine { .. }
684 | StepKind::AssignCapture { .. }
685 | StepKind::AwaitCapture { .. }
686 | StepKind::AsyncBlock { .. }
687 | StepKind::AssignAsync { .. }
688 | StepKind::Await { .. }
689 | StepKind::Cancel { .. }
690 | StepKind::RemoteBlock { .. }
691 | StepKind::FuncDef { .. }
692 | StepKind::Break
693 | StepKind::Continue => {}
694 }
695 }
696
697 pub fn walk_child_kinds(&self, f: &mut impl FnMut(&StepKind)) {
701 fn walk_body(body: &[Step], f: &mut impl FnMut(&StepKind)) {
702 for step in body {
703 f(&step.kind);
704 }
705 }
706 match self {
707 StepKind::WithIo { cmd, .. } => f(cmd),
708 StepKind::AssignCapture { cmd, .. } => f(cmd),
709 StepKind::For { body, .. }
710 | StepKind::While { body, .. }
711 | StepKind::FuncDef { body, .. }
712 | StepKind::Timeout { body, .. }
713 | StepKind::Isolated { body }
714 | StepKind::AssignAsync { body, .. }
715 | StepKind::AsyncBlock { body }
716 | StepKind::RemoteBlock { body, .. } => walk_body(body, f),
717 StepKind::If {
718 then_body,
719 else_ifs,
720 else_body,
721 ..
722 } => {
723 walk_body(then_body, f);
724 for (_, body) in else_ifs {
725 walk_body(body, f);
726 }
727 if let Some(body) = else_body {
728 walk_body(body, f);
729 }
730 }
731 StepKind::InheritEnv { .. }
732 | StepKind::IsolatedInheritEnv { .. }
733 | StepKind::TypeAlias { .. }
734 | StepKind::Workdir(_)
735 | StepKind::Workspace(_)
736 | StepKind::Env { .. }
737 | StepKind::Echo(_)
738 | StepKind::Run(_)
739 | StepKind::RunExec { .. }
740 | StepKind::Copy { .. }
741 | StepKind::CopyGit { .. }
742 | StepKind::Symlink { .. }
743 | StepKind::Archive { .. }
744 | StepKind::Unarchive { .. }
745 | StepKind::Install { .. }
746 | StepKind::Mkdir(_)
747 | StepKind::Ls(_)
748 | StepKind::Cwd
749 | StepKind::Read(_)
750 | StepKind::ReadLine { .. }
751 | StepKind::Prompt { .. }
752 | StepKind::Write { .. }
753 | StepKind::Append { .. }
754 | StepKind::Remove { .. }
755 | StepKind::Expand { .. }
756 | StepKind::AssertEq { .. }
757 | StepKind::AssertContains { .. }
758 | StepKind::HashSha256 { .. }
759 | StepKind::Exit(_)
760 | StepKind::WithIoBlock { .. }
761 | StepKind::Assign { .. }
762 | StepKind::Set { .. }
763 | StepKind::AwaitCapture { .. }
764 | StepKind::Await { .. }
765 | StepKind::Cancel { .. }
766 | StepKind::Sleep { .. }
767 | StepKind::ListAppend { .. }
768 | StepKind::Call { .. }
769 | StepKind::Return { .. }
770 | StepKind::Break
771 | StepKind::Continue => {}
772 }
773 }
774
775 pub fn walk_step_exprs(&self, f: &mut impl FnMut(&Expr)) {
780 self.walk_exprs(&mut |expr| expr.walk(f));
781 self.walk_child_kinds(&mut |kind| kind.walk_step_exprs(f));
782 }
783}
784
785#[derive(Debug, Clone, PartialEq)]
794pub enum AssertTarget {
795 Value(Arg),
796 Stdout,
797 Stderr,
798}
799
800impl AssertTarget {
801 pub fn render(&self) -> String {
802 match self {
803 AssertTarget::Value(arg) => arg.render(),
804 AssertTarget::Stdout => "stdout".to_string(),
805 AssertTarget::Stderr => "stderr".to_string(),
806 }
807 }
808}
809
810fn lower_assert_target(arg: Arg) -> ParseResult<AssertTarget> {
819 match arg {
820 Arg::Expr(_) => Ok(AssertTarget::Value(arg)),
821 Arg::String(text, quoted) if !quoted => match text.as_str() {
822 "stdout" => Ok(AssertTarget::Stdout),
823 "stderr" => Ok(AssertTarget::Stderr),
824 _ => Ok(AssertTarget::Value(lower_assert_operand(Arg::String(
825 text, false,
826 )))),
827 },
828 other => Ok(AssertTarget::Value(lower_assert_operand(other))),
829 }
830}
831
832fn lower_assert_operand(arg: Arg) -> Arg {
841 match arg {
842 Arg::String(text, false) => {
843 let clean = crate::command::strip_digit_separators(&text);
848 if let Ok(i) = clean.parse::<i64>() {
849 Arg::Expr(Expr::Literal(Value::int(i)))
850 } else if clean.contains('.') && clean.parse::<f64>().is_ok() {
851 Arg::Expr(Expr::Literal(Value::float(
852 clean.parse::<f64>().unwrap_or(f64::NAN),
853 )))
854 } else if text == "true" {
855 Arg::Expr(Expr::Literal(Value::bool(true)))
856 } else if text == "false" {
857 Arg::Expr(Expr::Literal(Value::bool(false)))
858 } else {
859 Arg::String(text, false)
860 }
861 }
862 other => other,
863 }
864}
865
866declare_commands! {
867 structural [
868 WithIo { bindings: Vec<IoBinding>, cmd: Box<StepKind> },
869 WithIoBlock { bindings: Vec<IoBinding> },
870 TypeAlias { name: String, target: String },
871 For { key_var: Option<String>, key_type: Option<String>, var: String, var_type: String, in_expr: Expr, body: Vec<Step> },
872 If { cond: Box<Expr>, then_body: Vec<Step>, else_ifs: Vec<(Box<Expr>, Vec<Step>)>, else_body: Option<Vec<Step>> },
873 Assign { var: String, decl_type: String, expr: Expr },
874 Set { var: String, expr: Expr },
875 AssignCapture { var: String, decl_type: String, cmd: Box<StepKind> },
876 AwaitCapture { out_var: String, out_type: String, task_var: String },
877 AsyncBlock { body: Vec<Step> },
878 AssignAsync { var: String, decl_type: String, body: Vec<Step> },
879 Await { var: String },
880 Cancel { var: String },
881 Timeout { duration: Arg, body: Vec<Step> },
882 Isolated { body: Vec<Step> },
883 IsolatedInheritEnv { keys: Vec<String> },
884 RemoteBlock { target: String, vars: Vec<String>, env: Vec<String>, body: Vec<Step> },
885 RunExec { argv: Vec<Arg> },
886 FuncDef { name: String, params: Vec<(String, String)>, body: Vec<Step> },
887 Call { name: String, args: Vec<Expr> },
888 Return { expr: Box<Expr> },
889 While { cond: Box<Expr>, body: Vec<Step> },
890 Break,
891 Continue,
892 ]
893
894 Workdir => [
895 name: "WORKDIR",
896 variant: Workdir(Arg),
897 syntax: "WORKDIR <path>",
898 summary: "Change the working directory.",
899 description: indoc! {r#"
900 Sets the current working directory.
901
902 Relative paths resolve against the current directory; `/` resets to
903 the workspace root. Paths cannot escape the workspace.
904 "#},
905 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Directory to change to", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
906 flags: &[],
907 default_output: None,
908 examples: &[ Example { name: "change working directory", fence_meta: None, code: indoc! {r#"
909 # Later relative paths resolve under the new directory.
910 WORKDIR project/src
911 WRITE generated.txt generated-under-workdir
912
913 LET $body: STRING = READ generated.txt
914 ASSERT_EQ $body "generated-under-workdir"
915 "#} }, Example { name: "workdir in a scoped block", fence_meta: None, code: indoc! {r#"
916 # The block reverts to the starting directory on exit.
917 LET $outside: STRING = CWD
918 MKDIR project
919
920 [bool:true] {
921 WORKDIR project
922 WRITE inner.txt inner
923 }
924
925 LET $back: STRING = CWD
926 ASSERT_EQ $back $outside
927 LET $body: STRING = READ project/inner.txt
928 ASSERT_EQ $body "inner"
929 "#} } ],
930 lower: |_flags, args| {
931 let path = args.into_iter().next().ok_or_else(|| ParseError::validation("WORKDIR", "WORKDIR requires a path".to_string(), &SpanContext::line_only(0)))?;
932 Ok(StepKind::Workdir(path))
933 },
934 ],
935
936 Workspace => [
937 name: "WORKSPACE",
938 variant: Workspace(WorkspaceTarget),
939 syntax: "WORKSPACE (SNAPSHOT|LOCAL|CACHE|SYSTEM) [--local]",
940 summary: "Switch workspace roots.",
941 description: indoc! {r#"
942 Switches the workspace root. The selection reverts at scope
943 exit like `WORKDIR`.
944
945 - `SNAPSHOT`: the materialized build snapshot (the default).
946 One session-shared directory: every selection resolves to
947 it, in any block.
948 - `LOCAL`: the local workspace directory.
949 - `CACHE`: a persistent per-project directory shared across
950 runs, never evicted. It lives under the OS user cache
951 (`OXDOCK_CACHE_DIR` pins an exact directory);
952 `WORKSPACE CACHE --local` keeps it in
953 `<project>/.cache/workspace` instead.
954 - `SYSTEM`: full filesystem access. Scripts using it are not
955 hermetic.
956 "#},
957 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 } ],
958 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)" } ],
959 default_output: None,
960 examples: &[ Example { name: "switch roots", fence_meta: None, code: indoc! {r#"
961 IMPORT [STD]
962 WORKSPACE LOCAL
963
964 LET $t: STRING = PATH_TYPE(".")
965 ASSERT_EQ $t "dir"
966 "#} }, Example { name: "workspace cache in a scoped block", fence_meta: None, code: indoc! {r#"
967 [bool:true] {
968 WORKSPACE CACHE
969 WRITE cached.txt cached-content
970 }
971
972 COPY --from-workspace CACHE cached.txt restored.txt
973 LET $body: STRING = READ restored.txt
974 ASSERT_EQ $body "cached-content"
975 "#} } ],
976 lower: |flags, args| {
977 let local = flags.iter().any(|(k, _)| k == "local");
978 let target = args.into_iter().next().ok_or_else(|| ParseError::validation("WORKSPACE", "WORKSPACE requires a target".to_string(), &SpanContext::line_only(0)))?;
979 match target.as_str() {
980 "SNAPSHOT" | "LOCAL" | "SYSTEM" if local => Err(ParseError::validation("WORKSPACE", "WORKSPACE --local requires CACHE".to_string(), &SpanContext::line_only(0))),
981 "SNAPSHOT" => Ok(StepKind::Workspace(WorkspaceTarget::Snapshot)),
982 "LOCAL" => Ok(StepKind::Workspace(WorkspaceTarget::Local)),
983 "CACHE" => Ok(StepKind::Workspace(WorkspaceTarget::Cache { local })),
984 "SYSTEM" => Ok(StepKind::Workspace(WorkspaceTarget::System)),
985 other => Err(ParseError::validation("WORKSPACE", format!("unknown workspace target: {other}"), &SpanContext::line_only(0))),
986 }
987 },
988 ],
989
990 Env => [
991 name: "ENV",
992 variant: Env { key: String, value: Arg },
993 syntax: "ENV KEY=value",
994 summary: "Set an environment variable.",
995 description: indoc! {r#"
996 Inserts or updates an env var.
997
998 The value uses the unified string-value rules shared by every command:
999 `"..."` or `'...'` quotes keep exact bytes (spaces, tabs), a lone `$var`
1000 evaluates that variable, `{{ ... }}` placeholders interpolate, unquoted
1001 words join with single spaces, and the first `=` splits key from value
1002 (`KEY=a=b` stores `a=b`).
1003
1004 A `$var` inside larger text stays literal — write `{{ $var }}` to
1005 interpolate there.
1006 "#},
1007 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 } ],
1008 flags: &[],
1009 default_output: None,
1010 examples: &[
1011 Example { name: "set env", fence_meta: None, code: indoc! {r#"
1012 ENV APP_MODE=production
1013 LET $mode: STRING = env:APP_MODE
1014 ASSERT_EQ $mode "production"
1015 "#} },
1016 Example { name: "quoted value with spaces", fence_meta: None, code: indoc! {r#"
1017 # Quotes keep the space: SET_FORTH stores `outer scope`.
1018 ENV SET_FORTH="outer scope"
1019 WRITE out.txt "{{ env:SET_FORTH }}"
1020
1021 LET $body: STRING = READ out.txt
1022 ASSERT_EQ $body "outer scope"
1023 "#} },
1024 Example { name: "variable value", fence_meta: None, code: indoc! {r#"
1025 # A lone $var evaluates, like ECHO $var.
1026 LET $who: STRING = "Alice"
1027 ENV GREETING=$who
1028 WRITE out.txt "{{ env:GREETING }}"
1029
1030 LET $body: STRING = READ out.txt
1031 ASSERT_EQ $body "Alice"
1032 "#} },
1033 Example { name: "all value forms agree", fence_meta: None, code: indoc! {r#"
1034 # A bare variable, a quoted literal, and a template all
1035 # store plain strings through the same value rules.
1036 LET $x: STRING = "Ada"
1037 ENV A=$x
1038 ENV B="hello world"
1039 ENV C="{{ $x }} concatenated"
1040 WRITE check.txt "{{ env:A }}|{{ env:B }}|{{ env:C }}"
1041
1042 LET $body: STRING = READ check.txt
1043 ASSERT_EQ $body "Ada|hello world|Ada concatenated"
1044 "#} },
1045 Example { name: "scoped env reverts", fence_meta: None, code: indoc! {r#"
1046 # ENV inside a braced block reverts when the block exits
1047 ENV MODE=production
1048
1049 [bool:true] {
1050 ENV MODE=staging
1051 WRITE inner.txt "{{ env:MODE }}"
1052 }
1053
1054 WRITE outer.txt "{{ env:MODE }}"
1055
1056 LET $inner_body: STRING = READ inner.txt
1057 ASSERT_EQ $inner_body "staging"
1058
1059 LET $outer_body: STRING = READ outer.txt
1060 ASSERT_EQ $outer_body "production"
1061 "#} },
1062 Example { name: "shell reads env per platform", fence_meta: None, code: indoc! {r#"
1063 # A shell command reads its own environment, with
1064 # per-platform spelling: quoted "$VAR" passes the parser
1065 # through untouched on Unix ...
1066 ENV PROXY_PORT=23791
1067
1068 [family:unix] LET $o: STRING = RUN echo serving on "$PROXY_PORT"
1069
1070 # ... while cmd expands %VAR% on Windows.
1071 [family:windows] LET $o: STRING = RUN echo serving on %PROXY_PORT%
1072
1073 ASSERT_CONTAINS $o "23791"
1074 "#} },
1075 ],
1076 lower: |_flags, args| lower_env_assignment(args),
1077 ],
1078
1079 InheritEnv => [
1080 name: "INHERIT_ENV",
1081 variant: InheritEnv { keys: Vec<String> },
1082 syntax: "INHERIT_ENV [<key>, ...]",
1083 summary: "Inherit env vars from host.",
1084 description: indoc! {r#"
1085 Declares which host environment variables to inherit into the script.
1086
1087 Must appear before any other commands. Several directives may
1088 appear so platform-specific names ride explicit guards
1089 (`[family:windows] INHERIT_ENV [USERPROFILE]`); each guarded
1090 line runs only when its guard passes.
1091
1092 Sandbox defaults need no declaration: loader bindings,
1093 terminal defaults, the host lookup path, and the user's
1094 profile locations seed automatically. See OxDock
1095 Environment Variable Contracts for the exact list, which grows with the
1096 engine.
1097
1098 Secrets and tool config stay opt-in here: a token or a
1099 `CARGO_HOME` override arrives only through this directive.
1100 "#},
1101 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 } ],
1102 flags: &[],
1103 default_output: None,
1104 examples: &[ Example { name: "inherit env", fence_meta: None, code: indoc! {r#"
1105 [family:unix] INHERIT_ENV [HOME]
1106 LET $path: STRING = env:PATH
1107 [family:unix] ASSERT_CONTAINS $path ":"
1108 [family:windows] ASSERT_CONTAINS $path ";"
1109 "#} } ],
1110 lower: |_flags, args| {
1111 let keys = args.into_iter().map(|a| a.as_str().to_string()).collect();
1112 Ok(StepKind::InheritEnv { keys })
1113 },
1114 ],
1115
1116 Echo => [
1117 name: "ECHO",
1118 variant: Echo(Arg),
1119 syntax: "ECHO <message>",
1120 summary: "Print to stdout.",
1121 description: "Outputs message to stdout.",
1122 args: &[ ArgSpec { name: "message", arg_type: ArgType::Rest(&ArgType::String), description: "Text", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1123 flags: &[],
1124 default_output: Some(Stream::Stdout),
1125 examples: &[
1126 Example { name: "echo", fence_meta: None, code: indoc! {r#"
1127 ECHO build-complete
1128 ASSERT_CONTAINS stdout "build-complete"
1129 "#} },
1130 Example { name: "variables", fence_meta: None, code: indoc! {r#"
1131 # {{ }} interpolates inside text; a lone $var evaluates on its own.
1132 LET $x: STRING = "World"
1133 ECHO "braced:{{ $x }}"
1134 ECHO $x
1135 ASSERT_EQ stdout "braced:World\nWorld\n"
1136 "#} },
1137 Example { name: "interpolation", fence_meta: None, code: indoc! {r#"
1138 # `{{ env:KEY }}` reads the script environment; a bare name
1139 # resolves a DSL variable instead. Unknown keys expand to
1140 # empty with no host fallback.
1141 ENV USER=OxDock
1142 LET $WHO: STRING = "Ada"
1143 ECHO "Hello {{ env:USER }}! Hi {{ WHO }}!{{ env:OXDOCK_DOC_NO_SUCH_KEY }}"
1144 ASSERT_CONTAINS stdout "Hello OxDock! Hi Ada!"
1145 "#} },
1146 ],
1147 lower: |_flags, args| Ok(StepKind::Echo(join_value(args, "ECHO")?)),
1148 ],
1149
1150 Run => [
1151 name: "RUN",
1152 variant: Run(Arg),
1153 syntax: "RUN <command...> | RUN [\"exe\", \"arg\", ...]",
1154 summary: "Execute shell command or direct executable.",
1155 description: indoc! {r#"
1156 Shell form (`RUN <command...>`) runs the joined command string in the
1157 batch shell (`sh -c` / `cmd /C`). Never the operator's login
1158 shell: login shells re-pollute scrubbed children from system
1159 profiles and break script portability, so step execution is
1160 pinned to POSIX `sh` (interactive `oxdock --shell` still uses
1161 `$SHELL`).
1162
1163 Exec form (`RUN ["exe", "arg", ...]`) spawns the executable directly
1164 with no shell, so there is no shell expansion, globbing, redirection,
1165 or pipes; use it for portable commands.
1166
1167 Guards and wrappers (`ASYNC`, `TIMEOUT`, `WITH_IO`, `LET`) apply to
1168 both forms.
1169 "#},
1170 args: &[ ArgSpec { name: "command", arg_type: ArgType::Rest(&ArgType::String), description: "Command", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1171 flags: &[],
1172 default_output: None,
1173 examples: &[ Example { name: "run", fence_meta: None, code: indoc! {r#"
1174 # Spawned children resolve through the seeded host PATH:
1175 # closed child env is the default, not ambient inherit.
1176 RUN echo hello
1177
1178 # Captured runs prove the output, not just the exit status.
1179 LET $o: STRING = RUN echo hello
1180 ASSERT_CONTAINS $o "hello"
1181 "#} }, Example { name: "run exec form", fence_meta: None, code: indoc! {r#"
1182 # No shell: `>` stays a literal argument, so no file is created.
1183 # Toolchain spawns bridge the host home explicitly: rustup
1184 # shims resolve toolchains through the host home.
1185 IMPORT [STD]
1186 [family:unix] INHERIT_ENV [HOME]
1187 [family:windows] INHERIT_ENV [USERPROFILE]
1188 RUN ["cargo", "--version", ">", "x.txt"]
1189 ASSERT_CONTAINS stdout "cargo"
1190
1191 LET $t: STRING = PATH_TYPE("x.txt")
1192 ASSERT_EQ $t "absent"
1193 "#} } ],
1194 lower: |_flags, args| match args.as_slice() {
1195 [Arg::Expr(Expr::List(elems))] if elems.is_empty() => {
1196 Err(ParseError::validation("RUN", "RUN requires at least one argument".to_string(), &SpanContext::line_only(0)))
1197 }
1198 [Arg::Expr(Expr::List(elems))] => Ok(StepKind::RunExec {
1199 argv: elems.iter().cloned().map(Arg::Expr).collect(),
1200 }),
1201 _ => Ok(StepKind::Run(join_value(args, "RUN")?)),
1202 },
1203 ],
1204
1205 Copy => [
1206 name: "COPY",
1207 variant: Copy { from_workspace: Option<WorkspaceTarget>, from_host: bool, to_host: bool, from: Arg, to: Arg },
1208 syntax: "COPY [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] [--from-host | --to-host] <from> <to>",
1209 summary: "Copy file into workspace.",
1210 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.",
1211 args: &[
1212 ArgSpec { name: "from", arg_type: ArgType::Path, description: "Source", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1213 ArgSpec { name: "to", arg_type: ArgType::Path, description: "Dest", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1214 ],
1215 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)" } ],
1216 default_output: None,
1217 examples: &[ Example { name: "copy", fence_meta: Some("roots:unified"), code: indoc! {r#"
1218 # Copy to a new name, then read back.
1219 WRITE src.txt content
1220 COPY src.txt dst.txt
1221
1222 LET $body: STRING = READ dst.txt
1223 ASSERT_EQ $body "content"
1224 "#} }, Example { name: "copy from workspace", fence_meta: None, code: indoc! {r#"
1225 # Same name, different contents per root: only LOCAL has ws-content.
1226 WRITE shared.txt from-snapshot
1227 WORKSPACE LOCAL
1228 WRITE shared.txt ws-content
1229
1230 WORKSPACE SNAPSHOT
1231 COPY --from-workspace LOCAL shared.txt ws-copy.txt
1232
1233 LET $body: STRING = READ ws-copy.txt
1234 ASSERT_EQ $body "ws-content"
1235 "#} } ],
1236 lower: |flags, args| {
1237 let from_workspace = flags
1238 .iter()
1239 .find(|(k, _)| k == "from_workspace")
1240 .map(|(_, v)| match v.as_str() {
1241 "SNAPSHOT" => Ok(WorkspaceTarget::Snapshot),
1242 "LOCAL" => Ok(WorkspaceTarget::Local),
1243 "CACHE" => Ok(WorkspaceTarget::Cache { local: false }),
1244 "SYSTEM" => Ok(WorkspaceTarget::System),
1245 other => Err(ParseError::validation("COPY", format!("unknown workspace source: {other}"), &SpanContext::line_only(0))),
1246 })
1247 .transpose()?;
1248 let mut it = args.into_iter();
1249 let from = it.next().ok_or_else(|| ParseError::validation("COPY", "COPY requires a source".to_string(), &SpanContext::line_only(0)))?;
1250 let to = it.next().ok_or_else(|| ParseError::validation("COPY", "COPY requires a destination".to_string(), &SpanContext::line_only(0)))?;
1251 let from_host = flags.iter().any(|(k, _)| k == "from_host");
1252 let to_host = flags.iter().any(|(k, _)| k == "to_host");
1253 if from_host && to_host {
1254 return Err(ParseError::validation("COPY", "COPY --from-host and --to-host are mutually exclusive".to_string(), &SpanContext::line_only(0)));
1255 }
1256 Ok(StepKind::Copy { from_workspace, from_host, to_host, from, to })
1257 },
1258 ],
1259
1260 CopyGit => [
1261 name: "COPY_GIT",
1262 variant: CopyGit { rev: Arg, from: Arg, to: Arg, include_dirty: bool },
1263 syntax: "COPY_GIT [--include-dirty] <rev> <src> <dst>",
1264 summary: "Copy from git revision.",
1265 description: "Checkout and copy.",
1266 args: &[
1267 ArgSpec { name: "rev", arg_type: ArgType::String, description: "Rev", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1268 ArgSpec { name: "src", arg_type: ArgType::Path, description: "Src", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
1269 ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Dst", io: IoDirection::Write, index: 2, required: true, fallback_stream: None },
1270 ],
1271 flags: &[ FlagSpec { name: "dirty", long: "--include-dirty", value_type: FlagValueType::Flag, required: false, description: "Include dirty" } ],
1272 default_output: None,
1273 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"#} } ],
1274 lower: |flags, args| {
1275 let include_dirty = flags.iter().any(|(k, _)| k == "dirty");
1276 let mut it = args.into_iter();
1277 let rev = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a revision".to_string(), &SpanContext::line_only(0)))?;
1278 let from = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a source".to_string(), &SpanContext::line_only(0)))?;
1279 let to = it.next().ok_or_else(|| ParseError::validation("COPY_GIT", "COPY_GIT requires a destination".to_string(), &SpanContext::line_only(0)))?;
1280 Ok(StepKind::CopyGit { rev, from, to, include_dirty })
1281 },
1282 ],
1283
1284 Symlink => [
1285 name: "SYMLINK",
1286 variant: Symlink { from_workspace: Option<WorkspaceTarget>, from: Arg, to: Arg },
1287 syntax: "SYMLINK [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>",
1288 summary: "Create symlink.",
1289 description: "Creates symlink. A directory destination (existing, or a trailing-slash spell) receives the link under the source basename.",
1290 args: &[
1291 ArgSpec { name: "from", arg_type: ArgType::Path, description: "Target", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1292 ArgSpec { name: "to", arg_type: ArgType::Path, description: "Link", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1293 ],
1294 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" } ],
1295 default_output: None,
1296 examples: &[ Example { name: "symlink", fence_meta: Some("roots:unified"), code: indoc! {r#"
1297 # A symlink reads like its target.
1298 WRITE original.txt content
1299 SYMLINK original.txt link.txt
1300
1301 LET $body: STRING = READ link.txt
1302 ASSERT_EQ $body "content"
1303 "#} }, Example { name: "symlink from workspace", fence_meta: None, code: indoc! {r#"
1304 # Same name, different contents per root: only LOCAL has ws-content.
1305 WRITE shared.txt from-snapshot
1306 WORKSPACE LOCAL
1307 WRITE shared.txt ws-content
1308
1309 WORKSPACE SNAPSHOT
1310 SYMLINK --from-workspace LOCAL shared.txt ws-link.txt
1311
1312 LET $body: STRING = READ ws-link.txt
1313 ASSERT_EQ $body "ws-content"
1314 "#} } ],
1315 lower: |flags, args| {
1316 let from_workspace = flags
1317 .iter()
1318 .find(|(k, _)| k == "from_workspace")
1319 .map(|(_, v)| match v.as_str() {
1320 "SNAPSHOT" => Ok(WorkspaceTarget::Snapshot),
1321 "LOCAL" => Ok(WorkspaceTarget::Local),
1322 "CACHE" => Ok(WorkspaceTarget::Cache { local: false }),
1323 "SYSTEM" => Ok(WorkspaceTarget::System),
1324 other => Err(ParseError::validation("SYMLINK", format!("unknown workspace source: {other}"), &SpanContext::line_only(0))),
1325 })
1326 .transpose()?;
1327 let mut it = args.into_iter();
1328 let from = it.next().ok_or_else(|| ParseError::validation("SYMLINK", "SYMLINK requires a source".to_string(), &SpanContext::line_only(0)))?;
1329 let to = it.next().ok_or_else(|| ParseError::validation("SYMLINK", "SYMLINK requires a target".to_string(), &SpanContext::line_only(0)))?;
1330 Ok(StepKind::Symlink { from_workspace, from, to })
1331 },
1332 ],
1333
1334 Mkdir => [
1335 name: "MKDIR",
1336 variant: Mkdir(Arg),
1337 syntax: "MKDIR <path>",
1338 summary: "Create directory.",
1339 description: "Creates dir with parents.",
1340 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Dir path", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1341 flags: &[],
1342 default_output: None,
1343 examples: &[ Example { name: "mkdir", fence_meta: None, code: indoc! {r#"
1344 IMPORT [STD]
1345 MKDIR deeply/nested/tree
1346
1347 LET $t: STRING = PATH_TYPE("deeply/nested/tree")
1348 ASSERT_EQ $t "dir"
1349 "#} } ],
1350 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)))?)),
1351 ],
1352
1353 Install => [
1354 name: "INSTALL",
1355 variant: Install { from: Arg, to: Arg },
1356 syntax: "INSTALL <source> <dest>",
1357 summary: "Atomically install a verified binary as executable.",
1358 description: "Stages the source as a temp file in the dest dir, sets executable mode, then renames into place.",
1359 args: &[
1360 ArgSpec { name: "from", arg_type: ArgType::Path, description: "Source file", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1361 ArgSpec { name: "to", arg_type: ArgType::Path, description: "Dest file", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1362 ],
1363 flags: &[],
1364 default_output: None,
1365 examples: &[ Example { name: "install", fence_meta: Some("roots:unified"), code: indoc! {r#"
1366 # Place a verified binary with executable mode.
1367 IMPORT [STD]
1368 WRITE src.bin payload
1369 INSTALL src.bin dst-bin/tool
1370
1371 LET $t: STRING = PATH_TYPE("dst-bin/tool")
1372 ASSERT_EQ $t "file"
1373 "#} } ],
1374 lower: |_flags, args| {
1375 let mut it = args.into_iter();
1376 let from = it.next().ok_or_else(|| ParseError::validation("INSTALL", "INSTALL requires a source".to_string(), &SpanContext::line_only(0)))?;
1377 let to = it.next().ok_or_else(|| ParseError::validation("INSTALL", "INSTALL requires a destination".to_string(), &SpanContext::line_only(0)))?;
1378 Ok(StepKind::Install { from, to })
1379 },
1380 ],
1381
1382 Archive => [
1383 name: "ARCHIVE",
1384 variant: Archive { src: Arg, dst: Arg, raw: bool },
1385 syntax: "ARCHIVE [--raw] <src> <dst>",
1386 summary: "Pack a file or directory into a tarball.",
1387 description: indoc! {r#"
1388 Packs a file or directory into a tarball, gzip-compressed by
1389 default (`--raw` writes an uncompressed tar instead).
1390
1391 A lone file packs as a single top-level entry under its
1392 basename; a directory recurses, preserving empty dirs. Source
1393 modes ride in the headers on Unix, so system `tar` restores
1394 them elsewhere. Symlink sources refuse: archives cross trust
1395 boundaries, so links never resolve into member bytes. Hashing
1396 stays with `HASH_SHA256`, which reads the finished archive
1397 like any other file.
1398 "#},
1399 args: &[
1400 ArgSpec { name: "src", arg_type: ArgType::Path, description: "File or directory to pack", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1401 ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Archive file to write", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1402 ],
1403 flags: &[ FlagSpec { name: "raw", long: "--raw", value_type: FlagValueType::Flag, required: false, description: "Write an uncompressed tar instead of gzip" } ],
1404 default_output: None,
1405 examples: &[ Example { name: "archive directory", fence_meta: None, code: indoc! {r#"
1406 # Stage a small tree to pack.
1407 WRITE bundle/app.txt bundled-payload
1408 WRITE bundle/nested/deep.txt deep-payload
1409
1410 # ARCHIVE packs it gzip-compressed by default.
1411 ARCHIVE bundle bundle.tar.gz
1412
1413 # UNARCHIVE restores the tree under the destination.
1414 UNARCHIVE bundle.tar.gz restored
1415
1416 # The payloads arrive byte-identical.
1417 LET $body: STRING = READ restored/app.txt
1418 ASSERT_EQ $body "bundled-payload"
1419
1420 LET $deep: STRING = READ restored/nested/deep.txt
1421 ASSERT_EQ $deep "deep-payload"
1422 "#} }, Example { name: "archive raw", fence_meta: None, code: indoc! {r#"
1423 # A lone file packs as a single top-level entry.
1424 WRITE tool.bin tool-payload
1425
1426 # Raw archives skip gzip and stay readable by any tar.
1427 ARCHIVE --raw tool.bin tool.tar
1428 UNARCHIVE tool.tar tool-out
1429
1430 # The entry lands under its basename.
1431 LET $body: STRING = READ tool-out/tool.bin
1432 ASSERT_EQ $body "tool-payload"
1433 "#} } ],
1434 lower: |flags, args| {
1435 let raw = flags.iter().any(|(k, _)| k == "raw");
1436 let mut it = args.into_iter();
1437 let src = it.next().ok_or_else(|| ParseError::validation("ARCHIVE", "ARCHIVE requires a source".to_string(), &SpanContext::line_only(0)))?;
1438 let dst = it.next().ok_or_else(|| ParseError::validation("ARCHIVE", "ARCHIVE requires a destination".to_string(), &SpanContext::line_only(0)))?;
1439 Ok(StepKind::Archive { src, dst, raw })
1440 },
1441 ],
1442
1443 Unarchive => [
1444 name: "UNARCHIVE",
1445 variant: Unarchive { src: Arg, dst: Arg, max_bytes: Option<Arg> },
1446 syntax: "UNARCHIVE <src> <dst> [--max-bytes <bytes>]",
1447 summary: "Unpack a tarball into a directory.",
1448 description: indoc! {r#"
1449 Unpacks a tarball under the destination directory, creating
1450 it first. Gzip and raw (`ARCHIVE --raw`) tarballs
1451 self-identify by magic bytes, so no flag is needed.
1452
1453 Member bytes meter against a 1 GiB default expansion cap
1454 across the whole archive: a decompression bomb trips it
1455 instead of filling the disk, and `--max-bytes` moves the
1456 ceiling either way (plain integer bytes). The tripped member
1457 stays truncated on disk while the step fails loudly.
1458
1459 Symlink and special members refuse naming the entry, and
1460 absolute or escaping paths fail closed before any byte
1461 lands: the member sanitizer plus the destination join check
1462 form two independent walls. Unix modes recorded in the
1463 headers restore on unpack; other platforms land default
1464 modes (confer executability with `INSTALL` there).
1465 "#},
1466 args: &[
1467 ArgSpec { name: "src", arg_type: ArgType::Path, description: "Archive file to unpack", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1468 ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Directory to unpack under", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1469 ],
1470 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)" } ],
1471 default_output: None,
1472 examples: &[ Example { name: "unarchive", fence_meta: None, code: indoc! {r#"
1473 # Pack a note, then restore it under a fresh destination.
1474 WRITE pack/note.txt packed-note
1475 ARCHIVE pack pack.tar.gz
1476 UNARCHIVE pack.tar.gz unpacked
1477
1478 LET $body: STRING = READ unpacked/note.txt
1479 ASSERT_EQ $body "packed-note"
1480 "#} }, Example { name: "unarchive with a lower cap", fence_meta: None, code: indoc! {r#"
1481 # Small payloads clear even a tight ceiling.
1482 WRITE pack/note.txt packed-note
1483 ARCHIVE pack pack.tar.gz
1484 UNARCHIVE pack.tar.gz capped --max-bytes 100KB
1485
1486 LET $body: STRING = READ capped/note.txt
1487 ASSERT_EQ $body "packed-note"
1488 "#} } ],
1489 lower: |flags, args| {
1490 let mut it = args.into_iter();
1491 let src = it.next().ok_or_else(|| ParseError::validation("UNARCHIVE", "UNARCHIVE requires an archive".to_string(), &SpanContext::line_only(0)))?;
1492 let dst = it.next().ok_or_else(|| ParseError::validation("UNARCHIVE", "UNARCHIVE requires a destination".to_string(), &SpanContext::line_only(0)))?;
1493 let max_bytes = flags
1494 .into_iter()
1495 .find_map(|(k, v)| (k == "max_bytes").then_some(v));
1496 if let Some(Arg::String(text, _)) = max_bytes.as_ref()
1500 && !text.contains("{{")
1501 && let Err(e) = crate::command::parse_byte_count(text)
1502 {
1503 return Err(ParseError::validation(
1504 "UNARCHIVE",
1505 format!("UNARCHIVE --max-bytes {e:#}"),
1506 &SpanContext::line_only(0),
1507 ));
1508 }
1509 Ok(StepKind::Unarchive { src, dst, max_bytes })
1510 },
1511 ],
1512
1513 Ls => [
1514 name: "LS",
1515 variant: Ls(Option<Arg>),
1516 syntax: "LS [<path>]",
1517 summary: "List directory.",
1518 description: "Lists entries.",
1519 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Dir", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
1520 flags: &[],
1521 default_output: Some(Stream::Stdout),
1522 examples: &[ Example { name: "ls", fence_meta: None, code: indoc! {r#"
1523 MKDIR inventory
1524 WRITE inventory/a.txt a
1525 LS inventory
1526 ASSERT_CONTAINS stdout "a.txt"
1527 "#} } ],
1528 lower: |_flags, args| Ok(StepKind::Ls(args.into_iter().next())),
1529 ],
1530
1531 Cwd => [
1532 name: "CWD",
1533 variant: Cwd,
1534 syntax: "CWD",
1535 summary: "Print working directory.",
1536 description: "Outputs cwd.",
1537 args: &[],
1538 flags: &[],
1539 default_output: Some(Stream::Stdout),
1540 examples: &[ Example { name: "cwd", fence_meta: None, code: indoc! {r#"
1541 CWD
1542
1543 # CWD tracks WORKDIR: the listing names the new directory.
1544 MKDIR sub
1545 WORKDIR sub
1546 LET $c: STRING = CWD
1547 ASSERT_CONTAINS $c "sub"
1548 "#} } ],
1549 lower: |_flags, _args| Ok(StepKind::Cwd),
1550 ],
1551
1552 Read => [
1553 name: "READ",
1554 variant: Read(Option<Arg>),
1555 syntax: "READ [<path>]",
1556 summary: "Read file to stdout.",
1557 description: "Outputs file contents.",
1558 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
1559 flags: &[],
1560 default_output: Some(Stream::Stdout),
1561 examples: &[ Example { name: "read", fence_meta: None, code: indoc! {r#"
1562 WRITE note.txt "hello"
1563 READ note.txt
1564
1565 LET $body: STRING = READ note.txt
1566 ASSERT_EQ $body "hello"
1567 "#} } ],
1568 lower: |_flags, args| Ok(StepKind::Read(args.into_iter().next())),
1569 ],
1570
1571 ReadLine => [
1572 name: "READ_LINE",
1573 variant: ReadLine { var: String },
1574 syntax: "READ_LINE $var",
1575 summary: "Read one line from stdin into a variable.",
1576 description: indoc! {r#"
1577 Reads bytes until newline without waiting for EOF, leaving the pipe open.
1578
1579 Trailing newline is stripped (shell-read parity). On premature EOF
1580 assigns accumulated bytes and returns.
1581 "#},
1582 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 } ],
1583 flags: &[],
1584 default_output: None,
1585 examples: &[ Example { name: "read line", fence_meta: None, code: indoc! {r#"
1586 # The trailing newline is stripped: the variable holds exactly `first`.
1587 LET $lines: PIPE
1588 WITH_IO [stdout=$lines] ECHO "first"
1589 WITH_IO [stdin=$lines] READ_LINE $reply
1590 ASSERT_EQ $reply "first"
1591 "#} } ],
1592 lower: |_flags, args| {
1593 let arg = args.into_iter().next().ok_or_else(|| ParseError::validation("READ_LINE", "READ_LINE requires a variable".to_string(), &SpanContext::line_only(0)))?;
1594 let var = match arg {
1595 Arg::Expr(Expr::Var(name)) => name,
1596 Arg::String(s, _) if s.starts_with('$') || s.contains("{{") => s.trim_start_matches('$').to_string(),
1599 other => return Err(ParseError::validation("READ_LINE", format!("READ_LINE requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
1600 };
1601 if var.is_empty() {
1602 return Err(ParseError::validation("READ_LINE", "READ_LINE requires a variable".to_string(), &SpanContext::line_only(0)))
1603 }
1604 Ok(StepKind::ReadLine { var })
1605 },
1606 ],
1607
1608 Prompt => [
1609 name: "PROMPT",
1610 variant: Prompt { var: String, message: Arg, default: Option<Arg> },
1611 syntax: "PROMPT $var <message> [<default>]",
1612 summary: "Prompt on the terminal into a variable.",
1613 description: indoc! {r#"
1614 Prints `{message} [{default}]: ` (or `{message}: ` with no
1615 default) to stderr and reads one line from the terminal.
1616
1617 Empty input yields the default when one is given, else an
1618 empty string. EOF aborts loudly. Non-TTY stdin never reads:
1619 a default binds with a stderr note, while no default bails.
1620 "#},
1621 args: &[
1622 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 },
1623 ArgSpec { name: "message", arg_type: ArgType::String, description: "Prompt message", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
1624 ArgSpec { name: "default", arg_type: ArgType::String, description: "Default on empty input", io: IoDirection::Read, index: 2, required: false, fallback_stream: None },
1625 ],
1626 flags: &[],
1627 default_output: None,
1628 examples: &[ Example { name: "prompt needs a terminal", fence_meta: Some("expect_error:\"non-TTY\""), code: indoc! {r#"
1629 # A redirected stdin can never answer: without a default the
1630 # prompt fails instead of hanging or reading piped stdin.
1631 LET $p: PIPE
1632 WITH_IO [stdin=$p] PROMPT $dir "Install destination?"
1633 "#} } ],
1634 lower: |_flags, args| {
1635 let mut it = args.into_iter();
1636 let var_arg = it.next().ok_or_else(|| ParseError::validation("PROMPT", "PROMPT requires a variable".to_string(), &SpanContext::line_only(0)))?;
1637 let var = match var_arg {
1638 Arg::Expr(Expr::Var(name)) => name,
1639 Arg::String(s, _) if s.starts_with('$') || s.contains("{{") => s.trim_start_matches('$').to_string(),
1640 other => return Err(ParseError::validation("PROMPT", format!("PROMPT requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
1641 };
1642 if var.is_empty() {
1643 return Err(ParseError::validation("PROMPT", "PROMPT requires a variable".to_string(), &SpanContext::line_only(0)))
1644 }
1645 let message = it.next().ok_or_else(|| ParseError::validation("PROMPT", "PROMPT requires a message".to_string(), &SpanContext::line_only(0)))?;
1646 let default = it.next();
1647 Ok(StepKind::Prompt { var, message, default })
1648 },
1649 ],
1650
1651 Write => [
1652 name: "WRITE",
1653 variant: Write { path: Arg, contents: Option<Arg> },
1654 syntax: "WRITE <path> [<contents>]",
1655 summary: "Write to file.",
1656 description: "Writes contents.",
1657 args: &[
1658 ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
1659 ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Content", io: IoDirection::Write, index: 1, required: false, fallback_stream: Some(Stream::Stdin) },
1660 ],
1661 flags: &[],
1662 default_output: None,
1663 examples: &[ Example { name: "write", fence_meta: None, code: indoc! {r#"
1664 WRITE output.txt hello-world
1665 LET $body: STRING = READ output.txt
1666 ASSERT_EQ $body "hello-world"
1667 "#} } ],
1668 lower: |_flags, args| {
1669 let mut it = args.into_iter();
1670 let path = it.next().ok_or_else(|| ParseError::validation("WRITE", "WRITE requires a path".to_string(), &SpanContext::line_only(0)))?;
1671 let remaining: Vec<Arg> = it.collect();
1672 let contents = if remaining.is_empty() { None } else { Some(join_value(remaining, "WRITE")?) };
1673 Ok(StepKind::Write { path, contents })
1674 },
1675 ],
1676
1677 Append => [
1678 name: "APPEND",
1679 variant: Append { path: Arg, contents: Option<Arg> },
1680 syntax: "APPEND <path> [<contents>]",
1681 summary: "Append to file.",
1682 description: "Appends contents.",
1683 args: &[
1684 ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
1685 ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Content", io: IoDirection::Write, index: 1, required: false, fallback_stream: Some(Stream::Stdin) },
1686 ],
1687 flags: &[],
1688 default_output: None,
1689 examples: &[ Example { name: "append", fence_meta: None, code: indoc! {r#"
1690 WRITE log.txt line1
1691 APPEND log.txt line2
1692
1693 # APPEND concatenates with no separator.
1694 LET $all: STRING = READ log.txt
1695 ASSERT_EQ $all "line1line2"
1696 "#} } ],
1697 lower: |_flags, args| {
1698 let mut it = args.into_iter();
1699 let path = it.next().ok_or_else(|| ParseError::validation("APPEND", "APPEND requires a path".to_string(), &SpanContext::line_only(0)))?;
1700 let remaining: Vec<Arg> = it.collect();
1701 let contents = if remaining.is_empty() { None } else { Some(join_value(remaining, "APPEND")?) };
1702 Ok(StepKind::Append { path, contents })
1703 },
1704 ],
1705
1706 Remove => [
1707 name: "REMOVE",
1708 variant: Remove { path: Arg, recursive: bool },
1709 syntax: "REMOVE [--recursive] <path>",
1710 summary: "Remove a file, symlink, or directory.",
1711 description: "Removes a file, symlink (the link itself), or empty dir. With --recursive removes a directory tree.",
1712 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Path to remove", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1713 flags: &[ FlagSpec { name: "recursive", long: "--recursive", value_type: FlagValueType::Flag, required: false, description: "Remove a directory tree" } ],
1714 default_output: None,
1715 examples: &[ Example { name: "remove", fence_meta: None, code: indoc! {r#"
1716 # WRITE then REMOVE leaves nothing behind.
1717 IMPORT [STD]
1718 WRITE scratch.txt content
1719
1720 # Assert original file is written
1721 LET $o: STRING = PATH_TYPE("scratch.txt")
1722 ASSERT_EQ $o "file"
1723
1724 REMOVE scratch.txt
1725
1726 # Assert file has been removed
1727 LET $t: STRING = PATH_TYPE("scratch.txt")
1728 ASSERT_EQ $t "absent"
1729 "#} } ],
1730 lower: |flags, args| {
1731 let recursive = flags.iter().any(|(k, _)| k == "recursive");
1732 let path = args.into_iter().next().ok_or_else(|| ParseError::validation("REMOVE", "REMOVE requires a path".to_string(), &SpanContext::line_only(0)))?;
1733 Ok(StepKind::Remove { path, recursive })
1734 },
1735 ],
1736
1737 Expand => [
1738 name: "EXPAND",
1739 variant: Expand { path: Option<Arg>, overrides: Vec<(String, Arg)> },
1740 syntax: "EXPAND [<path>] [<KEY=val> ...]",
1741 summary: "Expand a template file (or stdin) to stdout.",
1742 description: indoc! {r#"
1743 A template is any text file — or piped stdin when no path is given —
1744 containing `{{ ... }}` placeholders. EXPAND replaces each placeholder
1745 and prints the result to stdout.
1746
1747 Placeholders: `{{ NAME }}` reads a `KEY=val` override passed on this
1748 command; `{{ env:NAME }}` reads an override, falling back to the
1749 environment; `{{ $var }}` reads a script variable (dotted paths allowed).
1750 A missing key is an error, never a silent empty.
1751
1752 Calls: `{{ MODULE::FUNC(args) }}` invokes a pure registry function
1753 with `$var.path` references and `STRING`, `INT`, `FLOAT`, and `BOOL`
1754 literals as arguments. Only pure functions resolve here: stateful,
1755 script-defined, and pipe-backed entries fail naming themselves,
1756 since placeholder evaluation carries no step context. The same
1757 calls resolve in ordinary strings, so both paths agree.
1758
1759 Substitution runs in a single pass. `EXPAND` is not recursive and does not
1760 expand nested placeholders: a value that itself contains `{{ ... }}` is
1761 inserted verbatim and never expanded again.
1762
1763 A bare `$var` argument is a template path; `KEY=val` arguments are
1764 overrides whose values follow the unified string-value rules (same as
1765 `ENV`: quotes keep exact bytes, a lone `$var` evaluates,
1766 `{{ ... }}` interpolates).
1767
1768 NOTE: `WRITE` interpolates `{{ ... }}` while writing, so escape it
1769 (`\{{ ... }}`) when writing a template file for a later `EXPAND`.
1770
1771 With no path, the template arrives on stdin through a pipe. When piping
1772 from a shell, single-quote the template (`echo '{{ $x }}'`): double
1773 quotes let the shell swallow `$x`, so oxdock receives an empty `{{ }}`
1774 placeholder and errors.
1775 "#},
1776 args: &[
1777 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 },
1778 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 },
1779 ],
1780 flags: &[],
1781 default_output: Some(Stream::Stdout),
1782 examples: &[
1783 Example { name: "expand", fence_meta: None, code: indoc! {r#"
1784 # Placeholders read overrides first, then the environment.
1785 ENV NAME="Alice"
1786 WRITE template.md "Hello {{ env:NAME }}!"
1787 EXPAND template.md
1788
1789 ASSERT_CONTAINS stdout "Hello Alice!"
1790 "#} },
1791 Example { name: "override with spaces", fence_meta: None, code: indoc! {r#"
1792 # WRITE would interpolate {{ }} right away, so escape it.
1793 # The file must literally contain {{ env:NAME }} for EXPAND.
1794 WRITE template.md "Hello \{{ env:NAME }}!"
1795 EXPAND template.md NAME="Alice Smith"
1796
1797 ASSERT_CONTAINS stdout "Hello Alice Smith!"
1798 "#} },
1799 Example { name: "variable override", fence_meta: None, code: indoc! {r#"
1800 # Same escaping: keep the placeholder literal until EXPAND.
1801 # A lone $who evaluates, like ECHO $who.
1802 LET $who: STRING = "Bob"
1803 WRITE template.md "Hi \{{ env:WHO }}!"
1804 EXPAND template.md WHO=$who
1805
1806 ASSERT_CONTAINS stdout "Hi Bob!"
1807 "#} },
1808 Example { name: "override forms agree", fence_meta: None, code: indoc! {r#"
1809 # A bare variable and a template-with-tail expand identically.
1810 LET $x: STRING = "Ada"
1811 WRITE template.md "Hi \{{ env:NAME }} and \{{ env:NAME2 }}!"
1812 EXPAND template.md NAME=$x NAME2="{{ $x }} concatenated"
1813
1814 ASSERT_CONTAINS stdout "Hi Ada and Ada concatenated!"
1815 "#} },
1816 Example { name: "expand stdin", fence_meta: None, code: indoc! {r#"
1817 # No path: the template arrives on stdin through a pipe.
1818 LET $tpl: PIPE
1819 WITH_IO [stdout=$tpl] ECHO "Hello \{{ env:NAME }}!"
1820 WITH_IO [stdin=$tpl] EXPAND NAME=Alice
1821
1822 ASSERT_CONTAINS stdout "Hello Alice!"
1823 "#} },
1824 Example { name: "override does not leak", fence_meta: None, code: indoc! {r#"
1825 # KEY=val overrides shadow env for that EXPAND only.
1826 # They never update the environment itself.
1827 ENV NAME="Alice"
1828 WRITE template.md "Hi \{{ env:NAME }}!"
1829
1830 EXPAND template.md NAME="Bob"
1831 ASSERT_CONTAINS stdout "Hi Bob!"
1832
1833 EXPAND template.md
1834 ASSERT_CONTAINS stdout "Hi Alice!"
1835 "#} },
1836 Example { name: "function call", fence_meta: None, code: indoc! {r#"
1837 # Pure registry functions run inside placeholders.
1838 # WRITE would interpolate {{ }} right away, so escape it.
1839 IMPORT [STD]
1840 WRITE template.md "Count: \{{ STD::TEXT_COUNT(\"one two two three\", \"two\") }}!"
1841
1842 EXPAND template.md
1843 ASSERT_CONTAINS stdout "Count: 2!"
1844 "#} },
1845 ],
1846 lower: |_flags, args| {
1847 let mut path = None;
1848 let mut overrides = Vec::new();
1849 for arg in args {
1850 let text = arg.as_str();
1851 if let Some((key, value)) = split_assignment(text).map_err(|e| ParseError::validation("EXPAND", e.to_string(), &SpanContext::line_only(0)))? {
1852 overrides.push((key, value));
1853 } else if path.is_none() { path = Some(arg); }
1854 else { return Err(ParseError::validation("EXPAND", "EXPAND accepts at most one path".to_string(), &SpanContext::line_only(0))) }
1855 }
1856 Ok(StepKind::Expand { path, overrides })
1857 },
1858 ],
1859
1860 AssertEq => [
1861 name: "ASSERT_EQ",
1862 variant: AssertEq { hash: Option<String>, actual: AssertTarget, expected: Option<Arg> },
1863 syntax: "ASSERT_EQ <actual> <expected> | ASSERT_EQ --hash <sha256> <actual>",
1864 summary: "Assert strict equality.",
1865 description: indoc! {r#"
1866 Compares two evaluated values with typed equality (no coercion:
1867 `INT(42)` never equals `STRING("42")`), aborting the pipeline
1868 with a step-numbered error showing expected vs actual otherwise.
1869
1870 Both sides are values: `$var`, literals, templates, and calls
1871 evaluate in memory and never touch disk. Read files explicitly
1872 first (`LET $text: STRING = READ "out.txt"`, then
1873 `ASSERT_EQ $text ...`).
1874 Bare `stdout` / `stderr` observe stream buffers; a `$var`
1875 holding a `PIPE` observes its backend bytes. `--hash` compares
1876 the SHA-256 of a string, pipe, or captured-stdout actual
1877 instead of the raw bytes (`stderr` is unsupported).
1878 "#},
1879 args: &[
1880 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 },
1881 ArgSpec { name: "expected", arg_type: ArgType::Rest(&ArgType::Any), description: "Expected (required unless --hash)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
1882 ],
1883 flags: &[ FlagSpec { name: "hash", long: "--hash", value_type: FlagValueType::String, required: false, description: "SHA-256" } ],
1884 default_output: None,
1885 examples: &[ Example { name: "assert eq", fence_meta: None, code: indoc! {r#"
1886 LET $status: INT = 200
1887 ASSERT_EQ $status 200
1888 "#} },
1889 Example { name: "assert eq file", fence_meta: None, code: indoc! {r#"
1890 WRITE payload.bin stable-content
1891 LET $body: STRING = READ payload.bin
1892 ASSERT_EQ $body "stable-content"
1893 "#} },
1894 Example { name: "assert eq hash", fence_meta: None, code: indoc! {r#"
1895 # --hash compares the SHA-256 digest instead of raw bytes.
1896 WRITE payload.bin stable-content
1897 LET $body: STRING = READ payload.bin
1898 ASSERT_EQ --hash 08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c $body
1899 "#} } ],
1900 lower: |flags, args| {
1901 let hash = flags.iter().find(|(k, _)| k == "hash").map(|(_, v)| v.as_str().to_string());
1902 let mut it = args.into_iter();
1903 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)))?)?;
1904 let remaining: Vec<Arg> = it
1905 .map(lower_assert_operand)
1906 .collect::<Vec<Arg>>();
1907 let expected = if remaining.is_empty() {
1910 if hash.is_some() {
1911 None
1912 } else {
1913 return Err(ParseError::validation("ASSERT_EQ", "ASSERT_EQ requires an expected value".to_string(), &SpanContext::line_only(0)))
1914 }
1915 } else {
1916 Some(join_value(remaining, "ASSERT_EQ")?)
1917 };
1918 Ok(StepKind::AssertEq { hash, actual, expected })
1919 },
1920 ],
1921
1922 AssertContains => [
1923 name: "ASSERT_CONTAINS",
1924 variant: AssertContains { haystack: AssertTarget, needle: Arg },
1925 syntax: "ASSERT_CONTAINS <haystack> <needle>",
1926 summary: "Assert containment.",
1927 description: indoc! {r#"
1928 Checks containment and aborts the pipeline with a step-numbered
1929 error otherwise: substring for strings, element match for lists,
1930 key presence for maps, substring over stream and pipe buffers.
1931
1932 Like `ASSERT_EQ`, both sides are values read without implicit
1933 I/O; read files explicitly first
1934 (`LET $text: STRING = READ "cfg.txt"`).
1935 Bare `stdout` / `stderr` observe stream buffers; a `$var`
1936 holding a `PIPE` observes its backend bytes.
1937 "#},
1938 args: &[
1939 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 },
1940 ArgSpec { name: "needle", arg_type: ArgType::Rest(&ArgType::Any), description: "Substring, element, or key", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
1941 ],
1942 flags: &[],
1943 default_output: None,
1944 examples: &[ Example { name: "assert contains", fence_meta: None, code: indoc! {r#"
1945 ECHO build-complete
1946 ASSERT_CONTAINS stdout "build-complete"
1947 "#} } ],
1948 lower: |flags, args| {
1949 let _ = flags;
1950 let mut it = args.into_iter();
1951 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)))?)?;
1952 let remaining: Vec<Arg> = it
1953 .map(lower_assert_operand)
1954 .collect::<Vec<Arg>>();
1955 if remaining.is_empty() {
1956 return Err(ParseError::validation("ASSERT_CONTAINS", "ASSERT_CONTAINS requires a needle".to_string(), &SpanContext::line_only(0)))
1957 }
1958 let needle = join_value(remaining, "ASSERT_CONTAINS")?;
1959 Ok(StepKind::AssertContains { haystack, needle })
1960 },
1961 ],
1962
1963 HashSha256 => [
1964 name: "HASH_SHA256",
1965 variant: HashSha256 { path: Arg },
1966 syntax: "HASH_SHA256 <path>",
1967 summary: "Print SHA-256.",
1968 description: "Computes digest.",
1969 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Read, index: 0, required: true, fallback_stream: None } ],
1970 flags: &[],
1971 default_output: Some(Stream::Stdout),
1972 examples: &[ Example { name: "hash", fence_meta: None, code: indoc! {r#"
1973 WRITE payload.txt hello
1974 HASH_SHA256 payload.txt
1975
1976 LET $digest: STRING = HASH_SHA256 payload.txt
1977 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\n"
1978 "#} } ],
1979 lower: |_flags, args| Ok(StepKind::HashSha256 { path: args.into_iter().next().ok_or_else(|| ParseError::validation("HASH_SHA256", "HASH_SHA256 requires a path".to_string(), &SpanContext::line_only(0)))? }),
1980 ],
1981
1982 Exit => [
1983 name: "EXIT",
1984 variant: Exit(Arg),
1985 syntax: "EXIT <code>",
1986 summary: "Exit pipeline.",
1987 description: indoc! {r#"
1988 Stops the pipeline immediately with an `EXIT requested with code <code>`
1989 error; steps after it never run, at any nesting depth.
1990
1991 Enclosing blocks still unwind their LET/ENV/WORKDIR/WORKSPACE state,
1992 anonymous background tasks are killed synchronously, and files written
1993 before the EXIT persist.
1994
1995 The code reaches the OS: the CLI exits with `<code>` clamped to
1996 0..=255, and a guest EXIT relays through `REMOTE` the same way.
1997 "#},
1998 args: &[ ArgSpec { name: "code", arg_type: ArgType::Int, description: "Code", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1999 flags: &[],
2000 default_output: None,
2001 examples: &[ Example { name: "exit", fence_meta: Some("expect_error:\"EXIT requested with code 0\""), code: indoc! {r#"EXIT 0"#} } ],
2002 lower: |_flags, args| {
2003 let code = args.into_iter().next().ok_or_else(|| ParseError::validation("EXIT", "EXIT requires a code".to_string(), &SpanContext::line_only(0)))?;
2006 Ok(StepKind::Exit(code))
2007 },
2008 ],
2009
2010 Sleep => [
2011 name: "SLEEP",
2012 variant: Sleep { duration: Arg },
2013 syntax: "SLEEP <duration>",
2014 summary: "Pause execution for a duration.",
2015 description: indoc! {r#"
2016 Parks the step for the duration (e.g. 500ms, 10s, 2m).
2017
2018 Cooperative: checks for cancellation so an enclosing TIMEOUT or task
2019 teardown interrupts the sleep. Cross-platform alternative to shell sleep
2020 for testing time boundaries.
2021 "#},
2022 args: &[ ArgSpec { name: "duration", arg_type: ArgType::Duration, description: "How long to sleep", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
2023 flags: &[],
2024 default_output: None,
2025 examples: &[
2026 Example { name: "sleep", fence_meta: None, code: indoc! {r#"SLEEP 100ms"#} },
2027 Example {
2028 name: "sleep variable duration",
2029 fence_meta: None,
2030 code: indoc! {r#"
2031 # Durations resolve at runtime, so variables work too:
2032 # quoted or bare, both bind the same string.
2033 LET $pause: STRING = "100ms"
2034 SLEEP $pause
2035
2036 LET $bare: STRING = 100ms
2037 SLEEP $bare
2038 "#},
2039 },
2040 ],
2041 lower: |_flags, args| {
2042 let mut it = args.into_iter();
2043 let raw = it
2044 .next()
2045 .ok_or_else(|| ParseError::validation("SLEEP", "SLEEP requires a duration (e.g. SLEEP 500ms)".to_string(), &SpanContext::line_only(0)))?;
2046 if it.next().is_some() {
2047 return Err(ParseError::validation("SLEEP", "SLEEP takes exactly one duration argument".to_string(), &SpanContext::line_only(0)))
2048 }
2049 Ok(StepKind::Sleep { duration: raw })
2052 },
2053 ],
2054
2055 ListAppend => [
2056 name: "LIST_APPEND",
2057 variant: ListAppend { list: String, item: Arg },
2058 syntax: "LIST_APPEND $list <item>",
2059 summary: "Append an item to a LIST variable in place.",
2060 description: indoc! {r#"
2061 Appends the item to the LIST variable in place.
2062
2063 When the binding holds the only reference the push runs in
2064 amortized constant time. Aliased buffers detach first, so
2065 other holders keep their contents.
2066 "#},
2067 args: &[
2068 ArgSpec { name: "list", arg_type: ArgType::List, description: "Target LIST variable (`$name`)", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
2069 ArgSpec { name: "item", arg_type: ArgType::Any, description: "Item to append (any value)", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
2070 ],
2071 flags: &[],
2072 default_output: None,
2073 examples: &[ Example { name: "list append", fence_meta: None, code: indoc! {r#"
2074 # Appends accumulate in order.
2075 LET $items: LIST<STRING> = []
2076 LIST_APPEND $items "first"
2077 LIST_APPEND $items "second"
2078
2079 LET $want: LIST<STRING> = ["first", "second"]
2080 ASSERT_EQ $items $want
2081 "#} } ],
2082 lower: |_flags, args| {
2083 let mut it = args.into_iter();
2084 let raw_list = it
2085 .next()
2086 .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)))?;
2087 let list = match raw_list {
2088 Arg::Expr(Expr::Var(name)) => name,
2089 Arg::String(s, _) => s.trim_start_matches('$').to_string(),
2090 other => return Err(ParseError::validation("LIST_APPEND", format!("LIST_APPEND requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
2091 };
2092 if list.is_empty() {
2093 return Err(ParseError::validation("LIST_APPEND", "LIST_APPEND requires a LIST variable (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))
2094 }
2095 let item = it
2096 .next()
2097 .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)))?;
2098 if it.next().is_some() {
2099 return Err(ParseError::validation("LIST_APPEND", "LIST_APPEND takes exactly two arguments: LIST_APPEND $list <item>".to_string(), &SpanContext::line_only(0)))
2100 }
2101 Ok(StepKind::ListAppend { list, item })
2102 },
2103 ],
2104}
2105
2106pub fn all_structural_metadata() -> Vec<CommandMeta> {
2114 vec![
2115 CommandMeta {
2116 name: "WITH_IO",
2117 syntax: "WITH_IO [<stream>[=$var], ...] <command> | WITH_IO [bindings] { <commands> } | WITH_IO [tty[, stdin=$p][, rows=<int>][, cols=<int>]] RUN ...",
2118 summary: "Reroute standard streams.",
2119 description: indoc! {r#"
2120 Reroutes the standard streams of the next command or, in block form,
2121 of every enclosed command.
2122
2123 Bindings map streams (`stdin`, `stdout`, `stderr`) to a PIPE-typed
2124 variable (`stdout=$p`, `stdin=$p`), resolved from the variable
2125 when the step runs. Both stdout and stderr pipes capture output
2126 the same way. Declare the handle first with `LET $p: PIPE`.
2127
2128 A `RUN` step can opt into a pseudo-terminal with the bare `tty`
2129 flag instead of a new command: `WITH_IO [tty] RUN [...]`
2130 spawns the child under a pty sized from the host terminal
2131 when it names none (24x80 fallback off-terminal;
2132 `rows = <int>` / `cols = <int>` override each side).
2133 Unnamed sides track the host window while the step runs
2134 (signal-driven on Unix, polled where no window signal
2135 exists); explicit sides stay pinned.
2136
2137 The master carries the child's interleaved stdout and stderr
2138 as one stream, so it routes exclusively to `stdout` (step
2139 capture or a `stdout = $p` pipe): `stderr` bindings alongside
2140 `tty` are rejected, and `tty` outside a `RUN` step is
2141 rejected. Pty-backed descriptors never promote to OS
2142 kernel pipes, even inside `ASYNC` single-`RUN` bodies.
2143
2144 `stdin = $p` feeds the master; bare `[tty]`
2145 with a real terminal stdin feeds host keys the same
2146 way (raw, transparent) and stays closed headless. Host
2147 interrupt keys reach the child instead of cancelling the
2148 step, so bind a step `TIMEOUT` for a guaranteed exit.
2149
2150 Expect pty translation in assertions:
2151 newlines arrive as carriage return plus newline, and prompts
2152 echo input. On Windows, lone line feeds in fed input expand
2153 to carriage-return line feeds for console submission, so
2154 portable scripts need no per-platform line endings.
2155
2156 An input pipe that EOFs contributes a
2157 terminal-echoed end-of-transmission marker on some
2158 platforms: prefer `ASSERT_CONTAINS` over byte-exact
2159 assertions on fed sessions.
2160
2161 Pipes hold bytes in memory and spill to a temp file above 8 MiB, so a
2162 producer can finish before the consumer starts.
2163
2164 If WITH_IO wraps an ASYNC block whose body is a single RUN, guarded or
2165 not, the pipe is a zero copy OS kernel pipe instead: pair it with a
2166 consumer that runs while the producer is alive, since output past the
2167 64 KiB kernel buffer stalls until drained. That promotion never crosses
2168 a function boundary: pipes created, bound, or passed by variable inside FUNC
2169 bodies are always script pipes, even when the surrounding task would
2170 otherwise promote.
2171
2172 A second producer or consumer on a live handle is an explicit
2173 error. A handle bound as output can later feed another
2174 command's `stdin`, connecting commands without touching the
2175 terminal. Binding `stdout` and `stderr` to the same live
2176 handle fails deterministically. Merge streams in shell
2177 via `2>&1` instead.
2178
2179 Nested blocks stack defaults; inline bindings override inherited ones for
2180 their command only; closing a block restores previous wiring.
2181 "#},
2182 args: &[],
2183 flags: &[],
2184 default_output: None,
2185 examples: &[
2186 Example {
2187 name: "with_io block",
2188 fence_meta: None,
2189 code: indoc! {r#"
2190 LET $log: PIPE
2191 WITH_IO [stdout=$log] {
2192 ECHO first
2193 ECHO second
2194 }
2195 WITH_IO [stdin=$log] WRITE captured.txt
2196
2197 # The piped bytes landed in the file.
2198 LET $body: STRING = READ captured.txt
2199 ASSERT_CONTAINS $body "first"
2200 ASSERT_CONTAINS $body "second"
2201 "#},
2202 },
2203 Example {
2204 name: "variable pipe binding",
2205 fence_meta: None,
2206 code: indoc! {r#"
2207 # Declare the pipe first: `LET $p: PIPE` mints a fresh
2208 # backend without touching a stream. A plain string here
2209 # would be a TypeMismatch.
2210 LET $p: PIPE
2211 WITH_IO [stdout=$p] ECHO hello
2212 WITH_IO [stdin=$p] READ_LINE $line
2213 ASSERT_EQ $line "hello"
2214 "#},
2215 },
2216 Example {
2217 name: "pty terminal binding",
2218 fence_meta: None,
2219 code: indoc! {r#"
2220 # A RUN step under bare `tty` sees a terminal: newlines
2221 # arrive translated, so assert with CONTAINS, never EQ.
2222 LET $p: PIPE
2223 WITH_IO [tty, stdout=$p] RUN "echo hello-tty"
2224 WITH_IO [stdin=$p] READ_LINE $line
2225 ASSERT_CONTAINS $line "hello-tty"
2226 "#},
2227 },
2228 ],
2229 },
2230 CommandMeta {
2231 name: "FOR",
2232 syntax: "FOR $item: TYPE IN <expr> { <commands> } | FOR $key: STRING, $value: TYPE IN <expr> { <commands> }",
2233 summary: "Iterate over a list or map.",
2234 description: indoc! {r#"
2235 The loop variable receives each element (lists) or value (maps); with
2236 two variables, the first receives the key.
2237
2238 Loop variables are declared with explicit types and scoped per iteration;
2239 they do not leak outward. The body may be a braced block
2240 or a single-line `{ ... }` command.
2241
2242 `GLOB("...")` patterns must be quoted (`*` is not a bare word, so
2243 `GLOB(*)` is a parse error); GLOB returns a root-relative sorted list,
2244 empty when nothing matches, and rejects `..` escapes.
2245 "#},
2246 args: &[],
2247 flags: &[],
2248 default_output: None,
2249 examples: &[
2250 Example {
2251 name: "for loop",
2252 fence_meta: None,
2253 code: indoc! {r#"
2254 # Each element binds in turn; the loop body sees every one.
2255 LET $items: LIST<STRING> = ["a", "b"]
2256 FOR $item: STRING IN $items {
2257 ECHO $item
2258 }
2259 ASSERT_CONTAINS stdout "a"
2260 ASSERT_CONTAINS stdout "b"
2261
2262 # Key and value bind together for maps.
2263 LET $map: MAP<x: INT> = {"x": 1}
2264 FOR $k: STRING, $v: INT IN $map {
2265 ECHO "{{ $k }}={{ $v }}"
2266 }
2267 ASSERT_CONTAINS stdout "x=1"
2268 "#},
2269 },
2270 Example {
2271 name: "expand every match",
2272 fence_meta: None,
2273 code: indoc! {r#"
2274 # Single-line body; $x is a template path, WHO an override.
2275 IMPORT [STD]
2276 WRITE a.txt "hi \{{ env:WHO }}!"
2277 FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
2278
2279 ASSERT_CONTAINS stdout "hi World!"
2280 "#},
2281 },
2282 ],
2283 },
2284 CommandMeta {
2285 name: "IF",
2286 syntax: "IF <expr> { <commands> } [ELSE IF <expr> { <commands> } ...] [ELSE { <commands> }]",
2287 summary: "Conditional execution.",
2288 description: indoc! {r#"
2289 The condition is evaluated as a boolean expression.
2290
2291 Prefix `!` negates (`IF !false`); `&&` binds tighter than
2292 `||`, and both short-circuit, so `IF true || $missing`
2293 never evaluates the right side. Only Bool values are
2294 accepted as conditions.
2295 "#},
2296 args: &[],
2297 flags: &[],
2298 default_output: None,
2299 examples: &[
2300 Example {
2301 name: "if else",
2302 fence_meta: None,
2303 code: indoc! {r#"
2304 IMPORT [STD]
2305
2306 # True branch runs; the false branch is skipped.
2307 IF true {
2308 WRITE yes.txt taken
2309 } ELSE {
2310 WRITE yes.txt skipped
2311 }
2312
2313 # ELSE IF selects the first true branch.
2314 IF false {
2315 WRITE skipped.txt no
2316 } ELSE IF true {
2317 WRITE fallback.txt taken
2318 }
2319
2320 # !false evaluates to true, so this branch runs.
2321 IF !false {
2322 WRITE negated.txt taken
2323 }
2324
2325 LET $yes_body: STRING = READ yes.txt
2326 LET $fallback_body: STRING = READ fallback.txt
2327 LET $negated_body: STRING = READ negated.txt
2328 ASSERT_EQ $yes_body "taken"
2329 ASSERT_EQ $fallback_body "taken"
2330 ASSERT_EQ $negated_body "taken"
2331 LET $t: STRING = PATH_TYPE("skipped.txt")
2332 ASSERT_EQ $t "absent"
2333 "#},
2334 },
2335 Example {
2336 name: "logical condition composition",
2337 fence_meta: None,
2338 code: indoc! {r#"
2339 IMPORT [STD]
2340 LET $role: STRING = "admin"
2341 LET $level: INT = 3
2342
2343 # || is true when either side holds; && needs both.
2344 IF $role == "owner" || $level >= 5 {
2345 WRITE unexpected.txt no
2346 } ELSE {
2347 WRITE fallback.txt or-false
2348 }
2349
2350 LET $fb: STRING = READ fallback.txt
2351 ASSERT_EQ $fb "or-false"
2352 LET $t1: STRING = PATH_TYPE("unexpected.txt")
2353 ASSERT_EQ $t1 "absent"
2354
2355 IF $role == "admin" || $level >= 5 {
2356 WRITE chosen.txt or-true
2357 }
2358
2359 LET $ch: STRING = READ chosen.txt
2360 ASSERT_EQ $ch "or-true"
2361
2362 IF $role == "admin" && $level >= 5 {
2363 WRITE unexpected-too.txt no
2364 } ELSE {
2365 WRITE and.txt and-false
2366 }
2367
2368 LET $an: STRING = READ and.txt
2369 ASSERT_EQ $an "and-false"
2370 LET $t2: STRING = PATH_TYPE("unexpected-too.txt")
2371 ASSERT_EQ $t2 "absent"
2372 "#},
2373 },
2374 ],
2375 },
2376 CommandMeta {
2377 name: "LET",
2378 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> }",
2379 summary: "Bind script-local variables.",
2380 description: indoc! {r#"
2381 Declares a script-local variable with an explicit type (STRING, INT,
2382 FLOAT, BOOL, PIPE, LIST, MAP, HANDLE, DURATION, PATH). Duplicate LET
2383 in the same scope frame is a redeclaration error; mutate with
2384 `$var = <expr>`.
2385
2386 Variables are usable in templates (`{{ $var }}`), guards, and
2387 expressions. With `ASYNC`, spawns a background task and stores its
2388 handle (see ASYNC). The `$` sigil on the name is mandatory.
2389
2390 No hoisting: a variable exists only after its LET runs, in
2391 execution order. Reading `$var` before its LET (or after the
2392 block that declared it exits) fails with
2393 `undefined variable $var`. Scopes are a stack of frames and
2394 resolution walks innermost outward, so nothing pre-declares
2395 names. Function bodies read outer variables through the same
2396 walk, but their own LETs never leak out (see FUNC).
2397
2398 The right-hand side is always an expression — literals, lists, maps,
2399 arithmetic (`+ - * /` with `*`/`/` binding tighter, unary `-`,
2400 parentheses), comparisons (`< <= > >=` binding tighter than
2401 `== !=`), logical `&&` (tighter) and `||` with short-circuit,
2402 `!` negation, `env:KEY` reads, `INSPECT($var)` snapshots,
2403 `GLOB("*.md")`, `INT(x)` / `FLOAT(x)` conversions — never a
2404 `{{ ... }}` template; interpolation happens in string values,
2405 not here.
2406 The one exception is pipes: `LET $p: PIPE` with no `=`
2407 and no initializer mints a fresh anonymous backend,
2408 lazily materialized at first binding, so two declarations
2409 never share a channel.
2410
2411 Numbers are numeric literals: `42` binds `INT`, `3.14` binds
2412 `FLOAT`. `Int x Int` stays `INT` (checked, integer division,
2413 so `7 / 2` is `3`); any `Float` operand promotes to `FLOAT`.
2414 Division by zero, overflow, and non-finite results are errors.
2415 Both numeric sides compare numerically (`1 == 1.0` is true);
2416 otherwise `==`/`!=` compare rendered strings and ordering on
2417 non-numerics is a Type Error. Constant subtrees fold at parse
2418 time and dynamic arithmetic compiles to flat RPN with
2419 identical semantics.
2420
2421 Float equality is exact with no epsilon. Floats store decimals
2422 in binary, so a value is exact only when its reduced fraction
2423 has a power-of-2 denominator: 0.5 (1/2), 0.25 (1/4), 0.75
2424 (3/4) are exact, while 0.1 (1/10), 0.2 (1/5), 0.3 (3/10)
2425 repeat forever in binary (like 1/3 in decimal) and truncate,
2426 so `0.1 + 0.2 == 0.3` is false (the sum is
2427 `0.30000000000000004`). Rule of thumb: endings .5, .25, .75,
2428 .125, .625, .875 are exact; .1, .2, .3 and similar are
2429 approximations. Bound approximations instead of comparing
2430 them: `IF $sum > 0.299999 && $sum < 0.300001`.
2431
2432 Comparisons do not chain: `a < b < c` is a parse error, not
2433 `(a < b) < c`. Chaining would compare a `BOOL` against a
2434 number (a runtime Type Error in C-style parsing) or evaluate
2435 the middle term twice (Python-style chaining), so the grammar
2436 accepts exactly one comparison operator per level. Write the
2437 conjunction explicitly: `$a < $b && $b < $c`. The same holds
2438 for equality (`$a == $b == $c` is rejected).
2439
2440 Captured command output is a string, so convert before math:
2441 `LET $total: INT = $total + INT($size_str)` (`INT` trims ASCII
2442 whitespace; `FLOAT` accepts int strings and rejects
2443 non-finite).
2444
2445 Bare words need no quotes: `LET $d: STRING = 30s` binds the same string
2446 as quoted.
2447
2448 When the right-hand side is a synchronous command
2449 (`LET $out: STRING = ECHO hi`), the command runs to completion and its
2450 exact stdout bytes are captured into the variable as a string (no newline
2451 stripping; commands with no stdout capture as `""`; non-UTF8 stdout is
2452 an error). Combining capture with an explicit
2453 `WITH_IO [stdout=$var]` is a parse error.
2454
2455 Coming from Bash, the capture line looks familiar but behaves
2456 strictly:
2457
2458 | | Bash `output=$(...)` | OxDock `LET $out: STRING = ...` |
2459 | --- | --- | --- |
2460 | Trailing newlines | Stripped (all of them) | Preserved byte-exact |
2461 | Variable type | Always an untyped string | Declared: STRING, INT, FLOAT, ... |
2462 | Math on output | Implicit: `$((var + 1))` | Explicit: `INT($out) + 1` |
2463 | Failing command | Continues with empty output unless `set -e` | Step fails immediately, binds nothing |
2464
2465 `LET $out: TYPE = AWAIT $var` binds the background task's
2466 explicit `RETURN` value instead (tasks stream their stdout
2467 live, so there is no output left to capture); a task that
2468 succeeded without `RETURN` yields `INT` 0, like a process
2469 exit status.
2470
2471 An inline block (`LET $var: TYPE = { <commands> }`) runs its
2472 steps in a fresh scope and binds the nearest `RETURN` value,
2473 like a zero-arg function body: fallthrough without `RETURN`
2474 binds `""`, and `BREAK`/`CONTINUE` escaping the block are
2475 errors. Think IIFE: the block executes immediately where it
2476 stands and its value is the result. The block reads outer
2477 variables but its own LETs never leak out. A `{k: v}` shape
2478 still parses as a map literal; anything else in braces is
2479 a block.
2480
2481 The split is deliberate: synchronous commands capture
2482 stdout because they run inline to completion on the same
2483 thread; background tasks never capture stdout because
2484 concurrent output has no well-defined value. Task results
2485 travel only through `RETURN` (or `INT` 0 for void tasks).
2486
2487 `LET $e: STRING = env:FOO` reads the script environment into a plain
2488 string.
2489 "#},
2490 args: &[],
2491 flags: &[],
2492 default_output: None,
2493 examples: &[
2494 Example {
2495 name: "let",
2496 fence_meta: None,
2497 code: indoc! {r#"
2498 LET $name: STRING = "world"
2499 ECHO "hello, {{ $name }}"
2500 ASSERT_CONTAINS stdout "hello, world"
2501
2502 LET $items: LIST<STRING> = ["a", "b"]
2503 ASSERT_CONTAINS $items "a"
2504 ASSERT_CONTAINS $items "b"
2505
2506 LET $count: INT = 42
2507 ASSERT_EQ $count 42
2508 "#},
2509 },
2510 Example {
2511 name: "no hoisting",
2512 fence_meta: Some("expect_error:\"undefined variable\""),
2513 code: indoc! {r#"
2514 # Reading before the LET runs is an error, not an empty value.
2515 ECHO $too_early
2516 LET $too_early: STRING = "too late"
2517 "#},
2518 },
2519 Example {
2520 name: "glob binding",
2521 fence_meta: None,
2522 code: indoc! {r#"
2523 # The RHS is an expression: GLOB(...) runs and binds a list.
2524 IMPORT [STD]
2525 WRITE a.txt "x"
2526 LET $files: LIST<STRING> = GLOB("*.txt")
2527 FOR $f: STRING IN $files { ECHO $f }
2528
2529 ASSERT_CONTAINS stdout "a.txt"
2530 "#},
2531 },
2532 Example {
2533 name: "scoped variable reverts",
2534 fence_meta: None,
2535 code: indoc! {r#"
2536 # LET inside a braced block reverts when the block exits.
2537 LET $a: STRING = "outer"
2538
2539 [bool:true] {
2540 LET $a: STRING = "inner"
2541 WRITE inner.txt "{{ $a }}"
2542 }
2543
2544 WRITE outer.txt "{{ $a }}"
2545
2546 LET $in_body: STRING = READ inner.txt
2547 ASSERT_EQ $in_body "inner"
2548
2549 LET $out_body: STRING = READ outer.txt
2550 ASSERT_EQ $out_body "outer"
2551 "#},
2552 },
2553 Example {
2554 name: "capture command output",
2555 fence_meta: None,
2556 code: indoc! {r#"
2557 # Capture keeps the trailing newline.
2558 LET $out: STRING = ECHO hi
2559 ASSERT_EQ $out "hi\n"
2560 "#},
2561 },
2562 Example {
2563 name: "inline block",
2564 fence_meta: None,
2565 code: indoc! {r#"
2566 LET $who: STRING = "ada"
2567
2568 # An inline block binds its RETURN value like a function body.
2569 LET $res: STRING = {
2570 LET $loud: STRING = "{{ $who }}!"
2571 RETURN $loud
2572 }
2573 ASSERT_EQ $res "ada!"
2574
2575 # Any declared type works: the block value checks like any RHS.
2576 LET $n: INT = {
2577 RETURN 40 + 2
2578 }
2579 ASSERT_EQ $n 42
2580 "#},
2581 },
2582 Example {
2583 name: "arithmetic over captured output",
2584 fence_meta: None,
2585 code: indoc! {r#"
2586 # Captured output converts explicitly: INT() then arithmetic.
2587 IMPORT [STD]
2588 LET $size_str: STRING = ECHO 41
2589 LET $total: INT = INT($size_str) + 1
2590 ASSERT_EQ $total 42
2591
2592 # FLOAT() promotes instead of truncating.
2593 LET $ratio: FLOAT = 1 + 2.5
2594 ASSERT_EQ $ratio 3.5
2595
2596 # Int x Int stays INT: integer division truncates.
2597 LET $half: INT = 7 / 2
2598 ASSERT_EQ $half 3
2599 "#},
2600 },
2601 Example {
2602 name: "float equality is exact",
2603 fence_meta: None,
2604 code: indoc! {r#"
2605 # Binary fractions compare cleanly; decimal fractions may not:
2606 # 0.1 + 0.2 is 0.30000000000000004, so == is false.
2607 IMPORT [STD]
2608 LET $exact: BOOL = 0.5 + 0.25 == 0.75
2609 LET $decimal: BOOL = 0.1 + 0.2 == 0.3
2610 IF $exact {
2611 WRITE exact.txt yes
2612 }
2613 IF $decimal {
2614 WRITE unexpected.txt no
2615 }
2616
2617 LET $ok: STRING = READ exact.txt
2618 ASSERT_EQ $ok "yes"
2619
2620 LET $t: STRING = PATH_TYPE("unexpected.txt")
2621 ASSERT_EQ $t "absent"
2622 "#},
2623 },
2624 Example {
2625 name: "bound inexact decimals",
2626 fence_meta: None,
2627 code: indoc! {r#"
2628 # Never test inexact decimals for equality; bound them.
2629 LET $sum: FLOAT = 0.1 + 0.2
2630 IF $sum > 0.299999 && $sum < 0.300001 {
2631 WRITE bounded.txt yes
2632 }
2633
2634 LET $ok: STRING = READ bounded.txt
2635 ASSERT_EQ $ok "yes"
2636 "#},
2637 },
2638 Example {
2639 name: "inspect a variable",
2640 fence_meta: None,
2641 code: indoc! {r#"
2642 # INSPECT($var) snapshots a variable into a MAP: declared
2643 # type plus live details (pipe backend stats here), so
2644 # scripts can branch on engine state.
2645 IMPORT [STD]
2646 LET $p: PIPE
2647 WITH_IO [stdout=$p] ECHO hello
2648 LET $info: MAP<ANY> = INSPECT($p)
2649 IF $info.is_os_pipe {
2650 WRITE unexpected.txt "should be a script pipe"
2651 }
2652
2653 ASSERT_EQ $info.type "PIPE"
2654 LET $t: STRING = PATH_TYPE("unexpected.txt")
2655 ASSERT_EQ $t "absent"
2656 "#},
2657 },
2658 ],
2659 },
2660 CommandMeta {
2661 name: "MUTATION",
2662 syntax: "$var = <expr>",
2663 summary: "Mutate a declared variable.",
2664 description: indoc! {r#"
2665 Reassigns an existing variable, converting the new value to
2666 the type declared at LET time. The explicit annotation is
2667 what authorizes string-to-number conversion here (`$n = "42"`
2668 binds 42 for an INT); a non-numeric string is an error.
2669 Expressions never convert: `"100" + 1` is a Type Error, use
2670 `INT()` / `FLOAT()` to cross that boundary explicitly.
2671
2672 The leading `$` distinguishes mutation from `KEY=value` command
2673 assignments. Assigning an undeclared variable or a mismatched type is
2674 an error.
2675
2676 Mutation writes through to the scope where the variable was
2677 declared, so it survives block exit: `LET $x` outside a block
2678 followed by `$x = ...` inside still reads back the new value
2679 afterwards, for every type. This is the counterpart to LET
2680 shadowing, where `LET $x` *inside* the block declares a
2681 separate inner variable that reverts on exit.
2682
2683 Reassignment rebinds the variable to a new value: values
2684 captured earlier keep the old word (see the rebinding
2685 example below).
2686 "#},
2687 args: &[],
2688 flags: &[],
2689 default_output: None,
2690 examples: &[
2691 Example {
2692 name: "mutate",
2693 fence_meta: None,
2694 code: indoc! {r#"
2695 # Mutation writes through: the binding holds the new value.
2696 LET $count: INT = 1
2697 $count = 2
2698 ASSERT_EQ $count 2
2699 "#},
2700 },
2701 Example {
2702 name: "rebind keeps earlier captures",
2703 fence_meta: None,
2704 code: indoc! {r#"
2705 # Reassignment rebinds: a map built from `$s` still
2706 # reads the original string after `$s` moves on.
2707 LET $s: STRING = "test"
2708 LET $m: MAP<ANY> = {a: $s}
2709 $s = "changed"
2710 ASSERT_EQ $m.a "test"
2711
2712 # Appending to one list binding never touches its clones.
2713 LET $a: LIST<STRING> = ["1"]
2714 LET $b: LIST<STRING> = $a
2715 LIST_APPEND $a "2"
2716 LET $want: LIST<STRING> = ["1"]
2717 ASSERT_EQ $b $want
2718 "#},
2719 },
2720 Example {
2721 name: "convert before math",
2722 fence_meta: None,
2723 code: indoc! {r#"
2724 # Captured output is a string: `"100" + 1` is a Type Error.
2725 # Convert explicitly, then mutate with arithmetic.
2726 IMPORT [STD]
2727 LET $raw: STRING = ECHO 100
2728 LET $n: INT = INT($raw)
2729 $n = $n + 1
2730
2731 # The declared slot stays strict: strings parse only
2732 # through the explicit converter, never on assignment.
2733 $n = INT("42")
2734 ASSERT_EQ $n 42
2735
2736 # Same crossing for decimals via FLOAT().
2737 LET $frac_str: STRING = ECHO 2.5
2738 LET $f: FLOAT = FLOAT($frac_str) + 0.25
2739 ASSERT_EQ $f 2.75
2740 "#},
2741 },
2742 ],
2743 },
2744 CommandMeta {
2745 name: "ASYNC",
2746 syntax: "ASYNC <command...> | ASYNC { <commands> } | LET $var: HANDLE = ASYNC { <commands> }",
2747 summary: "Run steps in a background thread.",
2748 description: indoc! {r#"
2749 Runs a command or block of commands in a background thread with
2750 subshell isolation.
2751
2752 Mutations (ENV, WORKDIR) stay within the block. With `LET`, stores a
2753 task handle for `AWAIT`. Task output streams live to the parent
2754 stdout; a task publishes a value with an explicit `RETURN`,
2755 which `LET $out: TYPE = AWAIT $task` binds.
2756
2757 `WITH_IO` must wrap `ASYNC` from the outside (`LET $p: PIPE` first,
2758 then `WITH_IO [stdout=$p] ASYNC ...`) so pipe endpoints allocate on
2759 the main thread before the worker spawns. Placing `WITH_IO` directly
2760 inside `ASYNC` is rejected at parse time.
2761 "#},
2762 args: &[],
2763 flags: &[],
2764 default_output: None,
2765 examples: &[
2766 Example {
2767 name: "async",
2768 fence_meta: None,
2769 code: indoc! {r#"
2770 # Inline and block forms both run in the background; AWAIT joins them.
2771 ASYNC ECHO "warming-up"
2772 LET $a: HANDLE = ASYNC ECHO "first"
2773 LET $b: HANDLE = ASYNC {
2774 ECHO "second"
2775 }
2776 AWAIT $a
2777 AWAIT $b
2778 ASSERT_CONTAINS stdout "first"
2779 ASSERT_CONTAINS stdout "second"
2780 "#},
2781 },
2782 Example {
2783 name: "async task handle",
2784 fence_meta: None,
2785 code: indoc! {r#"
2786 LET $task: HANDLE = ASYNC {
2787 ECHO "built"
2788 }
2789 AWAIT $task
2790 ASSERT_CONTAINS stdout "built"
2791 "#},
2792 },
2793 ],
2794 },
2795 CommandMeta {
2796 name: "AWAIT",
2797 syntax: "AWAIT $var | LET $out: STRING = AWAIT $var",
2798 summary: "Join a background task.",
2799 description: indoc! {r#"
2800 Blocks until the named task completes. Propagates errors if the task failed.
2801
2802 Task output streams live during the run; joining binds nothing by
2803 itself. `LET $out: TYPE = AWAIT $var` binds the task's explicit
2804 `RETURN` value instead, or `INT` 0 when the task succeeded
2805 without one (add `RETURN <expr>` to the task body to yield
2806 a value).
2807 "#},
2808 args: &[],
2809 flags: &[],
2810 default_output: None,
2811 examples: &[
2812 Example {
2813 name: "await",
2814 fence_meta: None,
2815 code: indoc! {r#"
2816 LET $task: HANDLE = ASYNC ECHO "done"
2817 AWAIT $task
2818 ASSERT_CONTAINS stdout "done"
2819 "#},
2820 },
2821 Example {
2822 name: "await capture",
2823 fence_meta: None,
2824 code: indoc! {r#"
2825 LET $task: HANDLE = ASYNC {
2826 ECHO "logged"
2827 RETURN "returned"
2828 }
2829
2830 # AWAIT binds the RETURN value, not the streamed output.
2831 LET $out: STRING = AWAIT $task
2832 ASSERT_EQ $out "returned"
2833 "#},
2834 },
2835 ],
2836 },
2837 CommandMeta {
2838 name: "CANCEL",
2839 syntax: "CANCEL $var",
2840 summary: "Synchronously cancel a background task.",
2841 description: indoc! {r#"
2842 Kills the named background task spawned via LET $var: HANDLE = ASYNC ....
2843
2844 Blocking: returns only after the task thread has been joined and its OS
2845 process reaped, so no residual filesystem or stream mutation follows. A
2846 later AWAIT $var reports cancellation. Only named tasks can be cancelled.
2847 "#},
2848 args: &[],
2849 flags: &[],
2850 default_output: None,
2851 examples: &[
2852 Example {
2853 name: "cancel",
2854 fence_meta: None,
2855 code: indoc! {r#"
2856 LET $task: HANDLE = ASYNC SLEEP 30s
2857 CANCEL $task
2858 "#},
2859 },
2860 Example {
2861 name: "await after cancel reports cancellation",
2862 fence_meta: Some("expect_error:\"was cancelled\""),
2863 code: indoc! {r#"
2864 # A cancelled task stays cancelled: joining it reports.
2865 LET $task: HANDLE = ASYNC SLEEP 30s
2866 CANCEL $task
2867 AWAIT $task
2868 "#},
2869 },
2870 ],
2871 },
2872 CommandMeta {
2873 name: "TIMEOUT",
2874 syntax: "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> } | TIMEOUT <duration> AWAIT $var",
2875 summary: "Enforce an execution deadline.",
2876 description: indoc! {r#"
2877 Aborts the wrapped step or block with a deadline error if it exceeds the
2878 duration (e.g. 500ms, 10s, 2m; a bare number means seconds).
2879
2880 A blocking foreground process is killed.
2881
2882 ASYNC composes in either nesting order with order-dependent deadline
2883 semantics: `LET $task: HANDLE = ASYNC TIMEOUT 30s RUN "build"` enforces
2884 the deadline inside the background thread (a later `AWAIT $task`
2885 surfaces the `TIMEOUT` error), while `TIMEOUT 30s AWAIT $task`
2886 preempts a hung task from the awaiting side.
2887 "#},
2888 args: &[],
2889 flags: &[],
2890 default_output: None,
2891 examples: &[
2892 Example {
2893 name: "timeout",
2894 fence_meta: None,
2895 code: indoc! {r#"
2896 TIMEOUT 30s WRITE heartbeat.txt alive
2897 LET $beat: STRING = READ heartbeat.txt
2898 ASSERT_EQ $beat "alive"
2899 "#},
2900 },
2901 Example {
2902 name: "timeout block",
2903 fence_meta: None,
2904 code: indoc! {r#"
2905 TIMEOUT 30s {
2906 WRITE a.txt one
2907 WRITE b.txt two
2908 }
2909 LET $a: STRING = READ a.txt
2910 LET $b: STRING = READ b.txt
2911 ASSERT_EQ $a "one"
2912 ASSERT_EQ $b "two"
2913 "#},
2914 },
2915 Example {
2916 name: "deadline aborts the step",
2917 fence_meta: Some("expect_error:\"TIMEOUT after\""),
2918 code: indoc! {r#"
2919 # 50ms expires long before the sleep does: the step dies
2920 # with a deadline error instead of running out the clock.
2921 TIMEOUT 50ms SLEEP 30s
2922 "#},
2923 },
2924 Example {
2925 name: "timeout variable duration",
2926 fence_meta: None,
2927 code: indoc! {r#"
2928 # Durations resolve at runtime, so variables work too.
2929 LET $budget: DURATION = "30s"
2930 TIMEOUT $budget WRITE heartbeat.txt alive
2931
2932 LET $beat: STRING = READ heartbeat.txt
2933 ASSERT_EQ $beat "alive"
2934 "#},
2935 },
2936 Example {
2937 name: "timeout await",
2938 fence_meta: None,
2939 code: indoc! {r#"
2940 # AWAIT form bounds a task join instead of a step.
2941 LET $quick: HANDLE = ASYNC {
2942 ECHO hi
2943 }
2944 TIMEOUT 30s AWAIT $quick
2945 "#},
2946 },
2947 ],
2948 },
2949 CommandMeta {
2950 name: "ISOLATED",
2951 syntax: "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>",
2952 summary: "Run steps with the seeded script environment.",
2953 description: indoc! {r#"
2954 Resets the script environment for the block to the session
2955 seed: spawned children see the sandbox defaults plus names
2956 the block re-adds through its leading `INHERIT_ENV`.
2957
2958 The allowlist resolves against the outer scope, never the
2959 host. Absent names stay absent silently, matching top-level
2960 `INHERIT_ENV`.
2961
2962 Script variables, pipes, and files flow through untouched;
2963 only `env:` is reset. Files share the session workspace:
2964 blocks selecting the same `WORKSPACE` target resolve to the
2965 same directory with no per-block overlay, so one block's
2966 writes are visible to another.
2967
2968 Blocks nest (each level re-seeds from the same seed, so
2969 nesting only narrows through the allowlists) and compose
2970 with `ASYNC` and `FUNC`. Scope exit restores the prior
2971 environment.
2972 "#},
2973 args: &[],
2974 flags: &[],
2975 default_output: None,
2976 examples: &[
2977 Example {
2978 name: "isolated scope",
2979 fence_meta: None,
2980 code: indoc! {r#"
2981 # The block sees a clean env; plain steps still run and
2982 # outer bindings survive untouched.
2983 ENV MODE=outer
2984 ISOLATED {
2985 ENV MODE=inner
2986 WRITE inner.txt "{{ env:MODE }}"
2987 }
2988 LET $back: STRING = "{{ env:MODE }}"
2989 ASSERT_EQ $back "outer"
2990 LET $body: STRING = READ inner.txt
2991 ASSERT_EQ $body "inner"
2992 "#},
2993 },
2994 Example {
2995 name: "reseeded child env",
2996 fence_meta: None,
2997 code: indoc! {r#"
2998 # The block resets to the session seed: plain steps and
2999 # spawns run with zero prelude, while outer customs
3000 # stay out.
3001 ENV OUTER_CUSTOM=outer-val
3002 WRITE top-path.txt "{{ env:PATH }}"
3003 ISOLATED {
3004 WRITE inner-path.txt "{{ env:PATH }}"
3005 WRITE inner-custom.txt "{{ env:OUTER_CUSTOM }}"
3006 RUN "echo seed-ok"
3007 }
3008 LET $top: STRING = READ top-path.txt
3009 LET $inner: STRING = READ inner-path.txt
3010 ASSERT_EQ $inner $top
3011 LET $custom: STRING = READ inner-custom.txt
3012 ASSERT_EQ $custom ""
3013 ASSERT_CONTAINS stdout "seed-ok"
3014 "#},
3015 },
3016 Example {
3017 name: "absent names stay absent",
3018 fence_meta: None,
3019 code: indoc! {r#"
3020 # Listing a name the outer scope lacks is not an error:
3021 # the block simply runs without it.
3022 ISOLATED {
3023 INHERIT_ENV [OXDOC_DEFINITELY_ABSENT_12345]
3024 ECHO still-runs
3025 }
3026 ASSERT_CONTAINS stdout "still-runs"
3027 "#},
3028 },
3029 Example {
3030 name: "nesting narrows",
3031 fence_meta: None,
3032 code: indoc! {r#"
3033 # Each level snapshots the already-scrubbed parent, so
3034 # an inner block cannot recover what the outer dropped.
3035 ENV KEEP=yes
3036 ISOLATED {
3037 INHERIT_ENV [KEEP]
3038 ISOLATED {
3039 ENV KEEP=inner
3040 WRITE deep.txt "{{ env:KEEP }}"
3041 }
3042 LET $mid: STRING = "{{ env:KEEP }}"
3043 ASSERT_EQ $mid "yes"
3044 }
3045 LET $deep: STRING = READ deep.txt
3046 ASSERT_EQ $deep "inner"
3047 "#},
3048 },
3049 ],
3050 },
3051 CommandMeta {
3052 name: "REMOTE",
3053 syntax: "REMOTE <target> [[$var, ...] [env:NAME, ...]] { <commands> }",
3054 summary: "Run a sealed block on a remote target.",
3055 description: indoc! {r#"
3056 Runs the braced block on the named remote target, which the
3057 host binds at startup (`--remote`). The block is sealed:
3058 only header-listed `$var` and `env:NAME` entries cross, the
3059 guest starts empty, and results return through declared
3060 transfers or `WITH_IO` pipes.
3061
3062 The target is a static literal, never a variable. Unknown
3063 targets fail before execution starts.
3064
3065 Bodies check twice: the host static pass validates the
3066 body before anything ships, and the guest re-validates on
3067 arrival through the same entry point, so a body type error
3068 fails locally, never mid-run on the remote.
3069
3070 A failing guest fails the host step: EXIT in the body
3071 exits the guest, and the host relays the code to its own
3072 process exit status (see EXIT).
3073 "#},
3074 args: &[],
3075 flags: &[],
3076 default_output: None,
3077 examples: &[
3078 Example {
3079 name: "sealed header values cross, outer scope does not",
3080 fence_meta: Some("mock_remote:prod"),
3081 code: indoc! {r#"
3082 # Only header-listed names arrive: `$version` is visible
3083 # on the guest, `$secret` was never sent.
3084 LET $version: STRING = "1.2.3"
3085 LET $secret: STRING = "host-only"
3086 REMOTE prod [$version] {
3087 WRITE version.txt "{{ $version }}"
3088 COPY --to-host ./version.txt back.txt
3089 }
3090
3091 # The pushed file proves the guest saw the injected value.
3092 LET $back: STRING = READ back.txt
3093 ASSERT_EQ $back "1.2.3"
3094 "#},
3095 },
3096 Example {
3097 name: "background tasks stream through shared pipes",
3098 fence_meta: Some("mock_remote:prod"),
3099 code: indoc! {r#"
3100 # Two background REMOTEs share one capture pipe while a
3101 # WITH_IO block holds the write end open.
3102 IMPORT [STD]
3103 LET $cap: PIPE
3104 WITH_IO [stdout=$cap] {
3105 LET $a: HANDLE = ASYNC REMOTE prod {
3106 ECHO "from-a"
3107 }
3108 LET $b: HANDLE = ASYNC REMOTE prod {
3109 ECHO "from-b"
3110 }
3111 AWAIT $a
3112 AWAIT $b
3113 }
3114
3115 # EOF ends the drain: no sentinel line, no baked-in count.
3116 LET $n: INT = 0
3117 WHILE !EOF($cap) {
3118 WITH_IO [stdin=$cap] READ_LINE $line
3119 $n = $n + 1
3120 }
3121 ASSERT_EQ $n 2
3122 "#},
3123 },
3124 Example {
3125 name: "declared files cross both directions",
3126 fence_meta: Some("mock_remote:prod roots:unified"),
3127 code: indoc! {r#"
3128 # Fetches ride in, pushes ride back. Anything undeclared
3129 # never leaves its side.
3130 WRITE send.txt "payload"
3131 REMOTE prod {
3132 COPY --from-host ./send.txt got.txt
3133 LET $v: STRING = READ got.txt
3134 ASSERT_EQ $v "payload"
3135 WRITE back.txt "returned"
3136 COPY --to-host ./back.txt back.txt
3137 }
3138
3139 # The push landed on the host; guest staging is gone.
3140 LET $b: STRING = READ back.txt
3141 ASSERT_EQ $b "returned"
3142 "#},
3143 },
3144 Example {
3145 name: "guest workspace selection stays on the guest",
3146 fence_meta: Some("mock_remote:prod"),
3147 code: indoc! {r#"
3148 # WORKSPACE switches inside the block resolve against the
3149 # guest staging dir, which serves as both the SNAPSHOT
3150 # root and the LOCAL build context. The host selection
3151 # restores when the block exits.
3152 REMOTE prod {
3153 WORKSPACE SNAPSHOT
3154 WRITE out.txt "from-snapshot"
3155 COPY --to-host ./out.txt snap.txt
3156 }
3157
3158 LET $s: STRING = READ snap.txt
3159 ASSERT_EQ $s "from-snapshot"
3160 "#},
3161 },
3162 Example {
3163 name: "guest cache persists across execs",
3164 fence_meta: Some("mock_remote:prod"),
3165 code: indoc! {r#"
3166 # WORKSPACE CACHE addresses guest-local persistent
3167 # storage: the second block reads what the first wrote,
3168 # while the guest staging starts empty every time.
3169 REMOTE prod {
3170 WORKSPACE CACHE
3171 WRITE marker.txt "run-marker"
3172 }
3173 REMOTE prod {
3174 WORKSPACE CACHE
3175 LET $m: STRING = READ marker.txt
3176 ASSERT_EQ $m "run-marker"
3177 }
3178 "#},
3179 },
3180 Example {
3181 name: "pushes outside staging fail closed",
3182 fence_meta: Some("mock_remote:prod expect_error:\"escapes staging\""),
3183 code: indoc! {r#"
3184 # WORKSPACE SYSTEM exposes the whole guest machine, but
3185 # transfers stay staging scoped: a push source outside
3186 # staging fails loudly instead of crossing.
3187 REMOTE prod {
3188 WORKSPACE SYSTEM
3189 COPY --to-host /no/such/file.txt got.txt
3190 }
3191 "#},
3192 },
3193 Example {
3194 name: "guest exit fails the step, host survives",
3195 fence_meta: Some(
3196 "mock_remote:prod expect_error:\"REMOTE 'prod' exited with code 3\"",
3197 ),
3198 code: indoc! {r#"
3199 # EXIT in the body exits the guest with code 3. The
3200 # host is unaffected: it keeps executing after the
3201 # guest is already dead, and the failure surfaces as
3202 # a host step error carrying the same code. The CLI
3203 # then exits with it, so the guest code reaches the OS.
3204 LET $t: HANDLE = ASYNC REMOTE prod {
3205 EXIT 3
3206 }
3207 WRITE host-alive.txt "still here"
3208 AWAIT $t
3209 "#},
3210 },
3211 Example {
3212 name: "remote block without a runner",
3213 fence_meta: Some("expect_error:\"has no registered session\""),
3214 code: indoc! {r#"
3215 # Without a bound session, the block bails instead of
3216 # executing anywhere unexpected.
3217 REMOTE prod {
3218 ECHO "do something on remote"
3219 }
3220 "#},
3221 },
3222 ],
3223 },
3224 CommandMeta {
3225 name: "FUNC",
3226 syntax: "FUNC NAME([$param: TYPE, ...]) { <commands> }",
3227 summary: "Define a user function.",
3228 description: indoc! {r#"
3229 Defines a user function with UPPERCASE name and explicitly typed
3230 parameters.
3231
3232 Params bind by position, converting each argument to its
3233 declared parameter type before the body runs.
3234 Bodies run in a fresh variable scope; LETs inside do not leak. A nested
3235 FUNC definition is scoped to its block and reverts on exit. Names share
3236 one namespace with native and host-registered functions, which a FUNC
3237 may never shadow.
3238
3239 Functions resolve like variables: a name is visible from its
3240 definition line, so recursion works but mutual recursion does
3241 not (the second name does not exist while the first body
3242 lowers). Calls name their module (`STD::GLOB(...)`) unless
3243 imported; see IMPORT.
3244
3245 Invoke any function with one syntax: `NAME(...)` as a statement
3246 (discarding the value) or `LET $var: TYPE = NAME(...)` to capture
3247 the RETURN value (fallthrough without RETURN captures as "").
3248 "#},
3249 args: &[],
3250 flags: &[],
3251 default_output: None,
3252 examples: &[
3253 Example {
3254 name: "func def call",
3255 fence_meta: None,
3256 code: indoc! {r#"
3257 FUNC GREET($name: STRING) {
3258 RETURN $name
3259 }
3260
3261 LET $res: STRING = GREET("ada")
3262 ASSERT_EQ $res "ada"
3263
3264 # Statement form: parens stay, the value drops.
3265 GREET("bex")
3266 "#},
3267 },
3268 Example {
3269 name: "call with pipes",
3270 fence_meta: None,
3271 code: indoc! {r#"
3272 # A pipe handle travels into a function as a typed argument
3273 # and is usable as a binding target in both directions.
3274 # `LET $p: PIPE` mints the handle; `$p` passes it on.
3275 FUNC DRAIN($q: PIPE) {
3276 WITH_IO [stdin=$q] READ_LINE $line
3277 RETURN $line
3278 }
3279
3280 LET $p: PIPE
3281 WITH_IO [stdout=$p] ECHO "payload"
3282
3283 LET $got: STRING = DRAIN($p)
3284 ASSERT_EQ $got "payload"
3285 "#},
3286 },
3287 ],
3288 },
3289 CommandMeta {
3290 name: "RETURN",
3291 syntax: "RETURN [<expr>]",
3292 summary: "Return a value from a function, task, or inline block.",
3293 description: indoc! {r#"
3294 Ends the nearest enclosing boundary with a value: a function
3295 call, an `ASYNC` task (bound by `LET $o = AWAIT $t`), or an
3296 inline `LET` block. Bare `RETURN` with no expression yields
3297 `""`.
3298
3299 Falling off the end without RETURN yields "". RETURN with no
3300 enclosing boundary (including at top level) is an error; use
3301 EXIT or ECHO there.
3302 "#},
3303 args: &[],
3304 flags: &[],
3305 default_output: None,
3306 examples: &[Example {
3307 name: "return",
3308 fence_meta: None,
3309 code: indoc! {r#"
3310 FUNC PICK($flag: BOOL) {
3311 IF $flag {
3312 RETURN "yes"
3313 }
3314 RETURN "no"
3315 }
3316
3317 LET $res: STRING = PICK(true)
3318 ASSERT_EQ $res "yes"
3319
3320 # Fallthrough without RETURN yields its own value.
3321 LET $no: STRING = PICK(false)
3322 ASSERT_EQ $no "no"
3323 "#},
3324 }],
3325 },
3326 CommandMeta {
3327 name: "WHILE",
3328 syntax: "WHILE <bool-expr> { <commands> }",
3329 summary: "Loop while a condition holds.",
3330 description: indoc! {r#"
3331 Re-evaluates a Bool condition each iteration (same is_truthy rule as IF;
3332 non-Bool is a type error).
3333
3334 Each iteration runs in a fresh scope; mutate outer state with $var = ...
3335 so the next check observes it. BREAK exits the loop; CONTINUE skips to
3336 the next check.
3337 "#},
3338 args: &[],
3339 flags: &[],
3340 default_output: None,
3341 examples: &[Example {
3342 name: "while loop",
3343 fence_meta: None,
3344 code: indoc! {r#"
3345 # The condition re-evaluates every iteration: three passes, then stop.
3346 LET $n: INT = 0
3347 WHILE $n < 3 {
3348 WRITE tick.txt "{{ $n }}"
3349 $n = $n + 1
3350 }
3351
3352 ASSERT_EQ $n 3
3353 LET $tick: STRING = READ tick.txt
3354 ASSERT_EQ $tick "2"
3355 "#},
3356 }],
3357 },
3358 CommandMeta {
3359 name: "BREAK",
3360 syntax: "BREAK",
3361 summary: "Exit the innermost loop.",
3362 description: indoc! {r#"
3363 Exits the innermost enclosing FOR or WHILE loop.
3364
3365 BREAK outside a loop, or across a FUNC or ASYNC boundary, is an error.
3366 "#},
3367 args: &[],
3368 flags: &[],
3369 default_output: None,
3370 examples: &[Example {
3371 name: "break",
3372 fence_meta: None,
3373 code: indoc! {r#"
3374 # BREAK leaves after the first pass: only "a" is written.
3375 FOR $x: STRING IN ["a", "b"] {
3376 WRITE picked.txt "{{ $x }}"
3377 BREAK
3378 }
3379
3380 LET $body: STRING = READ picked.txt
3381 ASSERT_EQ $body "a"
3382 "#},
3383 }],
3384 },
3385 CommandMeta {
3386 name: "CONTINUE",
3387 syntax: "CONTINUE",
3388 summary: "Skip to the next loop iteration.",
3389 description: indoc! {r#"
3390 Skips the rest of the innermost enclosing FOR or WHILE body and starts
3391 the next iteration.
3392
3393 CONTINUE outside a loop, or across a FUNC or ASYNC boundary, is an error.
3394 "#},
3395 args: &[],
3396 flags: &[],
3397 default_output: None,
3398 examples: &[Example {
3399 name: "continue",
3400 fence_meta: None,
3401 code: indoc! {r#"
3402 # CONTINUE skips the write on "a": only "b" lands.
3403 FOR $x: STRING IN ["a", "b"] {
3404 IF $x == "a" {
3405 CONTINUE
3406 }
3407 WRITE picked.txt "{{ $x }}"
3408 }
3409
3410 LET $body: STRING = READ picked.txt
3411 ASSERT_EQ $body "b"
3412 "#},
3413 }],
3414 },
3415 CommandMeta {
3416 name: KEYWORD_IMPORT,
3417 syntax: "IMPORT [<module>, ...] | IMPORT <module>",
3418 summary: "Bring module functions into bare-call scope.",
3419 description: indoc! {r#"
3420 Every function call names its module (`STD::GLOB(...)`,
3421 `MOCK::READ_CSV(...)`) unless the module is imported:
3422 `IMPORT [STD]` lets the rest of the scope call `GLOB(...)`
3423 bare. Calls resolve at parse time against `SCRIPT`
3424 definitions first, then imported modules; unknown modules,
3425 unknown functions, and unimported bare calls are parse
3426 errors, never runtime surprises.
3427
3428 IMPORT is a lowering directive, not a step: it applies from
3429 its line to the enclosing block exit, then reverts, exactly
3430 like `LET` scoping but with no runtime footprint. Guards do
3431 not apply to it. Two imported modules exporting one name is
3432 an ambiguity error: qualify the call instead.
3433
3434 `EXPORT` marks top-level script `FUNC`s as externally
3435 callable tools (`EXPORT FOO`, `EXPORT [FOO, BAR]`).
3436 Single-file scope; see the MCP host for consumption.
3437 "#},
3438 args: &[],
3439 flags: &[],
3440 default_output: None,
3441 examples: &[Example {
3442 name: "import",
3443 fence_meta: None,
3444 code: indoc! {r#"
3445 # Calls name their module (STD::GLOB); IMPORT [STD] drops the prefix.
3446 WRITE a.txt "hi \{{ env:WHO }}!"
3447 IMPORT [STD]
3448 FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
3449 ASSERT_CONTAINS stdout "hi World!"
3450 "#},
3451 }],
3452 },
3453 ]
3454}
3455
3456impl fmt::Display for StepKind {
3459 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3460 match self {
3461 StepKind::InheritEnv { keys } => write!(f, "INHERIT_ENV [{}]", keys.join(", ")),
3462 StepKind::Workdir(a) => write!(f, "WORKDIR {}", fmt_value(a, quote_arg)),
3463 StepKind::Workspace(t) => write!(f, "WORKSPACE {}", t),
3464 StepKind::Env { key, value } => {
3465 write!(f, "ENV {}={}", key, fmt_value(value, quote_arg))
3466 }
3467 StepKind::Run(c) => write!(f, "RUN {}", fmt_value(c, quote_run)),
3468 StepKind::RunExec { argv } => {
3469 let parts: Vec<String> = argv.iter().map(fmt_exec_arg).collect();
3470 write!(f, "RUN [{}]", parts.join(", "))
3471 }
3472 StepKind::Echo(m) => write!(f, "ECHO {}", fmt_value(m, quote_msg)),
3473 StepKind::Copy {
3474 from_workspace,
3475 from_host,
3476 to_host,
3477 from,
3478 to,
3479 } => {
3480 let mut head = String::from("COPY");
3481 if let Some(target) = from_workspace {
3482 head.push_str(&format!(" --from-workspace {target}"));
3483 }
3484 if *from_host {
3485 head.push_str(" --from-host");
3486 }
3487 if *to_host {
3488 head.push_str(" --to-host");
3489 }
3490 write!(
3491 f,
3492 "{head} {} {}",
3493 fmt_value(from, quote_arg),
3494 fmt_value(to, quote_arg)
3495 )
3496 }
3497 StepKind::Symlink {
3498 from_workspace,
3499 from,
3500 to,
3501 } => {
3502 if let Some(target) = from_workspace {
3503 write!(
3504 f,
3505 "SYMLINK --from-workspace {} {} {}",
3506 target,
3507 fmt_value(from, quote_arg),
3508 fmt_value(to, quote_arg)
3509 )
3510 } else {
3511 write!(
3512 f,
3513 "SYMLINK {} {}",
3514 fmt_value(from, quote_arg),
3515 fmt_value(to, quote_arg)
3516 )
3517 }
3518 }
3519 StepKind::Mkdir(a) => write!(f, "MKDIR {}", fmt_value(a, quote_arg)),
3520 StepKind::Install { from, to } => write!(
3521 f,
3522 "INSTALL {} {}",
3523 fmt_value(from, quote_arg),
3524 fmt_value(to, quote_arg)
3525 ),
3526 StepKind::Archive { src, dst, raw } => {
3527 if *raw {
3528 write!(
3529 f,
3530 "ARCHIVE --raw {} {}",
3531 fmt_value(src, quote_arg),
3532 fmt_value(dst, quote_arg)
3533 )
3534 } else {
3535 write!(
3536 f,
3537 "ARCHIVE {} {}",
3538 fmt_value(src, quote_arg),
3539 fmt_value(dst, quote_arg)
3540 )
3541 }
3542 }
3543 StepKind::Unarchive {
3544 src,
3545 dst,
3546 max_bytes,
3547 } => {
3548 write!(f, "UNARCHIVE")?;
3549 if let Some(n) = max_bytes {
3550 write!(f, " --max-bytes {}", fmt_value(n, quote_arg))?;
3551 }
3552 write!(
3553 f,
3554 " {} {}",
3555 fmt_value(src, quote_arg),
3556 fmt_value(dst, quote_arg)
3557 )
3558 }
3559 StepKind::Ls(a) => {
3560 write!(f, "LS")?;
3561 if let Some(x) = a {
3562 write!(f, " {}", fmt_value(x, quote_arg))?;
3563 }
3564 Ok(())
3565 }
3566 StepKind::Cwd => write!(f, "CWD"),
3567 StepKind::Read(a) => {
3568 write!(f, "READ")?;
3569 if let Some(x) = a {
3570 write!(f, " {}", fmt_value(x, quote_arg))?;
3571 }
3572 Ok(())
3573 }
3574 StepKind::ReadLine { var } => write!(f, "READ_LINE ${}", var),
3575 StepKind::Prompt {
3576 var,
3577 message,
3578 default,
3579 } => {
3580 write!(f, "PROMPT ${} {}", var, fmt_value(message, quote_arg))?;
3581 if let Some(d) = default {
3582 write!(f, " {}", fmt_value(d, quote_arg))?;
3583 }
3584 Ok(())
3585 }
3586 StepKind::Write { path, contents } => {
3587 write!(f, "WRITE {}", fmt_value(path, quote_arg))?;
3588 if let Some(b) = contents {
3589 write!(f, " {}", fmt_value(b, quote_msg))?;
3590 }
3591 Ok(())
3592 }
3593 StepKind::Append { path, contents } => {
3594 write!(f, "APPEND {}", fmt_value(path, quote_arg))?;
3595 if let Some(b) = contents {
3596 write!(f, " {}", fmt_value(b, quote_msg))?;
3597 }
3598 Ok(())
3599 }
3600 StepKind::Remove { path, recursive } => {
3601 if *recursive {
3602 write!(f, "REMOVE --recursive {}", fmt_value(path, quote_arg))
3603 } else {
3604 write!(f, "REMOVE {}", fmt_value(path, quote_arg))
3605 }
3606 }
3607 StepKind::Expand { path, overrides } => {
3608 write!(f, "EXPAND")?;
3609 if let Some(p) = path {
3610 write!(f, " {}", fmt_value(p, quote_arg))?;
3611 }
3612 for (k, v) in overrides {
3613 write!(f, " {}={}", k, fmt_value(v, quote_arg))?;
3614 }
3615 Ok(())
3616 }
3617 StepKind::AssertEq {
3618 hash,
3619 actual,
3620 expected,
3621 } => {
3622 if let Some(d) = hash {
3623 write!(f, "ASSERT_EQ --hash {d} {}", fmt_assert_target(actual))?;
3624 } else {
3625 write!(
3626 f,
3627 "ASSERT_EQ {} {}",
3628 fmt_assert_target(actual),
3629 fmt_value(
3630 expected
3631 .as_ref()
3632 .expect("Display of ASSERT_EQ without --hash needs expected"),
3633 quote_msg
3634 )
3635 )?;
3636 }
3637 Ok(())
3638 }
3639 StepKind::AssertContains { haystack, needle } => write!(
3640 f,
3641 "ASSERT_CONTAINS {} {}",
3642 fmt_assert_target(haystack),
3643 fmt_value(needle, quote_msg)
3644 ),
3645 StepKind::WithIo { bindings, cmd } => {
3646 let p: Vec<String> = bindings.iter().map(fmt_io).collect();
3647 write!(f, "WITH_IO [{}] {}", p.join(", "), cmd)
3648 }
3649 StepKind::WithIoBlock { bindings } => {
3650 let p: Vec<String> = bindings.iter().map(fmt_io).collect();
3651 write!(f, "WITH_IO [{}] {{...}}", p.join(", "))
3652 }
3653 StepKind::CopyGit {
3654 rev,
3655 from,
3656 to,
3657 include_dirty,
3658 } => {
3659 if *include_dirty {
3660 write!(
3661 f,
3662 "COPY_GIT --include-dirty {} {} {}",
3663 fmt_value(rev, quote_arg),
3664 fmt_value(from, quote_arg),
3665 fmt_value(to, quote_arg)
3666 )
3667 } else {
3668 write!(
3669 f,
3670 "COPY_GIT {} {} {}",
3671 fmt_value(rev, quote_arg),
3672 fmt_value(from, quote_arg),
3673 fmt_value(to, quote_arg)
3674 )
3675 }
3676 }
3677 StepKind::HashSha256 { path } => {
3678 write!(f, "HASH_SHA256 {}", fmt_value(path, quote_arg))
3679 }
3680 StepKind::Exit(code) => write!(f, "EXIT {}", fmt_raw_arg(code)),
3681 StepKind::Sleep { duration } => write!(f, "SLEEP {}", fmt_raw_arg(duration)),
3682 StepKind::ListAppend { list, item } => {
3683 write!(f, "LIST_APPEND ${} {}", list, fmt_raw_arg(item))
3684 }
3685 StepKind::For {
3686 key_var,
3687 key_type,
3688 var,
3689 var_type,
3690 in_expr,
3691 body,
3692 } => {
3693 match key_var {
3694 Some(k) => {
3695 let kt = key_type.as_deref().unwrap_or("STRING");
3696 write!(
3697 f,
3698 "FOR ${}: {}, ${}: {} IN {} {{",
3699 k, kt, var, var_type, in_expr
3700 )?
3701 }
3702 None => write!(f, "FOR ${}: {} IN {} {{", var, var_type, in_expr)?,
3703 }
3704 for s in body {
3705 write!(f, "\n {}", s)?;
3706 }
3707 write!(f, "\n}}")
3708 }
3709 StepKind::If {
3710 cond,
3711 then_body,
3712 else_ifs,
3713 else_body,
3714 } => {
3715 write!(f, "IF {} {{", cond)?;
3716 for s in then_body {
3717 write!(f, "\n {}", s)?;
3718 }
3719 write!(f, " }}")?;
3720 for (c, b) in else_ifs {
3721 write!(f, " ELSE IF {} {{", c)?;
3722 for s in b {
3723 write!(f, "\n {}", s)?;
3724 }
3725 write!(f, " }}")?;
3726 }
3727 if let Some(b) = else_body {
3728 write!(f, " ELSE {{")?;
3729 for s in b {
3730 write!(f, "\n {}", s)?;
3731 }
3732 write!(f, " }}")?;
3733 }
3734 Ok(())
3735 }
3736 StepKind::Assign {
3737 var,
3738 decl_type,
3739 expr,
3740 } => {
3741 if matches!(expr, Expr::FreshPipe) {
3743 write!(f, "LET ${}: {}", var, decl_type)
3744 } else {
3745 write!(f, "LET ${}: {} = {}", var, decl_type, expr)
3746 }
3747 }
3748 StepKind::Set { var, expr } => write!(f, "${} = {}", var, expr),
3749 StepKind::AssignCapture {
3750 var,
3751 decl_type,
3752 cmd,
3753 } => {
3754 write!(f, "LET ${}: {} = {}", var, decl_type, cmd)
3755 }
3756 StepKind::AsyncBlock { body } => {
3757 write!(f, "ASYNC {{")?;
3758 for s in body {
3759 write!(f, "\n {}", s)?;
3760 }
3761 write!(f, "\n}}")
3762 }
3763 StepKind::AssignAsync {
3764 var,
3765 decl_type,
3766 body,
3767 } => {
3768 write!(f, "LET ${}: {} = ASYNC {{", var, decl_type)?;
3769 for s in body {
3770 write!(f, "\n {}", s)?;
3771 }
3772 write!(f, "\n}}")
3773 }
3774 StepKind::Await { var } => write!(f, "AWAIT ${}", var),
3775 StepKind::AwaitCapture {
3776 out_var,
3777 out_type,
3778 task_var,
3779 } => {
3780 write!(f, "LET ${}: {} = AWAIT ${}", out_var, out_type, task_var)
3781 }
3782 StepKind::Cancel { var } => write!(f, "CANCEL ${}", var),
3783 StepKind::Timeout { duration, body } => {
3784 let budget = fmt_raw_arg(duration);
3785 if body.len() == 1 {
3786 write!(f, "TIMEOUT {} {}", budget, body[0].kind)
3787 } else {
3788 write!(f, "TIMEOUT {} {{", budget)?;
3789 for s in body {
3790 write!(f, "\n {}", s)?;
3791 }
3792 write!(f, "\n}}")
3793 }
3794 }
3795 StepKind::Isolated { body } => {
3796 if body.len() == 1 {
3797 write!(f, "ISOLATED {}", body[0].kind)
3798 } else {
3799 write!(f, "ISOLATED {{")?;
3800 for s in body {
3801 write!(f, "\n {}", s)?;
3802 }
3803 write!(f, "\n}}")
3804 }
3805 }
3806 StepKind::IsolatedInheritEnv { keys } => {
3807 write!(f, "INHERIT_ENV [{}]", keys.join(", "))
3811 }
3812 StepKind::RemoteBlock {
3813 target,
3814 vars,
3815 env,
3816 body,
3817 } => {
3818 let mut entries: Vec<String> = vars.iter().map(|v| format!("${v}")).collect();
3819 entries.extend(env.iter().map(|e| format!("env:{e}")));
3820 if entries.is_empty() {
3821 write!(f, "REMOTE {target} {{")?;
3822 } else {
3823 write!(f, "REMOTE {target} [{}] {{", entries.join(", "))?;
3824 }
3825 for s in body {
3826 write!(f, "\n {}", s)?;
3827 }
3828 write!(f, "\n}}")
3829 }
3830 StepKind::FuncDef { name, params, body } => {
3831 let ps: Vec<String> = params
3832 .iter()
3833 .map(|(p, t)| format!("${}: {}", p, t))
3834 .collect();
3835 write!(f, "FUNC {}({}) {{", name, ps.join(", "))?;
3836 for s in body {
3837 write!(f, "\n {}", s)?;
3838 }
3839 write!(f, "\n}}")
3840 }
3841 StepKind::Call { name, args } => {
3842 let ps: Vec<String> = args.iter().map(|a| format!("{}", a)).collect();
3843 write!(f, "{}({})", name, ps.join(", "))
3844 }
3845 StepKind::Return { expr } => write!(f, "RETURN {}", expr),
3846 StepKind::TypeAlias { name, target } => write!(f, "TYPE {} = {}", name, target),
3847 StepKind::While { cond, body } => {
3848 write!(f, "WHILE {} {{", cond)?;
3849 for s in body {
3850 write!(f, "\n {}", s)?;
3851 }
3852 write!(f, "\n}}")
3853 }
3854 StepKind::Break => write!(f, "BREAK"),
3855 StepKind::Continue => write!(f, "CONTINUE"),
3856 }
3857 }
3858}
3859
3860#[cfg(test)]
3861mod tests {
3862 use super::*;
3863 use crate::command::{
3864 format_byte_count, format_duration, parse_byte_count, parse_duration,
3865 strip_digit_separators,
3866 };
3867 use crate::parser::parse_script;
3868
3869 fn parse_err(script: &str) -> String {
3870 parse_script(script, lower_command)
3871 .expect_err("script must fail to parse")
3872 .to_string()
3873 }
3874
3875 #[test]
3876 fn malformed_with_io_binding_names_the_bad_binding() {
3877 let err = parse_err("WITH_IO [stdout=discard] ECHO \"test\"\n");
3878 assert!(err.contains("invalid syntax for command WITH_IO"), "{err}");
3879 assert!(!err.contains("unknown command"), "{err}");
3880 assert!(err.contains("stdout=discard"), "{err}");
3881 assert!(err.contains("[stdout=$p]"), "{err}");
3882 }
3883
3884 #[test]
3885 fn connect_is_unknown_command() {
3886 let err = parse_err("CONNECT 127.0.0.1:8080\n");
3889 assert!(err.contains("unknown command"), "{err}");
3890 assert!(err.contains("CONNECT"), "{err}");
3891 }
3892
3893 #[test]
3894 fn listen_is_unknown_command() {
3895 let err = parse_err("LISTEN 127.0.0.1:8080\n");
3898 assert!(err.contains("unknown command"), "{err}");
3899 assert!(err.contains("LISTEN"), "{err}");
3900 }
3901
3902 #[test]
3903 fn await_without_task_variable_points_at_syntax() {
3904 let err = parse_err("AWAIT ECHO \"test\"\n");
3905 assert!(err.contains("invalid syntax for command AWAIT"), "{err}");
3906 assert!(!err.contains("unknown command"), "{err}");
3907 assert!(err.contains("AWAIT $t"), "{err}");
3908 assert!(err.contains("ECHO"), "{err}");
3909 }
3910
3911 #[test]
3912 fn bare_let_without_type_points_at_typed_syntax() {
3913 let err = parse_err("LET $x = 1\n");
3914 assert!(err.contains("invalid syntax for command LET"), "{err}");
3915 assert!(err.contains("LET $name: STRING = <expr>"), "{err}");
3916 }
3917
3918 #[test]
3919 fn workspace_accepts_all_four_targets_uppercase_only() {
3920 for (spelling, target) in [
3923 ("SNAPSHOT", WorkspaceTarget::Snapshot),
3924 ("LOCAL", WorkspaceTarget::Local),
3925 ("CACHE", WorkspaceTarget::Cache { local: false }),
3926 ("SYSTEM", WorkspaceTarget::System),
3927 ] {
3928 let steps =
3929 parse_script(&format!("WORKSPACE {spelling}\n"), lower_command).expect("parses");
3930 assert_eq!(steps.len(), 1);
3931 assert_eq!(steps[0].kind, StepKind::Workspace(target.clone()));
3932 assert_eq!(steps[0].kind.to_string(), format!("WORKSPACE {target}"));
3933 }
3934 for spelling in ["snapshot", "local", "cache", "system"] {
3935 let err = parse_err(&format!("WORKSPACE {spelling}\n"));
3936 assert!(
3937 err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
3938 "{spelling}: {err}"
3939 );
3940 }
3941 let err = parse_err("WORKSPACE REMOTE\n");
3942 assert!(
3943 err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
3944 "{err}"
3945 );
3946
3947 let steps = parse_script("WORKSPACE CACHE --local\n", lower_command).expect("parses");
3950 assert_eq!(
3951 steps[0].kind,
3952 StepKind::Workspace(WorkspaceTarget::Cache { local: true })
3953 );
3954 assert_eq!(steps[0].kind.to_string(), "WORKSPACE CACHE --local");
3955 for bad in [
3956 "WORKSPACE SNAPSHOT --local\n",
3957 "WORKSPACE LOCAL --local\n",
3958 "WORKSPACE SYSTEM --local\n",
3959 ] {
3960 let err = parse_err(bad);
3961 assert!(err.contains("--local requires CACHE"), "{bad}: {err}");
3962 }
3963 }
3964
3965 #[test]
3966 fn archive_unarchive_parse_and_round_trip() {
3967 let steps = parse_script("ARCHIVE bundle bundle.tar.gz\n", lower_command).expect("parses");
3968 match &steps[0].kind {
3969 StepKind::Archive { src, dst, raw } => {
3970 assert_eq!(src.as_str(), "bundle");
3971 assert_eq!(dst.as_str(), "bundle.tar.gz");
3972 assert!(!raw);
3973 }
3974 other => panic!("expected Archive, got {other:?}"),
3975 }
3976 assert_eq!(
3977 steps[0].kind.to_string(),
3978 "ARCHIVE bundle \"bundle.tar.gz\""
3979 );
3980
3981 let steps =
3982 parse_script("ARCHIVE --raw tool.bin tool.tar\n", lower_command).expect("parses");
3983 assert!(
3984 matches!(&steps[0].kind, StepKind::Archive { raw: true, .. }),
3985 "unexpected lowering: {:?}",
3986 steps[0].kind
3987 );
3988 assert_eq!(
3989 steps[0].kind.to_string(),
3990 "ARCHIVE --raw \"tool.bin\" \"tool.tar\""
3991 );
3992
3993 let steps =
3994 parse_script("UNARCHIVE pack.tar.gz unpacked\n", lower_command).expect("parses");
3995 match &steps[0].kind {
3996 StepKind::Unarchive {
3997 src,
3998 dst,
3999 max_bytes,
4000 } => {
4001 assert_eq!(src.as_str(), "pack.tar.gz");
4002 assert_eq!(dst.as_str(), "unpacked");
4003 assert_eq!(max_bytes, &None);
4004 }
4005 other => panic!("expected Unarchive, got {other:?}"),
4006 }
4007 assert_eq!(
4008 steps[0].kind.to_string(),
4009 "UNARCHIVE \"pack.tar.gz\" unpacked"
4010 );
4011
4012 let steps = parse_script(
4013 "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
4014 lower_command,
4015 )
4016 .expect("parses");
4017 match &steps[0].kind {
4018 StepKind::Unarchive {
4019 src,
4020 dst,
4021 max_bytes,
4022 } => {
4023 assert_eq!(src.as_str(), "pack.tar.gz");
4024 assert_eq!(dst.as_str(), "unpacked");
4025 assert_eq!(max_bytes.as_ref().map(|a| a.as_str()), Some("100_000"));
4026 }
4027 other => panic!("expected Unarchive, got {other:?}"),
4028 }
4029 assert_eq!(
4030 steps[0].kind.to_string(),
4031 "UNARCHIVE --max-bytes \"100_000\" \"pack.tar.gz\" unpacked"
4032 );
4033
4034 for script in [
4035 "ARCHIVE bundle bundle.tar.gz\n",
4036 "ARCHIVE --raw tool.bin tool.tar\n",
4037 "UNARCHIVE pack.tar.gz unpacked\n",
4038 "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
4039 ] {
4040 let first = parse_script(script, lower_command).expect("parses");
4041 let rendered = first[0].kind.to_string() + "\n";
4042 let second = parse_script(&rendered, lower_command).expect("reparses");
4043 assert_eq!(
4046 second[0].kind.to_string(),
4047 first[0].kind.to_string(),
4048 "Display must fixpoint for {script:?}"
4049 );
4050 }
4051
4052 for bad in ["ARCHIVE only-src\n", "ARCHIVE\n", "UNARCHIVE only-src\n"] {
4053 let err = parse_err(bad);
4054 assert!(
4055 err.contains("ARCHIVE") || err.contains("UNARCHIVE"),
4056 "{bad}: {err}"
4057 );
4058 }
4059 }
4060
4061 #[test]
4062 fn copy_from_workspace_selects_source_root() {
4063 for (spelling, target) in [
4064 ("SNAPSHOT", WorkspaceTarget::Snapshot),
4065 ("LOCAL", WorkspaceTarget::Local),
4066 ("CACHE", WorkspaceTarget::Cache { local: false }),
4067 ("SYSTEM", WorkspaceTarget::System),
4068 ] {
4069 let steps = parse_script(
4070 &format!("COPY --from-workspace {spelling} a.txt b.txt\n"),
4071 lower_command,
4072 )
4073 .expect("parses");
4074 assert!(
4075 matches!(&steps[0].kind, StepKind::Copy { from_workspace: Some(t), .. } if *t == target),
4076 "unexpected lowering for {spelling}: {:?}",
4077 steps[0].kind
4078 );
4079 }
4080 for script in [
4083 "COPY --from-workspace=CACHE a.txt b.txt\n",
4084 "COPY --from-workspace=\"CACHE\" a.txt b.txt\n",
4085 ] {
4086 let steps = parse_script(script, lower_command).expect("parses");
4087 assert!(
4088 matches!(
4089 &steps[0].kind,
4090 StepKind::Copy {
4091 from_workspace: Some(WorkspaceTarget::Cache { local: false }),
4092 ..
4093 }
4094 ),
4095 "unexpected lowering for {script:?}: {:?}",
4096 steps[0].kind
4097 );
4098 }
4099 let steps = parse_script("COPY a.txt b.txt\n", lower_command).expect("parses");
4101 assert!(
4102 matches!(
4103 &steps[0].kind,
4104 StepKind::Copy {
4105 from_workspace: None,
4106 ..
4107 }
4108 ),
4109 "unexpected lowering: {:?}",
4110 steps[0].kind
4111 );
4112 for bad in ["REMOTE", "local"] {
4114 let err = parse_err(&format!("COPY --from-workspace {bad} a.txt b.txt\n"));
4115 assert!(err.contains("unknown workspace source"), "{bad}: {err}");
4116 }
4117 }
4118
4119 #[test]
4120 fn symlink_from_workspace_selects_source_root() {
4121 for (spelling, target) in [
4122 ("SNAPSHOT", WorkspaceTarget::Snapshot),
4123 ("LOCAL", WorkspaceTarget::Local),
4124 ("CACHE", WorkspaceTarget::Cache { local: false }),
4125 ("SYSTEM", WorkspaceTarget::System),
4126 ] {
4127 let steps = parse_script(
4128 &format!("SYMLINK --from-workspace {spelling} a.txt b.txt\n"),
4129 lower_command,
4130 )
4131 .expect("parses");
4132 assert!(
4133 matches!(&steps[0].kind, StepKind::Symlink { from_workspace: Some(t), .. } if *t == target),
4134 "unexpected lowering for {spelling}: {:?}",
4135 steps[0].kind
4136 );
4137 let roundtrip = steps[0].kind.to_string();
4138 assert!(
4139 roundtrip.contains("--from-workspace"),
4140 "display should round-trip the flag: {roundtrip}"
4141 );
4142 }
4143 let steps = parse_script("SYMLINK a.txt b.txt\n", lower_command).expect("parses");
4144 assert!(
4145 matches!(
4146 &steps[0].kind,
4147 StepKind::Symlink {
4148 from_workspace: None,
4149 ..
4150 }
4151 ),
4152 "unexpected lowering: {:?}",
4153 steps[0].kind
4154 );
4155 for bad in ["REMOTE", "local"] {
4156 let err = parse_err(&format!("SYMLINK --from-workspace {bad} a.txt b.txt\n"));
4157 assert!(err.contains("unknown workspace source"), "{bad}: {err}");
4158 }
4159 let steps = parse_script(
4161 "SYMLINK --from-workspace=LOCAL a.txt b.txt\n",
4162 lower_command,
4163 )
4164 .expect("parses");
4165 assert!(
4166 matches!(
4167 &steps[0].kind,
4168 StepKind::Symlink {
4169 from_workspace: Some(WorkspaceTarget::Local),
4170 ..
4171 }
4172 ),
4173 "unexpected lowering: {:?}",
4174 steps[0].kind
4175 );
4176 }
4177
4178 #[test]
4179 fn dash_dash_equals_tokens_bypass_assignment() {
4180 let steps = parse_script("ENV --foo=bar\n", lower_command).expect("parses");
4183 let StepKind::Env { key, value } = &steps[0].kind else {
4184 panic!("expected Env, got {:?}", steps[0].kind);
4185 };
4186 assert_eq!(key, "--foo");
4187 assert_eq!(value.as_str(), "bar");
4188
4189 let steps = parse_script("RUN echo --foo=bar\n", lower_command).expect("parses");
4190 let StepKind::Run(cmd) = &steps[0].kind else {
4191 panic!("expected Run, got {:?}", steps[0].kind);
4192 };
4193 assert!(
4194 cmd.as_str().contains("--foo=bar"),
4195 "unexpected RUN lowering: {cmd:?}"
4196 );
4197
4198 let digest = "08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c";
4199 let steps = parse_script(&format!("ASSERT_EQ --hash={digest} $body\n"), lower_command)
4200 .expect("parses");
4201 let StepKind::AssertEq { hash, .. } = &steps[0].kind else {
4202 panic!("expected AssertEq, got {:?}", steps[0].kind);
4203 };
4204 assert_eq!(hash.as_deref(), Some(digest));
4205
4206 let steps = parse_script("EXPAND --k=v\n", lower_command).expect("parses");
4208 let StepKind::Expand { path, overrides } = &steps[0].kind else {
4209 panic!("expected Expand, got {:?}", steps[0].kind);
4210 };
4211 assert!(path.is_none());
4212 assert_eq!(overrides.len(), 1);
4213 assert_eq!(overrides[0].0.as_str(), "--k");
4214 }
4215
4216 #[test]
4217 fn space_before_paren_is_not_a_call() {
4218 let steps = parse_script("ECHO (1 + 2)\n", lower_command).expect("parses");
4221 assert_eq!(steps.len(), 1);
4222 assert!(
4223 !matches!(steps[0].kind, crate::ast::StepKind::Call { .. }),
4224 "space before paren must not route to a call: {:?}",
4225 steps[0].kind
4226 );
4227 }
4228
4229 #[test]
4230 fn unknown_type_tag_parses_as_custom() {
4231 let steps = parse_script("LET $x: FOO = 1\n", lower_command).expect("custom tag parses");
4235 let StepKind::Assign { decl_type, .. } = &steps[0].kind else {
4236 panic!("expected Assign, got {:?}", steps[0].kind);
4237 };
4238 assert_eq!(decl_type, "FOO");
4239 }
4240
4241 #[test]
4242 fn bare_for_without_types_is_rejected() {
4243 let err = parse_err("FOR $i IN [1] { ECHO hi }\n");
4244 assert!(err.contains("FOR requires explicit types"), "{err}");
4245 }
4246
4247 #[test]
4248 fn mutate_statement_parses_without_keyword() {
4249 let steps = parse_script("$y = 2\n", lower_command).expect("mutation parses");
4250 assert!(matches!(steps[0].kind, StepKind::Set { .. }));
4251 }
4252
4253 #[test]
4254 fn set_keyword_is_rejected_with_mutation_hint() {
4255 let err = parse_err("SET $y = 2\n");
4256 assert!(err.contains("not a keyword"), "{err}");
4257 assert!(err.contains("$var = <expr>"), "{err}");
4258 }
4259
4260 #[test]
4261 fn structural_fallthrough_commits_per_keyword() {
4262 for (script, cmd) in [
4263 ("CANCEL foo\n", "CANCEL"),
4264 ("TIMEOUT foo\n", "TIMEOUT"),
4265 ("FOR foo\n", "FOR"),
4266 ("IF foo\n", "IF"),
4267 ("LET foo\n", "LET"),
4268 ("ASYNC\n", "ASYNC"),
4272 ("ELSE foo\n", "ELSE"),
4273 ] {
4274 let err = parse_err(script);
4275 assert!(
4276 err.contains(&format!("invalid syntax for command {cmd}")),
4277 "{cmd}: {err}"
4278 );
4279 assert!(!err.contains("unknown command"), "{cmd}: {err}");
4280 }
4281 }
4282
4283 #[test]
4284 fn leaf_arity_errors_carry_invalid_syntax_prefix() {
4285 let err = parse_err("SLEEP 1s 2s\n");
4286 assert!(err.contains("invalid syntax for command SLEEP"), "{err}");
4287 assert!(!err.contains("unknown command"), "{err}");
4288 }
4289
4290 #[test]
4291 fn list_append_lowers_variable_and_item() {
4292 let steps = parse_script("LIST_APPEND $items \"hi\"\n", lower_command).expect("parses");
4293 let StepKind::ListAppend { list, item } = &steps[0].kind else {
4294 panic!("expected ListAppend, got {:?}", steps[0].kind);
4295 };
4296 assert_eq!(list, "items");
4297 assert!(matches!(item, Arg::String(s, _) if s == "hi"));
4298 assert_eq!(steps[0].kind.to_string(), "LIST_APPEND $items \"hi\"");
4299 }
4300
4301 #[test]
4302 fn list_append_rejects_wrong_arity() {
4303 for script in [
4304 "LIST_APPEND\n",
4305 "LIST_APPEND $items\n",
4306 "LIST_APPEND $items \"a\" \"b\"\n",
4307 ] {
4308 let err = parse_err(script);
4309 assert!(
4310 err.contains("invalid syntax for command LIST_APPEND"),
4311 "{script}: {err}"
4312 );
4313 assert!(!err.contains("unknown command"), "{script}: {err}");
4314 }
4315 }
4316
4317 #[test]
4318 fn list_append_rejects_non_variable_target() {
4319 let err = parse_err("LIST_APPEND items \"a\"\n");
4320 assert!(
4321 err.contains("invalid syntax for command LIST_APPEND"),
4322 "{err}"
4323 );
4324 assert!(!err.contains("unknown command"), "{err}");
4325 }
4326
4327 #[test]
4328 fn read_line_rejects_bare_word_target() {
4329 let err = parse_err("READ_LINE reply\n");
4333 assert!(err.contains("READ_LINE requires a $variable"), "{err}");
4334 assert!(!err.contains("unknown command"), "{err}");
4335 }
4336
4337 #[test]
4338 fn genuinely_unknown_command_keeps_bare_message() {
4339 let err = parse_err("FROBNICATE hi\n");
4340 assert!(err.contains("unknown command: FROBNICATE"), "{err}");
4341 assert!(!err.contains("did you mean"), "{err}");
4342 }
4343
4344 #[test]
4345 fn lowercase_command_suggests_uppercase() {
4346 let err = lower_command("echo", vec![Arg::String("hi".to_string(), false)])
4350 .expect_err("must fail")
4351 .to_string();
4352 assert!(err.contains("unknown command: echo"), "{err}");
4353 assert!(err.contains("did you mean `ECHO`"), "{err}");
4354 }
4355
4356 #[test]
4357 fn func_def_requires_typed_uppercase_name() {
4358 let steps = parse_script(
4359 "FUNC GREET($name: STRING) {\n RETURN $name\n}\n",
4360 lower_command,
4361 )
4362 .expect("func def parses");
4363 let StepKind::FuncDef { name, params, body } = &steps[0].kind else {
4364 panic!("expected FuncDef, got {:?}", steps[0].kind);
4365 };
4366 assert_eq!(name, "GREET");
4367 assert_eq!(
4368 params,
4369 &vec![("name".to_string(), "STRING".to_string())],
4370 "{params:?}"
4371 );
4372 assert!(matches!(body[0].kind, StepKind::Return { .. }));
4373 }
4374
4375 #[test]
4376 fn lowercase_func_name_is_rejected() {
4377 let err = parse_err("FUNC greet($x: STRING) {\n RETURN $x\n}\n");
4378 assert!(err.contains("FUNC"), "{err}");
4379 }
4380
4381 #[test]
4382 fn call_and_while_lower_correctly() {
4383 let steps = parse_script(
4384 "FUNC GREET($name: STRING) {\n RETURN $name\n}\nGREET(\"ada\")\n",
4385 lower_command,
4386 )
4387 .expect("call parses");
4388 assert!(
4389 matches!(&steps[1].kind, StepKind::Call { name, .. } if name == "SCRIPT::GREET"),
4390 "{:?}",
4391 steps[1].kind
4392 );
4393 let steps = parse_script(
4394 "FUNC GREET($a: STRING, $b: STRING) {\n RETURN $a\n}\nGREET(\"ada\", \"bex\")\n",
4395 lower_command,
4396 )
4397 .expect("spaced call parses");
4398 assert!(
4399 matches!(&steps[1].kind, StepKind::Call { name, args } if name == "SCRIPT::GREET" && args.len() == 2),
4400 "{:?}",
4401 steps[1].kind
4402 );
4403 let steps = parse_script(
4404 indoc! {r#"
4405 WHILE !$done {
4406 BREAK
4407 }
4408 "#},
4409 lower_command,
4410 )
4411 .expect("while parses");
4412 let StepKind::While { body, .. } = &steps[0].kind else {
4413 panic!("expected While, got {:?}", steps[0].kind);
4414 };
4415 assert!(matches!(body[0].kind, StepKind::Break));
4416 }
4417
4418 #[test]
4419 fn let_capture_call_and_async_call_lower() {
4420 let steps = parse_script(
4423 indoc! {r#"
4424 FUNC GREET($name: STRING) {
4425 RETURN $name
4426 }
4427 LET $r: STRING = GREET("ada")
4428 "#},
4429 lower_command,
4430 )
4431 .expect("capture call parses");
4432 let StepKind::Assign { var, expr, .. } = &steps[1].kind else {
4433 panic!("expected Assign, got {:?}", steps[1].kind);
4434 };
4435 assert_eq!(var, "r");
4436 assert!(
4437 matches!(expr, Expr::Call { name, .. } if name == "SCRIPT::GREET"),
4438 "{expr:?}"
4439 );
4440 let steps = parse_script(
4441 "FUNC GREET($name: STRING) {\n RETURN $name\n}\nLET $t: HANDLE = ASYNC GREET(\"a\")\n",
4442 lower_command,
4443 )
4444 .expect("async call parses");
4445 assert!(
4446 matches!(&steps[1].kind, StepKind::AssignAsync { .. }),
4447 "{:?}",
4448 steps[1].kind
4449 );
4450 }
4451
4452 #[test]
4453 fn multiline_call_args_span_lines() {
4454 let steps = parse_script(
4458 "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",
4459 lower_command,
4460 )
4461 .expect("multiline call parses");
4462 let StepKind::Assign { expr, .. } = &steps[1].kind else {
4463 panic!("expected Assign, got {:?}", steps[1].kind);
4464 };
4465 let Expr::Call { name, args } = expr else {
4466 panic!("expected Call expr, got {expr:?}");
4467 };
4468 assert_eq!(name, "SCRIPT::SERVE");
4469 assert_eq!(args.len(), 4);
4470 assert!(matches!(&args[3], Expr::Map(entries) if entries.len() == 1));
4471 let rendered = steps[1].to_string();
4473 assert!(!rendered.contains('\n'), "{rendered}");
4474 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";
4475 let again = parse_script(script, lower_command).expect("reparse ok");
4476 assert_eq!(again, steps);
4477 }
4478
4479 #[test]
4480 fn multiline_bare_call_and_list_span_lines() {
4481 let steps = parse_script(
4482 indoc! {r#"
4483 FUNC GREET($a: STRING) {
4484 RETURN $a
4485 }
4486 GREET(
4487 "ada"
4488 )
4489 "#},
4490 lower_command,
4491 )
4492 .expect("multiline bare call parses");
4493 let StepKind::Call { name, args } = &steps[1].kind else {
4494 panic!("expected Call, got {:?}", steps[1].kind);
4495 };
4496 assert_eq!(name, "SCRIPT::GREET");
4497 assert_eq!(args.len(), 1);
4498 let steps = parse_script(
4499 indoc! {r#"
4500 LET $l: LIST = [
4501 "a",
4502 "b"
4503 ]
4504 "#},
4505 lower_command,
4506 )
4507 .expect("multiline list parses");
4508 let StepKind::Assign { expr, .. } = &steps[0].kind else {
4509 panic!("expected Assign, got {:?}", steps[0].kind);
4510 };
4511 assert!(
4512 matches!(expr, Expr::List(items) if items.len() == 2),
4513 "{expr:?}"
4514 );
4515 }
4516
4517 #[test]
4518 fn parse_duration_units() {
4519 use std::time::Duration;
4520 assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
4521 assert_eq!(parse_duration("10s").unwrap(), Duration::from_secs(10));
4522 assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
4523 assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
4524 assert_eq!(parse_duration("30").unwrap(), Duration::from_secs(30));
4525 assert_eq!(parse_duration("30 s").unwrap(), Duration::from_secs(30));
4527 assert_eq!(parse_duration("2 m").unwrap(), Duration::from_secs(120));
4528 }
4529
4530 #[test]
4531 fn parse_duration_rejects_garbage() {
4532 assert!(parse_duration("").is_err());
4533 assert!(parse_duration("banana").is_err());
4534 assert!(parse_duration("10x").is_err());
4535 assert!(parse_duration("0s").is_err());
4536 assert!(parse_duration("0").is_err());
4537 assert!(parse_duration("-5s").is_err());
4538 assert!(parse_duration("30 s s").is_err());
4540 assert!(parse_duration("3 0s").is_err());
4541 }
4542
4543 #[test]
4544 fn parse_byte_count_units() {
4545 assert_eq!(parse_byte_count("500").unwrap(), 500);
4546 assert_eq!(parse_byte_count("500B").unwrap(), 500);
4547 assert_eq!(parse_byte_count("10KB").unwrap(), 10_000);
4548 assert_eq!(parse_byte_count("2MB").unwrap(), 2_000_000);
4549 assert_eq!(parse_byte_count("1GB").unwrap(), 1_000_000_000);
4550 assert_eq!(parse_byte_count("1TB").unwrap(), 1_000_000_000_000);
4551 assert_eq!(parse_byte_count("10KIB").unwrap(), 10 * 1_024);
4552 assert_eq!(parse_byte_count("2MIB").unwrap(), 2 * 1_024 * 1_024);
4553 assert_eq!(parse_byte_count("1GIB").unwrap(), 1_024 * 1_024 * 1_024);
4554 assert_eq!(
4555 parse_byte_count("1TIB").unwrap(),
4556 1_024 * 1_024 * 1_024 * 1_024
4557 );
4558 assert_eq!(parse_byte_count("1gb").unwrap(), 1_000_000_000);
4560 assert_eq!(parse_byte_count("1Gb").unwrap(), 1_000_000_000);
4561 assert_eq!(parse_byte_count("1gib").unwrap(), 1_024 * 1_024 * 1_024);
4562 assert_eq!(parse_byte_count("1Gib").unwrap(), 1_024 * 1_024 * 1_024);
4563 assert_eq!(parse_byte_count("1_000").unwrap(), 1_000);
4565 assert_eq!(
4566 parse_byte_count("1_000_000_000_000").unwrap(),
4567 1_000_000_000_000
4568 );
4569 assert_eq!(parse_byte_count("1_0KB").unwrap(), 10_000);
4570 assert_eq!(
4571 parse_byte_count("1_0GiB").unwrap(),
4572 10 * 1_024 * 1_024 * 1_024
4573 );
4574 assert_eq!(parse_byte_count("1 GB").unwrap(), 1_000_000_000);
4576 assert_eq!(parse_byte_count("10 KiB").unwrap(), 10_240);
4577 assert_eq!(parse_byte_count(" 2MB ").unwrap(), 2_000_000);
4578 assert_eq!(parse_byte_count("+1 GB").unwrap(), 1_000_000_000);
4580 assert!(parse_byte_count("-1 GB").is_err());
4581 }
4582
4583 #[test]
4584 fn parse_byte_count_rejects_garbage() {
4585 for bad in [
4586 "",
4587 "banana",
4588 "10x",
4589 "1G",
4590 "1K",
4591 "1.5GB",
4592 "-5",
4593 "-5GB",
4594 "0",
4595 "0GB",
4596 "_100",
4597 "100_",
4598 "1__000",
4599 "_",
4600 "1_GB",
4601 "1 G B",
4603 "1 2",
4604 "1 0",
4605 "1000000000000000000000000",
4607 "1000000000TB",
4608 ] {
4609 assert!(parse_byte_count(bad).is_err(), "{bad:?} must fail");
4610 }
4611 }
4612
4613 #[test]
4614 fn format_byte_count_round_trips() {
4615 for text in [
4616 "500", "500B", "10KB", "2MB", "1GB", "1TB", "10KIB", "2MIB", "1GIB", "1TIB", "1500B",
4617 ] {
4618 let parsed = parse_byte_count(text).unwrap();
4619 let rendered = format_byte_count(parsed);
4620 assert_eq!(
4621 parse_byte_count(&rendered).unwrap(),
4622 parsed,
4623 "round-trip failed for {text}"
4624 );
4625 }
4626 assert_eq!(format_byte_count(1_024 * 1_024 * 1_024), "1GiB");
4627 assert_eq!(format_byte_count(1_000_000_000), "1GB");
4628 }
4629
4630 #[test]
4631 fn strip_digit_separators_passes_signs_through() {
4632 assert_eq!(strip_digit_separators("-1_000"), "-1000");
4636 assert_eq!(strip_digit_separators("+1_000_000"), "+1000000");
4637 assert_eq!(strip_digit_separators("-1_000.5"), "-1000.5");
4638 assert_eq!(strip_digit_separators("1_000"), "1000");
4639 for untouched in ["+", "-", "", "1__0", "abc", "+-5", "--5"] {
4640 assert_eq!(strip_digit_separators(untouched), untouched);
4641 }
4642 assert!(parse_byte_count("-1_000").is_err());
4645 assert_eq!(parse_byte_count("+1GB").unwrap(), 1_000_000_000);
4646 }
4647
4648 #[test]
4649 fn format_byte_count_is_lossless() {
4650 for n in [
4655 1,
4656 500,
4657 999,
4658 1_000,
4659 1_024,
4660 1_500,
4661 1_000_000,
4662 1_048_576,
4663 1_000_000_000,
4664 1_073_741_824,
4665 1_000_000_000_000,
4666 1_099_511_627_776,
4667 u64::MAX,
4668 ] {
4669 assert_eq!(
4670 parse_byte_count(&format_byte_count(n)).unwrap(),
4671 n,
4672 "lossless round-trip failed for {n}"
4673 );
4674 }
4675 }
4676
4677 #[test]
4678 fn format_duration_round_trips() {
4679 for text in ["500ms", "10s", "2m", "1h", "90s", "1500ms"] {
4680 let parsed = parse_duration(text).unwrap();
4681 let rendered = format_duration(&parsed);
4682 assert_eq!(
4683 parse_duration(&rendered).unwrap(),
4684 parsed,
4685 "round-trip failed for {text}"
4686 );
4687 }
4688 assert_eq!(format_duration(&parse_duration("90s").unwrap()), "90s");
4689 assert_eq!(format_duration(&parse_duration("2m").unwrap()), "2m");
4690 }
4691
4692 #[test]
4693 fn structural_metadata_covers_all_structural_kinds() {
4694 use crate::ast::Value;
4695
4696 fn metadata_name(kind: &StepKind) -> Option<&'static str> {
4700 match kind {
4701 StepKind::WithIo { .. } | StepKind::WithIoBlock { .. } => Some("WITH_IO"),
4702 StepKind::For { .. } => Some("FOR"),
4703 StepKind::If { .. } => Some("IF"),
4704 StepKind::Assign { .. } => Some("LET"),
4705 StepKind::Set { .. } => Some("MUTATION"),
4706 StepKind::AssignCapture { .. } => Some("LET"),
4707 StepKind::AwaitCapture { .. } => Some("AWAIT"),
4708 StepKind::AsyncBlock { .. } | StepKind::AssignAsync { .. } => Some("ASYNC"),
4709 StepKind::Await { .. } => Some("AWAIT"),
4710 StepKind::Cancel { .. } => Some("CANCEL"),
4711 StepKind::Timeout { .. } => Some("TIMEOUT"),
4712 StepKind::Isolated { .. } => Some("ISOLATED"),
4713 StepKind::IsolatedInheritEnv { .. } => Some("ISOLATED"),
4714 StepKind::RemoteBlock { .. } => Some("REMOTE"),
4715 StepKind::FuncDef { .. } => Some("FUNC"),
4716 StepKind::Call { .. } => None,
4719 StepKind::Return { .. } => Some("RETURN"),
4720 StepKind::While { .. } => Some("WHILE"),
4721 StepKind::Break => Some("BREAK"),
4722 StepKind::Continue => Some("CONTINUE"),
4723 StepKind::TypeAlias { .. } => Some("LET"),
4727 StepKind::RunExec { .. } => None,
4728 StepKind::Workdir(_)
4729 | StepKind::Workspace(_)
4730 | StepKind::Env { .. }
4731 | StepKind::InheritEnv { .. }
4732 | StepKind::Run(_)
4733 | StepKind::Echo(_)
4734 | StepKind::Copy { .. }
4735 | StepKind::Symlink { .. }
4736 | StepKind::Mkdir(_)
4737 | StepKind::Archive { .. }
4738 | StepKind::Unarchive { .. }
4739 | StepKind::Install { .. }
4740 | StepKind::Ls(_)
4741 | StepKind::Cwd
4742 | StepKind::Read(_)
4743 | StepKind::ReadLine { .. }
4744 | StepKind::Prompt { .. }
4745 | StepKind::Write { .. }
4746 | StepKind::Append { .. }
4747 | StepKind::Remove { .. }
4748 | StepKind::Expand { .. }
4749 | StepKind::AssertEq { .. }
4750 | StepKind::AssertContains { .. }
4751 | StepKind::CopyGit { .. }
4752 | StepKind::HashSha256 { .. }
4753 | StepKind::Exit(_)
4754 | StepKind::Sleep { .. }
4755 | StepKind::ListAppend { .. } => None,
4756 }
4757 }
4758
4759 let dummies: Vec<StepKind> = vec![
4762 StepKind::WithIo {
4763 bindings: Vec::new(),
4764 cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
4765 "x".to_string(),
4766 false,
4767 ))),
4768 },
4769 StepKind::For {
4770 key_var: None,
4771 key_type: None,
4772 var: "i".to_string(),
4773 var_type: "STRING".to_string(),
4774 in_expr: Expr::Literal(Value::bool(true)),
4775 body: Vec::new(),
4776 },
4777 StepKind::If {
4778 cond: Box::new(Expr::Literal(Value::bool(true))),
4779 then_body: Vec::new(),
4780 else_ifs: Vec::new(),
4781 else_body: None,
4782 },
4783 StepKind::Assign {
4784 var: "v".to_string(),
4785 decl_type: "BOOL".to_string(),
4786 expr: Expr::Literal(Value::bool(true)),
4787 },
4788 StepKind::Set {
4789 var: "v".to_string(),
4790 expr: Expr::Literal(Value::bool(true)),
4791 },
4792 StepKind::AssignCapture {
4793 var: "v".to_string(),
4794 decl_type: "STRING".to_string(),
4795 cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
4796 "x".to_string(),
4797 false,
4798 ))),
4799 },
4800 StepKind::AwaitCapture {
4801 out_var: "o".to_string(),
4802 out_type: "STRING".to_string(),
4803 task_var: "t".to_string(),
4804 },
4805 StepKind::AsyncBlock { body: Vec::new() },
4806 StepKind::AssignAsync {
4807 var: "t".to_string(),
4808 decl_type: "HANDLE".to_string(),
4809 body: Vec::new(),
4810 },
4811 StepKind::Await {
4812 var: "t".to_string(),
4813 },
4814 StepKind::Cancel {
4815 var: "t".to_string(),
4816 },
4817 StepKind::Timeout {
4818 duration: Arg::String("1s".to_string(), false),
4819 body: Vec::new(),
4820 },
4821 StepKind::Isolated { body: Vec::new() },
4822 StepKind::IsolatedInheritEnv { keys: Vec::new() },
4823 StepKind::RemoteBlock {
4824 target: "prod".to_string(),
4825 vars: Vec::new(),
4826 env: Vec::new(),
4827 body: Vec::new(),
4828 },
4829 StepKind::FuncDef {
4830 name: "F".to_string(),
4831 params: Vec::new(),
4832 body: Vec::new(),
4833 },
4834 StepKind::Call {
4835 name: "F".to_string(),
4836 args: Vec::new(),
4837 },
4838 StepKind::Return {
4839 expr: Box::new(Expr::Literal(Value::bool(true))),
4840 },
4841 StepKind::While {
4842 cond: Box::new(Expr::Literal(Value::bool(true))),
4843 body: Vec::new(),
4844 },
4845 StepKind::Break,
4846 StepKind::Continue,
4847 StepKind::TypeAlias {
4848 name: "PERSON".to_string(),
4849 target: "MAP<name: STRING>".to_string(),
4850 },
4851 ];
4852 let registry = all_structural_metadata();
4853 for kind in &dummies {
4854 let Some(name) = metadata_name(kind) else {
4856 continue;
4857 };
4858 assert!(
4859 registry.iter().any(|meta| meta.name == name),
4860 "no structural metadata entry for {}",
4861 name
4862 );
4863 }
4864 }
4865}