1#![allow(rustdoc::invalid_codeblock_attributes)]
19#![doc = include_str!("../docs/command_reference.md")]
20
21extern crate self as oxdock_parser;
22
23pub mod ast;
24pub mod command;
25pub mod commands;
26pub mod constants;
27pub mod error;
28pub mod literal;
29#[cfg(feature = "proc-macro-api")]
30mod macro_input;
31pub mod markdown;
32pub mod parser;
33mod resolve;
34pub mod strip_flags;
35pub mod tag;
36pub mod template;
37pub mod tok;
38pub mod value;
39
40pub use ast::*;
41pub use command::{
42 ArgSpec, ArgType, CommandMeta, CommandSpec, Example, FlagSpec, FlagValueType, IoDirection,
43 Stream,
44};
45pub use commands::{all_metadata, all_structural_metadata, lower_command};
46pub use constants::*;
47pub use error::{ParseError, ParseErrorKind, ParseResult, SpanContext};
48pub use literal::{escape_dsl_string, render_dsl_literal, render_quoted};
49#[cfg(feature = "proc-macro-api")]
50pub use macro_input::{
51 DslMacroInput, ScriptSource, parse_braced_tokens, parse_braced_tokens_with_exports,
52 parse_braced_tokens_with_modules, parse_braced_tokens_with_modules_and_exports,
53 script_from_braced_tokens, split_modules_prefix,
54};
55pub use markdown::{BlockMetadata, FencedBlock, expect_error_from_info, extract_fenced_blocks};
56pub use parser::{
57 ExportKind, Exports, ParseCtx, ParsedScript, TokenError, parse_expression_str,
58 parse_guard_expr_str, parse_script, parse_script_with_exports, parse_script_with_modules,
59 parse_script_with_modules_and_exports, parse_script_with_preseed, parse_tokens,
60 parse_tokens_with_ctx,
61};
62pub use strip_flags::strip_flags;
63pub use tag::{
64 ANY_TAG, ANY_TYPE_NAME, BOOL_TYPE_NAME, DURATION_TYPE_NAME, FLOAT_TYPE_NAME, Field,
65 HANDLE_TYPE_NAME, INT_TYPE_NAME, LIST_TAG, LIST_TYPE_NAME, MAP_TAG, MAP_TYPE_NAME,
66 MAX_GENERIC_DEPTH, PATH_TYPE_NAME, PERMIT_TYPE_NAME, PIPE_TYPE_NAME, SEMAPHORE_TYPE_NAME,
67 STRING_TYPE_NAME, Spelled, SpelledDefault, SpelledField, TypeTag, VOID_TYPE_NAME,
68 canonicalize_spelling, check_value, check_value_at, intern_rendered, lookup_rendered,
69 parse_spelling, render_structural,
70};
71#[cfg(feature = "proc-macro-api")]
72pub use tok::lex_tokens;
73pub use tok::{GroupDelim, LexError, Tok, TokKind, lex_str};
74
75pub mod test_lower_mock {
79 use crate::error::{ParseError, SpanContext};
80 use crate::{Arg, ParseResult, StepKind, WorkspaceTarget};
81
82 fn validation(cmd: &str, msg: &str) -> ParseError {
83 ParseError::validation(cmd, msg.to_string(), &SpanContext::line_only(0))
84 }
85
86 pub fn lower(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
87 match name {
88 "LS" => Ok(StepKind::Ls(None)),
89 "WRITE" => {
90 let mut it = args.into_iter();
91 let path = it
92 .next()
93 .ok_or_else(|| validation("WRITE", "WRITE requires path"))?;
94 let remaining: Vec<_> = it.collect();
95 let contents = if remaining.is_empty() {
96 None
97 } else {
98 let joined = remaining
99 .iter()
100 .map(|a| a.as_str())
101 .collect::<Vec<_>>()
102 .join(" ");
103 Some(Arg::String(joined, false))
104 };
105 Ok(StepKind::Write { path, contents })
106 }
107 "ENV" => crate::commands::lower_env_assignment(args)
108 .map_err(|e| validation("ENV", &e.to_string())),
109 "WORKSPACE" => {
110 let mut it = args.into_iter();
111 let target = it
112 .next()
113 .ok_or_else(|| validation("WORKSPACE", "requires target"))?;
114 let local = it.any(|a| a.as_str() == "--local");
115 match target.as_str() {
116 "SNAPSHOT" | "LOCAL" | "SYSTEM" if local => {
117 Err(validation("WORKSPACE", "--local requires CACHE"))
118 }
119 "SNAPSHOT" => Ok(StepKind::Workspace(WorkspaceTarget::Snapshot)),
120 "LOCAL" => Ok(StepKind::Workspace(WorkspaceTarget::Local)),
121 "CACHE" => Ok(StepKind::Workspace(WorkspaceTarget::Cache { local })),
122 "SYSTEM" => Ok(StepKind::Workspace(WorkspaceTarget::System)),
123 _ => Err(validation("WORKSPACE", "unknown workspace target")),
124 }
125 }
126 "INHERIT_ENV" => {
127 let keys = args.into_iter().map(|a| a.as_str().to_string()).collect();
128 Ok(StepKind::InheritEnv { keys })
129 }
130 "ECHO" => {
131 let msg = args
132 .into_iter()
133 .next()
134 .ok_or_else(|| validation("ECHO", "ECHO requires arg"))?;
135 Ok(StepKind::Echo(msg))
136 }
137 "RUN" => {
138 let cmd = args
139 .into_iter()
140 .next()
141 .ok_or_else(|| validation("RUN", "RUN requires arg"))?;
142 Ok(StepKind::Run(cmd))
143 }
144 "WORKDIR" => {
145 let path = args
146 .into_iter()
147 .next()
148 .ok_or_else(|| validation("WORKDIR", "requires path"))?;
149 Ok(StepKind::Workdir(path))
150 }
151 "COPY" => {
152 let mut from_host = false;
156 let mut to_host = false;
157 let mut positional = Vec::new();
158 for arg in args {
159 match arg.as_str() {
160 "--from-host" => from_host = true,
161 "--to-host" => to_host = true,
162 _ => positional.push(arg),
163 }
164 }
165 if from_host && to_host {
166 return Err(validation(
167 "COPY",
168 "COPY --from-host and --to-host are mutually exclusive",
169 ));
170 }
171 let mut it = positional.into_iter();
172 let from = it
173 .next()
174 .ok_or_else(|| validation("COPY", "COPY requires a source"))?;
175 let to = it
176 .next()
177 .ok_or_else(|| validation("COPY", "COPY requires a destination"))?;
178 Ok(StepKind::Copy {
179 from_workspace: None,
180 from_host,
181 to_host,
182 from,
183 to,
184 })
185 }
186 "ARCHIVE" => {
187 let raw = args.iter().any(|a| a.as_str() == "--raw");
188 let positional: Vec<_> =
189 args.into_iter().filter(|a| a.as_str() != "--raw").collect();
190 let mut it = positional.into_iter();
191 let src = it
192 .next()
193 .ok_or_else(|| validation("ARCHIVE", "ARCHIVE requires a source"))?;
194 let dst = it
195 .next()
196 .ok_or_else(|| validation("ARCHIVE", "ARCHIVE requires a destination"))?;
197 Ok(StepKind::Archive { src, dst, raw })
198 }
199 "UNARCHIVE" => {
200 let mut max_bytes = None;
201 let mut positional = Vec::new();
202 let mut iter = args.into_iter().peekable();
203 while let Some(arg) = iter.next() {
204 if arg.as_str() == "--max-bytes" {
205 max_bytes = iter.next();
206 } else {
207 positional.push(arg);
208 }
209 }
210 let mut it = positional.into_iter();
211 let src = it
212 .next()
213 .ok_or_else(|| validation("UNARCHIVE", "UNARCHIVE requires an archive"))?;
214 let dst = it
215 .next()
216 .ok_or_else(|| validation("UNARCHIVE", "UNARCHIVE requires a destination"))?;
217 Ok(StepKind::Unarchive {
218 src,
219 dst,
220 max_bytes,
221 })
222 }
223 _ => Err(ParseError::unknown_command(
224 name,
225 format!("unknown command: {name}"),
226 None,
227 &SpanContext::line_only(0),
228 )),
229 }
230 }
231}
232
233#[cfg(test)]
234mod tests {
235 use super::*;
236 use indoc::indoc;
237 #[cfg(feature = "proc-macro-api")]
238 use quote::quote;
239 use std::collections::HashMap;
240
241 fn test_lower(name: &str, args: Vec<Arg>) -> ParseResult<StepKind> {
243 crate::test_lower_mock::lower(name, args)
244 }
245
246 fn guard_text(step: &Step) -> Option<String> {
247 step.guard.as_ref().map(|g| g.to_string())
248 }
249
250 #[test]
251 fn commands_are_case_sensitive() {
252 for bad in ["echo hi", "Echo hi", "eCHO hi"] {
253 parse_script(bad, test_lower).expect_err("mixed/lowercase commands must fail");
254 }
255 }
256
257 #[test]
258 fn string_dsl_supports_rust_style_comments() {
259 let script = indoc! {r#"
260 // leading comment line
261 WRITE out.txt // inline comment
262 WRITE 'echo "keep // literal"'
263 /* block comment
264 WRITE ignored
265 /* nested inner */
266 WRITE ignored as well
267 */
268 WRITE "echo final"
269 WRITE "echo 'literal /* stay */ value'"
270 "#};
271 let steps = parse_script(script, test_lower).expect("parse ok");
272 assert_eq!(steps.len(), 4, "expected 4 executable steps");
273 assert!(matches!(&steps[0].kind, StepKind::Write { .. }));
274 assert!(matches!(&steps[1].kind, StepKind::Write { .. }));
275 assert!(matches!(&steps[2].kind, StepKind::Write { .. }));
276 assert!(matches!(&steps[3].kind, StepKind::Write { .. }));
277 }
278
279 #[test]
280 fn string_dsl_errors_on_unclosed_block_comment() {
281 let script = indoc! {r#"
282 WRITE echo hi
283 /* unclosed
284 "#};
285 parse_script(script, test_lower).expect_err("should fail");
286 }
287
288 #[test]
289 fn semicolon_splits_instructions() {
290 let script = "WRITE \"echo hi\"; WRITE \"echo bye\"";
291 let steps = parse_script(script, test_lower).expect("parse ok");
292 assert_eq!(steps.len(), 2);
293 }
294
295 #[test]
296 fn guard_supports_colon_separator() {
297 let script = "[env:FOO] WRITE \"echo hi\"";
298 let steps = parse_script(script, test_lower).expect("parse ok");
299 assert_eq!(steps.len(), 1);
300 assert_eq!(guard_text(&steps[0]).as_deref(), Some("env:FOO"));
301 }
302
303 #[test]
304 fn guard_lines_chain_before_block() {
305 let script = indoc! {r#"
306 [env:A]
307 [env:B]
308 {
309 WRITE ok.txt hi
310 }
311 "#};
312 let steps = parse_script(script, test_lower).expect("parse ok");
313 assert_eq!(steps.len(), 1);
314 assert_eq!(guard_text(&steps[0]).as_deref(), Some("env:A, env:B"));
315 }
316
317 #[test]
318 fn guard_block_must_contain_command() {
319 let script = indoc! {r#"
320 [env.A] {
321 }
322 "#};
323 parse_script(script, test_lower).expect_err("empty block should fail");
324 }
325
326 #[test]
327 fn with_io_rejects_non_variable_bindings() {
328 let err = parse_script(
331 "WITH_IO [stdin, stdout=pipe:setup, stderr=pipe:errors] WRITE \"echo hi\"",
332 test_lower,
333 )
334 .expect_err("non-variable bindings must fail");
335 let msg = err.to_string();
336 assert!(
337 msg.contains("pipe:setup"),
338 "error must name the bad binding: {msg}"
339 );
340 assert_eq!(err.line(), 1, "error must name the failing line");
341 }
342
343 #[test]
344 fn with_io_supports_variable_pipes() {
345 let script = "WITH_IO [stdout=$p, stdin=$q] WRITE \"echo hi\"";
346 let steps = parse_script(script, test_lower).expect("parse ok");
347 assert_eq!(steps.len(), 1);
348 match &steps[0].kind {
349 StepKind::WithIo { bindings, cmd } => {
350 assert_eq!(bindings.len(), 2);
351 assert!(bindings.iter().any(|b| matches!(b.stream, IoStream::Stdout)
352 && b.pipe
353 == Some(PipeTarget::Var {
354 name: "p".to_string(),
355 })));
356 assert!(bindings.iter().any(|b| matches!(b.stream, IoStream::Stdin)
357 && b.pipe
358 == Some(PipeTarget::Var {
359 name: "q".to_string(),
360 })));
361 assert!(matches!(cmd.as_ref(), StepKind::Write { .. }));
362 }
363 other => panic!("expected WITH_IO, saw {:?}", other),
364 }
365 assert_eq!(
367 steps[0].kind.to_string(),
368 "WITH_IO [stdout=$p, stdin=$q] WRITE \"echo hi\""
369 );
370 }
371
372 #[test]
373 fn colon_text_in_expression_fails() {
374 let err = parse_script("LET $p: PIPE = pipe:ch", test_lower)
377 .expect_err("colon text in expression must fail");
378 assert_eq!(err.line(), 1, "error must name the failing line");
379 }
380
381 #[test]
382 fn colon_text_in_assert_is_a_plain_value() {
383 let steps = parse_script("ASSERT_EQ pipe:ch \"x\"", crate::commands::lower_command)
388 .expect("colon text parses as a literal");
389 assert_eq!(steps.len(), 1);
390 match &steps[0].kind {
391 StepKind::AssertEq { actual, .. } => {
392 assert_eq!(
393 actual,
394 &AssertTarget::Value(Arg::String("pipe:ch".to_string(), false)),
395 "colon text must stay a literal value, got {actual:?}"
396 );
397 }
398 other => panic!("expected AssertEq, got {other:?}"),
399 }
400 }
401
402 #[test]
403 fn grouped_int_assert_operand_types_as_int() {
404 let steps = parse_script("ASSERT_EQ $x 1_000_000", crate::commands::lower_command)
407 .expect("grouped int parses");
408 match &steps[0].kind {
409 StepKind::AssertEq { expected, .. } => {
410 assert_eq!(
411 expected,
412 &Some(Arg::Expr(Expr::Literal(Value::int(1_000_000)))),
413 "grouped digits must type as Int, got {expected:?}"
414 );
415 }
416 other => panic!("expected AssertEq, got {other:?}"),
417 }
418 }
419
420 #[test]
421 fn bare_let_pipe_declares_fresh_backend() {
422 let steps = parse_script("LET $p: PIPE", test_lower).expect("bare LET $p: PIPE parses");
423 assert_eq!(steps.len(), 1);
424 match &steps[0].kind {
425 StepKind::Bind {
426 var,
427 decl_type,
428 rhs: BindRhs::Expr(expr),
429 ..
430 } => {
431 assert_eq!(var, "p");
432 assert_eq!(decl_type, "PIPE");
433 assert!(
434 matches!(expr, Expr::FreshPipe),
435 "expected FreshPipe, got {expr:?}"
436 );
437 }
438 other => panic!("expected Bind, got {other:?}"),
439 }
440 assert_eq!(steps[0].kind.to_string(), "LET $p: PIPE");
442 let again =
443 parse_script(&steps[0].kind.to_string(), test_lower).expect("Display round-trips");
444 assert_eq!(again, steps);
445 let err = parse_script("LET $x: STRING", test_lower).expect_err("bare STRING must fail");
447 assert!(
448 err.to_string().contains("requires an expression"),
449 "unexpected error: {err}"
450 );
451 }
452
453 #[test]
454 fn brace_blocks_require_guard() {
455 let script = indoc! {r#"
456 {
457 WRITE nope.txt hi
458 }
459 "#};
460 parse_script(script, test_lower).expect_err("unguarded block should fail");
461 }
462
463 #[test]
464 fn multi_line_guard_blocks_apply_to_next_command() {
465 let script = indoc! {r#"
466 [
467 env:A,
468 env:B
469 ]
470 WRITE "echo guarded"
471 "#};
472 let steps = parse_script(script, test_lower).expect("parse ok");
473 assert_eq!(steps.len(), 1);
474 assert_eq!(guard_text(&steps[0]).as_deref(), Some("env:A, env:B"));
475 }
476
477 #[test]
478 fn guarded_brace_blocks_apply_to_all_inner_steps() {
479 let script = indoc! {r#"
480 [env:A] {
481 WRITE one.txt 1
482 WRITE two.txt 2
483 }
484 "#};
485 let steps = parse_script(script, test_lower).expect("parse ok");
486 assert_eq!(steps.len(), 2);
487 assert!(steps.iter().all(|s| s.guard.is_some()));
488 }
489
490 #[test]
491 fn nested_guard_blocks_stack() {
492 let script = indoc! {r#"
493 [env:A] {
494 WRITE outer.txt no
495 [env:B] {
496 WRITE nested.txt yes
497 }
498 }
499 "#};
500 let steps = parse_script(script, test_lower).expect("parse ok");
501 assert_eq!(steps.len(), 2);
502 assert_eq!(guard_text(&steps[0]).as_deref(), Some("env:A"));
503 assert_eq!(guard_text(&steps[1]).as_deref(), Some("env:A, env:B"));
504 }
505
506 #[test]
507 fn nested_guard_block_scopes_stack_counts() {
508 let script = indoc! {r#"
509 [env:A] {
510 WRITE outer.txt ok
511 [env:B] {
512 WRITE deep.txt ok
513 }
514 WRITE outer_again.txt ok
515 }
516 "#};
517 let steps = parse_script(script, test_lower).expect("parse ok");
518 assert_eq!(steps.len(), 3);
519 assert_eq!(steps[0].scope_enter, 1);
520 assert_eq!(steps[0].scope_exit, 0);
521 assert_eq!(steps[1].scope_enter, 1);
522 assert_eq!(steps[1].scope_exit, 1);
523 assert_eq!(steps[2].scope_enter, 0);
524 assert_eq!(steps[2].scope_exit, 1);
525 }
526
527 #[test]
528 fn guard_or_and_and_combine_as_expected() {
529 let script = indoc! {r#"
530 [env:A]
531 [any(env:B, env:C)]
532 WRITE "echo complex"
533 "#};
534 let steps = parse_script(script, test_lower).expect("parse ok");
535 assert_eq!(steps.len(), 1);
536 let guard = steps[0].guard.as_ref().expect("missing guard");
537 assert_eq!(guard.to_string(), "env:A, any(env:B, env:C)");
538
539 let mut env = HashMap::new();
540 env.insert("A".into(), "1".into());
541 env.insert("B".into(), "1".into());
542 assert!(guard_expr_allows(guard, &env), "A && B should pass");
543
544 env.remove("B");
545 env.insert("C".into(), "1".into());
546 assert!(guard_expr_allows(guard, &env), "A && C should pass");
547
548 env.remove("C");
549 assert!(!guard_expr_allows(guard, &env), "A without B/C should fail");
550 }
551
552 #[test]
553 fn guard_or_requires_at_least_one_branch() {
554 let expr = GuardExpr::or(vec![
555 Guard::Attr {
556 ns: Ns::Env,
557 key: Some("MISSING".into()),
558 val: None,
559 }
560 .into(),
561 Guard::Attr {
562 ns: Ns::Env,
563 key: Some("ALSO_MISSING".into()),
564 val: None,
565 }
566 .into(),
567 ]);
568 assert!(!guard_expr_allows(&expr, &HashMap::new()));
569 let mut env = HashMap::new();
570 env.insert("MISSING".into(), "1".into());
571 assert!(guard_expr_allows(&expr, &env));
572 }
573
574 #[test]
575 fn guard_or_can_chain_with_additional_predicates() {
576 let script = "[any(env:A, os:linux), os:macos] WRITE \"echo hi\"";
577 let steps = parse_script(script, test_lower).expect("parse ok");
578 assert_eq!(steps.len(), 1);
579 let guard = steps[0].guard.as_ref().expect("missing guard");
580 assert_eq!(guard.to_string(), "any(env:A, os:linux), os:macos");
581 let GuardExpr::All(children) = guard else {
582 panic!("expected ALL guard");
583 };
584 assert!(matches!(children[0], GuardExpr::Or(_)));
585 match &children[1] {
586 GuardExpr::Predicate(Guard::Attr {
587 ns: Ns::Os,
588 key: None,
589 val: Some(value),
590 }) if value == "macos" => {}
591 other => panic!("unexpected trailing guard: {other:?}"),
592 }
593 }
594
595 #[test]
596 fn guard_or_guard_line_parses() {
597 parse_guard_expr_str("any(os:linux, env:FOO)").expect("guard line should parse");
598 }
599
600 #[test]
601 fn guard_bare_platform_word_fails_to_parse() {
602 let err = parse_script("[unix] WRITE \"echo hi\"", test_lower)
605 .expect_err("bare platform must fail");
606 let text = format!("{err:#}");
607 assert!(!text.contains("family:unix"), "{text}");
608 }
609
610 #[test]
611 fn env_equals_guard_with_not_wrapper() {
612 let g = GuardExpr::Not(Box::new(GuardExpr::Predicate(Guard::Attr {
613 ns: Ns::Env,
614 key: Some("A".into()),
615 val: Some("1".into()),
616 })));
617 let mut env = HashMap::new();
618 env.insert("A".into(), "1".into());
619 assert!(!guard_expr_allows(&g, &env));
620 env.insert("A".into(), "2".into());
621 assert!(guard_expr_allows(&g, &env));
622 }
623
624 #[test]
625 fn guard_block_emits_scope_markers() {
626 let script = indoc! {r#"
627 ENV RUN=1
628 [env:RUN] {
629 WRITE one.txt 1
630 WRITE two.txt 2
631 }
632 WRITE three.txt 3
633 "#};
634 let steps = parse_script(script, test_lower).expect("parse ok");
635 assert_eq!(steps.len(), 4);
636 assert_eq!(steps[1].scope_enter, 1);
637 assert_eq!(steps[1].scope_exit, 0);
638 assert_eq!(steps[2].scope_enter, 0);
639 assert_eq!(steps[2].scope_exit, 1);
640 assert_eq!(steps[3].scope_enter, 0);
641 assert_eq!(steps[3].scope_exit, 0);
642 }
643
644 #[test]
645 fn mock_hash_form_parses() {
646 let script = "ASSERT_EQ --hash aabb path.txt";
649 let steps = parse_script(script, crate::commands::lower_command).expect("parse ok");
650 match &steps[0].kind {
651 StepKind::AssertEq {
652 hash,
653 actual,
654 expected,
655 } => {
656 assert_eq!(hash.as_deref(), Some("aabb"));
657 assert_eq!(
658 actual,
659 &AssertTarget::Value(Arg::String("path.txt".to_string(), false))
660 );
661 assert_eq!(expected, &None);
662 }
663 other => panic!("expected AssertEq, saw {:?}", other),
664 }
665 }
666
667 #[test]
668 fn mock_commands_parse_and_round_trip() {
669 let script = indoc! {r#"
670 WRITE "dist/hello.txt" "Built with OxDock"
671 WRITE "deeply/nested/tree"
672 WRITE "chained.txt"
673 WRITE "visible-after-comments"
674 "#};
675 let steps = parse_script(script, test_lower).expect("parse ok");
676 assert_eq!(steps.len(), 4);
677
678 for step in &steps {
680 assert!(
681 matches!(&step.kind, StepKind::Write { .. }),
682 "expected Write variant"
683 );
684 }
685 }
686
687 #[test]
688 fn quoted_string_content_preserved() {
689 let script = "WRITE 'echo \"a; b\"'";
690 let steps = parse_script(script, test_lower).expect("parse ok");
691 match &steps[0].kind {
692 StepKind::Write { path, .. } => assert_eq!(path, "echo \"a; b\""),
693 other => panic!("expected Write, saw {:?}", other),
694 }
695 }
696
697 #[test]
698 fn block_string_dedents_to_closing_baseline() {
699 let script = indoc! {r#"
700 ECHO """
701 SELECT *
702 FROM users
703 """
704 "#};
705 let steps = parse_script(script, test_lower).expect("parse ok");
706 assert_eq!(steps.len(), 1);
707 match &steps[0].kind {
708 StepKind::Echo(arg) => assert_eq!(arg.as_str(), "SELECT *\nFROM users"),
709 other => panic!("expected Echo, saw {:?}", other),
710 }
711 }
712
713 #[test]
714 fn block_string_preserves_relative_indent_and_blank_lines() {
715 let script = indoc! {r#"
716 ECHO """
717 outer
718 inner
719
720 after-blank
721 """
722 "#};
723 let steps = parse_script(script, test_lower).expect("parse ok");
724 match &steps[0].kind {
725 StepKind::Echo(arg) => {
726 assert_eq!(arg.as_str(), "outer\n inner\n\nafter-blank");
727 }
728 other => panic!("expected Echo, saw {:?}", other),
729 }
730 }
731
732 #[test]
733 fn block_string_inline_opening_keeps_first_line() {
734 let script = indoc! {r#"
735 ECHO """hello
736 world
737 """
738 "#};
739 let steps = parse_script(script, test_lower).expect("parse ok");
740 match &steps[0].kind {
741 StepKind::Echo(arg) => assert_eq!(arg.as_str(), "hello\nworld"),
742 other => panic!("expected Echo, saw {:?}", other),
743 }
744 }
745
746 #[test]
747 fn block_string_allows_single_and_double_quotes() {
748 let script = indoc! {r#"
749 ECHO """
750 say "hi" and 'bye'
751 """
752 "#};
753 let steps = parse_script(script, test_lower).expect("parse ok");
754 match &steps[0].kind {
755 StepKind::Echo(arg) => assert_eq!(arg.as_str(), "say \"hi\" and 'bye'"),
756 other => panic!("expected Echo, saw {:?}", other),
757 }
758 }
759
760 #[test]
761 fn block_string_escape_defers_to_runtime_verbatim() {
762 let script = indoc! {r#"
763 ECHO """
764 escaped \"\"\" stays
765 """
766 "#};
767 let steps = parse_script(script, test_lower).expect("parse ok");
768 match &steps[0].kind {
769 StepKind::Echo(arg) => assert_eq!(arg.as_str(), "escaped \\\"\\\"\\\" stays"),
770 other => panic!("expected Echo, saw {:?}", other),
771 }
772 }
773
774 #[test]
775 fn block_string_keeps_templates_verbatim() {
776 let script = indoc! {r#"
777 ECHO """
778 hello {{ $name }}
779 """
780 "#};
781 let steps = parse_script(script, test_lower).expect("parse ok");
782 match &steps[0].kind {
783 StepKind::Echo(arg) => assert_eq!(arg.as_str(), "hello {{ $name }}"),
784 other => panic!("expected Echo, saw {:?}", other),
785 }
786 }
787
788 #[test]
789 fn block_string_empty_yields_empty() {
790 for script in ["ECHO \"\"\"\"\"\"", "ECHO \"\"\"\n\"\"\""] {
791 let steps = parse_script(script, test_lower).expect("parse ok");
792 match &steps[0].kind {
793 StepKind::Echo(arg) => assert_eq!(arg.as_str(), ""),
794 other => panic!("expected Echo, saw {:?}", other),
795 }
796 }
797 }
798
799 #[test]
800 fn block_string_crlf_normalizes_to_lf() {
801 let script = "ECHO \"\"\"\r\n line one\r\n line two\r\n \"\"\"";
802 let steps = parse_script(script, test_lower).expect("parse ok");
803 match &steps[0].kind {
804 StepKind::Echo(arg) => assert_eq!(arg.as_str(), "line one\nline two"),
805 other => panic!("expected Echo, saw {:?}", other),
806 }
807 }
808
809 #[test]
810 fn block_string_unterminated_fails_at_opening_line() {
811 let script = "ECHO ok\nECHO \"\"\"\n stranded\n";
812 let err = parse_script(script, test_lower).expect_err("unterminated must fail");
813 let text = format!("{err:#}");
814 assert!(text.contains("line 2"), "{text}");
815 }
816
817 #[test]
818 fn block_string_next_step_keeps_line_number() {
819 let script = indoc! {r#"
820 ECHO """
821 multi
822 line
823 """
824 ECHO after
825 "#};
826 let steps = parse_script(script, test_lower).expect("parse ok");
827 assert_eq!(steps.len(), 2);
828 match &steps[1].kind {
829 StepKind::Echo(arg) => assert_eq!(arg.as_str(), "after"),
830 other => panic!("expected Echo, saw {:?}", other),
831 }
832 }
833
834 #[test]
835 fn block_string_in_let_list_map_and_call() {
836 let script = indoc! {r#"
837 LET $text: STRING = """
838 hello
839 """
840 LET $items: LIST = ["""
841 one
842 """, "two"]
843 LET $entry: MAP = {key: """
844 value
845 """}
846 "#};
847 let steps = parse_script(script, test_lower).expect("parse ok");
848 assert_eq!(steps.len(), 3);
849 match &steps[0].kind {
850 StepKind::Bind {
851 var,
852 rhs: BindRhs::Expr(expr),
853 ..
854 } => {
855 assert_eq!(var, "text");
856 assert_eq!(expr, &Expr::Literal(Value::string("hello".to_string())));
857 }
858 other => panic!("expected Bind, got {:?}", other),
859 }
860 match &steps[1].kind {
861 StepKind::Bind {
862 var,
863 rhs: BindRhs::Expr(expr),
864 ..
865 } => {
866 assert_eq!(var, "items");
867 assert_eq!(
868 expr,
869 &Expr::List(vec![
870 Expr::Literal(Value::string("one".to_string())),
871 Expr::Literal(Value::string("two".to_string())),
872 ])
873 );
874 }
875 other => panic!("expected Bind, got {:?}", other),
876 }
877 match &steps[2].kind {
878 StepKind::Bind {
879 var,
880 rhs: BindRhs::Expr(expr),
881 ..
882 } => {
883 assert_eq!(var, "entry");
884 assert_eq!(
885 expr,
886 &Expr::Map(vec![(
887 "key".to_string(),
888 Expr::Literal(Value::string("value".to_string()))
889 )])
890 );
891 }
892 other => panic!("expected Bind, got {:?}", other),
893 }
894 }
895
896 #[test]
897 fn block_string_in_assignment_value() {
898 let script = indoc! {r#"
899 ENV GREETING="""
900 hi there
901 """
902 "#};
903 let steps = parse_script(script, test_lower).expect("parse ok");
904 assert_eq!(steps.len(), 1);
905 match &steps[0].kind {
906 StepKind::Env { key, value } => {
907 assert_eq!(key, "GREETING");
908 assert_eq!(value.as_str(), "hi there");
909 }
910 other => panic!("expected Env, got {:?}", other),
911 }
912 }
913
914 #[test]
915 fn block_map_key_dedents() {
916 let steps = parse_script("LET $m: MAP = {\"\"\"\nkey\n\"\"\": \"v\"}", test_lower)
917 .expect("parse ok");
918 match &steps[0].kind {
919 StepKind::Bind {
920 rhs: oxdock_parser::BindRhs::Expr(expr),
921 ..
922 } => {
923 assert_eq!(
924 expr,
925 &Expr::Map(vec![(
926 "key".to_string(),
927 Expr::Literal(Value::string("v".to_string()))
928 )])
929 );
930 }
931 other => panic!("expected Bind, got {:?}", other),
932 }
933 }
934
935 #[test]
936 fn block_guard_value_dedents() {
937 let steps =
938 parse_script("[eq(env:K, \"\"\"\nv\n\"\"\")] WRITE x", test_lower).expect("parse ok");
939 match &steps[0].guard {
940 Some(GuardExpr::Predicate(Guard::Attr { val, .. })) => {
941 assert_eq!(val.as_deref(), Some("v"));
942 }
943 other => panic!("expected env guard, got {:?}", other),
944 }
945 }
946
947 #[test]
948 fn block_escaped_opener_stays_literal() {
949 let script = indoc! {r#"
950 ECHO """
951 \{{ $x }} stays
952 """
953 "#};
954 let steps = parse_script(script, test_lower).expect("parse ok");
955 match &steps[0].kind {
956 StepKind::Echo(arg) => assert_eq!(arg.as_str(), "\\{{ $x }} stays"),
957 other => panic!("expected Echo, saw {:?}", other),
958 }
959 }
960
961 #[test]
962 fn with_io_block_form_consumes_node() {
963 let steps =
967 parse_script("WITH_IO [stdout=$p] {\n ECHO hi\n}", test_lower).expect("parse ok");
968 assert_eq!(steps.len(), 1);
969 assert!(
970 !matches!(steps[0].kind, StepKind::WithIoBlock { .. }),
971 "transient node leaked: {:?}",
972 steps[0].kind
973 );
974 }
975
976 #[test]
977 fn assignment_key_allows_colons() {
978 let steps = parse_script("ENV a:b=c", test_lower).expect("parse ok");
979 match &steps[0].kind {
980 StepKind::Env { key, value } => {
981 assert_eq!(key, "a:b");
982 assert_eq!(value.as_str(), "c");
983 }
984 other => panic!("expected Env, got {:?}", other),
985 }
986 }
987
988 #[test]
989 fn block_string_display_round_trips() {
990 let script = indoc! {r#"
991 ECHO """
992 SELECT *
993 FROM users
994 """
995 "#};
996 let steps = parse_script(script, test_lower).expect("parse ok");
997 let rendered = steps[0].to_string();
998 assert!(rendered.contains("\"\"\""), "{rendered}");
999 let reparsed = parse_script(&rendered, test_lower).expect("reparse ok");
1000 assert_eq!(steps, reparsed);
1001 }
1002
1003 #[test]
1004 fn templated_argument_with_spaces() {
1005 let script = "WRITE {{ env:OXBOOK_RUNNER_DIR }}";
1006 let steps = parse_script(script, test_lower).expect("parse ok");
1007 assert_eq!(steps.len(), 1);
1008 match &steps[0].kind {
1009 StepKind::Write { path, .. } => assert_eq!(path, "{{ env:OXBOOK_RUNNER_DIR }}"),
1010 other => panic!("expected Write, saw {:?}", other),
1011 }
1012 }
1013
1014 #[test]
1015 #[cfg(feature = "proc-macro-api")]
1016 fn string_and_braced_scripts_produce_identical_ast() {
1017 let mut cases = Vec::new();
1018
1019 cases.push((
1020 indoc! {r#"
1021 WRITE /tmp
1022 WRITE hello
1023 "#}
1024 .trim()
1025 .to_string(),
1026 quote! {
1027 WRITE /tmp
1028 WRITE hello
1029 },
1030 ));
1031
1032 cases.push((
1033 indoc! {r#"
1034 [not(env:SKIP)]
1035 [family:windows] WRITE win
1036 [eq(env:MODE, beta), os:linux] WRITE combo
1037 "#}
1038 .trim()
1039 .to_string(),
1040 quote! {
1041 [not(env:SKIP)]
1042 [family:windows] WRITE win
1043 [eq(env:MODE, beta), os:linux] WRITE combo
1044 },
1045 ));
1046
1047 cases.push((
1048 indoc! {r#"
1049 [env:OUTER] {
1050 WRITE nested
1051 [env:INNER] WRITE deep
1052 }
1053 "#}
1054 .trim()
1055 .to_string(),
1056 quote! {
1057 [env:OUTER] {
1058 WRITE nested
1059 [env:INNER] WRITE deep
1060 }
1061 },
1062 ));
1063
1064 cases.push((
1065 indoc! {r#"
1066 [eq(env:TEST, 1)]
1067 WITH_IO [stdout=$capture_case] WRITE hi
1068 WITH_IO [stdin=$capture_case] WRITE out.txt
1069 "#}
1070 .trim()
1071 .to_string(),
1072 quote! {
1073 [eq(env:TEST, 1)]
1074 WITH_IO [stdout=$capture_case] WRITE hi
1075 WITH_IO [stdin=$capture_case] WRITE out.txt
1076 },
1077 ));
1078
1079 for (idx, (literal, tokens)) in cases.iter().enumerate() {
1080 let text = literal.trim();
1081 let string_steps = parse_script(text, test_lower)
1082 .unwrap_or_else(|e| panic!("string parse failed for case {idx}: {e}"));
1083 let braced_steps = parse_braced_tokens(tokens, test_lower)
1084 .unwrap_or_else(|e| panic!("token parse failed for case {idx}: {e}"));
1085 assert_eq!(
1086 string_steps, braced_steps,
1087 "AST mismatch for case {idx} literal:\n{text}"
1088 );
1089 }
1090 }
1091
1092 #[test]
1093 fn let_assign_with_bare_word() {
1094 let script = r#"LET $x: STRING = hello"#;
1095 let steps = parse_script(script, test_lower).expect("parse ok");
1096 assert_eq!(steps.len(), 1);
1097 match &steps[0].kind {
1098 StepKind::Bind {
1099 var,
1100 rhs: BindRhs::Expr(expr),
1101 ..
1102 } => {
1103 assert_eq!(var, "x");
1104 assert_eq!(expr, &Expr::Literal(Value::string("hello".to_string())));
1105 }
1106 other => panic!("expected Bind, got {:?}", other),
1107 }
1108 }
1109
1110 #[test]
1111 fn let_assign_grouped_int_literal() {
1112 let steps =
1113 parse_script("LET $x: INT = 1_000_000", test_lower).expect("grouped int parses");
1114 match &steps[0].kind {
1115 StepKind::Bind {
1116 rhs: oxdock_parser::BindRhs::Expr(expr),
1117 ..
1118 } => {
1119 assert_eq!(expr, &Expr::Literal(Value::int(1_000_000)));
1120 }
1121 other => panic!("expected Bind, got {other:?}"),
1122 }
1123 let steps =
1125 parse_script("LET $f: FLOAT = 1_024.768", test_lower).expect("grouped float parses");
1126 match &steps[0].kind {
1127 StepKind::Bind {
1128 rhs: oxdock_parser::BindRhs::Expr(expr),
1129 ..
1130 } => {
1131 assert_eq!(expr, &Expr::Literal(Value::float(1024.768)));
1132 }
1133 other => panic!("expected Bind, got {other:?}"),
1134 }
1135 let steps = parse_script("ECHO 1__0", test_lower).expect("parses as text");
1138 match &steps[0].kind {
1139 StepKind::Echo(arg) => assert_eq!(arg.as_str(), "1__0"),
1140 other => panic!("expected Echo, got {other:?}"),
1141 }
1142 }
1143
1144 #[test]
1145 fn grouped_numeric_boundaries() {
1146 for (spelling, expected) in [
1150 ("0", Value::int(0)),
1151 ("1_000", Value::int(1_000)),
1152 ("1_000_000", Value::int(1_000_000)),
1153 ("9_223_372_036_854_775_807", Value::int(i64::MAX)),
1154 ("1_024.768", Value::float(1024.768)),
1155 ("0.5", Value::float(0.5)),
1156 ] {
1157 let script = format!("LET $x: ANY = {spelling}");
1158 let steps = parse_script(&script, test_lower).expect("parses");
1159 match &steps[0].kind {
1160 StepKind::Bind {
1161 rhs: oxdock_parser::BindRhs::Expr(expr),
1162 ..
1163 } => {
1164 assert_eq!(expr, &Expr::Literal(expected.clone()), "{spelling:?}");
1165 }
1166 other => panic!("expected Bind, got {other:?}"),
1167 }
1168 let plain = spelling.replace('_', "");
1170 let script = format!("LET $x: ANY = {plain}");
1171 let again = parse_script(&script, test_lower).expect("parses");
1172 assert_eq!(again, steps, "{spelling:?} must stage like {plain:?}");
1173 }
1174 for spelling in ["9_223_372_036_854_775_808", "9223372036854775808"] {
1178 let err = parse_script(&format!("LET $x: ANY = {spelling}"), test_lower)
1179 .expect_err("boundary outside negation must fail");
1180 assert!(err.to_string().contains("exceeds i64::MAX"), "{err}");
1181 }
1182 let steps = parse_script("LET $x: INT = -9_223_372_036_854_775_808", test_lower)
1183 .expect("negated boundary parses");
1184 match &steps[0].kind {
1185 StepKind::Bind {
1186 rhs: oxdock_parser::BindRhs::Expr(expr),
1187 ..
1188 } => {
1189 assert_eq!(expr, &Expr::Literal(Value::int(i64::MIN)));
1190 }
1191 other => panic!("expected Bind, got {other:?}"),
1192 }
1193 let err = parse_script("LET $x: ANY = 9_223_372_036_854_775_809", test_lower)
1194 .expect_err("overflow must fail");
1195 assert!(err.to_string().contains("exceeds i64::MAX"), "{err}");
1196 }
1197
1198 #[test]
1199 fn let_assign_with_quoted_string() {
1200 let script = r#"LET $x: STRING = "hello world""#;
1201 let steps = parse_script(script, test_lower).expect("parse ok");
1202 assert_eq!(steps.len(), 1);
1203 match &steps[0].kind {
1204 StepKind::Bind {
1205 var,
1206 rhs: BindRhs::Expr(expr),
1207 ..
1208 } => {
1209 assert_eq!(var, "x");
1210 assert_eq!(
1211 expr,
1212 &Expr::Literal(Value::string("hello world".to_string()))
1213 );
1214 }
1215 other => panic!("expected Bind, got {:?}", other),
1216 }
1217 }
1218
1219 #[test]
1220 fn let_assign_with_list_literal() {
1221 let script = r#"LET $x: LIST = ["a", "b", "c"]"#;
1222 let steps = parse_script(script, test_lower).expect("parse ok");
1223 assert_eq!(steps.len(), 1);
1224 match &steps[0].kind {
1225 StepKind::Bind {
1226 var,
1227 rhs: BindRhs::Expr(expr),
1228 ..
1229 } => {
1230 assert_eq!(var, "x");
1231 assert_eq!(
1232 expr,
1233 &Expr::List(vec![
1234 Expr::Literal(Value::string("a".to_string())),
1235 Expr::Literal(Value::string("b".to_string())),
1236 Expr::Literal(Value::string("c".to_string()))
1237 ])
1238 );
1239 }
1240 other => panic!("expected Bind, got {:?}", other),
1241 }
1242 }
1243
1244 #[test]
1245 fn let_assign_with_variable_ref() {
1246 let script = r#"LET $x: STRING = $y"#;
1247 let steps = parse_script(script, test_lower).expect("parse ok");
1248 assert_eq!(steps.len(), 1);
1249 match &steps[0].kind {
1250 StepKind::Bind {
1251 var,
1252 rhs: BindRhs::Expr(expr),
1253 ..
1254 } => {
1255 assert_eq!(var, "x");
1256 assert_eq!(
1257 expr,
1258 &Expr::Var {
1259 name: "y".to_string(),
1260 }
1261 );
1262 }
1263 other => panic!("expected Bind, got {:?}", other),
1264 }
1265 }
1266
1267 #[test]
1268 fn let_assign_with_block() {
1269 let script = r#"LET $a: STRING = { RETURN "hello" }"#;
1270 let steps = parse_script(script, test_lower).expect("parse ok");
1271 assert_eq!(steps.len(), 1);
1272 match &steps[0].kind {
1273 StepKind::Bind {
1274 var,
1275 rhs: BindRhs::Expr(expr),
1276 ..
1277 } => {
1278 assert_eq!(var, "a");
1279 match expr {
1280 Expr::Block(body) => {
1281 assert_eq!(body.len(), 1);
1282 assert!(matches!(body[0].kind, StepKind::Return { .. }));
1283 }
1284 other => panic!("expected Block, got {:?}", other),
1285 }
1286 }
1287 other => panic!("expected Bind, got {:?}", other),
1288 }
1289 }
1290
1291 #[test]
1292 fn let_assign_multiline_block_with_nesting() {
1293 let script = indoc! {r#"
1294 LET $a: STRING = {
1295 LET $b: STRING = { RETURN "hi" }
1296 RETURN $b
1297 }
1298 "#};
1299 let steps = parse_script(script, test_lower).expect("parse ok");
1300 assert_eq!(steps.len(), 1);
1301 match &steps[0].kind {
1302 StepKind::Bind {
1303 rhs: oxdock_parser::BindRhs::Expr(expr),
1304 ..
1305 } => match expr {
1306 Expr::Block(body) => {
1307 assert_eq!(body.len(), 2);
1308 assert!(matches!(body[0].kind, StepKind::Bind { .. }));
1309 assert!(matches!(body[1].kind, StepKind::Return { .. }));
1310 let StepKind::Bind {
1311 rhs: BindRhs::Expr(inner),
1312 ..
1313 } = &body[0].kind
1314 else {
1315 panic!("expected inner Bind");
1316 };
1317 assert!(matches!(inner, Expr::Block(_)));
1318 }
1319 other => panic!("expected Block, got {:?}", other),
1320 },
1321 other => panic!("expected Bind, got {:?}", other),
1322 }
1323 }
1324
1325 #[test]
1326 fn let_assign_map_literal_stays_map() {
1327 let script = r#"LET $m: MAP = {a: 1, b: 2}"#;
1328 let steps = parse_script(script, test_lower).expect("parse ok");
1329 match &steps[0].kind {
1330 StepKind::Bind {
1331 rhs: oxdock_parser::BindRhs::Expr(expr),
1332 ..
1333 } => {
1334 assert!(matches!(expr, Expr::Map(entries) if entries.len() == 2));
1335 }
1336 other => panic!("expected Bind, got {:?}", other),
1337 }
1338 }
1339
1340 #[test]
1341 fn map_literal_spans_lines_with_comments() {
1342 let script = indoc! {r#"
1343 LET $m: MAP = {
1344 // leading comment
1345 "a": 1, /* trailing */
1346 // own line
1347 b: 2
1348 }
1349 "#};
1350 let steps = parse_script(script, test_lower).expect("parse ok");
1351 match &steps[0].kind {
1352 StepKind::Bind {
1353 rhs: oxdock_parser::BindRhs::Expr(expr),
1354 ..
1355 } => match expr {
1356 Expr::Map(entries) => {
1357 assert_eq!(entries.len(), 2);
1358 assert_eq!(entries[0].0, "a");
1359 assert_eq!(entries[1].0, "b");
1360 }
1361 other => panic!("expected Map, got {:?}", other),
1362 },
1363 other => panic!("expected Bind, got {:?}", other),
1364 }
1365 }
1366
1367 #[test]
1368 fn call_args_accept_comments_between_lines() {
1369 let script = indoc! {r#"
1370 FUNC SERVE($h: STRING, $u: STRING, $p: STRING, $o: MAP): STRING {
1371 RETURN $h
1372 }
1373 LET $s: STRING = SERVE(
1374 // host port
1375 "127.0.0.1:2251",
1376 "test",
1377 "test123", {
1378 // workspace-relative key
1379 key_path: "/temp/test_key"
1380 }
1381 )
1382 "#};
1383 let steps = parse_script(script, test_lower).expect("parse ok");
1384 assert_eq!(steps.len(), 2);
1385 match &steps[1].kind {
1386 StepKind::Bind {
1387 rhs: oxdock_parser::BindRhs::Expr(expr),
1388 ..
1389 } => match expr {
1390 Expr::Call { name, args } => {
1391 assert_eq!(name, "SCRIPT::SERVE");
1392 assert_eq!(args.len(), 4);
1393 assert!(matches!(&args[3], Expr::Map(entries) if entries.len() == 1));
1394 }
1395 other => panic!("expected Call, got {:?}", other),
1396 },
1397 other => panic!("expected Bind, got {:?}", other),
1398 }
1399 }
1400
1401 #[test]
1402 fn hash_comments_trail_map_entries() {
1403 let script = indoc! {r#"
1404 # 1. Ephemeral server setup
1405 LET $m: MAP = {
1406 key_path: "temp/test_key" # Fixed: Relative workspace pathing
1407 }
1408 "#};
1409 let steps = parse_script(script, test_lower).expect("parse ok");
1410 match &steps[0].kind {
1411 StepKind::Bind {
1412 rhs: oxdock_parser::BindRhs::Expr(expr),
1413 ..
1414 } => match expr {
1415 Expr::Map(entries) => {
1416 assert_eq!(entries.len(), 1);
1417 assert_eq!(entries[0].0, "key_path");
1418 }
1419 other => panic!("expected Map, got {:?}", other),
1420 },
1421 other => panic!("expected Bind, got {:?}", other),
1422 }
1423 }
1424
1425 #[test]
1426 fn hash_comments_span_call_args_like_slash_comments() {
1427 let script = indoc! {r#"
1428 FUNC SERVE($h: STRING, $o: MAP): STRING {
1429 RETURN $h
1430 }
1431 # leading hash comment
1432 LET $s: STRING = SERVE(
1433 # host port
1434 "127.0.0.1:2251", {
1435 # workspace-relative key
1436 key_path: "temp/test_key" # trailing hash comment
1437 }
1438 )
1439 "#};
1440 let steps = parse_script(script, test_lower).expect("parse ok");
1441 assert_eq!(steps.len(), 2);
1442 match &steps[1].kind {
1443 StepKind::Bind {
1444 rhs: oxdock_parser::BindRhs::Expr(expr),
1445 ..
1446 } => match expr {
1447 Expr::Call { name, args } => {
1448 assert_eq!(name, "SCRIPT::SERVE");
1449 assert_eq!(args.len(), 2);
1450 assert!(matches!(&args[1], Expr::Map(entries) if entries.len() == 1));
1451 }
1452 other => panic!("expected Call, got {:?}", other),
1453 },
1454 other => panic!("expected Bind, got {:?}", other),
1455 }
1456 }
1457
1458 #[test]
1459 fn for_loop_parses() {
1460 let script = indoc! {r#"
1461 FOR $f: STRING IN ["x", "y"] {
1462 WRITE $f
1463 }
1464 "#};
1465 let steps = parse_script(script, test_lower).expect("parse ok");
1466 assert_eq!(steps.len(), 1);
1467 match &steps[0].kind {
1468 StepKind::For {
1469 key_var,
1470 var,
1471 in_expr,
1472 body,
1473 ..
1474 } => {
1475 assert!(key_var.is_none());
1476 assert_eq!(var, "f");
1477 assert_eq!(
1478 in_expr,
1479 &Expr::List(vec![
1480 Expr::Literal(Value::string("x".to_string())),
1481 Expr::Literal(Value::string("y".to_string()))
1482 ])
1483 );
1484 assert_eq!(body.len(), 1);
1485 }
1486 other => panic!("expected For, got {:?}", other),
1487 }
1488 }
1489
1490 #[test]
1491 fn for_map_iteration_parses() {
1492 let script = indoc! {r#"
1493 FOR $k: STRING, $v: STRING IN $map {
1494 WRITE $k
1495 }
1496 "#};
1497 let steps = parse_script(script, test_lower).expect("parse ok");
1498 assert_eq!(steps.len(), 1);
1499 match &steps[0].kind {
1500 StepKind::For {
1501 key_var,
1502 var,
1503 in_expr,
1504 body,
1505 ..
1506 } => {
1507 assert_eq!(key_var.as_deref(), Some("k"));
1508 assert_eq!(var, "v");
1509 assert_eq!(
1510 in_expr,
1511 &Expr::Var {
1512 name: "map".to_string(),
1513 }
1514 );
1515 assert_eq!(body.len(), 1);
1516 }
1517 other => panic!("expected For, got {:?}", other),
1518 }
1519 }
1520
1521 #[test]
1522 fn if_statement_parses() {
1523 let script = "IF true { WRITE yes }\n";
1524 let steps = parse_script(script, test_lower).expect("parse ok");
1525 assert_eq!(steps.len(), 1);
1526 match &steps[0].kind {
1527 StepKind::If { .. } => {}
1528 other => panic!("expected If, got {:?}", other),
1529 }
1530 }
1531
1532 #[test]
1533 fn if_head_parses_through_backend() {
1534 let steps = parse_script("IF true {\n WRITE yes\n}", test_lower).expect("IF parses");
1535 assert_eq!(steps.len(), 1);
1536 assert!(
1537 matches!(steps[0].kind, StepKind::If { .. }),
1538 "expected If, got {:?}",
1539 steps[0].kind
1540 );
1541 }
1542
1543 #[test]
1544 fn not_expression_parses() {
1545 let script = r#"LET $x: BOOL = !true"#;
1546 let steps = parse_script(script, test_lower).expect("parse ok");
1547 match &steps[0].kind {
1548 StepKind::Bind {
1549 var,
1550 rhs: BindRhs::Expr(expr),
1551 ..
1552 } => {
1553 assert_eq!(var, "x");
1554 assert_eq!(expr, &Expr::Not(Box::new(Expr::Literal(Value::bool(true)))));
1555 }
1556 other => panic!("expected Bind, got {:?}", other),
1557 }
1558
1559 let steps = parse_script(r#"LET $x: BOOL = !!false"#, test_lower).expect("parse ok");
1561 match &steps[0].kind {
1562 StepKind::Bind {
1563 rhs: oxdock_parser::BindRhs::Expr(expr),
1564 ..
1565 } => {
1566 assert_eq!(
1567 expr,
1568 &Expr::Not(Box::new(Expr::Not(Box::new(Expr::Literal(Value::bool(
1569 false
1570 ))))))
1571 );
1572 }
1573 other => panic!("expected Bind, got {:?}", other),
1574 }
1575
1576 let steps = parse_script(r#"LET $x: BOOL = !true == false"#, test_lower).expect("parse ok");
1578 match &steps[0].kind {
1579 StepKind::Bind {
1580 rhs: oxdock_parser::BindRhs::Expr(expr),
1581 ..
1582 } => {
1583 assert!(matches!(expr, Expr::Compare { .. }), "got {expr:?}");
1584 if let Expr::Compare { left, .. } = expr {
1585 assert!(matches!(left.as_ref(), Expr::Not(_)), "got {left:?}");
1586 }
1587 }
1588 other => panic!("expected Bind, got {:?}", other),
1589 }
1590
1591 let steps =
1593 parse_script(r#"LET $x: BOOL = !(true == false)"#, test_lower).expect("parse ok");
1594 match &steps[0].kind {
1595 StepKind::Bind {
1596 rhs: oxdock_parser::BindRhs::Expr(expr),
1597 ..
1598 } => {
1599 assert!(matches!(expr, Expr::Not(_)), "got {expr:?}");
1600 }
1601 other => panic!("expected Bind, got {:?}", other),
1602 }
1603 }
1604
1605 #[test]
1606 fn not_expression_display_round_trips() {
1607 for script in [
1608 "LET $x: BOOL = !true",
1609 "LET $x: BOOL = !!false",
1610 "LET $x: BOOL = !(true == false)",
1611 "IF !true {\n WRITE yes\n}",
1612 ] {
1613 let steps = parse_script(script, test_lower).expect("parse");
1614 let rendered: Vec<String> = steps.iter().map(|s| s.to_string()).collect();
1615 let reparsed = parse_script(&rendered.join("\n"), test_lower).expect("reparse");
1616 assert_eq!(steps, reparsed, "Display round-trip failed for {script}");
1617 }
1618 }
1619
1620 #[test]
1621 fn guard_block_with_mock_command() {
1622 let script = "WRITE probe.txt\n[env:GATE] {\n WRITE gated\n}\n[eq(env:A, 1)] WRITE eq\n";
1623 let steps = parse_script(script, test_lower).expect("parse should succeed");
1624 assert!(
1625 steps.len() >= 2,
1626 "expected at least 2 steps, got {}",
1627 steps.len()
1628 );
1629 }
1630
1631 #[test]
1632 fn single_line_blocks() {
1633 let test_cases = [
1634 "IF true { WRITE \"hello\" }",
1635 "IF true { WRITE \"cargo test\" }",
1636 "IF true { WRITE \"/app\" }",
1637 ];
1638 for script in test_cases {
1639 assert!(
1640 parse_script(script, test_lower).is_ok(),
1641 "Failed to parse: {}",
1642 script
1643 );
1644 }
1645 }
1646
1647 #[test]
1648 fn async_run_parses() {
1649 let script = "ASYNC RUN \"echo hello\"";
1650 let steps = parse_script(script, test_lower).expect("parse should succeed");
1651 assert_eq!(steps.len(), 1);
1652 assert!(matches!(&steps[0].kind, StepKind::AsyncBlock { .. }));
1653 }
1654
1655 #[test]
1656 fn async_block_parses() {
1657 let script = indoc! {r#"
1658 ASYNC {
1659 RUN "echo one"
1660 RUN "echo two"
1661 }
1662 "#};
1663 let steps = parse_script(script, test_lower).expect("parse should succeed");
1664 assert_eq!(steps.len(), 1);
1665 match &steps[0].kind {
1666 StepKind::AsyncBlock { body } => {
1667 assert_eq!(body.len(), 2);
1668 }
1669 other => panic!("expected AsyncBlock, got {:?}", other),
1670 }
1671 }
1672
1673 #[test]
1674 fn nested_async_parses() {
1675 let script = "ASYNC ASYNC RUN \"echo nested\"";
1676 let steps = parse_script(script, test_lower).expect("parse should succeed");
1677 assert_eq!(steps.len(), 1);
1678 match &steps[0].kind {
1679 StepKind::AsyncBlock { body } => {
1680 assert_eq!(body.len(), 1);
1681 match &body[0].kind {
1682 StepKind::AsyncBlock { body } => {
1683 assert_eq!(body.len(), 1);
1684 assert!(matches!(&body[0].kind, StepKind::Run(_)));
1685 }
1686 other => panic!("expected inner AsyncBlock, got {:?}", other),
1687 }
1688 }
1689 other => panic!("expected outer AsyncBlock, got {:?}", other),
1690 }
1691 }
1692
1693 #[test]
1694 fn nested_async_block_form_parses() {
1695 let script = indoc! {r#"
1696 ASYNC {
1697 ASYNC {
1698 RUN "echo nested"
1699 }
1700 }
1701 "#};
1702 let steps = parse_script(script, test_lower).expect("parse should succeed");
1703 assert_eq!(steps.len(), 1);
1704 match &steps[0].kind {
1705 StepKind::AsyncBlock { body } => {
1706 assert_eq!(body.len(), 1);
1707 match &body[0].kind {
1708 StepKind::AsyncBlock { body } => {
1709 assert_eq!(body.len(), 1);
1710 assert!(matches!(&body[0].kind, StepKind::Run(_)));
1711 }
1712 other => panic!("expected inner AsyncBlock, got {:?}", other),
1713 }
1714 }
1715 other => panic!("expected outer AsyncBlock, got {:?}", other),
1716 }
1717 }
1718
1719 #[test]
1720 fn with_io_wrapping_async_parses() {
1721 let script = "WITH_IO [stdout] ASYNC RUN \"echo test\"";
1722 let steps = parse_script(script, test_lower).expect("parse should succeed");
1723 assert_eq!(steps.len(), 1);
1724 match &steps[0].kind {
1725 StepKind::WithIo { cmd, .. } => {
1726 assert!(matches!(cmd.as_ref(), StepKind::AsyncBlock { .. }));
1727 }
1728 other => panic!("expected WithIo, got {:?}", other),
1729 }
1730 }
1731
1732 #[test]
1733 fn with_io_async_block_nested_for_parses() {
1734 let script = indoc! {r#"
1738 WITH_IO [stdout=$out] ASYNC {
1739 FOR $x: INT IN [0, 1] {
1740 ECHO hi
1741 }
1742 }
1743 "#};
1744 let steps = parse_script(script, test_lower).expect("parse should succeed");
1745 assert_eq!(steps.len(), 1);
1746 match &steps[0].kind {
1747 StepKind::WithIo { bindings, cmd } => {
1748 assert_eq!(bindings.len(), 1);
1749 assert!(matches!(bindings[0].stream, IoStream::Stdout));
1750 assert_eq!(
1751 bindings[0].pipe,
1752 Some(PipeTarget::Var {
1753 name: "out".to_string(),
1754 })
1755 );
1756 match cmd.as_ref() {
1757 StepKind::AsyncBlock { body } => {
1758 assert_eq!(body.len(), 1);
1759 match &body[0].kind {
1760 StepKind::For { var, body, .. } => {
1761 assert_eq!(var, "x");
1762 assert_eq!(body.len(), 1);
1763 assert!(matches!(&body[0].kind, StepKind::Echo(_)));
1764 }
1765 other => panic!("expected For, got {:?}", other),
1766 }
1767 }
1768 other => panic!("expected AsyncBlock, got {:?}", other),
1769 }
1770 }
1771 other => panic!("expected WithIo, got {:?}", other),
1772 }
1773 }
1774
1775 #[test]
1776 fn for_int_key_parses_for_list_enumeration() {
1777 let script = indoc! {r#"
1778 FOR $i: INT, $v: STRING IN $items {
1779 WRITE $v
1780 }
1781 "#};
1782 let steps = parse_script(script, test_lower).expect("parse ok");
1783 match &steps[0].kind {
1784 StepKind::For {
1785 key_var,
1786 key_type,
1787 var,
1788 var_type,
1789 ..
1790 } => {
1791 assert_eq!(key_var.as_deref(), Some("i"));
1792 assert_eq!(*key_type, Some("INT".to_string()));
1793 assert_eq!(var, "v");
1794 assert_eq!(*var_type, "STRING".to_string());
1795 }
1796 other => panic!("expected For, got {:?}", other),
1797 }
1798 }
1799
1800 #[test]
1801 fn for_non_index_key_type_is_rejected() {
1802 let err = parse_script(
1803 "FOR $k: BOOL, $v: STRING IN $map { WRITE $v }\n",
1804 test_lower,
1805 )
1806 .expect_err("BOOL key must fail");
1807 assert!(
1808 err.to_string().contains("must be INT or STRING"),
1809 "unexpected error: {err}"
1810 );
1811 }
1812
1813 #[test]
1814 fn with_io_async_block_nested_if_else_parses() {
1815 let script = indoc! {r#"
1817 WITH_IO [stdout=$out] ASYNC {
1818 IF $a == $b {
1819 ECHO yes
1820 } ELSE {
1821 ECHO no
1822 }
1823 }
1824 "#};
1825 let steps = parse_script(script, test_lower).expect("parse should succeed");
1826 match &steps[0].kind {
1827 StepKind::WithIo { cmd, .. } => match cmd.as_ref() {
1828 StepKind::AsyncBlock { body } => {
1829 assert!(matches!(&body[0].kind, StepKind::If { .. }));
1830 match &body[0].kind {
1831 StepKind::If { else_body, .. } => {
1832 assert_eq!(else_body.as_ref().map(Vec::len), Some(1));
1833 }
1834 other => panic!("expected If, got {:?}", other),
1835 }
1836 }
1837 other => panic!("expected AsyncBlock, got {:?}", other),
1838 },
1839 other => panic!("expected WithIo, got {:?}", other),
1840 }
1841 }
1842
1843 #[test]
1844 fn timeout_block_nested_for_parses() {
1845 let script = indoc! {r#"
1848 TIMEOUT 30s {
1849 FOR $x: INT IN [1] {
1850 ECHO hi
1851 }
1852 }
1853 "#};
1854 let steps = parse_script(script, test_lower).expect("parse should succeed");
1855 match &steps[0].kind {
1856 StepKind::Timeout { body, .. } => {
1857 assert_eq!(body.len(), 1);
1858 assert!(matches!(&body[0].kind, StepKind::For { .. }));
1859 }
1860 other => panic!("expected Timeout, got {:?}", other),
1861 }
1862 }
1863
1864 #[test]
1865 fn isolated_block_rewrites_nested_allowlist() {
1866 let script = indoc! {r#"
1870 ISOLATED {
1871 INHERIT_ENV [KEEP]
1872 IF true {
1873 INHERIT_ENV [ALSO]
1874 }
1875 ISOLATED {
1876 INHERIT_ENV [DEEP]
1877 }
1878 }
1879 "#};
1880 let steps = parse_script(script, test_lower).expect("parse should succeed");
1881 match &steps[0].kind {
1882 StepKind::Isolated { body } => {
1883 assert!(
1884 matches!(&body[0].kind, StepKind::IsolatedInheritEnv { .. }),
1885 "direct allowlist rewrites, got {:?}",
1886 body[0].kind
1887 );
1888 match &body[1].kind {
1889 StepKind::If { then_body, .. } => assert!(
1890 matches!(&then_body[0].kind, StepKind::IsolatedInheritEnv { .. }),
1891 "allowlist inside nested IF rewrites, got {:?}",
1892 then_body[0].kind
1893 ),
1894 other => panic!("expected If, got {:?}", other),
1895 }
1896 match &body[2].kind {
1897 StepKind::Isolated { body: inner } => assert!(
1898 matches!(&inner[0].kind, StepKind::IsolatedInheritEnv { .. }),
1899 "allowlist inside nested ISOLATED rewrites, got {:?}",
1900 inner[0].kind
1901 ),
1902 other => panic!("expected Isolated, got {:?}", other),
1903 }
1904 }
1905 other => panic!("expected Isolated, got {:?}", other),
1906 }
1907 }
1908
1909 #[test]
1910 fn isolated_single_command_form_parses() {
1911 let script = indoc! {r#"
1914 ISOLATED RUN echo hi
1915 "#};
1916 let steps = parse_script(script, test_lower).expect("parse should succeed");
1917 match &steps[0].kind {
1918 StepKind::Isolated { body } => {
1919 assert_eq!(body.len(), 1);
1920 assert!(matches!(&body[0].kind, StepKind::Run(_)));
1921 }
1922 other => panic!("expected Isolated, got {:?}", other),
1923 }
1924 }
1925
1926 #[test]
1927 fn isolated_func_body_inherit_still_rejected() {
1928 let script = indoc! {r#"
1933 ISOLATED {
1934 FUNC F(): VOID {
1935 INHERIT_ENV [NOPE]
1936 }
1937 }
1938 "#};
1939 let err = parse_script(script, test_lower).expect_err("FUNC-nested allowlist must fail");
1940 assert!(
1941 err.to_string().contains("nested"),
1942 "unexpected error: {err}"
1943 );
1944 }
1945
1946 #[test]
1947 fn with_io_async_block_nested_let_map_parses() {
1948 let script = indoc! {r#"
1950 WITH_IO [stdout] ASYNC {
1951 LET $m: MAP = {a: 1, b: 2}
1952 }
1953 "#};
1954 let steps = parse_script(script, test_lower).expect("parse should succeed");
1955 match &steps[0].kind {
1956 StepKind::WithIo { cmd, .. } => match cmd.as_ref() {
1957 StepKind::AsyncBlock { body } => {
1958 assert!(matches!(&body[0].kind, StepKind::Bind { .. }));
1959 }
1960 other => panic!("expected AsyncBlock, got {:?}", other),
1961 },
1962 other => panic!("expected WithIo, got {:?}", other),
1963 }
1964 }
1965
1966 #[test]
1967 fn variable_sigil_binds_tightly() {
1968 parse_script("ECHO $ x", test_lower).expect_err("spaced sigil must fail");
1974 parse_script("LET $x: STRING = $ y", test_lower).expect_err("spaced sigil must fail");
1975 let steps = parse_script("ECHO $x", test_lower).expect("tight sigil parses");
1976 assert!(matches!(&steps[0].kind, StepKind::Echo(_)));
1977 }
1978
1979 #[test]
1980 fn let_async_block_parses() {
1981 let script = indoc! {r#"
1982 LET $task: HANDLE = ASYNC {
1983 RUN "echo hello"
1984 }
1985 "#};
1986 let steps = parse_script(script, test_lower).expect("parse should succeed");
1987 assert_eq!(steps.len(), 1);
1988 match &steps[0].kind {
1989 StepKind::Bind {
1990 var,
1991 rhs: BindRhs::Async(body),
1992 ..
1993 } => {
1994 assert_eq!(var, "task");
1995 assert_eq!(body.len(), 1);
1996 assert!(matches!(&body[0].kind, StepKind::Run(_)));
1997 }
1998 other => panic!("expected Bind Async, got {:?}", other),
1999 }
2000 }
2001
2002 #[test]
2003 fn let_async_inline_parses() {
2004 let script = "LET $t: HANDLE = ASYNC RUN \"echo hi\"";
2005 let steps = parse_script(script, test_lower).expect("parse should succeed");
2006 assert_eq!(steps.len(), 1);
2007 match &steps[0].kind {
2008 StepKind::Bind {
2009 var,
2010 rhs: BindRhs::Async(body),
2011 ..
2012 } => {
2013 assert_eq!(var, "t");
2014 assert_eq!(body.len(), 1);
2015 assert!(matches!(&body[0].kind, StepKind::Run(_)));
2016 }
2017 other => panic!("expected Bind Async, got {:?}", other),
2018 }
2019 }
2020
2021 #[test]
2022 fn await_parses() {
2023 let script = "AWAIT $task";
2024 let steps = parse_script(script, test_lower).expect("parse should succeed");
2025 assert_eq!(steps.len(), 1);
2026 match &steps[0].kind {
2027 StepKind::Await { var, .. } => {
2028 assert_eq!(var, "task");
2029 }
2030 other => panic!("expected Await, got {:?}", other),
2031 }
2032 }
2033}