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