Skip to main content

constructo_runtime/
lexer.rs

1//! Converts the text of a types file into tokens.
2
3use crate::diagnostics::Pos;
4
5/// The words that the lexer gives their own tokens, so that they cannot be the name of anything.
6pub const KEYWORDS: [&str; 2] = ["enum", "const"];
7
8/// A token of a types file or a values file.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum Tok {
11    /// The keyword `enum`.
12    Enum,
13    /// The keyword `const`.
14    Const,
15    /// An identifier starting with an uppercase letter.
16    TypeName(String),
17    /// An identifier starting with a lowercase letter or underscore, other than `enum` and `const`.
18    Name(String),
19    /// `=`.
20    Eq,
21    /// `,`.
22    Comma,
23    /// `;`.
24    Semi,
25    /// `<`.
26    Lt,
27    /// `>`.
28    Gt,
29    /// `{`.
30    LBrace,
31    /// `}`.
32    RBrace,
33    /// `(`.
34    LParen,
35    /// `)`.
36    RParen,
37    /// `[`.
38    LBracket,
39    /// `]`.
40    RBracket,
41    /// `:`.
42    Colon,
43    /// `::`, which follows the group or the full name of a project in a qualified name.
44    ColonColon,
45    /// `.`, which separates the parts of the full name of a project in a qualified name.
46    Dot,
47    /// The postfix `?`, which is shorthand for `Option` in a type and for `Some` in a value.
48    Question,
49    /// An unsigned integer literal, such as `42`, with its text unchanged.
50    Nat(String),
51    /// A signed integer literal, such as `+8` or `-1`.
52    Int(String),
53    /// A floating-point literal, such as `3.0` or `-2.5e3`.
54    Float(String),
55    /// A string literal, with its escapes decoded.
56    Str(String),
57    /// A character that cannot start any token. The parser reports it as a syntax error.
58    Invalid(char),
59    /// A malformed literal. The token's position is that of the offending character.
60    Error(String),
61    /// The end of the text.
62    Eof,
63}
64
65/// A token and where it starts.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct Token {
68    /// The token.
69    pub tok: Tok,
70    /// The position of its first character.
71    pub pos: Pos,
72}
73
74/// Removes a byte order mark from the start of the text, as `rustc` does for a source file. Some editors add one, and it
75/// is not a part of the text: the first character that is left is at line 1, col 1.
76pub fn strip_bom(text: &str) -> &str {
77    text.strip_prefix('\u{feff}').unwrap_or(text)
78}
79
80/// Splits `text` into tokens, always ending with a single `Tok::Eof`.
81pub fn lex(text: &str) -> Vec<Token> {
82    let text = strip_bom(text);
83    let chars: Vec<char> = text.chars().collect();
84    let mut tokens = Vec::new();
85    let (mut i, mut line, mut col) = (0usize, 1u32, 1u32);
86    while i < chars.len() {
87        let c = chars[i];
88        let pos = Pos { line, col };
89        if c == '\n' {
90            i += 1;
91            line += 1;
92            col = 1;
93        } else if c.is_whitespace() {
94            i += 1;
95            col += 1;
96        } else if c == '/' && chars.get(i + 1) == Some(&'/') {
97            while i < chars.len() && chars[i] != '\n' {
98                i += 1;
99                col += 1;
100            }
101        } else if c.is_ascii_digit() || c == '+' || c == '-' {
102            let (tok, end, error_at) = scan_number(&chars, i);
103            let (tok, pos) = match error_at {
104                Some((index, message)) => (
105                    Tok::Error(message),
106                    Pos {
107                        line,
108                        col: col + (index - i) as u32,
109                    },
110                ),
111                None => (tok, pos),
112            };
113            tokens.push(Token { tok, pos });
114            col += (end - i) as u32;
115            i = end;
116        } else if c == '"' {
117            let (tok, end, error_at) = match scan_string(&chars, i) {
118                Ok((text, end)) => (Tok::Str(text), end, None),
119                Err((index, message, resume)) => (Tok::Error(message), resume, Some(index)),
120            };
121            let pos = match error_at {
122                Some(index) => Pos {
123                    line,
124                    col: col + (index - i) as u32,
125                },
126                None => pos,
127            };
128            tokens.push(Token { tok, pos });
129            col += (end - i) as u32;
130            i = end;
131        } else if c.is_ascii_alphabetic() || c == '_' {
132            let start = i;
133            while i < chars.len() && (chars[i].is_ascii_alphanumeric() || chars[i] == '_') {
134                i += 1;
135                col += 1;
136            }
137            let word: String = chars[start..i].iter().collect();
138            let tok = if word == KEYWORDS[0] {
139                Tok::Enum
140            } else if word == KEYWORDS[1] {
141                Tok::Const
142            } else if c.is_ascii_uppercase() {
143                Tok::TypeName(word)
144            } else {
145                Tok::Name(word)
146            };
147            tokens.push(Token { tok, pos });
148        } else if c == ':' && chars.get(i + 1) == Some(&':') {
149            tokens.push(Token {
150                tok: Tok::ColonColon,
151                pos,
152            });
153            i += 2;
154            col += 2;
155        } else {
156            let tok = match c {
157                '=' => Tok::Eq,
158                ',' => Tok::Comma,
159                ';' => Tok::Semi,
160                '<' => Tok::Lt,
161                '>' => Tok::Gt,
162                '{' => Tok::LBrace,
163                '}' => Tok::RBrace,
164                '(' => Tok::LParen,
165                ')' => Tok::RParen,
166                '[' => Tok::LBracket,
167                ']' => Tok::RBracket,
168                ':' => Tok::Colon,
169                '.' => Tok::Dot,
170                '?' => Tok::Question,
171                other => Tok::Invalid(other),
172            };
173            tokens.push(Token { tok, pos });
174            i += 1;
175            col += 1;
176        }
177    }
178    tokens.push(Token {
179        tok: Tok::Eof,
180        pos: Pos { line, col },
181    });
182    tokens
183}
184
185/// Scans a number starting at `start`, which holds a digit or a sign.
186///
187/// Returns the token, the index after the text that was consumed, and for a malformed number the index of the
188/// character where the error was found and the message. A malformed number consumes the text up to that character.
189fn scan_number(chars: &[char], start: usize) -> (Tok, usize, Option<(usize, String)>) {
190    let digits_from = |mut i: usize| {
191        while i < chars.len() && chars[i].is_ascii_digit() {
192            i += 1;
193        }
194        i
195    };
196    let signed = chars[start] == '+' || chars[start] == '-';
197    let after_int = digits_from(if signed { start + 1 } else { start });
198    if after_int == start + usize::from(signed) {
199        let error = (start + 1, "Expected a digit after the sign".to_string());
200        return (Tok::Nat(String::new()), start + 1, Some(error));
201    }
202    let text = |end: usize| chars[start..end].iter().collect::<String>();
203    if chars.get(after_int) != Some(&'.') {
204        let tok = if signed {
205            Tok::Int(text(after_int))
206        } else {
207            Tok::Nat(text(after_int))
208        };
209        return (tok, after_int, None);
210    }
211    let after_fraction = digits_from(after_int + 1);
212    if after_fraction == after_int + 1 {
213        let error = (after_int + 1, "Expected a digit after the decimal point".to_string());
214        return (Tok::Nat(String::new()), after_int + 1, Some(error));
215    }
216    let mut end = after_fraction;
217    if matches!(chars.get(end), Some('e') | Some('E')) {
218        let mut exponent = end + 1;
219        if matches!(chars.get(exponent), Some('+') | Some('-')) {
220            exponent += 1;
221        }
222        let after_exponent = digits_from(exponent);
223        if after_exponent == exponent {
224            let error = (exponent, "Expected a digit in the exponent".to_string());
225            return (Tok::Nat(String::new()), exponent, Some(error));
226        }
227        end = after_exponent;
228    }
229    (Tok::Float(text(end)), end, None)
230}
231
232/// Scans a string literal whose opening quote is at `start`.
233///
234/// Returns the decoded text and the index after the closing quote. For a malformed string it returns the index of the
235/// error, the message, and the index at which lexing should resume. The lexer of queries uses it too, so that a string
236/// in a query is read as one in a values file is. It is hidden from the documentation, since it is there for
237/// `constructo` and is not a part of the API that generated code relies on.
238#[doc(hidden)]
239pub fn scan_string(chars: &[char], start: usize) -> Result<(String, usize), (usize, String, usize)> {
240    let mut text = String::new();
241    let mut i = start + 1;
242    loop {
243        match chars.get(i) {
244            None | Some('\n') => return Err((start, "Unterminated string".to_string(), i)),
245            Some('"') => return Ok((text, i + 1)),
246            Some('\\') => {
247                let escape = chars.get(i + 1).copied();
248                let simple = match escape {
249                    Some('"') => Some('"'),
250                    Some('\\') => Some('\\'),
251                    Some('/') => Some('/'),
252                    Some('b') => Some('\u{8}'),
253                    Some('f') => Some('\u{c}'),
254                    Some('n') => Some('\n'),
255                    Some('r') => Some('\r'),
256                    Some('t') => Some('\t'),
257                    _ => None,
258                };
259                if let Some(c) = simple {
260                    text.push(c);
261                    i += 2;
262                } else if escape == Some('u') {
263                    match scan_unicode_escape(chars, i) {
264                        Some((c, next)) => {
265                            text.push(c);
266                            i = next;
267                        }
268                        None => return Err((i, "Invalid Unicode escape".to_string(), i + 2)),
269                    }
270                } else {
271                    return Err((i, "Invalid escape in string".to_string(), i + 2));
272                }
273            }
274            Some(c) if c.is_control() => return Err((i, "Control character in string".to_string(), i + 1)),
275            Some(c) => {
276                text.push(*c);
277                i += 1;
278            }
279        }
280    }
281}
282
283/// Reads the four hex digits of a `\u` escape at `at`, pairing a high surrogate with the low surrogate that must
284/// follow it. Returns the character and the index after the escape, or `None` if the escape is not valid.
285fn scan_unicode_escape(chars: &[char], at: usize) -> Option<(char, usize)> {
286    let unit = |at: usize| -> Option<u32> {
287        let digits: String = chars.get(at + 2..at + 6)?.iter().collect();
288        if digits.len() == 4 && digits.chars().all(|c| c.is_ascii_hexdigit()) {
289            u32::from_str_radix(&digits, 16).ok()
290        } else {
291            None
292        }
293    };
294    let first = unit(at)?;
295    match first {
296        0xD800..=0xDBFF => {
297            // A high surrogate is only valid as the first half of a pair.
298            if chars.get(at + 6) != Some(&'\\') || chars.get(at + 7) != Some(&'u') {
299                return None;
300            }
301            let second = unit(at + 6)?;
302            if !(0xDC00..=0xDFFF).contains(&second) {
303                return None;
304            }
305            let c = char::from_u32(0x10000 + ((first - 0xD800) << 10) + (second - 0xDC00))?;
306            Some((c, at + 12))
307        }
308        0xDC00..=0xDFFF => None,
309        _ => Some((char::from_u32(first)?, at + 6)),
310    }
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316
317    fn toks(text: &str) -> Vec<Tok> {
318        lex(text).into_iter().map(|t| t.tok).collect()
319    }
320
321    #[test]
322    fn lexes_the_parts_of_a_qualified_name() {
323        assert_eq!(
324            toks("acme.Shapes::Foo x: y a::b"),
325            vec![
326                Tok::Name("acme".into()),
327                Tok::Dot,
328                Tok::TypeName("Shapes".into()),
329                Tok::ColonColon,
330                Tok::TypeName("Foo".into()),
331                Tok::Name("x".into()),
332                Tok::Colon,
333                Tok::Name("y".into()),
334                Tok::Name("a".into()),
335                Tok::ColonColon,
336                Tok::Name("b".into()),
337                Tok::Eof
338            ]
339        );
340        // Three colons are `::` and then `:`, and a dot inside a number is part of the number.
341        assert_eq!(toks(":::")[..2], [Tok::ColonColon, Tok::Colon]);
342        assert_eq!(toks("1.5")[0], Tok::Float("1.5".into()));
343    }
344
345    #[test]
346    fn classifies_identifiers() {
347        assert_eq!(
348            toks("enum Foo bar _t"),
349            vec![
350                Tok::Enum,
351                Tok::TypeName("Foo".into()),
352                Tok::Name("bar".into()),
353                Tok::Name("_t".into()),
354                Tok::Eof
355            ]
356        );
357    }
358
359    #[test]
360    fn skips_comments_and_tracks_positions() {
361        let tokens = lex("// note\n  A;");
362        assert_eq!(tokens[0].pos, Pos { line: 2, col: 3 });
363        assert_eq!(tokens[1].tok, Tok::Semi);
364        assert_eq!(tokens[1].pos, Pos { line: 2, col: 4 });
365    }
366
367    #[test]
368    fn reports_invalid_characters() {
369        assert_eq!(toks("é"), vec![Tok::Invalid('é'), Tok::Eof]);
370    }
371
372    #[test]
373    fn a_leading_byte_order_mark_is_not_a_token_or_a_column() {
374        let with = lex("\u{feff}enum A = X;");
375        assert_eq!(with, lex("enum A = X;"));
376        assert_eq!(with[0].pos, Pos { line: 1, col: 1 });
377        // Only one at the start is removed, and any other is not a part of a name.
378        assert_eq!(lex("\u{feff}\u{feff}A")[0].tok, Tok::Invalid('\u{feff}'));
379        assert_eq!(lex("A\u{feff}")[1].tok, Tok::Invalid('\u{feff}'));
380    }
381
382    #[test]
383    fn lexes_numbers() {
384        assert_eq!(
385            toks("42 +8 -1 3.0 -2.5e3 1.5E+2"),
386            vec![
387                Tok::Nat("42".into()),
388                Tok::Int("+8".into()),
389                Tok::Int("-1".into()),
390                Tok::Float("3.0".into()),
391                Tok::Float("-2.5e3".into()),
392                Tok::Float("1.5E+2".into()),
393                Tok::Eof
394            ]
395        );
396    }
397
398    #[test]
399    fn reports_malformed_numbers_at_the_offending_character() {
400        let error = |text: &str| {
401            let t = lex(text).remove(0);
402            match t.tok {
403                Tok::Error(m) => (t.pos.col, m),
404                other => panic!("expected an error, got {:?}", other),
405            }
406        };
407        assert_eq!(error("3."), (3, "Expected a digit after the decimal point".to_string()));
408        assert_eq!(error("+x"), (2, "Expected a digit after the sign".to_string()));
409        assert_eq!(error("1.5e"), (5, "Expected a digit in the exponent".to_string()));
410    }
411
412    #[test]
413    fn lexes_strings_and_decodes_escapes() {
414        assert_eq!(
415            toks(r#""esc \" \\ \n \u00e9 é""#)[0],
416            Tok::Str("esc \" \\ \n é é".into())
417        );
418        assert_eq!(toks(r#""\ud83d\ude00""#)[0], Tok::Str("😀".into()));
419        assert_eq!(toks(r#""""#)[0], Tok::Str(String::new()));
420    }
421
422    #[test]
423    fn reports_malformed_strings() {
424        let error = |text: &str| {
425            let t = lex(text).remove(0);
426            match t.tok {
427                Tok::Error(m) => (t.pos.col, m),
428                other => panic!("expected an error, got {:?}", other),
429            }
430        };
431        assert_eq!(error("\"oops"), (1, "Unterminated string".to_string()));
432        assert_eq!(error("\"oops\nmore\""), (1, "Unterminated string".to_string()));
433        assert_eq!(error(r#""a\qb""#), (3, "Invalid escape in string".to_string()));
434        assert_eq!(error(r#""\u12""#), (2, "Invalid Unicode escape".to_string()));
435        assert_eq!(error(r#""\ud800""#), (2, "Invalid Unicode escape".to_string()));
436        assert_eq!(error("\"a\u{1}b\""), (3, "Control character in string".to_string()));
437    }
438}