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