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