1mod 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 offset: usize,
26 errors: Vec<LexError>,
27}
28
29impl<'src> Lexer<'src> {
30 pub fn new(src: &'src str) -> Self {
32 Self::with_offset(src, 0)
33 }
34
35 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 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 fn span_from(&self, start: usize) -> Span {
86 Span::new(self.offset + start, self.offset + self.cursor.pos())
87 }
88
89 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 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 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 '+' if c.eat('=') => TokenKind::PlusEq,
121 '+' => TokenKind::Plus,
122 '*' if c.eat('=') => TokenKind::StarEq,
123 '*' => TokenKind::Star,
124 '/' => TokenKind::Slash,
125 '%' => TokenKind::Percent,
126 '?' => TokenKind::Question,
127
128 ':' if c.eat(':') => TokenKind::ColonColon,
129 ':' => TokenKind::Colon,
130 '.' if c.eat('.') => {
131 if c.eat('=') {
132 TokenKind::DotDotEq
133 } else {
134 TokenKind::DotDot
135 }
136 }
137 '.' => TokenKind::Dot,
138 '-' if c.eat('>') => TokenKind::Arrow,
139 '-' if c.eat('=') => TokenKind::MinusEq,
140 '-' => TokenKind::Minus,
141 '=' if c.eat('=') => TokenKind::EqEq,
142 '=' if c.eat('>') => TokenKind::FatArrow,
143 '=' => TokenKind::Eq,
144 '!' if c.eat('=') => TokenKind::BangEq,
145 '!' => TokenKind::Bang,
146 '<' if c.eat('=') => TokenKind::LtEq,
147 '<' => TokenKind::Lt,
148 '>' if c.eat('=') => TokenKind::GtEq,
149 '>' => TokenKind::Gt,
150 '&' if c.eat('&') => TokenKind::AmpAmp,
151 '&' => TokenKind::Amp,
152 '|' if c.eat('|') => TokenKind::PipePipe,
153 '|' => TokenKind::Pipe,
154 '^' => TokenKind::Caret,
155 '~' => TokenKind::Tilde,
156 '@' => TokenKind::At,
157
158 _ => return None,
159 };
160 Some(kind)
161 }
162
163 fn skip_trivia(&mut self) {
166 loop {
167 self.cursor.eat_while(char::is_whitespace);
168
169 let start = self.cursor.pos();
170 if self.cursor.eat_str("//") {
171 self.cursor.eat_while(|c| c != '\n');
172 } else if self.cursor.eat_str("/*") {
173 if !self.skip_block_comment() {
174 self.error(LexErrorKind::UnterminatedBlockComment, start);
175 }
176 } else {
177 return;
178 }
179 }
180 }
181
182 fn skip_block_comment(&mut self) -> bool {
185 let mut depth = 1u32;
186 while depth > 0 {
187 if self.cursor.eat_str("/*") {
188 depth += 1;
189 } else if self.cursor.eat_str("*/") {
190 depth -= 1;
191 } else if self.cursor.bump().is_none() {
192 return false;
193 }
194 }
195 true
196 }
197
198 fn lex_string(&mut self, start: usize) -> TokenKind<'src> {
202 let content_start = self.cursor.pos();
203 loop {
204 match self.cursor.peek() {
205 None | Some('\n') => {
206 self.error(LexErrorKind::UnterminatedString, start);
207 return TokenKind::StringLit(self.cursor.slice_from(content_start));
208 }
209 Some('"') => break,
210 Some('\\') => {
211 self.cursor.bump();
212 self.cursor.bump();
213 }
214 Some(_) => {
215 self.cursor.bump();
216 }
217 }
218 }
219 let content = self.cursor.slice_from(content_start);
220 self.cursor.bump(); TokenKind::StringLit(content)
222 }
223
224 fn lex_number(&mut self, start: usize) -> TokenKind<'src> {
225 if self.cursor.slice_from(start) == "0"
228 && matches!(self.cursor.peek(), Some('x' | 'o' | 'b'))
229 {
230 self.cursor.bump();
231 self.cursor
232 .eat_while(|c| c.is_ascii_alphanumeric() || c == '_');
233 return TokenKind::IntLit(self.cursor.slice_from(start));
234 }
235 let is_digit = |c: char| c.is_ascii_digit() || c == '_';
236 self.cursor.eat_while(is_digit);
237
238 let is_float = self.cursor.peek() == Some('.')
239 && self
240 .cursor
241 .peek_second()
242 .is_some_and(|c| c.is_ascii_digit());
243 if is_float {
244 self.cursor.bump(); self.cursor.eat_while(is_digit);
246 }
247
248 let text = self.cursor.slice_from(start);
249 if is_float {
250 TokenKind::FloatLit(text)
251 } else {
252 TokenKind::IntLit(text)
253 }
254 }
255
256 fn lex_ident(&mut self, start: usize) -> TokenKind<'src> {
257 self.cursor.eat_while(unicode_ident::is_xid_continue);
258 match self.cursor.slice_from(start) {
259 "_" => TokenKind::Underscore,
260 "b" if self.cursor.eat('"') => match self.lex_string(start) {
261 TokenKind::StringLit(content) => TokenKind::ByteStrLit(content),
262 other => other,
263 },
264 name => Keyword::try_from(name).map_or(TokenKind::Ident(name), TokenKind::Keyword),
265 }
266 }
267}
268
269fn is_ident_start(c: char) -> bool {
270 c == '_' || unicode_ident::is_xid_start(c)
271}