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. Arguments check against the registered
1755 signature, so wrong arity or mistyped values fail at the call;
1756 unknown names fail listing the known functions. Only pure
1757 functions resolve here: stateful, script-defined, and pipe-backed
1758 entries fail naming themselves, since placeholder evaluation
1759 carries no step context. The same calls resolve in ordinary
1760 strings, so both paths agree.
1761
1762 Substitution runs in a single pass. `EXPAND` is not recursive and does not
1763 expand nested placeholders: a value that itself contains `{{ ... }}` is
1764 inserted verbatim and never expanded again.
1765
1766 A bare `$var` argument is a template path; `KEY=val` arguments are
1767 overrides whose values follow the unified string-value rules (same as
1768 `ENV`: quotes keep exact bytes, a lone `$var` evaluates,
1769 `{{ ... }}` interpolates).
1770
1771 NOTE: `WRITE` interpolates `{{ ... }}` while writing, so escape it
1772 (`\{{ ... }}`) when writing a template file for a later `EXPAND`.
1773
1774 With no path, the template arrives on stdin through a pipe. When piping
1775 from a shell, single-quote the template (`echo '{{ $x }}'`): double
1776 quotes let the shell swallow `$x`, so oxdock receives an empty `{{ }}`
1777 placeholder and errors.
1778 "#},
1779 args: &[
1780 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 },
1781 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 },
1782 ],
1783 flags: &[],
1784 default_output: Some(Stream::Stdout),
1785 examples: &[
1786 Example { name: "expand", fence_meta: None, code: indoc! {r#"
1787 # Placeholders read overrides first, then the environment.
1788 ENV NAME="Alice"
1789 WRITE template.md "Hello {{ env:NAME }}!"
1790 EXPAND template.md
1791
1792 ASSERT_CONTAINS stdout "Hello Alice!"
1793 "#} },
1794 Example { name: "override with spaces", fence_meta: None, code: indoc! {r#"
1795 # WRITE would interpolate {{ }} right away, so escape it.
1796 # The file must literally contain {{ env:NAME }} for EXPAND.
1797 WRITE template.md "Hello \{{ env:NAME }}!"
1798 EXPAND template.md NAME="Alice Smith"
1799
1800 ASSERT_CONTAINS stdout "Hello Alice Smith!"
1801 "#} },
1802 Example { name: "variable override", fence_meta: None, code: indoc! {r#"
1803 # Same escaping: keep the placeholder literal until EXPAND.
1804 # A lone $who evaluates, like ECHO $who.
1805 LET $who: STRING = "Bob"
1806 WRITE template.md "Hi \{{ env:WHO }}!"
1807 EXPAND template.md WHO=$who
1808
1809 ASSERT_CONTAINS stdout "Hi Bob!"
1810 "#} },
1811 Example { name: "override forms agree", fence_meta: None, code: indoc! {r#"
1812 # A bare variable and a template-with-tail expand identically.
1813 LET $x: STRING = "Ada"
1814 WRITE template.md "Hi \{{ env:NAME }} and \{{ env:NAME2 }}!"
1815 EXPAND template.md NAME=$x NAME2="{{ $x }} concatenated"
1816
1817 ASSERT_CONTAINS stdout "Hi Ada and Ada concatenated!"
1818 "#} },
1819 Example { name: "expand stdin", fence_meta: None, code: indoc! {r#"
1820 # No path: the template arrives on stdin through a pipe.
1821 LET $tpl: PIPE
1822 WITH_IO [stdout=$tpl] ECHO "Hello \{{ env:NAME }}!"
1823 WITH_IO [stdin=$tpl] EXPAND NAME=Alice
1824
1825 ASSERT_CONTAINS stdout "Hello Alice!"
1826 "#} },
1827 Example { name: "override does not leak", fence_meta: None, code: indoc! {r#"
1828 # KEY=val overrides shadow env for that EXPAND only.
1829 # They never update the environment itself.
1830 ENV NAME="Alice"
1831 WRITE template.md "Hi \{{ env:NAME }}!"
1832
1833 EXPAND template.md NAME="Bob"
1834 ASSERT_CONTAINS stdout "Hi Bob!"
1835
1836 EXPAND template.md
1837 ASSERT_CONTAINS stdout "Hi Alice!"
1838 "#} },
1839 Example { name: "function call", fence_meta: None, code: indoc! {r#"
1840 # Pure registry functions run inside placeholders.
1841 # WRITE would interpolate {{ }} right away, so escape it.
1842 IMPORT [STD]
1843 WRITE template.md "Count: \{{ STD::TEXT_COUNT(\"one two two three\", \"two\") }}!"
1844
1845 EXPAND template.md
1846 ASSERT_CONTAINS stdout "Count: 2!"
1847 "#} },
1848 ],
1849 lower: |_flags, args| {
1850 let mut path = None;
1851 let mut overrides = Vec::new();
1852 for arg in args {
1853 let text = arg.as_str();
1854 if let Some((key, value)) = split_assignment(text).map_err(|e| ParseError::validation("EXPAND", e.to_string(), &SpanContext::line_only(0)))? {
1855 overrides.push((key, value));
1856 } else if path.is_none() { path = Some(arg); }
1857 else { return Err(ParseError::validation("EXPAND", "EXPAND accepts at most one path".to_string(), &SpanContext::line_only(0))) }
1858 }
1859 Ok(StepKind::Expand { path, overrides })
1860 },
1861 ],
1862
1863 AssertEq => [
1864 name: "ASSERT_EQ",
1865 variant: AssertEq { hash: Option<String>, actual: AssertTarget, expected: Option<Arg> },
1866 syntax: "ASSERT_EQ <actual> <expected> | ASSERT_EQ --hash <sha256> <actual>",
1867 summary: "Assert strict equality.",
1868 description: indoc! {r#"
1869 Compares two evaluated values with typed equality (no coercion:
1870 `INT(42)` never equals `STRING("42")`), aborting the pipeline
1871 with a step-numbered error showing expected vs actual otherwise.
1872
1873 Both sides are values: `$var`, literals, templates, and calls
1874 evaluate in memory and never touch disk. Read files explicitly
1875 first (`LET $text: STRING = READ "out.txt"`, then
1876 `ASSERT_EQ $text ...`).
1877 Bare `stdout` / `stderr` observe stream buffers; a `$var`
1878 holding a `PIPE` observes its backend bytes. `--hash` compares
1879 the SHA-256 of a string, pipe, or captured-stdout actual
1880 instead of the raw bytes (`stderr` is unsupported).
1881 "#},
1882 args: &[
1883 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 },
1884 ArgSpec { name: "expected", arg_type: ArgType::Rest(&ArgType::Any), description: "Expected (required unless --hash)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
1885 ],
1886 flags: &[ FlagSpec { name: "hash", long: "--hash", value_type: FlagValueType::String, required: false, description: "SHA-256" } ],
1887 default_output: None,
1888 examples: &[ Example { name: "assert eq", fence_meta: None, code: indoc! {r#"
1889 LET $status: INT = 200
1890 ASSERT_EQ $status 200
1891 "#} },
1892 Example { name: "assert eq file", fence_meta: None, code: indoc! {r#"
1893 WRITE payload.bin stable-content
1894 LET $body: STRING = READ payload.bin
1895 ASSERT_EQ $body "stable-content"
1896 "#} },
1897 Example { name: "assert eq hash", fence_meta: None, code: indoc! {r#"
1898 # --hash compares the SHA-256 digest instead of raw bytes.
1899 WRITE payload.bin stable-content
1900 LET $body: STRING = READ payload.bin
1901 ASSERT_EQ --hash 08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c $body
1902 "#} } ],
1903 lower: |flags, args| {
1904 let hash = flags.iter().find(|(k, _)| k == "hash").map(|(_, v)| v.as_str().to_string());
1905 let mut it = args.into_iter();
1906 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)))?)?;
1907 let remaining: Vec<Arg> = it
1908 .map(lower_assert_operand)
1909 .collect::<Vec<Arg>>();
1910 let expected = if remaining.is_empty() {
1913 if hash.is_some() {
1914 None
1915 } else {
1916 return Err(ParseError::validation("ASSERT_EQ", "ASSERT_EQ requires an expected value".to_string(), &SpanContext::line_only(0)))
1917 }
1918 } else {
1919 Some(join_value(remaining, "ASSERT_EQ")?)
1920 };
1921 Ok(StepKind::AssertEq { hash, actual, expected })
1922 },
1923 ],
1924
1925 AssertContains => [
1926 name: "ASSERT_CONTAINS",
1927 variant: AssertContains { haystack: AssertTarget, needle: Arg },
1928 syntax: "ASSERT_CONTAINS <haystack> <needle>",
1929 summary: "Assert containment.",
1930 description: indoc! {r#"
1931 Checks containment and aborts the pipeline with a step-numbered
1932 error otherwise: substring for strings, element match for lists,
1933 key presence for maps, substring over stream and pipe buffers.
1934
1935 Like `ASSERT_EQ`, both sides are values read without implicit
1936 I/O; read files explicitly first
1937 (`LET $text: STRING = READ "cfg.txt"`).
1938 Bare `stdout` / `stderr` observe stream buffers; a `$var`
1939 holding a `PIPE` observes its backend bytes.
1940 "#},
1941 args: &[
1942 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 },
1943 ArgSpec { name: "needle", arg_type: ArgType::Rest(&ArgType::Any), description: "Substring, element, or key", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
1944 ],
1945 flags: &[],
1946 default_output: None,
1947 examples: &[ Example { name: "assert contains", fence_meta: None, code: indoc! {r#"
1948 ECHO build-complete
1949 ASSERT_CONTAINS stdout "build-complete"
1950 "#} } ],
1951 lower: |flags, args| {
1952 let _ = flags;
1953 let mut it = args.into_iter();
1954 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)))?)?;
1955 let remaining: Vec<Arg> = it
1956 .map(lower_assert_operand)
1957 .collect::<Vec<Arg>>();
1958 if remaining.is_empty() {
1959 return Err(ParseError::validation("ASSERT_CONTAINS", "ASSERT_CONTAINS requires a needle".to_string(), &SpanContext::line_only(0)))
1960 }
1961 let needle = join_value(remaining, "ASSERT_CONTAINS")?;
1962 Ok(StepKind::AssertContains { haystack, needle })
1963 },
1964 ],
1965
1966 HashSha256 => [
1967 name: "HASH_SHA256",
1968 variant: HashSha256 { path: Arg },
1969 syntax: "HASH_SHA256 <path>",
1970 summary: "Print SHA-256.",
1971 description: "Computes digest.",
1972 args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Read, index: 0, required: true, fallback_stream: None } ],
1973 flags: &[],
1974 default_output: Some(Stream::Stdout),
1975 examples: &[ Example { name: "hash", fence_meta: None, code: indoc! {r#"
1976 WRITE payload.txt hello
1977 HASH_SHA256 payload.txt
1978
1979 LET $digest: STRING = HASH_SHA256 payload.txt
1980 ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\n"
1981 "#} } ],
1982 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)))? }),
1983 ],
1984
1985 Exit => [
1986 name: "EXIT",
1987 variant: Exit(Arg),
1988 syntax: "EXIT <code>",
1989 summary: "Exit pipeline.",
1990 description: indoc! {r#"
1991 Stops the pipeline immediately with an `EXIT requested with code <code>`
1992 error; steps after it never run, at any nesting depth.
1993
1994 Enclosing blocks still unwind their LET/ENV/WORKDIR/WORKSPACE state,
1995 anonymous background tasks are killed synchronously, and files written
1996 before the EXIT persist.
1997
1998 The code reaches the OS: the CLI exits with `<code>` clamped to
1999 0..=255, and a guest EXIT relays through `REMOTE` the same way.
2000 "#},
2001 args: &[ ArgSpec { name: "code", arg_type: ArgType::Int, description: "Code", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
2002 flags: &[],
2003 default_output: None,
2004 examples: &[ Example { name: "exit", fence_meta: Some("expect_error:\"EXIT requested with code 0\""), code: indoc! {r#"EXIT 0"#} } ],
2005 lower: |_flags, args| {
2006 let code = args.into_iter().next().ok_or_else(|| ParseError::validation("EXIT", "EXIT requires a code".to_string(), &SpanContext::line_only(0)))?;
2009 Ok(StepKind::Exit(code))
2010 },
2011 ],
2012
2013 Sleep => [
2014 name: "SLEEP",
2015 variant: Sleep { duration: Arg },
2016 syntax: "SLEEP <duration>",
2017 summary: "Pause execution for a duration.",
2018 description: indoc! {r#"
2019 Parks the step for the duration (e.g. 500ms, 10s, 2m).
2020
2021 Cooperative: checks for cancellation so an enclosing TIMEOUT or task
2022 teardown interrupts the sleep. Cross-platform alternative to shell sleep
2023 for testing time boundaries.
2024 "#},
2025 args: &[ ArgSpec { name: "duration", arg_type: ArgType::Duration, description: "How long to sleep", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
2026 flags: &[],
2027 default_output: None,
2028 examples: &[
2029 Example { name: "sleep", fence_meta: None, code: indoc! {r#"SLEEP 100ms"#} },
2030 Example {
2031 name: "sleep variable duration",
2032 fence_meta: None,
2033 code: indoc! {r#"
2034 # Durations resolve at runtime, so variables work too:
2035 # quoted or bare, both bind the same string.
2036 LET $pause: STRING = "100ms"
2037 SLEEP $pause
2038
2039 LET $bare: STRING = 100ms
2040 SLEEP $bare
2041 "#},
2042 },
2043 ],
2044 lower: |_flags, args| {
2045 let mut it = args.into_iter();
2046 let raw = it
2047 .next()
2048 .ok_or_else(|| ParseError::validation("SLEEP", "SLEEP requires a duration (e.g. SLEEP 500ms)".to_string(), &SpanContext::line_only(0)))?;
2049 if it.next().is_some() {
2050 return Err(ParseError::validation("SLEEP", "SLEEP takes exactly one duration argument".to_string(), &SpanContext::line_only(0)))
2051 }
2052 Ok(StepKind::Sleep { duration: raw })
2055 },
2056 ],
2057
2058 ListAppend => [
2059 name: "LIST_APPEND",
2060 variant: ListAppend { list: String, item: Arg },
2061 syntax: "LIST_APPEND $list <item>",
2062 summary: "Append an item to a LIST variable in place.",
2063 description: indoc! {r#"
2064 Appends the item to the LIST variable in place.
2065
2066 When the binding holds the only reference the push runs in
2067 amortized constant time. Aliased buffers detach first, so
2068 other holders keep their contents.
2069 "#},
2070 args: &[
2071 ArgSpec { name: "list", arg_type: ArgType::List, description: "Target LIST variable (`$name`)", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
2072 ArgSpec { name: "item", arg_type: ArgType::Any, description: "Item to append (any value)", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
2073 ],
2074 flags: &[],
2075 default_output: None,
2076 examples: &[ Example { name: "list append", fence_meta: None, code: indoc! {r#"
2077 # Appends accumulate in order.
2078 LET $items: LIST<STRING> = []
2079 LIST_APPEND $items "first"
2080 LIST_APPEND $items "second"
2081
2082 LET $want: LIST<STRING> = ["first", "second"]
2083 ASSERT_EQ $items $want
2084 "#} } ],
2085 lower: |_flags, args| {
2086 let mut it = args.into_iter();
2087 let raw_list = it
2088 .next()
2089 .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)))?;
2090 let list = match raw_list {
2091 Arg::Expr(Expr::Var(name)) => name,
2092 Arg::String(s, _) => s.trim_start_matches('$').to_string(),
2093 other => return Err(ParseError::validation("LIST_APPEND", format!("LIST_APPEND requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
2094 };
2095 if list.is_empty() {
2096 return Err(ParseError::validation("LIST_APPEND", "LIST_APPEND requires a LIST variable (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))
2097 }
2098 let item = it
2099 .next()
2100 .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)))?;
2101 if it.next().is_some() {
2102 return Err(ParseError::validation("LIST_APPEND", "LIST_APPEND takes exactly two arguments: LIST_APPEND $list <item>".to_string(), &SpanContext::line_only(0)))
2103 }
2104 Ok(StepKind::ListAppend { list, item })
2105 },
2106 ],
2107}
2108
2109pub fn all_structural_metadata() -> Vec<CommandMeta> {
2117 vec![
2118 CommandMeta {
2119 name: "WITH_IO",
2120 syntax: "WITH_IO [<stream>[=$var], ...] <command> | WITH_IO [bindings] { <commands> } | WITH_IO [tty[, stdin=$p][, rows=<int>][, cols=<int>]] RUN ...",
2121 summary: "Reroute standard streams.",
2122 description: indoc! {r#"
2123 Reroutes the standard streams of the next command or, in block form,
2124 of every enclosed command.
2125
2126 Bindings map streams (`stdin`, `stdout`, `stderr`) to a PIPE-typed
2127 variable (`stdout=$p`, `stdin=$p`), resolved from the variable
2128 when the step runs. Both stdout and stderr pipes capture output
2129 the same way. Declare the handle first with `LET $p: PIPE`.
2130
2131 A `RUN` step can opt into a pseudo-terminal with the bare `tty`
2132 flag instead of a new command: `WITH_IO [tty] RUN [...]`
2133 spawns the child under a pty sized from the host terminal
2134 when it names none (24x80 fallback off-terminal;
2135 `rows = <int>` / `cols = <int>` override each side).
2136 Unnamed sides track the host window while the step runs
2137 (signal-driven on Unix, polled where no window signal
2138 exists); explicit sides stay pinned.
2139
2140 The master carries the child's interleaved stdout and stderr
2141 as one stream, so it routes exclusively to `stdout` (step
2142 capture or a `stdout = $p` pipe): `stderr` bindings alongside
2143 `tty` are rejected, and `tty` outside a `RUN` step is
2144 rejected. Pty-backed descriptors never promote to OS
2145 kernel pipes, even inside `ASYNC` single-`RUN` bodies.
2146
2147 `stdin = $p` feeds the master; bare `[tty]`
2148 with a real terminal stdin feeds host keys the same
2149 way (raw, transparent) and stays closed headless. Host
2150 interrupt keys reach the child instead of cancelling the
2151 step, so bind a step `TIMEOUT` for a guaranteed exit.
2152
2153 Expect pty translation in assertions:
2154 newlines arrive as carriage return plus newline, and prompts
2155 echo input. On Windows, lone line feeds in fed input expand
2156 to carriage-return line feeds for console submission, so
2157 portable scripts need no per-platform line endings.
2158
2159 An input pipe that EOFs contributes a
2160 terminal-echoed end-of-transmission marker on some
2161 platforms: prefer `ASSERT_CONTAINS` over byte-exact
2162 assertions on fed sessions.
2163
2164 Pipes hold bytes in memory and spill to a temp file above 8 MiB, so a
2165 producer can finish before the consumer starts.
2166
2167 If WITH_IO wraps an ASYNC block whose body is a single RUN, guarded or
2168 not, the pipe is a zero copy OS kernel pipe instead: pair it with a
2169 consumer that runs while the producer is alive, since output past the
2170 64 KiB kernel buffer stalls until drained. That promotion never crosses
2171 a function boundary: pipes created, bound, or passed by variable inside FUNC
2172 bodies are always script pipes, even when the surrounding task would
2173 otherwise promote.
2174
2175 A second producer or consumer on a live handle is an explicit
2176 error. A handle bound as output can later feed another
2177 command's `stdin`, connecting commands without touching the
2178 terminal. Binding `stdout` and `stderr` to the same live
2179 handle fails deterministically. Merge streams in shell
2180 via `2>&1` instead.
2181
2182 Nested blocks stack defaults; inline bindings override inherited ones for
2183 their command only; closing a block restores previous wiring.
2184 "#},
2185 args: &[],
2186 flags: &[],
2187 default_output: None,
2188 examples: &[
2189 Example {
2190 name: "with_io block",
2191 fence_meta: None,
2192 code: indoc! {r#"
2193 LET $log: PIPE
2194 WITH_IO [stdout=$log] {
2195 ECHO first
2196 ECHO second
2197 }
2198 WITH_IO [stdin=$log] WRITE captured.txt
2199
2200 # The piped bytes landed in the file.
2201 LET $body: STRING = READ captured.txt
2202 ASSERT_CONTAINS $body "first"
2203 ASSERT_CONTAINS $body "second"
2204 "#},
2205 },
2206 Example {
2207 name: "variable pipe binding",
2208 fence_meta: None,
2209 code: indoc! {r#"
2210 # Declare the pipe first: `LET $p: PIPE` mints a fresh
2211 # backend without touching a stream. A plain string here
2212 # would be a TypeMismatch.
2213 LET $p: PIPE
2214 WITH_IO [stdout=$p] ECHO hello
2215 WITH_IO [stdin=$p] READ_LINE $line
2216 ASSERT_EQ $line "hello"
2217 "#},
2218 },
2219 Example {
2220 name: "pty terminal binding",
2221 fence_meta: None,
2222 code: indoc! {r#"
2223 # A RUN step under bare `tty` sees a terminal: newlines
2224 # arrive translated, so assert with CONTAINS, never EQ.
2225 LET $p: PIPE
2226 WITH_IO [tty, stdout=$p] RUN "echo hello-tty"
2227 WITH_IO [stdin=$p] READ_LINE $line
2228 ASSERT_CONTAINS $line "hello-tty"
2229 "#},
2230 },
2231 ],
2232 },
2233 CommandMeta {
2234 name: "FOR",
2235 syntax: "FOR $item: TYPE IN <expr> { <commands> } | FOR $key: STRING, $value: TYPE IN <expr> { <commands> }",
2236 summary: "Iterate over a list or map.",
2237 description: indoc! {r#"
2238 The loop variable receives each element (lists) or value (maps); with
2239 two variables, the first receives the key.
2240
2241 Loop variables are declared with explicit types and scoped per iteration;
2242 they do not leak outward. The body may be a braced block
2243 or a single-line `{ ... }` command.
2244
2245 `GLOB("...")` patterns must be quoted (`*` is not a bare word, so
2246 `GLOB(*)` is a parse error); GLOB returns a root-relative sorted list,
2247 empty when nothing matches, and rejects `..` escapes.
2248 "#},
2249 args: &[],
2250 flags: &[],
2251 default_output: None,
2252 examples: &[
2253 Example {
2254 name: "for loop",
2255 fence_meta: None,
2256 code: indoc! {r#"
2257 # Each element binds in turn; the loop body sees every one.
2258 LET $items: LIST<STRING> = ["a", "b"]
2259 FOR $item: STRING IN $items {
2260 ECHO $item
2261 }
2262 ASSERT_CONTAINS stdout "a"
2263 ASSERT_CONTAINS stdout "b"
2264
2265 # Key and value bind together for maps.
2266 LET $map: MAP<x: INT> = {"x": 1}
2267 FOR $k: STRING, $v: INT IN $map {
2268 ECHO "{{ $k }}={{ $v }}"
2269 }
2270 ASSERT_CONTAINS stdout "x=1"
2271 "#},
2272 },
2273 Example {
2274 name: "expand every match",
2275 fence_meta: None,
2276 code: indoc! {r#"
2277 # Single-line body; $x is a template path, WHO an override.
2278 IMPORT [STD]
2279 WRITE a.txt "hi \{{ env:WHO }}!"
2280 FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
2281
2282 ASSERT_CONTAINS stdout "hi World!"
2283 "#},
2284 },
2285 ],
2286 },
2287 CommandMeta {
2288 name: "IF",
2289 syntax: "IF <expr> { <commands> } [ELSE IF <expr> { <commands> } ...] [ELSE { <commands> }]",
2290 summary: "Conditional execution.",
2291 description: indoc! {r#"
2292 The condition is evaluated as a boolean expression.
2293
2294 Prefix `!` negates (`IF !false`); `&&` binds tighter than
2295 `||`, and both short-circuit, so `IF true || $missing`
2296 never evaluates the right side. Only Bool values are
2297 accepted as conditions.
2298 "#},
2299 args: &[],
2300 flags: &[],
2301 default_output: None,
2302 examples: &[
2303 Example {
2304 name: "if else",
2305 fence_meta: None,
2306 code: indoc! {r#"
2307 IMPORT [STD]
2308
2309 # True branch runs; the false branch is skipped.
2310 IF true {
2311 WRITE yes.txt taken
2312 } ELSE {
2313 WRITE yes.txt skipped
2314 }
2315
2316 # ELSE IF selects the first true branch.
2317 IF false {
2318 WRITE skipped.txt no
2319 } ELSE IF true {
2320 WRITE fallback.txt taken
2321 }
2322
2323 # !false evaluates to true, so this branch runs.
2324 IF !false {
2325 WRITE negated.txt taken
2326 }
2327
2328 LET $yes_body: STRING = READ yes.txt
2329 LET $fallback_body: STRING = READ fallback.txt
2330 LET $negated_body: STRING = READ negated.txt
2331 ASSERT_EQ $yes_body "taken"
2332 ASSERT_EQ $fallback_body "taken"
2333 ASSERT_EQ $negated_body "taken"
2334 LET $t: STRING = PATH_TYPE("skipped.txt")
2335 ASSERT_EQ $t "absent"
2336 "#},
2337 },
2338 Example {
2339 name: "logical condition composition",
2340 fence_meta: None,
2341 code: indoc! {r#"
2342 IMPORT [STD]
2343 LET $role: STRING = "admin"
2344 LET $level: INT = 3
2345
2346 # || is true when either side holds; && needs both.
2347 IF $role == "owner" || $level >= 5 {
2348 WRITE unexpected.txt no
2349 } ELSE {
2350 WRITE fallback.txt or-false
2351 }
2352
2353 LET $fb: STRING = READ fallback.txt
2354 ASSERT_EQ $fb "or-false"
2355 LET $t1: STRING = PATH_TYPE("unexpected.txt")
2356 ASSERT_EQ $t1 "absent"
2357
2358 IF $role == "admin" || $level >= 5 {
2359 WRITE chosen.txt or-true
2360 }
2361
2362 LET $ch: STRING = READ chosen.txt
2363 ASSERT_EQ $ch "or-true"
2364
2365 IF $role == "admin" && $level >= 5 {
2366 WRITE unexpected-too.txt no
2367 } ELSE {
2368 WRITE and.txt and-false
2369 }
2370
2371 LET $an: STRING = READ and.txt
2372 ASSERT_EQ $an "and-false"
2373 LET $t2: STRING = PATH_TYPE("unexpected-too.txt")
2374 ASSERT_EQ $t2 "absent"
2375 "#},
2376 },
2377 ],
2378 },
2379 CommandMeta {
2380 name: "LET",
2381 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> }",
2382 summary: "Bind script-local variables.",
2383 description: indoc! {r#"
2384 Declares a script-local variable with an explicit type (STRING, INT,
2385 FLOAT, BOOL, PIPE, LIST, MAP, HANDLE, DURATION, PATH). Duplicate LET
2386 in the same scope frame is a redeclaration error; mutate with
2387 `$var = <expr>`.
2388
2389 Variables are usable in templates (`{{ $var }}`), guards, and
2390 expressions. With `ASYNC`, spawns a background task and stores its
2391 handle (see ASYNC). The `$` sigil on the name is mandatory.
2392
2393 No hoisting: a variable exists only after its LET runs, in
2394 execution order. Reading `$var` before its LET (or after the
2395 block that declared it exits) fails with
2396 `undefined variable $var`. Scopes are a stack of frames and
2397 resolution walks innermost outward, so nothing pre-declares
2398 names. Function bodies read outer variables through the same
2399 walk, but their own LETs never leak out (see FUNC).
2400
2401 The right-hand side is always an expression — literals, lists, maps,
2402 arithmetic (`+ - * /` with `*`/`/` binding tighter, unary `-`,
2403 parentheses), comparisons (`< <= > >=` binding tighter than
2404 `== !=`), logical `&&` (tighter) and `||` with short-circuit,
2405 `!` negation, `env:KEY` reads, `INSPECT($var)` snapshots,
2406 `GLOB("*.md")`, `INT(x)` / `FLOAT(x)` conversions — never a
2407 `{{ ... }}` template; interpolation happens in string values,
2408 not here.
2409 The one exception is pipes: `LET $p: PIPE` with no `=`
2410 and no initializer mints a fresh anonymous backend,
2411 lazily materialized at first binding, so two declarations
2412 never share a channel.
2413
2414 Numbers are numeric literals: `42` binds `INT`, `3.14` binds
2415 `FLOAT`. `Int x Int` stays `INT` (checked, integer division,
2416 so `7 / 2` is `3`); any `Float` operand promotes to `FLOAT`.
2417 Division by zero, overflow, and non-finite results are errors.
2418 Both numeric sides compare numerically (`1 == 1.0` is true);
2419 otherwise `==`/`!=` compare rendered strings and ordering on
2420 non-numerics is a Type Error. Constant subtrees fold at parse
2421 time and dynamic arithmetic compiles to flat RPN with
2422 identical semantics.
2423
2424 Float equality is exact with no epsilon. Floats store decimals
2425 in binary, so a value is exact only when its reduced fraction
2426 has a power-of-2 denominator: 0.5 (1/2), 0.25 (1/4), 0.75
2427 (3/4) are exact, while 0.1 (1/10), 0.2 (1/5), 0.3 (3/10)
2428 repeat forever in binary (like 1/3 in decimal) and truncate,
2429 so `0.1 + 0.2 == 0.3` is false (the sum is
2430 `0.30000000000000004`). Rule of thumb: endings .5, .25, .75,
2431 .125, .625, .875 are exact; .1, .2, .3 and similar are
2432 approximations. Bound approximations instead of comparing
2433 them: `IF $sum > 0.299999 && $sum < 0.300001`.
2434
2435 Comparisons do not chain: `a < b < c` is a parse error, not
2436 `(a < b) < c`. Chaining would compare a `BOOL` against a
2437 number (a runtime Type Error in C-style parsing) or evaluate
2438 the middle term twice (Python-style chaining), so the grammar
2439 accepts exactly one comparison operator per level. Write the
2440 conjunction explicitly: `$a < $b && $b < $c`. The same holds
2441 for equality (`$a == $b == $c` is rejected).
2442
2443 Captured command output is a string, so convert before math:
2444 `LET $total: INT = $total + INT($size_str)` (`INT` trims ASCII
2445 whitespace; `FLOAT` accepts int strings and rejects
2446 non-finite).
2447
2448 Bare words need no quotes: `LET $d: STRING = 30s` binds the same string
2449 as quoted.
2450
2451 When the right-hand side is a synchronous command
2452 (`LET $out: STRING = ECHO hi`), the command runs to completion and its
2453 exact stdout bytes are captured into the variable as a string (no newline
2454 stripping; commands with no stdout capture as `""`; non-UTF8 stdout is
2455 an error). Combining capture with an explicit
2456 `WITH_IO [stdout=$var]` is a parse error.
2457
2458 Coming from Bash, the capture line looks familiar but behaves
2459 strictly:
2460
2461 | | Bash `output=$(...)` | OxDock `LET $out: STRING = ...` |
2462 | --- | --- | --- |
2463 | Trailing newlines | Stripped (all of them) | Preserved byte-exact |
2464 | Variable type | Always an untyped string | Declared: STRING, INT, FLOAT, ... |
2465 | Math on output | Implicit: `$((var + 1))` | Explicit: `INT($out) + 1` |
2466 | Failing command | Continues with empty output unless `set -e` | Step fails immediately, binds nothing |
2467
2468 `LET $out: TYPE = AWAIT $var` binds the background task's
2469 explicit `RETURN` value instead (tasks stream their stdout
2470 live, so there is no output left to capture); a task that
2471 succeeded without `RETURN` yields `INT` 0, like a process
2472 exit status.
2473
2474 An inline block (`LET $var: TYPE = { <commands> }`) runs its
2475 steps in a fresh scope and binds the nearest `RETURN` value,
2476 like a zero-arg function body: fallthrough without `RETURN`
2477 binds `""`, and `BREAK`/`CONTINUE` escaping the block are
2478 errors. Think IIFE: the block executes immediately where it
2479 stands and its value is the result. The block reads outer
2480 variables but its own LETs never leak out. A `{k: v}` shape
2481 still parses as a map literal; anything else in braces is
2482 a block.
2483
2484 The split is deliberate: synchronous commands capture
2485 stdout because they run inline to completion on the same
2486 thread; background tasks never capture stdout because
2487 concurrent output has no well-defined value. Task results
2488 travel only through `RETURN` (or `INT` 0 for void tasks).
2489
2490 `LET $e: STRING = env:FOO` reads the script environment into a plain
2491 string.
2492 "#},
2493 args: &[],
2494 flags: &[],
2495 default_output: None,
2496 examples: &[
2497 Example {
2498 name: "let",
2499 fence_meta: None,
2500 code: indoc! {r#"
2501 LET $name: STRING = "world"
2502 ECHO "hello, {{ $name }}"
2503 ASSERT_CONTAINS stdout "hello, world"
2504
2505 LET $items: LIST<STRING> = ["a", "b"]
2506 ASSERT_CONTAINS $items "a"
2507 ASSERT_CONTAINS $items "b"
2508
2509 LET $count: INT = 42
2510 ASSERT_EQ $count 42
2511 "#},
2512 },
2513 Example {
2514 name: "no hoisting",
2515 fence_meta: Some("expect_error:\"undefined variable\""),
2516 code: indoc! {r#"
2517 # Reading before the LET runs is an error, not an empty value.
2518 ECHO $too_early
2519 LET $too_early: STRING = "too late"
2520 "#},
2521 },
2522 Example {
2523 name: "glob binding",
2524 fence_meta: None,
2525 code: indoc! {r#"
2526 # The RHS is an expression: GLOB(...) runs and binds a list.
2527 IMPORT [STD]
2528 WRITE a.txt "x"
2529 LET $files: LIST<STRING> = GLOB("*.txt")
2530 FOR $f: STRING IN $files { ECHO $f }
2531
2532 ASSERT_CONTAINS stdout "a.txt"
2533 "#},
2534 },
2535 Example {
2536 name: "scoped variable reverts",
2537 fence_meta: None,
2538 code: indoc! {r#"
2539 # LET inside a braced block reverts when the block exits.
2540 LET $a: STRING = "outer"
2541
2542 [bool:true] {
2543 LET $a: STRING = "inner"
2544 WRITE inner.txt "{{ $a }}"
2545 }
2546
2547 WRITE outer.txt "{{ $a }}"
2548
2549 LET $in_body: STRING = READ inner.txt
2550 ASSERT_EQ $in_body "inner"
2551
2552 LET $out_body: STRING = READ outer.txt
2553 ASSERT_EQ $out_body "outer"
2554 "#},
2555 },
2556 Example {
2557 name: "capture command output",
2558 fence_meta: None,
2559 code: indoc! {r#"
2560 # Capture keeps the trailing newline.
2561 LET $out: STRING = ECHO hi
2562 ASSERT_EQ $out "hi\n"
2563 "#},
2564 },
2565 Example {
2566 name: "inline block",
2567 fence_meta: None,
2568 code: indoc! {r#"
2569 LET $who: STRING = "ada"
2570
2571 # An inline block binds its RETURN value like a function body.
2572 LET $res: STRING = {
2573 LET $loud: STRING = "{{ $who }}!"
2574 RETURN $loud
2575 }
2576 ASSERT_EQ $res "ada!"
2577
2578 # Any declared type works: the block value checks like any RHS.
2579 LET $n: INT = {
2580 RETURN 40 + 2
2581 }
2582 ASSERT_EQ $n 42
2583 "#},
2584 },
2585 Example {
2586 name: "arithmetic over captured output",
2587 fence_meta: None,
2588 code: indoc! {r#"
2589 # Captured output converts explicitly: INT() then arithmetic.
2590 IMPORT [STD]
2591 LET $size_str: STRING = ECHO 41
2592 LET $total: INT = INT($size_str) + 1
2593 ASSERT_EQ $total 42
2594
2595 # FLOAT() promotes instead of truncating.
2596 LET $ratio: FLOAT = 1 + 2.5
2597 ASSERT_EQ $ratio 3.5
2598
2599 # Int x Int stays INT: integer division truncates.
2600 LET $half: INT = 7 / 2
2601 ASSERT_EQ $half 3
2602 "#},
2603 },
2604 Example {
2605 name: "float equality is exact",
2606 fence_meta: None,
2607 code: indoc! {r#"
2608 # Binary fractions compare cleanly; decimal fractions may not:
2609 # 0.1 + 0.2 is 0.30000000000000004, so == is false.
2610 IMPORT [STD]
2611 LET $exact: BOOL = 0.5 + 0.25 == 0.75
2612 LET $decimal: BOOL = 0.1 + 0.2 == 0.3
2613 IF $exact {
2614 WRITE exact.txt yes
2615 }
2616 IF $decimal {
2617 WRITE unexpected.txt no
2618 }
2619
2620 LET $ok: STRING = READ exact.txt
2621 ASSERT_EQ $ok "yes"
2622
2623 LET $t: STRING = PATH_TYPE("unexpected.txt")
2624 ASSERT_EQ $t "absent"
2625 "#},
2626 },
2627 Example {
2628 name: "bound inexact decimals",
2629 fence_meta: None,
2630 code: indoc! {r#"
2631 # Never test inexact decimals for equality; bound them.
2632 LET $sum: FLOAT = 0.1 + 0.2
2633 IF $sum > 0.299999 && $sum < 0.300001 {
2634 WRITE bounded.txt yes
2635 }
2636
2637 LET $ok: STRING = READ bounded.txt
2638 ASSERT_EQ $ok "yes"
2639 "#},
2640 },
2641 Example {
2642 name: "inspect a variable",
2643 fence_meta: None,
2644 code: indoc! {r#"
2645 # INSPECT($var) snapshots a variable into a MAP: declared
2646 # type plus live details (pipe backend stats here), so
2647 # scripts can branch on engine state.
2648 IMPORT [STD]
2649 LET $p: PIPE
2650 WITH_IO [stdout=$p] ECHO hello
2651 LET $info: MAP<ANY> = INSPECT($p)
2652 IF $info.is_os_pipe {
2653 WRITE unexpected.txt "should be a script pipe"
2654 }
2655
2656 ASSERT_EQ $info.type "PIPE"
2657 LET $t: STRING = PATH_TYPE("unexpected.txt")
2658 ASSERT_EQ $t "absent"
2659 "#},
2660 },
2661 ],
2662 },
2663 CommandMeta {
2664 name: "MUTATION",
2665 syntax: "$var = <expr>",
2666 summary: "Mutate a declared variable.",
2667 description: indoc! {r#"
2668 Reassigns an existing variable, converting the new value to
2669 the type declared at LET time. The explicit annotation is
2670 what authorizes string-to-number conversion here (`$n = "42"`
2671 binds 42 for an INT); a non-numeric string is an error.
2672 Expressions never convert: `"100" + 1` is a Type Error, use
2673 `INT()` / `FLOAT()` to cross that boundary explicitly.
2674
2675 The leading `$` distinguishes mutation from `KEY=value` command
2676 assignments. Assigning an undeclared variable or a mismatched type is
2677 an error.
2678
2679 Mutation writes through to the scope where the variable was
2680 declared, so it survives block exit: `LET $x` outside a block
2681 followed by `$x = ...` inside still reads back the new value
2682 afterwards, for every type. This is the counterpart to LET
2683 shadowing, where `LET $x` *inside* the block declares a
2684 separate inner variable that reverts on exit.
2685
2686 Reassignment rebinds the variable to a new value: values
2687 captured earlier keep the old word (see the rebinding
2688 example below).
2689 "#},
2690 args: &[],
2691 flags: &[],
2692 default_output: None,
2693 examples: &[
2694 Example {
2695 name: "mutate",
2696 fence_meta: None,
2697 code: indoc! {r#"
2698 # Mutation writes through: the binding holds the new value.
2699 LET $count: INT = 1
2700 $count = 2
2701 ASSERT_EQ $count 2
2702 "#},
2703 },
2704 Example {
2705 name: "rebind keeps earlier captures",
2706 fence_meta: None,
2707 code: indoc! {r#"
2708 # Reassignment rebinds: a map built from `$s` still
2709 # reads the original string after `$s` moves on.
2710 LET $s: STRING = "test"
2711 LET $m: MAP<ANY> = {a: $s}
2712 $s = "changed"
2713 ASSERT_EQ $m.a "test"
2714
2715 # Appending to one list binding never touches its clones.
2716 LET $a: LIST<STRING> = ["1"]
2717 LET $b: LIST<STRING> = $a
2718 LIST_APPEND $a "2"
2719 LET $want: LIST<STRING> = ["1"]
2720 ASSERT_EQ $b $want
2721 "#},
2722 },
2723 Example {
2724 name: "convert before math",
2725 fence_meta: None,
2726 code: indoc! {r#"
2727 # Captured output is a string: `"100" + 1` is a Type Error.
2728 # Convert explicitly, then mutate with arithmetic.
2729 IMPORT [STD]
2730 LET $raw: STRING = ECHO 100
2731 LET $n: INT = INT($raw)
2732 $n = $n + 1
2733
2734 # The declared slot stays strict: strings parse only
2735 # through the explicit converter, never on assignment.
2736 $n = INT("42")
2737 ASSERT_EQ $n 42
2738
2739 # Same crossing for decimals via FLOAT().
2740 LET $frac_str: STRING = ECHO 2.5
2741 LET $f: FLOAT = FLOAT($frac_str) + 0.25
2742 ASSERT_EQ $f 2.75
2743 "#},
2744 },
2745 ],
2746 },
2747 CommandMeta {
2748 name: "ASYNC",
2749 syntax: "ASYNC <command...> | ASYNC { <commands> } | LET $var: HANDLE = ASYNC { <commands> }",
2750 summary: "Run steps in a background thread.",
2751 description: indoc! {r#"
2752 Runs a command or block of commands in a background thread with
2753 subshell isolation.
2754
2755 Mutations (ENV, WORKDIR) stay within the block. With `LET`, stores a
2756 task handle for `AWAIT`. Task output streams live to the parent
2757 stdout; a task publishes a value with an explicit `RETURN`,
2758 which `LET $out: TYPE = AWAIT $task` binds.
2759
2760 `WITH_IO` must wrap `ASYNC` from the outside (`LET $p: PIPE` first,
2761 then `WITH_IO [stdout=$p] ASYNC ...`) so pipe endpoints allocate on
2762 the main thread before the worker spawns. Placing `WITH_IO` directly
2763 inside `ASYNC` is rejected at parse time.
2764 "#},
2765 args: &[],
2766 flags: &[],
2767 default_output: None,
2768 examples: &[
2769 Example {
2770 name: "async",
2771 fence_meta: None,
2772 code: indoc! {r#"
2773 # Inline and block forms both run in the background; AWAIT joins them.
2774 ASYNC ECHO "warming-up"
2775 LET $a: HANDLE = ASYNC ECHO "first"
2776 LET $b: HANDLE = ASYNC {
2777 ECHO "second"
2778 }
2779 AWAIT $a
2780 AWAIT $b
2781 ASSERT_CONTAINS stdout "first"
2782 ASSERT_CONTAINS stdout "second"
2783 "#},
2784 },
2785 Example {
2786 name: "async task handle",
2787 fence_meta: None,
2788 code: indoc! {r#"
2789 LET $task: HANDLE = ASYNC {
2790 ECHO "built"
2791 }
2792 AWAIT $task
2793 ASSERT_CONTAINS stdout "built"
2794 "#},
2795 },
2796 ],
2797 },
2798 CommandMeta {
2799 name: "AWAIT",
2800 syntax: "AWAIT $var | LET $out: STRING = AWAIT $var",
2801 summary: "Join a background task.",
2802 description: indoc! {r#"
2803 Blocks until the named task completes. Propagates errors if the task failed.
2804
2805 Task output streams live during the run; joining binds nothing by
2806 itself. `LET $out: TYPE = AWAIT $var` binds the task's explicit
2807 `RETURN` value instead, or `INT` 0 when the task succeeded
2808 without one (add `RETURN <expr>` to the task body to yield
2809 a value).
2810 "#},
2811 args: &[],
2812 flags: &[],
2813 default_output: None,
2814 examples: &[
2815 Example {
2816 name: "await",
2817 fence_meta: None,
2818 code: indoc! {r#"
2819 LET $task: HANDLE = ASYNC ECHO "done"
2820 AWAIT $task
2821 ASSERT_CONTAINS stdout "done"
2822 "#},
2823 },
2824 Example {
2825 name: "await capture",
2826 fence_meta: None,
2827 code: indoc! {r#"
2828 LET $task: HANDLE = ASYNC {
2829 ECHO "logged"
2830 RETURN "returned"
2831 }
2832
2833 # AWAIT binds the RETURN value, not the streamed output.
2834 LET $out: STRING = AWAIT $task
2835 ASSERT_EQ $out "returned"
2836 "#},
2837 },
2838 ],
2839 },
2840 CommandMeta {
2841 name: "CANCEL",
2842 syntax: "CANCEL $var",
2843 summary: "Synchronously cancel a background task.",
2844 description: indoc! {r#"
2845 Kills the named background task spawned via LET $var: HANDLE = ASYNC ....
2846
2847 Blocking: returns only after the task thread has been joined and its OS
2848 process reaped, so no residual filesystem or stream mutation follows. A
2849 later AWAIT $var reports cancellation. Only named tasks can be cancelled.
2850 "#},
2851 args: &[],
2852 flags: &[],
2853 default_output: None,
2854 examples: &[
2855 Example {
2856 name: "cancel",
2857 fence_meta: None,
2858 code: indoc! {r#"
2859 LET $task: HANDLE = ASYNC SLEEP 30s
2860 CANCEL $task
2861 "#},
2862 },
2863 Example {
2864 name: "await after cancel reports cancellation",
2865 fence_meta: Some("expect_error:\"was cancelled\""),
2866 code: indoc! {r#"
2867 # A cancelled task stays cancelled: joining it reports.
2868 LET $task: HANDLE = ASYNC SLEEP 30s
2869 CANCEL $task
2870 AWAIT $task
2871 "#},
2872 },
2873 ],
2874 },
2875 CommandMeta {
2876 name: "TIMEOUT",
2877 syntax: "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> } | TIMEOUT <duration> AWAIT $var",
2878 summary: "Enforce an execution deadline.",
2879 description: indoc! {r#"
2880 Aborts the wrapped step or block with a deadline error if it exceeds the
2881 duration (e.g. 500ms, 10s, 2m; a bare number means seconds).
2882
2883 A blocking foreground process is killed.
2884
2885 ASYNC composes in either nesting order with order-dependent deadline
2886 semantics: `LET $task: HANDLE = ASYNC TIMEOUT 30s RUN "build"` enforces
2887 the deadline inside the background thread (a later `AWAIT $task`
2888 surfaces the `TIMEOUT` error), while `TIMEOUT 30s AWAIT $task`
2889 preempts a hung task from the awaiting side.
2890 "#},
2891 args: &[],
2892 flags: &[],
2893 default_output: None,
2894 examples: &[
2895 Example {
2896 name: "timeout",
2897 fence_meta: None,
2898 code: indoc! {r#"
2899 TIMEOUT 30s WRITE heartbeat.txt alive
2900 LET $beat: STRING = READ heartbeat.txt
2901 ASSERT_EQ $beat "alive"
2902 "#},
2903 },
2904 Example {
2905 name: "timeout block",
2906 fence_meta: None,
2907 code: indoc! {r#"
2908 TIMEOUT 30s {
2909 WRITE a.txt one
2910 WRITE b.txt two
2911 }
2912 LET $a: STRING = READ a.txt
2913 LET $b: STRING = READ b.txt
2914 ASSERT_EQ $a "one"
2915 ASSERT_EQ $b "two"
2916 "#},
2917 },
2918 Example {
2919 name: "deadline aborts the step",
2920 fence_meta: Some("expect_error:\"TIMEOUT after\""),
2921 code: indoc! {r#"
2922 # 50ms expires long before the sleep does: the step dies
2923 # with a deadline error instead of running out the clock.
2924 TIMEOUT 50ms SLEEP 30s
2925 "#},
2926 },
2927 Example {
2928 name: "timeout variable duration",
2929 fence_meta: None,
2930 code: indoc! {r#"
2931 # Durations resolve at runtime, so variables work too.
2932 LET $budget: DURATION = "30s"
2933 TIMEOUT $budget WRITE heartbeat.txt alive
2934
2935 LET $beat: STRING = READ heartbeat.txt
2936 ASSERT_EQ $beat "alive"
2937 "#},
2938 },
2939 Example {
2940 name: "timeout await",
2941 fence_meta: None,
2942 code: indoc! {r#"
2943 # AWAIT form bounds a task join instead of a step.
2944 LET $quick: HANDLE = ASYNC {
2945 ECHO hi
2946 }
2947 TIMEOUT 30s AWAIT $quick
2948 "#},
2949 },
2950 ],
2951 },
2952 CommandMeta {
2953 name: "ISOLATED",
2954 syntax: "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>",
2955 summary: "Run steps with the seeded script environment.",
2956 description: indoc! {r#"
2957 Resets the script environment for the block to the session
2958 seed: spawned children see the sandbox defaults plus names
2959 the block re-adds through its leading `INHERIT_ENV`.
2960
2961 The allowlist resolves against the outer scope, never the
2962 host. Absent names stay absent silently, matching top-level
2963 `INHERIT_ENV`.
2964
2965 Script variables, pipes, and files flow through untouched;
2966 only `env:` is reset. Files share the session workspace:
2967 blocks selecting the same `WORKSPACE` target resolve to the
2968 same directory with no per-block overlay, so one block's
2969 writes are visible to another.
2970
2971 Blocks nest (each level re-seeds from the same seed, so
2972 nesting only narrows through the allowlists) and compose
2973 with `ASYNC` and `FUNC`. Scope exit restores the prior
2974 environment.
2975 "#},
2976 args: &[],
2977 flags: &[],
2978 default_output: None,
2979 examples: &[
2980 Example {
2981 name: "isolated scope",
2982 fence_meta: None,
2983 code: indoc! {r#"
2984 # The block sees a clean env; plain steps still run and
2985 # outer bindings survive untouched.
2986 ENV MODE=outer
2987 ISOLATED {
2988 ENV MODE=inner
2989 WRITE inner.txt "{{ env:MODE }}"
2990 }
2991 LET $back: STRING = "{{ env:MODE }}"
2992 ASSERT_EQ $back "outer"
2993 LET $body: STRING = READ inner.txt
2994 ASSERT_EQ $body "inner"
2995 "#},
2996 },
2997 Example {
2998 name: "reseeded child env",
2999 fence_meta: None,
3000 code: indoc! {r#"
3001 # The block resets to the session seed: plain steps and
3002 # spawns run with zero prelude, while outer customs
3003 # stay out.
3004 ENV OUTER_CUSTOM=outer-val
3005 WRITE top-path.txt "{{ env:PATH }}"
3006 ISOLATED {
3007 WRITE inner-path.txt "{{ env:PATH }}"
3008 WRITE inner-custom.txt "{{ env:OUTER_CUSTOM }}"
3009 RUN "echo seed-ok"
3010 }
3011 LET $top: STRING = READ top-path.txt
3012 LET $inner: STRING = READ inner-path.txt
3013 ASSERT_EQ $inner $top
3014 LET $custom: STRING = READ inner-custom.txt
3015 ASSERT_EQ $custom ""
3016 ASSERT_CONTAINS stdout "seed-ok"
3017 "#},
3018 },
3019 Example {
3020 name: "absent names stay absent",
3021 fence_meta: None,
3022 code: indoc! {r#"
3023 # Listing a name the outer scope lacks is not an error:
3024 # the block simply runs without it.
3025 ISOLATED {
3026 INHERIT_ENV [OXDOC_DEFINITELY_ABSENT_12345]
3027 ECHO still-runs
3028 }
3029 ASSERT_CONTAINS stdout "still-runs"
3030 "#},
3031 },
3032 Example {
3033 name: "nesting narrows",
3034 fence_meta: None,
3035 code: indoc! {r#"
3036 # Each level snapshots the already-scrubbed parent, so
3037 # an inner block cannot recover what the outer dropped.
3038 ENV KEEP=yes
3039 ISOLATED {
3040 INHERIT_ENV [KEEP]
3041 ISOLATED {
3042 ENV KEEP=inner
3043 WRITE deep.txt "{{ env:KEEP }}"
3044 }
3045 LET $mid: STRING = "{{ env:KEEP }}"
3046 ASSERT_EQ $mid "yes"
3047 }
3048 LET $deep: STRING = READ deep.txt
3049 ASSERT_EQ $deep "inner"
3050 "#},
3051 },
3052 ],
3053 },
3054 CommandMeta {
3055 name: "REMOTE",
3056 syntax: "REMOTE <target> [[$var, ...] [env:NAME, ...]] { <commands> }",
3057 summary: "Run a sealed block on a remote target.",
3058 description: indoc! {r#"
3059 Runs the braced block on the named remote target, which the
3060 host binds at startup (`--remote`). The block is sealed:
3061 only header-listed `$var` and `env:NAME` entries cross, the
3062 guest starts empty, and results return through declared
3063 transfers or `WITH_IO` pipes.
3064
3065 The target is a static literal, never a variable. Unknown
3066 targets fail before execution starts.
3067
3068 Bodies check twice: the host static pass validates the
3069 body before anything ships, and the guest re-validates on
3070 arrival through the same entry point, so a body type error
3071 fails locally, never mid-run on the remote.
3072
3073 A failing guest fails the host step: EXIT in the body
3074 exits the guest, and the host relays the code to its own
3075 process exit status (see EXIT).
3076 "#},
3077 args: &[],
3078 flags: &[],
3079 default_output: None,
3080 examples: &[
3081 Example {
3082 name: "sealed header values cross, outer scope does not",
3083 fence_meta: Some("mock_remote:prod"),
3084 code: indoc! {r#"
3085 # Only header-listed names arrive: `$version` is visible
3086 # on the guest, `$secret` was never sent.
3087 LET $version: STRING = "1.2.3"
3088 LET $secret: STRING = "host-only"
3089 REMOTE prod [$version] {
3090 WRITE version.txt "{{ $version }}"
3091 COPY --to-host ./version.txt back.txt
3092 }
3093
3094 # The pushed file proves the guest saw the injected value.
3095 LET $back: STRING = READ back.txt
3096 ASSERT_EQ $back "1.2.3"
3097 "#},
3098 },
3099 Example {
3100 name: "background tasks stream through shared pipes",
3101 fence_meta: Some("mock_remote:prod"),
3102 code: indoc! {r#"
3103 # Two background REMOTEs share one capture pipe while a
3104 # WITH_IO block holds the write end open.
3105 IMPORT [STD]
3106 LET $cap: PIPE
3107 WITH_IO [stdout=$cap] {
3108 LET $a: HANDLE = ASYNC REMOTE prod {
3109 ECHO "from-a"
3110 }
3111 LET $b: HANDLE = ASYNC REMOTE prod {
3112 ECHO "from-b"
3113 }
3114 AWAIT $a
3115 AWAIT $b
3116 }
3117
3118 # EOF ends the drain: no sentinel line, no baked-in count.
3119 LET $n: INT = 0
3120 WHILE !EOF($cap) {
3121 WITH_IO [stdin=$cap] READ_LINE $line
3122 $n = $n + 1
3123 }
3124 ASSERT_EQ $n 2
3125 "#},
3126 },
3127 Example {
3128 name: "declared files cross both directions",
3129 fence_meta: Some("mock_remote:prod roots:unified"),
3130 code: indoc! {r#"
3131 # Fetches ride in, pushes ride back. Anything undeclared
3132 # never leaves its side.
3133 WRITE send.txt "payload"
3134 REMOTE prod {
3135 COPY --from-host ./send.txt got.txt
3136 LET $v: STRING = READ got.txt
3137 ASSERT_EQ $v "payload"
3138 WRITE back.txt "returned"
3139 COPY --to-host ./back.txt back.txt
3140 }
3141
3142 # The push landed on the host; guest staging is gone.
3143 LET $b: STRING = READ back.txt
3144 ASSERT_EQ $b "returned"
3145 "#},
3146 },
3147 Example {
3148 name: "guest workspace selection stays on the guest",
3149 fence_meta: Some("mock_remote:prod"),
3150 code: indoc! {r#"
3151 # WORKSPACE switches inside the block resolve against the
3152 # guest staging dir, which serves as both the SNAPSHOT
3153 # root and the LOCAL build context. The host selection
3154 # restores when the block exits.
3155 REMOTE prod {
3156 WORKSPACE SNAPSHOT
3157 WRITE out.txt "from-snapshot"
3158 COPY --to-host ./out.txt snap.txt
3159 }
3160
3161 LET $s: STRING = READ snap.txt
3162 ASSERT_EQ $s "from-snapshot"
3163 "#},
3164 },
3165 Example {
3166 name: "guest cache persists across execs",
3167 fence_meta: Some("mock_remote:prod"),
3168 code: indoc! {r#"
3169 # WORKSPACE CACHE addresses guest-local persistent
3170 # storage: the second block reads what the first wrote,
3171 # while the guest staging starts empty every time.
3172 REMOTE prod {
3173 WORKSPACE CACHE
3174 WRITE marker.txt "run-marker"
3175 }
3176 REMOTE prod {
3177 WORKSPACE CACHE
3178 LET $m: STRING = READ marker.txt
3179 ASSERT_EQ $m "run-marker"
3180 }
3181 "#},
3182 },
3183 Example {
3184 name: "pushes outside staging fail closed",
3185 fence_meta: Some("mock_remote:prod expect_error:\"escapes staging\""),
3186 code: indoc! {r#"
3187 # WORKSPACE SYSTEM exposes the whole guest machine, but
3188 # transfers stay staging scoped: a push source outside
3189 # staging fails loudly instead of crossing.
3190 REMOTE prod {
3191 WORKSPACE SYSTEM
3192 COPY --to-host /no/such/file.txt got.txt
3193 }
3194 "#},
3195 },
3196 Example {
3197 name: "guest exit fails the step, host survives",
3198 fence_meta: Some(
3199 "mock_remote:prod expect_error:\"REMOTE 'prod' exited with code 3\"",
3200 ),
3201 code: indoc! {r#"
3202 # EXIT in the body exits the guest with code 3. The
3203 # host is unaffected: it keeps executing after the
3204 # guest is already dead, and the failure surfaces as
3205 # a host step error carrying the same code. The CLI
3206 # then exits with it, so the guest code reaches the OS.
3207 LET $t: HANDLE = ASYNC REMOTE prod {
3208 EXIT 3
3209 }
3210 WRITE host-alive.txt "still here"
3211 AWAIT $t
3212 "#},
3213 },
3214 Example {
3215 name: "remote block without a runner",
3216 fence_meta: Some("expect_error:\"has no registered session\""),
3217 code: indoc! {r#"
3218 # Without a bound session, the block bails instead of
3219 # executing anywhere unexpected.
3220 REMOTE prod {
3221 ECHO "do something on remote"
3222 }
3223 "#},
3224 },
3225 ],
3226 },
3227 CommandMeta {
3228 name: "FUNC",
3229 syntax: "FUNC NAME([$param: TYPE, ...]) { <commands> }",
3230 summary: "Define a user function.",
3231 description: indoc! {r#"
3232 Defines a user function with UPPERCASE name and explicitly typed
3233 parameters.
3234
3235 Params bind by position, converting each argument to its
3236 declared parameter type before the body runs.
3237 Bodies run in a fresh variable scope; LETs inside do not leak. A nested
3238 FUNC definition is scoped to its block and reverts on exit. Names share
3239 one namespace with native and host-registered functions, which a FUNC
3240 may never shadow.
3241
3242 Functions resolve like variables: a name is visible from its
3243 definition line, so recursion works but mutual recursion does
3244 not (the second name does not exist while the first body
3245 lowers). Calls name their module (`STD::GLOB(...)`) unless
3246 imported; see IMPORT.
3247
3248 Invoke any function with one syntax: `NAME(...)` as a statement
3249 (discarding the value) or `LET $var: TYPE = NAME(...)` to capture
3250 the RETURN value (fallthrough without RETURN captures as "").
3251 "#},
3252 args: &[],
3253 flags: &[],
3254 default_output: None,
3255 examples: &[
3256 Example {
3257 name: "func def call",
3258 fence_meta: None,
3259 code: indoc! {r#"
3260 FUNC GREET($name: STRING) {
3261 RETURN $name
3262 }
3263
3264 LET $res: STRING = GREET("ada")
3265 ASSERT_EQ $res "ada"
3266
3267 # Statement form: parens stay, the value drops.
3268 GREET("bex")
3269 "#},
3270 },
3271 Example {
3272 name: "call with pipes",
3273 fence_meta: None,
3274 code: indoc! {r#"
3275 # A pipe handle travels into a function as a typed argument
3276 # and is usable as a binding target in both directions.
3277 # `LET $p: PIPE` mints the handle; `$p` passes it on.
3278 FUNC DRAIN($q: PIPE) {
3279 WITH_IO [stdin=$q] READ_LINE $line
3280 RETURN $line
3281 }
3282
3283 LET $p: PIPE
3284 WITH_IO [stdout=$p] ECHO "payload"
3285
3286 LET $got: STRING = DRAIN($p)
3287 ASSERT_EQ $got "payload"
3288 "#},
3289 },
3290 ],
3291 },
3292 CommandMeta {
3293 name: "RETURN",
3294 syntax: "RETURN [<expr>]",
3295 summary: "Return a value from a function, task, or inline block.",
3296 description: indoc! {r#"
3297 Ends the nearest enclosing boundary with a value: a function
3298 call, an `ASYNC` task (bound by `LET $o = AWAIT $t`), or an
3299 inline `LET` block. Bare `RETURN` with no expression yields
3300 `""`.
3301
3302 Falling off the end without RETURN yields "". RETURN with no
3303 enclosing boundary (including at top level) is an error; use
3304 EXIT or ECHO there.
3305 "#},
3306 args: &[],
3307 flags: &[],
3308 default_output: None,
3309 examples: &[Example {
3310 name: "return",
3311 fence_meta: None,
3312 code: indoc! {r#"
3313 FUNC PICK($flag: BOOL) {
3314 IF $flag {
3315 RETURN "yes"
3316 }
3317 RETURN "no"
3318 }
3319
3320 LET $res: STRING = PICK(true)
3321 ASSERT_EQ $res "yes"
3322
3323 # Fallthrough without RETURN yields its own value.
3324 LET $no: STRING = PICK(false)
3325 ASSERT_EQ $no "no"
3326 "#},
3327 }],
3328 },
3329 CommandMeta {
3330 name: "WHILE",
3331 syntax: "WHILE <bool-expr> { <commands> }",
3332 summary: "Loop while a condition holds.",
3333 description: indoc! {r#"
3334 Re-evaluates a Bool condition each iteration (same is_truthy rule as IF;
3335 non-Bool is a type error).
3336
3337 Each iteration runs in a fresh scope; mutate outer state with $var = ...
3338 so the next check observes it. BREAK exits the loop; CONTINUE skips to
3339 the next check.
3340 "#},
3341 args: &[],
3342 flags: &[],
3343 default_output: None,
3344 examples: &[Example {
3345 name: "while loop",
3346 fence_meta: None,
3347 code: indoc! {r#"
3348 # The condition re-evaluates every iteration: three passes, then stop.
3349 LET $n: INT = 0
3350 WHILE $n < 3 {
3351 WRITE tick.txt "{{ $n }}"
3352 $n = $n + 1
3353 }
3354
3355 ASSERT_EQ $n 3
3356 LET $tick: STRING = READ tick.txt
3357 ASSERT_EQ $tick "2"
3358 "#},
3359 }],
3360 },
3361 CommandMeta {
3362 name: "BREAK",
3363 syntax: "BREAK",
3364 summary: "Exit the innermost loop.",
3365 description: indoc! {r#"
3366 Exits the innermost enclosing FOR or WHILE loop.
3367
3368 BREAK outside a loop, or across a FUNC or ASYNC boundary, is an error.
3369 "#},
3370 args: &[],
3371 flags: &[],
3372 default_output: None,
3373 examples: &[Example {
3374 name: "break",
3375 fence_meta: None,
3376 code: indoc! {r#"
3377 # BREAK leaves after the first pass: only "a" is written.
3378 FOR $x: STRING IN ["a", "b"] {
3379 WRITE picked.txt "{{ $x }}"
3380 BREAK
3381 }
3382
3383 LET $body: STRING = READ picked.txt
3384 ASSERT_EQ $body "a"
3385 "#},
3386 }],
3387 },
3388 CommandMeta {
3389 name: "CONTINUE",
3390 syntax: "CONTINUE",
3391 summary: "Skip to the next loop iteration.",
3392 description: indoc! {r#"
3393 Skips the rest of the innermost enclosing FOR or WHILE body and starts
3394 the next iteration.
3395
3396 CONTINUE outside a loop, or across a FUNC or ASYNC boundary, is an error.
3397 "#},
3398 args: &[],
3399 flags: &[],
3400 default_output: None,
3401 examples: &[Example {
3402 name: "continue",
3403 fence_meta: None,
3404 code: indoc! {r#"
3405 # CONTINUE skips the write on "a": only "b" lands.
3406 FOR $x: STRING IN ["a", "b"] {
3407 IF $x == "a" {
3408 CONTINUE
3409 }
3410 WRITE picked.txt "{{ $x }}"
3411 }
3412
3413 LET $body: STRING = READ picked.txt
3414 ASSERT_EQ $body "b"
3415 "#},
3416 }],
3417 },
3418 CommandMeta {
3419 name: KEYWORD_IMPORT,
3420 syntax: "IMPORT [<module>, ...] | IMPORT <module>",
3421 summary: "Bring module functions into bare-call scope.",
3422 description: indoc! {r#"
3423 Every function call names its module (`STD::GLOB(...)`,
3424 `MOCK::READ_CSV(...)`) unless the module is imported:
3425 `IMPORT [STD]` lets the rest of the scope call `GLOB(...)`
3426 bare. Calls resolve at parse time against `SCRIPT`
3427 definitions first, then imported modules; unknown modules,
3428 unknown functions, and unimported bare calls are parse
3429 errors, never runtime surprises.
3430
3431 IMPORT is a lowering directive, not a step: it applies from
3432 its line to the enclosing block exit, then reverts, exactly
3433 like `LET` scoping but with no runtime footprint. Guards do
3434 not apply to it. Two imported modules exporting one name is
3435 an ambiguity error: qualify the call instead.
3436
3437 `EXPORT` marks top-level script `FUNC`s as externally
3438 callable tools (`EXPORT FOO`, `EXPORT [FOO, BAR]`).
3439 Single-file scope; see the MCP host for consumption.
3440 "#},
3441 args: &[],
3442 flags: &[],
3443 default_output: None,
3444 examples: &[Example {
3445 name: "import",
3446 fence_meta: None,
3447 code: indoc! {r#"
3448 # Calls name their module (STD::GLOB); IMPORT [STD] drops the prefix.
3449 WRITE a.txt "hi \{{ env:WHO }}!"
3450 IMPORT [STD]
3451 FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
3452 ASSERT_CONTAINS stdout "hi World!"
3453 "#},
3454 }],
3455 },
3456 ]
3457}
3458
3459impl fmt::Display for StepKind {
3462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3463 match self {
3464 StepKind::InheritEnv { keys } => write!(f, "INHERIT_ENV [{}]", keys.join(", ")),
3465 StepKind::Workdir(a) => write!(f, "WORKDIR {}", fmt_value(a, quote_arg)),
3466 StepKind::Workspace(t) => write!(f, "WORKSPACE {}", t),
3467 StepKind::Env { key, value } => {
3468 write!(f, "ENV {}={}", key, fmt_value(value, quote_arg))
3469 }
3470 StepKind::Run(c) => write!(f, "RUN {}", fmt_value(c, quote_run)),
3471 StepKind::RunExec { argv } => {
3472 let parts: Vec<String> = argv.iter().map(fmt_exec_arg).collect();
3473 write!(f, "RUN [{}]", parts.join(", "))
3474 }
3475 StepKind::Echo(m) => write!(f, "ECHO {}", fmt_value(m, quote_msg)),
3476 StepKind::Copy {
3477 from_workspace,
3478 from_host,
3479 to_host,
3480 from,
3481 to,
3482 } => {
3483 let mut head = String::from("COPY");
3484 if let Some(target) = from_workspace {
3485 head.push_str(&format!(" --from-workspace {target}"));
3486 }
3487 if *from_host {
3488 head.push_str(" --from-host");
3489 }
3490 if *to_host {
3491 head.push_str(" --to-host");
3492 }
3493 write!(
3494 f,
3495 "{head} {} {}",
3496 fmt_value(from, quote_arg),
3497 fmt_value(to, quote_arg)
3498 )
3499 }
3500 StepKind::Symlink {
3501 from_workspace,
3502 from,
3503 to,
3504 } => {
3505 if let Some(target) = from_workspace {
3506 write!(
3507 f,
3508 "SYMLINK --from-workspace {} {} {}",
3509 target,
3510 fmt_value(from, quote_arg),
3511 fmt_value(to, quote_arg)
3512 )
3513 } else {
3514 write!(
3515 f,
3516 "SYMLINK {} {}",
3517 fmt_value(from, quote_arg),
3518 fmt_value(to, quote_arg)
3519 )
3520 }
3521 }
3522 StepKind::Mkdir(a) => write!(f, "MKDIR {}", fmt_value(a, quote_arg)),
3523 StepKind::Install { from, to } => write!(
3524 f,
3525 "INSTALL {} {}",
3526 fmt_value(from, quote_arg),
3527 fmt_value(to, quote_arg)
3528 ),
3529 StepKind::Archive { src, dst, raw } => {
3530 if *raw {
3531 write!(
3532 f,
3533 "ARCHIVE --raw {} {}",
3534 fmt_value(src, quote_arg),
3535 fmt_value(dst, quote_arg)
3536 )
3537 } else {
3538 write!(
3539 f,
3540 "ARCHIVE {} {}",
3541 fmt_value(src, quote_arg),
3542 fmt_value(dst, quote_arg)
3543 )
3544 }
3545 }
3546 StepKind::Unarchive {
3547 src,
3548 dst,
3549 max_bytes,
3550 } => {
3551 write!(f, "UNARCHIVE")?;
3552 if let Some(n) = max_bytes {
3553 write!(f, " --max-bytes {}", fmt_value(n, quote_arg))?;
3554 }
3555 write!(
3556 f,
3557 " {} {}",
3558 fmt_value(src, quote_arg),
3559 fmt_value(dst, quote_arg)
3560 )
3561 }
3562 StepKind::Ls(a) => {
3563 write!(f, "LS")?;
3564 if let Some(x) = a {
3565 write!(f, " {}", fmt_value(x, quote_arg))?;
3566 }
3567 Ok(())
3568 }
3569 StepKind::Cwd => write!(f, "CWD"),
3570 StepKind::Read(a) => {
3571 write!(f, "READ")?;
3572 if let Some(x) = a {
3573 write!(f, " {}", fmt_value(x, quote_arg))?;
3574 }
3575 Ok(())
3576 }
3577 StepKind::ReadLine { var } => write!(f, "READ_LINE ${}", var),
3578 StepKind::Prompt {
3579 var,
3580 message,
3581 default,
3582 } => {
3583 write!(f, "PROMPT ${} {}", var, fmt_value(message, quote_arg))?;
3584 if let Some(d) = default {
3585 write!(f, " {}", fmt_value(d, quote_arg))?;
3586 }
3587 Ok(())
3588 }
3589 StepKind::Write { path, contents } => {
3590 write!(f, "WRITE {}", fmt_value(path, quote_arg))?;
3591 if let Some(b) = contents {
3592 write!(f, " {}", fmt_value(b, quote_msg))?;
3593 }
3594 Ok(())
3595 }
3596 StepKind::Append { path, contents } => {
3597 write!(f, "APPEND {}", fmt_value(path, quote_arg))?;
3598 if let Some(b) = contents {
3599 write!(f, " {}", fmt_value(b, quote_msg))?;
3600 }
3601 Ok(())
3602 }
3603 StepKind::Remove { path, recursive } => {
3604 if *recursive {
3605 write!(f, "REMOVE --recursive {}", fmt_value(path, quote_arg))
3606 } else {
3607 write!(f, "REMOVE {}", fmt_value(path, quote_arg))
3608 }
3609 }
3610 StepKind::Expand { path, overrides } => {
3611 write!(f, "EXPAND")?;
3612 if let Some(p) = path {
3613 write!(f, " {}", fmt_value(p, quote_arg))?;
3614 }
3615 for (k, v) in overrides {
3616 write!(f, " {}={}", k, fmt_value(v, quote_arg))?;
3617 }
3618 Ok(())
3619 }
3620 StepKind::AssertEq {
3621 hash,
3622 actual,
3623 expected,
3624 } => {
3625 if let Some(d) = hash {
3626 write!(f, "ASSERT_EQ --hash {d} {}", fmt_assert_target(actual))?;
3627 } else {
3628 write!(
3629 f,
3630 "ASSERT_EQ {} {}",
3631 fmt_assert_target(actual),
3632 fmt_value(
3633 expected
3634 .as_ref()
3635 .expect("Display of ASSERT_EQ without --hash needs expected"),
3636 quote_msg
3637 )
3638 )?;
3639 }
3640 Ok(())
3641 }
3642 StepKind::AssertContains { haystack, needle } => write!(
3643 f,
3644 "ASSERT_CONTAINS {} {}",
3645 fmt_assert_target(haystack),
3646 fmt_value(needle, quote_msg)
3647 ),
3648 StepKind::WithIo { bindings, cmd } => {
3649 let p: Vec<String> = bindings.iter().map(fmt_io).collect();
3650 write!(f, "WITH_IO [{}] {}", p.join(", "), cmd)
3651 }
3652 StepKind::WithIoBlock { bindings } => {
3653 let p: Vec<String> = bindings.iter().map(fmt_io).collect();
3654 write!(f, "WITH_IO [{}] {{...}}", p.join(", "))
3655 }
3656 StepKind::CopyGit {
3657 rev,
3658 from,
3659 to,
3660 include_dirty,
3661 } => {
3662 if *include_dirty {
3663 write!(
3664 f,
3665 "COPY_GIT --include-dirty {} {} {}",
3666 fmt_value(rev, quote_arg),
3667 fmt_value(from, quote_arg),
3668 fmt_value(to, quote_arg)
3669 )
3670 } else {
3671 write!(
3672 f,
3673 "COPY_GIT {} {} {}",
3674 fmt_value(rev, quote_arg),
3675 fmt_value(from, quote_arg),
3676 fmt_value(to, quote_arg)
3677 )
3678 }
3679 }
3680 StepKind::HashSha256 { path } => {
3681 write!(f, "HASH_SHA256 {}", fmt_value(path, quote_arg))
3682 }
3683 StepKind::Exit(code) => write!(f, "EXIT {}", fmt_raw_arg(code)),
3684 StepKind::Sleep { duration } => write!(f, "SLEEP {}", fmt_raw_arg(duration)),
3685 StepKind::ListAppend { list, item } => {
3686 write!(f, "LIST_APPEND ${} {}", list, fmt_raw_arg(item))
3687 }
3688 StepKind::For {
3689 key_var,
3690 key_type,
3691 var,
3692 var_type,
3693 in_expr,
3694 body,
3695 } => {
3696 match key_var {
3697 Some(k) => {
3698 let kt = key_type.as_deref().unwrap_or("STRING");
3699 write!(
3700 f,
3701 "FOR ${}: {}, ${}: {} IN {} {{",
3702 k, kt, var, var_type, in_expr
3703 )?
3704 }
3705 None => write!(f, "FOR ${}: {} IN {} {{", var, var_type, in_expr)?,
3706 }
3707 for s in body {
3708 write!(f, "\n {}", s)?;
3709 }
3710 write!(f, "\n}}")
3711 }
3712 StepKind::If {
3713 cond,
3714 then_body,
3715 else_ifs,
3716 else_body,
3717 } => {
3718 write!(f, "IF {} {{", cond)?;
3719 for s in then_body {
3720 write!(f, "\n {}", s)?;
3721 }
3722 write!(f, " }}")?;
3723 for (c, b) in else_ifs {
3724 write!(f, " ELSE IF {} {{", c)?;
3725 for s in b {
3726 write!(f, "\n {}", s)?;
3727 }
3728 write!(f, " }}")?;
3729 }
3730 if let Some(b) = else_body {
3731 write!(f, " ELSE {{")?;
3732 for s in b {
3733 write!(f, "\n {}", s)?;
3734 }
3735 write!(f, " }}")?;
3736 }
3737 Ok(())
3738 }
3739 StepKind::Assign {
3740 var,
3741 decl_type,
3742 expr,
3743 } => {
3744 if matches!(expr, Expr::FreshPipe) {
3746 write!(f, "LET ${}: {}", var, decl_type)
3747 } else {
3748 write!(f, "LET ${}: {} = {}", var, decl_type, expr)
3749 }
3750 }
3751 StepKind::Set { var, expr } => write!(f, "${} = {}", var, expr),
3752 StepKind::AssignCapture {
3753 var,
3754 decl_type,
3755 cmd,
3756 } => {
3757 write!(f, "LET ${}: {} = {}", var, decl_type, cmd)
3758 }
3759 StepKind::AsyncBlock { body } => {
3760 write!(f, "ASYNC {{")?;
3761 for s in body {
3762 write!(f, "\n {}", s)?;
3763 }
3764 write!(f, "\n}}")
3765 }
3766 StepKind::AssignAsync {
3767 var,
3768 decl_type,
3769 body,
3770 } => {
3771 write!(f, "LET ${}: {} = ASYNC {{", var, decl_type)?;
3772 for s in body {
3773 write!(f, "\n {}", s)?;
3774 }
3775 write!(f, "\n}}")
3776 }
3777 StepKind::Await { var } => write!(f, "AWAIT ${}", var),
3778 StepKind::AwaitCapture {
3779 out_var,
3780 out_type,
3781 task_var,
3782 } => {
3783 write!(f, "LET ${}: {} = AWAIT ${}", out_var, out_type, task_var)
3784 }
3785 StepKind::Cancel { var } => write!(f, "CANCEL ${}", var),
3786 StepKind::Timeout { duration, body } => {
3787 let budget = fmt_raw_arg(duration);
3788 if body.len() == 1 {
3789 write!(f, "TIMEOUT {} {}", budget, body[0].kind)
3790 } else {
3791 write!(f, "TIMEOUT {} {{", budget)?;
3792 for s in body {
3793 write!(f, "\n {}", s)?;
3794 }
3795 write!(f, "\n}}")
3796 }
3797 }
3798 StepKind::Isolated { body } => {
3799 if body.len() == 1 {
3800 write!(f, "ISOLATED {}", body[0].kind)
3801 } else {
3802 write!(f, "ISOLATED {{")?;
3803 for s in body {
3804 write!(f, "\n {}", s)?;
3805 }
3806 write!(f, "\n}}")
3807 }
3808 }
3809 StepKind::IsolatedInheritEnv { keys } => {
3810 write!(f, "INHERIT_ENV [{}]", keys.join(", "))
3814 }
3815 StepKind::RemoteBlock {
3816 target,
3817 vars,
3818 env,
3819 body,
3820 } => {
3821 let mut entries: Vec<String> = vars.iter().map(|v| format!("${v}")).collect();
3822 entries.extend(env.iter().map(|e| format!("env:{e}")));
3823 if entries.is_empty() {
3824 write!(f, "REMOTE {target} {{")?;
3825 } else {
3826 write!(f, "REMOTE {target} [{}] {{", entries.join(", "))?;
3827 }
3828 for s in body {
3829 write!(f, "\n {}", s)?;
3830 }
3831 write!(f, "\n}}")
3832 }
3833 StepKind::FuncDef { name, params, body } => {
3834 let ps: Vec<String> = params
3835 .iter()
3836 .map(|(p, t)| format!("${}: {}", p, t))
3837 .collect();
3838 write!(f, "FUNC {}({}) {{", name, ps.join(", "))?;
3839 for s in body {
3840 write!(f, "\n {}", s)?;
3841 }
3842 write!(f, "\n}}")
3843 }
3844 StepKind::Call { name, args } => {
3845 let ps: Vec<String> = args.iter().map(|a| format!("{}", a)).collect();
3846 write!(f, "{}({})", name, ps.join(", "))
3847 }
3848 StepKind::Return { expr } => write!(f, "RETURN {}", expr),
3849 StepKind::TypeAlias { name, target } => write!(f, "TYPE {} = {}", name, target),
3850 StepKind::While { cond, body } => {
3851 write!(f, "WHILE {} {{", cond)?;
3852 for s in body {
3853 write!(f, "\n {}", s)?;
3854 }
3855 write!(f, "\n}}")
3856 }
3857 StepKind::Break => write!(f, "BREAK"),
3858 StepKind::Continue => write!(f, "CONTINUE"),
3859 }
3860 }
3861}
3862
3863#[cfg(test)]
3864mod tests {
3865 use super::*;
3866 use crate::command::{
3867 format_byte_count, format_duration, parse_byte_count, parse_duration,
3868 strip_digit_separators,
3869 };
3870 use crate::parser::parse_script;
3871
3872 fn parse_err(script: &str) -> String {
3873 parse_script(script, lower_command)
3874 .expect_err("script must fail to parse")
3875 .to_string()
3876 }
3877
3878 #[test]
3879 fn malformed_with_io_binding_names_the_bad_binding() {
3880 let err = parse_err("WITH_IO [stdout=discard] ECHO \"test\"\n");
3881 assert!(err.contains("invalid syntax for command WITH_IO"), "{err}");
3882 assert!(!err.contains("unknown command"), "{err}");
3883 assert!(err.contains("stdout=discard"), "{err}");
3884 assert!(err.contains("[stdout=$p]"), "{err}");
3885 }
3886
3887 #[test]
3888 fn connect_is_unknown_command() {
3889 let err = parse_err("CONNECT 127.0.0.1:8080\n");
3892 assert!(err.contains("unknown command"), "{err}");
3893 assert!(err.contains("CONNECT"), "{err}");
3894 }
3895
3896 #[test]
3897 fn listen_is_unknown_command() {
3898 let err = parse_err("LISTEN 127.0.0.1:8080\n");
3901 assert!(err.contains("unknown command"), "{err}");
3902 assert!(err.contains("LISTEN"), "{err}");
3903 }
3904
3905 #[test]
3906 fn await_without_task_variable_points_at_syntax() {
3907 let err = parse_err("AWAIT ECHO \"test\"\n");
3908 assert!(err.contains("invalid syntax for command AWAIT"), "{err}");
3909 assert!(!err.contains("unknown command"), "{err}");
3910 assert!(err.contains("AWAIT $t"), "{err}");
3911 assert!(err.contains("ECHO"), "{err}");
3912 }
3913
3914 #[test]
3915 fn bare_let_without_type_points_at_typed_syntax() {
3916 let err = parse_err("LET $x = 1\n");
3917 assert!(err.contains("invalid syntax for command LET"), "{err}");
3918 assert!(err.contains("LET $name: STRING = <expr>"), "{err}");
3919 }
3920
3921 #[test]
3922 fn workspace_accepts_all_four_targets_uppercase_only() {
3923 for (spelling, target) in [
3926 ("SNAPSHOT", WorkspaceTarget::Snapshot),
3927 ("LOCAL", WorkspaceTarget::Local),
3928 ("CACHE", WorkspaceTarget::Cache { local: false }),
3929 ("SYSTEM", WorkspaceTarget::System),
3930 ] {
3931 let steps =
3932 parse_script(&format!("WORKSPACE {spelling}\n"), lower_command).expect("parses");
3933 assert_eq!(steps.len(), 1);
3934 assert_eq!(steps[0].kind, StepKind::Workspace(target.clone()));
3935 assert_eq!(steps[0].kind.to_string(), format!("WORKSPACE {target}"));
3936 }
3937 for spelling in ["snapshot", "local", "cache", "system"] {
3938 let err = parse_err(&format!("WORKSPACE {spelling}\n"));
3939 assert!(
3940 err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
3941 "{spelling}: {err}"
3942 );
3943 }
3944 let err = parse_err("WORKSPACE REMOTE\n");
3945 assert!(
3946 err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
3947 "{err}"
3948 );
3949
3950 let steps = parse_script("WORKSPACE CACHE --local\n", lower_command).expect("parses");
3953 assert_eq!(
3954 steps[0].kind,
3955 StepKind::Workspace(WorkspaceTarget::Cache { local: true })
3956 );
3957 assert_eq!(steps[0].kind.to_string(), "WORKSPACE CACHE --local");
3958 for bad in [
3959 "WORKSPACE SNAPSHOT --local\n",
3960 "WORKSPACE LOCAL --local\n",
3961 "WORKSPACE SYSTEM --local\n",
3962 ] {
3963 let err = parse_err(bad);
3964 assert!(err.contains("--local requires CACHE"), "{bad}: {err}");
3965 }
3966 }
3967
3968 #[test]
3969 fn archive_unarchive_parse_and_round_trip() {
3970 let steps = parse_script("ARCHIVE bundle bundle.tar.gz\n", lower_command).expect("parses");
3971 match &steps[0].kind {
3972 StepKind::Archive { src, dst, raw } => {
3973 assert_eq!(src.as_str(), "bundle");
3974 assert_eq!(dst.as_str(), "bundle.tar.gz");
3975 assert!(!raw);
3976 }
3977 other => panic!("expected Archive, got {other:?}"),
3978 }
3979 assert_eq!(
3980 steps[0].kind.to_string(),
3981 "ARCHIVE bundle \"bundle.tar.gz\""
3982 );
3983
3984 let steps =
3985 parse_script("ARCHIVE --raw tool.bin tool.tar\n", lower_command).expect("parses");
3986 assert!(
3987 matches!(&steps[0].kind, StepKind::Archive { raw: true, .. }),
3988 "unexpected lowering: {:?}",
3989 steps[0].kind
3990 );
3991 assert_eq!(
3992 steps[0].kind.to_string(),
3993 "ARCHIVE --raw \"tool.bin\" \"tool.tar\""
3994 );
3995
3996 let steps =
3997 parse_script("UNARCHIVE pack.tar.gz unpacked\n", lower_command).expect("parses");
3998 match &steps[0].kind {
3999 StepKind::Unarchive {
4000 src,
4001 dst,
4002 max_bytes,
4003 } => {
4004 assert_eq!(src.as_str(), "pack.tar.gz");
4005 assert_eq!(dst.as_str(), "unpacked");
4006 assert_eq!(max_bytes, &None);
4007 }
4008 other => panic!("expected Unarchive, got {other:?}"),
4009 }
4010 assert_eq!(
4011 steps[0].kind.to_string(),
4012 "UNARCHIVE \"pack.tar.gz\" unpacked"
4013 );
4014
4015 let steps = parse_script(
4016 "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
4017 lower_command,
4018 )
4019 .expect("parses");
4020 match &steps[0].kind {
4021 StepKind::Unarchive {
4022 src,
4023 dst,
4024 max_bytes,
4025 } => {
4026 assert_eq!(src.as_str(), "pack.tar.gz");
4027 assert_eq!(dst.as_str(), "unpacked");
4028 assert_eq!(max_bytes.as_ref().map(|a| a.as_str()), Some("100_000"));
4029 }
4030 other => panic!("expected Unarchive, got {other:?}"),
4031 }
4032 assert_eq!(
4033 steps[0].kind.to_string(),
4034 "UNARCHIVE --max-bytes \"100_000\" \"pack.tar.gz\" unpacked"
4035 );
4036
4037 for script in [
4038 "ARCHIVE bundle bundle.tar.gz\n",
4039 "ARCHIVE --raw tool.bin tool.tar\n",
4040 "UNARCHIVE pack.tar.gz unpacked\n",
4041 "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
4042 ] {
4043 let first = parse_script(script, lower_command).expect("parses");
4044 let rendered = first[0].kind.to_string() + "\n";
4045 let second = parse_script(&rendered, lower_command).expect("reparses");
4046 assert_eq!(
4049 second[0].kind.to_string(),
4050 first[0].kind.to_string(),
4051 "Display must fixpoint for {script:?}"
4052 );
4053 }
4054
4055 for bad in ["ARCHIVE only-src\n", "ARCHIVE\n", "UNARCHIVE only-src\n"] {
4056 let err = parse_err(bad);
4057 assert!(
4058 err.contains("ARCHIVE") || err.contains("UNARCHIVE"),
4059 "{bad}: {err}"
4060 );
4061 }
4062 }
4063
4064 #[test]
4065 fn copy_from_workspace_selects_source_root() {
4066 for (spelling, target) in [
4067 ("SNAPSHOT", WorkspaceTarget::Snapshot),
4068 ("LOCAL", WorkspaceTarget::Local),
4069 ("CACHE", WorkspaceTarget::Cache { local: false }),
4070 ("SYSTEM", WorkspaceTarget::System),
4071 ] {
4072 let steps = parse_script(
4073 &format!("COPY --from-workspace {spelling} a.txt b.txt\n"),
4074 lower_command,
4075 )
4076 .expect("parses");
4077 assert!(
4078 matches!(&steps[0].kind, StepKind::Copy { from_workspace: Some(t), .. } if *t == target),
4079 "unexpected lowering for {spelling}: {:?}",
4080 steps[0].kind
4081 );
4082 }
4083 for script in [
4086 "COPY --from-workspace=CACHE a.txt b.txt\n",
4087 "COPY --from-workspace=\"CACHE\" a.txt b.txt\n",
4088 ] {
4089 let steps = parse_script(script, lower_command).expect("parses");
4090 assert!(
4091 matches!(
4092 &steps[0].kind,
4093 StepKind::Copy {
4094 from_workspace: Some(WorkspaceTarget::Cache { local: false }),
4095 ..
4096 }
4097 ),
4098 "unexpected lowering for {script:?}: {:?}",
4099 steps[0].kind
4100 );
4101 }
4102 let steps = parse_script("COPY a.txt b.txt\n", lower_command).expect("parses");
4104 assert!(
4105 matches!(
4106 &steps[0].kind,
4107 StepKind::Copy {
4108 from_workspace: None,
4109 ..
4110 }
4111 ),
4112 "unexpected lowering: {:?}",
4113 steps[0].kind
4114 );
4115 for bad in ["REMOTE", "local"] {
4117 let err = parse_err(&format!("COPY --from-workspace {bad} a.txt b.txt\n"));
4118 assert!(err.contains("unknown workspace source"), "{bad}: {err}");
4119 }
4120 }
4121
4122 #[test]
4123 fn symlink_from_workspace_selects_source_root() {
4124 for (spelling, target) in [
4125 ("SNAPSHOT", WorkspaceTarget::Snapshot),
4126 ("LOCAL", WorkspaceTarget::Local),
4127 ("CACHE", WorkspaceTarget::Cache { local: false }),
4128 ("SYSTEM", WorkspaceTarget::System),
4129 ] {
4130 let steps = parse_script(
4131 &format!("SYMLINK --from-workspace {spelling} a.txt b.txt\n"),
4132 lower_command,
4133 )
4134 .expect("parses");
4135 assert!(
4136 matches!(&steps[0].kind, StepKind::Symlink { from_workspace: Some(t), .. } if *t == target),
4137 "unexpected lowering for {spelling}: {:?}",
4138 steps[0].kind
4139 );
4140 let roundtrip = steps[0].kind.to_string();
4141 assert!(
4142 roundtrip.contains("--from-workspace"),
4143 "display should round-trip the flag: {roundtrip}"
4144 );
4145 }
4146 let steps = parse_script("SYMLINK a.txt b.txt\n", lower_command).expect("parses");
4147 assert!(
4148 matches!(
4149 &steps[0].kind,
4150 StepKind::Symlink {
4151 from_workspace: None,
4152 ..
4153 }
4154 ),
4155 "unexpected lowering: {:?}",
4156 steps[0].kind
4157 );
4158 for bad in ["REMOTE", "local"] {
4159 let err = parse_err(&format!("SYMLINK --from-workspace {bad} a.txt b.txt\n"));
4160 assert!(err.contains("unknown workspace source"), "{bad}: {err}");
4161 }
4162 let steps = parse_script(
4164 "SYMLINK --from-workspace=LOCAL a.txt b.txt\n",
4165 lower_command,
4166 )
4167 .expect("parses");
4168 assert!(
4169 matches!(
4170 &steps[0].kind,
4171 StepKind::Symlink {
4172 from_workspace: Some(WorkspaceTarget::Local),
4173 ..
4174 }
4175 ),
4176 "unexpected lowering: {:?}",
4177 steps[0].kind
4178 );
4179 }
4180
4181 #[test]
4182 fn dash_dash_equals_tokens_bypass_assignment() {
4183 let steps = parse_script("ENV --foo=bar\n", lower_command).expect("parses");
4186 let StepKind::Env { key, value } = &steps[0].kind else {
4187 panic!("expected Env, got {:?}", steps[0].kind);
4188 };
4189 assert_eq!(key, "--foo");
4190 assert_eq!(value.as_str(), "bar");
4191
4192 let steps = parse_script("RUN echo --foo=bar\n", lower_command).expect("parses");
4193 let StepKind::Run(cmd) = &steps[0].kind else {
4194 panic!("expected Run, got {:?}", steps[0].kind);
4195 };
4196 assert!(
4197 cmd.as_str().contains("--foo=bar"),
4198 "unexpected RUN lowering: {cmd:?}"
4199 );
4200
4201 let digest = "08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c";
4202 let steps = parse_script(&format!("ASSERT_EQ --hash={digest} $body\n"), lower_command)
4203 .expect("parses");
4204 let StepKind::AssertEq { hash, .. } = &steps[0].kind else {
4205 panic!("expected AssertEq, got {:?}", steps[0].kind);
4206 };
4207 assert_eq!(hash.as_deref(), Some(digest));
4208
4209 let steps = parse_script("EXPAND --k=v\n", lower_command).expect("parses");
4211 let StepKind::Expand { path, overrides } = &steps[0].kind else {
4212 panic!("expected Expand, got {:?}", steps[0].kind);
4213 };
4214 assert!(path.is_none());
4215 assert_eq!(overrides.len(), 1);
4216 assert_eq!(overrides[0].0.as_str(), "--k");
4217 }
4218
4219 #[test]
4220 fn space_before_paren_is_not_a_call() {
4221 let steps = parse_script("ECHO (1 + 2)\n", lower_command).expect("parses");
4224 assert_eq!(steps.len(), 1);
4225 assert!(
4226 !matches!(steps[0].kind, crate::ast::StepKind::Call { .. }),
4227 "space before paren must not route to a call: {:?}",
4228 steps[0].kind
4229 );
4230 }
4231
4232 #[test]
4233 fn unknown_type_tag_parses_as_custom() {
4234 let steps = parse_script("LET $x: FOO = 1\n", lower_command).expect("custom tag parses");
4238 let StepKind::Assign { decl_type, .. } = &steps[0].kind else {
4239 panic!("expected Assign, got {:?}", steps[0].kind);
4240 };
4241 assert_eq!(decl_type, "FOO");
4242 }
4243
4244 #[test]
4245 fn bare_for_without_types_is_rejected() {
4246 let err = parse_err("FOR $i IN [1] { ECHO hi }\n");
4247 assert!(err.contains("FOR requires explicit types"), "{err}");
4248 }
4249
4250 #[test]
4251 fn mutate_statement_parses_without_keyword() {
4252 let steps = parse_script("$y = 2\n", lower_command).expect("mutation parses");
4253 assert!(matches!(steps[0].kind, StepKind::Set { .. }));
4254 }
4255
4256 #[test]
4257 fn set_keyword_is_rejected_with_mutation_hint() {
4258 let err = parse_err("SET $y = 2\n");
4259 assert!(err.contains("not a keyword"), "{err}");
4260 assert!(err.contains("$var = <expr>"), "{err}");
4261 }
4262
4263 #[test]
4264 fn structural_fallthrough_commits_per_keyword() {
4265 for (script, cmd) in [
4266 ("CANCEL foo\n", "CANCEL"),
4267 ("TIMEOUT foo\n", "TIMEOUT"),
4268 ("FOR foo\n", "FOR"),
4269 ("IF foo\n", "IF"),
4270 ("LET foo\n", "LET"),
4271 ("ASYNC\n", "ASYNC"),
4275 ("ELSE foo\n", "ELSE"),
4276 ] {
4277 let err = parse_err(script);
4278 assert!(
4279 err.contains(&format!("invalid syntax for command {cmd}")),
4280 "{cmd}: {err}"
4281 );
4282 assert!(!err.contains("unknown command"), "{cmd}: {err}");
4283 }
4284 }
4285
4286 #[test]
4287 fn leaf_arity_errors_carry_invalid_syntax_prefix() {
4288 let err = parse_err("SLEEP 1s 2s\n");
4289 assert!(err.contains("invalid syntax for command SLEEP"), "{err}");
4290 assert!(!err.contains("unknown command"), "{err}");
4291 }
4292
4293 #[test]
4294 fn list_append_lowers_variable_and_item() {
4295 let steps = parse_script("LIST_APPEND $items \"hi\"\n", lower_command).expect("parses");
4296 let StepKind::ListAppend { list, item } = &steps[0].kind else {
4297 panic!("expected ListAppend, got {:?}", steps[0].kind);
4298 };
4299 assert_eq!(list, "items");
4300 assert!(matches!(item, Arg::String(s, _) if s == "hi"));
4301 assert_eq!(steps[0].kind.to_string(), "LIST_APPEND $items \"hi\"");
4302 }
4303
4304 #[test]
4305 fn list_append_rejects_wrong_arity() {
4306 for script in [
4307 "LIST_APPEND\n",
4308 "LIST_APPEND $items\n",
4309 "LIST_APPEND $items \"a\" \"b\"\n",
4310 ] {
4311 let err = parse_err(script);
4312 assert!(
4313 err.contains("invalid syntax for command LIST_APPEND"),
4314 "{script}: {err}"
4315 );
4316 assert!(!err.contains("unknown command"), "{script}: {err}");
4317 }
4318 }
4319
4320 #[test]
4321 fn list_append_rejects_non_variable_target() {
4322 let err = parse_err("LIST_APPEND items \"a\"\n");
4323 assert!(
4324 err.contains("invalid syntax for command LIST_APPEND"),
4325 "{err}"
4326 );
4327 assert!(!err.contains("unknown command"), "{err}");
4328 }
4329
4330 #[test]
4331 fn read_line_rejects_bare_word_target() {
4332 let err = parse_err("READ_LINE reply\n");
4336 assert!(err.contains("READ_LINE requires a $variable"), "{err}");
4337 assert!(!err.contains("unknown command"), "{err}");
4338 }
4339
4340 #[test]
4341 fn genuinely_unknown_command_keeps_bare_message() {
4342 let err = parse_err("FROBNICATE hi\n");
4343 assert!(err.contains("unknown command: FROBNICATE"), "{err}");
4344 assert!(!err.contains("did you mean"), "{err}");
4345 }
4346
4347 #[test]
4348 fn lowercase_command_suggests_uppercase() {
4349 let err = lower_command("echo", vec![Arg::String("hi".to_string(), false)])
4353 .expect_err("must fail")
4354 .to_string();
4355 assert!(err.contains("unknown command: echo"), "{err}");
4356 assert!(err.contains("did you mean `ECHO`"), "{err}");
4357 }
4358
4359 #[test]
4360 fn func_def_requires_typed_uppercase_name() {
4361 let steps = parse_script(
4362 "FUNC GREET($name: STRING) {\n RETURN $name\n}\n",
4363 lower_command,
4364 )
4365 .expect("func def parses");
4366 let StepKind::FuncDef { name, params, body } = &steps[0].kind else {
4367 panic!("expected FuncDef, got {:?}", steps[0].kind);
4368 };
4369 assert_eq!(name, "GREET");
4370 assert_eq!(
4371 params,
4372 &vec![("name".to_string(), "STRING".to_string())],
4373 "{params:?}"
4374 );
4375 assert!(matches!(body[0].kind, StepKind::Return { .. }));
4376 }
4377
4378 #[test]
4379 fn lowercase_func_name_is_rejected() {
4380 let err = parse_err("FUNC greet($x: STRING) {\n RETURN $x\n}\n");
4381 assert!(err.contains("FUNC"), "{err}");
4382 }
4383
4384 #[test]
4385 fn call_and_while_lower_correctly() {
4386 let steps = parse_script(
4387 "FUNC GREET($name: STRING) {\n RETURN $name\n}\nGREET(\"ada\")\n",
4388 lower_command,
4389 )
4390 .expect("call parses");
4391 assert!(
4392 matches!(&steps[1].kind, StepKind::Call { name, .. } if name == "SCRIPT::GREET"),
4393 "{:?}",
4394 steps[1].kind
4395 );
4396 let steps = parse_script(
4397 "FUNC GREET($a: STRING, $b: STRING) {\n RETURN $a\n}\nGREET(\"ada\", \"bex\")\n",
4398 lower_command,
4399 )
4400 .expect("spaced call parses");
4401 assert!(
4402 matches!(&steps[1].kind, StepKind::Call { name, args } if name == "SCRIPT::GREET" && args.len() == 2),
4403 "{:?}",
4404 steps[1].kind
4405 );
4406 let steps = parse_script(
4407 indoc! {r#"
4408 WHILE !$done {
4409 BREAK
4410 }
4411 "#},
4412 lower_command,
4413 )
4414 .expect("while parses");
4415 let StepKind::While { body, .. } = &steps[0].kind else {
4416 panic!("expected While, got {:?}", steps[0].kind);
4417 };
4418 assert!(matches!(body[0].kind, StepKind::Break));
4419 }
4420
4421 #[test]
4422 fn let_capture_call_and_async_call_lower() {
4423 let steps = parse_script(
4426 indoc! {r#"
4427 FUNC GREET($name: STRING) {
4428 RETURN $name
4429 }
4430 LET $r: STRING = GREET("ada")
4431 "#},
4432 lower_command,
4433 )
4434 .expect("capture call parses");
4435 let StepKind::Assign { var, expr, .. } = &steps[1].kind else {
4436 panic!("expected Assign, got {:?}", steps[1].kind);
4437 };
4438 assert_eq!(var, "r");
4439 assert!(
4440 matches!(expr, Expr::Call { name, .. } if name == "SCRIPT::GREET"),
4441 "{expr:?}"
4442 );
4443 let steps = parse_script(
4444 "FUNC GREET($name: STRING) {\n RETURN $name\n}\nLET $t: HANDLE = ASYNC GREET(\"a\")\n",
4445 lower_command,
4446 )
4447 .expect("async call parses");
4448 assert!(
4449 matches!(&steps[1].kind, StepKind::AssignAsync { .. }),
4450 "{:?}",
4451 steps[1].kind
4452 );
4453 }
4454
4455 #[test]
4456 fn multiline_call_args_span_lines() {
4457 let steps = parse_script(
4461 "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",
4462 lower_command,
4463 )
4464 .expect("multiline call parses");
4465 let StepKind::Assign { expr, .. } = &steps[1].kind else {
4466 panic!("expected Assign, got {:?}", steps[1].kind);
4467 };
4468 let Expr::Call { name, args } = expr else {
4469 panic!("expected Call expr, got {expr:?}");
4470 };
4471 assert_eq!(name, "SCRIPT::SERVE");
4472 assert_eq!(args.len(), 4);
4473 assert!(matches!(&args[3], Expr::Map(entries) if entries.len() == 1));
4474 let rendered = steps[1].to_string();
4476 assert!(!rendered.contains('\n'), "{rendered}");
4477 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";
4478 let again = parse_script(script, lower_command).expect("reparse ok");
4479 assert_eq!(again, steps);
4480 }
4481
4482 #[test]
4483 fn multiline_bare_call_and_list_span_lines() {
4484 let steps = parse_script(
4485 indoc! {r#"
4486 FUNC GREET($a: STRING) {
4487 RETURN $a
4488 }
4489 GREET(
4490 "ada"
4491 )
4492 "#},
4493 lower_command,
4494 )
4495 .expect("multiline bare call parses");
4496 let StepKind::Call { name, args } = &steps[1].kind else {
4497 panic!("expected Call, got {:?}", steps[1].kind);
4498 };
4499 assert_eq!(name, "SCRIPT::GREET");
4500 assert_eq!(args.len(), 1);
4501 let steps = parse_script(
4502 indoc! {r#"
4503 LET $l: LIST = [
4504 "a",
4505 "b"
4506 ]
4507 "#},
4508 lower_command,
4509 )
4510 .expect("multiline list parses");
4511 let StepKind::Assign { expr, .. } = &steps[0].kind else {
4512 panic!("expected Assign, got {:?}", steps[0].kind);
4513 };
4514 assert!(
4515 matches!(expr, Expr::List(items) if items.len() == 2),
4516 "{expr:?}"
4517 );
4518 }
4519
4520 #[test]
4521 fn parse_duration_units() {
4522 use std::time::Duration;
4523 assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
4524 assert_eq!(parse_duration("10s").unwrap(), Duration::from_secs(10));
4525 assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
4526 assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
4527 assert_eq!(parse_duration("30").unwrap(), Duration::from_secs(30));
4528 assert_eq!(parse_duration("30 s").unwrap(), Duration::from_secs(30));
4530 assert_eq!(parse_duration("2 m").unwrap(), Duration::from_secs(120));
4531 }
4532
4533 #[test]
4534 fn parse_duration_rejects_garbage() {
4535 assert!(parse_duration("").is_err());
4536 assert!(parse_duration("banana").is_err());
4537 assert!(parse_duration("10x").is_err());
4538 assert!(parse_duration("0s").is_err());
4539 assert!(parse_duration("0").is_err());
4540 assert!(parse_duration("-5s").is_err());
4541 assert!(parse_duration("30 s s").is_err());
4543 assert!(parse_duration("3 0s").is_err());
4544 }
4545
4546 #[test]
4547 fn parse_byte_count_units() {
4548 assert_eq!(parse_byte_count("500").unwrap(), 500);
4549 assert_eq!(parse_byte_count("500B").unwrap(), 500);
4550 assert_eq!(parse_byte_count("10KB").unwrap(), 10_000);
4551 assert_eq!(parse_byte_count("2MB").unwrap(), 2_000_000);
4552 assert_eq!(parse_byte_count("1GB").unwrap(), 1_000_000_000);
4553 assert_eq!(parse_byte_count("1TB").unwrap(), 1_000_000_000_000);
4554 assert_eq!(parse_byte_count("10KIB").unwrap(), 10 * 1_024);
4555 assert_eq!(parse_byte_count("2MIB").unwrap(), 2 * 1_024 * 1_024);
4556 assert_eq!(parse_byte_count("1GIB").unwrap(), 1_024 * 1_024 * 1_024);
4557 assert_eq!(
4558 parse_byte_count("1TIB").unwrap(),
4559 1_024 * 1_024 * 1_024 * 1_024
4560 );
4561 assert_eq!(parse_byte_count("1gb").unwrap(), 1_000_000_000);
4563 assert_eq!(parse_byte_count("1Gb").unwrap(), 1_000_000_000);
4564 assert_eq!(parse_byte_count("1gib").unwrap(), 1_024 * 1_024 * 1_024);
4565 assert_eq!(parse_byte_count("1Gib").unwrap(), 1_024 * 1_024 * 1_024);
4566 assert_eq!(parse_byte_count("1_000").unwrap(), 1_000);
4568 assert_eq!(
4569 parse_byte_count("1_000_000_000_000").unwrap(),
4570 1_000_000_000_000
4571 );
4572 assert_eq!(parse_byte_count("1_0KB").unwrap(), 10_000);
4573 assert_eq!(
4574 parse_byte_count("1_0GiB").unwrap(),
4575 10 * 1_024 * 1_024 * 1_024
4576 );
4577 assert_eq!(parse_byte_count("1 GB").unwrap(), 1_000_000_000);
4579 assert_eq!(parse_byte_count("10 KiB").unwrap(), 10_240);
4580 assert_eq!(parse_byte_count(" 2MB ").unwrap(), 2_000_000);
4581 assert_eq!(parse_byte_count("+1 GB").unwrap(), 1_000_000_000);
4583 assert!(parse_byte_count("-1 GB").is_err());
4584 }
4585
4586 #[test]
4587 fn parse_byte_count_rejects_garbage() {
4588 for bad in [
4589 "",
4590 "banana",
4591 "10x",
4592 "1G",
4593 "1K",
4594 "1.5GB",
4595 "-5",
4596 "-5GB",
4597 "0",
4598 "0GB",
4599 "_100",
4600 "100_",
4601 "1__000",
4602 "_",
4603 "1_GB",
4604 "1 G B",
4606 "1 2",
4607 "1 0",
4608 "1000000000000000000000000",
4610 "1000000000TB",
4611 ] {
4612 assert!(parse_byte_count(bad).is_err(), "{bad:?} must fail");
4613 }
4614 }
4615
4616 #[test]
4617 fn format_byte_count_round_trips() {
4618 for text in [
4619 "500", "500B", "10KB", "2MB", "1GB", "1TB", "10KIB", "2MIB", "1GIB", "1TIB", "1500B",
4620 ] {
4621 let parsed = parse_byte_count(text).unwrap();
4622 let rendered = format_byte_count(parsed);
4623 assert_eq!(
4624 parse_byte_count(&rendered).unwrap(),
4625 parsed,
4626 "round-trip failed for {text}"
4627 );
4628 }
4629 assert_eq!(format_byte_count(1_024 * 1_024 * 1_024), "1GiB");
4630 assert_eq!(format_byte_count(1_000_000_000), "1GB");
4631 }
4632
4633 #[test]
4634 fn strip_digit_separators_passes_signs_through() {
4635 assert_eq!(strip_digit_separators("-1_000"), "-1000");
4639 assert_eq!(strip_digit_separators("+1_000_000"), "+1000000");
4640 assert_eq!(strip_digit_separators("-1_000.5"), "-1000.5");
4641 assert_eq!(strip_digit_separators("1_000"), "1000");
4642 for untouched in ["+", "-", "", "1__0", "abc", "+-5", "--5"] {
4643 assert_eq!(strip_digit_separators(untouched), untouched);
4644 }
4645 assert!(parse_byte_count("-1_000").is_err());
4648 assert_eq!(parse_byte_count("+1GB").unwrap(), 1_000_000_000);
4649 }
4650
4651 #[test]
4652 fn format_byte_count_is_lossless() {
4653 for n in [
4658 1,
4659 500,
4660 999,
4661 1_000,
4662 1_024,
4663 1_500,
4664 1_000_000,
4665 1_048_576,
4666 1_000_000_000,
4667 1_073_741_824,
4668 1_000_000_000_000,
4669 1_099_511_627_776,
4670 u64::MAX,
4671 ] {
4672 assert_eq!(
4673 parse_byte_count(&format_byte_count(n)).unwrap(),
4674 n,
4675 "lossless round-trip failed for {n}"
4676 );
4677 }
4678 }
4679
4680 #[test]
4681 fn format_duration_round_trips() {
4682 for text in ["500ms", "10s", "2m", "1h", "90s", "1500ms"] {
4683 let parsed = parse_duration(text).unwrap();
4684 let rendered = format_duration(&parsed);
4685 assert_eq!(
4686 parse_duration(&rendered).unwrap(),
4687 parsed,
4688 "round-trip failed for {text}"
4689 );
4690 }
4691 assert_eq!(format_duration(&parse_duration("90s").unwrap()), "90s");
4692 assert_eq!(format_duration(&parse_duration("2m").unwrap()), "2m");
4693 }
4694
4695 #[test]
4696 fn structural_metadata_covers_all_structural_kinds() {
4697 use crate::ast::Value;
4698
4699 fn metadata_name(kind: &StepKind) -> Option<&'static str> {
4703 match kind {
4704 StepKind::WithIo { .. } | StepKind::WithIoBlock { .. } => Some("WITH_IO"),
4705 StepKind::For { .. } => Some("FOR"),
4706 StepKind::If { .. } => Some("IF"),
4707 StepKind::Assign { .. } => Some("LET"),
4708 StepKind::Set { .. } => Some("MUTATION"),
4709 StepKind::AssignCapture { .. } => Some("LET"),
4710 StepKind::AwaitCapture { .. } => Some("AWAIT"),
4711 StepKind::AsyncBlock { .. } | StepKind::AssignAsync { .. } => Some("ASYNC"),
4712 StepKind::Await { .. } => Some("AWAIT"),
4713 StepKind::Cancel { .. } => Some("CANCEL"),
4714 StepKind::Timeout { .. } => Some("TIMEOUT"),
4715 StepKind::Isolated { .. } => Some("ISOLATED"),
4716 StepKind::IsolatedInheritEnv { .. } => Some("ISOLATED"),
4717 StepKind::RemoteBlock { .. } => Some("REMOTE"),
4718 StepKind::FuncDef { .. } => Some("FUNC"),
4719 StepKind::Call { .. } => None,
4722 StepKind::Return { .. } => Some("RETURN"),
4723 StepKind::While { .. } => Some("WHILE"),
4724 StepKind::Break => Some("BREAK"),
4725 StepKind::Continue => Some("CONTINUE"),
4726 StepKind::TypeAlias { .. } => Some("LET"),
4730 StepKind::RunExec { .. } => None,
4731 StepKind::Workdir(_)
4732 | StepKind::Workspace(_)
4733 | StepKind::Env { .. }
4734 | StepKind::InheritEnv { .. }
4735 | StepKind::Run(_)
4736 | StepKind::Echo(_)
4737 | StepKind::Copy { .. }
4738 | StepKind::Symlink { .. }
4739 | StepKind::Mkdir(_)
4740 | StepKind::Archive { .. }
4741 | StepKind::Unarchive { .. }
4742 | StepKind::Install { .. }
4743 | StepKind::Ls(_)
4744 | StepKind::Cwd
4745 | StepKind::Read(_)
4746 | StepKind::ReadLine { .. }
4747 | StepKind::Prompt { .. }
4748 | StepKind::Write { .. }
4749 | StepKind::Append { .. }
4750 | StepKind::Remove { .. }
4751 | StepKind::Expand { .. }
4752 | StepKind::AssertEq { .. }
4753 | StepKind::AssertContains { .. }
4754 | StepKind::CopyGit { .. }
4755 | StepKind::HashSha256 { .. }
4756 | StepKind::Exit(_)
4757 | StepKind::Sleep { .. }
4758 | StepKind::ListAppend { .. } => None,
4759 }
4760 }
4761
4762 let dummies: Vec<StepKind> = vec![
4765 StepKind::WithIo {
4766 bindings: Vec::new(),
4767 cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
4768 "x".to_string(),
4769 false,
4770 ))),
4771 },
4772 StepKind::For {
4773 key_var: None,
4774 key_type: None,
4775 var: "i".to_string(),
4776 var_type: "STRING".to_string(),
4777 in_expr: Expr::Literal(Value::bool(true)),
4778 body: Vec::new(),
4779 },
4780 StepKind::If {
4781 cond: Box::new(Expr::Literal(Value::bool(true))),
4782 then_body: Vec::new(),
4783 else_ifs: Vec::new(),
4784 else_body: None,
4785 },
4786 StepKind::Assign {
4787 var: "v".to_string(),
4788 decl_type: "BOOL".to_string(),
4789 expr: Expr::Literal(Value::bool(true)),
4790 },
4791 StepKind::Set {
4792 var: "v".to_string(),
4793 expr: Expr::Literal(Value::bool(true)),
4794 },
4795 StepKind::AssignCapture {
4796 var: "v".to_string(),
4797 decl_type: "STRING".to_string(),
4798 cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
4799 "x".to_string(),
4800 false,
4801 ))),
4802 },
4803 StepKind::AwaitCapture {
4804 out_var: "o".to_string(),
4805 out_type: "STRING".to_string(),
4806 task_var: "t".to_string(),
4807 },
4808 StepKind::AsyncBlock { body: Vec::new() },
4809 StepKind::AssignAsync {
4810 var: "t".to_string(),
4811 decl_type: "HANDLE".to_string(),
4812 body: Vec::new(),
4813 },
4814 StepKind::Await {
4815 var: "t".to_string(),
4816 },
4817 StepKind::Cancel {
4818 var: "t".to_string(),
4819 },
4820 StepKind::Timeout {
4821 duration: Arg::String("1s".to_string(), false),
4822 body: Vec::new(),
4823 },
4824 StepKind::Isolated { body: Vec::new() },
4825 StepKind::IsolatedInheritEnv { keys: Vec::new() },
4826 StepKind::RemoteBlock {
4827 target: "prod".to_string(),
4828 vars: Vec::new(),
4829 env: Vec::new(),
4830 body: Vec::new(),
4831 },
4832 StepKind::FuncDef {
4833 name: "F".to_string(),
4834 params: Vec::new(),
4835 body: Vec::new(),
4836 },
4837 StepKind::Call {
4838 name: "F".to_string(),
4839 args: Vec::new(),
4840 },
4841 StepKind::Return {
4842 expr: Box::new(Expr::Literal(Value::bool(true))),
4843 },
4844 StepKind::While {
4845 cond: Box::new(Expr::Literal(Value::bool(true))),
4846 body: Vec::new(),
4847 },
4848 StepKind::Break,
4849 StepKind::Continue,
4850 StepKind::TypeAlias {
4851 name: "PERSON".to_string(),
4852 target: "MAP<name: STRING>".to_string(),
4853 },
4854 ];
4855 let registry = all_structural_metadata();
4856 for kind in &dummies {
4857 let Some(name) = metadata_name(kind) else {
4859 continue;
4860 };
4861 assert!(
4862 registry.iter().any(|meta| meta.name == name),
4863 "no structural metadata entry for {}",
4864 name
4865 );
4866 }
4867 }
4868}