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