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