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