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