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