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