oxdock-parser 0.44.1-alpha

Parser and AST definitions for the OxDock DSL.
Documentation
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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
//! 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::constants::{
    KEYWORD_ASYNC, KEYWORD_ELSE, KEYWORD_IF, KEYWORD_IN, KEYWORD_ISOLATED, KEYWORD_TIMEOUT,
    KEYWORD_WITH_IO, MODULE_SEPARATOR,
};
use super::{Command, Step};
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> {
        // Fields accept any order so call sites can lead with the
        // staging directory ahead of a long script block. Each field
        // must appear exactly once.
        let mut name: Option<Ident> = None;
        let mut script: Option<ScriptSource> = None;
        let mut out_dir: Option<LitStr> = None;
        while !input.is_empty() {
            let label: Ident = input.parse()?;
            let label_span = label.span();
            let label_name = label.to_string();
            input.parse::<Token![:]>()?;
            match label_name.as_str() {
                "name" => {
                    if name.is_some() {
                        return Err(syn::Error::new(label_span, "duplicate `name` label"));
                    }
                    name = Some(input.parse()?);
                }
                "script" => {
                    if script.is_some() {
                        return Err(syn::Error::new(label_span, "duplicate `script` label"));
                    }
                    if input.peek(LitStr) {
                        let s: LitStr = input.parse()?;
                        script = Some(ScriptSource::Literal(s));
                    } else if input.peek(syn::token::Brace) {
                        let content;
                        syn::braced!(content in input);
                        let ts: TokenStream2 = content.parse()?;
                        script = Some(ScriptSource::Braced(ts));
                    } else {
                        return Err(syn::Error::new(
                            input.span(),
                            "expected string literal or braced script block",
                        ));
                    }
                }
                "out_dir" => {
                    if out_dir.is_some() {
                        return Err(syn::Error::new(label_span, "duplicate `out_dir` label"));
                    }
                    out_dir = Some(input.parse()?);
                }
                _ => {
                    return Err(syn::Error::new(
                        label_span,
                        format!(
                            "unknown label `{label_name}`: expected `name`, `script`, or `out_dir`"
                        ),
                    ));
                }
            }
            let _ = input.parse::<Token![,]>().ok();
        }

        Ok(Self {
            name: name.ok_or_else(|| syn::Error::new(input.span(), "missing `name: ...` field"))?,
            script: script
                .ok_or_else(|| syn::Error::new(input.span(), "missing `script: ...` field"))?,
            out_dir: out_dir
                .ok_or_else(|| syn::Error::new(input.span(), "missing `out_dir: ...` field"))?,
        })
    }
}

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)
}

/// True for UPPERCASE function heads (`GREET`, `LOAD_TOML`): the token-level
/// call-head rule.
fn is_upper_func_head(text: &str) -> bool {
    let mut chars = text.chars();
    match chars.next() {
        Some(first) if first.is_ascii_uppercase() => (),
        _ => return false,
    }
    chars.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
}

/// True for a call-head token, plain (`GREET`) or module-qualified
/// (`MOCK::READ_CSV`): every `::` segment is non-empty, leading segments
/// are UPPERCASE, and the tail is identifier-shaped. The tail stays
/// case-open so `STD::glob(` attaches contiguously and fails at lowering
/// with a span-accurate UPPERCASE error; the grammar still rejects it.
/// Lets the `(` attach contiguously so the string grammar routes `M::F(...)`
/// to `call_statement`; deeper paths (`A::B::F`) still fail at parse
/// time.
fn is_call_head_token(token: &str) -> bool {
    match token.rsplit_once(MODULE_SEPARATOR) {
        // Qualified: every leading segment is a non-empty UPPERCASE
        // identifier and the tail is identifier-shaped (case checked at
        // lowering, so `STD::glob(` still attaches and fails with a span).
        Some((head, tail)) => {
            !tail.is_empty()
                && tail.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
                && !head.is_empty()
                && head
                    .split(MODULE_SEPARATOR)
                    .all(|part| !part.is_empty() && is_upper_func_head(part))
        }
        // Plain: exactly the old rule, so bare lowercase heads keep falling
        // through to the unknown-command path with its did-you-mean hint.
        None => is_upper_func_head(token),
    }
}

/// True when the current line ends with a bare-call head: an uppercase
/// identifier that is neither a known command nor a statement keyword.
/// Used to attach `(` contiguously (see the parenthesis group handling).
fn trailing_call_head(line: &str) -> bool {
    let Some(token) = line.split_whitespace().last() else {
        return false;
    };
    is_call_head_token(token)
        && Command::parse(token).is_none()
        && !Command::is_statement_keyword(token)
}

/// 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,
    in_guard: 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,
        in_guard,
        &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());
}

/// True when a rebuilt line still awaits its inner command: a bare
/// wrapper head (`ISOLATED`, `ASYNC`), a `WITH_IO [...]` bindings line
/// with no command yet, or the expression continuations (`=`, `IN`,
/// trailing `ASYNC`, `TIMEOUT` duration). A new statement keyword on a
/// later line glues only in these cases; a complete wrapper line
/// (`ISOLATED ENV K=v`) splits. Found by multistep fuzz: the token
/// rebuild dropped newlines after complete single-form wrappers.
fn line_awaits_inner_command(trimmed: &str) -> bool {
    let trimmed_end = trimmed.trim_end();
    let last_word = trimmed_end.split_whitespace().last();
    if trimmed_end.ends_with('=')
        || last_word == Some(KEYWORD_IN)
        || last_word == Some(KEYWORD_ASYNC)
        || line_ends_in_timeout_duration(trimmed_end)
    {
        return true;
    }
    if matches!(last_word, Some(KEYWORD_ISOLATED) | Some(KEYWORD_ASYNC)) {
        return true;
    }
    if trimmed_end.ends_with(']') {
        let head = trimmed.split_whitespace().next();
        if head == Some(KEYWORD_WITH_IO) {
            return true;
        }
    }
    false
}

fn line_expects_inner_command(line: &str) -> bool {
    matches!(
        current_line_command(line),
        Some(cmd) if cmd.expects_inner_command()
    )
}

/// True when the line ends in a `TIMEOUT <duration>` still awaiting its
/// command: `TIMEOUT 10s` or `LET $x: STRING = TIMEOUT 10s`. Mirrors
/// `timeout_literal` (`digits` plus optional `ms`/`s`/`m`/`h`; bare
/// digits are seconds), so the wrapped command glues instead of
/// starting a new line.
fn line_ends_in_timeout_duration(line: &str) -> bool {
    let mut words = line.split_whitespace().rev();
    let duration = words.next().unwrap_or("");
    if words.next() != Some(KEYWORD_TIMEOUT) {
        return false;
    }
    let digits = duration.trim_end_matches(|c: char| c.is_ascii_alphabetic());
    if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
        return false;
    }
    matches!(&duration[digits.len()..], "" | "ms" | "s" | "m" | "h")
}

fn line_is_run_context(line: &str) -> bool {
    matches!(current_line_command(line), Some(Command::Run))
}

/// Token-to-text rebuild: threading eight independent states (input,
/// line buffers, command tracking, interpolation/guard modes, capture
/// flags, span tracking) is clearer than bundling them into a context
/// object the ten call sites would construct field by field.
#[allow(clippy::too_many_arguments)]
fn walk(
    ts: TokenStream2,
    line: &mut String,
    lines: &mut Vec<String>,
    last_was_command: &mut bool,
    in_interpolation: bool,
    in_guard: 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 raw_gap = last_span_end
            .map(|prev| span_gap_requires_space(prev, span.start()))
            .unwrap_or(false);
        // Inside `${ guard_line ... }` implicit whitespace is off, so the
        // rebuild must not invent spaces the grammar cannot skip: glue at
        // structural punctuation, keep source spacing elsewhere (bare
        // values like `a b` need their space). Commas always allow the
        // space (`ws?` in the grammar); brackets, parens, colons, pipes,
        // and `$` never do.
        let gap_space = if in_guard {
            let prev_punct = line
                .trim_end()
                .ends_with(['(', ')', ',', '[', ']', ':', '|', '$']);
            let next_punct = matches!(
                &tt,
                TokenTree::Punct(p)
                    if matches!(p.as_char(), '(' | ')' | ',' | '[' | ']' | ':' | '|' | '$')
            );
            raw_gap && (line.trim_end().ends_with(',') || (!prev_punct && !next_punct))
        } else {
            raw_gap
        };
        // Blank source lines survive the rebuild as empty lines:
        // TokenStreams carry no blank tokens, but span line numbers jump
        // over them, and blank lines are significant (a blank line severs
        // a `#` doc block from its FUNC). Finalize any open line, then
        // emit one empty line per skipped line. Degenerate spans never
        // gap, so synthetic streams are unaffected.
        if !in_guard
            && !in_interpolation
            && let Some(prev) = *last_span_end
            && span.start().line > prev.line + 1
        {
            finalize_line(lines, line, capture_has_inner);
            for _ in prev.line + 1..span.start().line {
                lines.push(String::new());
            }
        }
        // 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 !in_guard
            && 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,
                                    in_guard,
                                    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,
                                    in_guard,
                                    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,
                                    in_guard,
                                    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,
                                    in_guard,
                                    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(KEYWORD_IN);
                            // A bracket opening on a later line than the
                            // previous token starts a new statement (a
                            // leading guard), even right after a bare
                            // command: without this, `LS` followed by
                            // `[env:X] ECHO` glues into `LS [env:X]`,
                            // dropping the guard or failing arity.
                            // Expression continuations (`=`/`IN`/etc.)
                            // still attach across lines.
                            let opens_new_line = last_span_end
                                .map(|prev| span.start().line > prev.line)
                                .unwrap_or(false);
                            if (*last_was_command && !opens_new_line) || 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,
                                    in_guard,
                                    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., [bool:true], [env:KEY])
                                // or second bracket group after a command.
                                // Finalize any previous line and render the
                                // guard open/expr/close exactly like the
                                // string grammar reads them (a guard_line may
                                // span lines; it guards the next element).
                                // But do NOT finalize after `]`: the grammar
                                // joins a guard block's `]` to its `{` with
                                // gap only, so the brace must attach to the
                                // `]` line or the enclosing block misparses
                                // (misreported at its opener).
                                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,
                                    true,
                                    capture_has_inner,
                                    &mut inner_span_end,
                                )?;
                                finalize_line(lines, line, capture_has_inner);
                                push_fragment(line, &close.to_string(), false);
                            }
                        }
                        _ => {
                            // A `(` group after an uppercase non-command head
                            // is a bare call: push it contiguously so the
                            // string grammar routes `FOO(...)` to
                            // `call_statement`, except when source spans
                            // show a real gap (`FOO (` stays an instruction).
                            // Commands keep existing spacing (`ECHO (1 + 2)`).
                            // Note: this bypasses `push_fragment`, whose
                            // `needs_space` heuristic would re-insert the
                            // space we are deliberately dropping.
                            let attach_call = open == '('
                                && trailing_call_head(line)
                                && last_span_end
                                    .map(|prev| prev == span.start())
                                    .unwrap_or(true);
                            // Guard parens glue unconditionally: the
                            // atomic context admits no gaps around them.
                            let guard_paren = in_guard && (open == '(' || open == ')');
                            if attach_call || guard_paren {
                                line.push(open);
                            } else {
                                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,
                                in_guard,
                                capture_has_inner,
                                &mut inner_span_end,
                            )?;
                            if in_guard && close == ')' {
                                line.push(close);
                            } else {
                                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,
                        in_guard,
                        capture_has_inner,
                        &mut inner_span_end,
                    )?;
                }
                *last_span_end = Some(span.end());
            }
            TokenTree::Literal(lit) => {
                let frag = lit.to_string();
                // Fused string runs: Rust lexes `"""..."""` as adjacent
                // string literals, and the string grammar reads contiguous
                // literals with no gap. Rebuilding them spaced would glue a
                // different value (or shred a block), so a quote junction
                // with no span gap fuses verbatim instead. Spaced literals
                // keep their separating space. Synthetic (`quote!`) spans
                // are zero-width and carry no adjacency signal, so they
                // always take the spaced reading. Blocks holding raw `"`
                // cannot pass here at all: the lexer ends the literal at
                // every quote, shredding content into idents and puncts
                // that read as separate arguments. That shape is
                // indistinguishable from legitimate multi-arg statements,
                // so it stays string-pathway-only by construction.
                let fuse = frag.starts_with('"')
                    && line.trim_end().ends_with('"')
                    && span.start() != span.end()
                    && last_span_end
                        .map(|prev| prev == span.start())
                        .unwrap_or(false);
                // Contiguous quote junctions fuse regardless of context;
                // structural junctions inside guards glue for the same
                // reason: the grammar takes no gap in either spot.
                if fuse || in_guard && line.trim_end().ends_with(['(', ',', '[', ':', '|', '$']) {
                    line.push_str(&frag);
                } else {
                    push_fragment(line, &frag, *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 != ';');
                // Glued dashes in RUN shell text stay glued (`W-XYZ`):
                // `Spacing::Alone` only means "followed by a non-punct",
                // not "gapped", so an adjacent non-degenerate `-` must
                // not invent a space. Degenerate spans (`quote!`, all
                // zero-width) carry no adjacency signal and keep the
                // spaced reading, which shell flags need.
                let dash_glued = last_span_end.is_some_and(|prev| prev == span.start())
                    && span.start() != span.end();
                if ch == '-'
                    && p.spacing() == Spacing::Alone
                    && !dash_glued
                    && 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;
                }
                // A `#` comment opening on a later line starts a new
                // rebuilt line, so contiguous doc blocks above `FUNC`
                // stay one-comment-per-line for `func_docs` collection.
                // Same-line `#` (`#var` interpolation, `#{expr}`) keeps
                // gluing; guards keep gluing (never a comment there).
                if ch == '#'
                    && !in_guard
                    && !in_interpolation
                    && !line.trim().is_empty()
                    && last_span_end.is_some_and(|prev| span.start().line > prev.line)
                {
                    finalize_line(lines, line, capture_has_inner);
                }
                // A `$var` mutate statement opening on a later line starts
                // a new statement, mirroring the Ident arm: without this,
                // `$x = 1` after a complete step glues onto its line.
                // Restricted to `$`+Ident (`${..}` interpolation has a
                // Group next, `=` continuations await) so same-line args
                // (`ECHO $x`) and interpolation never split.
                if ch == '$'
                    && matches!(next, Some(TokenTree::Ident(_)))
                    && !line.trim().is_empty()
                    && !line_is_run_context(line.trim())
                    && !line_awaits_inner_command(line.trim())
                    && last_span_end.is_some_and(|prev| span.start().line > prev.line)
                {
                    finalize_line(lines, line, capture_has_inner);
                }
                // Atomic guard context admits no implicit gaps around
                // structural punctuation: push directly instead of
                // letting `push_fragment` invent spacing the grammar
                // cannot skip. (No trailing space can exist here: pushes
                // never leave any, so gluing is always faithful.)
                if in_guard && matches!(ch, '(' | ')' | ',' | '[' | ']' | ':' | '|' | '$') {
                    line.push(ch);
                } else {
                    push_fragment(line, &ch.to_string(), force_space);
                }
                *last_was_command = false;
                *last_span_end = Some(span.end());
                // `;` ends statements everywhere except inside guards,
                // where the key charset admits it literally.
                if ch == ';' && !in_guard {
                    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,
                // RETURN, WHILE, BREAK, CONTINUE): without this, `FUNC`
                // after `MKDIR dist` would glue onto the same line.
                let is_new_statement = super::Command::is_statement_keyword(&ident_text);
                // A bare `NAME(...)` call opens a statement when it starts a
                // new source line with an empty continuation state. This
                // mirrors the string grammar, where statement calls begin
                // lines: `GREET("ada")` after `WRITE a.txt hi` must split,
                // while `ECHO GREET("ada")` (same line, argument position)
                // and `LET $r: STRING = GREET("ada")` (after `=`) stay glued.
                // `FOO (` with a space is not a call (calls need a joint paren), so a
                // gap between the head and the paren group opts out.
                let is_call_statement_start = !is_command
                    && is_upper_func_head(&ident_text)
                    && matches!(
                        next,
                        Some(TokenTree::Group(g))
                            if g.delimiter() == Delimiter::Parenthesis
                    )
                    && {
                        let head_end = span.end();
                        match next {
                            Some(TokenTree::Group(g)) => {
                                let paren_start = g.span().start();
                                paren_start.line == head_end.line
                                    && paren_start.column == head_end.column
                            }
                            _ => false,
                        }
                    };
                // A qualified `MODULE::NAME(...)` call opens a statement
                // under the same conditions: the head starts at the module
                // identifier, so look ahead over `::`, the name, and the
                // paren group. Without this, `MOCK::READ_CSV(..)` after a
                // complete statement glues onto its line (the module ident
                // alone matches neither the keyword nor the bare-call rule).
                let is_qualified_call_start = is_upper_func_head(&ident_text)
                    && matches!(next, Some(TokenTree::Punct(p)) if p.as_char() == ':')
                    && matches!(tokens.get(idx + 2), Some(TokenTree::Punct(p)) if p.as_char() == ':')
                    && matches!(tokens.get(idx + 3), Some(TokenTree::Ident(_)))
                    && matches!(
                        tokens.get(idx + 4),
                        Some(TokenTree::Group(g))
                            if g.delimiter() == Delimiter::Parenthesis
                    );
                let trimmed = line.trim();
                let trimmed_empty = trimmed.is_empty();
                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 = F()`,
                // `LET $t: HANDLE<T> = ASYNC ...`, `FOR $x: STRING IN [...]`.
                // A trailing `ASYNC` expects its command the same way:
                // without this, `LET $t: HANDLE<VOID> = ASYNC ECHO hi` splits
                // the command onto its own line and misparses.
                // A statement keyword there continues the line instead of
                // starting a new one.
                let trimmed_end = trimmed.trim_end();
                let last_word = trimmed_end.split_whitespace().last();
                let expects_expr = trimmed_end.ends_with('=')
                    || last_word == Some(KEYWORD_IN)
                    || last_word == Some(KEYWORD_ASYNC)
                    || line_ends_in_timeout_duration(trimmed_end);
                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 == KEYWORD_ELSE
                    || (ident_text == KEYWORD_IF && trimmed.ends_with(KEYWORD_ELSE))
                {
                    should_finalize = false;
                // Guard idents are values, never statements: even a
                // command-named value (`LS`) or a guard call (`not(`)
                // must glue, so the split rules below stay quiet here.
                } else if is_new_statement && !in_guard && !trimmed_empty && !expects_expr {
                    // A statement keyword opening on a later source line
                    // starts a new statement unless the line still awaits
                    // its inner command (bare wrapper head, bindings
                    // without command, `=`/`IN`/duration continuations).
                    // Same-line occurrences keep gluing (wrapper
                    // continuations like `ISOLATED ECHO hi`).
                    // Degenerate spans (synthetic `call_site`/`quote!`
                    // streams where every token reports the same
                    // position) carry no line signal: fall back to
                    // splitting, preserving the old behavior there.
                    let new_line = last_span_end
                        .map(|prev| span.start().line > prev.line)
                        .unwrap_or(false);
                    let spans_degenerate = last_span_end
                        .map(|prev| prev == span.start())
                        .unwrap_or(false);
                    should_finalize = !line_is_run_context(trimmed)
                        && !line_awaits_inner_command(trimmed)
                        && (new_line || spans_degenerate);
                }
                // Bare and qualified calls split like keywords when they open
                // a new source line after a complete statement. Same-line
                // occurrences (command arguments, parenthesized groups)
                // attach instead. A head continuing a `MODULE::` qualifier
                // never splits: `MOCK::` plus `READ_CSV(` is one call head
                // (the split, if any, already happened at the module ident).
                if (is_call_statement_start || is_qualified_call_start)
                    && !in_guard
                    && !trimmed_empty
                    && !expects_expr
                    && !line_is_run_context(trimmed)
                    && !trimmed_end.ends_with(MODULE_SEPARATOR)
                    && last_span_end.is_some_and(|prev| span.start().line > prev.line)
                {
                    should_finalize = true;
                }
                if is_command
                    && !trimmed_empty
                    && *capture_has_inner
                    && line_requires_inner
                    && ident_text != KEYWORD_ASYNC
                {
                    finalize_line(lines, line, capture_has_inner);
                }
                if should_finalize {
                    finalize_line(lines, line, capture_has_inner);
                }
                // Guard structural punctuation glues to the next token:
                // `(env`, `,env` need no space (the grammar takes none),
                // while word-word junctions keep source spacing below.
                if in_guard && line.trim_end().ends_with(['(', ',', '[', ':', '|', '$']) {
                    line.push_str(&ident_text);
                } else {
                    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(())
}

/// Split an optional leading `modules: [A, B]` prefix off a braced macro
/// token stream. The names declare opaque modules (membership unknown at
/// compile time) for the `oxdock!` parse; the remainder walks as DSL.
/// Returns no names when the stream opens with anything else, so plain
/// scripts pass through untouched.
pub fn split_modules_prefix(ts: &TokenStream2) -> Result<(Vec<String>, TokenStream2)> {
    use std::iter::FromIterator;
    let mut tokens: Vec<TokenTree> = ts.clone().into_iter().collect();
    let prefix = match tokens.as_slice() {
        [
            TokenTree::Ident(head),
            TokenTree::Punct(colon),
            TokenTree::Group(list),
            ..,
        ] if head == "modules"
            && colon.as_char() == ':'
            && list.delimiter() == Delimiter::Bracket =>
        {
            let mut names = Vec::new();
            for item in list.stream().into_iter() {
                match item {
                    TokenTree::Ident(name) => names.push(name.to_string()),
                    TokenTree::Punct(comma) if comma.as_char() == ',' => {}
                    other => {
                        anyhow::bail!("modules: prefix holds module names, found `{other}`");
                    }
                }
            }
            names
        }
        _ => return Ok((Vec::new(), ts.clone())),
    };
    tokens.drain(..3);
    // An optional comma separates the prefix from the script body.
    if let Some(TokenTree::Punct(comma)) = tokens.first()
        && comma.as_char() == ','
    {
        tokens.drain(..1);
    }
    Ok((prefix, TokenStream2::from_iter(tokens)))
}

/// 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,
        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.
/// Returns `anyhow::Error` rather than `ParseError` (unlike the
/// string entry points) because macro-side failures carry the head
/// token span enrichment, which has no `ParseError` channel.
pub fn parse_braced_tokens(
    ts: &TokenStream2,
    lower: impl Fn(&str, Vec<crate::Arg>) -> crate::ParseResult<crate::StepKind>,
) -> Result<Vec<Step>> {
    Ok(parse_braced_tokens_with_exports(ts, lower)?.steps)
}

/// Parse a braced token stream with single-file `EXPORT` metadata and
/// `#` doc comments for top-level `FUNC`s, mirroring
/// [`crate::parse_script_with_exports`]. `#` comment lines survive the
/// `walk()` rebuild as literal `# ...` lines (like the existing `#cmd`
/// comment test), so `func_docs` collection sees the same text the
/// string path would.
pub fn parse_braced_tokens_with_exports(
    ts: &TokenStream2,
    lower: impl Fn(&str, Vec<crate::Arg>) -> crate::ParseResult<crate::StepKind>,
) -> Result<crate::ParsedScript> {
    let script = script_from_braced_tokens(ts)?;
    // The string rebuild loses per token positions. Forward the head
    // token coordinates so failures still carry a macro position; the
    // caller keeps its own span handle for `syn::Error` squiggles.
    let head_ctx = ts.clone().into_iter().next().map(|t| {
        let start = t.span().start();
        crate::SpanContext::from_compiler_span(
            start.line.max(1),
            Some(start.column.saturating_add(1)),
            Some(start.column.saturating_add(1)),
            t.span(),
        )
    });
    crate::parse_script_with_exports(&script, lower).map_err(|e| {
        let e = match &head_ctx {
            Some(ctx) => e.with_span(ctx),
            None => e,
        };
        anyhow::Error::from(e)
    })
}

/// Parse a braced token stream with an explicit module table, so
/// qualified calls resolve exactly like the string pathway with the
/// same table. `parse_braced_tokens` stays table-free for callers
/// without host modules. Same `anyhow::Error` carrier as the other
/// braced entry points (macro-side span enrichment).
pub fn parse_braced_tokens_with_modules(
    ts: &TokenStream2,
    lower: impl Fn(&str, Vec<crate::Arg>) -> crate::ParseResult<crate::StepKind>,
    reserved_names: std::collections::HashSet<String>,
    modules: crate::ModuleTable,
) -> Result<Vec<Step>> {
    Ok(parse_braced_tokens_with_modules_and_exports(ts, lower, reserved_names, modules)?.steps)
}

/// Parse a braced token stream with an explicit module table plus
/// single-file `EXPORT` metadata and `#` doc comments, mirroring
/// [`crate::parse_script_with_modules_and_exports`]. Future MCP hosts
/// reading braced input get the same `exports` + `func_docs` the file
/// path provides today.
pub fn parse_braced_tokens_with_modules_and_exports(
    ts: &TokenStream2,
    lower: impl Fn(&str, Vec<crate::Arg>) -> crate::ParseResult<crate::StepKind>,
    reserved_names: std::collections::HashSet<String>,
    modules: crate::ModuleTable,
) -> Result<crate::ParsedScript> {
    let script = script_from_braced_tokens(ts)?;
    let head_ctx = ts.clone().into_iter().next().map(|t| {
        let start = t.span().start();
        crate::SpanContext::from_compiler_span(
            start.line.max(1),
            Some(start.column.saturating_add(1)),
            Some(start.column.saturating_add(1)),
            t.span(),
        )
    });
    crate::parse_script_with_modules_and_exports(&script, lower, reserved_names, modules).map_err(
        |e| {
            let e = match &head_ctx {
                Some(ctx) => e.with_span(ctx),
                None => e,
            };
            anyhow::Error::from(e)
        },
    )
}

#[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>) -> crate::ParseResult<StepKind> {
        crate::test_lower_mock::lower(name, args)
    }

    #[test]
    fn leading_guard_after_bare_command_starts_new_line() {
        // A guard opening on a later line than a bare command starts a
        // new statement: without this, `LS` followed by `[env:X] ECHO`
        // glues into `LS [env:X]` and fails arity. Found by multistep
        // fuzz (`LS` + guarded step); real `oxdock!` users hit the same
        // shape writing guarded steps after bare commands.
        let text = "LS\n[env:X] ECHO hi";
        let ts: proc_macro2::TokenStream = text.parse().expect("tokens");
        let script = script_from_braced_tokens(&ts).expect("rebuild");
        let braced = parse_braced_tokens(&ts, mock_lower).expect("braced parse");
        let string = crate::parse_script(text, mock_lower).expect("string parse");
        assert_eq!(braced, string, "pathways must agree (rebuilt: {script:?})");
        assert_eq!(braced.len(), 2, "steps split: {script:?}");
        assert!(
            braced[1].guard.is_some(),
            "guard dropped in rebuild: {script:?}"
        );
    }

    #[test]
    fn braced_wrapper_continuations_stay_glued() {
        // Every wrapper that takes a trailing command must rebuild on
        // one line, exactly as the string grammar requires. Regression
        // coverage for the `ASYNC` split and the `TIMEOUT` duration split.
        for text in [
            "TIMEOUT 10s ECHO hi",
            "WITH_IO [stdout=$p] ECHO hi",
            "ISOLATED ECHO hi",
            "RETURN $x",
            "LET $t: HANDLE = ASYNC ECHO hi",
            "LET $o: STRING = AWAIT $t",
            "ASYNC ECHO hi",
            "LET $x: STRING = TIMEOUT 10s ECHO hi",
        ] {
            let ts: proc_macro2::TokenStream = text.parse().expect("tokens");
            let script = script_from_braced_tokens(&ts).expect("rebuild");
            assert_eq!(script.lines().count(), 1, "{text:?} split: {script:?}");
            let braced = parse_braced_tokens(&ts, mock_lower).expect("braced parse");
            let string = crate::parse_script(text, mock_lower).expect("string parse");
            assert_eq!(braced, string, "pathways must agree on {text:?}");
        }
    }

    #[test]
    fn braced_triple_quote_fuses_to_block() {
        // Rust lexes `"""hi"""` as three adjacent string literals. The
        // walker fuses the quote junction back, so the string grammar
        // reads one block, exactly as the string path does.
        let ts: proc_macro2::TokenStream = "ECHO \"\"\"hi\"\"\"".parse().expect("tokens");
        let script = script_from_braced_tokens(&ts).expect("rebuild");
        assert_eq!(script, "ECHO \"\"\"hi\"\"\"", "got: {script}");
        let braced = parse_braced_tokens(&ts, mock_lower).expect("parse");
        let string = crate::parse_script("ECHO \"\"\"hi\"\"\"", mock_lower).expect("string parse");
        assert_eq!(braced, string, "braced and string forms must agree");
        match &braced[0].kind {
            StepKind::Echo(arg) => assert_eq!(arg.as_str(), "hi"),
            other => panic!("expected Echo, saw {:?}", other),
        }
    }

    #[test]
    fn braced_multiline_block_dedents() {
        // Contiguous literals fuse with their newlines intact, so block
        // payloads keep their indentation and dedent normally.
        let ts: proc_macro2::TokenStream = "ECHO \"\"\"\n    SELECT *\n    FROM users\n    \"\"\""
            .parse()
            .expect("tokens");
        let steps = parse_braced_tokens(&ts, mock_lower).expect("parse");
        match &steps[0].kind {
            StepKind::Echo(arg) => assert_eq!(arg.as_str(), "SELECT *\nFROM users"),
            other => panic!("expected Echo, saw {:?}", other),
        }
    }

    #[test]
    fn braced_statement_after_block_starts_new_line() {
        // Fused newlines must not glue the next statement onto the block.
        let ts: proc_macro2::TokenStream = "ECHO \"\"\"\n    hi\n    \"\"\"\nWRITE out.txt done"
            .parse()
            .expect("tokens");
        let steps = parse_braced_tokens(&ts, mock_lower).expect("parse");
        assert_eq!(steps.len(), 2, "got: {steps:?}");
        match &steps[0].kind {
            StepKind::Echo(arg) => assert_eq!(arg.as_str(), "hi"),
            other => panic!("expected Echo, saw {:?}", other),
        }
    }

    #[test]
    fn braced_contiguous_strings_match_string_path() {
        // `"a""b"` fuses to its source spelling, agreeing with the
        // string grammar (one glued value), instead of the spaced
        // reading (`a b`).
        let ts: proc_macro2::TokenStream = "ECHO \"a\"\"b\"".parse().expect("tokens");
        let braced = parse_braced_tokens(&ts, mock_lower).expect("parse");
        let string = crate::parse_script("ECHO \"a\"\"b\"", mock_lower).expect("string parse");
        assert_eq!(braced, string, "braced and string forms must agree");
    }

    #[test]
    fn braced_adjacent_strings_with_gaps_still_rebuild() {
        // Spaced literals are genuinely separate fragments: no triple
        // quote forms, so the guard must stay quiet. Parsed from text,
        // so spans are real, exactly as rustc hands a proc macro.
        let ts: proc_macro2::TokenStream = "ECHO \"a\" \"b\"".parse().expect("tokens");
        let script = script_from_braced_tokens(&ts).expect("rebuild");
        assert_eq!(script, "ECHO \"a\" \"b\"", "got: {script}");
    }

    #[test]
    fn braced_quote_macro_strings_stay_unflagged() {
        // `quote!` spans are synthetic (zero-width, no adjacency
        // signal), so the triple-quote guard cannot apply there. This
        // pins the exemption: contiguous literals from `quote!` rebuild
        // spaced, and the string grammar glues them into one value.
        // Divergent from the string path (`"a""b"` reads `ab`), but the
        // token stream no longer carries the contiguity proof, so the
        // walker takes the spaced reading instead of guessing.
        let ts = quote! { ECHO "a" "b" };
        let script = script_from_braced_tokens(&ts).expect("rebuild");
        assert_eq!(script, "ECHO \"a\" \"b\"", "got: {script}");
        let braced = parse_braced_tokens(&ts, mock_lower).expect("parse");
        let string = crate::parse_script("ECHO \"a\" \"b\"", mock_lower).expect("string parse");
        assert_eq!(braced, string, "braced and string forms must agree");
    }

    #[test]
    fn literal_script_form_parses_block_string() {
        // The supported route for blocks in macros: a string literal
        // passes through untouched, so dedent baselines survive.
        let src = "name: foo, script: r#\"ECHO \"\"\"\n    hi\n    \"\"\"\"#, out_dir: \"out\"";
        let input: DslMacroInput = syn::parse_str(src).expect("parse literal script");
        let ScriptSource::Literal(lit) = input.script else {
            panic!("expected literal script");
        };
        let steps = crate::parse_script(&lit.value(), mock_lower).expect("block parses");
        assert_eq!(steps.len(), 1);
        match &steps[0].kind {
            StepKind::Echo(arg) => assert_eq!(arg.as_str(), "hi"),
            other => panic!("expected Echo, saw {:?}", other),
        }
    }

    #[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 parse_dsl_macro_input_accepts_any_field_order() {
        // The README leads with `out_dir` ahead of a long script block.
        let input: DslMacroInput =
            syn::parse_str("name: foo, out_dir: \"out\", script: { RUN echo hi }")
                .expect("out_dir before script");
        assert_eq!(input.name.to_string(), "foo");
        assert_eq!(input.out_dir.value(), "out");
        assert!(matches!(input.script, ScriptSource::Braced(_)));

        let input: DslMacroInput =
            syn::parse_str("out_dir: \"out\", script: \"RUN echo hi\", name: foo")
                .expect("fully reversed order");
        assert_eq!(input.name.to_string(), "foo");
        assert!(matches!(input.script, ScriptSource::Literal(_)));
    }

    #[test]
    fn parse_dsl_macro_input_rejects_duplicates_unknown_and_missing() {
        assert!(
            syn::parse_str::<DslMacroInput>(
                "name: foo, name: bar, script: \"RUN echo hi\", out_dir: \"out\""
            )
            .is_err()
        );
        assert!(
            syn::parse_str::<DslMacroInput>(
                "name: foo, script: \"RUN echo hi\", script: \"RUN echo yo\", out_dir: \"out\""
            )
            .is_err()
        );
        assert!(
            syn::parse_str::<DslMacroInput>(
                "name: foo, script: \"RUN echo hi\", out_dir: \"a\", out_dir: \"b\""
            )
            .is_err()
        );
        assert!(
            syn::parse_str::<DslMacroInput>(
                "name: foo, script: \"RUN echo hi\", out_dir: \"out\", extra: 1"
            )
            .is_err()
        );
        assert!(syn::parse_str::<DslMacroInput>("script: \"x\", out_dir: \"y\"").is_err());
        assert!(syn::parse_str::<DslMacroInput>("name: foo, out_dir: \"y\"").is_err());
        assert!(syn::parse_str::<DslMacroInput>("name: foo, script: \"x\"").is_err());
    }

    #[test]
    fn braced_and_string_agree_on_escape_layers() {
        // Escaped content (`\"`, `\\`) stays verbatim through lowering on
        // purpose (runtime decodes it), so both pathways must produce the
        // SAME layered value. This pins the agreement the fuzzer cannot
        // cover: its alphabet excludes `\` and `"` as unrepresentable
        // across render cycles, but direct source parses fine on both.
        for text in [
            "ECHO \"a\\\"b\"",
            "ECHO \"a\\\\b\"",
            "ECHO \"\"\"\nescaped \\\"\\\"\\\" stays\n\"\"\"",
        ] {
            let ts: proc_macro2::TokenStream = text.parse().expect("tokens");
            let braced = parse_braced_tokens(&ts, mock_lower).expect("braced parse");
            let string = crate::parse_script(text, mock_lower).expect("string parse");
            assert_eq!(braced, string, "pathways must agree on {text:?}");
        }
    }

    #[test]
    fn braced_quote_shredding_divergence_is_pinned() {
        // KNOWN DIVERGENCE, not parity: a block holding a raw `"` cannot
        // cross a token stream (the lexer ends the literal at every
        // quote), so the string path reads one block while the token
        // path reads glued fragments. The shape is indistinguishable
        // from legitimate multi-arg statements, so no walker rule can
        // separate them. This test locks the divergence in place: if
        // either side shifts, it fails and forces a conscious decision.
        let text = "ECHO \"\"\"\nsay \"hi\"\n\"\"\"";
        let string = crate::parse_script(text, mock_lower).expect("string parse");
        match &string[0].kind {
            StepKind::Echo(arg) => assert_eq!(arg.as_str(), "say \"hi\""),
            other => panic!("expected Echo, saw {:?}", other),
        }
        let ts: proc_macro2::TokenStream = text.parse().expect("tokens");
        let braced = parse_braced_tokens(&ts, mock_lower).expect("braced parse");
        assert_ne!(
            braced, string,
            "if these ever agree, delete this test and celebrate"
        );
    }

    #[test]
    fn braced_let_run_exec_stays_exec_form() {
        // End-to-end guard for the README embed example: tokens shaped
        // exactly like the macro receives them must rebuild to text
        // that still lowers to RunExec, never shell text. A prior
        // revision executed `[ cargo , --version ]` through zsh.
        let ts: proc_macro2::TokenStream = r#"LET $cargo: STRING = RUN ["cargo", "--version"]"#
            .parse()
            .expect("tokens");
        let script = script_from_braced_tokens(&ts).expect("rebuild");
        let steps =
            crate::parse_script(&script, crate::lower_command).expect("parse rebuilt script");
        assert_eq!(steps.len(), 1);
        match &steps[0].kind {
            StepKind::Bind {
                var,
                rhs: crate::commands::BindRhs::Capture(cmd),
                ..
            } => {
                assert_eq!(var, "cargo");
                assert!(
                    matches!(cmd.as_ref(), StepKind::RunExec { .. }),
                    "rebuilt {script:?} degraded to {cmd:?}"
                );
            }
            other => panic!("expected Bind Capture, got {other:?}"),
        }
    }

    #[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_guard_block_keeps_brace_on_bracket_line() {
        // The grammar joins a guard block's `]` to its `{` with gap only,
        // so the walker must attach the brace to the `]` line: a split
        // `]` / `{` never parses back and misreports at the enclosing
        // block opener.
        let ts: proc_macro2::TokenStream = indoc! {r#"
            FUNC FOO($x: MAP): VOID {
                [bool:true] {
                    WRITE inner.txt inside
                }
            }
        "#}
        .parse()
        .expect("tokens");
        let script = script_from_braced_tokens(&ts).expect("render braced script");
        assert!(
            script.contains("] {"),
            "guard close and block open must share a line, got:\n{script}"
        );
        let steps = parse_braced_tokens(&ts, mock_lower).expect("guarded block parses");
        assert_eq!(steps.len(), 1, "got: {steps:?}");
    }

    #[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 = crate::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, bare calls, 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): STRING {
                RETURN $name
            }
            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 ...`, `= F(...)`) 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::Bind { .. }));
        assert!(matches!(steps[1].kind, StepKind::For { .. }));
        assert!(matches!(steps[2].kind, StepKind::Bind { .. }));
    }

    #[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::Bind { .. }));
    }

    #[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 { .. }));
    }

    #[test]
    fn qualified_call_never_splits_at_double_colon() {
        // `MOCK::READ_CSV(...)` lexes as Ident Punct Punct Ident Group:
        // the statement split happens at the module ident (own line), and
        // the walker must not split again between `::` and the name.
        // Intra-line spacing is cosmetic; line structure is what's pinned.
        // Real spans required: `quote!` stamps every token line 1, which
        // disables line-driven splitting by design.
        let ts: proc_macro2::TokenStream = indoc! {r#"
            WRITE a.txt hi
            MOCK::READ_CSV("a")
        "#}
        .parse()
        .expect("tokens");
        let script = script_from_braced_tokens(&ts).expect("render braced script");
        let lines: Vec<&str> = script.lines().collect();
        assert_eq!(lines.len(), 2, "got: {script}");
        assert_eq!(lines[0], "WRITE a.txt hi", "got: {script}");
        assert_eq!(
            lines[1].replace(' ', ""),
            "MOCK::READ_CSV(\"a\")",
            "got: {script}"
        );
    }

    #[test]
    fn qualified_call_in_expression_position_stays_glued() {
        let ts = quote! {
            LET $x: STRING = STD::INT("2")
        };
        let script = script_from_braced_tokens(&ts).expect("render braced script");
        assert_eq!(
            script.replace(' ', ""),
            "LET$x:STRING=STD::INT(\"2\")",
            "got: {script}"
        );
    }

    #[test]
    fn modules_prefix_splits_off_and_leaves_script() {
        let ts = quote! {
            modules: [DOCS]
            IMPORT [STD, DOCS]
        };
        let (names, rest) = split_modules_prefix(&ts).expect("split prefix");
        assert_eq!(names, vec!["DOCS".to_string()]);
        let script = script_from_braced_tokens(&rest).expect("render rest");
        assert_eq!(script.replace(' ', ""), "IMPORT[STD,DOCS]", "got: {script}");
    }

    #[test]
    fn modules_prefix_absent_passes_through() {
        let ts = quote! {
            WRITE a.txt hi
        };
        let (names, rest) = split_modules_prefix(&ts).expect("split prefix");
        assert!(names.is_empty());
        let script = script_from_braced_tokens(&rest).expect("render rest");
        assert_eq!(script.trim(), "WRITE a.txt hi", "got: {script}");
    }

    #[test]
    fn modules_prefix_rejects_non_ident_entries() {
        let ts = quote! {
            modules: [42]
        };
        assert!(split_modules_prefix(&ts).is_err());
    }
}