oxdock-parser 0.41.0-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
//! Shared token model for the unified parser backend.
//!
//! Two context-free lexers emit [`Tok`]: [`lex_str`] for string sources
//! and `lex_tokens` (behind `proc-macro-api`) for `TokenStream`.
//! Both are positional only: they record gap adjacency (`joint`) and
//! literal newlines, but never decide statement boundaries. Whether a
//! newline ends a statement (or a `[` opens a guard vs. args, or a word
//! continues a wrapper) is grammar state, so it lives in the parser
//! backend, never here.
//!
//! String semantics are single-sourced in `lex_string_spelling`: the
//! `TokenStream` frontend fuses span-adjacent shredded literals back to
//! their source spelling (`""` + `"hi"` + `""` is `"""hi"""`) and runs
//! the same scanner. Contents stay verbatim (escapes expand at runtime
//! `expand_string`, matching `parse_quoted_string`); `"""` bodies lower
//! later through the shared `lower_block_string`.

use crate::constants::{
    KEYWORD_ASYNC, KEYWORD_ELSE, KEYWORD_FOR, KEYWORD_FUNC, KEYWORD_IF, KEYWORD_ISOLATED,
    KEYWORD_REMOTE, KEYWORD_TIMEOUT, KEYWORD_WHILE, KEYWORD_WITH_IO,
};
use crate::error::ParseErrorKind;
use std::fmt;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GroupDelim {
    Bracket,
    Paren,
    Brace,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TokKind {
    /// Bare word: commands, keywords, numbers-as-spelled, paths, flags.
    /// Any run of non-delimiter chars; never contains whitespace.
    Word(String),
    /// Verbatim inner of `"..."` / `'...'` (escapes intact for runtime).
    /// The quote style round-trips raw-text positions (in-arg groups).
    Str { text: String, quote: char },
    /// Full `"""..."""` spelling including delimiters; lower with
    /// `lower_block_string` at parse time.
    BlockStr(String),
    /// Single punctuation char (`=`, `$`, `:`, `!`, `<`, `>`, `,`, `|`,
    /// `&`, `@`). Multi-char operators combine in the parser using
    /// `joint`.
    Punct(char),
    /// Delimited group with recursively lexed contents. `open_joint`
    /// is gaplessness between the opener and the first inner token;
    /// `close_joint` between the last inner token and the closer (both
    /// vacuously true when empty). Statement splitting and guard
    /// parsing ignore them; raw-text splices need them.
    Group {
        delim: GroupDelim,
        inner: Vec<Tok>,
        open_joint: bool,
        close_joint: bool,
    },
    /// Literal newline (`\n`, `\r\n`, `\r` all normalize to one).
    Newline,
    /// Explicit `;` statement terminator.
    Semicolon,
    /// A skipped comment's raw spelling (`//...`, `#...`, `/*...*/`),
    /// emitted only where the lexer skips comments (line starts, top
    /// level and inside groups). Statement splitting ignores them but
    /// releases pending `ELSE` continuations (a comment line breaks
    /// the `}`/`ELSE` chain like the grammar); raw-text renders
    /// reproduce them byte-identically (templates keep comment text
    /// like the atomic grammar span). The token frontend never emits
    /// these (`rustc` strips comments before us).
    Comment(String),
}

/// One token plus the gap signal: `joint` is true when no gap (no
/// whitespace, comment, or newline) precedes it. The parser uses this
/// where the grammar requires adjacency (`::`, `$var`, `==`, `"a""b"`
/// fragment joins, `FOO (` not-a-call); it never affects token identity.
/// `line`/`col` are the 1-based start coordinates (`0` when unknown:
/// synthetic streams, fused fragments, group interiors lexed without
/// position context). Only statement-head positions are consumed
/// (statement starts for errors and step coordinates); everything else
/// rides along for future tooling. Equality ignores coordinates so
/// token streams compare by content across frontends.
#[derive(Debug, Clone)]
pub struct Tok {
    pub kind: TokKind,
    pub joint: bool,
    pub line: usize,
    pub col: usize,
}

impl PartialEq for Tok {
    fn eq(&self, other: &Self) -> bool {
        self.kind == other.kind && self.joint == other.joint
    }
}

impl Eq for Tok {}

impl Tok {
    pub(crate) fn fresh(kind: TokKind, joint: bool) -> Self {
        Self {
            kind,
            joint,
            line: 0,
            col: 0,
        }
    }

    pub(crate) fn at(kind: TokKind, joint: bool, line: usize, col: usize) -> Self {
        Self {
            kind,
            joint,
            line,
            col,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LexError {
    pub line: usize,
    pub col: usize,
    pub msg: String,
    /// Machine-readable kind when the lexer knows it (an unclosed
    /// `WITH_IO` bracket is that command's syntax error, never a bare
    /// grammar failure); `None` means a plain syntax failure.
    pub kind: Option<ParseErrorKind>,
}

impl fmt::Display for LexError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "lex error at {}:{}: {}", self.line, self.col, self.msg)
    }
}

impl std::error::Error for LexError {}

/// Keywords that open a `{...}` block head (`IF`, `WHILE`, ...).
/// The unclosed-group diagnostic names the first unsatisfied one so
/// fragmented blocks blame their opener, never the enclosing head.
fn is_block_head(w: &str) -> bool {
    matches!(
        w,
        KEYWORD_IF
            | KEYWORD_ELSE
            | KEYWORD_FOR
            | KEYWORD_WHILE
            | KEYWORD_FUNC
            | KEYWORD_TIMEOUT
            | KEYWORD_ISOLATED
            | KEYWORD_ASYNC
            | KEYWORD_REMOTE
            | KEYWORD_WITH_IO
    )
}

/// True for template placeholders (`{{ .. }}` lex as a brace group
/// holding a brace group).
fn is_template_group(t: &Tok) -> bool {
    if let TokKind::Group {
        delim: GroupDelim::Brace,
        inner,
        ..
    } = &t.kind
    {
        matches!(
            inner.first().map(|f| &f.kind),
            Some(TokKind::Group {
                delim: GroupDelim::Brace,
                ..
            })
        )
    } else {
        false
    }
}

/// Chars that always delimit words in string sources. The set mirrors
/// `rustc` tokenization so both frontends emit identical streams:
/// operators and structural chars split in both (`--flag` arrives as
/// `-`, `-`, `flag` with joint flags; the parser backend reassembles
/// payloads losslessly). `.` splits too (`a.b`, `1.0.0`); `~` and
/// backtick stay word chars (`rustc` rejects them, so they are
/// string-pathway-only by construction, like raw-`"` blocks).
fn is_delim(c: char) -> bool {
    matches!(
        c,
        '"' | '\''
            | '$'
            | ':'
            | ','
            | '='
            | '!'
            | '<'
            | '>'
            | '+'
            | '-'
            | '*'
            | '/'
            | '%'
            | '.'
            | '?'
            | '^'
            | '('
            | ')'
            | '['
            | ']'
            | '{'
            | '}'
            | ';'
            | '#'
            | '|'
            | '&'
            | '@'
    )
}

/// Scan one string literal at the head of `s` (which must start with
/// `"`, `'`, or `"""`), mirroring the `quoted_string` / `block_string`
/// pest rules. Returns the token kind plus bytes consumed.
fn scan_string(s: &str) -> Result<(TokKind, usize), String> {
    if s.starts_with("\"\"\"") {
        let mut end = 3;
        while end < s.len() {
            if s[end..].starts_with('\\') {
                let next_len = s[end + 1..]
                    .chars()
                    .next()
                    .map(|c| c.len_utf8())
                    .unwrap_or(0);
                if next_len == 0 {
                    return Err("trailing backslash in block string".to_string());
                }
                end += 1 + next_len;
                continue;
            }
            if s[end..].starts_with("\"\"\"") {
                end += 3;
                return Ok((TokKind::BlockStr(s[..end].to_string()), end));
            }
            end += s[end..].chars().next().map(|c| c.len_utf8()).unwrap_or(1);
        }
        return Err("unterminated block string".to_string());
    }
    let quote = s.as_bytes()[0] as char;
    if quote != '"' && quote != '\'' {
        return Err("string must open with a quote".to_string());
    }
    let mut end = 1;
    while end < s.len() {
        let rest = &s[end..];
        let c = rest.chars().next().unwrap();
        if c == '\\' {
            // An escape pair is atomic: skip the backslash plus
            // whatever follows (matching the block-string arm and
            // `lex_word`). Skipping only before the quote char
            // misreads `"a\\"` as unterminated: the second
            // backslash would escape the closing quote.
            let mut it = rest.chars();
            it.next();
            match it.next() {
                Some(n) => end += 1 + n.len_utf8(),
                None => end += 1,
            }
            continue;
        }
        if c == quote {
            end += c.len_utf8();
            return Ok((
                TokKind::Str {
                    text: s[1..end - 1].to_string(),
                    quote,
                },
                end,
            ));
        }
        end += c.len_utf8();
    }
    Err("unterminated string".to_string())
}

/// Lex one or more adjacent string spellings (the fused `TokenStream`
/// shreds, or a single literal): `""".."""` reads as one
/// [`TokKind::BlockStr`], `"a""b"` as two [`TokKind::Str`]. The first
/// token inherits `joint`; later ones are always joint (no gap inside a
/// spelling). Only the `TokenStream` frontend needs multi-spelling
/// input; the string lexer calls [`scan_string`] directly.
#[cfg(feature = "proc-macro-api")]
fn lex_string_spelling(s: &str, joint: bool) -> Result<Vec<Tok>, String> {
    let mut out = Vec::new();
    let mut rest = s;
    let mut first = true;
    while !rest.is_empty() {
        let (kind, used) = scan_string(rest)?;
        out.push(Tok::fresh(kind, if first { joint } else { true }));
        first = false;
        rest = &rest[used..];
    }
    if out.is_empty() {
        return Err("empty string spelling".to_string());
    }
    Ok(out)
}

/// A `'` opens a string where a gap precedes it (`= 'hi'`, `['a']`);
/// inside a payload word (`coverage's`) it stays a literal char. The
/// top-level lexer tracks this via its gap flag; group scanning uses
/// the raw text before the quote for the same decision.
fn quote_opens_before(src: &str) -> bool {
    src.chars()
        .rev()
        .find(|c| !c.is_whitespace())
        .map(|c| {
            matches!(
                c,
                '[' | '(' | '{' | ',' | ':' | '=' | '$' | '!' | '<' | '>' | '|' | '&'
            )
        })
        .unwrap_or(true)
}

struct StrLexer<'a> {
    src: &'a str,
    pos: usize,
    line: usize,
    col: usize,
    out: Vec<Tok>,
    /// Top-level words with their source lines, plus the output length
    /// when pushed. Unclosed-group errors scan this for the block head
    /// whose opener never closed (issue #215's "unclosed `IF` block
    /// opened on line N" naming, without grammar internals).
    heads: Vec<(String, usize, usize)>,
    /// Start coordinates of the token currently being scanned, captured
    /// at token begin and stamped by `push`. The main loop marks every
    /// iteration (each scans exactly one token); group interiors inherit
    /// absolute positions from a seeded child lexer instead.
    mark_line: usize,
    mark_col: usize,
    /// True when a gap (space, tab, comment, newline, `;`) precedes the
    /// next token. Reset after each emitted token.
    gapped: bool,
}

impl<'a> StrLexer<'a> {
    fn new(src: &'a str) -> Self {
        Self::with_start(src, 1, 1)
    }

    /// Child lexer over group-interior text starting at an absolute
    /// position (just past the opener): interior tokens and errors
    /// come out absolute, so no remapping is needed downstream.
    fn with_start(src: &'a str, line: usize, col: usize) -> Self {
        Self {
            src,
            pos: 0,
            line,
            col,
            out: Vec::new(),
            heads: Vec::new(),
            mark_line: 0,
            mark_col: 0,
            gapped: true,
        }
    }

    fn err(&self, msg: impl Into<String>) -> LexError {
        LexError {
            line: self.line,
            col: self.col,
            msg: msg.into(),
            kind: None,
        }
    }

    fn rest(&self) -> &'a str {
        &self.src[self.pos..]
    }

    fn bump(&mut self, n: usize, newlines: usize) {
        self.pos += n;
        if newlines > 0 {
            self.line += newlines;
            self.col = 1;
        } else {
            self.col += n;
        }
    }

    fn push(&mut self, kind: TokKind) {
        let joint = !self.gapped;
        self.gapped = false;
        if let TokKind::Word(w) = &kind {
            self.heads.push((w.clone(), self.line, self.out.len()));
        }
        let (line, col) = (self.mark_line, self.mark_col);
        self.out.push(Tok::at(kind, joint, line, col));
    }

    /// Block-head keyword whose `{...}` never closed: the first head
    /// word with no balanced brace group after it (a head whose block
    /// closed is satisfied, like `IF` in `IF {..} ELSE {..}`; other
    /// groups such as `[...]` lists never satisfy). Returns the head
    /// and its opener line for the unclosed-block diagnostic.
    fn unclosed_head(&self) -> Option<(String, usize)> {
        for (word, line, idx) in &self.heads {
            if !is_block_head(word) {
                continue;
            }
            // Templates (`{{ .. }}`, a brace group holding a brace
            // group) never satisfy: only real blocks close a head.
            let satisfied = self.out[*idx..].iter().any(|t| {
                matches!(
                    &t.kind,
                    TokKind::Group {
                        delim: GroupDelim::Brace,
                        ..
                    }
                ) && !is_template_group(t)
            });
            if !satisfied {
                return Some((word.clone(), *line));
            }
        }
        None
    }

    /// True when only whitespace precedes on this line (comment position).
    fn at_line_start(&self) -> bool {
        let line_start = self.src[..self.pos].rfind('\n').map(|i| i + 1).unwrap_or(0);
        self.src[line_start..self.pos]
            .chars()
            .all(|c| c == ' ' || c == '\t' || c == '\r')
    }

    fn lex_word(&mut self) {
        let mut word = String::new();
        while self.pos < self.src.len() {
            let rest = self.rest();
            let c = rest.chars().next().unwrap();
            if c == '\\' {
                let mut it = rest.chars();
                it.next();
                match it.next() {
                    Some(n) => {
                        word.push('\\');
                        word.push(n);
                        self.bump(1 + n.len_utf8(), 0);
                    }
                    None => {
                        word.push('\\');
                        self.bump(1, 0);
                    }
                }
                continue;
            }
            if c.is_whitespace() || is_delim(c) {
                break;
            }
            word.push(c);
            self.bump(c.len_utf8(), 0);
        }
        self.push(TokKind::Word(word));
    }

    /// Scan a delimited group, copying its raw inner text (with `"..."`
    /// and `'...'` regions protected so brackets inside strings never
    /// affect nesting) and re-lexing it recursively. Edge gaps are
    /// positional: `open_joint` is false when whitespace follows the
    /// opener, `close_joint` is false when it precedes the closer.
    fn lex_group(&mut self, close: char, delim: GroupDelim) -> Result<(), LexError> {
        let (start_line, start_col) = (self.line, self.col);
        self.bump(1, 0);
        let open_joint = !self.rest().starts_with([' ', '\t', '\r', '\n']);
        let mut stack: Vec<char> = Vec::new();
        let mut inner_src = String::new();
        while self.pos < self.src.len() {
            let rest = self.rest();
            let c = rest.chars().next().unwrap();
            if c == '"' || (c == '\'' && quote_opens_before(&inner_src)) {
                let (kind, used) = scan_string(rest).map_err(|m| self.err(m))?;
                match kind {
                    TokKind::Str { text, quote } => {
                        inner_src.push(quote);
                        inner_src.push_str(&text);
                        inner_src.push(quote);
                    }
                    TokKind::BlockStr(full) => inner_src.push_str(&full),
                    _ => unreachable!(),
                }
                let newlines = rest[..used].matches('\n').count();
                self.bump(used, newlines);
                continue;
            }
            if c == '[' || c == '(' || c == '{' {
                stack.push(c);
            } else if c == '/' && (rest.starts_with("//") || rest.starts_with("/*")) {
                // Comments never nest groups (`// {` stays text like
                // the grammar): copy through the comment terminator
                // verbatim for the recursive re-lex.
                if rest.starts_with("//") {
                    inner_src.push_str("//");
                    let mut k = 2;
                    while k < rest.len() {
                        let ch = rest[k..].chars().next().unwrap();
                        if ch == '\n' || ch == '\r' {
                            break;
                        }
                        // A closer at nesting depth zero ends the
                        // comment copy: `//` runs to end of line,
                        // and inside a group the closer is never
                        // past a newline (`[a //c]` closes here,
                        // like the grammar's literal reading).
                        if ch == close && stack.is_empty() {
                            break;
                        }
                        inner_src.push(ch);
                        k += ch.len_utf8();
                    }
                    self.bump(k, 0);
                    continue;
                }
                inner_src.push_str("/*");
                self.bump(2, 0);
                let mut k = 2;
                let mut depth = 1usize;
                while k < rest.len() && depth > 0 {
                    if rest[k..].starts_with("/*") {
                        depth += 1;
                        inner_src.push_str("/*");
                        self.bump(2, 0);
                        k += 2;
                    } else if rest[k..].starts_with("*/") {
                        depth -= 1;
                        inner_src.push_str("*/");
                        self.bump(2, 0);
                        k += 2;
                    } else {
                        let ch = rest[k..].chars().next().unwrap();
                        // A depth-zero closer ends the copy even when no
                        // `*/` has closed the span (`[a /* c]` closes
                        // here, the old literal reading; the splice
                        // re-adds the closer downstream, so bytes stay
                        // exact).
                        if ch == close && stack.is_empty() {
                            break;
                        }
                        if ch == '\r' && rest[k..].starts_with("\r\n") {
                            inner_src.push('\n');
                            self.bump(2, 1);
                            k += 2;
                        } else {
                            inner_src.push(ch);
                            let nl = usize::from(ch == '\n');
                            self.bump(ch.len_utf8(), nl);
                            k += ch.len_utf8();
                        }
                    }
                }
                continue;
            } else if c == ']' || c == ')' || c == '}' {
                if c == close && stack.is_empty() {
                    let close_joint = !matches!(
                        self.src[..self.pos].chars().next_back(),
                        Some(' ' | '\t' | '\r' | '\n')
                    );
                    self.bump(c.len_utf8(), 0);
                    // Interior text starts just past the opener, so a
                    // child lexer seeded there yields absolute
                    // coordinates for interior tokens and errors alike
                    // (no remapping downstream).
                    let mut child = StrLexer::with_start(&inner_src, start_line, start_col + 1);
                    child.run()?;
                    let mut inner = child.out;
                    if open_joint
                        && let Some(first) = inner.first()
                        && !matches!(
                            first.kind,
                            TokKind::Newline | TokKind::Semicolon | TokKind::Comment(_)
                        )
                    {
                        inner[0].joint = true;
                    }
                    self.push(TokKind::Group {
                        delim,
                        inner,
                        open_joint,
                        close_joint,
                    });
                    return Ok(());
                }
                if stack.pop().is_none() {
                    return Err(self.err(format!("unmatched `{c}`")));
                }
            }
            if c == '\r' && rest.starts_with("\r\n") {
                inner_src.push('\n');
                self.bump(2, 1);
                continue;
            }
            if c == '\n' || c == '\r' {
                inner_src.push('\n');
                self.bump(c.len_utf8(), 1);
                continue;
            }
            inner_src.push(c);
            self.bump(c.len_utf8(), 0);
        }
        // Fragmented blocks blame their opener past the head (never
        // the enclosing head, never a grammar dump): the first
        // unsatisfied block head names the message; anything else
        // reports the opener position. The EOF position lands the
        // span past every head line.
        let (msg, kind) = match (delim, self.unclosed_head()) {
            (GroupDelim::Brace, Some((head, opened))) => (
                format!("unclosed `{head}` block opened on line {opened}"),
                None,
            ),
            // An unclosed `WITH_IO` bracket is that command's syntax
            // error (never unknown): it names the missing closer.
            (GroupDelim::Bracket, Some((head, opened))) if head == KEYWORD_WITH_IO => (
                format!("{KEYWORD_WITH_IO} bindings missing closing `]` (opened on line {opened})"),
                Some(ParseErrorKind::InvalidSyntax {
                    command: KEYWORD_WITH_IO.to_string(),
                }),
            ),
            _ => (format!("unclosed group, expected `{close}`"), None),
        };
        Err(LexError {
            line: self.line,
            col: self.col,
            msg,
            kind,
        })
    }

    fn skip_line_comment(&mut self) -> String {
        let start = self.pos;
        while self.pos < self.src.len() {
            let c = self.rest().chars().next().unwrap();
            if c == '\n' || c == '\r' {
                break;
            }
            self.bump(c.len_utf8(), 0);
        }
        self.src[start..self.pos].to_string()
    }

    fn skip_block_comment(&mut self) -> Result<String, LexError> {
        let start = self.pos;
        self.bump(2, 0);
        let mut depth = 1usize;
        while self.pos < self.src.len() {
            let rest = self.rest();
            if rest.starts_with("/*") {
                depth += 1;
                self.bump(2, 0);
            } else if rest.starts_with("*/") {
                depth -= 1;
                self.bump(2, 0);
                if depth == 0 {
                    self.gapped = true;
                    return Ok(self.src[start..self.pos].to_string());
                }
            } else {
                let c = rest.chars().next().unwrap();
                if c == '\r' && rest.starts_with("\r\n") {
                    self.bump(2, 1);
                } else if c == '\n' || c == '\r' {
                    self.bump(c.len_utf8(), 1);
                } else {
                    self.bump(c.len_utf8(), 0);
                }
            }
        }
        Err(self.err("unclosed block comment"))
    }

    fn run(&mut self) -> Result<(), LexError> {
        while self.pos < self.src.len() {
            let rest = self.rest();
            let c = rest.chars().next().unwrap();
            // Every iteration scans exactly one token: record its start
            // coordinates for the positioned emits below (`push` reads
            // the same marks; group interiors are seeded absolute).
            self.mark_line = self.line;
            self.mark_col = self.col;
            match c {
                ' ' | '\t' => {
                    self.bump(c.len_utf8(), 0);
                    self.gapped = true;
                }
                '\r' if rest.starts_with("\r\n") => {
                    self.bump(2, 1);
                    self.out.push(Tok::at(
                        TokKind::Newline,
                        false,
                        self.mark_line,
                        self.mark_col,
                    ));
                    self.gapped = true;
                }
                '\n' | '\r' => {
                    self.bump(c.len_utf8(), 1);
                    self.out.push(Tok::at(
                        TokKind::Newline,
                        false,
                        self.mark_line,
                        self.mark_col,
                    ));
                    self.gapped = true;
                }
                ';' => {
                    self.bump(1, 0);
                    self.out.push(Tok::at(
                        TokKind::Semicolon,
                        false,
                        self.mark_line,
                        self.mark_col,
                    ));
                    self.gapped = true;
                }
                // `//` opens a comment anywhere (line comment to end
                // of line, like the grammar): line starts emit the
                // marker for the splitter; mid-line markers let raw
                // runs type them as literals and gap positions skip
                // them, exactly like the grammar's dual reading.
                // (`#` and `/*` stay payload mid-line: `#` is arg text
                // there, `/*` reads as math operators.)
                '/' if rest.starts_with("//") && self.at_line_start() => {
                    let text = self.skip_line_comment();
                    self.out.push(Tok::at(
                        TokKind::Comment(text),
                        false,
                        self.mark_line,
                        self.mark_col,
                    ));
                    self.gapped = true;
                }
                '/' if rest.starts_with("//") => {
                    let text = self.skip_line_comment();
                    let joint = !self.gapped;
                    self.out.push(Tok::at(
                        TokKind::Comment(text),
                        joint,
                        self.mark_line,
                        self.mark_col,
                    ));
                    self.gapped = false;
                }
                '/' if rest.starts_with("/*") && self.at_line_start() => {
                    let text = self.skip_block_comment()?;
                    self.out.push(Tok::at(
                        TokKind::Comment(text),
                        false,
                        self.mark_line,
                        self.mark_col,
                    ));
                }
                '#' if self.at_line_start() => {
                    let text = self.skip_line_comment();
                    self.out.push(Tok::at(
                        TokKind::Comment(text),
                        false,
                        self.mark_line,
                        self.mark_col,
                    ));
                    self.gapped = true;
                }
                '"' => {
                    let joint = !self.gapped;
                    let (kind, used) = scan_string(rest).map_err(|m| self.err(m))?;
                    let newlines = rest[..used].matches('\n').count();
                    self.bump(used, newlines);
                    self.gapped = false;
                    self.out
                        .push(Tok::at(kind, joint, self.mark_line, self.mark_col));
                }
                '\'' if self.gapped => {
                    let joint = !self.gapped;
                    match scan_string(rest) {
                        Ok((kind, used)) => {
                            let newlines = rest[..used].matches('\n').count();
                            self.bump(used, newlines);
                            self.gapped = false;
                            self.out
                                .push(Tok::at(kind, joint, self.mark_line, self.mark_col));
                        }
                        // Lone `'` (lifetimes, apostrophes): matches the
                        // `TokenStream` shape (`'` punct + word) instead
                        // of failing where `rustc` would not.
                        Err(_) => {
                            self.bump(1, 0);
                            self.push(TokKind::Punct('\''));
                        }
                    }
                }
                '[' => self.lex_group(']', GroupDelim::Bracket)?,
                '(' => self.lex_group(')', GroupDelim::Paren)?,
                '{' => self.lex_group('}', GroupDelim::Brace)?,
                ']' | ')' | '}' => {
                    return Err(self.err(format!("unmatched `{c}`")));
                }
                _ if is_delim(c) => {
                    self.bump(c.len_utf8(), 0);
                    self.push(TokKind::Punct(c));
                }
                _ => self.lex_word(),
            }
        }
        Ok(())
    }
}

fn lex_str_inner(s: &str) -> Result<Vec<Tok>, LexError> {
    let mut lx = StrLexer::new(s);
    lx.run()?;
    Ok(lx.out)
}

/// Lex a string source into context-free tokens. Newlines normalize to
/// [`TokKind::Newline`] (one per line break); statement-level `//`,
/// `/* */`, and whole-line `#` comments emit [`TokKind::Comment`]
/// markers (the newline itself still emits).
pub fn lex_str(s: &str) -> Result<Vec<Tok>, LexError> {
    lex_str_inner(s)
}

/// Lex a `TokenStream` into the same context-free tokens. Newlines come
/// from span positions only (one per line advanced, inside groups too);
/// no syntax is consulted. Span-adjacent string shreds fuse back to
/// source spelling before `lex_string_spelling`; degenerate
/// (zero-width, e.g. `quote!`) spans carry no adjacency signal, so
/// literals there take the spaced reading.
#[cfg(feature = "proc-macro-api")]
pub fn lex_tokens(ts: &proc_macro2::TokenStream) -> Result<Vec<Tok>, LexError> {
    use proc_macro2::{Delimiter, Spacing, TokenTree};

    struct Walker {
        out: Vec<Tok>,
        gapped: bool,
        prev_end: Option<proc_macro2::LineColumn>,
        prev_joint: bool,
        /// Fused raw spellings of an adjacent string-literal run plus
        /// the joint flag of its first piece.
        pending_str: Option<(String, bool)>,
        /// Start coordinates of the token currently being scanned
        /// (1-based; `0` means unknown). Set by `note_position` from
        /// each token's own span; degenerate spans record `(0, 0)`.
        mark_line: usize,
        mark_col: usize,
    }

    impl Walker {
        fn new() -> Self {
            Self {
                out: Vec::new(),
                gapped: true,
                prev_end: None,
                prev_joint: false,
                pending_str: None,
                mark_line: 0,
                mark_col: 0,
            }
        }

        /// Positional only: newlines from line advances, adjacency from
        /// span equality (or joint spacing). Degenerate spans reset to
        /// gapped: they carry no position signal.
        fn note_position(&mut self, start: proc_macro2::LineColumn, end: proc_macro2::LineColumn) {
            if start == end {
                self.gapped = true;
                self.mark_line = 0;
                self.mark_col = 0;
            } else {
                match self.prev_end {
                    None => self.gapped = true,
                    Some(prev) => {
                        if start.line > prev.line {
                            for i in 0..(start.line - prev.line) {
                                // Newlines terminate the lines being left;
                                // columns are unknowable here, so only the
                                // line is recorded (`0` col = unknown).
                                self.out
                                    .push(Tok::at(TokKind::Newline, false, prev.line + i, 0));
                            }
                            self.gapped = true;
                        } else {
                            self.gapped = !(prev == start || self.prev_joint);
                        }
                    }
                }
                // proc_macro2 columns are 0-based byte offsets; toks are
                // 1-based.
                self.mark_line = start.line;
                self.mark_col = start.column + 1;
            }
            self.prev_end = Some(end);
            self.prev_joint = false;
        }

        fn flush_str(&mut self) -> Result<(), LexError> {
            if let Some((raw, joint)) = self.pending_str.take() {
                let toks = lex_string_spelling(&raw, joint).map_err(|m| LexError {
                    line: 0,
                    col: 0,
                    msg: m,
                    kind: None,
                })?;
                self.out.extend(toks);
            }
            Ok(())
        }

        fn push(&mut self, kind: TokKind) {
            let joint = !self.gapped;
            self.gapped = false;
            self.out
                .push(Tok::at(kind, joint, self.mark_line, self.mark_col));
        }

        fn walk_stream(&mut self, ts: &proc_macro2::TokenStream) -> Result<(), LexError> {
            let trees: Vec<TokenTree> = ts.clone().into_iter().collect();
            self.walk_trees(&trees)
        }

        fn walk_trees(&mut self, trees: &[TokenTree]) -> Result<(), LexError> {
            for tt in trees {
                match tt {
                    TokenTree::Group(g) => {
                        let (start, end) = (g.span().start(), g.span().end());
                        self.flush_str()?;
                        self.note_position(start, end);
                        let mut inner = Walker::new();
                        inner.walk_stream(&g.stream())?;
                        inner.flush_str()?;
                        // Edge gaps are positional: the opener sits at the
                        // group start (one column wide), the closer just
                        // before the group end. Degenerate spans report a
                        // gap (spaced reading, like string lexing).
                        let inner_trees: Vec<TokenTree> = g.stream().into_iter().collect();
                        let open_joint = inner_trees.first().is_some_and(|first| {
                            let s = first.span().start();
                            s.line == start.line && s.column == start.column + 1
                        }) || inner_trees.is_empty();
                        let close_joint = inner_trees.last().is_some_and(|last| {
                            let e = last.span().end();
                            e.line == end.line && e.column + 1 == end.column
                        }) || inner_trees.is_empty();
                        if open_joint
                            && let Some(idx) = inner.out.iter().position(|t| {
                                !matches!(t.kind, TokKind::Newline | TokKind::Semicolon)
                            })
                        {
                            inner.out[idx].joint = true;
                        }
                        let mut group = |delim| TokKind::Group {
                            delim,
                            inner: std::mem::take(&mut inner.out),
                            open_joint,
                            close_joint,
                        };
                        match g.delimiter() {
                            Delimiter::Parenthesis => self.push(group(GroupDelim::Paren)),
                            Delimiter::Bracket => self.push(group(GroupDelim::Bracket)),
                            Delimiter::Brace => self.push(group(GroupDelim::Brace)),
                            // Transparent: splice contents through.
                            Delimiter::None => {
                                for mut t in inner.out {
                                    if matches!(t.kind, TokKind::Newline | TokKind::Semicolon) {
                                        self.out.push(t);
                                        self.gapped = true;
                                    } else {
                                        t.joint = false;
                                        self.out.push(t);
                                        self.gapped = false;
                                    }
                                }
                            }
                        }
                    }
                    TokenTree::Ident(ident) => {
                        let (start, end) = (ident.span().start(), ident.span().end());
                        self.flush_str()?;
                        self.note_position(start, end);
                        self.push(TokKind::Word(ident.to_string()));
                    }
                    TokenTree::Literal(lit) => {
                        let (start, end) = (lit.span().start(), lit.span().end());
                        let spelling = lit.to_string();
                        let stringy = spelling.starts_with('"') || spelling.starts_with('\'');
                        if stringy
                            && start != end
                            && self.prev_end.map(|p| p == start).unwrap_or(false)
                        {
                            // Shredded `"""` run (or `"a""b"`): fuse raw.
                            let raw = match self.pending_str.take() {
                                Some((mut raw, joint)) => {
                                    raw.push_str(&spelling);
                                    (raw, joint)
                                }
                                None => (spelling, false),
                            };
                            self.pending_str = Some(raw);
                            self.prev_end = Some(end);
                            self.prev_joint = false;
                            continue;
                        }
                        self.flush_str()?;
                        self.note_position(start, end);
                        if stringy {
                            let joint = !self.gapped;
                            self.pending_str = Some((spelling, joint));
                            self.gapped = false;
                        } else {
                            self.push(TokKind::Word(spelling));
                        }
                    }
                    TokenTree::Punct(p) => {
                        let (start, end) = (p.span().start(), p.span().end());
                        let ch = p.as_char();
                        self.flush_str()?;
                        self.note_position(start, end);
                        if ch == ';' {
                            self.out.push(Tok::at(
                                TokKind::Semicolon,
                                false,
                                self.mark_line,
                                self.mark_col,
                            ));
                            self.gapped = true;
                        } else {
                            self.push(TokKind::Punct(ch));
                        }
                        if p.spacing() == Spacing::Joint {
                            self.prev_joint = true;
                            self.gapped = false;
                        }
                    }
                }
            }
            Ok(())
        }
    }

    let mut w = Walker::new();
    w.walk_stream(ts)?;
    w.flush_str()?;
    Ok(w.out)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn w(s: &str) -> Tok {
        Tok::fresh(TokKind::Word(s.to_string()), false)
    }

    fn wj(s: &str) -> Tok {
        Tok::fresh(TokKind::Word(s.to_string()), true)
    }

    fn punct(c: char) -> Tok {
        Tok::fresh(TokKind::Punct(c), false)
    }

    fn punctj(c: char) -> Tok {
        Tok::fresh(TokKind::Punct(c), true)
    }

    fn str_tok(s: &str) -> Tok {
        str_tok_q(s, '"')
    }

    fn str_tok_q(s: &str, quote: char) -> Tok {
        Tok::fresh(
            TokKind::Str {
                text: s.to_string(),
                quote,
            },
            false,
        )
    }

    fn block_tok(s: &str) -> Tok {
        Tok::fresh(TokKind::BlockStr(s.to_string()), false)
    }

    fn nl() -> Tok {
        Tok::fresh(TokKind::Newline, false)
    }

    fn comment(s: &str) -> Tok {
        Tok::fresh(TokKind::Comment(s.to_string()), false)
    }

    fn semi() -> Tok {
        Tok::fresh(TokKind::Semicolon, false)
    }

    /// Both frontends must emit identical streams for the same source.
    /// `TokenStream` parsing normalizes `\r\n` to `\n`, so inputs here
    /// use `\n` only.
    #[cfg(feature = "proc-macro-api")]
    fn assert_both(text: &str, expected: Vec<Tok>) {
        let from_str = lex_str(text).expect("string lex must succeed");
        assert_eq!(from_str, expected, "string lexer mismatch for {text:?}");
        let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
        let from_tokens = lex_tokens(&ts).expect("token lex must succeed");
        assert_eq!(
            from_tokens, expected,
            "token lexer mismatch for {text:?}\nstring: {from_str:?}"
        );
    }

    #[test]
    fn lex_simple_command() {
        let toks = lex_str("ECHO hi").unwrap();
        assert_eq!(toks, vec![w("ECHO"), w("hi")]);
    }

    #[test]
    fn lex_newlines_and_semicolons() {
        let toks = lex_str("ECHO hi\nWRITE x").unwrap();
        assert_eq!(toks, vec![w("ECHO"), w("hi"), nl(), w("WRITE"), w("x")]);
        let toks = lex_str("ECHO hi; WRITE x").unwrap();
        assert_eq!(toks, vec![w("ECHO"), w("hi"), semi(), w("WRITE"), w("x")]);
    }

    #[test]
    fn lex_operators_are_positional() {
        let toks = lex_str("LET $x: INT = $a == 1").unwrap();
        assert_eq!(
            toks,
            vec![
                w("LET"),
                punct('$'),
                wj("x"),
                punctj(':'),
                w("INT"),
                punct('='),
                punct('$'),
                wj("a"),
                punct('='),
                punctj('='),
                w("1"),
            ]
        );
    }

    #[test]
    fn lex_strings_verbatim() {
        let toks = lex_str("ECHO \"a\\nb\"").unwrap();
        assert_eq!(toks, vec![w("ECHO"), str_tok("a\\nb")]);
        let toks = lex_str("ECHO 'hi'").unwrap();
        assert_eq!(toks, vec![w("ECHO"), str_tok_q("hi", '\'')]);
    }

    #[test]
    fn lex_block_string_atomic() {
        let toks = lex_str("ECHO \"\"\"hi\"\"\"").unwrap();
        assert_eq!(toks, vec![w("ECHO"), block_tok("\"\"\"hi\"\"\"")]);
    }

    #[test]
    fn lex_groups_nest() {
        let toks = lex_str("[env:X] ECHO hi").unwrap();
        assert_eq!(
            toks,
            vec![
                Tok::fresh(
                    TokKind::Group {
                        delim: GroupDelim::Bracket,
                        inner: vec![wj("env"), punctj(':'), wj("X")],
                        open_joint: true,
                        close_joint: true,
                    },
                    false,
                ),
                w("ECHO"),
                w("hi"),
            ]
        );
    }

    #[test]
    fn lex_comments_emit_markers_but_newline_stays() {
        let toks = lex_str("// hello\nECHO hi").unwrap();
        assert_eq!(toks, vec![comment("// hello"), nl(), w("ECHO"), w("hi")]);
        // Mid-line `//` marks too (jointness preserved for run
        // gluing); mid-line `/* */` is payload text, not a comment:
        // comments are statement-level (line start) only, matching
        // the grammar's dual reading.
        let toks = lex_str("ECHO hi //c").unwrap();
        assert_eq!(toks, vec![w("ECHO"), w("hi"), comment("//c")]);
        let toks = lex_str("ECHO a//b").unwrap();
        assert_eq!(
            toks,
            vec![
                w("ECHO"),
                w("a"),
                Tok::fresh(TokKind::Comment("//b".to_string()), true),
            ]
        );
        let toks = lex_str("ECHO hi /* mid */").unwrap();
        assert_eq!(
            toks,
            vec![
                w("ECHO"),
                w("hi"),
                punct('/'),
                punctj('*'),
                w("mid"),
                punct('*'),
                punctj('/'),
            ]
        );
    }

    #[test]
    fn lex_splits_where_rustc_splits() {
        // Operators split in both frontends (joint flags keep payloads
        // reassemblable in the parser); only `10s`-style alphanumerics
        // stay whole.
        let toks = lex_str("RUN echo --flag a/b 10s 1.0.0").unwrap();
        assert_eq!(
            toks,
            vec![
                w("RUN"),
                w("echo"),
                punct('-'),
                punctj('-'),
                wj("flag"),
                w("a"),
                punctj('/'),
                wj("b"),
                w("10s"),
                w("1"),
                punctj('.'),
                wj("0"),
                punctj('.'),
                wj("0"),
            ]
        );
    }

    #[test]
    fn lex_crlf_normalizes() {
        let toks = lex_str("ECHO hi\r\nWRITE x").unwrap();
        assert_eq!(toks, vec![w("ECHO"), w("hi"), nl(), w("WRITE"), w("x")]);
    }

    #[test]
    fn lex_unclosed_group_errors() {
        assert!(lex_str("ECHO [hi").is_err());
        assert!(lex_str("ECHO \"hi").is_err());
    }

    #[cfg(feature = "proc-macro-api")]
    #[test]
    fn both_frontends_agree_on_commands() {
        assert_both("ECHO hi", vec![w("ECHO"), w("hi")]);
        assert_both(
            "ECHO hi\nWRITE x",
            vec![w("ECHO"), w("hi"), nl(), w("WRITE"), w("x")],
        );
        assert_both(
            "[env:X] ECHO hi",
            vec![
                Tok::fresh(
                    TokKind::Group {
                        delim: GroupDelim::Bracket,
                        inner: vec![wj("env"), punctj(':'), wj("X")],
                        open_joint: true,
                        close_joint: true,
                    },
                    false,
                ),
                w("ECHO"),
                w("hi"),
            ],
        );
    }

    #[cfg(feature = "proc-macro-api")]
    #[test]
    fn both_frontends_agree_on_exprs() {
        assert_both(
            "LET $x: INT = $a + $b",
            vec![
                w("LET"),
                punct('$'),
                wj("x"),
                punctj(':'),
                w("INT"),
                punct('='),
                punct('$'),
                wj("a"),
                punct('+'),
                punct('$'),
                wj("b"),
            ],
        );
    }

    #[cfg(feature = "proc-macro-api")]
    #[test]
    fn both_frontends_fuse_block_strings() {
        assert_both(
            "ECHO \"\"\"hi\"\"\"",
            vec![w("ECHO"), block_tok("\"\"\"hi\"\"\"")],
        );
    }

    #[cfg(feature = "proc-macro-api")]
    #[test]
    fn degenerate_spans_take_spaced_reading() {
        let ts = quote::quote! { ECHO "a" "b" };
        let toks = lex_tokens(&ts).expect("degenerate lex must succeed");
        let strs: Vec<_> = toks
            .iter()
            .filter(|t| matches!(t.kind, TokKind::Str { .. }))
            .collect();
        assert_eq!(strs.len(), 2, "synthetic spans must not fuse: {toks:?}");
    }
}