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