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        Self {
42            cursor: Cursor::new(src),
43            offset,
44            errors: Vec::new(),
45        }
46    }
47
48    /// Lexes the whole source.
49    ///
50    /// Returns every token (always ending with `Eof`) and every error found.
51    /// Errors never leave gaps in the token stream.
52    pub fn tokenise(mut self) -> (Vec<Token<'src>>, Vec<LexError>) {
53        let mut tokens = Vec::new();
54        loop {
55            let token = self.next_token();
56            tokens.push(token);
57            if token.kind == TokenKind::Eof {
58                return (tokens, self.errors);
59            }
60        }
61    }
62
63    fn next_token(&mut self) -> Token<'src> {
64        loop {
65            self.skip_trivia();
66
67            let start = self.cursor.pos();
68            let Some(first) = self.cursor.bump() else {
69                return Token::new(TokenKind::Eof, self.span_from(start));
70            };
71            match self.lex_token(first, start) {
72                Some(kind) => return Token::new(kind, self.span_from(start)),
73                None => self.error(LexErrorKind::UnexpectedChar(first), start),
74            }
75        }
76    }
77
78    /// The span from cursor position `start` to the current position.
79    fn span_from(&self, start: usize) -> Span {
80        Span::new(self.offset + start, self.offset + self.cursor.pos())
81    }
82
83    /// Records an error covering `start` up to the current position.
84    fn error(&mut self, kind: LexErrorKind, start: usize) {
85        let span = self.span_from(start);
86        self.errors.push(LexError { kind, span });
87    }
88
89    /// Lexes the token starting with the already-consumed `first`, or
90    /// returns `None` if no token can start with it.
91    fn lex_token(&mut self, first: char, start: usize) -> Option<TokenKind<'src>> {
92        let kind = match first {
93            '"' => self.lex_string(start),
94            c if c.is_ascii_digit() => self.lex_number(start),
95            c if is_ident_start(c) => self.lex_ident(start),
96            c => return self.lex_punct(c),
97        };
98        Some(kind)
99    }
100
101    /// Lexes punctuation and operators, preferring the longest match.
102    fn lex_punct(&mut self, first: char) -> Option<TokenKind<'src>> {
103        let c = &mut self.cursor;
104        let kind = match first {
105            '(' => TokenKind::LParen,
106            ')' => TokenKind::RParen,
107            '{' => TokenKind::LBrace,
108            '}' => TokenKind::RBrace,
109            '[' => TokenKind::LBracket,
110            ']' => TokenKind::RBracket,
111            ';' => TokenKind::Semi,
112            ',' => TokenKind::Comma,
113            '#' => TokenKind::Hash,
114            '+' => TokenKind::Plus,
115            '*' => TokenKind::Star,
116            '/' => TokenKind::Slash,
117            '%' => TokenKind::Percent,
118            '?' => TokenKind::Question,
119
120            ':' if c.eat(':') => TokenKind::ColonColon,
121            ':' => TokenKind::Colon,
122            '.' if c.eat('.') => {
123                if c.eat('=') {
124                    TokenKind::DotDotEq
125                } else {
126                    TokenKind::DotDot
127                }
128            }
129            '.' => TokenKind::Dot,
130            '-' if c.eat('>') => TokenKind::Arrow,
131            '-' => TokenKind::Minus,
132            '=' if c.eat('=') => TokenKind::EqEq,
133            '=' if c.eat('>') => TokenKind::FatArrow,
134            '=' => TokenKind::Eq,
135            '!' if c.eat('=') => TokenKind::BangEq,
136            '!' => TokenKind::Bang,
137            '<' if c.eat('=') => TokenKind::LtEq,
138            '<' => TokenKind::Lt,
139            '>' if c.eat('=') => TokenKind::GtEq,
140            '>' => TokenKind::Gt,
141            '&' if c.eat('&') => TokenKind::AmpAmp,
142            '|' if c.eat('|') => TokenKind::PipePipe,
143            '|' => TokenKind::Pipe,
144
145            _ => return None,
146        };
147        Some(kind)
148    }
149
150    /// Skips whitespace, line comments and (nested) block comments.
151    ///
152    fn skip_trivia(&mut self) {
153        loop {
154            self.cursor.eat_while(char::is_whitespace);
155
156            let start = self.cursor.pos();
157            if self.cursor.eat_str("//") {
158                self.cursor.eat_while(|c| c != '\n');
159            } else if self.cursor.eat_str("/*") {
160                if !self.skip_block_comment() {
161                    self.error(LexErrorKind::UnterminatedBlockComment, start);
162                }
163            } else {
164                return;
165            }
166        }
167    }
168
169    /// Skips the rest of a block comment whose opening `/*` was already consumed.
170    /// Returns `false` if the input ended before the comment was closed.
171    fn skip_block_comment(&mut self) -> bool {
172        let mut depth = 1u32;
173        while depth > 0 {
174            if self.cursor.eat_str("/*") {
175                depth += 1;
176            } else if self.cursor.eat_str("*/") {
177                depth -= 1;
178            } else if self.cursor.bump().is_none() {
179                return false;
180            }
181        }
182        true
183    }
184
185    /// Lexes a string literal whose opening `"` was already consumed.
186    ///
187    /// An unterminated string ends at the end of its line.
188    fn lex_string(&mut self, start: usize) -> TokenKind<'src> {
189        let content_start = self.cursor.pos();
190        loop {
191            match self.cursor.peek() {
192                None | Some('\n') => {
193                    self.error(LexErrorKind::UnterminatedString, start);
194                    return TokenKind::StringLit(self.cursor.slice_from(content_start));
195                }
196                Some('"') => break,
197                Some('\\') => {
198                    self.cursor.bump();
199                    self.cursor.bump();
200                }
201                Some(_) => {
202                    self.cursor.bump();
203                }
204            }
205        }
206        let content = self.cursor.slice_from(content_start);
207        self.cursor.bump(); // closing '"'
208        TokenKind::StringLit(content)
209    }
210
211    fn lex_number(&mut self, start: usize) -> TokenKind<'src> {
212        let is_digit = |c: char| c.is_ascii_digit() || c == '_';
213        self.cursor.eat_while(is_digit);
214
215        let is_float = self.cursor.peek() == Some('.')
216            && self
217                .cursor
218                .peek_second()
219                .is_some_and(|c| c.is_ascii_digit());
220        if is_float {
221            self.cursor.bump(); // '.'
222            self.cursor.eat_while(is_digit);
223        }
224
225        let text = self.cursor.slice_from(start);
226        if is_float {
227            TokenKind::FloatLit(text)
228        } else {
229            TokenKind::IntLit(text)
230        }
231    }
232
233    fn lex_ident(&mut self, start: usize) -> TokenKind<'src> {
234        self.cursor.eat_while(unicode_ident::is_xid_continue);
235        match self.cursor.slice_from(start) {
236            "_" => TokenKind::Underscore,
237            name => Keyword::try_from(name).map_or(TokenKind::Ident(name), TokenKind::Keyword),
238        }
239    }
240}
241
242fn is_ident_start(c: char) -> bool {
243    c == '_' || unicode_ident::is_xid_start(c)
244}