Skip to main content

oxdock_parser/
tok.rs

1//! Shared token model for the unified parser backend.
2//!
3//! Two context-free lexers emit [`Tok`]: [`lex_str`] for string sources
4//! and `lex_tokens` (behind `proc-macro-api`) for `TokenStream`.
5//! Both are positional only: they record gap adjacency (`joint`) and
6//! literal newlines, but never decide statement boundaries. Whether a
7//! newline ends a statement (or a `[` opens a guard vs. args, or a word
8//! continues a wrapper) is grammar state, so it lives in the parser
9//! backend, never here.
10//!
11//! String semantics are single-sourced in `lex_string_spelling`: the
12//! `TokenStream` frontend fuses span-adjacent shredded literals back to
13//! their source spelling (`""` + `"hi"` + `""` is `"""hi"""`) and runs
14//! the same scanner. Contents stay verbatim (escapes expand at runtime
15//! `expand_string`, matching `parse_quoted_string`); `"""` bodies lower
16//! later through the shared `lower_block_string`.
17
18use crate::constants::{
19    KEYWORD_ASYNC, KEYWORD_CASE, KEYWORD_DEFAULT, KEYWORD_ELSE, KEYWORD_FOR, KEYWORD_FUNC,
20    KEYWORD_IF, KEYWORD_ISOLATED, KEYWORD_REMOTE, KEYWORD_SWITCH, KEYWORD_TIMEOUT, KEYWORD_WHILE,
21    KEYWORD_WITH_IO,
22};
23use crate::error::ParseErrorKind;
24use std::fmt;
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum GroupDelim {
28    Bracket,
29    Paren,
30    Brace,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum TokKind {
35    /// Bare word: commands, keywords, numbers-as-spelled, paths, flags.
36    /// Any run of non-delimiter chars; never contains whitespace.
37    Word(String),
38    /// Verbatim inner of `"..."` / `'...'` (escapes intact for runtime).
39    /// The quote style round-trips raw-text positions (in-arg groups).
40    Str { text: String, quote: char },
41    /// Full `"""..."""` spelling including delimiters; lower with
42    /// `lower_block_string` at parse time.
43    BlockStr(String),
44    /// Single punctuation char (`=`, `$`, `:`, `!`, `<`, `>`, `,`, `|`,
45    /// `&`, `@`). Multi-char operators combine in the parser using
46    /// `joint`.
47    Punct(char),
48    /// Delimited group with recursively lexed contents. `open_joint`
49    /// is gaplessness between the opener and the first inner token;
50    /// `close_joint` between the last inner token and the closer (both
51    /// vacuously true when empty). Statement splitting and guard
52    /// parsing ignore them; raw-text splices need them.
53    Group {
54        delim: GroupDelim,
55        inner: Vec<Tok>,
56        open_joint: bool,
57        close_joint: bool,
58    },
59    /// Literal newline (`\n`, `\r\n`, `\r` all normalize to one).
60    Newline,
61    /// Explicit `;` statement terminator.
62    Semicolon,
63    /// A skipped comment's raw spelling (`//...`, `#...`, `/*...*/`),
64    /// emitted only where the lexer skips comments (line starts, top
65    /// level and inside groups). Statement splitting ignores them but
66    /// releases pending `ELSE` continuations (a comment line breaks
67    /// the `}`/`ELSE` chain like the grammar); raw-text renders
68    /// reproduce them byte-identically (templates keep comment text
69    /// like the atomic grammar span). The token frontend never emits
70    /// these (`rustc` strips comments before us).
71    Comment(String),
72}
73
74/// One token plus the gap signal: `joint` is true when no gap (no
75/// whitespace, comment, or newline) precedes it. The parser uses this
76/// where the grammar requires adjacency (`::`, `$var`, `==`, `"a""b"`
77/// fragment joins, `FOO (` not-a-call); it never affects token identity.
78/// `line`/`col` are the 1-based start coordinates (`0` when unknown:
79/// synthetic streams, fused fragments, group interiors lexed without
80/// position context). Only statement-head positions are consumed
81/// (statement starts for errors and step coordinates); everything else
82/// rides along for future tooling. Equality ignores coordinates so
83/// token streams compare by content across frontends.
84#[derive(Debug, Clone)]
85pub struct Tok {
86    pub kind: TokKind,
87    pub joint: bool,
88    pub line: usize,
89    pub col: usize,
90}
91
92impl PartialEq for Tok {
93    fn eq(&self, other: &Self) -> bool {
94        self.kind == other.kind && self.joint == other.joint
95    }
96}
97
98impl Eq for Tok {}
99
100impl Tok {
101    pub(crate) fn fresh(kind: TokKind, joint: bool) -> Self {
102        Self {
103            kind,
104            joint,
105            line: 0,
106            col: 0,
107        }
108    }
109
110    pub(crate) fn at(kind: TokKind, joint: bool, line: usize, col: usize) -> Self {
111        Self {
112            kind,
113            joint,
114            line,
115            col,
116        }
117    }
118}
119
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct LexError {
122    pub line: usize,
123    pub col: usize,
124    pub msg: String,
125    /// Machine-readable kind when the lexer knows it (an unclosed
126    /// `WITH_IO` bracket is that command's syntax error, never a bare
127    /// grammar failure); `None` means a plain syntax failure.
128    pub kind: Option<ParseErrorKind>,
129}
130
131impl fmt::Display for LexError {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        write!(f, "lex error at {}:{}: {}", self.line, self.col, self.msg)
134    }
135}
136
137impl std::error::Error for LexError {}
138
139/// Keywords that open a `{...}` block head (`IF`, `WHILE`, ...).
140/// The unclosed-group diagnostic names the first unsatisfied one so
141/// fragmented blocks blame their opener, never the enclosing head.
142fn is_block_head(w: &str) -> bool {
143    matches!(
144        w,
145        KEYWORD_IF
146            | KEYWORD_ELSE
147            | KEYWORD_SWITCH
148            | KEYWORD_CASE
149            | KEYWORD_DEFAULT
150            | KEYWORD_FOR
151            | KEYWORD_WHILE
152            | KEYWORD_FUNC
153            | KEYWORD_TIMEOUT
154            | KEYWORD_ISOLATED
155            | KEYWORD_ASYNC
156            | KEYWORD_REMOTE
157            | KEYWORD_WITH_IO
158    )
159}
160
161/// True for template placeholders (`{{ .. }}` lex as a brace group
162/// holding a brace group).
163fn is_template_group(t: &Tok) -> bool {
164    if let TokKind::Group {
165        delim: GroupDelim::Brace,
166        inner,
167        ..
168    } = &t.kind
169    {
170        matches!(
171            inner.first().map(|f| &f.kind),
172            Some(TokKind::Group {
173                delim: GroupDelim::Brace,
174                ..
175            })
176        )
177    } else {
178        false
179    }
180}
181
182/// Chars that always delimit words in string sources. The set mirrors
183/// `rustc` tokenization so both frontends emit identical streams:
184/// operators and structural chars split in both (`--flag` arrives as
185/// `-`, `-`, `flag` with joint flags; the parser backend reassembles
186/// payloads losslessly). `.` splits too (`a.b`, `1.0.0`); `~` and
187/// backtick stay word chars (`rustc` rejects them, so they are
188/// string-pathway-only by construction, like raw-`"` blocks).
189fn is_delim(c: char) -> bool {
190    matches!(
191        c,
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/// Scan one string literal at the head of `s` (which must start with
223/// `"`, `'`, or `"""`), mirroring the `quoted_string` / `block_string`
224/// pest rules. Returns the token kind plus bytes consumed.
225fn scan_string(s: &str) -> Result<(TokKind, usize), String> {
226    if s.starts_with("\"\"\"") {
227        let mut end = 3;
228        while end < s.len() {
229            if s[end..].starts_with('\\') {
230                let next_len = s[end + 1..]
231                    .chars()
232                    .next()
233                    .map(|c| c.len_utf8())
234                    .unwrap_or(0);
235                if next_len == 0 {
236                    return Err("trailing backslash in block string".to_string());
237                }
238                end += 1 + next_len;
239                continue;
240            }
241            if s[end..].starts_with("\"\"\"") {
242                end += 3;
243                return Ok((TokKind::BlockStr(s[..end].to_string()), end));
244            }
245            end += s[end..].chars().next().map(|c| c.len_utf8()).unwrap_or(1);
246        }
247        return Err("unterminated block string".to_string());
248    }
249    let quote = s.as_bytes()[0] as char;
250    if quote != '"' && quote != '\'' {
251        return Err("string must open with a quote".to_string());
252    }
253    let mut end = 1;
254    while end < s.len() {
255        let rest = &s[end..];
256        let c = rest.chars().next().unwrap();
257        if c == '\\' {
258            // An escape pair is atomic: skip the backslash plus
259            // whatever follows (matching the block-string arm and
260            // `lex_word`). Skipping only before the quote char
261            // misreads `"a\\"` as unterminated: the second
262            // backslash would escape the closing quote.
263            let mut it = rest.chars();
264            it.next();
265            match it.next() {
266                Some(n) => end += 1 + n.len_utf8(),
267                None => end += 1,
268            }
269            continue;
270        }
271        if c == quote {
272            end += c.len_utf8();
273            return Ok((
274                TokKind::Str {
275                    text: s[1..end - 1].to_string(),
276                    quote,
277                },
278                end,
279            ));
280        }
281        end += c.len_utf8();
282    }
283    Err("unterminated string".to_string())
284}
285
286/// Lex one or more adjacent string spellings (the fused `TokenStream`
287/// shreds, or a single literal): `""".."""` reads as one
288/// [`TokKind::BlockStr`], `"a""b"` as two [`TokKind::Str`]. The first
289/// token inherits `joint`; later ones are always joint (no gap inside a
290/// spelling). Only the `TokenStream` frontend needs multi-spelling
291/// input; the string lexer calls [`scan_string`] directly.
292#[cfg(feature = "proc-macro-api")]
293fn lex_string_spelling(s: &str, joint: bool) -> Result<Vec<Tok>, String> {
294    let mut out = Vec::new();
295    let mut rest = s;
296    let mut first = true;
297    while !rest.is_empty() {
298        let (kind, used) = scan_string(rest)?;
299        out.push(Tok::fresh(kind, if first { joint } else { true }));
300        first = false;
301        rest = &rest[used..];
302    }
303    if out.is_empty() {
304        return Err("empty string spelling".to_string());
305    }
306    Ok(out)
307}
308
309/// A `'` opens a string where a gap precedes it (`= 'hi'`, `['a']`);
310/// inside a payload word (`coverage's`) it stays a literal char. The
311/// top-level lexer tracks this via its gap flag; group scanning uses
312/// the raw text before the quote for the same decision.
313fn quote_opens_before(src: &str) -> bool {
314    src.chars()
315        .rev()
316        .find(|c| !c.is_whitespace())
317        .map(|c| {
318            matches!(
319                c,
320                '[' | '(' | '{' | ',' | ':' | '=' | '$' | '!' | '<' | '>' | '|' | '&'
321            )
322        })
323        .unwrap_or(true)
324}
325
326struct StrLexer<'a> {
327    src: &'a str,
328    pos: usize,
329    line: usize,
330    col: usize,
331    out: Vec<Tok>,
332    /// Top-level words with their source lines, plus the output length
333    /// when pushed. Unclosed-group errors scan this for the block head
334    /// whose opener never closed (issue #215's "unclosed `IF` block
335    /// opened on line N" naming, without grammar internals).
336    heads: Vec<(String, usize, usize)>,
337    /// Start coordinates of the token currently being scanned, captured
338    /// at token begin and stamped by `push`. The main loop marks every
339    /// iteration (each scans exactly one token); group interiors inherit
340    /// absolute positions from a seeded child lexer instead.
341    mark_line: usize,
342    mark_col: usize,
343    /// True when a gap (space, tab, comment, newline, `;`) precedes the
344    /// next token. Reset after each emitted token.
345    gapped: bool,
346}
347
348impl<'a> StrLexer<'a> {
349    fn new(src: &'a str) -> Self {
350        Self::with_start(src, 1, 1)
351    }
352
353    /// Child lexer over group-interior text starting at an absolute
354    /// position (just past the opener): interior tokens and errors
355    /// come out absolute, so no remapping is needed downstream.
356    fn with_start(src: &'a str, line: usize, col: usize) -> Self {
357        Self {
358            src,
359            pos: 0,
360            line,
361            col,
362            out: Vec::new(),
363            heads: Vec::new(),
364            mark_line: 0,
365            mark_col: 0,
366            gapped: true,
367        }
368    }
369
370    fn err(&self, msg: impl Into<String>) -> LexError {
371        LexError {
372            line: self.line,
373            col: self.col,
374            msg: msg.into(),
375            kind: None,
376        }
377    }
378
379    fn rest(&self) -> &'a str {
380        &self.src[self.pos..]
381    }
382
383    fn bump(&mut self, n: usize, newlines: usize) {
384        self.pos += n;
385        if newlines > 0 {
386            self.line += newlines;
387            self.col = 1;
388        } else {
389            self.col += n;
390        }
391    }
392
393    fn push(&mut self, kind: TokKind) {
394        let joint = !self.gapped;
395        self.gapped = false;
396        if let TokKind::Word(w) = &kind {
397            self.heads.push((w.clone(), self.line, self.out.len()));
398        }
399        let (line, col) = (self.mark_line, self.mark_col);
400        self.out.push(Tok::at(kind, joint, line, col));
401    }
402
403    /// Block-head keyword whose `{...}` never closed: the first head
404    /// word with no balanced brace group after it (a head whose block
405    /// closed is satisfied, like `IF` in `IF {..} ELSE {..}`; other
406    /// groups such as `[...]` lists never satisfy). Returns the head
407    /// and its opener line for the unclosed-block diagnostic.
408    fn unclosed_head(&self) -> Option<(String, usize)> {
409        for (word, line, idx) in &self.heads {
410            if !is_block_head(word) {
411                continue;
412            }
413            // Templates (`{{ .. }}`, a brace group holding a brace
414            // group) never satisfy: only real blocks close a head.
415            let satisfied = self.out[*idx..].iter().any(|t| {
416                matches!(
417                    &t.kind,
418                    TokKind::Group {
419                        delim: GroupDelim::Brace,
420                        ..
421                    }
422                ) && !is_template_group(t)
423            });
424            if !satisfied {
425                return Some((word.clone(), *line));
426            }
427        }
428        None
429    }
430
431    /// True when only whitespace precedes on this line (comment position).
432    fn at_line_start(&self) -> bool {
433        let line_start = self.src[..self.pos].rfind('\n').map(|i| i + 1).unwrap_or(0);
434        self.src[line_start..self.pos]
435            .chars()
436            .all(|c| c == ' ' || c == '\t' || c == '\r')
437    }
438
439    fn lex_word(&mut self) {
440        let mut word = String::new();
441        while self.pos < self.src.len() {
442            let rest = self.rest();
443            let c = rest.chars().next().unwrap();
444            if c == '\\' {
445                let mut it = rest.chars();
446                it.next();
447                match it.next() {
448                    Some(n) => {
449                        word.push('\\');
450                        word.push(n);
451                        self.bump(1 + n.len_utf8(), 0);
452                    }
453                    None => {
454                        word.push('\\');
455                        self.bump(1, 0);
456                    }
457                }
458                continue;
459            }
460            if c.is_whitespace() || is_delim(c) {
461                break;
462            }
463            word.push(c);
464            self.bump(c.len_utf8(), 0);
465        }
466        self.push(TokKind::Word(word));
467    }
468
469    /// Scan a delimited group, copying its raw inner text (with `"..."`
470    /// and `'...'` regions protected so brackets inside strings never
471    /// affect nesting) and re-lexing it recursively. Edge gaps are
472    /// positional: `open_joint` is false when whitespace follows the
473    /// opener, `close_joint` is false when it precedes the closer.
474    fn lex_group(&mut self, close: char, delim: GroupDelim) -> Result<(), LexError> {
475        let (start_line, start_col) = (self.line, self.col);
476        self.bump(1, 0);
477        let open_joint = !self.rest().starts_with([' ', '\t', '\r', '\n']);
478        let mut stack: Vec<char> = Vec::new();
479        let mut inner_src = String::new();
480        while self.pos < self.src.len() {
481            let rest = self.rest();
482            let c = rest.chars().next().unwrap();
483            if c == '"' || (c == '\'' && quote_opens_before(&inner_src)) {
484                let (kind, used) = scan_string(rest).map_err(|m| self.err(m))?;
485                match kind {
486                    TokKind::Str { text, quote } => {
487                        inner_src.push(quote);
488                        inner_src.push_str(&text);
489                        inner_src.push(quote);
490                    }
491                    TokKind::BlockStr(full) => inner_src.push_str(&full),
492                    _ => unreachable!(),
493                }
494                let newlines = rest[..used].matches('\n').count();
495                self.bump(used, newlines);
496                continue;
497            }
498            if c == '[' || c == '(' || c == '{' {
499                stack.push(c);
500            } else if c == '/' && (rest.starts_with("//") || rest.starts_with("/*")) {
501                // Comments never nest groups (`// {` stays text like
502                // the grammar): copy through the comment terminator
503                // verbatim for the recursive re-lex.
504                if rest.starts_with("//") {
505                    inner_src.push_str("//");
506                    let mut k = 2;
507                    while k < rest.len() {
508                        let ch = rest[k..].chars().next().unwrap();
509                        if ch == '\n' || ch == '\r' {
510                            break;
511                        }
512                        // A closer at nesting depth zero ends the
513                        // comment copy: `//` runs to end of line,
514                        // and inside a group the closer is never
515                        // past a newline (`[a //c]` closes here,
516                        // like the grammar's literal reading).
517                        if ch == close && stack.is_empty() {
518                            break;
519                        }
520                        inner_src.push(ch);
521                        k += ch.len_utf8();
522                    }
523                    self.bump(k, 0);
524                    continue;
525                }
526                inner_src.push_str("/*");
527                self.bump(2, 0);
528                let mut k = 2;
529                let mut depth = 1usize;
530                while k < rest.len() && depth > 0 {
531                    if rest[k..].starts_with("/*") {
532                        depth += 1;
533                        inner_src.push_str("/*");
534                        self.bump(2, 0);
535                        k += 2;
536                    } else if rest[k..].starts_with("*/") {
537                        depth -= 1;
538                        inner_src.push_str("*/");
539                        self.bump(2, 0);
540                        k += 2;
541                    } else {
542                        let ch = rest[k..].chars().next().unwrap();
543                        // A depth-zero closer ends the copy even when no
544                        // `*/` has closed the span (`[a /* c]` closes
545                        // here, the old literal reading; the splice
546                        // re-adds the closer downstream, so bytes stay
547                        // exact).
548                        if ch == close && stack.is_empty() {
549                            break;
550                        }
551                        if ch == '\r' && rest[k..].starts_with("\r\n") {
552                            inner_src.push('\n');
553                            self.bump(2, 1);
554                            k += 2;
555                        } else {
556                            inner_src.push(ch);
557                            let nl = usize::from(ch == '\n');
558                            self.bump(ch.len_utf8(), nl);
559                            k += ch.len_utf8();
560                        }
561                    }
562                }
563                continue;
564            } else if c == ']' || c == ')' || c == '}' {
565                if c == close && stack.is_empty() {
566                    let close_joint = !matches!(
567                        self.src[..self.pos].chars().next_back(),
568                        Some(' ' | '\t' | '\r' | '\n')
569                    );
570                    self.bump(c.len_utf8(), 0);
571                    // Interior text starts just past the opener, so a
572                    // child lexer seeded there yields absolute
573                    // coordinates for interior tokens and errors alike
574                    // (no remapping downstream).
575                    let mut child = StrLexer::with_start(&inner_src, start_line, start_col + 1);
576                    child.run()?;
577                    let mut inner = child.out;
578                    if open_joint
579                        && let Some(first) = inner.first()
580                        && !matches!(
581                            first.kind,
582                            TokKind::Newline | TokKind::Semicolon | TokKind::Comment(_)
583                        )
584                    {
585                        inner[0].joint = true;
586                    }
587                    self.push(TokKind::Group {
588                        delim,
589                        inner,
590                        open_joint,
591                        close_joint,
592                    });
593                    return Ok(());
594                }
595                if stack.pop().is_none() {
596                    return Err(self.err(format!("unmatched `{c}`")));
597                }
598            }
599            if c == '\r' && rest.starts_with("\r\n") {
600                inner_src.push('\n');
601                self.bump(2, 1);
602                continue;
603            }
604            if c == '\n' || c == '\r' {
605                inner_src.push('\n');
606                self.bump(c.len_utf8(), 1);
607                continue;
608            }
609            inner_src.push(c);
610            self.bump(c.len_utf8(), 0);
611        }
612        // Fragmented blocks blame their opener past the head (never
613        // the enclosing head, never a grammar dump): the first
614        // unsatisfied block head names the message; anything else
615        // reports the opener position. The EOF position lands the
616        // span past every head line.
617        let (msg, kind) = match (delim, self.unclosed_head()) {
618            (GroupDelim::Brace, Some((head, opened))) => (
619                format!("unclosed `{head}` block opened on line {opened}"),
620                None,
621            ),
622            // An unclosed `WITH_IO` bracket is that command's syntax
623            // error (never unknown): it names the missing closer.
624            (GroupDelim::Bracket, Some((head, opened))) if head == KEYWORD_WITH_IO => (
625                format!("{KEYWORD_WITH_IO} bindings missing closing `]` (opened on line {opened})"),
626                Some(ParseErrorKind::InvalidSyntax {
627                    command: KEYWORD_WITH_IO.to_string(),
628                }),
629            ),
630            _ => (format!("unclosed group, expected `{close}`"), None),
631        };
632        Err(LexError {
633            line: self.line,
634            col: self.col,
635            msg,
636            kind,
637        })
638    }
639
640    fn skip_line_comment(&mut self) -> String {
641        let start = self.pos;
642        while self.pos < self.src.len() {
643            let c = self.rest().chars().next().unwrap();
644            if c == '\n' || c == '\r' {
645                break;
646            }
647            self.bump(c.len_utf8(), 0);
648        }
649        self.src[start..self.pos].to_string()
650    }
651
652    fn skip_block_comment(&mut self) -> Result<String, LexError> {
653        let start = self.pos;
654        self.bump(2, 0);
655        let mut depth = 1usize;
656        while self.pos < self.src.len() {
657            let rest = self.rest();
658            if rest.starts_with("/*") {
659                depth += 1;
660                self.bump(2, 0);
661            } else if rest.starts_with("*/") {
662                depth -= 1;
663                self.bump(2, 0);
664                if depth == 0 {
665                    self.gapped = true;
666                    return Ok(self.src[start..self.pos].to_string());
667                }
668            } else {
669                let c = rest.chars().next().unwrap();
670                if c == '\r' && rest.starts_with("\r\n") {
671                    self.bump(2, 1);
672                } else if c == '\n' || c == '\r' {
673                    self.bump(c.len_utf8(), 1);
674                } else {
675                    self.bump(c.len_utf8(), 0);
676                }
677            }
678        }
679        Err(self.err("unclosed block comment"))
680    }
681
682    fn run(&mut self) -> Result<(), LexError> {
683        while self.pos < self.src.len() {
684            let rest = self.rest();
685            let c = rest.chars().next().unwrap();
686            // Every iteration scans exactly one token: record its start
687            // coordinates for the positioned emits below (`push` reads
688            // the same marks; group interiors are seeded absolute).
689            self.mark_line = self.line;
690            self.mark_col = self.col;
691            match c {
692                ' ' | '\t' => {
693                    self.bump(c.len_utf8(), 0);
694                    self.gapped = true;
695                }
696                '\r' if rest.starts_with("\r\n") => {
697                    self.bump(2, 1);
698                    self.out.push(Tok::at(
699                        TokKind::Newline,
700                        false,
701                        self.mark_line,
702                        self.mark_col,
703                    ));
704                    self.gapped = true;
705                }
706                '\n' | '\r' => {
707                    self.bump(c.len_utf8(), 1);
708                    self.out.push(Tok::at(
709                        TokKind::Newline,
710                        false,
711                        self.mark_line,
712                        self.mark_col,
713                    ));
714                    self.gapped = true;
715                }
716                ';' => {
717                    self.bump(1, 0);
718                    self.out.push(Tok::at(
719                        TokKind::Semicolon,
720                        false,
721                        self.mark_line,
722                        self.mark_col,
723                    ));
724                    self.gapped = true;
725                }
726                // `//` opens a comment anywhere (line comment to end
727                // of line, like the grammar): line starts emit the
728                // marker for the splitter; mid-line markers let raw
729                // runs type them as literals and gap positions skip
730                // them, exactly like the grammar's dual reading.
731                // (`#` and `/*` stay payload mid-line: `#` is arg text
732                // there, `/*` reads as math operators.)
733                '/' if rest.starts_with("//") && self.at_line_start() => {
734                    let text = self.skip_line_comment();
735                    self.out.push(Tok::at(
736                        TokKind::Comment(text),
737                        false,
738                        self.mark_line,
739                        self.mark_col,
740                    ));
741                    self.gapped = true;
742                }
743                '/' if rest.starts_with("//") => {
744                    let text = self.skip_line_comment();
745                    let joint = !self.gapped;
746                    self.out.push(Tok::at(
747                        TokKind::Comment(text),
748                        joint,
749                        self.mark_line,
750                        self.mark_col,
751                    ));
752                    self.gapped = false;
753                }
754                '/' if rest.starts_with("/*") && self.at_line_start() => {
755                    let text = self.skip_block_comment()?;
756                    self.out.push(Tok::at(
757                        TokKind::Comment(text),
758                        false,
759                        self.mark_line,
760                        self.mark_col,
761                    ));
762                }
763                '#' if self.at_line_start() => {
764                    let text = self.skip_line_comment();
765                    self.out.push(Tok::at(
766                        TokKind::Comment(text),
767                        false,
768                        self.mark_line,
769                        self.mark_col,
770                    ));
771                    self.gapped = true;
772                }
773                '"' => {
774                    let joint = !self.gapped;
775                    let (kind, used) = scan_string(rest).map_err(|m| self.err(m))?;
776                    let newlines = rest[..used].matches('\n').count();
777                    self.bump(used, newlines);
778                    self.gapped = false;
779                    self.out
780                        .push(Tok::at(kind, joint, self.mark_line, self.mark_col));
781                }
782                '\'' if self.gapped => {
783                    let joint = !self.gapped;
784                    match scan_string(rest) {
785                        Ok((kind, used)) => {
786                            let newlines = rest[..used].matches('\n').count();
787                            self.bump(used, newlines);
788                            self.gapped = false;
789                            self.out
790                                .push(Tok::at(kind, joint, self.mark_line, self.mark_col));
791                        }
792                        // Lone `'` (lifetimes, apostrophes): matches the
793                        // `TokenStream` shape (`'` punct + word) instead
794                        // of failing where `rustc` would not.
795                        Err(_) => {
796                            self.bump(1, 0);
797                            self.push(TokKind::Punct('\''));
798                        }
799                    }
800                }
801                '[' => self.lex_group(']', GroupDelim::Bracket)?,
802                '(' => self.lex_group(')', GroupDelim::Paren)?,
803                '{' => self.lex_group('}', GroupDelim::Brace)?,
804                ']' | ')' | '}' => {
805                    return Err(self.err(format!("unmatched `{c}`")));
806                }
807                _ if is_delim(c) => {
808                    self.bump(c.len_utf8(), 0);
809                    self.push(TokKind::Punct(c));
810                }
811                _ => self.lex_word(),
812            }
813        }
814        Ok(())
815    }
816}
817
818fn lex_str_inner(s: &str) -> Result<Vec<Tok>, LexError> {
819    let mut lx = StrLexer::new(s);
820    lx.run()?;
821    Ok(lx.out)
822}
823
824/// Lex a string source into context-free tokens. Newlines normalize to
825/// [`TokKind::Newline`] (one per line break); statement-level `//`,
826/// `/* */`, and whole-line `#` comments emit [`TokKind::Comment`]
827/// markers (the newline itself still emits).
828pub fn lex_str(s: &str) -> Result<Vec<Tok>, LexError> {
829    lex_str_inner(s)
830}
831
832/// Lex a `TokenStream` into the same context-free tokens. Newlines come
833/// from span positions only (one per line advanced, inside groups too);
834/// no syntax is consulted. Span-adjacent string shreds fuse back to
835/// source spelling before `lex_string_spelling`; degenerate
836/// (zero-width, e.g. `quote!`) spans carry no adjacency signal, so
837/// literals there take the spaced reading.
838#[cfg(feature = "proc-macro-api")]
839pub fn lex_tokens(ts: &proc_macro2::TokenStream) -> Result<Vec<Tok>, LexError> {
840    use proc_macro2::{Delimiter, Spacing, TokenTree};
841
842    struct Walker {
843        out: Vec<Tok>,
844        gapped: bool,
845        prev_end: Option<proc_macro2::LineColumn>,
846        prev_joint: bool,
847        /// Fused raw spellings of an adjacent string-literal run plus
848        /// the joint flag of its first piece.
849        pending_str: Option<(String, bool)>,
850        /// Start coordinates of the token currently being scanned
851        /// (1-based; `0` means unknown). Set by `note_position` from
852        /// each token's own span; degenerate spans record `(0, 0)`.
853        mark_line: usize,
854        mark_col: usize,
855    }
856
857    impl Walker {
858        fn new() -> Self {
859            Self {
860                out: Vec::new(),
861                gapped: true,
862                prev_end: None,
863                prev_joint: false,
864                pending_str: None,
865                mark_line: 0,
866                mark_col: 0,
867            }
868        }
869
870        /// Positional only: newlines from line advances, adjacency from
871        /// span equality (or joint spacing). Degenerate spans reset to
872        /// gapped: they carry no position signal.
873        fn note_position(&mut self, start: proc_macro2::LineColumn, end: proc_macro2::LineColumn) {
874            if start == end {
875                self.gapped = true;
876                self.mark_line = 0;
877                self.mark_col = 0;
878            } else {
879                match self.prev_end {
880                    None => self.gapped = true,
881                    Some(prev) => {
882                        if start.line > prev.line {
883                            for i in 0..(start.line - prev.line) {
884                                // Newlines terminate the lines being left;
885                                // columns are unknowable here, so only the
886                                // line is recorded (`0` col = unknown).
887                                self.out
888                                    .push(Tok::at(TokKind::Newline, false, prev.line + i, 0));
889                            }
890                            self.gapped = true;
891                        } else {
892                            self.gapped = !(prev == start || self.prev_joint);
893                        }
894                    }
895                }
896                // proc_macro2 columns are 0-based byte offsets; toks are
897                // 1-based.
898                self.mark_line = start.line;
899                self.mark_col = start.column + 1;
900            }
901            self.prev_end = Some(end);
902            self.prev_joint = false;
903        }
904
905        fn flush_str(&mut self) -> Result<(), LexError> {
906            if let Some((raw, joint)) = self.pending_str.take() {
907                let toks = lex_string_spelling(&raw, joint).map_err(|m| LexError {
908                    line: 0,
909                    col: 0,
910                    msg: m,
911                    kind: None,
912                })?;
913                self.out.extend(toks);
914            }
915            Ok(())
916        }
917
918        fn push(&mut self, kind: TokKind) {
919            let joint = !self.gapped;
920            self.gapped = false;
921            self.out
922                .push(Tok::at(kind, joint, self.mark_line, self.mark_col));
923        }
924
925        fn walk_stream(&mut self, ts: &proc_macro2::TokenStream) -> Result<(), LexError> {
926            let trees: Vec<TokenTree> = ts.clone().into_iter().collect();
927            self.walk_trees(&trees)
928        }
929
930        fn walk_trees(&mut self, trees: &[TokenTree]) -> Result<(), LexError> {
931            for tt in trees {
932                match tt {
933                    TokenTree::Group(g) => {
934                        let (start, end) = (g.span().start(), g.span().end());
935                        self.flush_str()?;
936                        self.note_position(start, end);
937                        let mut inner = Walker::new();
938                        inner.walk_stream(&g.stream())?;
939                        inner.flush_str()?;
940                        // Edge gaps are positional: the opener sits at the
941                        // group start (one column wide), the closer just
942                        // before the group end. Degenerate spans report a
943                        // gap (spaced reading, like string lexing).
944                        let inner_trees: Vec<TokenTree> = g.stream().into_iter().collect();
945                        let open_joint = inner_trees.first().is_some_and(|first| {
946                            let s = first.span().start();
947                            s.line == start.line && s.column == start.column + 1
948                        }) || inner_trees.is_empty();
949                        let close_joint = inner_trees.last().is_some_and(|last| {
950                            let e = last.span().end();
951                            e.line == end.line && e.column + 1 == end.column
952                        }) || inner_trees.is_empty();
953                        if open_joint
954                            && let Some(idx) = inner.out.iter().position(|t| {
955                                !matches!(t.kind, TokKind::Newline | TokKind::Semicolon)
956                            })
957                        {
958                            inner.out[idx].joint = true;
959                        }
960                        let mut group = |delim| TokKind::Group {
961                            delim,
962                            inner: std::mem::take(&mut inner.out),
963                            open_joint,
964                            close_joint,
965                        };
966                        match g.delimiter() {
967                            Delimiter::Parenthesis => self.push(group(GroupDelim::Paren)),
968                            Delimiter::Bracket => self.push(group(GroupDelim::Bracket)),
969                            Delimiter::Brace => self.push(group(GroupDelim::Brace)),
970                            // Transparent: splice contents through.
971                            Delimiter::None => {
972                                for mut t in inner.out {
973                                    if matches!(t.kind, TokKind::Newline | TokKind::Semicolon) {
974                                        self.out.push(t);
975                                        self.gapped = true;
976                                    } else {
977                                        t.joint = false;
978                                        self.out.push(t);
979                                        self.gapped = false;
980                                    }
981                                }
982                            }
983                        }
984                    }
985                    TokenTree::Ident(ident) => {
986                        let (start, end) = (ident.span().start(), ident.span().end());
987                        self.flush_str()?;
988                        self.note_position(start, end);
989                        self.push(TokKind::Word(ident.to_string()));
990                    }
991                    TokenTree::Literal(lit) => {
992                        let (start, end) = (lit.span().start(), lit.span().end());
993                        let spelling = lit.to_string();
994                        let stringy = spelling.starts_with('"') || spelling.starts_with('\'');
995                        if stringy
996                            && start != end
997                            && self.prev_end.map(|p| p == start).unwrap_or(false)
998                        {
999                            // Shredded `"""` run (or `"a""b"`): fuse raw.
1000                            let raw = match self.pending_str.take() {
1001                                Some((mut raw, joint)) => {
1002                                    raw.push_str(&spelling);
1003                                    (raw, joint)
1004                                }
1005                                None => (spelling, false),
1006                            };
1007                            self.pending_str = Some(raw);
1008                            self.prev_end = Some(end);
1009                            self.prev_joint = false;
1010                            continue;
1011                        }
1012                        self.flush_str()?;
1013                        self.note_position(start, end);
1014                        if stringy {
1015                            let joint = !self.gapped;
1016                            self.pending_str = Some((spelling, joint));
1017                            self.gapped = false;
1018                        } else {
1019                            self.push(TokKind::Word(spelling));
1020                        }
1021                    }
1022                    TokenTree::Punct(p) => {
1023                        let (start, end) = (p.span().start(), p.span().end());
1024                        let ch = p.as_char();
1025                        self.flush_str()?;
1026                        self.note_position(start, end);
1027                        if ch == ';' {
1028                            self.out.push(Tok::at(
1029                                TokKind::Semicolon,
1030                                false,
1031                                self.mark_line,
1032                                self.mark_col,
1033                            ));
1034                            self.gapped = true;
1035                        } else {
1036                            self.push(TokKind::Punct(ch));
1037                        }
1038                        if p.spacing() == Spacing::Joint {
1039                            self.prev_joint = true;
1040                            self.gapped = false;
1041                        }
1042                    }
1043                }
1044            }
1045            Ok(())
1046        }
1047    }
1048
1049    let mut w = Walker::new();
1050    w.walk_stream(ts)?;
1051    w.flush_str()?;
1052    Ok(w.out)
1053}
1054
1055#[cfg(test)]
1056mod tests {
1057    use super::*;
1058
1059    fn w(s: &str) -> Tok {
1060        Tok::fresh(TokKind::Word(s.to_string()), false)
1061    }
1062
1063    fn wj(s: &str) -> Tok {
1064        Tok::fresh(TokKind::Word(s.to_string()), true)
1065    }
1066
1067    fn punct(c: char) -> Tok {
1068        Tok::fresh(TokKind::Punct(c), false)
1069    }
1070
1071    fn punctj(c: char) -> Tok {
1072        Tok::fresh(TokKind::Punct(c), true)
1073    }
1074
1075    fn str_tok(s: &str) -> Tok {
1076        str_tok_q(s, '"')
1077    }
1078
1079    fn str_tok_q(s: &str, quote: char) -> Tok {
1080        Tok::fresh(
1081            TokKind::Str {
1082                text: s.to_string(),
1083                quote,
1084            },
1085            false,
1086        )
1087    }
1088
1089    fn block_tok(s: &str) -> Tok {
1090        Tok::fresh(TokKind::BlockStr(s.to_string()), false)
1091    }
1092
1093    fn nl() -> Tok {
1094        Tok::fresh(TokKind::Newline, false)
1095    }
1096
1097    fn comment(s: &str) -> Tok {
1098        Tok::fresh(TokKind::Comment(s.to_string()), false)
1099    }
1100
1101    fn semi() -> Tok {
1102        Tok::fresh(TokKind::Semicolon, false)
1103    }
1104
1105    /// Both frontends must emit identical streams for the same source.
1106    /// `TokenStream` parsing normalizes `\r\n` to `\n`, so inputs here
1107    /// use `\n` only.
1108    #[cfg(feature = "proc-macro-api")]
1109    fn assert_both(text: &str, expected: Vec<Tok>) {
1110        let from_str = lex_str(text).expect("string lex must succeed");
1111        assert_eq!(from_str, expected, "string lexer mismatch for {text:?}");
1112        let ts: proc_macro2::TokenStream = text.parse().expect("must tokenize");
1113        let from_tokens = lex_tokens(&ts).expect("token lex must succeed");
1114        assert_eq!(
1115            from_tokens, expected,
1116            "token lexer mismatch for {text:?}\nstring: {from_str:?}"
1117        );
1118    }
1119
1120    #[test]
1121    fn lex_simple_command() {
1122        let toks = lex_str("ECHO hi").unwrap();
1123        assert_eq!(toks, vec![w("ECHO"), w("hi")]);
1124    }
1125
1126    #[test]
1127    fn lex_newlines_and_semicolons() {
1128        let toks = lex_str("ECHO hi\nWRITE x").unwrap();
1129        assert_eq!(toks, vec![w("ECHO"), w("hi"), nl(), w("WRITE"), w("x")]);
1130        let toks = lex_str("ECHO hi; WRITE x").unwrap();
1131        assert_eq!(toks, vec![w("ECHO"), w("hi"), semi(), w("WRITE"), w("x")]);
1132    }
1133
1134    #[test]
1135    fn lex_operators_are_positional() {
1136        let toks = lex_str("LET $x: INT = $a == 1").unwrap();
1137        assert_eq!(
1138            toks,
1139            vec![
1140                w("LET"),
1141                punct('$'),
1142                wj("x"),
1143                punctj(':'),
1144                w("INT"),
1145                punct('='),
1146                punct('$'),
1147                wj("a"),
1148                punct('='),
1149                punctj('='),
1150                w("1"),
1151            ]
1152        );
1153    }
1154
1155    #[test]
1156    fn lex_strings_verbatim() {
1157        let toks = lex_str("ECHO \"a\\nb\"").unwrap();
1158        assert_eq!(toks, vec![w("ECHO"), str_tok("a\\nb")]);
1159        let toks = lex_str("ECHO 'hi'").unwrap();
1160        assert_eq!(toks, vec![w("ECHO"), str_tok_q("hi", '\'')]);
1161    }
1162
1163    #[test]
1164    fn lex_block_string_atomic() {
1165        let toks = lex_str("ECHO \"\"\"hi\"\"\"").unwrap();
1166        assert_eq!(toks, vec![w("ECHO"), block_tok("\"\"\"hi\"\"\"")]);
1167    }
1168
1169    #[test]
1170    fn lex_groups_nest() {
1171        let toks = lex_str("[env:X] ECHO hi").unwrap();
1172        assert_eq!(
1173            toks,
1174            vec![
1175                Tok::fresh(
1176                    TokKind::Group {
1177                        delim: GroupDelim::Bracket,
1178                        inner: vec![wj("env"), punctj(':'), wj("X")],
1179                        open_joint: true,
1180                        close_joint: true,
1181                    },
1182                    false,
1183                ),
1184                w("ECHO"),
1185                w("hi"),
1186            ]
1187        );
1188    }
1189
1190    #[test]
1191    fn lex_comments_emit_markers_but_newline_stays() {
1192        let toks = lex_str("// hello\nECHO hi").unwrap();
1193        assert_eq!(toks, vec![comment("// hello"), nl(), w("ECHO"), w("hi")]);
1194        // Mid-line `//` marks too (jointness preserved for run
1195        // gluing); mid-line `/* */` is payload text, not a comment:
1196        // comments are statement-level (line start) only, matching
1197        // the grammar's dual reading.
1198        let toks = lex_str("ECHO hi //c").unwrap();
1199        assert_eq!(toks, vec![w("ECHO"), w("hi"), comment("//c")]);
1200        let toks = lex_str("ECHO a//b").unwrap();
1201        assert_eq!(
1202            toks,
1203            vec![
1204                w("ECHO"),
1205                w("a"),
1206                Tok::fresh(TokKind::Comment("//b".to_string()), true),
1207            ]
1208        );
1209        let toks = lex_str("ECHO hi /* mid */").unwrap();
1210        assert_eq!(
1211            toks,
1212            vec![
1213                w("ECHO"),
1214                w("hi"),
1215                punct('/'),
1216                punctj('*'),
1217                w("mid"),
1218                punct('*'),
1219                punctj('/'),
1220            ]
1221        );
1222    }
1223
1224    #[test]
1225    fn lex_splits_where_rustc_splits() {
1226        // Operators split in both frontends (joint flags keep payloads
1227        // reassemblable in the parser); only `10s`-style alphanumerics
1228        // stay whole.
1229        let toks = lex_str("RUN echo --flag a/b 10s 1.0.0").unwrap();
1230        assert_eq!(
1231            toks,
1232            vec![
1233                w("RUN"),
1234                w("echo"),
1235                punct('-'),
1236                punctj('-'),
1237                wj("flag"),
1238                w("a"),
1239                punctj('/'),
1240                wj("b"),
1241                w("10s"),
1242                w("1"),
1243                punctj('.'),
1244                wj("0"),
1245                punctj('.'),
1246                wj("0"),
1247            ]
1248        );
1249    }
1250
1251    #[test]
1252    fn lex_crlf_normalizes() {
1253        let toks = lex_str("ECHO hi\r\nWRITE x").unwrap();
1254        assert_eq!(toks, vec![w("ECHO"), w("hi"), nl(), w("WRITE"), w("x")]);
1255    }
1256
1257    #[test]
1258    fn lex_unclosed_group_errors() {
1259        assert!(lex_str("ECHO [hi").is_err());
1260        assert!(lex_str("ECHO \"hi").is_err());
1261    }
1262
1263    #[cfg(feature = "proc-macro-api")]
1264    #[test]
1265    fn both_frontends_agree_on_commands() {
1266        assert_both("ECHO hi", vec![w("ECHO"), w("hi")]);
1267        assert_both(
1268            "ECHO hi\nWRITE x",
1269            vec![w("ECHO"), w("hi"), nl(), w("WRITE"), w("x")],
1270        );
1271        assert_both(
1272            "[env:X] ECHO hi",
1273            vec![
1274                Tok::fresh(
1275                    TokKind::Group {
1276                        delim: GroupDelim::Bracket,
1277                        inner: vec![wj("env"), punctj(':'), wj("X")],
1278                        open_joint: true,
1279                        close_joint: true,
1280                    },
1281                    false,
1282                ),
1283                w("ECHO"),
1284                w("hi"),
1285            ],
1286        );
1287    }
1288
1289    #[cfg(feature = "proc-macro-api")]
1290    #[test]
1291    fn both_frontends_agree_on_exprs() {
1292        assert_both(
1293            "LET $x: INT = $a + $b",
1294            vec![
1295                w("LET"),
1296                punct('$'),
1297                wj("x"),
1298                punctj(':'),
1299                w("INT"),
1300                punct('='),
1301                punct('$'),
1302                wj("a"),
1303                punct('+'),
1304                punct('$'),
1305                wj("b"),
1306            ],
1307        );
1308    }
1309
1310    #[cfg(feature = "proc-macro-api")]
1311    #[test]
1312    fn both_frontends_fuse_block_strings() {
1313        assert_both(
1314            "ECHO \"\"\"hi\"\"\"",
1315            vec![w("ECHO"), block_tok("\"\"\"hi\"\"\"")],
1316        );
1317    }
1318
1319    #[cfg(feature = "proc-macro-api")]
1320    #[test]
1321    fn degenerate_spans_take_spaced_reading() {
1322        let ts = quote::quote! { ECHO "a" "b" };
1323        let toks = lex_tokens(&ts).expect("degenerate lex must succeed");
1324        let strs: Vec<_> = toks
1325            .iter()
1326            .filter(|t| matches!(t.kind, TokKind::Str { .. }))
1327            .collect();
1328        assert_eq!(strs.len(), 2, "synthetic spans must not fuse: {toks:?}");
1329    }
1330}