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 args: &[],
3972 flags: &[],
3973 default_output: None,
3974 examples: &[
3975 Example {
3976 name: "const",
3977 fence_meta: None,
3978 code: indoc! {r#"
3979 # CONST reads through `$`, like LET.
3980 CONST $NAME: STRING = "world"
3981 ECHO "hello, {{ $NAME }}"
3982 ASSERT_CONTAINS stdout "hello, world"
3983
3984 # Containers freeze with the binding.
3985 CONST $ITEMS: LIST<STRING> = ["a", "b"]
3986 ASSERT_CONTAINS {{ $ITEMS }} "a"
3987
3988 # File CONSTs read inside the file's own FUNCs.
3989 CONST $GREETING: STRING = "hi"
3990 FUNC SHOUT(): STRING {
3991 RETURN $GREETING
3992 }
3993 LET $s: STRING = SHOUT()
3994 ASSERT_EQ $s "hi"
3995 "#},
3996 },
3997 Example {
3998 name: "const alias reads across modules",
3999 fence_meta: Some("roots:unified"),
4000 code: indoc! {r#"
4001 # Exported CONSTs cross only as alias reads, never bare.
4002 IMPORT [STD]
4003 WRITE lib.oxfile """
4004 CONST $VERSION: STRING = "1.2.3"
4005 CONST $BUILD: INT = 4
4006 EXPORT CONST $VERSION
4007 EXPORT [CONST $BUILD]
4008 """
4009
4010 # The entry reads the exports at top level, in math, and in templates.
4011 WRITE main.oxfile """
4012 IMPORT ["lib.oxfile" AS LIB]
4013 LET $v: STRING = $LIB::VERSION
4014 ASSERT_EQ $v "1.2.3"
4015 LET $e: INT = $LIB::BUILD * 2
4016 ASSERT_EQ $e 8
4017 LET $w: STRING = "v\{{ $LIB::VERSION }}"
4018 ASSERT_EQ $w "v1.2.3"
4019 ECHO "export-ok \{{ $LIB::VERSION }}"
4020 """
4021
4022 # A child run proves the import from a fresh interpreter.
4023 LET $exe: STRING = INTERPRETER()
4024 LET $out: STRING = RUN [$exe, "main.oxfile"]
4025 ASSERT_CONTAINS $out "export-ok 1.2.3"
4026 "#},
4027 },
4028 Example {
4029 name: "const alias reads inside func bodies",
4030 fence_meta: Some("roots:unified"),
4031 code: indoc! {r#"
4032 # Alias reads work inside importer FUNC bodies exactly like at top level.
4033 IMPORT [STD]
4034 WRITE lib.oxfile """
4035 CONST $VERSION: STRING = "1.2.3"
4036 EXPORT CONST $VERSION
4037 """
4038
4039 # The importer FUNCs return alias reads from expressions and templates.
4040 WRITE main.oxfile """
4041 IMPORT ["lib.oxfile" AS LIB]
4042 FUNC SHOW(): STRING {
4043 RETURN $LIB::VERSION
4044 }
4045 FUNC LABELED(): STRING {
4046 RETURN "v\{{ $LIB::VERSION }}"
4047 }
4048 LET $s: STRING = SHOW()
4049 ASSERT_EQ $s "1.2.3"
4050 LET $t: STRING = LABELED()
4051 ASSERT_EQ $t "v1.2.3"
4052 ECHO "body-ok \{{ $LIB::VERSION }}"
4053 """
4054
4055 # A child run proves body reads from a fresh interpreter.
4056 LET $exe: STRING = INTERPRETER()
4057 LET $out: STRING = RUN [$exe, "main.oxfile"]
4058 ASSERT_CONTAINS $out "body-ok 1.2.3"
4059 "#},
4060 },
4061 Example {
4062 name: "const rejects mutation",
4063 fence_meta: Some("expect_error:\"cannot mutate CONST\""),
4064 code: indoc! {r#"
4065 # SET on a CONST fails instead of rebinding.
4066 CONST $N: INT = 1
4067 $N = 2
4068 "#},
4069 },
4070 Example {
4071 name: "const rejects append",
4072 fence_meta: Some("expect_error:\"cannot mutate CONST\""),
4073 code: indoc! {r#"
4074 # LIST_APPEND on a CONST fails instead of pushing.
4075 CONST $ITEMS: LIST<STRING> = ["a"]
4076 LIST_APPEND $ITEMS "b"
4077 "#},
4078 },
4079 Example {
4080 name: "const freeze detaches from its source",
4081 fence_meta: None,
4082 code: indoc! {r#"
4083 # Freezing detaches: the LET source stays mutable.
4084 LET $inner: LIST<STRING> = ["a"]
4085 CONST $C: LIST<ANY> = [$inner]
4086 LIST_APPEND $inner "b"
4087 ASSERT_CONTAINS $inner "b"
4088
4089 # Equality ignores CONST-ness: the frozen copy equals an unfrozen twin.
4090 LET $twin: LIST<ANY> = [["a"]]
4091 ASSERT_EQ $C $twin
4092 "#},
4093 },
4094 Example {
4095 name: "const nested freeze",
4096 fence_meta: Some("expect_error:\"cannot mutate CONST\""),
4097 code: indoc! {r#"
4098 # Nested containers freeze with the binding.
4099 CONST $C: LIST<ANY> = [["a"]]
4100 LET $nested: LIST<STRING> = $C.0
4101 LIST_APPEND $nested "b"
4102 "#},
4103 },
4104 Example {
4105 name: "const alias shares frozenness",
4106 fence_meta: Some("expect_error:\"cannot mutate CONST\""),
4107 code: indoc! {r#"
4108 # Aliases share frozenness: copying a CONST never thaws it.
4109 CONST $C: LIST<STRING> = ["a"]
4110 LET $alias: LIST<STRING> = $C
4111 LIST_APPEND $alias "b"
4112 "#},
4113 },
4114 Example {
4115 name: "const map set fails",
4116 fence_meta: Some("expect_error:\"cannot mutate CONST\""),
4117 code: indoc! {r#"
4118 # MAP_SET on a CONST fails instead of deriving.
4119 IMPORT [STD]
4120 CONST $M: MAP<ANY> = {a: 1}
4121 LET $z: MAP<ANY> = MAP_SET($M, "x", 1)
4122 "#},
4123 },
4124 Example {
4125 name: "const merge maps fails",
4126 fence_meta: Some("expect_error:\"cannot mutate CONST\""),
4127 code: indoc! {r#"
4128 # MERGE_MAPS over a CONST fails instead of merging.
4129 IMPORT [STD]
4130 CONST $M: MAP<ANY> = {a: 1}
4131 LET $n: MAP<ANY> = MERGE_MAPS([$M], "overwrite")
4132 "#},
4133 },
4134 ],
4135 },
4136 CommandMeta {
4137 in_index: false,
4139 name: "MUTATION",
4140 syntax: "$var = <expr>",
4141 summary: "Mutate a declared variable.",
4142 description: indoc! {r#"
4143 Reassigns an existing variable, converting the new value to
4144 the type declared at LET time through the same narrow
4145 coercion pairs as declaration. Strings never parse to
4146 numbers implicitly: `$n = "42"` is a TypeMismatch for an
4147 INT, write `$n = INT("42")` instead.
4148 Expressions never convert: `"100" + 1` is a Type Error, use
4149 `INT()` / `FLOAT()` to cross that boundary explicitly.
4150
4151 The leading `$` distinguishes mutation from `KEY=value` command
4152 assignments. Assigning an undeclared variable or a mismatched type is
4153 an error.
4154
4155 Mutation writes through to the scope where the variable was
4156 declared, so it survives block exit: `LET $x` outside a block
4157 followed by `$x = ...` inside still reads back the new value
4158 afterwards, for every type. This is the counterpart to LET
4159 shadowing, where `LET $x` *inside* the block declares a
4160 separate inner variable that reverts on exit.
4161
4162 Reassignment rebinds the variable to a new value: values
4163 captured earlier keep the old word (see the rebinding
4164 example below).
4165 "#},
4166 args: &[],
4167 flags: &[],
4168 default_output: None,
4169 examples: &[
4170 Example {
4171 name: "mutate",
4172 fence_meta: None,
4173 code: indoc! {r#"
4174 # Mutation writes through: the binding holds the new value.
4175 LET $count: INT = 1
4176 $count = 2
4177 ASSERT_EQ $count 2
4178 "#},
4179 },
4180 Example {
4181 name: "rebind keeps earlier captures",
4182 fence_meta: None,
4183 code: indoc! {r#"
4184 # Reassignment rebinds: a map built from `$s` still
4185 # reads the original string after `$s` moves on.
4186 LET $s: STRING = "test"
4187 LET $m: MAP<ANY> = {a: $s}
4188 $s = "changed"
4189 ASSERT_EQ $m.a "test"
4190
4191 # Appending to one list binding never touches its clones.
4192 LET $a: LIST<STRING> = ["1"]
4193 LET $b: LIST<STRING> = $a
4194 LIST_APPEND $a "2"
4195 LET $want: LIST<STRING> = ["1"]
4196 ASSERT_EQ $b $want
4197 "#},
4198 },
4199 Example {
4200 name: "convert before math",
4201 fence_meta: None,
4202 code: indoc! {r#"
4203 # Captured output is a string: `"100" + 1` is a Type Error.
4204 # Convert explicitly, then mutate with arithmetic.
4205 IMPORT [STD]
4206 LET $raw: STRING = ECHO 100
4207 LET $n: INT = INT($raw)
4208 $n = $n + 1
4209
4210 # The declared slot stays strict: strings parse only
4211 # through the explicit converter, never on assignment.
4212 $n = INT("42")
4213 ASSERT_EQ $n 42
4214
4215 # Same crossing for decimals via FLOAT().
4216 LET $frac_str: STRING = ECHO 2.5
4217 LET $f: FLOAT = FLOAT($frac_str) + 0.25
4218 ASSERT_EQ $f 2.75
4219 "#},
4220 },
4221 Example {
4222 name: "reject keypath target",
4223 fence_meta: Some("expect_error:\"cannot assign to $M.a\""),
4224 code: indoc! {r#"
4225 # Rebind the whole variable to update one entry.
4226 IMPORT [STD]
4227 LET $M: MAP<ANY> = {a: 1}
4228 $M = MAP_SET($M, "a", 2)
4229 ASSERT_EQ $M.a 2
4230
4231 # Key paths read in expressions but are never mutation targets.
4232 $M.a = 3
4233 "#},
4234 },
4235 ],
4236 },
4237 CommandMeta {
4238 in_index: true,
4239 name: KEYWORD_ASYNC,
4240 syntax: "ASYNC <command...> | ASYNC { <commands> } | LET $var: HANDLE<T> = ASYNC { <commands> }",
4241 summary: "Run steps in a background thread.",
4242 description: indoc! {r#"
4243 Runs a command or block of commands in a background thread with
4244 subshell isolation.
4245
4246 Mutations (ENV, WORKDIR) stay within the block. With `LET`, stores a
4247 task handle for `AWAIT`. Task output streams live to the parent
4248 stdout; a task publishes a value with an explicit `RETURN`,
4249 which `LET $out: TYPE = AWAIT $task` binds.
4250
4251 `WITH_IO` must wrap `ASYNC` from the outside (`LET $p: PIPE` first,
4252 then `WITH_IO [stdout=$p] ASYNC ...`) so pipe endpoints allocate on
4253 the main thread before the worker spawns. Placing `WITH_IO` directly
4254 inside `ASYNC` is rejected at parse time.
4255 "#},
4256 args: &[],
4257 flags: &[],
4258 default_output: None,
4259 examples: &[
4260 Example {
4261 name: "async",
4262 fence_meta: None,
4263 code: indoc! {r#"
4264 # Inline and block forms both run in the background; AWAIT joins them.
4265 ASYNC ECHO "warming-up"
4266 LET $a: HANDLE<VOID> = ASYNC ECHO "first"
4267 LET $b: HANDLE<VOID> = ASYNC {
4268 ECHO "second"
4269 }
4270 AWAIT $a
4271 AWAIT $b
4272 ASSERT_CONTAINS stdout "first"
4273 ASSERT_CONTAINS stdout "second"
4274 "#},
4275 },
4276 Example {
4277 name: "async task handle",
4278 fence_meta: None,
4279 code: indoc! {r#"
4280 LET $task: HANDLE<VOID> = ASYNC {
4281 ECHO "built"
4282 }
4283 AWAIT $task
4284 ASSERT_CONTAINS stdout "built"
4285 "#},
4286 },
4287 ],
4288 },
4289 CommandMeta {
4290 in_index: true,
4291 name: KEYWORD_AWAIT,
4292 syntax: "AWAIT $var | LET $out: STRING = AWAIT $var",
4293 summary: "Join a background task.",
4294 description: indoc! {r#"
4295 Blocks until the named task completes. Propagates errors if the task failed.
4296
4297 Task output streams live during the run; joining binds nothing by
4298 itself. `LET $out: TYPE = AWAIT $var` binds the task's explicit
4299 `RETURN` value instead, or `INT` 0 when the task succeeded
4300 without one (add `RETURN <expr>` to the task body to yield
4301 a value).
4302 "#},
4303 args: &[],
4304 flags: &[],
4305 default_output: None,
4306 examples: &[
4307 Example {
4308 name: "await",
4309 fence_meta: None,
4310 code: indoc! {r#"
4311 LET $task: HANDLE<VOID> = ASYNC ECHO "done"
4312 AWAIT $task
4313 ASSERT_CONTAINS stdout "done"
4314 "#},
4315 },
4316 Example {
4317 name: "await capture",
4318 fence_meta: None,
4319 code: indoc! {r#"
4320 LET $task: HANDLE<STRING> = ASYNC {
4321 ECHO "logged"
4322 RETURN "returned"
4323 }
4324
4325 # AWAIT binds the RETURN value, not the streamed output.
4326 LET $out: STRING = AWAIT $task
4327 ASSERT_EQ $out "returned"
4328 "#},
4329 },
4330 ],
4331 },
4332 CommandMeta {
4333 in_index: true,
4334 name: KEYWORD_CANCEL,
4335 syntax: "CANCEL $var",
4336 summary: "Synchronously cancel a background task.",
4337 description: indoc! {r#"
4338 Kills the named background task spawned via `LET $var: HANDLE<T> = ASYNC ...`.
4339
4340 Blocking: returns only after the task thread has been joined and its OS
4341 process reaped, so no residual filesystem or stream mutation follows. A
4342 later AWAIT $var reports cancellation. Only named tasks can be cancelled.
4343 "#},
4344 args: &[],
4345 flags: &[],
4346 default_output: None,
4347 examples: &[
4348 Example {
4349 name: "cancel",
4350 fence_meta: None,
4351 code: indoc! {r#"
4352 LET $task: HANDLE<VOID> = ASYNC SLEEP 30s
4353 CANCEL $task
4354 "#},
4355 },
4356 Example {
4357 name: "await after cancel reports cancellation",
4358 fence_meta: Some("expect_error:\"was cancelled\""),
4359 code: indoc! {r#"
4360 # A cancelled task stays cancelled: joining it reports.
4361 LET $task: HANDLE<VOID> = ASYNC SLEEP 30s
4362 CANCEL $task
4363 AWAIT $task
4364 "#},
4365 },
4366 ],
4367 },
4368 CommandMeta {
4369 in_index: true,
4370 name: KEYWORD_TIMEOUT,
4371 syntax: "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> } | TIMEOUT <duration> AWAIT $var",
4372 summary: "Enforce an execution deadline.",
4373 description: indoc! {r#"
4374 Aborts the wrapped step or block with a deadline error if it exceeds the
4375 duration (e.g. 500ms, 10s, 2m; a bare number means seconds).
4376
4377 A blocking foreground process is killed.
4378
4379 ASYNC nests in either order with order-dependent deadline
4380 semantics: `LET $task: HANDLE<VOID> = ASYNC TIMEOUT 30s RUN "build"` enforces
4381 the deadline inside the background thread (a later `AWAIT $task`
4382 surfaces the `TIMEOUT` error), while `TIMEOUT 30s AWAIT $task`
4383 preempts a hung task from the awaiting side.
4384 "#},
4385 args: &[],
4386 flags: &[],
4387 default_output: None,
4388 examples: &[
4389 Example {
4390 name: "timeout",
4391 fence_meta: None,
4392 code: indoc! {r#"
4393 TIMEOUT 30s WRITE heartbeat.txt alive
4394 LET $beat: STRING = READ heartbeat.txt
4395 ASSERT_EQ $beat "alive"
4396 "#},
4397 },
4398 Example {
4399 name: "timeout block",
4400 fence_meta: None,
4401 code: indoc! {r#"
4402 TIMEOUT 30s {
4403 WRITE a.txt one
4404 WRITE b.txt two
4405 }
4406 LET $a: STRING = READ a.txt
4407 LET $b: STRING = READ b.txt
4408 ASSERT_EQ $a "one"
4409 ASSERT_EQ $b "two"
4410 "#},
4411 },
4412 Example {
4413 name: "deadline aborts the step",
4414 fence_meta: Some("expect_error:\"TIMEOUT after\""),
4415 code: indoc! {r#"
4416 # 50ms expires long before the sleep does: the step dies
4417 # with a deadline error instead of running out the clock.
4418 TIMEOUT 50ms SLEEP 30s
4419 "#},
4420 },
4421 Example {
4422 name: "timeout variable duration",
4423 fence_meta: None,
4424 code: indoc! {r#"
4425 # Durations resolve at runtime, so variables work too.
4426 LET $budget: DURATION = "30s"
4427 TIMEOUT $budget WRITE heartbeat.txt alive
4428
4429 LET $beat: STRING = READ heartbeat.txt
4430 ASSERT_EQ $beat "alive"
4431 "#},
4432 },
4433 Example {
4434 name: "timeout await",
4435 fence_meta: None,
4436 code: indoc! {r#"
4437 # AWAIT form bounds a task join instead of a step.
4438 LET $quick: HANDLE<VOID> = ASYNC {
4439 ECHO hi
4440 }
4441 TIMEOUT 30s AWAIT $quick
4442 "#},
4443 },
4444 ],
4445 },
4446 CommandMeta {
4447 in_index: true,
4448 name: KEYWORD_FAIL,
4449 syntax: "FAIL [<code>] [<message>] [{ <commands> }]",
4450 summary: "Print a failure message and exit.",
4451 description: indoc! {r#"
4452 Prints the message to stderr (the `ECHO` plus `EXIT` idiom as
4453 one step, rerouted to the error stream), runs the optional
4454 block first, then exits through the `EXIT` path with
4455 `EXIT requested with code <code>`.
4456
4457 With no code the exit code is 1; with a code it clamps to
4458 0..=255 like `EXIT`. The block runs first in a child scope
4459 that reads caller locals, with its stdout rerouted to
4460 stderr, so usage text, cleanup, and callee output all land
4461 on the error stream while stdout stays empty: the only
4462 form a `FUNC` cannot express, since functions take values,
4463 never blocks. At least one of message or block is required.
4464
4465 A lone bare int is a silent code (`FAIL 2` exits 2 with no
4466 output); quoting decides, so `FAIL "2"` prints `2` and
4467 exits 1.
4468 "#},
4469 args: &[],
4470 flags: &[],
4471 default_output: Some(Stream::Stderr),
4472 examples: &[
4473 Example {
4474 name: "fail",
4475 fence_meta: Some("expect_error:\"EXIT requested with code 1\""),
4476 code: indoc! {r#"
4477 # The message prints to stderr, never stdout, so a
4478 # failure cannot pollute captured output. No code
4479 # means exit 1.
4480 FAIL "cargo not found in image"
4481 "#},
4482 },
4483 Example {
4484 name: "fail code",
4485 fence_meta: Some("expect_error:\"EXIT requested with code 2\""),
4486 code: indoc! {r#"
4487 # An explicit code exits with that code (clamped to
4488 # 0..=255 like EXIT); the message still prints to
4489 # stderr.
4490 FAIL 2 "cargo not found in image"
4491 "#},
4492 },
4493 Example {
4494 name: "fail block",
4495 fence_meta: Some("expect_error:\"EXIT requested with code 1\""),
4496 code: indoc! {r#"
4497 # The block runs first with its stdout rerouted to
4498 # stderr: usage text and cleanup land on the error
4499 # stream beside the message, and stdout stays empty.
4500 # Callee output reroutes too: a FUNC called here
4501 # inherits the swapped handle.
4502 FAIL "unknown command" {
4503 ECHO usage-text
4504 }
4505 "#},
4506 },
4507 ],
4508 },
4509 CommandMeta {
4510 in_index: true,
4511 name: KEYWORD_ISOLATED,
4512 syntax: "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>",
4513 summary: "Run steps with the seeded script environment.",
4514 description: indoc! {r#"
4515 Resets the script environment for the block to the session
4516 seed: spawned children see the sandbox defaults plus names
4517 the block re-adds through its leading `INHERIT_ENV`.
4518
4519 The allowlist resolves against the outer scope, never the
4520 host. Absent names stay absent silently, matching top-level
4521 `INHERIT_ENV`.
4522
4523 Script variables, pipes, and files flow through untouched;
4524 only `env:` is reset. Files share the session workspace:
4525 blocks selecting the same `WORKSPACE` target resolve to the
4526 same directory with no per-block overlay, so one block's
4527 writes are visible to another.
4528
4529 Blocks nest (each level re-seeds from the same seed, so
4530 nesting only narrows through the allowlists) and combine
4531 with `ASYNC` and `FUNC`. Scope exit restores the prior
4532 environment.
4533 "#},
4534 args: &[],
4535 flags: &[],
4536 default_output: None,
4537 examples: &[
4538 Example {
4539 name: "isolated scope",
4540 fence_meta: None,
4541 code: indoc! {r#"
4542 # The block sees a clean env; plain steps still run and
4543 # outer bindings survive untouched.
4544 ENV MODE=outer
4545 ISOLATED {
4546 ENV MODE=inner
4547 WRITE inner.txt "{{ env:MODE }}"
4548 }
4549 LET $back: STRING = "{{ env:MODE }}"
4550 ASSERT_EQ $back "outer"
4551 LET $body: STRING = READ inner.txt
4552 ASSERT_EQ $body "inner"
4553 "#},
4554 },
4555 Example {
4556 name: "reseeded child env",
4557 fence_meta: None,
4558 code: indoc! {r#"
4559 # The block resets to the session seed: plain steps and
4560 # spawns run with zero prelude. PATH needs no
4561 # declaration: contract seed rows are always admitted.
4562 WRITE top-path.txt "{{ env:PATH }}"
4563 ISOLATED {
4564 WRITE inner-path.txt "{{ env:PATH }}"
4565 RUN "echo seed-ok"
4566 }
4567 LET $top: STRING = READ top-path.txt
4568 LET $inner: STRING = READ inner-path.txt
4569 ASSERT_EQ $inner $top
4570 ASSERT_CONTAINS stdout "seed-ok"
4571 "#},
4572 },
4573 Example {
4574 name: "outer customs stay out",
4575 fence_meta: Some("expect_error:\"env:OUTER_CUSTOM\""),
4576 code: indoc! {r#"
4577 # Outer customs never enter the block: without an
4578 # allowlist entry the static gate rejects the read
4579 # before the first step runs.
4580 ENV OUTER_CUSTOM=outer-val
4581 ISOLATED {
4582 WRITE inner-custom.txt "{{ env:OUTER_CUSTOM }}"
4583 }
4584 "#},
4585 },
4586 Example {
4587 name: "absent names stay absent",
4588 fence_meta: None,
4589 code: indoc! {r#"
4590 # Listing a name the outer scope lacks is not an error:
4591 # the block simply runs without it.
4592 ISOLATED {
4593 INHERIT_ENV [OXDOC_DEFINITELY_ABSENT_12345]
4594 ECHO still-runs
4595 }
4596 ASSERT_CONTAINS stdout "still-runs"
4597 "#},
4598 },
4599 Example {
4600 name: "nesting narrows",
4601 fence_meta: None,
4602 code: indoc! {r#"
4603 # Each level snapshots the already-scrubbed parent, so
4604 # an inner block cannot recover what the outer dropped.
4605 ENV KEEP=yes
4606 ISOLATED {
4607 INHERIT_ENV [KEEP]
4608 ISOLATED {
4609 ENV KEEP=inner
4610 WRITE deep.txt "{{ env:KEEP }}"
4611 }
4612 LET $mid: STRING = "{{ env:KEEP }}"
4613 ASSERT_EQ $mid "yes"
4614 }
4615 LET $deep: STRING = READ deep.txt
4616 ASSERT_EQ $deep "inner"
4617 "#},
4618 },
4619 ],
4620 },
4621 CommandMeta {
4622 in_index: true,
4623 name: KEYWORD_REMOTE,
4624 syntax: "REMOTE <target> [[$var, ...] [env:NAME, ...]] { <commands> }",
4625 summary: "Run a sealed block on a remote target.",
4626 description: indoc! {r#"
4627 Runs the braced block on the named remote target, which the
4628 host binds at startup (`--remote`). The block is sealed:
4629 only header-listed `$var` and `env:NAME` entries cross, the
4630 guest starts empty, and results return through declared
4631 transfers or `WITH_IO` pipes.
4632
4633 The target is a static literal, never a variable. Unknown
4634 targets fail before execution starts.
4635
4636 Bodies check twice: the host static pass validates the
4637 body before anything ships, and the guest re-validates on
4638 arrival through the same entry point, so a body type error
4639 fails locally, never mid-run on the remote.
4640
4641 A failing guest fails the host step: EXIT in the body
4642 exits the guest, and the host relays the code to its own
4643 process exit status (see EXIT).
4644 "#},
4645 args: &[],
4646 flags: &[],
4647 default_output: None,
4648 examples: &[
4649 Example {
4650 name: "sealed header values cross, outer scope does not",
4651 fence_meta: Some("mock_remote:prod"),
4652 code: indoc! {r#"
4653 # Only header-listed names arrive: `$version` is visible
4654 # on the guest, `$secret` was never sent.
4655 LET $version: STRING = "1.2.3"
4656 LET $secret: STRING = "host-only"
4657 REMOTE prod [$version] {
4658 WRITE version.txt "{{ $version }}"
4659 COPY --to-host ./version.txt back.txt
4660 }
4661
4662 # The pushed file proves the guest saw the injected value.
4663 LET $back: STRING = READ back.txt
4664 ASSERT_EQ $back "1.2.3"
4665 "#},
4666 },
4667 Example {
4668 name: "background tasks stream through shared pipes",
4669 fence_meta: Some("mock_remote:prod"),
4670 code: indoc! {r#"
4671 # Two background REMOTEs share one capture pipe while a
4672 # WITH_IO block holds the write end open.
4673 IMPORT [STD]
4674 LET $cap: PIPE
4675 WITH_IO [stdout=$cap] {
4676 LET $a: HANDLE<VOID> = ASYNC REMOTE prod {
4677 ECHO "from-a"
4678 }
4679 LET $b: HANDLE<VOID> = ASYNC REMOTE prod {
4680 ECHO "from-b"
4681 }
4682 AWAIT $a
4683 AWAIT $b
4684 }
4685
4686 # EOF ends the drain: no sentinel line, no baked-in count.
4687 LET $n: INT = 0
4688 WHILE !EOF($cap) {
4689 WITH_IO [stdin=$cap] READ_LINE $line
4690 $n = $n + 1
4691 }
4692 ASSERT_EQ $n 2
4693 "#},
4694 },
4695 Example {
4696 name: "declared files cross both directions",
4697 fence_meta: Some("mock_remote:prod roots:unified"),
4698 code: indoc! {r#"
4699 # Fetches ride in, pushes ride back. Anything undeclared
4700 # never leaves its side.
4701 WRITE send.txt "payload"
4702 REMOTE prod {
4703 COPY --from-host ./send.txt got.txt
4704 LET $v: STRING = READ got.txt
4705 ASSERT_EQ $v "payload"
4706 WRITE back.txt "returned"
4707 COPY --to-host ./back.txt back.txt
4708 }
4709
4710 # The push landed on the host; guest staging is gone.
4711 LET $b: STRING = READ back.txt
4712 ASSERT_EQ $b "returned"
4713 "#},
4714 },
4715 Example {
4716 name: "guest workspace selection stays on the guest",
4717 fence_meta: Some("mock_remote:prod"),
4718 code: indoc! {r#"
4719 # WORKSPACE switches inside the block resolve against the
4720 # guest staging dir, which serves as both the SNAPSHOT
4721 # root and the LOCAL build context. The host selection
4722 # restores when the block exits.
4723 REMOTE prod {
4724 WORKSPACE SNAPSHOT
4725 WRITE out.txt "from-snapshot"
4726 COPY --to-host ./out.txt snap.txt
4727 }
4728
4729 LET $s: STRING = READ snap.txt
4730 ASSERT_EQ $s "from-snapshot"
4731 "#},
4732 },
4733 Example {
4734 name: "guest cache persists across execs",
4735 fence_meta: Some("mock_remote:prod"),
4736 code: indoc! {r#"
4737 # WORKSPACE CACHE addresses guest-local persistent
4738 # storage: the second block reads what the first wrote,
4739 # while the guest staging starts empty every time.
4740 REMOTE prod {
4741 WORKSPACE CACHE
4742 WRITE marker.txt "run-marker"
4743 }
4744 REMOTE prod {
4745 WORKSPACE CACHE
4746 LET $m: STRING = READ marker.txt
4747 ASSERT_EQ $m "run-marker"
4748 }
4749 "#},
4750 },
4751 Example {
4752 name: "pushes outside staging fail closed",
4753 fence_meta: Some("mock_remote:prod expect_error:\"escapes staging\""),
4754 code: indoc! {r#"
4755 # WORKSPACE SYSTEM exposes the whole guest machine, but
4756 # transfers stay staging scoped: a push source outside
4757 # staging fails loudly instead of crossing.
4758 REMOTE prod {
4759 WORKSPACE SYSTEM
4760 COPY --to-host /no/such/file.txt got.txt
4761 }
4762 "#},
4763 },
4764 Example {
4765 name: "guest exit fails the step, host survives",
4766 fence_meta: Some(
4767 "mock_remote:prod expect_error:\"REMOTE 'prod' exited with code 3\"",
4768 ),
4769 code: indoc! {r#"
4770 # EXIT in the body exits the guest with code 3. The
4771 # host is unaffected: it keeps executing after the
4772 # guest is already dead, and the failure surfaces as
4773 # a host step error carrying the same code. The CLI
4774 # then exits with it, so the guest code reaches the OS.
4775 LET $t: HANDLE<VOID> = ASYNC REMOTE prod {
4776 EXIT 3
4777 }
4778 WRITE host-alive.txt "still here"
4779 AWAIT $t
4780 "#},
4781 },
4782 Example {
4783 name: "remote block without a runner",
4784 fence_meta: Some("expect_error:\"has no registered session\""),
4785 code: indoc! {r#"
4786 # Without a bound session, the block bails instead of
4787 # executing anywhere unexpected.
4788 REMOTE prod {
4789 ECHO "do something on remote"
4790 }
4791 "#},
4792 },
4793 ],
4794 },
4795 CommandMeta {
4796 in_index: true,
4797 name: KEYWORD_FUNC,
4798 syntax: "FUNC NAME([$param: TYPE, ...]): RET { <commands> } | ASYNC FUNC NAME([$param: TYPE, ...]): HANDLE<T> { <commands> }",
4799 summary: "Define a user function.",
4800 description: indoc! {r#"
4801 Defines a user function with UPPERCASE name and explicitly typed
4802 parameters. `FUNC` runs synchronously; `ASYNC FUNC` is the same
4803 with a structural guarantee: the declaration must be
4804 `HANDLE<T>`, so every `RETURN` hands out a task handle.
4805
4806 Params bind by position, converting each argument to its
4807 declared parameter type before the body runs.
4808 A trailing `$name?: TYPE` marks an optional param: callers
4809 may omit trailing optionals, which fill with zero values
4810 (`false`, `""`, `0`, `0.0`, `[]`, `{}`) before the body
4811 binds. A required param after an optional one fails at
4812 definition, and an optional param with no zero value
4813 (records with required fields, unions, handles, custom
4814 types) fails at definition naming the fix: drop the `?`
4815 or pass the argument explicitly.
4816 Bodies run isolated: a fresh variable scope plus the
4817 callee definition-site jail (workspace, cwd, and env
4818 reset; only explicit arguments cross, #322). Module
4819 bodies restore the workspace selection and cwd their
4820 own top-level left behind, so a lib declaring
4821 WORKSPACE at the top serves its FUNCs from there no
4822 matter which workspace the caller sits in; entry
4823 bodies restore the workspace selection and cwd sealed
4824 at their definition site (defaulting to the snapshot
4825 jail when none was set before definition). A FUNC-level
4826 WORKSPACE or WORKDIR statement overrides the file
4827 default for that call, and the caller context returns
4828 on every exit path. Conditional top-level configuration
4829 uses guards (`[env:FLAG] WORKSPACE LOCAL`): `IF` bodies
4830 unwind on exit and never become the jail; see IMPORT.
4831 LETs inside do not leak. A nested
4832 FUNC definition is scoped to its block and reverts on exit. Names share
4833 one namespace with native and host-registered functions, which a FUNC
4834 may never shadow.
4835
4836 Functions resolve like variables: a name is visible from its
4837 definition line, so recursion works but mutual recursion does
4838 not (the second name does not exist while the first body
4839 lowers). Calls name their module (`STD::GLOB(...)`) unless
4840 imported; see IMPORT.
4841
4842 Invoke any function with one syntax: `NAME(...)` as a statement
4843 (discarding the value) or `LET $var: TYPE = NAME(...)` to capture
4844 the RETURN value (fallthrough without RETURN is a static error unless RET is VOID).
4845
4846 `ASYNC FUNC` does not spawn on call. The body runs
4847 synchronously on the caller thread up to its inner `ASYNC`
4848 step, which spawns the background task and yields its handle
4849 immediately; the function then hands that handle out with
4850 `RETURN $t`. The caller joins it separately with `AWAIT`.
4851 "#},
4852 args: &[],
4853 flags: &[],
4854 default_output: None,
4855 examples: &[
4856 Example {
4857 name: "func def call",
4858 fence_meta: None,
4859 code: indoc! {r#"
4860 FUNC GREET($name: STRING): STRING {
4861 RETURN $name
4862 }
4863
4864 LET $res: STRING = GREET("ada")
4865 ASSERT_EQ $res "ada"
4866
4867 # Statement form: parens stay, the value drops.
4868 GREET("bex")
4869 "#},
4870 },
4871 Example {
4872 name: "bind then interpolate",
4873 fence_meta: None,
4874 code: indoc! {r#"
4875 # Script FUNCs run as steps, never inside {{ }}.
4876 FUNC GREET($name: STRING): STRING {
4877 RETURN $name
4878 }
4879
4880 # Call as a step to capture the RETURN.
4881 LET $res: STRING = GREET("ada")
4882
4883 # {{ }} reads the bound var.
4884 LET $msg: STRING = "says {{ $res }}"
4885
4886 ASSERT_EQ $msg "says ada"
4887 "#},
4888 },
4889 Example {
4890 name: "script funcs never resolve in placeholders",
4891 fence_meta: Some(
4892 "expect_error:\"placeholder function 'SCRIPT::GREET' is a script function\"",
4893 ),
4894 code: indoc! {r#"
4895 # Placeholders carry no step context: pure registry only.
4896 FUNC GREET($name: STRING): STRING {
4897 RETURN $name
4898 }
4899
4900 # Bind the argument as a step var to keep quoting flat.
4901 LET $who: STRING = "ada"
4902
4903 # This fails naming the pure-only boundary.
4904 ECHO "{{ SCRIPT::GREET($who) }}"
4905 "#},
4906 },
4907 Example {
4908 name: "optional params fill zero values",
4909 fence_meta: None,
4910 code: indoc! {r#"
4911 IMPORT [STD]
4912 # Trailing `?` params may be omitted; they fill with
4913 # zero values (false, empty map) before the body binds,
4914 # so plain IF works on an omitted BOOL.
4915 FUNC ENSURE($check?: BOOL, $opts?: MAP<mode?: STRING>): STRING {
4916 IF $check {
4917 RETURN "checked"
4918 }
4919 IF HAS_KEY($opts, "mode") {
4920 RETURN "opts"
4921 }
4922 RETURN "plain"
4923 }
4924 LET $a: STRING = ENSURE()
4925 ASSERT_EQ $a "plain"
4926 LET $b: STRING = ENSURE(true)
4927 ASSERT_EQ $b "checked"
4928 LET $opts: MAP<mode?: STRING> = PARSE_JSON("{\"mode\": \"fast\"}")
4929 LET $c: STRING = ENSURE(false, $opts)
4930 ASSERT_EQ $c "opts"
4931 "#},
4932 },
4933 Example {
4934 name: "optional params must trail",
4935 fence_meta: Some("expect_error:\"optional ? params must be trailing\""),
4936 code: indoc! {r#"
4937 # A required param after an optional one fails at definition.
4938 FUNC BAD($a?: STRING, $b: STRING): STRING {
4939 RETURN $b
4940 }
4941 "#},
4942 },
4943 Example {
4944 name: "async func is a handle guarantee",
4945 fence_meta: None,
4946 code: indoc! {r#"
4947 # Side by side: identical bodies, identical handling. The
4948 # ASYNC marker only guarantees the HANDLE declaration.
4949 ASYNC FUNC FETCH(): HANDLE<STRING> {
4950 LET $t: HANDLE<STRING> = ASYNC { RETURN "hi" }
4951 RETURN $t
4952 }
4953 FUNC MAKE(): HANDLE<STRING> {
4954 LET $t: HANDLE<STRING> = ASYNC { RETURN "hi" }
4955 RETURN $t
4956 }
4957
4958 # Both run synchronously to RETURN; the inner ASYNC spawns.
4959 LET $a: HANDLE<STRING> = FETCH()
4960 LET $b: HANDLE<STRING> = MAKE()
4961 LET $x: STRING = AWAIT $a
4962 LET $y: STRING = AWAIT $b
4963 ASSERT_EQ $x "hi"
4964 ASSERT_EQ $y "hi"
4965 "#},
4966 },
4967 Example {
4968 name: "call with pipes",
4969 fence_meta: None,
4970 code: indoc! {r#"
4971 # A pipe handle travels into a function as a typed argument
4972 # and is usable as a binding target in both directions.
4973 # `LET $p: PIPE` mints the handle; `$p` passes it on.
4974 FUNC DRAIN($q: PIPE): STRING {
4975 WITH_IO [stdin=$q] READ_LINE $line
4976 RETURN $line
4977 }
4978
4979 LET $p: PIPE
4980 WITH_IO [stdout=$p] ECHO "payload"
4981
4982 LET $got: STRING = DRAIN($p)
4983 ASSERT_EQ $got "payload"
4984 "#},
4985 },
4986 ],
4987 },
4988 CommandMeta {
4989 in_index: true,
4990 name: KEYWORD_RETURN,
4991 syntax: "RETURN [<expr>]",
4992 summary: "Return a value from a function, task, or inline block.",
4993 description: indoc! {r#"
4994 Ends the nearest enclosing boundary with a value: a function
4995 call, an `ASYNC` task (bound by `LET $out: STRING = AWAIT $t`), or an
4996 inline `LET` block. Bare `RETURN` with no expression yields
4997 `""`.
4998
4999 Falling off the end without RETURN yields "". RETURN with no
5000 enclosing boundary (including at top level) is an error; use
5001 EXIT or ECHO there.
5002 "#},
5003 args: &[],
5004 flags: &[],
5005 default_output: None,
5006 examples: &[Example {
5007 name: "return",
5008 fence_meta: None,
5009 code: indoc! {r#"
5010 FUNC PICK($flag: BOOL): STRING {
5011 IF $flag {
5012 RETURN "yes"
5013 }
5014 RETURN "no"
5015 }
5016
5017 LET $res: STRING = PICK(true)
5018 ASSERT_EQ $res "yes"
5019
5020 # Fallthrough without RETURN yields its own value.
5021 LET $no: STRING = PICK(false)
5022 ASSERT_EQ $no "no"
5023 "#},
5024 }],
5025 },
5026 CommandMeta {
5027 in_index: true,
5028 name: KEYWORD_WHILE,
5029 syntax: "WHILE <bool-expr> { <commands> }",
5030 summary: "Loop while a condition holds.",
5031 description: indoc! {r#"
5032 Re-evaluates a Bool condition each iteration (same is_truthy rule as IF;
5033 non-Bool is a type error).
5034
5035 Each iteration runs in a fresh scope; mutate outer state with $var = ...
5036 so the next check observes it. BREAK exits the loop; CONTINUE skips to
5037 the next check.
5038 "#},
5039 args: &[],
5040 flags: &[],
5041 default_output: None,
5042 examples: &[Example {
5043 name: "while loop",
5044 fence_meta: None,
5045 code: indoc! {r#"
5046 # The condition re-evaluates every iteration: three passes, then stop.
5047 LET $n: INT = 0
5048 WHILE $n < 3 {
5049 WRITE tick.txt "{{ $n }}"
5050 $n = $n + 1
5051 }
5052
5053 ASSERT_EQ $n 3
5054 LET $tick: STRING = READ tick.txt
5055 ASSERT_EQ $tick "2"
5056 "#},
5057 }],
5058 },
5059 CommandMeta {
5060 in_index: true,
5061 name: KEYWORD_BREAK,
5062 syntax: KEYWORD_BREAK,
5063 summary: "Exit the innermost loop.",
5064 description: indoc! {r#"
5065 Exits the innermost enclosing FOR or WHILE loop.
5066
5067 BREAK outside a loop, or across a FUNC or ASYNC boundary, is an error.
5068 "#},
5069 args: &[],
5070 flags: &[],
5071 default_output: None,
5072 examples: &[
5073 Example {
5074 name: "break",
5075 fence_meta: None,
5076 code: indoc! {r#"
5077 # BREAK leaves after the first pass: only "a" is written.
5078 FOR $x: STRING IN ["a", "b"] {
5079 WRITE picked.txt "{{ $x }}"
5080 BREAK
5081 }
5082
5083 LET $body: STRING = READ picked.txt
5084 ASSERT_EQ $body "a"
5085 "#},
5086 },
5087 Example {
5088 name: "break nested",
5089 fence_meta: None,
5090 code: indoc! {r#"
5091 # Inner BREAK exits only the inner loop: the outer runs
5092 # both passes, and each inner stops before 2.
5093 LET $hits: LIST<STRING> = []
5094 FOR $o: STRING IN ["x", "y"] {
5095 FOR $i: INT IN [1, 2, 3] {
5096 IF $i == 2 {
5097 BREAK
5098 }
5099 LIST_APPEND $hits "{{ $o }}{{ $i }}"
5100 }
5101 }
5102
5103 LET $want: LIST<STRING> = ["x1", "y1"]
5104 ASSERT_EQ $hits $want
5105 "#},
5106 },
5107 ],
5108 },
5109 CommandMeta {
5110 in_index: true,
5111 name: KEYWORD_CONTINUE,
5112 syntax: KEYWORD_CONTINUE,
5113 summary: "Skip to the next loop iteration.",
5114 description: indoc! {r#"
5115 Skips the rest of the innermost enclosing FOR or WHILE body and starts
5116 the next iteration.
5117
5118 CONTINUE outside a loop, or across a FUNC or ASYNC boundary, is an error.
5119 "#},
5120 args: &[],
5121 flags: &[],
5122 default_output: None,
5123 examples: &[
5124 Example {
5125 name: "continue",
5126 fence_meta: None,
5127 code: indoc! {r#"
5128 # CONTINUE skips the write on "a": only "b" lands.
5129 FOR $x: STRING IN ["a", "b"] {
5130 IF $x == "a" {
5131 CONTINUE
5132 }
5133 WRITE picked.txt "{{ $x }}"
5134 }
5135
5136 LET $body: STRING = READ picked.txt
5137 ASSERT_EQ $body "b"
5138 "#},
5139 },
5140 Example {
5141 name: "continue nested",
5142 fence_meta: None,
5143 code: indoc! {r#"
5144 # Inner CONTINUE skips only the inner 2: the outer runs
5145 # both passes, and each inner still reaches 3.
5146 LET $hits: LIST<STRING> = []
5147 FOR $o: STRING IN ["x", "y"] {
5148 FOR $i: INT IN [1, 2, 3] {
5149 IF $i == 2 {
5150 CONTINUE
5151 }
5152 LIST_APPEND $hits "{{ $o }}{{ $i }}"
5153 }
5154 }
5155
5156 LET $want: LIST<STRING> = ["x1", "x3", "y1", "y3"]
5157 ASSERT_EQ $hits $want
5158 "#},
5159 },
5160 ],
5161 },
5162 CommandMeta {
5163 in_index: true,
5164 name: KEYWORD_IMPORT,
5165 syntax: "IMPORT [<module>, ...] | IMPORT <module> | IMPORT [\"<path>\" AS <ALIAS>] | IMPORT [<module | \"<path>\" AS <ALIAS> | [F, ... FROM (\"<path>\" | <module>) (AS <ALIAS>)?]>, ...]",
5166 summary: "Bring module functions into bare-call scope; import script files and types.",
5167 description: indoc! {r#"
5168 Bare calls:
5169 - Every call names its module (`STD::GLOB(...)`)
5170 unless the module is imported. `IMPORT [STD]` lets
5171 the rest of the scope call `GLOB(...)` bare.
5172 - Calls resolve at parse time: `SCRIPT` definitions
5173 first, then imported modules. Unknown modules,
5174 unknown functions, and unimported bare calls are
5175 parse errors, never runtime surprises.
5176
5177 Scope:
5178 - A file or harvest `IMPORT` applies from its line to
5179 the enclosing block exit, then unwinds like `LET`
5180 scoping: reads inside the block resolve, reads past
5181 it fail closed. Top-level imports persist for the
5182 unit. Module-only imports (`IMPORT [STD]`) register
5183 names with no step and no scope.
5184 - An `IMPORT` that never executes leaves its alias
5185 unknown: reads must follow the import in execution
5186 order.
5187 - Guards gate execution: a guarded `IMPORT` runs only
5188 where its guard holds. Same-frame duplicates reject
5189 at parse unless every entry is guard-gated;
5190 all-guarded duplicates resolve per platform when
5191 their guards are disjoint, and fail ambiguous on
5192 overlap.
5193 - Two imported modules exporting one name is an
5194 ambiguity error: qualify the call instead.
5195
5196 File imports:
5197 - Form: `IMPORT ["./lib.oxdock" AS LIB]` (any file
5198 extension). The alias is mandatory and becomes the
5199 namespace (`LIB::FOO`), with no filename inference.
5200 - Only `EXPORT`ed top-level `FUNC`s cross the
5201 boundary. Unexported means private; variables are
5202 never exportable.
5203 - Types cross qualified: a whole-file import exposes
5204 every exported alias as `ALIAS::NAME` only
5205 (`LET $p: LIB::PERSON` after
5206 `IMPORT ["./lib.oxfile" AS LIB]`), mirroring func
5207 views. Nothing bare leaks from an aliased import,
5208 so same-named types in different files coexist;
5209 harvests below stay the explicit way to request a
5210 bare name.
5211 - Each file initializes once; every alias shares the
5212 module's top-level bindings.
5213 - The file must exist when the run starts. Generated
5214 imports are rejected before the first step.
5215
5216 Mixed brackets:
5217 - Brackets mix both kinds across lines if needed
5218 (`IMPORT [STD, "a.oxdock" AS A]`). Each module entry
5219 registers in order; each file entry runs in order.
5220 - Without an alias a file entry is a parse error.
5221 - Value positions (`LET`, `ASYNC`,
5222 `WITH_IO`/`TIMEOUT` inners) take exactly one file
5223 entry and no modules.
5224
5225 Selective harvests:
5226 - Form: `IMPORT [FOO FROM "x.oxdock"]`,
5227 optionally `AS ALIAS`. Only the named top-level
5228 functions register, bare or namespaced under the
5229 alias. Harvested names must be `EXPORT`ed.
5230 - Single name needs no inner brackets
5231 (`IMPORT [FOO FROM "x.oxdock"]`); several names from
5232 one file combine in one bracket with explicit kinds
5233 (`IMPORT [TYPE A, TYPE B FROM "x.oxdock"]`, file or
5234 host alike: `IMPORT [FUNC FOO, FUNC BAR FROM
5235 "x.oxdock"]`). Bare names always read as modules, so
5236 a bare multi-name fails naming the explicit-kind
5237 fix. Prefer one import per file over grouping
5238 harvests.
5239 - Types and functions combine in one entry
5240 (`IMPORT [TYPE PERSON, FUNC FOO FROM "x.oxdock"]`).
5241 Harvested types must be `EXPORT TYPE`d. Unaliased
5242 harvests persist bare globally (collision-checked),
5243 so `FUNC` signatures keep working; aliased harvests
5244 persist qualified-only, like whole-file imports.
5245 - The file body never executes, so harvesting is
5246 side-effect free. The file's own nested imports
5247 still load. Harvests produce no value and never
5248 appear in value positions.
5249
5250 Host library types:
5251 - Form: `IMPORT [TYPE PIPE FROM STD]`. The import
5252 validates the type resolves globally and records no
5253 file. Host types stay global with or without the
5254 harvest; the explicit form only documents the
5255 dependency and fails fast on typos.
5256 - Bare `FROM` names a library; quoted `FROM`
5257 names a file path. Quoted `FROM "STD"` still parses
5258 for backcompat, but bare is preferred.
5259
5260 Paths:
5261 - Workspace-side, against the importing file's
5262 directory (entry parent at top level; off-workspace
5263 entries resolve like stdin against the root).
5264 - Relative operation paths resolve against the
5265 defining file's own jail: each module top-level
5266 runs isolated in the snapshot jail, and its
5267 WORKSPACE and WORKDIR statements establish the
5268 context its FUNCs restore on every call (#322).
5269 - Missing files fail before the first step runs.
5270 Write-then-import in one script is rejected; check
5271 libraries into the tree, or combine them at runtime
5272 and run a child interpreter (see the child run
5273 examples below).
5274
5275 Module rules (every file import is a module):
5276 - Context: never inherits the caller's namespace. Env
5277 resets to the seed plus the module init's own
5278 contributions (declared `INHERIT_ENV` names re-read
5279 from the host on every call). Workspace selection
5280 and cwd reset to the module top-level jail: the
5281 init body runs isolated in the snapshot jail, and
5282 the selection plus cwd it leaves behind become the
5283 default every FUNC of that file restores on entry,
5284 unless the FUNC body overrides them. A module
5285 function needing the caller directory takes it as
5286 a path argument.
5287 - Determinism: behavior is a pure function of the
5288 file. The same file behaves identically no matter
5289 who imports it or which workspace the importer
5290 sits in.
5291 - State: one init per file, shared by every alias.
5292 Top-level `LET` bindings drain into a single store
5293 visible to all of the module's functions.
5294 - Workspace: `WORKSPACE` and `WORKDIR` at a module
5295 top-level establish that module's jail for its
5296 FUNCs; `WORKSPACE` and `WORKDIR` inside a FUNC
5297 body override the file default for that call.
5298 Caller and callee selections never leak across
5299 the call in either direction.
5300 - Conditional top-level: `IF` bodies unwind on exit,
5301 so a `WORKSPACE` inside one never becomes the jail.
5302 Guard-gated steps (`[env:FLAG]`) run in place, so
5303 they persist: use guards for conditional config.
5304 - Exports: only `EXPORT`ed top-level `FUNC`s and
5305 `EXPORT TYPE` aliases cross. Variables never cross.
5306 - Imports: whole-file or harvest, only exported
5307 functions and types cross. Stateful harvests are
5308 rejected (import the file to share its module).
5309 Nested imports load automatically.
5310 - Cycles: circular imports and depth over 32 fail
5311 before the first step runs.
5312
5313 Exports and tools:
5314 - `EXPORT` marks top-level `FUNC`s as externally
5315 callable (`EXPORT FOO`, `EXPORT [FOO, BAR]`) and as
5316 the file importable interface. Re-exports promote
5317 an import (`IMPORT ["x.oxdock" AS A]` then `EXPORT
5318 A::FOO`).
5319 - `EXPORT TYPE` marks aliases the same way
5320 (`EXPORT TYPE PERSON`, `EXPORT TYPE [A, B]`, mixed
5321 `EXPORT [TYPE A, FUNC B]`). Only exported aliases
5322 cross, so `FUNC` signatures survive imports.
5323 - Serving resolves re-exports through the registry;
5324 unexported names fail tool setup instead of serving
5325 a dead tool. The MCP server skips `TYPE` exports
5326 when building tools while still resolving imported
5327 types for signatures. Single-file scope otherwise;
5328 see the MCP host for consumption.
5329 "#},
5330 args: &[],
5331 flags: &[],
5332 default_output: None,
5333 examples: &[
5334 Example {
5335 name: "import",
5336 fence_meta: None,
5337 code: indoc! {r#"
5338 # Calls name their module (STD::GLOB); IMPORT [STD] drops the prefix.
5339 WRITE a.txt "hi \{{ env:WHO }}!"
5340 IMPORT [STD]
5341 FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
5342 ASSERT_CONTAINS stdout "hi World!"
5343 "#},
5344 },
5345 Example {
5346 name: "module top-level jail",
5347 fence_meta: Some("roots:unified"),
5348 code: indoc! {r#"
5349 # A module top-level establishes its own jail: the lib
5350 # selects WORKSPACE LOCAL and a WORKDIR up front, and
5351 # its FUNC restores both on entry while the entry sits
5352 # elsewhere. Unified roots: the child inherits one
5353 # workspace, so parent and child see the same files.
5354 IMPORT [STD]
5355 WRITE lib.oxfile """
5356 IMPORT [STD]
5357 WORKSPACE LOCAL
5358 MKDIR modsub
5359 WORKDIR modsub
5360 EXPORT [FUNC WHERE]
5361 FUNC WHERE(): STRING {
5362 LET $c: STRING = CWD()
5363 RETURN $c
5364 }
5365 """
5366 WRITE main.oxfile """
5367 IMPORT [STD, "lib.oxfile" AS LIB]
5368 MKDIR entry-sub
5369 WORKDIR entry-sub
5370 LET $caller: STRING = CWD()
5371 LET $callee: STRING = LIB::WHERE()
5372 ASSERT_NE $caller $callee
5373 LET $base: STRING = STD::PATH_BASE($callee)
5374 ECHO "base \{{ $base }}"
5375 """
5376 LET $exe: STRING = INTERPRETER()
5377 LET $out: STRING = RUN [$exe, "main.oxfile"]
5378 ASSERT_CONTAINS $out "base modsub"
5379 "#},
5380 },
5381 Example {
5382 name: "blocks unwind, guards persist",
5383 fence_meta: None,
5384 code: indoc! {r#"
5385 # Blocks unwind on exit: the WORKDIR inside IF reverts,
5386 # so it never becomes a module jail. Bare guarded blocks
5387 # unwind the same way. Guards only skip, never push a
5388 # scope, so a guard-gated step persists.
5389 IMPORT [STD]
5390 WORKSPACE LOCAL
5391 LET $root: STRING = CWD()
5392 LET $go: BOOL = true
5393 IF $go {
5394 MKDIR inner
5395 WORKDIR inner
5396 }
5397 LET $after_if: STRING = CWD()
5398 ASSERT_EQ $root $after_if
5399 [bool:true] WORKDIR inner
5400 LET $after_guard: STRING = CWD()
5401 ASSERT_NE $root $after_guard
5402 MKDIR bare
5403 [bool:true] {
5404 WORKDIR bare
5405 }
5406 LET $after_bare: STRING = CWD()
5407 ASSERT_EQ $after_guard $after_bare
5408 "#},
5409 },
5410 Example {
5411 name: "import missing file fails upfront",
5412 fence_meta: Some("expect_error:\"must exist when the run starts\""),
5413 code: indoc! {r#"
5414 # Generated imports are rejected: a file that does not
5415 # exist when the run starts cannot be analyzed, so the
5416 # import fails before the first step runs.
5417 WORKSPACE LOCAL
5418 WRITE lib.oxdock 'FUNC F($x: STRING): STRING { RETURN $x } EXPORT F'
5419 IMPORT ["lib.oxdock" AS LIB]
5420 "#},
5421 },
5422 Example {
5423 name: "import missing alias fails",
5424 fence_meta: Some("expect_error:\"mandatory alias\""),
5425 code: indoc! {r#"
5426 # A file entry without AS is a parse error.
5427 IMPORT ["./lib.oxdock"]
5428 "#},
5429 },
5430 Example {
5431 name: "module cannot export a variable",
5432 fence_meta: Some("expect_error:\"does not match any top-level FUNC\""),
5433 code: indoc! {r#"
5434 # Only top-level FUNCs are exportable, never variables.
5435 LET $FOO: STRING = "x"
5436 EXPORT FOO
5437 "#},
5438 },
5439 Example {
5440 name: "import re-export unknown alias fails",
5441 fence_meta: Some("expect_error:\"does not match any top-level FUNC\""),
5442 code: indoc! {r#"
5443 # Re-exports name a visible import alias.
5444 IMPORT ["x.oxdock" AS A]
5445 EXPORT NOSUCH::FOO
5446 "#},
5447 },
5448 Example {
5449 name: "export type aliases",
5450 fence_meta: None,
5451 code: indoc! {r#"
5452 # TYPE aliases declare shapes once; EXPORT TYPE shares
5453 # them so importing files can use the same spelling.
5454 TYPE PERSON = MAP<name: STRING>
5455
5456 FUNC GREET($p: PERSON): STRING {
5457 RETURN "hi {{ $p.name }}"
5458 }
5459 EXPORT GREET
5460 EXPORT TYPE PERSON
5461
5462 LET $p: PERSON = {name: "Ada"}
5463 LET $greeting: STRING = GREET($p)
5464 ASSERT_EQ $greeting "hi Ada"
5465 "#},
5466 },
5467 Example {
5468 name: "import type from library",
5469 fence_meta: None,
5470 code: indoc! {r#"
5471 # One bracket mixes entry kinds: STD brings functions bare,
5472 # each harvest names a type. Types resolve globally with
5473 # or without the harvests; the explicit form only documents
5474 # the dependency, so this grouping is example only. Bare
5475 # FROM names a library; quoted FROM names a file path.
5476 IMPORT [STD, [TYPE PIPE FROM STD], [TYPE DURATION FROM STD]]
5477
5478 LET $p: PIPE
5479 WITH_IO [stdout=$p] ECHO hello
5480 WITH_IO [stdin=$p] READ_LINE $line
5481 ASSERT_EQ $line "hello"
5482
5483 LET $d: DURATION = "5s"
5484 LET $files: LIST<STRING> = GLOB("*.oxdock")
5485 "#},
5486 },
5487 Example {
5488 name: "run rendered modules in a child",
5489 fence_meta: Some("roots:unified"),
5490 code: indoc! {r#"
5491 # Dynamic assembly with files: the parent writes a
5492 # library and an entry script, then runs the entry in a
5493 # fresh interpreter. Child-side {{ }} stays escaped so
5494 # the parent does not interpolate it while writing. The
5495 # child runs by path so entry-relative IMPORT resolves.
5496 # Unified roots: the child inherits one workspace, so
5497 # parent and child see the same files.
5498 IMPORT [STD]
5499 WRITE lib.oxfile """
5500 FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
5501 EXPORT GREET
5502 """
5503 WRITE main.oxfile """
5504 IMPORT ["lib.oxfile" AS LIB]
5505 LET $g: STRING = LIB::GREET("Ada")
5506 ECHO "says \{{ $g }}"
5507 """
5508 LET $exe: STRING = INTERPRETER()
5509 LET $out: STRING = RUN [$exe, "main.oxfile"]
5510 ASSERT_CONTAINS $out "says hi Ada"
5511 "#},
5512 },
5513 Example {
5514 name: "dynamic module assembly",
5515 fence_meta: Some("roots:unified"),
5516 code: indoc! {r#"
5517 # A function that assembles a module: MAKE_GREETER bakes
5518 # its argument into a generated file with a bare {{ }},
5519 # then a child run imports the result. Bare {{ }} injects
5520 # parent values at write time; escaped \{{ }} survives for
5521 # the child to interpolate. Bind imported calls with LET:
5522 # {{ }} placeholders resolve pure functions only.
5523 IMPORT [STD]
5524
5525 # The renderer: parent values land in the module source.
5526 FUNC MAKE_GREETER($who: STRING): STRING {
5527 WRITE greeter.oxfile """
5528 FUNC GREET(): STRING { RETURN "hi {{ $who }}" }
5529 EXPORT GREET
5530 """
5531 RETURN "greeter.oxfile"
5532 }
5533
5534 # The entry: imports the rendered module by its path.
5535 WRITE main.oxfile """
5536 IMPORT ["greeter.oxfile" AS G]
5537 LET $g: STRING = G::GREET()
5538 ECHO "says \{{ $g }}"
5539 """
5540
5541 # Assemble, then run the entry in a fresh interpreter.
5542 LET $made: STRING = MAKE_GREETER("Ada")
5543 ASSERT_EQ $made "greeter.oxfile"
5544 LET $exe: STRING = INTERPRETER()
5545 LET $out: STRING = RUN [$exe, "main.oxfile"]
5546 ASSERT_CONTAINS $out "says hi Ada"
5547 "#},
5548 },
5549 Example {
5550 name: "export unknown type fails",
5551 fence_meta: Some("expect_error:\"does not match any top-level TYPE\""),
5552 code: indoc! {r#"
5553 # Only declared TYPE aliases are exportable.
5554 TYPE PERSON = MAP<name: STRING>
5555 EXPORT TYPE ANIMAL
5556 "#},
5557 },
5558 Example {
5559 name: "undeclared type fails",
5560 fence_meta: Some("expect_error:\"unknown type\""),
5561 code: indoc! {r#"
5562 # TYPE names must be declared before use.
5563 LET $p: PERSON = {name: "Ada"}
5564 "#},
5565 },
5566 ],
5567 },
5568 ]
5569}
5570
5571impl fmt::Display for StepKind {
5574 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5575 match self {
5576 StepKind::InheritEnv { keys } => {
5577 write!(f, "{} [{}]", KEYWORD_INHERIT_ENV, keys.join(", "))
5578 }
5579 StepKind::Workdir(a) => write!(f, "{} {}", KEYWORD_WORKDIR, fmt_value(a, quote_arg)),
5580 StepKind::Workspace(t) => write!(f, "{} {}", KEYWORD_WORKSPACE, t),
5581 StepKind::Env { key, value } => {
5582 write!(f, "{} {}={}", KEYWORD_ENV, key, fmt_value(value, quote_arg))
5583 }
5584 StepKind::Run(c) => write!(f, "{} {}", KEYWORD_RUN, fmt_value(c, quote_run)),
5585 StepKind::RunExec { argv } => {
5586 let parts: Vec<String> = argv.iter().map(fmt_exec_arg).collect();
5587 write!(f, "{} [{}]", KEYWORD_RUN, parts.join(", "))
5588 }
5589 StepKind::Echo(m) => write!(f, "{} {}", KEYWORD_ECHO, fmt_value(m, quote_msg)),
5590 StepKind::Copy {
5591 from_workspace,
5592 from_host,
5593 to_host,
5594 from,
5595 to,
5596 } => {
5597 let mut head = String::from(KEYWORD_COPY);
5598 if let Some(target) = from_workspace {
5599 head.push_str(&format!(" --from-workspace {target}"));
5600 }
5601 if *from_host {
5602 head.push_str(" --from-host");
5603 }
5604 if *to_host {
5605 head.push_str(" --to-host");
5606 }
5607 write!(
5608 f,
5609 "{head} {} {}",
5610 fmt_value(from, quote_arg),
5611 fmt_value(to, quote_arg)
5612 )
5613 }
5614 StepKind::Symlink {
5615 from_workspace,
5616 from,
5617 to,
5618 } => {
5619 if let Some(target) = from_workspace {
5620 write!(
5621 f,
5622 "{} --from-workspace {} {} {}",
5623 KEYWORD_SYMLINK,
5624 target,
5625 fmt_value(from, quote_arg),
5626 fmt_value(to, quote_arg)
5627 )
5628 } else {
5629 write!(
5630 f,
5631 "{} {} {}",
5632 KEYWORD_SYMLINK,
5633 fmt_value(from, quote_arg),
5634 fmt_value(to, quote_arg)
5635 )
5636 }
5637 }
5638 StepKind::Mkdir(a) => write!(f, "{} {}", KEYWORD_MKDIR, fmt_value(a, quote_arg)),
5639 StepKind::Install { from, to } => write!(
5640 f,
5641 "{} {} {}",
5642 KEYWORD_INSTALL,
5643 fmt_value(from, quote_arg),
5644 fmt_value(to, quote_arg)
5645 ),
5646 StepKind::SetExecutable { path } => {
5647 write!(
5648 f,
5649 "{} {}",
5650 KEYWORD_SET_EXECUTABLE,
5651 fmt_value(path, quote_arg)
5652 )
5653 }
5654 StepKind::Archive { src, dst, raw } => {
5655 if *raw {
5656 write!(
5657 f,
5658 "{} --raw {} {}",
5659 KEYWORD_ARCHIVE,
5660 fmt_value(src, quote_arg),
5661 fmt_value(dst, quote_arg)
5662 )
5663 } else {
5664 write!(
5665 f,
5666 "{} {} {}",
5667 KEYWORD_ARCHIVE,
5668 fmt_value(src, quote_arg),
5669 fmt_value(dst, quote_arg)
5670 )
5671 }
5672 }
5673 StepKind::Unarchive {
5674 src,
5675 dst,
5676 max_bytes,
5677 } => {
5678 write!(f, "{KEYWORD_UNARCHIVE}")?;
5679 if let Some(n) = max_bytes {
5680 write!(f, " --max-bytes {}", fmt_value(n, quote_arg))?;
5681 }
5682 write!(
5683 f,
5684 " {} {}",
5685 fmt_value(src, quote_arg),
5686 fmt_value(dst, quote_arg)
5687 )
5688 }
5689 StepKind::Ls(a) => {
5690 write!(f, "{KEYWORD_LS}")?;
5691 if let Some(x) = a {
5692 write!(f, " {}", fmt_value(x, quote_arg))?;
5693 }
5694 Ok(())
5695 }
5696 StepKind::Read(a) => {
5697 write!(f, "{KEYWORD_READ}")?;
5698 if let Some(x) = a {
5699 write!(f, " {}", fmt_value(x, quote_arg))?;
5700 }
5701 Ok(())
5702 }
5703 StepKind::ReadLine { var } => write!(f, "{} ${}", KEYWORD_READ_LINE, var),
5704 StepKind::Prompt {
5705 var,
5706 message,
5707 default,
5708 } => {
5709 write!(
5710 f,
5711 "{} ${} {}",
5712 KEYWORD_PROMPT,
5713 var,
5714 fmt_value(message, quote_arg)
5715 )?;
5716 if let Some(d) = default {
5717 write!(f, " {}", fmt_value(d, quote_arg))?;
5718 }
5719 Ok(())
5720 }
5721 StepKind::Write { path, contents } => {
5722 write!(f, "{} {}", KEYWORD_WRITE, fmt_value(path, quote_arg))?;
5723 if let Some(b) = contents {
5724 write!(f, " {}", fmt_value(b, quote_msg))?;
5725 }
5726 Ok(())
5727 }
5728 StepKind::Append { path, contents } => {
5729 write!(f, "{} {}", KEYWORD_APPEND, fmt_value(path, quote_arg))?;
5730 if let Some(b) = contents {
5731 write!(f, " {}", fmt_value(b, quote_msg))?;
5732 }
5733 Ok(())
5734 }
5735 StepKind::AppendLine { path, contents } => {
5736 write!(
5737 f,
5738 "{} {} {}",
5739 KEYWORD_APPEND_LINE,
5740 fmt_value(path, quote_arg),
5741 fmt_value(contents, quote_msg)
5742 )
5743 }
5744 StepKind::Remove { path, recursive } => {
5745 if *recursive {
5746 write!(
5747 f,
5748 "{} --recursive {}",
5749 KEYWORD_REMOVE,
5750 fmt_value(path, quote_arg)
5751 )
5752 } else {
5753 write!(f, "{} {}", KEYWORD_REMOVE, fmt_value(path, quote_arg))
5754 }
5755 }
5756 StepKind::Expand { path, overrides } => {
5757 write!(f, "{KEYWORD_EXPAND}")?;
5758 if let Some(p) = path {
5759 write!(f, " {}", fmt_value(p, quote_arg))?;
5760 }
5761 for (k, v) in overrides {
5762 write!(f, " {}={}", k, fmt_value(v, quote_arg))?;
5763 }
5764 Ok(())
5765 }
5766 StepKind::AssertEq {
5767 hash,
5768 actual,
5769 expected,
5770 }
5771 | StepKind::AssertNe {
5772 hash,
5773 actual,
5774 expected,
5775 } => {
5776 let verb = match self {
5777 StepKind::AssertEq { .. } => KEYWORD_ASSERT_EQ,
5778 _ => KEYWORD_ASSERT_NE,
5779 };
5780 if let Some(d) = hash {
5781 write!(f, "{verb} --hash {d} {}", fmt_assert_target(actual))?;
5782 } else {
5783 write!(
5784 f,
5785 "{verb} {} {}",
5786 fmt_assert_target(actual),
5787 fmt_value(
5788 expected
5789 .as_ref()
5790 .expect("Display of ASSERT without --hash needs expected"),
5791 quote_msg
5792 )
5793 )?;
5794 }
5795 Ok(())
5796 }
5797 StepKind::AssertContains { haystack, needle } => write!(
5798 f,
5799 "{} {} {}",
5800 KEYWORD_ASSERT_CONTAINS,
5801 fmt_assert_target(haystack),
5802 fmt_value(needle, quote_msg)
5803 ),
5804 StepKind::WithIo { bindings, cmd } => {
5805 let p: Vec<String> = bindings.iter().map(fmt_io).collect();
5806 write!(f, "{} [{}] {}", KEYWORD_WITH_IO, p.join(", "), cmd)
5807 }
5808 StepKind::WithIoBlock { bindings } => {
5809 let p: Vec<String> = bindings.iter().map(fmt_io).collect();
5810 write!(f, "{} [{}] {{...}}", KEYWORD_WITH_IO, p.join(", "))
5811 }
5812 StepKind::CopyGit {
5813 rev,
5814 from,
5815 to,
5816 include_dirty,
5817 } => {
5818 if *include_dirty {
5819 write!(
5820 f,
5821 "{} --include-dirty {} {} {}",
5822 KEYWORD_COPY_GIT,
5823 fmt_value(rev, quote_arg),
5824 fmt_value(from, quote_arg),
5825 fmt_value(to, quote_arg)
5826 )
5827 } else {
5828 write!(
5829 f,
5830 "{} {} {} {}",
5831 KEYWORD_COPY_GIT,
5832 fmt_value(rev, quote_arg),
5833 fmt_value(from, quote_arg),
5834 fmt_value(to, quote_arg)
5835 )
5836 }
5837 }
5838 StepKind::Exit(code) => write!(f, "{} {}", KEYWORD_EXIT, fmt_raw_arg(code)),
5839 StepKind::Fail {
5840 code,
5841 message,
5842 body,
5843 } => {
5844 write!(f, "{}", KEYWORD_FAIL)?;
5845 if let Some(c) = code {
5846 write!(f, " {}", fmt_raw_arg(c))?;
5847 }
5848 if let Some(m) = message {
5849 let rendered = match m {
5855 Arg::String(s, _)
5856 if code.is_none()
5857 && crate::command::strip_digit_separators(s)
5858 .parse::<i64>()
5859 .is_ok() =>
5860 {
5861 quote_dsl_string(s)
5862 }
5863 _ => fmt_value(m, quote_msg),
5864 };
5865 write!(f, " {rendered}")?;
5866 }
5867 if body.is_empty() {
5868 if code.is_none() && message.is_none() {
5873 return write!(f, " {{}}");
5874 }
5875 return Ok(());
5876 }
5877 write!(f, " {{")?;
5878 for s in body {
5879 write!(f, "\n {}", s)?;
5880 }
5881 write!(f, "\n}}")
5882 }
5883 StepKind::Sleep { duration } => {
5884 write!(f, "{} {}", KEYWORD_SLEEP, fmt_raw_arg(duration))
5885 }
5886 StepKind::ListAppend { list, item } => {
5887 write!(f, "{} ${} {}", KEYWORD_LIST_APPEND, list, fmt_raw_arg(item))
5888 }
5889 StepKind::For {
5890 key_var,
5891 key_type,
5892 var,
5893 var_type,
5894 in_expr,
5895 body,
5896 } => {
5897 match key_var {
5898 Some(k) => {
5899 let kt = key_type.as_deref().unwrap_or(crate::tag::STRING_TYPE_NAME);
5900 write!(
5901 f,
5902 "{} ${}: {}, ${}: {} IN {} {{",
5903 KEYWORD_FOR, k, kt, var, var_type, in_expr
5904 )?
5905 }
5906 None => write!(
5907 f,
5908 "{} ${}: {} IN {} {{",
5909 KEYWORD_FOR, var, var_type, in_expr
5910 )?,
5911 }
5912 for s in body {
5913 write!(f, "\n {}", s)?;
5914 }
5915 write!(f, "\n}}")
5916 }
5917 StepKind::If {
5918 cond,
5919 then_body,
5920 else_ifs,
5921 else_body,
5922 } => {
5923 write!(f, "{} {} {{", KEYWORD_IF, cond)?;
5924 for s in then_body {
5925 write!(f, "\n {}", s)?;
5926 }
5927 write!(f, " }}")?;
5928 for (c, b) in else_ifs {
5929 write!(f, " {} {} {} {{", KEYWORD_ELSE, KEYWORD_IF, c)?;
5930 for s in b {
5931 write!(f, "\n {}", s)?;
5932 }
5933 write!(f, " }}")?;
5934 }
5935 if let Some(b) = else_body {
5936 write!(f, " {} {{", KEYWORD_ELSE)?;
5937 for s in b {
5938 write!(f, "\n {}", s)?;
5939 }
5940 write!(f, " }}")?;
5941 }
5942 Ok(())
5943 }
5944 StepKind::Switch {
5945 discriminant,
5946 cases,
5947 default_body,
5948 } => {
5949 match discriminant {
5950 Some(disc) => write!(f, "{} {} {{", KEYWORD_SWITCH, disc)?,
5951 None => write!(f, "{} {{", KEYWORD_SWITCH)?,
5952 }
5953 for (exprs, body) in cases {
5954 write!(f, " {} ", KEYWORD_CASE)?;
5955 for (i, expr) in exprs.iter().enumerate() {
5956 if i > 0 {
5957 write!(f, ", ")?;
5958 }
5959 write!(f, "{}", expr)?;
5960 }
5961 write!(f, " {{")?;
5962 for s in body {
5963 write!(f, "\n {}", s)?;
5964 }
5965 write!(f, " }}")?;
5966 }
5967 if let Some(b) = default_body {
5968 write!(f, " {} {{", KEYWORD_DEFAULT)?;
5969 for s in b {
5970 write!(f, "\n {}", s)?;
5971 }
5972 write!(f, " }}")?;
5973 }
5974 write!(f, " }}")
5975 }
5976 StepKind::Bind {
5977 var,
5978 decl_type,
5979 is_const,
5980 rhs,
5981 } => {
5982 let keyword = if *is_const {
5983 KEYWORD_CONST
5984 } else {
5985 KEYWORD_LET
5986 };
5987 let name = sigil_var(var);
5988 match rhs {
5989 BindRhs::Expr(expr) => {
5990 if matches!(expr, Expr::FreshPipe) {
5992 write!(f, "{} {}: {}", keyword, name, decl_type)
5993 } else {
5994 write!(f, "{} {}: {} = {}", keyword, name, decl_type, expr)
5995 }
5996 }
5997 BindRhs::Capture(cmd) => {
5998 write!(f, "{} {}: {} = {}", keyword, name, decl_type, cmd)
5999 }
6000 BindRhs::Async(body) => {
6001 write!(
6002 f,
6003 "{} {}: {} = {} {{",
6004 keyword, name, decl_type, KEYWORD_ASYNC
6005 )?;
6006 for s in body {
6007 write!(f, "\n {}", s)?;
6008 }
6009 write!(f, "\n}}")
6010 }
6011 BindRhs::Await { task_var } => {
6012 write!(
6013 f,
6014 "{} {}: {} = {} ${}",
6015 keyword, name, decl_type, KEYWORD_AWAIT, task_var
6016 )
6017 }
6018 }
6019 }
6020 StepKind::Set { var, expr } => write!(f, "${} = {}", var, expr),
6021 StepKind::AsyncBlock { body } => {
6022 write!(f, "{} {{", KEYWORD_ASYNC)?;
6023 for s in body {
6024 write!(f, "\n {}", s)?;
6025 }
6026 write!(f, "\n}}")
6027 }
6028 StepKind::Await { var } => {
6029 write!(f, "{} ${}", KEYWORD_AWAIT, var)
6030 }
6031 StepKind::Cancel { var } => {
6032 write!(f, "{} ${}", KEYWORD_CANCEL, var)
6033 }
6034 StepKind::Timeout { duration, body } => {
6035 let budget = fmt_raw_arg(duration);
6036 if body.len() == 1 && body[0].guard.is_none() {
6040 write!(f, "{} {} {}", KEYWORD_TIMEOUT, budget, body[0].kind)
6041 } else {
6042 write!(f, "{} {} {{", KEYWORD_TIMEOUT, budget)?;
6043 for s in body {
6044 write!(f, "\n {}", s)?;
6045 }
6046 write!(f, "\n}}")
6047 }
6048 }
6049 StepKind::Isolated { body } => {
6050 if body.len() == 1 && body[0].guard.is_none() {
6051 write!(f, "{} {}", KEYWORD_ISOLATED, body[0].kind)
6052 } else {
6053 write!(f, "{} {{", KEYWORD_ISOLATED)?;
6054 for s in body {
6055 write!(f, "\n {}", s)?;
6056 }
6057 write!(f, "\n}}")
6058 }
6059 }
6060 StepKind::IsolatedInheritEnv { keys } => {
6061 write!(f, "{} [{}]", KEYWORD_INHERIT_ENV, keys.join(", "))
6065 }
6066 StepKind::RemoteBlock {
6067 target,
6068 vars,
6069 env,
6070 body,
6071 } => {
6072 let mut entries: Vec<String> = vars.iter().map(|v| sigil_var(v)).collect();
6073 entries.extend(env.iter().map(|e| format!("env:{e}")));
6074 if entries.is_empty() {
6075 write!(f, "{} {target} {{", KEYWORD_REMOTE)?;
6076 } else {
6077 write!(f, "{} {target} [{}] {{", KEYWORD_REMOTE, entries.join(", "))?;
6078 }
6079 for s in body {
6080 write!(f, "\n {}", s)?;
6081 }
6082 write!(f, "\n}}")
6083 }
6084 StepKind::FuncDef {
6085 name,
6086 params,
6087 return_type,
6088 is_async,
6089 body,
6090 docs,
6091 } => {
6092 if let Some((_, full)) = docs {
6096 for doc_line in full.split('\n') {
6097 writeln!(f, "# {doc_line}")?;
6098 }
6099 }
6100 let ps: Vec<String> = params
6101 .iter()
6102 .map(|(p, t, optional)| {
6103 format!(
6104 "{}{}: {}",
6105 sigil_var(p),
6106 if *optional { "?" } else { "" },
6107 t
6108 )
6109 })
6110 .collect();
6111 if *is_async {
6112 write!(
6113 f,
6114 "{} {} {}({}): {} {{",
6115 KEYWORD_ASYNC,
6116 KEYWORD_FUNC,
6117 name,
6118 ps.join(", "),
6119 return_type
6120 )?;
6121 } else {
6122 write!(
6123 f,
6124 "{} {}({}): {} {{",
6125 KEYWORD_FUNC,
6126 name,
6127 ps.join(", "),
6128 return_type
6129 )?;
6130 }
6131 for s in body {
6132 write!(f, "\n {}", s)?;
6133 }
6134 write!(f, "\n}}")
6135 }
6136 StepKind::Call { name, args } => {
6137 let ps: Vec<String> = args.iter().map(|a| format!("{}", a)).collect();
6138 write!(f, "{}({})", name, ps.join(", "))
6139 }
6140 StepKind::ImportFile { path, alias } => {
6141 write!(f, "{} [\"{}\" AS {}]", KEYWORD_IMPORT, path, alias)
6142 }
6143 StepKind::ImportFuncs {
6144 path,
6145 alias,
6146 func_names,
6147 type_names,
6148 } => {
6149 let mut parts: Vec<String> = Vec::new();
6150 for t in type_names {
6151 parts.push(format!("{KEYWORD_TYPE} {t}"));
6152 }
6153 for n in func_names {
6154 parts.push(n.clone());
6155 }
6156 match alias {
6157 Some(alias) => write!(
6158 f,
6159 "{} [[{} FROM \"{}\" AS {}]]",
6160 KEYWORD_IMPORT,
6161 parts.join(", "),
6162 path,
6163 alias
6164 ),
6165 None => write!(
6166 f,
6167 "{} [[{} FROM \"{}\"]]",
6168 KEYWORD_IMPORT,
6169 parts.join(", "),
6170 path
6171 ),
6172 }
6173 }
6174 StepKind::Return { expr, is_bare } => {
6175 if *is_bare {
6176 write!(f, "{KEYWORD_RETURN}")
6177 } else {
6178 write!(f, "{} {}", KEYWORD_RETURN, expr)
6179 }
6180 }
6181 StepKind::TypeAlias { name, target } => {
6182 write!(f, "{} {} = {}", KEYWORD_TYPE, name, target)
6183 }
6184 StepKind::While { cond, body } => {
6185 write!(f, "{} {} {{", KEYWORD_WHILE, cond)?;
6186 for s in body {
6187 write!(f, "\n {}", s)?;
6188 }
6189 write!(f, "\n}}")
6190 }
6191 StepKind::Break => write!(f, "{KEYWORD_BREAK}"),
6192 StepKind::Continue => write!(f, "{KEYWORD_CONTINUE}"),
6193 }
6194 }
6195}
6196
6197pub(crate) enum InsToken {
6202 Pos(Arg),
6203 Assign(String, Arg),
6204}
6205
6206pub(crate) fn lower_env_tokens(ctx: &SpanContext, tokens: Vec<InsToken>) -> ParseResult<StepKind> {
6207 if tokens.is_empty() {
6208 return Err(ParseError::from_diagnostic(
6209 ParseErrorKind::Validation {
6210 command: KEYWORD_ENV.to_string(),
6211 },
6212 dsl_diag::env_requires_assignment(),
6213 ctx,
6214 ));
6215 }
6216 match tokens.as_slice() {
6217 [InsToken::Assign(key, value)] => {
6218 if crate::command::split_assignment(&format!("{key}={}", value.render()))
6221 .map_err(|e| {
6222 ParseError::from_diagnostic(
6223 ParseErrorKind::Validation {
6224 command: KEYWORD_ENV.to_string(),
6225 },
6226 dsl_diag::env_assignment_error(e),
6227 ctx,
6228 )
6229 })?
6230 .is_none()
6231 {
6232 return Err(ParseError::from_diagnostic(
6233 ParseErrorKind::Validation {
6234 command: KEYWORD_ENV.to_string(),
6235 },
6236 dsl_diag::env_bad_format(),
6237 ctx,
6238 ));
6239 }
6240 Ok(StepKind::Env {
6241 key: key.clone(),
6242 value: value.clone(),
6243 })
6244 }
6245 [InsToken::Pos(Arg::String(text, _))] => match crate::command::split_assignment(text)
6246 .map_err(|e| {
6247 ParseError::from_diagnostic(
6248 ParseErrorKind::Validation {
6249 command: KEYWORD_ENV.to_string(),
6250 },
6251 dsl_diag::env_assignment_error(e),
6252 ctx,
6253 )
6254 })? {
6255 Some((key, value)) => Ok(StepKind::Env { key, value }),
6256 None => Err(ParseError::from_diagnostic(
6257 ParseErrorKind::Validation {
6258 command: KEYWORD_ENV.to_string(),
6259 },
6260 dsl_diag::env_bad_format(),
6261 ctx,
6262 )),
6263 },
6264 _ => Err(ParseError::from_diagnostic(
6265 ParseErrorKind::Validation {
6266 command: KEYWORD_ENV.to_string(),
6267 },
6268 dsl_diag::env_bad_format(),
6269 ctx,
6270 )),
6271 }
6272}
6273
6274pub(crate) fn lower_expand_tokens(
6278 ctx: &SpanContext,
6279 tokens: Vec<InsToken>,
6280) -> ParseResult<StepKind> {
6281 let mut path = None;
6282 let mut overrides = Vec::new();
6283 for token in tokens {
6284 match token {
6285 InsToken::Assign(key, value) => {
6286 if key.is_empty() {
6287 return Err(ParseError::from_diagnostic(
6288 ParseErrorKind::Validation {
6289 command: KEYWORD_EXPAND.to_string(),
6290 },
6291 dsl_diag::expand_bad_override(),
6292 ctx,
6293 ));
6294 }
6295 overrides.push((key, value));
6296 }
6297 InsToken::Pos(arg) => match &arg {
6298 Arg::String(text, quoted) if !quoted && text.contains('=') => {
6299 let Some((key, value)) =
6300 crate::command::split_assignment(text).map_err(|e| {
6301 ParseError::from_diagnostic(
6302 ParseErrorKind::Validation {
6303 command: KEYWORD_EXPAND.to_string(),
6304 },
6305 dsl_diag::expand_assignment_error(e),
6306 ctx,
6307 )
6308 })?
6309 else {
6310 return Err(ParseError::from_diagnostic(
6311 ParseErrorKind::Validation {
6312 command: KEYWORD_EXPAND.to_string(),
6313 },
6314 dsl_diag::expand_bad_override(),
6315 ctx,
6316 ));
6317 };
6318 overrides.push((key, value));
6319 }
6320 _ => {
6321 if path.is_none() {
6322 ArgType::Path.check_arg(&arg).map_err(|e| {
6326 ParseError::from_diagnostic(
6327 ParseErrorKind::Validation {
6328 command: KEYWORD_EXPAND.to_string(),
6329 },
6330 dsl_diag::expand_path_error(e),
6331 ctx,
6332 )
6333 })?;
6334 path = Some(arg);
6335 } else {
6336 return Err(ParseError::from_diagnostic(
6337 ParseErrorKind::Validation {
6338 command: KEYWORD_EXPAND.to_string(),
6339 },
6340 dsl_diag::expand_extra_path(),
6341 ctx,
6342 ));
6343 }
6344 }
6345 },
6346 }
6347 }
6348 Ok(StepKind::Expand { path, overrides })
6349}
6350
6351#[derive(Default)]
6355pub(crate) struct IoBindingSet {
6356 stdin: Option<IoBinding>,
6357 stdout: Option<IoBinding>,
6358 stderr: Option<IoBinding>,
6359 tty: Option<IoBinding>,
6360 rows: Option<IoBinding>,
6361 cols: Option<IoBinding>,
6362}
6363
6364impl IoBindingSet {
6365 pub(crate) fn insert(&mut self, binding: IoBinding) {
6366 match binding.stream {
6367 IoStream::Stdin => self.stdin = Some(binding),
6368 IoStream::Stdout => self.stdout = Some(binding),
6369 IoStream::Stderr => self.stderr = Some(binding),
6370 IoStream::Tty => self.tty = Some(binding),
6371 IoStream::Rows(_) => self.rows = Some(binding),
6372 IoStream::Cols(_) => self.cols = Some(binding),
6373 }
6374 }
6375
6376 pub(crate) fn into_vec(self) -> Vec<IoBinding> {
6377 let mut out = Vec::new();
6378 if let Some(binding) = self.stdin {
6379 out.push(binding);
6380 }
6381 if let Some(binding) = self.stdout {
6382 out.push(binding);
6383 }
6384 if let Some(binding) = self.stderr {
6385 out.push(binding);
6386 }
6387 if let Some(binding) = self.tty {
6388 out.push(binding);
6389 }
6390 if let Some(binding) = self.rows {
6391 out.push(binding);
6392 }
6393 if let Some(binding) = self.cols {
6394 out.push(binding);
6395 }
6396 out
6397 }
6398}
6399
6400pub(crate) fn merge_bindings(defaults: &[IoBinding], overrides: &[IoBinding]) -> Vec<IoBinding> {
6401 let mut set = IoBindingSet::default();
6402 for binding in defaults {
6403 set.insert(binding.clone());
6404 }
6405 for binding in overrides {
6406 set.insert(binding.clone());
6407 }
6408 set.into_vec()
6409}
6410
6411pub(crate) fn and_guard_exprs(
6412 left: Option<GuardExpr>,
6413 right: Option<GuardExpr>,
6414) -> Option<GuardExpr> {
6415 match (left, right) {
6416 (None, None) => None,
6417 (Some(expr), None) | (None, Some(expr)) => Some(expr),
6418 (Some(lhs), Some(rhs)) => Some(GuardExpr::all(vec![lhs, rhs])),
6419 }
6420}
6421
6422pub(crate) fn has_stdout_pipe(bindings: &[IoBinding]) -> bool {
6423 bindings
6424 .iter()
6425 .any(|b| b.stream == IoStream::Stdout && b.pipe.is_some())
6426}
6427
6428pub(crate) fn reject_async_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
6431 let bad = match kind {
6432 StepKind::AsyncBlock { .. }
6433 | StepKind::Bind {
6434 rhs: BindRhs::Async(_) | BindRhs::Await { .. },
6435 ..
6436 }
6437 | StepKind::Await { .. }
6438 | StepKind::Cancel { .. } => true,
6439 _ => {
6440 let mut bad = false;
6441 kind.walk_child_kinds(&mut |child| {
6442 bad = bad || reject_async_in_capture(ctx, child).is_err();
6443 });
6444 bad
6445 }
6446 };
6447 if bad {
6448 return Err(ParseError::from_diagnostic(
6449 ParseErrorKind::Structural {
6450 rule: KEYWORD_LET.to_lowercase(),
6451 },
6452 dsl_diag::let_capture_async(),
6453 ctx,
6454 ));
6455 }
6456 Ok(())
6457}
6458
6459pub(crate) fn reject_pipe_stdout_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
6462 if let StepKind::WithIo { bindings, .. } = kind
6463 && has_stdout_pipe(bindings)
6464 {
6465 return Err(ParseError::from_diagnostic(
6466 ParseErrorKind::Structural {
6467 rule: KEYWORD_LET.to_lowercase(),
6468 },
6469 dsl_diag::let_capture_pipe_stdout(),
6470 ctx,
6471 ));
6472 }
6473 let mut result = Ok(());
6474 kind.walk_child_kinds(&mut |child| {
6475 if result.is_ok() {
6476 result = reject_pipe_stdout_in_capture(ctx, child);
6477 }
6478 });
6479 result
6480}
6481
6482pub(crate) fn rewrite_isolated_inherit(body: &mut [Step]) {
6486 for step in body {
6487 rewrite_isolated_inherit_kind(&mut step.kind);
6488 }
6489}
6490
6491pub(crate) fn rewrite_isolated_inherit_kind(kind: &mut StepKind) {
6495 if let StepKind::InheritEnv { keys } = kind {
6496 *kind = StepKind::IsolatedInheritEnv { keys: keys.clone() };
6497 }
6498 match kind {
6499 StepKind::For { body, .. }
6500 | StepKind::While { body, .. }
6501 | StepKind::Timeout { body, .. }
6502 | StepKind::Fail { body, .. }
6503 | StepKind::Isolated { body }
6504 | StepKind::AsyncBlock { body } => rewrite_isolated_inherit(body),
6505 StepKind::Bind {
6506 rhs: BindRhs::Async(body),
6507 ..
6508 } => rewrite_isolated_inherit(body),
6509 StepKind::If {
6510 then_body,
6511 else_ifs,
6512 else_body,
6513 ..
6514 } => {
6515 rewrite_isolated_inherit(then_body);
6516 for (_, branch) in else_ifs {
6517 rewrite_isolated_inherit(branch);
6518 }
6519 if let Some(else_body) = else_body {
6520 rewrite_isolated_inherit(else_body);
6521 }
6522 }
6523 StepKind::Switch {
6524 cases,
6525 default_body,
6526 ..
6527 } => {
6528 for (_, branch) in cases {
6529 rewrite_isolated_inherit(branch);
6530 }
6531 if let Some(default_body) = default_body {
6532 rewrite_isolated_inherit(default_body);
6533 }
6534 }
6535 StepKind::WithIo { cmd, .. } => {
6536 rewrite_isolated_inherit_kind(cmd);
6537 }
6538 StepKind::Bind {
6539 rhs: BindRhs::Capture(cmd),
6540 ..
6541 } => {
6542 rewrite_isolated_inherit_kind(cmd);
6543 }
6544 _ => {}
6545 }
6546}
6547
6548pub(crate) fn contains_inherit_env(kind: &StepKind) -> bool {
6549 if matches!(kind, StepKind::InheritEnv { .. }) {
6550 return true;
6551 }
6552 let mut found = false;
6553 kind.walk_child_kinds(&mut |child| {
6554 found = found || contains_inherit_env(child);
6555 });
6556 found
6557}
6558
6559pub(crate) fn reject_nested_inherit_env(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
6563 if contains_inherit_env(kind) {
6564 return Err(ParseError::from_diagnostic(
6565 ParseErrorKind::Structural {
6566 rule: KEYWORD_INHERIT_ENV.to_lowercase(),
6567 },
6568 dsl_diag::nested_inherit_env(),
6569 ctx,
6570 ));
6571 }
6572 Ok(())
6573}
6574
6575pub(crate) fn check_tty_wrapping(
6576 bindings: &[IoBinding],
6577 cmd: Option<&StepKind>,
6578 span: &SpanContext,
6579) -> ParseResult<()> {
6580 let has_tty = bindings.iter().any(|b| matches!(b.stream, IoStream::Tty));
6581 let has_geometry = bindings
6582 .iter()
6583 .any(|b| matches!(b.stream, IoStream::Rows(_) | IoStream::Cols(_)));
6584 if has_geometry && !has_tty {
6585 return Err(ParseError::from_diagnostic(
6586 ParseErrorKind::Structural {
6587 rule: KEYWORD_WITH_IO.to_lowercase(),
6588 },
6589 dsl_diag::tty_geometry_without_tty(),
6590 span,
6591 ));
6592 }
6593 if !has_tty {
6594 return Ok(());
6595 }
6596 if bindings
6597 .iter()
6598 .any(|b| matches!(b.stream, IoStream::Stderr))
6599 {
6600 return Err(ParseError::from_diagnostic(
6601 ParseErrorKind::Structural {
6602 rule: KEYWORD_WITH_IO.to_lowercase(),
6603 },
6604 dsl_diag::tty_with_stderr(),
6605 span,
6606 ));
6607 }
6608 match cmd {
6609 Some(StepKind::Run(_) | StepKind::RunExec { .. }) | None => Ok(()),
6610 Some(_) => Err(ParseError::from_diagnostic(
6611 ParseErrorKind::Structural {
6612 rule: KEYWORD_WITH_IO.to_lowercase(),
6613 },
6614 dsl_diag::tty_wraps_non_run(),
6615 span,
6616 )),
6617 }
6618}
6619
6620pub(crate) fn reject_with_io_in_async(ctx: &SpanContext, body: &[Step]) -> ParseResult<()> {
6623 for step in body {
6624 if matches!(&step.kind, StepKind::WithIo { .. }) {
6625 return Err(ParseError::from_diagnostic(
6626 ParseErrorKind::Structural {
6627 rule: KEYWORD_ASYNC.to_lowercase(),
6628 },
6629 dsl_diag::with_io_in_async(),
6630 ctx,
6631 ));
6632 }
6633 }
6634 Ok(())
6635}
6636
6637#[allow(clippy::too_many_arguments)]
6650pub(crate) fn validate_exports(
6651 ctx: &SpanContext,
6652 exports: &super::parser::Exports,
6653 top: &HashSet<String>,
6654 top_types: &HashSet<String>,
6655 top_consts: &HashSet<String>,
6656 modules: &ModuleTable,
6657 top_imports: &[String],
6658) -> ParseResult<()> {
6659 for name in &exports.funcs {
6660 let valid = match crate::constants::split_qualified(name) {
6661 None => top.contains(name),
6662 Some((module, base)) if module == crate::constants::SCRIPT_MODULE_NAME => {
6663 top.contains(base)
6664 }
6665 Some((module, _base)) => match modules.modules.get(module) {
6666 None => {
6667 top_imports.iter().any(|m| m == module)
6675 }
6676 Some(None) => true,
6677 Some(Some(funcs)) => funcs.func_names.contains(_base),
6678 },
6679 };
6680 if !valid {
6681 return Err(ParseError::from_diagnostic(
6682 ParseErrorKind::Validation {
6683 command: crate::constants::KEYWORD_EXPORT.to_string(),
6684 },
6685 dsl_diag::export_unknown_func(name),
6686 ctx,
6687 ));
6688 }
6689 }
6690 for name in &exports.types {
6691 if crate::constants::split_qualified(name).is_some() {
6700 return Err(ParseError::from_diagnostic(
6701 ParseErrorKind::Validation {
6702 command: crate::constants::KEYWORD_EXPORT.to_string(),
6703 },
6704 dsl_diag::export_type_qualified(name),
6705 ctx,
6706 ));
6707 }
6708 if !top_types.contains(name) && top_imports.is_empty() {
6709 return Err(ParseError::from_diagnostic(
6710 ParseErrorKind::Validation {
6711 command: crate::constants::KEYWORD_EXPORT.to_string(),
6712 },
6713 dsl_diag::export_unknown_type(name),
6714 ctx,
6715 ));
6716 }
6717 }
6718 for name in &exports.consts {
6719 let valid = match crate::constants::split_qualified(name) {
6732 None => top_consts.contains(name),
6733 Some((module, _)) if module == crate::constants::SCRIPT_MODULE_NAME => false,
6734 Some((module, _base)) => top_imports.iter().any(|m| m == module),
6735 };
6736 if !valid {
6737 let diag = match crate::constants::split_qualified(name) {
6738 Some((module, _)) if module == crate::constants::SCRIPT_MODULE_NAME => {
6739 dsl_diag::export_const_script_namespace(name)
6740 }
6741 Some((module, _)) => dsl_diag::export_const_unknown_alias(name, module),
6742 None => dsl_diag::export_const_unknown(name),
6743 };
6744 return Err(ParseError::from_diagnostic(
6745 ParseErrorKind::Validation {
6746 command: crate::constants::KEYWORD_EXPORT.to_string(),
6747 },
6748 diag,
6749 ctx,
6750 ));
6751 }
6752 }
6753 Ok(())
6754}
6755
6756pub(crate) fn validate_remote_copy_placement(steps: &[Step], ctx: &SpanContext) -> ParseResult<()> {
6763 fn visit_kind(kind: &StepKind, in_remote: bool, ctx: &SpanContext) -> ParseResult<()> {
6764 if let StepKind::Copy {
6765 from_host, to_host, ..
6766 } = kind
6767 && (*from_host || *to_host)
6768 && !in_remote
6769 {
6770 return Err(ParseError::from_diagnostic(
6771 ParseErrorKind::Structural {
6772 rule: KEYWORD_COPY.to_lowercase(),
6773 },
6774 dsl_diag::copy_host_outside_remote(),
6775 ctx,
6776 ));
6777 }
6778 let child_remote = in_remote || matches!(kind, StepKind::RemoteBlock { .. });
6779 let mut result = Ok(());
6780 kind.walk_child_kinds(&mut |child| {
6781 if result.is_ok() {
6782 result = visit_kind(child, child_remote, ctx);
6783 }
6784 });
6785 result
6786 }
6787 for step in steps {
6788 visit_kind(&step.kind, false, ctx)?;
6789 }
6790 Ok(())
6791}
6792
6793pub(crate) fn contains_remote_block(steps: &[Step]) -> bool {
6797 steps.iter().any(|step| contains_remote_kind(&step.kind))
6798}
6799
6800pub(crate) fn contains_remote_kind(kind: &StepKind) -> bool {
6801 if matches!(kind, StepKind::RemoteBlock { .. }) {
6802 return true;
6803 }
6804 let mut found = false;
6805 kind.walk_child_kinds(&mut |child| {
6806 found = found || contains_remote_kind(child);
6807 });
6808 found
6809}
6810
6811pub(crate) fn collect_remote_body_symbols(
6817 steps: &[Step],
6818 defs: &mut HashSet<String>,
6819 calls: &mut Vec<String>,
6820) {
6821 for step in steps {
6822 collect_remote_kind_symbols(&step.kind, defs, calls);
6823 }
6824}
6825
6826pub(crate) fn collect_remote_kind_symbols(
6827 kind: &StepKind,
6828 defs: &mut HashSet<String>,
6829 calls: &mut Vec<String>,
6830) {
6831 if let StepKind::FuncDef { name, .. } = kind {
6832 defs.insert(name.clone());
6833 }
6834 if let StepKind::Call { name, .. } = kind {
6835 calls.push(name.clone());
6836 }
6837 kind.walk_step_exprs(&mut |expr| match expr {
6838 Expr::Call { name, .. } => calls.push(name.clone()),
6839 Expr::CompiledMath(ops) => {
6840 for op in ops {
6841 if let MathOp::Call { name, .. } = op {
6842 calls.push(name.clone());
6843 }
6844 }
6845 }
6846 Expr::Block(steps) => collect_remote_body_symbols(steps, defs, calls),
6847 _ => {}
6848 });
6849}
6850
6851pub(crate) fn reject_boundary(ctx: &SpanContext, expr: &Expr) -> ParseResult<()> {
6860 if matches!(expr, Expr::UnsignedIntBoundary(_)) {
6861 return Err(ParseError::from_diagnostic(
6862 ParseErrorKind::Structural {
6863 rule: "expr".to_string(),
6864 },
6865 dsl_diag::int_boundary_overflow(),
6866 ctx,
6867 ));
6868 }
6869 Ok(())
6870}
6871
6872pub(crate) fn apply_unary_neg(ctx: &SpanContext, expr: Expr) -> ParseResult<Expr> {
6876 match expr {
6877 Expr::Literal(v) => match (v.as_i64(), v.as_f64()) {
6878 (Some(n), _) => match n.checked_neg() {
6879 Some(neg) => Ok(Expr::Literal(Value::int(neg))),
6880 None => Ok(Expr::CompiledMath(vec![MathOp::PushConst(v), MathOp::Neg])),
6881 },
6882 (None, Some(f)) => Ok(Expr::Literal(Value::float(-f))),
6883 (None, None) => {
6884 let other = Expr::Literal(v);
6885 if let Some(mut ops) = expr_to_rpn(&other) {
6886 ops.push(MathOp::Neg);
6887 Ok(Expr::CompiledMath(ops))
6888 } else {
6889 Ok(Expr::Arithmetic {
6892 op: ArithOp::Sub,
6893 left: Box::new(Expr::Literal(Value::int(0))),
6894 right: Box::new(other),
6895 })
6896 }
6897 }
6898 },
6899 Expr::UnsignedIntBoundary(n) => {
6900 if n == i64::MAX as u64 + 1 {
6901 Ok(Expr::Literal(Value::int(i64::MIN)))
6902 } else {
6903 Err(ParseError::from_diagnostic(
6904 ParseErrorKind::Structural {
6905 rule: "expr".to_string(),
6906 },
6907 dsl_diag::int_overflow(n),
6908 ctx,
6909 ))
6910 }
6911 }
6912 other => {
6913 if let Some(mut ops) = expr_to_rpn(&other) {
6914 ops.push(MathOp::Neg);
6915 Ok(Expr::CompiledMath(ops))
6916 } else {
6917 Ok(Expr::Arithmetic {
6920 op: ArithOp::Sub,
6921 left: Box::new(Expr::Literal(Value::int(0))),
6922 right: Box::new(other),
6923 })
6924 }
6925 }
6926 }
6927}
6928
6929fn try_fold_arith(op: ArithOp, left: &Expr, right: &Expr) -> Option<Expr> {
6934 let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
6935 return None;
6936 };
6937 fold_arith_values(op, lv, rv).map(Expr::Literal)
6938}
6939
6940fn fold_arith_values(op: ArithOp, left: &Value, right: &Value) -> Option<Value> {
6941 match (left.as_i64(), right.as_i64()) {
6942 (Some(a), Some(b)) => {
6943 let v = match op {
6944 ArithOp::Add => a.checked_add(b)?,
6945 ArithOp::Sub => a.checked_sub(b)?,
6946 ArithOp::Mul => a.checked_mul(b)?,
6947 ArithOp::Div => a.checked_div(b)?,
6948 };
6949 Some(Value::int(v))
6950 }
6951 _ => {
6952 let (af, bf) = (as_f64(left)?, as_f64(right)?);
6953 fold_float(op, af, bf)
6954 }
6955 }
6956}
6957
6958fn fold_float(op: ArithOp, a: f64, b: f64) -> Option<Value> {
6959 if !a.is_finite() || !b.is_finite() {
6960 return None;
6961 }
6962 let v = match op {
6963 ArithOp::Add => a + b,
6964 ArithOp::Sub => a - b,
6965 ArithOp::Mul => a * b,
6966 ArithOp::Div => {
6967 if b == 0.0 {
6968 return None;
6969 }
6970 a / b
6971 }
6972 };
6973 if v.is_finite() {
6974 Some(Value::float(v))
6975 } else {
6976 None
6977 }
6978}
6979
6980fn try_fold_compare(op: CompareOp, left: &Expr, right: &Expr) -> Option<Expr> {
6981 let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
6982 return None;
6983 };
6984 match (lv.as_i64(), rv.as_i64()) {
6985 (Some(a), Some(b)) => {
6986 let r = match op {
6987 CompareOp::Eq => a == b,
6988 CompareOp::Ne => a != b,
6989 CompareOp::Lt => a < b,
6990 CompareOp::Le => a <= b,
6991 CompareOp::Gt => a > b,
6992 CompareOp::Ge => a >= b,
6993 };
6994 Some(Expr::Literal(Value::bool(r)))
6995 }
6996 _ => {
6997 if let (Some(a), Some(b)) = (lv.as_bool(), rv.as_bool()) {
6998 return match op {
6999 CompareOp::Eq => Some(Expr::Literal(Value::bool(a == b))),
7000 CompareOp::Ne => Some(Expr::Literal(Value::bool(a != b))),
7001 _ => None,
7002 };
7003 }
7004 let (af, bf) = (as_f64(lv)?, as_f64(rv)?);
7005 let r = match op {
7006 CompareOp::Eq => af == bf,
7007 CompareOp::Ne => af != bf,
7008 CompareOp::Lt => af < bf,
7009 CompareOp::Le => af <= bf,
7010 CompareOp::Gt => af > bf,
7011 CompareOp::Ge => af >= bf,
7012 };
7013 Some(Expr::Literal(Value::bool(r)))
7014 }
7015 }
7016}
7017
7018fn as_f64(v: &Value) -> Option<f64> {
7019 if let Some(n) = v.as_i64() {
7020 return Some(n as f64);
7021 }
7022 match v.as_f64() {
7023 Some(f) if f.is_finite() => Some(f),
7024 _ => None,
7025 }
7026}
7027
7028pub(crate) fn make_arith(
7030 ctx: &SpanContext,
7031 op: ArithOp,
7032 left: Expr,
7033 right: Expr,
7034) -> ParseResult<Expr> {
7035 reject_boundary(ctx, &left)?;
7036 reject_boundary(ctx, &right)?;
7037 if let Some(folded) = try_fold_arith(op, &left, &right) {
7038 return Ok(folded);
7039 }
7040 if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
7041 lops.append(&mut rops);
7042 lops.push(match op {
7043 ArithOp::Add => MathOp::Add,
7044 ArithOp::Sub => MathOp::Sub,
7045 ArithOp::Mul => MathOp::Mul,
7046 ArithOp::Div => MathOp::Div,
7047 });
7048 return Ok(Expr::CompiledMath(lops));
7049 }
7050 Ok(Expr::Arithmetic {
7051 op,
7052 left: Box::new(left),
7053 right: Box::new(right),
7054 })
7055}
7056
7057pub(crate) fn make_compare(
7059 ctx: &SpanContext,
7060 op: CompareOp,
7061 left: Expr,
7062 right: Expr,
7063) -> ParseResult<Expr> {
7064 reject_boundary(ctx, &left)?;
7065 reject_boundary(ctx, &right)?;
7066 if let Some(folded) = try_fold_compare(op, &left, &right) {
7067 return Ok(folded);
7068 }
7069 if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
7070 lops.append(&mut rops);
7071 lops.push(match op {
7072 CompareOp::Eq => MathOp::Eq,
7073 CompareOp::Ne => MathOp::Ne,
7074 CompareOp::Lt => MathOp::Lt,
7075 CompareOp::Le => MathOp::Le,
7076 CompareOp::Gt => MathOp::Gt,
7077 CompareOp::Ge => MathOp::Ge,
7078 });
7079 return Ok(Expr::CompiledMath(lops));
7080 }
7081 Ok(Expr::Compare {
7082 op,
7083 left: Box::new(left),
7084 right: Box::new(right),
7085 })
7086}
7087
7088pub(crate) fn expr_to_rpn(expr: &Expr) -> Option<Vec<MathOp>> {
7094 match expr {
7095 Expr::Literal(v) => Some(vec![MathOp::PushConst(v.clone())]),
7096 Expr::Var { name } => Some(vec![MathOp::Load { name: name.clone() }]),
7097 Expr::ConstRef { alias, name } => Some(vec![MathOp::LoadConstRef {
7098 alias: alias.clone(),
7099 name: name.clone(),
7100 }]),
7101 Expr::Env(key) => Some(vec![MathOp::LoadEnv(key.clone())]),
7102 Expr::KeyPath { base, keys } => Some(vec![MathOp::LoadKeyPath {
7103 base: base.clone(),
7104 keys: keys.clone(),
7105 }]),
7106 Expr::Call { name, args } => {
7107 let mut ops = Vec::new();
7108 for arg in args {
7109 ops.extend(expr_to_rpn(arg)?);
7110 }
7111 ops.push(MathOp::Call {
7112 name: name.clone(),
7113 arity: args.len(),
7114 });
7115 Some(ops)
7116 }
7117 Expr::Inspect { name } => Some(vec![MathOp::Inspect { name: name.clone() }]),
7118 Expr::Arithmetic { op, left, right } => {
7119 let mut ops = expr_to_rpn(left)?;
7120 ops.extend(expr_to_rpn(right)?);
7121 ops.push(match op {
7122 ArithOp::Add => MathOp::Add,
7123 ArithOp::Sub => MathOp::Sub,
7124 ArithOp::Mul => MathOp::Mul,
7125 ArithOp::Div => MathOp::Div,
7126 });
7127 Some(ops)
7128 }
7129 Expr::Compare { op, left, right } => {
7130 let mut ops = expr_to_rpn(left)?;
7131 ops.extend(expr_to_rpn(right)?);
7132 ops.push(match op {
7133 CompareOp::Eq => MathOp::Eq,
7134 CompareOp::Ne => MathOp::Ne,
7135 CompareOp::Lt => MathOp::Lt,
7136 CompareOp::Le => MathOp::Le,
7137 CompareOp::Gt => MathOp::Gt,
7138 CompareOp::Ge => MathOp::Ge,
7139 });
7140 Some(ops)
7141 }
7142 Expr::CompiledMath(ops) => Some(ops.clone()),
7143 Expr::FreshPipe => None,
7144 Expr::Not(_) | Expr::Logical { .. } | Expr::List(_) | Expr::Map(_) | Expr::Block(_) => None,
7145 Expr::UnsignedIntBoundary(_) => None,
7146 }
7147}
7148
7149pub(crate) fn classify_numeric_text(text: &str) -> Result<Expr, String> {
7154 let clean = text.replace('_', "");
7155 if clean.contains('.') {
7156 let parsed: f64 = clean
7157 .parse()
7158 .map_err(|_| format!("invalid float literal {text:?}"))?;
7159 if !parsed.is_finite() {
7160 return Err(format!("invalid float literal {text:?}"));
7161 }
7162 return Ok(Expr::Literal(Value::float(parsed)));
7163 }
7164 let digits: u64 = clean
7165 .parse()
7166 .map_err(|_| format!("integer overflow: {text:?} exceeds i64::MAX"))?;
7167 if digits <= i64::MAX as u64 {
7168 Ok(Expr::Literal(Value::int(digits as i64)))
7169 } else if digits == i64::MAX as u64 + 1 {
7170 Ok(Expr::UnsignedIntBoundary(digits))
7171 } else {
7172 Err(format!("integer overflow: {text:?} exceeds i64::MAX"))
7173 }
7174}
7175
7176#[cfg(test)]
7177mod tests {
7178 use super::*;
7179 use crate::command::{
7180 format_byte_count, format_duration, parse_byte_count, parse_duration,
7181 strip_digit_separators,
7182 };
7183 use crate::parser::parse_script;
7184
7185 fn parse_err(script: &str) -> String {
7186 parse_script(script, lower_command)
7187 .expect_err("script must fail to parse")
7188 .to_string()
7189 }
7190
7191 #[test]
7192 fn malformed_with_io_binding_names_the_bad_binding() {
7193 let err = parse_err("WITH_IO [stdout=discard] ECHO \"test\"\n");
7194 assert!(err.contains("WITH_IO"), "{err}");
7195 assert!(!err.contains("unknown command"), "{err}");
7196 assert!(err.contains("stdout=discard"), "{err}");
7197 assert!(err.contains("[stdout=$p]"), "{err}");
7198 }
7199
7200 #[test]
7201 fn connect_is_unknown_command() {
7202 let err = parse_err("CONNECT 127.0.0.1:8080\n");
7205 assert!(err.contains("unknown command"), "{err}");
7206 assert!(err.contains("CONNECT"), "{err}");
7207 }
7208
7209 #[test]
7210 fn listen_is_unknown_command() {
7211 let err = parse_err("LISTEN 127.0.0.1:8080\n");
7214 assert!(err.contains("unknown command"), "{err}");
7215 assert!(err.contains("LISTEN"), "{err}");
7216 }
7217
7218 #[test]
7219 fn await_without_task_variable_points_at_syntax() {
7220 let err = parse_err("AWAIT ECHO \"test\"\n");
7221 assert!(err.starts_with("AWAIT"), "{err}");
7222 assert!(!err.contains("unknown command"), "{err}");
7223 assert!(err.contains("AWAIT $t"), "{err}");
7224 assert!(err.contains("ECHO"), "{err}");
7225 }
7226
7227 #[test]
7228 fn bare_let_without_type_points_at_typed_syntax() {
7229 let err = parse_err("LET $x = 1\n");
7230 assert!(err.contains("LET requires explicit types"), "{err}");
7231 assert!(err.contains("LET $var: TYPE = <expr>"), "{err}");
7232 }
7233
7234 #[test]
7235 fn workspace_accepts_all_four_targets_uppercase_only() {
7236 for (spelling, target) in [
7239 ("SNAPSHOT", WorkspaceTarget::Snapshot),
7240 ("LOCAL", WorkspaceTarget::Local),
7241 ("CACHE", WorkspaceTarget::Cache { local: false }),
7242 ("SYSTEM", WorkspaceTarget::System),
7243 ] {
7244 let steps =
7245 parse_script(&format!("WORKSPACE {spelling}\n"), lower_command).expect("parses");
7246 assert_eq!(steps.len(), 1);
7247 assert_eq!(steps[0].kind, StepKind::Workspace(target.clone()));
7248 assert_eq!(steps[0].kind.to_string(), format!("WORKSPACE {target}"));
7249 }
7250 for spelling in ["snapshot", "local", "cache", "system"] {
7251 let err = parse_err(&format!("WORKSPACE {spelling}\n"));
7252 assert!(
7253 err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
7254 "{spelling}: {err}"
7255 );
7256 }
7257 let err = parse_err("WORKSPACE REMOTE\n");
7258 assert!(
7259 err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
7260 "{err}"
7261 );
7262
7263 let steps = parse_script("WORKSPACE CACHE --local\n", lower_command).expect("parses");
7266 assert_eq!(
7267 steps[0].kind,
7268 StepKind::Workspace(WorkspaceTarget::Cache { local: true })
7269 );
7270 assert_eq!(steps[0].kind.to_string(), "WORKSPACE CACHE --local");
7271 for bad in [
7272 "WORKSPACE SNAPSHOT --local\n",
7273 "WORKSPACE LOCAL --local\n",
7274 "WORKSPACE SYSTEM --local\n",
7275 ] {
7276 let err = parse_err(bad);
7277 assert!(err.contains("--local requires CACHE"), "{bad}: {err}");
7278 }
7279 }
7280
7281 #[test]
7282 fn archive_unarchive_parse_and_round_trip() {
7283 let steps = parse_script("ARCHIVE bundle bundle.tar.gz\n", lower_command).expect("parses");
7284 match &steps[0].kind {
7285 StepKind::Archive { src, dst, raw } => {
7286 assert_eq!(src.as_str(), "bundle");
7287 assert_eq!(dst.as_str(), "bundle.tar.gz");
7288 assert!(!raw);
7289 }
7290 other => panic!("expected Archive, got {other:?}"),
7291 }
7292 assert_eq!(
7293 steps[0].kind.to_string(),
7294 "ARCHIVE bundle \"bundle.tar.gz\""
7295 );
7296
7297 let steps =
7298 parse_script("ARCHIVE --raw tool.bin tool.tar\n", lower_command).expect("parses");
7299 assert!(
7300 matches!(&steps[0].kind, StepKind::Archive { raw: true, .. }),
7301 "unexpected lowering: {:?}",
7302 steps[0].kind
7303 );
7304 assert_eq!(
7305 steps[0].kind.to_string(),
7306 "ARCHIVE --raw \"tool.bin\" \"tool.tar\""
7307 );
7308
7309 let steps =
7310 parse_script("UNARCHIVE pack.tar.gz unpacked\n", lower_command).expect("parses");
7311 match &steps[0].kind {
7312 StepKind::Unarchive {
7313 src,
7314 dst,
7315 max_bytes,
7316 } => {
7317 assert_eq!(src.as_str(), "pack.tar.gz");
7318 assert_eq!(dst.as_str(), "unpacked");
7319 assert_eq!(max_bytes, &None);
7320 }
7321 other => panic!("expected Unarchive, got {other:?}"),
7322 }
7323 assert_eq!(
7324 steps[0].kind.to_string(),
7325 "UNARCHIVE \"pack.tar.gz\" unpacked"
7326 );
7327
7328 let steps = parse_script(
7329 "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
7330 lower_command,
7331 )
7332 .expect("parses");
7333 match &steps[0].kind {
7334 StepKind::Unarchive {
7335 src,
7336 dst,
7337 max_bytes,
7338 } => {
7339 assert_eq!(src.as_str(), "pack.tar.gz");
7340 assert_eq!(dst.as_str(), "unpacked");
7341 assert_eq!(max_bytes.as_ref().map(|a| a.as_str()), Some("100_000"));
7342 }
7343 other => panic!("expected Unarchive, got {other:?}"),
7344 }
7345 assert_eq!(
7346 steps[0].kind.to_string(),
7347 "UNARCHIVE --max-bytes \"100_000\" \"pack.tar.gz\" unpacked"
7348 );
7349
7350 for script in [
7351 "ARCHIVE bundle bundle.tar.gz\n",
7352 "ARCHIVE --raw tool.bin tool.tar\n",
7353 "UNARCHIVE pack.tar.gz unpacked\n",
7354 "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
7355 ] {
7356 let first = parse_script(script, lower_command).expect("parses");
7357 let rendered = first[0].kind.to_string() + "\n";
7358 let second = parse_script(&rendered, lower_command).expect("reparses");
7359 assert_eq!(
7362 second[0].kind.to_string(),
7363 first[0].kind.to_string(),
7364 "Display must fixpoint for {script:?}"
7365 );
7366 }
7367
7368 for bad in ["ARCHIVE only-src\n", "ARCHIVE\n", "UNARCHIVE only-src\n"] {
7369 let err = parse_err(bad);
7370 assert!(
7371 err.contains("ARCHIVE") || err.contains("UNARCHIVE"),
7372 "{bad}: {err}"
7373 );
7374 }
7375 }
7376
7377 #[test]
7378 fn copy_from_workspace_selects_source_root() {
7379 for (spelling, target) in [
7380 ("SNAPSHOT", WorkspaceTarget::Snapshot),
7381 ("LOCAL", WorkspaceTarget::Local),
7382 ("CACHE", WorkspaceTarget::Cache { local: false }),
7383 ("SYSTEM", WorkspaceTarget::System),
7384 ] {
7385 let steps = parse_script(
7386 &format!("COPY --from-workspace {spelling} a.txt b.txt\n"),
7387 lower_command,
7388 )
7389 .expect("parses");
7390 assert!(
7391 matches!(&steps[0].kind, StepKind::Copy { from_workspace: Some(t), .. } if *t == target),
7392 "unexpected lowering for {spelling}: {:?}",
7393 steps[0].kind
7394 );
7395 }
7396 for script in [
7399 "COPY --from-workspace=CACHE a.txt b.txt\n",
7400 "COPY --from-workspace=\"CACHE\" a.txt b.txt\n",
7401 ] {
7402 let steps = parse_script(script, lower_command).expect("parses");
7403 assert!(
7404 matches!(
7405 &steps[0].kind,
7406 StepKind::Copy {
7407 from_workspace: Some(WorkspaceTarget::Cache { local: false }),
7408 ..
7409 }
7410 ),
7411 "unexpected lowering for {script:?}: {:?}",
7412 steps[0].kind
7413 );
7414 }
7415 let steps = parse_script("COPY a.txt b.txt\n", lower_command).expect("parses");
7417 assert!(
7418 matches!(
7419 &steps[0].kind,
7420 StepKind::Copy {
7421 from_workspace: None,
7422 ..
7423 }
7424 ),
7425 "unexpected lowering: {:?}",
7426 steps[0].kind
7427 );
7428 for bad in ["REMOTE", "local"] {
7430 let err = parse_err(&format!("COPY --from-workspace {bad} a.txt b.txt\n"));
7431 assert!(err.contains("unknown workspace source"), "{bad}: {err}");
7432 }
7433 }
7434
7435 #[test]
7436 fn symlink_from_workspace_selects_source_root() {
7437 for (spelling, target) in [
7438 ("SNAPSHOT", WorkspaceTarget::Snapshot),
7439 ("LOCAL", WorkspaceTarget::Local),
7440 ("CACHE", WorkspaceTarget::Cache { local: false }),
7441 ("SYSTEM", WorkspaceTarget::System),
7442 ] {
7443 let steps = parse_script(
7444 &format!("SYMLINK --from-workspace {spelling} a.txt b.txt\n"),
7445 lower_command,
7446 )
7447 .expect("parses");
7448 assert!(
7449 matches!(&steps[0].kind, StepKind::Symlink { from_workspace: Some(t), .. } if *t == target),
7450 "unexpected lowering for {spelling}: {:?}",
7451 steps[0].kind
7452 );
7453 let roundtrip = steps[0].kind.to_string();
7454 assert!(
7455 roundtrip.contains("--from-workspace"),
7456 "display should round-trip the flag: {roundtrip}"
7457 );
7458 }
7459 let steps = parse_script("SYMLINK a.txt b.txt\n", lower_command).expect("parses");
7460 assert!(
7461 matches!(
7462 &steps[0].kind,
7463 StepKind::Symlink {
7464 from_workspace: None,
7465 ..
7466 }
7467 ),
7468 "unexpected lowering: {:?}",
7469 steps[0].kind
7470 );
7471 for bad in ["REMOTE", "local"] {
7472 let err = parse_err(&format!("SYMLINK --from-workspace {bad} a.txt b.txt\n"));
7473 assert!(err.contains("unknown workspace source"), "{bad}: {err}");
7474 }
7475 let steps = parse_script(
7477 "SYMLINK --from-workspace=LOCAL a.txt b.txt\n",
7478 lower_command,
7479 )
7480 .expect("parses");
7481 assert!(
7482 matches!(
7483 &steps[0].kind,
7484 StepKind::Symlink {
7485 from_workspace: Some(WorkspaceTarget::Local),
7486 ..
7487 }
7488 ),
7489 "unexpected lowering: {:?}",
7490 steps[0].kind
7491 );
7492 }
7493
7494 #[test]
7495 fn dash_dash_equals_tokens_bypass_assignment() {
7496 let steps = parse_script("ENV --foo=bar\n", lower_command).expect("parses");
7499 let StepKind::Env { key, value } = &steps[0].kind else {
7500 panic!("expected Env, got {:?}", steps[0].kind);
7501 };
7502 assert_eq!(key, "--foo");
7503 assert_eq!(value.as_str(), "bar");
7504
7505 let steps = parse_script("RUN echo --foo=bar\n", lower_command).expect("parses");
7506 let StepKind::Run(cmd) = &steps[0].kind else {
7507 panic!("expected Run, got {:?}", steps[0].kind);
7508 };
7509 assert!(
7510 cmd.as_str().contains("--foo=bar"),
7511 "unexpected RUN lowering: {cmd:?}"
7512 );
7513
7514 let digest = "08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c";
7515 let steps = parse_script(&format!("ASSERT_EQ --hash={digest} $body\n"), lower_command)
7516 .expect("parses");
7517 let StepKind::AssertEq { hash, .. } = &steps[0].kind else {
7518 panic!("expected AssertEq, got {:?}", steps[0].kind);
7519 };
7520 assert_eq!(hash.as_deref(), Some(digest));
7521
7522 let steps = parse_script("EXPAND --k=v\n", lower_command).expect("parses");
7524 let StepKind::Expand { path, overrides } = &steps[0].kind else {
7525 panic!("expected Expand, got {:?}", steps[0].kind);
7526 };
7527 assert!(path.is_none());
7528 assert_eq!(overrides.len(), 1);
7529 assert_eq!(overrides[0].0.as_str(), "--k");
7530 }
7531
7532 #[test]
7533 fn assert_ne_lowers_and_round_trips() {
7534 let steps = parse_script("ASSERT_NE $status 404\n", lower_command).expect("parses");
7535 let StepKind::AssertNe {
7536 hash,
7537 actual,
7538 expected,
7539 } = &steps[0].kind
7540 else {
7541 panic!("expected AssertNe, got {:?}", steps[0].kind);
7542 };
7543 assert!(hash.is_none());
7544 assert!(
7545 matches!(actual, AssertTarget::Value(_)),
7546 "unexpected actual: {actual:?}"
7547 );
7548 assert!(
7549 matches!(expected, Some(Arg::Expr(_))),
7550 "numeric expected lowers to an expression: {expected:?}"
7551 );
7552 let roundtrip = steps[0].kind.to_string();
7553 assert!(
7554 roundtrip.contains(Command::AssertNe.as_str()) && roundtrip.contains("404"),
7555 "display should round-trip the command: {roundtrip}"
7556 );
7557
7558 let err = parse_script("ASSERT_NE $status\n", lower_command).expect_err("needs expected");
7559 assert!(
7560 err.to_string().contains("requires an expected value"),
7561 "unexpected error: {err}"
7562 );
7563
7564 let err = parse_script("ASSERT_NE --hash abc123 $status \"junk\"\n", lower_command)
7565 .expect_err("hash plus expected must fail");
7566 assert!(
7567 err.to_string().contains("cannot be combined"),
7568 "unexpected error: {err}"
7569 );
7570
7571 let err = parse_script("ASSERT_EQ --hash abc123 $status \"junk\"\n", lower_command)
7573 .expect_err("hash plus expected must fail");
7574 assert!(
7575 err.to_string().contains("cannot be combined"),
7576 "unexpected error: {err}"
7577 );
7578 }
7579
7580 #[test]
7581 fn space_before_paren_is_not_a_call() {
7582 let steps = parse_script("ECHO (1 + 2)\n", lower_command).expect("parses");
7585 assert_eq!(steps.len(), 1);
7586 assert!(
7587 !matches!(steps[0].kind, crate::ast::StepKind::Call { .. }),
7588 "space before paren must not route to a call: {:?}",
7589 steps[0].kind
7590 );
7591 }
7592
7593 #[test]
7594 fn unknown_type_tag_parses_as_custom() {
7595 let steps = parse_script("LET $x: FOO = 1\n", lower_command).expect("custom tag parses");
7599 let StepKind::Bind {
7600 decl_type,
7601 rhs: BindRhs::Expr(_),
7602 ..
7603 } = &steps[0].kind
7604 else {
7605 panic!("expected Bind, got {:?}", steps[0].kind);
7606 };
7607 assert_eq!(decl_type, "FOO");
7608 }
7609
7610 #[test]
7611 fn bare_for_without_types_is_rejected() {
7612 let err = parse_err("FOR $i IN [1] { ECHO hi }\n");
7613 assert!(err.contains("FOR requires explicit types"), "{err}");
7614 }
7615
7616 #[test]
7617 fn mutate_statement_parses_without_keyword() {
7618 let steps = parse_script("$y = 2\n", lower_command).expect("mutation parses");
7619 assert!(matches!(steps[0].kind, StepKind::Set { .. }));
7620 }
7621
7622 #[test]
7623 fn keypath_mutation_target_is_rejected() {
7624 for script in ["$M.a = 2\n", "$C.0 = 2\n"] {
7627 let err = parse_err(script);
7628 assert!(err.contains("cannot assign to"), "{script}: {err}");
7629 assert!(err.contains("never mutation targets"), "{script}: {err}");
7630 }
7631 }
7632
7633 #[test]
7634 fn set_keyword_is_rejected_with_mutation_hint() {
7635 let err = parse_err("SET $y = 2\n");
7636 assert!(err.contains("not a keyword"), "{err}");
7637 assert!(err.contains("$var = <expr>"), "{err}");
7638 }
7639
7640 #[test]
7641 fn structural_fallthrough_commits_per_keyword() {
7642 for (script, cmd) in [
7643 ("CANCEL foo\n", "CANCEL"),
7644 ("TIMEOUT foo\n", "TIMEOUT"),
7645 ("FOR foo\n", "FOR"),
7646 ("IF foo\n", "IF"),
7647 ("LET foo\n", "LET"),
7648 ("ASYNC\n", "ASYNC"),
7652 ("ELSE foo\n", "ELSE"),
7653 ] {
7654 let err = parse_err(script);
7655 assert!(err.starts_with(cmd), "{cmd}: {err}");
7656 assert!(!err.contains("unknown command"), "{cmd}: {err}");
7657 }
7658 }
7659
7660 #[test]
7661 fn syntax_strings_open_with_their_keyword() {
7662 for cmd in crate::COMMANDS {
7667 let keyword = cmd.as_str();
7668 let syntax = cmd.syntax();
7669 assert!(
7670 syntax.starts_with(keyword),
7671 "syntax for {keyword} diverges from its keyword: {syntax:?}"
7672 );
7673 }
7674 for meta in all_metadata() {
7675 if meta.name == "MUTATION" {
7678 continue;
7679 }
7680 assert!(
7681 meta.syntax.starts_with(meta.name),
7682 "syntax for {} diverges from its keyword: {:?}",
7683 meta.name,
7684 meta.syntax
7685 );
7686 }
7687 }
7688
7689 #[test]
7690 fn leaf_arity_errors_are_command_lead() {
7691 let err = parse_err("SLEEP 1s 2s\n");
7692 assert!(err.starts_with("SLEEP"), "{err}");
7693 assert!(!err.contains("unknown command"), "{err}");
7694 }
7695
7696 #[test]
7697 fn list_append_lowers_variable_and_item() {
7698 let steps = parse_script("LIST_APPEND $items \"hi\"\n", lower_command).expect("parses");
7699 let StepKind::ListAppend { list, item } = &steps[0].kind else {
7700 panic!("expected ListAppend, got {:?}", steps[0].kind);
7701 };
7702 assert_eq!(list, "items");
7703 assert!(matches!(item, Arg::String(s, _) if s == "hi"));
7704 assert_eq!(steps[0].kind.to_string(), "LIST_APPEND $items \"hi\"");
7705 }
7706
7707 #[test]
7708 fn list_append_accepts_call_shaped_item() {
7709 let steps = parse_script(
7713 "FUNC MAKE(): STRING { RETURN \"made\" }\nLIST_APPEND $items MAKE()\n",
7714 lower_command,
7715 )
7716 .expect("parses");
7717 let StepKind::ListAppend { list, item } = &steps[1].kind else {
7718 panic!("expected ListAppend, got {:?}", steps[1].kind);
7719 };
7720 assert_eq!(list, "items");
7721 assert!(
7722 matches!(item, Arg::Expr(Expr::Call { name, .. }) if name == "SCRIPT::MAKE"),
7723 "{item:?}"
7724 );
7725 }
7726
7727 #[test]
7728 fn list_append_rejects_unknown_call_shaped_item() {
7729 let err = parse_err("LIST_APPEND $items NOPE()\n");
7733 assert!(err.contains("unknown function `NOPE`"), "{err}");
7734 }
7735
7736 #[test]
7737 fn list_append_rejects_wrong_arity() {
7738 for script in [
7739 "LIST_APPEND\n",
7740 "LIST_APPEND $items\n",
7741 "LIST_APPEND $items \"a\" \"b\"\n",
7742 ] {
7743 let err = parse_err(script);
7744 assert!(err.starts_with("LIST_APPEND"), "{script}: {err}");
7745 assert!(!err.contains("unknown command"), "{script}: {err}");
7746 }
7747 }
7748
7749 #[test]
7750 fn list_append_rejects_non_variable_target() {
7751 let err = parse_err("LIST_APPEND items \"a\"\n");
7752 assert!(err.starts_with("LIST_APPEND"), "{err}");
7753 assert!(!err.contains("unknown command"), "{err}");
7754 let err = parse_err("LIST_APPEND ITEMS \"a\"\n");
7757 assert!(err.starts_with("LIST_APPEND"), "{err}");
7758 assert!(!err.contains("unknown command"), "{err}");
7759 }
7760
7761 #[test]
7762 fn read_line_rejects_bare_word_target() {
7763 let err = parse_err("READ_LINE reply\n");
7768 assert!(err.contains("READ_LINE requires a $variable"), "{err}");
7769 assert!(!err.contains("unknown command"), "{err}");
7770 let err = parse_err("READ_LINE X\n");
7771 assert!(err.contains("READ_LINE requires a $variable"), "{err}");
7772 assert!(!err.contains("unknown command"), "{err}");
7773 }
7774
7775 #[test]
7776 fn genuinely_unknown_command_keeps_bare_message() {
7777 let err = parse_err("FROBNICATE hi\n");
7778 assert!(err.contains("unknown command \"FROBNICATE\""), "{err}");
7779 assert!(!err.contains("did you mean"), "{err}");
7780 }
7781
7782 #[test]
7783 fn lowercase_command_suggests_uppercase() {
7784 let err = lower_command("echo", vec![Arg::String("hi".to_string(), false)])
7788 .expect_err("must fail")
7789 .to_string();
7790 assert!(err.contains("unknown command \"echo\""), "{err}");
7791 assert!(err.contains("did you mean `ECHO`"), "{err}");
7792 }
7793
7794 #[test]
7795 fn func_def_requires_typed_uppercase_name() {
7796 let steps = parse_script(
7797 "FUNC GREET($name: STRING): STRING {\n RETURN $name\n}\n",
7798 lower_command,
7799 )
7800 .expect("func def parses");
7801 let StepKind::FuncDef {
7802 name,
7803 params,
7804 return_type,
7805 is_async,
7806 body,
7807 docs,
7808 } = &steps[0].kind
7809 else {
7810 panic!("expected FuncDef, got {:?}", steps[0].kind);
7811 };
7812 assert_eq!(name, "GREET");
7813 assert_eq!(
7814 params,
7815 &vec![("name".to_string(), "STRING".to_string(), false)],
7816 "{params:?}"
7817 );
7818 assert_eq!(return_type, "STRING", "{return_type:?}");
7819 assert!(!is_async, "plain FUNC is not async");
7820 assert!(matches!(body[0].kind, StepKind::Return { .. }));
7821 assert!(docs.is_none(), "undocumented FUNC carries no docs");
7822 }
7823
7824 #[test]
7825 fn lowercase_func_name_is_rejected() {
7826 let err = parse_err("FUNC greet($x: STRING) {\n RETURN $x\n}\n");
7827 assert!(err.contains("FUNC"), "{err}");
7828 }
7829
7830 #[test]
7831 fn func_def_optional_params_parse_with_flag() {
7832 let steps = parse_script(
7833 "FUNC F($a: STRING, $b?: INT): STRING {\n RETURN $a\n}\n",
7834 lower_command,
7835 )
7836 .expect("optional params parse");
7837 let StepKind::FuncDef { params, .. } = &steps[0].kind else {
7838 panic!("expected FuncDef, got {:?}", steps[0].kind);
7839 };
7840 assert_eq!(
7841 params,
7842 &vec![
7843 ("a".to_string(), "STRING".to_string(), false),
7844 ("b".to_string(), "INT".to_string(), true),
7845 ],
7846 "{params:?}"
7847 );
7848 assert_eq!(
7849 steps[0].kind.to_string(),
7850 "FUNC F($a: STRING, $b?: INT): STRING {\n RETURN $a\n}",
7851 "display marks the optional"
7852 );
7853 }
7854
7855 #[test]
7856 fn func_def_optional_params_must_trail() {
7857 let err = parse_err("FUNC F($a?: INT, $b: STRING): STRING {\n RETURN $b\n}\n");
7858 assert!(err.contains("optional ? params must be trailing"), "{err}");
7859 assert!(err.contains("`$b`"), "{err}");
7860 }
7861
7862 #[test]
7863 fn func_def_param_type_must_be_uppercase() {
7864 let err = parse_err("FUNC F($q: string): STRING {\n RETURN $q\n}\n");
7865 assert!(err.contains("needs an uppercase type"), "{err}");
7866 assert!(err.contains("`string`"), "{err}");
7867 }
7868
7869 #[test]
7870 fn func_def_malformed_params_name_the_shape() {
7871 for (script, expected) in [
7872 (
7873 "FUNC F($x?): STRING {\n RETURN \"hi\"\n}\n",
7874 "needs `: TYPE` after the name",
7875 ),
7876 (
7877 "FUNC F(bar): STRING {\n RETURN \"hi\"\n}\n",
7878 "must be `$name: TYPE` separated by commas",
7879 ),
7880 (
7881 "FUNC F($x: STRING,): STRING {\n RETURN $x\n}\n",
7882 "must not end with a trailing comma",
7883 ),
7884 ] {
7885 let err = parse_err(script);
7886 assert!(err.contains(expected), "{script}: {err}");
7887 }
7888 let err = parse_err("FUNC FOO() ECHO hi\n");
7891 assert!(err.starts_with("FUNC"), "{err}");
7892 assert!(err.contains("got `FOO() ECHO hi`"), "{err}");
7893 }
7894
7895 #[test]
7896 fn call_and_while_lower_correctly() {
7897 let steps = parse_script(
7898 "FUNC GREET($name: STRING): STRING {\n RETURN $name\n}\nGREET(\"ada\")\n",
7899 lower_command,
7900 )
7901 .expect("call parses");
7902 assert!(
7903 matches!(&steps[1].kind, StepKind::Call { name, .. } if name == "SCRIPT::GREET"),
7904 "{:?}",
7905 steps[1].kind
7906 );
7907 let steps = parse_script(
7908 "FUNC GREET($a: STRING, $b: STRING): STRING {\n RETURN $a\n}\nGREET(\"ada\", \"bex\")\n",
7909 lower_command,
7910 )
7911 .expect("spaced call parses");
7912 assert!(
7913 matches!(&steps[1].kind, StepKind::Call { name, args } if name == "SCRIPT::GREET" && args.len() == 2),
7914 "{:?}",
7915 steps[1].kind
7916 );
7917 let steps = parse_script(
7918 indoc! {r#"
7919 WHILE !$done {
7920 BREAK
7921 }
7922 "#},
7923 lower_command,
7924 )
7925 .expect("while parses");
7926 let StepKind::While { body, .. } = &steps[0].kind else {
7927 panic!("expected While, got {:?}", steps[0].kind);
7928 };
7929 assert!(matches!(body[0].kind, StepKind::Break));
7930 }
7931
7932 #[test]
7933 fn let_capture_call_and_async_call_lower() {
7934 let steps = parse_script(
7937 indoc! {r#"
7938 FUNC GREET($name: STRING): STRING {
7939 RETURN $name
7940 }
7941 LET $r: STRING = GREET("ada")
7942 "#},
7943 lower_command,
7944 )
7945 .expect("capture call parses");
7946 let StepKind::Bind {
7947 var,
7948 rhs: BindRhs::Expr(expr),
7949 ..
7950 } = &steps[1].kind
7951 else {
7952 panic!("expected Bind, got {:?}", steps[1].kind);
7953 };
7954 assert_eq!(var, "r");
7955 assert!(
7956 matches!(expr, Expr::Call { name, .. } if name == "SCRIPT::GREET"),
7957 "{expr:?}"
7958 );
7959 let steps = parse_script(
7960 "FUNC GREET($name: STRING): STRING {\n RETURN $name\n}\nLET $t: HANDLE<STRING> = ASYNC GREET(\"a\")\n",
7961 lower_command,
7962 )
7963 .expect("async call parses");
7964 assert!(
7965 matches!(
7966 &steps[1].kind,
7967 StepKind::Bind {
7968 rhs: BindRhs::Async(_),
7969 ..
7970 }
7971 ),
7972 "{:?}",
7973 steps[1].kind
7974 );
7975 }
7976
7977 #[test]
7978 fn multiline_call_args_span_lines() {
7979 let steps = parse_script(
7983 "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",
7984 lower_command,
7985 )
7986 .expect("multiline call parses");
7987 let StepKind::Bind {
7988 rhs: BindRhs::Expr(expr),
7989 ..
7990 } = &steps[1].kind
7991 else {
7992 panic!("expected Bind, got {:?}", steps[1].kind);
7993 };
7994 let Expr::Call { name, args } = expr else {
7995 panic!("expected Call expr, got {expr:?}");
7996 };
7997 assert_eq!(name, "SCRIPT::SERVE");
7998 assert_eq!(args.len(), 4);
7999 assert!(matches!(&args[3], Expr::Map(entries) if entries.len() == 1));
8000 let rendered = steps[1].to_string();
8002 assert!(!rendered.contains('\n'), "{rendered}");
8003 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";
8004 let again = parse_script(script, lower_command).expect("reparse ok");
8005 assert_eq!(again, steps);
8006 }
8007
8008 #[test]
8009 fn multiline_bare_call_and_list_span_lines() {
8010 let steps = parse_script(
8011 indoc! {r#"
8012 FUNC GREET($a: STRING): STRING {
8013 RETURN $a
8014 }
8015 GREET(
8016 "ada"
8017 )
8018 "#},
8019 lower_command,
8020 )
8021 .expect("multiline bare call parses");
8022 let StepKind::Call { name, args } = &steps[1].kind else {
8023 panic!("expected Call, got {:?}", steps[1].kind);
8024 };
8025 assert_eq!(name, "SCRIPT::GREET");
8026 assert_eq!(args.len(), 1);
8027 let steps = parse_script(
8028 indoc! {r#"
8029 LET $l: LIST = [
8030 "a",
8031 "b"
8032 ]
8033 "#},
8034 lower_command,
8035 )
8036 .expect("multiline list parses");
8037 let StepKind::Bind {
8038 rhs: BindRhs::Expr(expr),
8039 ..
8040 } = &steps[0].kind
8041 else {
8042 panic!("expected Bind, got {:?}", steps[0].kind);
8043 };
8044 assert!(
8045 matches!(expr, Expr::List(items) if items.len() == 2),
8046 "{expr:?}"
8047 );
8048 }
8049
8050 #[test]
8051 fn parse_duration_units() {
8052 use std::time::Duration;
8053 assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
8054 assert_eq!(parse_duration("10s").unwrap(), Duration::from_secs(10));
8055 assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
8056 assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
8057 assert_eq!(parse_duration("30").unwrap(), Duration::from_secs(30));
8058 assert_eq!(parse_duration("30 s").unwrap(), Duration::from_secs(30));
8060 assert_eq!(parse_duration("2 m").unwrap(), Duration::from_secs(120));
8061 }
8062
8063 #[test]
8064 fn parse_duration_rejects_garbage() {
8065 assert!(parse_duration("").is_err());
8066 assert!(parse_duration("banana").is_err());
8067 assert!(parse_duration("10x").is_err());
8068 assert!(parse_duration("0s").is_err());
8069 assert!(parse_duration("0").is_err());
8070 assert!(parse_duration("-5s").is_err());
8071 assert!(parse_duration("30 s s").is_err());
8073 assert!(parse_duration("3 0s").is_err());
8074 }
8075
8076 #[test]
8077 fn parse_byte_count_units() {
8078 assert_eq!(parse_byte_count("500").unwrap(), 500);
8079 assert_eq!(parse_byte_count("500B").unwrap(), 500);
8080 assert_eq!(parse_byte_count("10KB").unwrap(), 10_000);
8081 assert_eq!(parse_byte_count("2MB").unwrap(), 2_000_000);
8082 assert_eq!(parse_byte_count("1GB").unwrap(), 1_000_000_000);
8083 assert_eq!(parse_byte_count("1TB").unwrap(), 1_000_000_000_000);
8084 assert_eq!(parse_byte_count("10KIB").unwrap(), 10 * 1_024);
8085 assert_eq!(parse_byte_count("2MIB").unwrap(), 2 * 1_024 * 1_024);
8086 assert_eq!(parse_byte_count("1GIB").unwrap(), 1_024 * 1_024 * 1_024);
8087 assert_eq!(
8088 parse_byte_count("1TIB").unwrap(),
8089 1_024 * 1_024 * 1_024 * 1_024
8090 );
8091 assert_eq!(parse_byte_count("1gb").unwrap(), 1_000_000_000);
8093 assert_eq!(parse_byte_count("1Gb").unwrap(), 1_000_000_000);
8094 assert_eq!(parse_byte_count("1gib").unwrap(), 1_024 * 1_024 * 1_024);
8095 assert_eq!(parse_byte_count("1Gib").unwrap(), 1_024 * 1_024 * 1_024);
8096 assert_eq!(parse_byte_count("1_000").unwrap(), 1_000);
8098 assert_eq!(
8099 parse_byte_count("1_000_000_000_000").unwrap(),
8100 1_000_000_000_000
8101 );
8102 assert_eq!(parse_byte_count("1_0KB").unwrap(), 10_000);
8103 assert_eq!(
8104 parse_byte_count("1_0GiB").unwrap(),
8105 10 * 1_024 * 1_024 * 1_024
8106 );
8107 assert_eq!(parse_byte_count("1 GB").unwrap(), 1_000_000_000);
8109 assert_eq!(parse_byte_count("10 KiB").unwrap(), 10_240);
8110 assert_eq!(parse_byte_count(" 2MB ").unwrap(), 2_000_000);
8111 assert_eq!(parse_byte_count("+1 GB").unwrap(), 1_000_000_000);
8113 assert!(parse_byte_count("-1 GB").is_err());
8114 }
8115
8116 #[test]
8117 fn parse_byte_count_rejects_garbage() {
8118 for bad in [
8119 "",
8120 "banana",
8121 "10x",
8122 "1G",
8123 "1K",
8124 "1.5GB",
8125 "-5",
8126 "-5GB",
8127 "0",
8128 "0GB",
8129 "_100",
8130 "100_",
8131 "1__000",
8132 "_",
8133 "1_GB",
8134 "1 G B",
8136 "1 2",
8137 "1 0",
8138 "1000000000000000000000000",
8140 "1000000000TB",
8141 ] {
8142 assert!(parse_byte_count(bad).is_err(), "{bad:?} must fail");
8143 }
8144 }
8145
8146 #[test]
8147 fn format_byte_count_round_trips() {
8148 for text in [
8149 "500", "500B", "10KB", "2MB", "1GB", "1TB", "10KIB", "2MIB", "1GIB", "1TIB", "1500B",
8150 ] {
8151 let parsed = parse_byte_count(text).unwrap();
8152 let rendered = format_byte_count(parsed);
8153 assert_eq!(
8154 parse_byte_count(&rendered).unwrap(),
8155 parsed,
8156 "round-trip failed for {text}"
8157 );
8158 }
8159 assert_eq!(format_byte_count(1_024 * 1_024 * 1_024), "1GiB");
8160 assert_eq!(format_byte_count(1_000_000_000), "1GB");
8161 }
8162
8163 #[test]
8164 fn strip_digit_separators_passes_signs_through() {
8165 assert_eq!(strip_digit_separators("-1_000"), "-1000");
8169 assert_eq!(strip_digit_separators("+1_000_000"), "+1000000");
8170 assert_eq!(strip_digit_separators("-1_000.5"), "-1000.5");
8171 assert_eq!(strip_digit_separators("1_000"), "1000");
8172 for untouched in ["+", "-", "", "1__0", "abc", "+-5", "--5"] {
8173 assert_eq!(strip_digit_separators(untouched), untouched);
8174 }
8175 assert!(parse_byte_count("-1_000").is_err());
8178 assert_eq!(parse_byte_count("+1GB").unwrap(), 1_000_000_000);
8179 }
8180
8181 #[test]
8182 fn format_byte_count_is_lossless() {
8183 for n in [
8188 1,
8189 500,
8190 999,
8191 1_000,
8192 1_024,
8193 1_500,
8194 1_000_000,
8195 1_048_576,
8196 1_000_000_000,
8197 1_073_741_824,
8198 1_000_000_000_000,
8199 1_099_511_627_776,
8200 u64::MAX,
8201 ] {
8202 assert_eq!(
8203 parse_byte_count(&format_byte_count(n)).unwrap(),
8204 n,
8205 "lossless round-trip failed for {n}"
8206 );
8207 }
8208 }
8209
8210 #[test]
8211 fn format_duration_round_trips() {
8212 for text in ["500ms", "10s", "2m", "1h", "90s", "1500ms"] {
8213 let parsed = parse_duration(text).unwrap();
8214 let rendered = format_duration(&parsed);
8215 assert_eq!(
8216 parse_duration(&rendered).unwrap(),
8217 parsed,
8218 "round-trip failed for {text}"
8219 );
8220 }
8221 assert_eq!(format_duration(&parse_duration("90s").unwrap()), "90s");
8222 assert_eq!(format_duration(&parse_duration("2m").unwrap()), "2m");
8223 }
8224
8225 #[test]
8226 fn structural_metadata_covers_all_structural_kinds() {
8227 use crate::ast::Value;
8228
8229 fn metadata_name(kind: &StepKind) -> Option<&'static str> {
8233 match kind {
8234 StepKind::WithIo { .. } | StepKind::WithIoBlock { .. } => Some(KEYWORD_WITH_IO),
8235 StepKind::For { .. } => Some(KEYWORD_FOR),
8236 StepKind::If { .. } => Some(KEYWORD_IF),
8237 StepKind::Switch { .. } => Some(KEYWORD_SWITCH),
8238 StepKind::Bind { is_const, rhs, .. } => Some(match rhs {
8239 BindRhs::Await { .. } => {
8240 if *is_const {
8241 KEYWORD_CONST
8242 } else {
8243 KEYWORD_AWAIT
8244 }
8245 }
8246 BindRhs::Async(_) => {
8247 if *is_const {
8248 KEYWORD_CONST
8249 } else {
8250 KEYWORD_ASYNC
8251 }
8252 }
8253 _ => {
8254 if *is_const {
8255 KEYWORD_CONST
8256 } else {
8257 KEYWORD_LET
8258 }
8259 }
8260 }),
8261 StepKind::Set { .. } => Some("MUTATION"),
8262 StepKind::AsyncBlock { .. } => Some(KEYWORD_ASYNC),
8263 StepKind::Await { .. } => Some(KEYWORD_AWAIT),
8264 StepKind::Cancel { .. } => Some(KEYWORD_CANCEL),
8265 StepKind::Timeout { .. } => Some(KEYWORD_TIMEOUT),
8266 StepKind::Fail { .. } => Some(KEYWORD_FAIL),
8267 StepKind::Isolated { .. } => Some(KEYWORD_ISOLATED),
8268 StepKind::IsolatedInheritEnv { .. } => Some(KEYWORD_ISOLATED),
8269 StepKind::RemoteBlock { .. } => Some(KEYWORD_REMOTE),
8270 StepKind::FuncDef { .. } => Some(KEYWORD_FUNC),
8271 StepKind::Call { .. } => None,
8274 StepKind::ImportFile { .. } | StepKind::ImportFuncs { .. } => Some(KEYWORD_IMPORT),
8276 StepKind::Return { .. } => Some(KEYWORD_RETURN),
8277 StepKind::While { .. } => Some(KEYWORD_WHILE),
8278 StepKind::Break => Some(KEYWORD_BREAK),
8279 StepKind::Continue => Some(KEYWORD_CONTINUE),
8280 StepKind::TypeAlias { .. } => Some(KEYWORD_LET),
8284 StepKind::RunExec { .. } => None,
8285 StepKind::Workdir(_)
8286 | StepKind::Workspace(_)
8287 | StepKind::Env { .. }
8288 | StepKind::InheritEnv { .. }
8289 | StepKind::Run(_)
8290 | StepKind::Echo(_)
8291 | StepKind::Copy { .. }
8292 | StepKind::Symlink { .. }
8293 | StepKind::Mkdir(_)
8294 | StepKind::Archive { .. }
8295 | StepKind::Unarchive { .. }
8296 | StepKind::Install { .. }
8297 | StepKind::SetExecutable { .. }
8298 | StepKind::Ls(_)
8299 | StepKind::Read(_)
8300 | StepKind::ReadLine { .. }
8301 | StepKind::Prompt { .. }
8302 | StepKind::Write { .. }
8303 | StepKind::Append { .. }
8304 | StepKind::AppendLine { .. }
8305 | StepKind::Remove { .. }
8306 | StepKind::Expand { .. }
8307 | StepKind::AssertEq { .. }
8308 | StepKind::AssertContains { .. }
8309 | StepKind::AssertNe { .. }
8310 | StepKind::CopyGit { .. }
8311 | StepKind::Exit(_)
8312 | StepKind::Sleep { .. }
8313 | StepKind::ListAppend { .. } => None,
8314 }
8315 }
8316
8317 let dummies: Vec<StepKind> = vec![
8320 StepKind::WithIo {
8321 bindings: Vec::new(),
8322 cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
8323 "x".to_string(),
8324 false,
8325 ))),
8326 },
8327 StepKind::For {
8328 key_var: None,
8329 key_type: None,
8330 var: "i".to_string(),
8331 var_type: crate::tag::STRING_TYPE_NAME.to_string(),
8332 in_expr: Expr::Literal(Value::bool(true)),
8333 body: Vec::new(),
8334 },
8335 StepKind::If {
8336 cond: Box::new(Expr::Literal(Value::bool(true))),
8337 then_body: Vec::new(),
8338 else_ifs: Vec::new(),
8339 else_body: None,
8340 },
8341 StepKind::Switch {
8342 discriminant: None,
8343 cases: Vec::new(),
8344 default_body: None,
8345 },
8346 StepKind::Bind {
8347 var: "v".to_string(),
8348 decl_type: crate::tag::BOOL_TYPE_NAME.to_string(),
8349 is_const: false,
8350 rhs: BindRhs::Expr(Expr::Literal(Value::bool(true))),
8351 },
8352 StepKind::Bind {
8353 var: "v".to_string(),
8354 decl_type: crate::tag::BOOL_TYPE_NAME.to_string(),
8355 is_const: true,
8356 rhs: BindRhs::Expr(Expr::Literal(Value::bool(true))),
8357 },
8358 StepKind::Set {
8359 var: "v".to_string(),
8360 expr: Expr::Literal(Value::bool(true)),
8361 },
8362 StepKind::Bind {
8363 var: "v".to_string(),
8364 decl_type: crate::tag::STRING_TYPE_NAME.to_string(),
8365 is_const: false,
8366 rhs: BindRhs::Capture(Box::new(StepKind::Echo(crate::ast::Arg::String(
8367 "x".to_string(),
8368 false,
8369 )))),
8370 },
8371 StepKind::Bind {
8372 var: "o".to_string(),
8373 decl_type: crate::tag::STRING_TYPE_NAME.to_string(),
8374 is_const: false,
8375 rhs: BindRhs::Await {
8376 task_var: "t".to_string(),
8377 },
8378 },
8379 StepKind::AsyncBlock { body: Vec::new() },
8380 StepKind::Bind {
8381 var: "t".to_string(),
8382 decl_type: crate::tag::HANDLE_TYPE_NAME.to_string(),
8383 is_const: false,
8384 rhs: BindRhs::Async(Vec::new()),
8385 },
8386 StepKind::Await {
8387 var: "t".to_string(),
8388 },
8389 StepKind::Cancel {
8390 var: "t".to_string(),
8391 },
8392 StepKind::Timeout {
8393 duration: Arg::String("1s".to_string(), false),
8394 body: Vec::new(),
8395 },
8396 StepKind::Fail {
8397 code: None,
8398 message: None,
8399 body: Vec::new(),
8400 },
8401 StepKind::Isolated { body: Vec::new() },
8402 StepKind::IsolatedInheritEnv { keys: Vec::new() },
8403 StepKind::RemoteBlock {
8404 target: "prod".to_string(),
8405 vars: Vec::new(),
8406 env: Vec::new(),
8407 body: Vec::new(),
8408 },
8409 StepKind::FuncDef {
8410 name: "F".to_string(),
8411 params: Vec::new(),
8412 return_type: "STRING".to_string(),
8413 is_async: false,
8414 body: Vec::new(),
8415 docs: None,
8416 },
8417 StepKind::Call {
8418 name: "F".to_string(),
8419 args: Vec::new(),
8420 },
8421 StepKind::Return {
8422 expr: Box::new(Expr::Literal(Value::bool(true))),
8423 is_bare: false,
8424 },
8425 StepKind::While {
8426 cond: Box::new(Expr::Literal(Value::bool(true))),
8427 body: Vec::new(),
8428 },
8429 StepKind::Break,
8430 StepKind::Continue,
8431 StepKind::TypeAlias {
8432 name: "PERSON".to_string(),
8433 target: "MAP<name: STRING>".to_string(),
8434 },
8435 ];
8436 let registry = all_structural_metadata();
8437 for kind in &dummies {
8438 let Some(name) = metadata_name(kind) else {
8440 continue;
8441 };
8442 assert!(
8443 registry.iter().any(|meta| meta.name == name),
8444 "no structural metadata entry for {}",
8445 name
8446 );
8447 }
8448 }
8449}