Skip to main content

xur_parser/lexer/
mod.rs

1//! Lexer for the Xur language.
2//!
3//! - Zero-copy: tokens borrow slices from the original `&'src str`.
4//! - Unicode identifiers via UAX #31 (`unicode-ident`).
5//! - Nested block comments (`/* ... /* ... */ ... */`).
6//! - Resilient: like rustc's lexer, errors are recorded on the side and a
7//!   best-effort token is still produced (an unknown character is skipped,
8//!   an unterminated string still becomes a string), so the parser never
9//!   sees holes and every error in a file is reported in one pass.
10//! - Literals keep their source text; turning them into values (and
11//!   reporting overflow or bad escapes) is the parser's job.
12
13mod cursor;
14#[cfg(test)]
15mod tests;
16
17use crate::error::{LexError, LexErrorKind};
18use crate::token::{Keyword, Token, TokenKind};
19use cursor::Cursor;
20use xur_span::{SourceFile, Span};
21
22pub struct Lexer<'src> {
23    cursor: Cursor<'src>,
24    /// Global position of the start of the source, added to every span.
25    offset: usize,
26    errors: Vec<LexError>,
27}
28
29impl<'src> Lexer<'src> {
30    /// Lexes a standalone string; spans start at position 0.
31    pub fn new(src: &'src str) -> Self {
32        Self::with_offset(src, 0)
33    }
34
35    /// Lexes a file from the source map, with spans in its global positions.
36    pub fn for_file(file: &'src SourceFile) -> Self {
37        Self::with_offset(&file.src, file.start)
38    }
39
40    fn with_offset(src: &'src str, offset: usize) -> Self {
41        let mut cursor = Cursor::new(src);
42        if src.starts_with("#!") {
43            while cursor.peek().is_some_and(|c| c != '\n') {
44                cursor.bump();
45            }
46        }
47        Self {
48            cursor,
49            offset,
50            errors: Vec::new(),
51        }
52    }
53
54    /// Lexes the whole source.
55    ///
56    /// Returns every token (always ending with `Eof`) and every error found.
57    /// Errors never leave gaps in the token stream.
58    pub fn tokenise(mut self) -> (Vec<Token<'src>>, Vec<LexError>) {
59        let mut tokens = Vec::new();
60        loop {
61            let token = self.next_token();
62            tokens.push(token);
63            if token.kind == TokenKind::Eof {
64                return (tokens, self.errors);
65            }
66        }
67    }
68
69    fn next_token(&mut self) -> Token<'src> {
70        loop {
71            self.skip_trivia();
72
73            let start = self.cursor.pos();
74            let Some(first) = self.cursor.bump() else {
75                return Token::new(TokenKind::Eof, self.span_from(start));
76            };
77            match self.lex_token(first, start) {
78                Some(kind) => return Token::new(kind, self.span_from(start)),
79                None => self.error(LexErrorKind::UnexpectedChar(first), start),
80            }
81        }
82    }
83
84    /// The span from cursor position `start` to the current position.
85    fn span_from(&self, start: usize) -> Span {
86        Span::new(self.offset + start, self.offset + self.cursor.pos())
87    }
88
89    /// Records an error covering `start` up to the current position.
90    fn error(&mut self, kind: LexErrorKind, start: usize) {
91        let span = self.span_from(start);
92        self.errors.push(LexError { kind, span });
93    }
94
95    /// Lexes the token starting with the already-consumed `first`, or
96    /// returns `None` if no token can start with it.
97    fn lex_token(&mut self, first: char, start: usize) -> Option<TokenKind<'src>> {
98        let kind = match first {
99            '"' => self.lex_string(start),
100            c if c.is_ascii_digit() => self.lex_number(start),
101            c if is_ident_start(c) => self.lex_ident(start),
102            c => return self.lex_punct(c),
103        };
104        Some(kind)
105    }
106
107    /// Lexes punctuation and operators, preferring the longest match.
108    fn lex_punct(&mut self, first: char) -> Option<TokenKind<'src>> {
109        let c = &mut self.cursor;
110        let kind = match first {
111            '(' => TokenKind::LParen,
112            ')' => TokenKind::RParen,
113            '{' => TokenKind::LBrace,
114            '}' => TokenKind::RBrace,
115            '[' => TokenKind::LBracket,
116            ']' => TokenKind::RBracket,
117            ';' => TokenKind::Semi,
118            ',' => TokenKind::Comma,
119            '#' => TokenKind::Hash,
120            '+' => TokenKind::Plus,
121            '*' => TokenKind::Star,
122            '/' => TokenKind::Slash,
123            '%' => TokenKind::Percent,
124            '?' => TokenKind::Question,
125
126            ':' if c.eat(':') => TokenKind::ColonColon,
127            ':' => TokenKind::Colon,
128            '.' if c.eat('.') => {
129                if c.eat('=') {
130                    TokenKind::DotDotEq
131                } else {
132                    TokenKind::DotDot
133                }
134            }
135            '.' => TokenKind::Dot,
136            '-' if c.eat('>') => TokenKind::Arrow,
137            '-' => TokenKind::Minus,
138            '=' if c.eat('=') => TokenKind::EqEq,
139            '=' if c.eat('>') => TokenKind::FatArrow,
140            '=' => TokenKind::Eq,
141            '!' if c.eat('=') => TokenKind::BangEq,
142            '!' => TokenKind::Bang,
143            '<' if c.eat('=') => TokenKind::LtEq,
144            '<' => TokenKind::Lt,
145            '>' if c.eat('=') => TokenKind::GtEq,
146            '>' => TokenKind::Gt,
147            '&' if c.eat('&') => TokenKind::AmpAmp,
148            '&' => TokenKind::Amp,
149            '|' if c.eat('|') => TokenKind::PipePipe,
150            '|' => TokenKind::Pipe,
151            '^' => TokenKind::Caret,
152            '~' => TokenKind::Tilde,
153            '@' => TokenKind::At,
154
155            _ => return None,
156        };
157        Some(kind)
158    }
159
160    /// Skips whitespace, line comments and (nested) block comments.
161    ///
162    fn skip_trivia(&mut self) {
163        loop {
164            self.cursor.eat_while(char::is_whitespace);
165
166            let start = self.cursor.pos();
167            if self.cursor.eat_str("//") {
168                self.cursor.eat_while(|c| c != '\n');
169            } else if self.cursor.eat_str("/*") {
170                if !self.skip_block_comment() {
171                    self.error(LexErrorKind::UnterminatedBlockComment, start);
172                }
173            } else {
174                return;
175            }
176        }
177    }
178
179    /// Skips the rest of a block comment whose opening `/*` was already consumed.
180    /// Returns `false` if the input ended before the comment was closed.
181    fn skip_block_comment(&mut self) -> bool {
182        let mut depth = 1u32;
183        while depth > 0 {
184            if self.cursor.eat_str("/*") {
185                depth += 1;
186            } else if self.cursor.eat_str("*/") {
187                depth -= 1;
188            } else if self.cursor.bump().is_none() {
189                return false;
190            }
191        }
192        true
193    }
194
195    /// Lexes a string literal whose opening `"` was already consumed.
196    ///
197    /// An unterminated string ends at the end of its line.
198    fn lex_string(&mut self, start: usize) -> TokenKind<'src> {
199        let content_start = self.cursor.pos();
200        loop {
201            match self.cursor.peek() {
202                None | Some('\n') => {
203                    self.error(LexErrorKind::UnterminatedString, start);
204                    return TokenKind::StringLit(self.cursor.slice_from(content_start));
205                }
206                Some('"') => break,
207                Some('\\') => {
208                    self.cursor.bump();
209                    self.cursor.bump();
210                }
211                Some(_) => {
212                    self.cursor.bump();
213                }
214            }
215        }
216        let content = self.cursor.slice_from(content_start);
217        self.cursor.bump(); // closing '"'
218        TokenKind::StringLit(content)
219    }
220
221    fn lex_number(&mut self, start: usize) -> TokenKind<'src> {
222        // `0x1F`, `0o17`, `0b101`: the digits are checked when decoded, so
223        // a bad digit is reported as such rather than ending the number.
224        if self.cursor.slice_from(start) == "0"
225            && matches!(self.cursor.peek(), Some('x' | 'o' | 'b'))
226        {
227            self.cursor.bump();
228            self.cursor
229                .eat_while(|c| c.is_ascii_alphanumeric() || c == '_');
230            return TokenKind::IntLit(self.cursor.slice_from(start));
231        }
232        let is_digit = |c: char| c.is_ascii_digit() || c == '_';
233        self.cursor.eat_while(is_digit);
234
235        let is_float = self.cursor.peek() == Some('.')
236            && self
237                .cursor
238                .peek_second()
239                .is_some_and(|c| c.is_ascii_digit());
240        if is_float {
241            self.cursor.bump(); // '.'
242            self.cursor.eat_while(is_digit);
243        }
244
245        let text = self.cursor.slice_from(start);
246        if is_float {
247            TokenKind::FloatLit(text)
248        } else {
249            TokenKind::IntLit(text)
250        }
251    }
252
253    fn lex_ident(&mut self, start: usize) -> TokenKind<'src> {
254        self.cursor.eat_while(unicode_ident::is_xid_continue);
255        match self.cursor.slice_from(start) {
256            "_" => TokenKind::Underscore,
257            "b" if self.cursor.eat('"') => match self.lex_string(start) {
258                TokenKind::StringLit(content) => TokenKind::ByteStrLit(content),
259                other => other,
260            },
261            name => Keyword::try_from(name).map_or(TokenKind::Ident(name), TokenKind::Keyword),
262        }
263    }
264}
265
266fn is_ident_start(c: char) -> bool {
267    c == '_' || unicode_ident::is_xid_start(c)
268}