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