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