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