Skip to main content

oxdock_parser/
lib.rs

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