1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! Helpers that let proc-macro inputs reuse the regular string parser.
//!
//! The macros ultimately want everything to flow through `parse_script`, since
//! that code already does the heavy lifting of guard handling, scope tracking,
//! and AST construction. Unfortunately `TokenStream` values do not retain
//! whitespace or “line” structure, so we first have to rebuild a textual DSL
//! representation that the parser understands. The `sticky`/`needs_space`
//! helpers below exist solely to recreate enough spacing for commands such as
//! `ENV FOO=bar` or `RUN echo && ls` to look exactly like the string DSL,
//! keeping both pathways unified.
use super::{Command, Step, parse_script};
use anyhow::Result;
use proc_macro2::{Delimiter, LineColumn, Spacing, TokenStream as TokenStream2, TokenTree};
use syn::parse::{Parse, ParseStream};
use syn::{Ident, LitStr, Token};
/// Parsed macro arguments for `oxdock_embed!` and `oxdock_prepare!`.
pub struct DslMacroInput {
pub name: Ident,
pub script: ScriptSource,
pub out_dir: LitStr,
}
/// The script payload, either as a literal string or a braced token stream.
pub enum ScriptSource {
Literal(LitStr),
Braced(TokenStream2),
}
impl Parse for DslMacroInput {
fn parse(input: ParseStream) -> syn::Result<Self> {
let name_label: Ident = input.parse()?;
if name_label != "name" {
return Err(syn::Error::new(name_label.span(), "expected `name` label"));
}
input.parse::<Token![:]>()?;
let name: Ident = input.parse()?;
let _ = input.parse::<Token![,]>().ok();
let script_label: Ident = input.parse()?;
if script_label != "script" {
return Err(syn::Error::new(
script_label.span(),
"expected `script` label",
));
}
input.parse::<Token![:]>()?;
let script = if input.peek(LitStr) {
let s: LitStr = input.parse()?;
ScriptSource::Literal(s)
} else if input.peek(syn::token::Brace) {
let content;
syn::braced!(content in input);
let ts: TokenStream2 = content.parse()?;
ScriptSource::Braced(ts)
} else {
return Err(syn::Error::new(
input.span(),
"expected string literal or braced script block",
));
};
let _ = input.parse::<Token![,]>().ok();
let out_dir_label: Ident = input.parse()?;
if out_dir_label != "out_dir" {
return Err(syn::Error::new(
out_dir_label.span(),
"expected `out_dir` label",
));
}
input.parse::<Token![:]>()?;
let out_dir: LitStr = input.parse()?;
let _ = input.parse::<Token![,]>().ok();
Ok(Self {
name,
script,
out_dir,
})
}
}
fn finalize_line(lines: &mut Vec<String>, line: &mut String, capture_has_inner: &mut bool) {
let trimmed = line.trim();
if !trimmed.is_empty() {
lines.push(trimmed.to_string());
}
line.clear();
*capture_has_inner = false;
}
fn sticky(c: char) -> bool {
matches!(c, '/' | '.' | '-' | ':' | '=' | '$' | '{' | '}')
}
fn needs_space(prev: char, next: char) -> bool {
if next == ';' {
return false;
}
if prev.is_whitespace() || next.is_whitespace() {
return false;
}
if sticky(prev) || sticky(next) {
return false;
}
if (prev == '&' && next == '&') || (prev == '|' && next == '|') {
return false;
}
true
}
fn push_fragment(buf: &mut String, frag: &str, force_space: bool) {
if frag.is_empty() {
return;
}
let next_char = frag.chars().next().unwrap_or(' ');
if let Some(prev) = buf.chars().rev().find(|c| !c.is_whitespace())
&& ((force_space && !prev.is_whitespace()) || needs_space(prev, next_char))
{
buf.push(' ');
}
buf.push_str(frag);
}
fn span_gap_requires_space(prev: LineColumn, next: LineColumn) -> bool {
prev.line == next.line && next.column > prev.column
}
fn delim_pair(delim: Delimiter) -> Option<(char, char)> {
match delim {
Delimiter::Parenthesis => Some(('(', ')')),
Delimiter::Brace => Some(('{', '}')),
Delimiter::Bracket => Some(('[', ']')),
Delimiter::None => None,
}
}
fn current_line_command(line: &str) -> Option<Command> {
let trimmed = line.trim_start();
let head = trimmed.split_whitespace().next()?;
Command::parse(head)
}
/// Check if a brace group is a `{{ ... }}` template placeholder.
/// Rust lexes `{{ env:KEY }}` as a brace group containing a single nested brace group.
fn is_template_group(g: &proc_macro2::Group) -> bool {
let mut inner_tokens = g.stream().into_iter();
matches!(
inner_tokens.next(),
Some(TokenTree::Group(inner))
if inner.delimiter() == Delimiter::Brace && inner_tokens.next().is_none()
)
}
/// Emit a `{{ ... }}` template placeholder on the current line,
/// reconstructing interior spacing from span positions.
fn emit_template_placeholder(
g: &proc_macro2::Group,
line: &mut String,
span: proc_macro2::Span,
gap_space: bool,
last_span_end: &mut Option<LineColumn>,
) {
let Some(TokenTree::Group(inner)) = g.stream().into_iter().next() else {
unreachable!("is_template_group checked above")
};
push_fragment(line, "{{", gap_space);
let mut inner_tokens = inner.stream().into_iter();
let leading_space = inner_tokens
.next()
.map(|tt| {
let start = tt.span().start();
start.line == span.start().line && start.column > span.start().column + 2
})
.unwrap_or(false);
if leading_space {
line.push(' ');
}
let mut inner_span_end = None;
let mut last_was_command = false;
let mut capture_has_inner = false;
walk(
inner.stream(),
line,
&mut Vec::new(),
&mut last_was_command,
false,
&mut capture_has_inner,
&mut inner_span_end,
)
.ok();
let trailing_space = inner_span_end
.map(|end| span.end().line == end.line && span.end().column > end.column + 2)
.unwrap_or(false);
let close_text = if trailing_space { " }}" } else { "}}" };
push_fragment(line, close_text, false);
*last_span_end = Some(span.end());
}
fn line_expects_inner_command(line: &str) -> bool {
matches!(
current_line_command(line),
Some(cmd) if cmd.expects_inner_command()
)
}
fn line_is_run_context(line: &str) -> bool {
matches!(current_line_command(line), Some(Command::Run))
}
fn walk(
ts: TokenStream2,
line: &mut String,
lines: &mut Vec<String>,
last_was_command: &mut bool,
in_interpolation: bool,
capture_has_inner: &mut bool,
last_span_end: &mut Option<LineColumn>,
) -> Result<()> {
let tokens: Vec<TokenTree> = ts.into_iter().collect();
let mut idx = 0;
while idx < tokens.len() {
let tt = tokens[idx].clone();
let next = tokens.get(idx + 1);
let span = tt.span();
let gap_space = last_span_end
.map(|prev| span_gap_requires_space(prev, span.start()))
.unwrap_or(false);
// A RUN step consumes the rest of its source line as shell text
// (`RUN echo && ls` stays one step), but any token opening on a later
// line starts a new statement: without this, `RUN echo hi` followed by
// `WRITE x` — or by a punctuation-led statement like `$count = 1` —
// would glue into a single shell command. Punctuation must participate
// too: `$`/`#` would otherwise advance `last_span_end` and blind the
// check for the tokens that follow them on the same line.
if last_span_end.is_some_and(|prev| span.start().line > prev.line)
&& !line.trim().is_empty()
&& line_is_run_context(line.trim())
{
finalize_line(lines, line, capture_has_inner);
}
match tt {
TokenTree::Group(g) => {
if let Some((open, close)) = delim_pair(g.delimiter()) {
match g.delimiter() {
Delimiter::Brace => {
let trimmed = line.trim_end();
// 1. Interpolation context: ${var} or #{expr}
// Keep the entire expression on one line.
if trimmed.ends_with('$') || trimmed.ends_with('#') {
push_fragment(line, &open.to_string(), false);
*last_was_command = false;
let mut inner_span_end = None;
walk(
g.stream(),
line,
lines,
last_was_command,
true,
capture_has_inner,
&mut inner_span_end,
)?;
push_fragment(line, &close.to_string(), false);
}
// 2. Template placeholder: {{ env:KEY }}
// Rust lexes this as nested brace groups.
else if is_template_group(&g) {
emit_template_placeholder(&g, line, span, gap_space, last_span_end);
}
// 3. DSL statement block: WITH_IO [...] {, FOR ..., LET ...
// Attach opening brace to the current line, then walk body.
else if !trimmed.is_empty() {
push_fragment(line, &open.to_string(), gap_space);
finalize_line(lines, line, capture_has_inner);
*last_was_command = false;
let mut inner_span_end = None;
walk(
g.stream(),
line,
lines,
last_was_command,
false,
capture_has_inner,
&mut inner_span_end,
)?;
finalize_line(lines, line, capture_has_inner);
push_fragment(line, &close.to_string(), false);
finalize_line(lines, line, capture_has_inner);
}
// 4. Standalone / top-level block
else {
finalize_line(lines, line, capture_has_inner);
line.push(open);
finalize_line(lines, line, capture_has_inner);
*last_was_command = false;
let mut inner_span_end = None;
walk(
g.stream(),
line,
lines,
last_was_command,
false,
capture_has_inner,
&mut inner_span_end,
)?;
finalize_line(lines, line, capture_has_inner);
line.push(close);
finalize_line(lines, line, capture_has_inner);
*last_was_command = false;
}
}
Delimiter::Bracket => {
// A `[` group continues the current statement when it
// reads as an expression: argv/bindings right after a
// command (`RUN [...]`, `WITH_IO [...]`), or a list
// literal after `=`, `IN`, `(`, `[`, `,`. Otherwise
// it starts a guard on a new line. This is purely
// syntactic so it also holds for synthetic spans
// (e.g. `quote!`), where line numbers carry no signal.
let trimmed_here = line.trim_end();
let continues_expr = trimmed_here.ends_with('=')
|| trimmed_here.ends_with(':')
|| trimmed_here.ends_with('(')
|| trimmed_here.ends_with('[')
|| trimmed_here.ends_with(',')
|| trimmed_here.split_whitespace().last() == Some("IN");
if *last_was_command || continues_expr {
// First bracket group after a command: attach to the command
// (e.g., INHERIT_ENV [keys], WITH_IO [bindings]).
// Same-line groups elsewhere attach as expressions.
push_fragment(line, &open.to_string(), gap_space);
let mut inner_span_end = None;
walk(
g.stream(),
line,
lines,
last_was_command,
false,
capture_has_inner,
&mut inner_span_end,
)?;
push_fragment(line, &close.to_string(), false);
// Reset so the next bracket group (if any) is recognized as a guard.
*last_was_command = false;
} else {
// Guard bracket (e.g., [#flag], [env:KEY])
// or second bracket group after a command.
// Finalize previous line and start guard on a new line.
finalize_line(lines, line, capture_has_inner);
push_fragment(line, &open.to_string(), gap_space);
finalize_line(lines, line, capture_has_inner);
let mut inner_span_end = None;
walk(
g.stream(),
line,
lines,
last_was_command,
false,
capture_has_inner,
&mut inner_span_end,
)?;
finalize_line(lines, line, capture_has_inner);
push_fragment(line, &close.to_string(), false);
finalize_line(lines, line, capture_has_inner);
}
}
_ => {
push_fragment(line, &open.to_string(), *last_was_command || gap_space);
*last_was_command = false;
let mut inner_span_end = None;
walk(
g.stream(),
line,
lines,
last_was_command,
in_interpolation,
capture_has_inner,
&mut inner_span_end,
)?;
push_fragment(line, &close.to_string(), *last_was_command);
}
}
} else {
let mut inner_span_end = None;
walk(
g.stream(),
line,
lines,
last_was_command,
in_interpolation,
capture_has_inner,
&mut inner_span_end,
)?;
}
*last_span_end = Some(span.end());
}
TokenTree::Literal(lit) => {
push_fragment(line, &lit.to_string(), *last_was_command || gap_space);
*last_was_command = false;
*last_span_end = Some(span.end());
}
TokenTree::Punct(p) => {
let ch = p.as_char();
let mut force_space = gap_space || (*last_was_command && ch != ';');
if ch == '-'
&& p.spacing() == Spacing::Alone
&& line_is_run_context(line)
&& matches!(next, Some(TokenTree::Ident(_) | TokenTree::Literal(_)))
&& let Some(prev) = line.chars().rev().find(|c| !c.is_whitespace())
&& (prev.is_ascii_alphanumeric() || matches!(prev, ')' | ']' | '"' | '\''))
{
force_space = true;
}
push_fragment(line, &ch.to_string(), force_space);
*last_was_command = false;
*last_span_end = Some(span.end());
if ch == ';' {
finalize_line(lines, line, capture_has_inner);
}
}
TokenTree::Ident(ident) => {
let ident_text = ident.to_string();
if in_interpolation {
push_fragment(line, &ident_text, false);
*last_was_command = false;
idx += 1;
continue;
}
// A RUN step consumes the rest of its source line as shell
// text, but an ident opening on a later line starts a new
// statement: the hoisted check at the top of the loop already
// finalized the RUN line, so statement detection below sees a
// fresh line.
let is_command = super::Command::parse(&ident_text).is_some();
// LET and FOR introduce new statements but aren't in the Command enum.
// They must still trigger line finalization so they start on a new line.
// The same holds for the other structural statements parsed by PEG
// rules rather than plain-command lowering (AWAIT, CANCEL, FUNC,
// CALL, RETURN, WHILE, BREAK, CONTINUE): without this, `FUNC`
// after `MKDIR dist` would glue onto the same line.
let is_new_statement = is_command
|| matches!(
ident_text.as_str(),
"LET"
| "FOR"
| "IF"
| "ELSE"
| "ASYNC"
| "AWAIT"
| "CANCEL"
| "FUNC"
| "CALL"
| "RETURN"
| "WHILE"
| "BREAK"
| "CONTINUE"
);
let trimmed = line.trim();
let trimmed_empty = trimmed.is_empty();
let guard_prefix = trimmed.starts_with('[');
let line_requires_inner = line_expects_inner_command(trimmed);
// A line ending in `=` (or the `IN` of a FOR header) expects an
// expression next: `LET $o: STRING = ECHO hi`,
// `LET $r: STRING = CALL F()`,
// `LET $t: HANDLE = ASYNC ...`, `FOR $x: STRING IN [...]`.
// A statement keyword there continues the line instead of
// starting a new one.
let trimmed_end = trimmed.trim_end();
let expects_expr = trimmed_end.ends_with('=')
|| trimmed_end.split_whitespace().last() == Some("IN");
let mut should_finalize = false;
// ELSE always appends to current line — grammar handles } \n ELSE via blank*
// IF after ELSE stays on same line (ELSE IF clause)
if ident_text == "ELSE" || (ident_text == "IF" && trimmed.ends_with("ELSE")) {
should_finalize = false;
} else if is_new_statement && !trimmed_empty && !guard_prefix && !expects_expr {
let current_expects_inner = line_expects_inner_command(trimmed);
should_finalize = !line_is_run_context(trimmed) && !current_expects_inner;
}
if is_command
&& !trimmed_empty
&& !guard_prefix
&& *capture_has_inner
&& line_requires_inner
&& ident_text != "ASYNC"
{
finalize_line(lines, line, capture_has_inner);
}
if should_finalize {
finalize_line(lines, line, capture_has_inner);
}
push_fragment(line, &ident_text, *last_was_command || gap_space);
if is_command
&& line_expects_inner_command(line)
&& !matches!(
Command::parse(&ident_text),
Some(cmd) if cmd.expects_inner_command()
)
{
*capture_has_inner = true;
}
*last_was_command = is_new_statement;
*last_span_end = Some(span.end());
}
}
idx += 1;
}
Ok(())
}
/// Convert a braced Rust token stream into textual DSL lines.
pub fn script_from_braced_tokens(ts: &TokenStream2) -> Result<String> {
let mut lines = Vec::new();
let mut current = String::new();
let mut last_was_command = false;
let mut capture_has_inner = false;
let mut last_span_end = None;
walk(
ts.clone(),
&mut current,
&mut lines,
&mut last_was_command,
false,
&mut capture_has_inner,
&mut last_span_end,
)?;
finalize_line(&mut lines, &mut current, &mut capture_has_inner);
Ok(lines.join("\n"))
}
/// Parse a braced token stream directly into DSL steps.
/// Requires a lowering function — callers must provide it.
pub fn parse_braced_tokens(
ts: &TokenStream2,
lower: impl Fn(&str, Vec<crate::Arg>) -> anyhow::Result<crate::StepKind>,
) -> Result<Vec<Step>> {
let script = script_from_braced_tokens(ts)?;
parse_script(&script, lower)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::StepKind;
use indoc::indoc;
use quote::quote;
/// Mock lowering for macro_input tests.
fn mock_lower(name: &str, args: Vec<crate::Arg>) -> anyhow::Result<StepKind> {
crate::test_lower_mock::lower(name, args)
}
#[test]
fn parse_dsl_macro_input_literal_script() {
let input: DslMacroInput =
syn::parse_str("name: foo, script: \"RUN echo hi\", out_dir: \"target/out\"")
.expect("parse literal script");
assert!(matches!(input.script, ScriptSource::Literal(_)));
assert_eq!(input.name.to_string(), "foo");
assert_eq!(input.out_dir.value(), "target/out");
}
#[test]
fn parse_dsl_macro_input_braced_script() {
let input: DslMacroInput =
syn::parse_str("name: foo, script: { RUN echo hi }, out_dir: \"out\"")
.expect("parse braced script");
assert!(matches!(input.script, ScriptSource::Braced(_)));
}
#[test]
fn braced_script_preserves_dot_path_spacing() {
// Parsed from real text so span-column gaps drive spacing decisions,
// exactly like the historical proc-macro input pathway.
let ts: proc_macro2::TokenStream = "SYMLINK ./client ./client".parse().expect("tokens");
let script = script_from_braced_tokens(&ts).expect("render braced script");
assert!(
script.contains("SYMLINK ./client ./client"),
"expected dot paths separated, got: {script}"
);
}
#[test]
fn braced_script_splits_semicolon_commands() {
let ts = quote! { RUN echo; LS; RUN echo && ls };
let script = script_from_braced_tokens(&ts).expect("render braced script");
assert!(script.lines().count() >= 3, "got: {script}");
}
#[test]
fn braced_script_with_guard_block_parses() {
let ts = quote! {
[env:TEST_SCOPE] {
WRITE inner.txt inside
}
};
let steps = parse_braced_tokens(&ts, mock_lower).expect("parse guarded block");
assert_eq!(steps.len(), 1);
}
#[test]
fn braced_script_preserves_template_placeholders() {
// `{{ env:X }}` nests as brace-within-brace in the token stream; the
// normalizer must re-emit it verbatim instead of exploding it across
// lines.
let ts: proc_macro2::TokenStream = "WRITE dist/hello.txt Built with {{ env:PROJECT }}"
.parse()
.expect("tokens");
let script = script_from_braced_tokens(&ts).expect("render braced script");
assert_eq!(
script, "WRITE dist/hello.txt Built with {{ env:PROJECT }}",
"template placeholder must round-trip"
);
let steps = parse_braced_tokens(&ts, mock_lower).expect("parse templated script");
match &steps[0].kind {
StepKind::Write { path, contents } => {
assert_eq!(path.as_ref(), "dist/hello.txt");
assert_eq!(
contents.as_ref().map(AsRef::as_ref),
Some("Built with {{ env:PROJECT }}")
);
}
other => panic!("expected WRITE, saw {:?}", other),
}
}
#[test]
fn braced_and_string_forms_agree_on_templates() {
let text = indoc! {r#"
ENV GREETING=hello
ECHO <{{ env:GREETING }}>
"#}
.trim();
let ts: proc_macro2::TokenStream = text.parse().expect("tokens");
let braced = parse_braced_tokens(&ts, mock_lower).expect("braced parse");
let string = parse_script(text, mock_lower).expect("string parse");
assert_eq!(braced, string, "template AST parity between forms");
}
#[test]
fn braced_template_spacing_round_trips_both_variants() {
for source in [
"WRITE f.txt Built with {{ env:P }}",
"WRITE f.txt Built with {{env:P}}",
] {
let ts: proc_macro2::TokenStream = source.parse().expect("tokens");
let script = script_from_braced_tokens(&ts)
.unwrap_or_else(|e| panic!("render failed for {source}: {e}"));
assert_eq!(script, source, "spacing must round-trip verbatim");
let steps = parse_braced_tokens(&ts, mock_lower).expect("parse");
match &steps[0].kind {
StepKind::Write { path, contents } => {
assert_eq!(path.as_ref(), "f.txt", "path must match for {source}");
assert_eq!(
contents.as_ref().map(AsRef::as_ref),
Some(source.strip_prefix("WRITE f.txt ").expect("prefix")),
"AST interior must match source for {source}"
);
}
other => panic!("expected WRITE, saw {:?}", other),
}
}
}
#[test]
fn braced_structural_statements_start_new_lines() {
// FUNC, CALL, WHILE (and friends) are parsed by PEG rules rather than
// plain-command lowering, so the token walker must still recognize them
// as statement starters instead of gluing them onto the previous line.
let ts: proc_macro2::TokenStream = indoc! {r#"
WRITE a.txt hi
FUNC GREET($name: STRING) {
RETURN $name
}
CALL GREET("ada")
WHILE $flag {
BREAK
}
"#}
.parse()
.expect("tokens");
let steps = parse_braced_tokens(&ts, mock_lower).expect("structural statements parse");
assert_eq!(steps.len(), 4, "got: {steps:?}");
assert!(matches!(steps[0].kind, StepKind::Write { .. }));
assert!(matches!(steps[1].kind, StepKind::FuncDef { .. }));
assert!(matches!(steps[2].kind, StepKind::Call { .. }));
assert!(matches!(steps[3].kind, StepKind::While { .. }));
}
#[test]
fn braced_expression_continuations_stay_on_one_line() {
// A statement keyword after `=` or `IN` continues the line: LET-capture
// (`= ECHO ...`, `= CALL ...`) and list literals (`= [...]`,
// `IN [...]`) must not split.
let ts: proc_macro2::TokenStream = indoc! {r#"
LET $names: LIST = ["alpha", "beta"]
FOR $n: STRING IN ["alpha", "beta"] {
WRITE out.txt hi
}
LET $echo: STRING = ECHO hi
"#}
.parse()
.expect("tokens");
let steps = parse_braced_tokens(&ts, mock_lower).expect("continuations parse");
assert_eq!(steps.len(), 3, "got: {steps:?}");
assert!(matches!(steps[0].kind, StepKind::Assign { .. }));
assert!(matches!(steps[1].kind, StepKind::For { .. }));
assert!(matches!(steps[2].kind, StepKind::AssignCapture { .. }));
}
#[test]
fn braced_map_literal_with_list_value_parses() {
// A list literal after a map entry colon (`{ key: [...] }`) is an
// expression fragment, not a guard: it must not split onto a new line.
let ts: proc_macro2::TokenStream = indoc! {r#"
LET $m: MAP = {"key": ["a", "b"]}
"#}
.parse()
.expect("tokens");
let steps = parse_braced_tokens(&ts, mock_lower).expect("map literal parses");
assert_eq!(steps.len(), 1, "got: {steps:?}");
assert!(matches!(steps[0].kind, StepKind::Assign { .. }));
}
#[test]
fn braced_run_ends_at_source_line_break() {
// Shell text stays on one step (`RUN echo && ls`), but a step opening
// on a later source line must not glue onto the RUN command.
let ts: proc_macro2::TokenStream = indoc! {r#"
RUN echo hi
WRITE out.txt hi
RUN echo again
"#}
.parse()
.expect("tokens");
let steps = parse_braced_tokens(&ts, mock_lower).expect("run lines parse");
assert_eq!(steps.len(), 3, "got: {steps:?}");
}
#[test]
fn braced_run_followed_by_mutation_or_interpolation_ends_line() {
// Punctuation-led statements (`$count = 1`, `#cmd`) open with `$`/`#`,
// not an Ident: the RUN line break must fire for any token type, or the
// `$` would merely advance the span cursor and blind the check for the
// tokens that follow it on the same line. (`#cmd` is a DSL comment, so
// only the RUN and the mutation survive as steps.)
let ts: proc_macro2::TokenStream = indoc! {r#"
RUN echo hi
$count = 1
#cmd
"#}
.parse()
.expect("tokens");
let steps = parse_braced_tokens(&ts, mock_lower).expect("post-RUN lines parse");
assert_eq!(steps.len(), 2, "got: {steps:?}");
assert!(matches!(steps[0].kind, StepKind::Run(_)));
assert!(matches!(steps[1].kind, StepKind::Set { .. }));
}
#[test]
fn braced_guards_still_start_new_lines() {
// A `[` group on a fresh line is a guard, even though same-line
// brackets attach as expressions.
let ts: proc_macro2::TokenStream = indoc! {r#"
WRITE a.txt hi
[bool:true] WRITE b.txt yo
"#}
.parse()
.expect("tokens");
let steps = parse_braced_tokens(&ts, mock_lower).expect("guarded lines parse");
assert_eq!(steps.len(), 2, "got: {steps:?}");
assert!(matches!(steps[0].kind, StepKind::Write { .. }));
assert!(matches!(steps[1].kind, StepKind::Write { .. }));
}
}