constructo-runtime 0.1.0

The syntax of Constructo data-values: the lexer, parser and printer that generated code depends on
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! Converts the text of a types file into tokens.

use crate::diagnostics::Pos;

/// The words that the lexer gives their own tokens, so that they cannot be the name of anything.
pub const KEYWORDS: [&str; 2] = ["enum", "const"];

/// A token of a types file or a values file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Tok {
    /// The keyword `enum`.
    Enum,
    /// The keyword `const`.
    Const,
    /// An identifier starting with an uppercase letter.
    TypeName(String),
    /// An identifier starting with a lowercase letter or underscore, other than `enum` and `const`.
    Name(String),
    /// `=`.
    Eq,
    /// `,`.
    Comma,
    /// `;`.
    Semi,
    /// `<`.
    Lt,
    /// `>`.
    Gt,
    /// `{`.
    LBrace,
    /// `}`.
    RBrace,
    /// `(`.
    LParen,
    /// `)`.
    RParen,
    /// `[`.
    LBracket,
    /// `]`.
    RBracket,
    /// `:`.
    Colon,
    /// `::`, which follows the group or the full name of a project in a qualified name.
    ColonColon,
    /// `.`, which separates the parts of the full name of a project in a qualified name.
    Dot,
    /// The postfix `?`, which is shorthand for `Option` in a type and for `Some` in a value.
    Question,
    /// An unsigned integer literal, such as `42`, with its text unchanged.
    Nat(String),
    /// A signed integer literal, such as `+8` or `-1`.
    Int(String),
    /// A floating-point literal, such as `3.0` or `-2.5e3`.
    Float(String),
    /// A string literal, with its escapes decoded.
    Str(String),
    /// A character that cannot start any token. The parser reports it as a syntax error.
    Invalid(char),
    /// A malformed literal. The token's position is that of the offending character.
    Error(String),
    /// The end of the text.
    Eof,
}

/// A token and where it starts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Token {
    /// The token.
    pub tok: Tok,
    /// The position of its first character.
    pub pos: Pos,
}

/// Removes a byte order mark from the start of the text, as `rustc` does for a source file. Some editors add one, and it
/// is not a part of the text: the first character that is left is at line 1, col 1.
pub fn strip_bom(text: &str) -> &str {
    text.strip_prefix('\u{feff}').unwrap_or(text)
}

/// Splits `text` into tokens, always ending with a single `Tok::Eof`.
pub fn lex(text: &str) -> Vec<Token> {
    let text = strip_bom(text);
    let chars: Vec<char> = text.chars().collect();
    let mut tokens = Vec::new();
    let (mut i, mut line, mut col) = (0usize, 1u32, 1u32);
    while i < chars.len() {
        let c = chars[i];
        let pos = Pos { line, col };
        if c == '\n' {
            i += 1;
            line += 1;
            col = 1;
        } else if c.is_whitespace() {
            i += 1;
            col += 1;
        } else if c == '/' && chars.get(i + 1) == Some(&'/') {
            while i < chars.len() && chars[i] != '\n' {
                i += 1;
                col += 1;
            }
        } else if c.is_ascii_digit() || c == '+' || c == '-' {
            let (tok, end, error_at) = scan_number(&chars, i);
            let (tok, pos) = match error_at {
                Some((index, message)) => (
                    Tok::Error(message),
                    Pos {
                        line,
                        col: col + (index - i) as u32,
                    },
                ),
                None => (tok, pos),
            };
            tokens.push(Token { tok, pos });
            col += (end - i) as u32;
            i = end;
        } else if c == '"' {
            let (tok, end, error_at) = match scan_string(&chars, i) {
                Ok((text, end)) => (Tok::Str(text), end, None),
                Err((index, message, resume)) => (Tok::Error(message), resume, Some(index)),
            };
            let pos = match error_at {
                Some(index) => Pos {
                    line,
                    col: col + (index - i) as u32,
                },
                None => pos,
            };
            tokens.push(Token { tok, pos });
            col += (end - i) as u32;
            i = end;
        } else if c.is_ascii_alphabetic() || c == '_' {
            let start = i;
            while i < chars.len() && (chars[i].is_ascii_alphanumeric() || chars[i] == '_') {
                i += 1;
                col += 1;
            }
            let word: String = chars[start..i].iter().collect();
            let tok = if word == KEYWORDS[0] {
                Tok::Enum
            } else if word == KEYWORDS[1] {
                Tok::Const
            } else if c.is_ascii_uppercase() {
                Tok::TypeName(word)
            } else {
                Tok::Name(word)
            };
            tokens.push(Token { tok, pos });
        } else if c == ':' && chars.get(i + 1) == Some(&':') {
            tokens.push(Token {
                tok: Tok::ColonColon,
                pos,
            });
            i += 2;
            col += 2;
        } else {
            let tok = match c {
                '=' => Tok::Eq,
                ',' => Tok::Comma,
                ';' => Tok::Semi,
                '<' => Tok::Lt,
                '>' => Tok::Gt,
                '{' => Tok::LBrace,
                '}' => Tok::RBrace,
                '(' => Tok::LParen,
                ')' => Tok::RParen,
                '[' => Tok::LBracket,
                ']' => Tok::RBracket,
                ':' => Tok::Colon,
                '.' => Tok::Dot,
                '?' => Tok::Question,
                other => Tok::Invalid(other),
            };
            tokens.push(Token { tok, pos });
            i += 1;
            col += 1;
        }
    }
    tokens.push(Token {
        tok: Tok::Eof,
        pos: Pos { line, col },
    });
    tokens
}

/// Scans a number starting at `start`, which holds a digit or a sign.
///
/// Returns the token, the index after the text that was consumed, and for a malformed number the index of the
/// character where the error was found and the message. A malformed number consumes the text up to that character.
fn scan_number(chars: &[char], start: usize) -> (Tok, usize, Option<(usize, String)>) {
    let digits_from = |mut i: usize| {
        while i < chars.len() && chars[i].is_ascii_digit() {
            i += 1;
        }
        i
    };
    let signed = chars[start] == '+' || chars[start] == '-';
    let after_int = digits_from(if signed { start + 1 } else { start });
    if after_int == start + usize::from(signed) {
        let error = (start + 1, "Expected a digit after the sign".to_string());
        return (Tok::Nat(String::new()), start + 1, Some(error));
    }
    let text = |end: usize| chars[start..end].iter().collect::<String>();
    if chars.get(after_int) != Some(&'.') {
        let tok = if signed {
            Tok::Int(text(after_int))
        } else {
            Tok::Nat(text(after_int))
        };
        return (tok, after_int, None);
    }
    let after_fraction = digits_from(after_int + 1);
    if after_fraction == after_int + 1 {
        let error = (after_int + 1, "Expected a digit after the decimal point".to_string());
        return (Tok::Nat(String::new()), after_int + 1, Some(error));
    }
    let mut end = after_fraction;
    if matches!(chars.get(end), Some('e') | Some('E')) {
        let mut exponent = end + 1;
        if matches!(chars.get(exponent), Some('+') | Some('-')) {
            exponent += 1;
        }
        let after_exponent = digits_from(exponent);
        if after_exponent == exponent {
            let error = (exponent, "Expected a digit in the exponent".to_string());
            return (Tok::Nat(String::new()), exponent, Some(error));
        }
        end = after_exponent;
    }
    (Tok::Float(text(end)), end, None)
}

/// Scans a string literal whose opening quote is at `start`.
///
/// Returns the decoded text and the index after the closing quote. For a malformed string it returns the index of the
/// error, the message, and the index at which lexing should resume. The lexer of queries uses it too, so that a string
/// in a query is read as one in a values file is. It is hidden from the documentation, since it is there for
/// `constructo` and is not a part of the API that generated code relies on.
#[doc(hidden)]
pub fn scan_string(chars: &[char], start: usize) -> Result<(String, usize), (usize, String, usize)> {
    let mut text = String::new();
    let mut i = start + 1;
    loop {
        match chars.get(i) {
            None | Some('\n') => return Err((start, "Unterminated string".to_string(), i)),
            Some('"') => return Ok((text, i + 1)),
            Some('\\') => {
                let escape = chars.get(i + 1).copied();
                let simple = match escape {
                    Some('"') => Some('"'),
                    Some('\\') => Some('\\'),
                    Some('/') => Some('/'),
                    Some('b') => Some('\u{8}'),
                    Some('f') => Some('\u{c}'),
                    Some('n') => Some('\n'),
                    Some('r') => Some('\r'),
                    Some('t') => Some('\t'),
                    _ => None,
                };
                if let Some(c) = simple {
                    text.push(c);
                    i += 2;
                } else if escape == Some('u') {
                    match scan_unicode_escape(chars, i) {
                        Some((c, next)) => {
                            text.push(c);
                            i = next;
                        }
                        None => return Err((i, "Invalid Unicode escape".to_string(), i + 2)),
                    }
                } else {
                    return Err((i, "Invalid escape in string".to_string(), i + 2));
                }
            }
            Some(c) if c.is_control() => return Err((i, "Control character in string".to_string(), i + 1)),
            Some(c) => {
                text.push(*c);
                i += 1;
            }
        }
    }
}

/// Reads the four hex digits of a `\u` escape at `at`, pairing a high surrogate with the low surrogate that must
/// follow it. Returns the character and the index after the escape, or `None` if the escape is not valid.
fn scan_unicode_escape(chars: &[char], at: usize) -> Option<(char, usize)> {
    let unit = |at: usize| -> Option<u32> {
        let digits: String = chars.get(at + 2..at + 6)?.iter().collect();
        if digits.len() == 4 && digits.chars().all(|c| c.is_ascii_hexdigit()) {
            u32::from_str_radix(&digits, 16).ok()
        } else {
            None
        }
    };
    let first = unit(at)?;
    match first {
        0xD800..=0xDBFF => {
            // A high surrogate is only valid as the first half of a pair.
            if chars.get(at + 6) != Some(&'\\') || chars.get(at + 7) != Some(&'u') {
                return None;
            }
            let second = unit(at + 6)?;
            if !(0xDC00..=0xDFFF).contains(&second) {
                return None;
            }
            let c = char::from_u32(0x10000 + ((first - 0xD800) << 10) + (second - 0xDC00))?;
            Some((c, at + 12))
        }
        0xDC00..=0xDFFF => None,
        _ => Some((char::from_u32(first)?, at + 6)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn toks(text: &str) -> Vec<Tok> {
        lex(text).into_iter().map(|t| t.tok).collect()
    }

    #[test]
    fn lexes_the_parts_of_a_qualified_name() {
        assert_eq!(
            toks("acme.Shapes::Foo x: y a::b"),
            vec![
                Tok::Name("acme".into()),
                Tok::Dot,
                Tok::TypeName("Shapes".into()),
                Tok::ColonColon,
                Tok::TypeName("Foo".into()),
                Tok::Name("x".into()),
                Tok::Colon,
                Tok::Name("y".into()),
                Tok::Name("a".into()),
                Tok::ColonColon,
                Tok::Name("b".into()),
                Tok::Eof
            ]
        );
        // Three colons are `::` and then `:`, and a dot inside a number is part of the number.
        assert_eq!(toks(":::")[..2], [Tok::ColonColon, Tok::Colon]);
        assert_eq!(toks("1.5")[0], Tok::Float("1.5".into()));
    }

    #[test]
    fn classifies_identifiers() {
        assert_eq!(
            toks("enum Foo bar _t"),
            vec![
                Tok::Enum,
                Tok::TypeName("Foo".into()),
                Tok::Name("bar".into()),
                Tok::Name("_t".into()),
                Tok::Eof
            ]
        );
    }

    #[test]
    fn skips_comments_and_tracks_positions() {
        let tokens = lex("// note\n  A;");
        assert_eq!(tokens[0].pos, Pos { line: 2, col: 3 });
        assert_eq!(tokens[1].tok, Tok::Semi);
        assert_eq!(tokens[1].pos, Pos { line: 2, col: 4 });
    }

    #[test]
    fn reports_invalid_characters() {
        assert_eq!(toks("é"), vec![Tok::Invalid('é'), Tok::Eof]);
    }

    #[test]
    fn a_leading_byte_order_mark_is_not_a_token_or_a_column() {
        let with = lex("\u{feff}enum A = X;");
        assert_eq!(with, lex("enum A = X;"));
        assert_eq!(with[0].pos, Pos { line: 1, col: 1 });
        // Only one at the start is removed, and any other is not a part of a name.
        assert_eq!(lex("\u{feff}\u{feff}A")[0].tok, Tok::Invalid('\u{feff}'));
        assert_eq!(lex("A\u{feff}")[1].tok, Tok::Invalid('\u{feff}'));
    }

    #[test]
    fn lexes_numbers() {
        assert_eq!(
            toks("42 +8 -1 3.0 -2.5e3 1.5E+2"),
            vec![
                Tok::Nat("42".into()),
                Tok::Int("+8".into()),
                Tok::Int("-1".into()),
                Tok::Float("3.0".into()),
                Tok::Float("-2.5e3".into()),
                Tok::Float("1.5E+2".into()),
                Tok::Eof
            ]
        );
    }

    #[test]
    fn reports_malformed_numbers_at_the_offending_character() {
        let error = |text: &str| {
            let t = lex(text).remove(0);
            match t.tok {
                Tok::Error(m) => (t.pos.col, m),
                other => panic!("expected an error, got {:?}", other),
            }
        };
        assert_eq!(error("3."), (3, "Expected a digit after the decimal point".to_string()));
        assert_eq!(error("+x"), (2, "Expected a digit after the sign".to_string()));
        assert_eq!(error("1.5e"), (5, "Expected a digit in the exponent".to_string()));
    }

    #[test]
    fn lexes_strings_and_decodes_escapes() {
        assert_eq!(
            toks(r#""esc \" \\ \n \u00e9 é""#)[0],
            Tok::Str("esc \" \\ \n é é".into())
        );
        assert_eq!(toks(r#""\ud83d\ude00""#)[0], Tok::Str("😀".into()));
        assert_eq!(toks(r#""""#)[0], Tok::Str(String::new()));
    }

    #[test]
    fn reports_malformed_strings() {
        let error = |text: &str| {
            let t = lex(text).remove(0);
            match t.tok {
                Tok::Error(m) => (t.pos.col, m),
                other => panic!("expected an error, got {:?}", other),
            }
        };
        assert_eq!(error("\"oops"), (1, "Unterminated string".to_string()));
        assert_eq!(error("\"oops\nmore\""), (1, "Unterminated string".to_string()));
        assert_eq!(error(r#""a\qb""#), (3, "Invalid escape in string".to_string()));
        assert_eq!(error(r#""\u12""#), (2, "Invalid Unicode escape".to_string()));
        assert_eq!(error(r#""\ud800""#), (2, "Invalid Unicode escape".to_string()));
        assert_eq!(error("\"a\u{1}b\""), (3, "Control character in string".to_string()));
    }
}