antlr-rust-runtime 0.15.0

High performance Rust runtime and target support for ANTLR v4 generated parsers
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
use antlr4_runtime::atn::IntervalSet;

use super::unicode::simple_uppercase;

const MAX_CODE_POINT: i32 = 0x10_FFFF;

pub(super) fn get_antlr_char_literal_for_char(code_point: i32) -> String {
    let escaped = match code_point {
        0x08 => Some("\\b"),
        0x09 => Some("\\t"),
        0x0a => Some("\\n"),
        0x0c => Some("\\f"),
        0x0d => Some("\\r"),
        0x5c => Some("\\\\"),
        _ => None,
    };
    let body = if code_point < 0 {
        "<INVALID>".to_owned()
    } else if let Some(escaped) = escaped {
        escaped.to_owned()
    } else if code_point <= 0x7f
        && !u8::try_from(code_point).is_ok_and(|value| value.is_ascii_control())
    {
        match code_point {
            0x27 => "\\'".to_owned(),
            _ => char::from_u32(
                u32::try_from(code_point).expect("Basic Latin code point is nonnegative"),
            )
            .expect("Basic Latin code point is valid")
            .to_string(),
        }
    } else if code_point <= 0xffff {
        format!("\\u{code_point:04X}")
    } else {
        format!("\\u{{{code_point:06X}}}")
    };
    format!("'{body}'")
}

pub(super) fn get_char_value_from_grammar_char_literal(literal: Option<&str>) -> i32 {
    let Some(literal) = literal.filter(|literal| literal.len() >= 3) else {
        return -1;
    };
    literal
        .get(1..literal.len() - 1)
        .map_or(-1, get_char_value_from_char_in_grammar_literal)
}

pub(super) fn get_string_from_grammar_string_literal(literal: &str) -> Option<String> {
    if literal.len() < 2 {
        return Some(String::new());
    }
    let body = literal.get(1..literal.len() - 1)?;
    let values = decode_literal_body(body).ok()?;
    values
        .into_iter()
        .map(|value| u32::try_from(value).ok().and_then(char::from_u32))
        .collect()
}

pub(super) fn get_char_value_from_char_in_grammar_literal(text: &str) -> i32 {
    let mut characters = text.chars();
    if let Some(value) = characters.next()
        && characters.next().is_none()
    {
        return value as i32;
    }
    if !text.starts_with('\\') {
        return -1;
    }
    parse_code_point_escape(text, 0, false).map_or(-1, |(value, consumed)| {
        if consumed == text.len() { value } else { -1 }
    })
}

pub(super) fn parse_hex_value(text: &str, start: isize, end: isize) -> i32 {
    let (Ok(start), Ok(end)) = (usize::try_from(start), usize::try_from(end)) else {
        return -1;
    };
    let Some(digits) = text.get(start..end) else {
        return -1;
    };
    if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return -1;
    }
    i32::from_str_radix(digits, 16).unwrap_or(-1)
}

pub(super) fn capitalize(value: &str) -> String {
    let mut characters = value.chars();
    let Some(first) = characters.next() else {
        return String::new();
    };
    let mapped = simple_uppercase(first as i32);
    let first = u32::try_from(mapped)
        .ok()
        .and_then(char::from_u32)
        .unwrap_or(first);
    let mut result = String::with_capacity(value.len());
    result.push(first);
    result.push_str(characters.as_str());
    result
}

pub(super) fn get_interval_set_escaped_string(intervals: &IntervalSet) -> String {
    intervals
        .ranges()
        .iter()
        .map(|&(start, stop)| get_range_escaped_string(start, stop))
        .collect::<Vec<_>>()
        .join(" | ")
}

pub(super) fn get_range_escaped_string(start: i32, stop: i32) -> String {
    if start == stop {
        get_antlr_char_literal_for_char(start)
    } else {
        format!(
            "{}..{}",
            get_antlr_char_literal_for_char(start),
            get_antlr_char_literal_for_char(stop)
        )
    }
}

pub(super) fn decode_string_literal(literal: &str) -> Result<Vec<i32>, String> {
    let decoded = decode_string_literal_with_errors(literal)?;
    if let Some(error) = decoded.invalid_escapes.first() {
        return Err(format!("invalid escape sequence {}", error.sequence));
    }
    Ok(decoded.values)
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct InvalidEscapeSequence {
    pub(super) offset: usize,
    pub(super) sequence: String,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct DecodedStringLiteral {
    pub(super) values: Vec<i32>,
    pub(super) invalid_escapes: Vec<InvalidEscapeSequence>,
}

pub(super) fn decode_string_literal_with_errors(
    literal: &str,
) -> Result<DecodedStringLiteral, String> {
    let body = literal
        .strip_prefix('\'')
        .and_then(|value| value.strip_suffix('\''))
        .ok_or_else(|| format!("invalid lexer string literal {literal}"))?;
    let mut values = Vec::new();
    let mut invalid_escapes = Vec::new();
    let mut cursor = 0;
    while cursor < body.len() {
        let character = body[cursor..]
            .chars()
            .next()
            .expect("cursor is on a character boundary");
        if character != '\\' {
            push_code_point(&mut values, character as i32);
            cursor += character.len_utf8();
            continue;
        }

        let (value, consumed) = scan_string_escape(body, cursor);
        if let Some(value) = value {
            push_code_point(&mut values, value);
        } else {
            invalid_escapes.push(InvalidEscapeSequence {
                offset: cursor + 1,
                sequence: body[cursor..cursor + consumed].to_owned(),
            });
        }
        cursor += consumed;
    }
    Ok(DecodedStringLiteral {
        values,
        invalid_escapes,
    })
}

pub(super) fn decode_character_literal(literal: &str) -> Result<i32, String> {
    let values = decode_string_literal(literal)?;
    match values.as_slice() {
        [value] => Ok(*value),
        _ => Err(format!(
            "lexer character literal {literal} must contain exactly one Unicode scalar"
        )),
    }
}

fn decode_literal_body(body: &str) -> Result<Vec<i32>, String> {
    let mut values = Vec::new();
    let mut cursor = 0;
    while cursor < body.len() {
        let character = body[cursor..]
            .chars()
            .next()
            .expect("cursor is on a character boundary");
        if character == '\\' {
            let (value, consumed) = parse_code_point_escape(body, cursor, false)?;
            push_code_point(&mut values, value);
            cursor += consumed;
        } else {
            push_code_point(&mut values, character as i32);
            cursor += character.len_utf8();
        }
    }
    Ok(values)
}

fn scan_string_escape(body: &str, start: usize) -> (Option<i32>, usize) {
    let tail = &body[start..];
    let mut characters = tail.char_indices();
    let Some((_, '\\')) = characters.next() else {
        unreachable!("string escape scan starts at a backslash");
    };
    let Some((escaped_offset, escaped)) = characters.next() else {
        return (None, 1);
    };
    let escaped_end = escaped_offset + escaped.len_utf8();
    let consumed = if escaped == 'u' {
        let unicode = &tail[escaped_end..];
        unicode.strip_prefix('{').map_or_else(
            || 6.min(tail.len()),
            |braced| {
                braced
                    .find('}')
                    .map_or(tail.len(), |close| escaped_end + 1 + close + 1)
            },
        )
    } else {
        escaped_end
    };
    let sequence = &tail[..consumed];
    let value = get_char_value_from_char_in_grammar_literal(sequence);
    ((value >= 0).then_some(value), consumed)
}

fn push_code_point(values: &mut Vec<i32>, value: i32) {
    let Some(&high) = values.last() else {
        values.push(value);
        return;
    };
    if (0xD800..=0xDBFF).contains(&high) && (0xDC00..=0xDFFF).contains(&value) {
        let supplementary = 0x1_0000 + ((high - 0xD800) << 10) + value - 0xDC00;
        *values.last_mut().expect("last value exists") = supplementary;
    } else {
        values.push(value);
    }
}

pub(super) fn parse_code_point_escape(
    text: &str,
    start: usize,
    in_set: bool,
) -> Result<(i32, usize), String> {
    let tail = text
        .get(start..)
        .ok_or_else(|| "escape starts outside source text".to_owned())?;
    let mut characters = tail.char_indices();
    let (_, slash) = characters
        .next()
        .ok_or_else(|| "unterminated escape sequence".to_owned())?;
    if slash != '\\' {
        return Err("escape sequence does not start with a backslash".to_owned());
    }
    let (escaped_offset, escaped) = characters
        .next()
        .ok_or_else(|| "unterminated escape sequence".to_owned())?;
    let simple = match escaped {
        'n' => Some('\n'),
        'r' => Some('\r'),
        't' => Some('\t'),
        'b' => Some('\u{0008}'),
        'f' => Some('\u{000c}'),
        '\\' => Some('\\'),
        '\'' if !in_set => Some('\''),
        ']' | '-' if in_set => Some(escaped),
        _ => None,
    };
    if let Some(value) = simple {
        return Ok((value as i32, escaped_offset + escaped.len_utf8()));
    }
    if escaped != 'u' {
        return Err(format!("invalid escape sequence \\{escaped}"));
    }

    let digits_start = escaped_offset + escaped.len_utf8();
    let unicode = &tail[digits_start..];
    let (digits, consumed) = if let Some(rest) = unicode.strip_prefix('{') {
        let close = rest
            .find('}')
            .ok_or_else(|| "unterminated braced Unicode escape".to_owned())?;
        (&rest[..close], digits_start + 1 + close + 1)
    } else {
        if unicode.len() < 4 {
            return Err("Unicode escape must contain four hexadecimal digits".to_owned());
        }
        (&unicode[..4], digits_start + 4)
    };
    if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Err(format!("invalid Unicode escape \\u{{{digits}}}"));
    }
    let value = u32::from_str_radix(digits, 16)
        .map_err(|_| format!("invalid Unicode escape \\u{{{digits}}}"))?;
    if value > MAX_CODE_POINT as u32 {
        return Err(format!("Unicode escape is out of range: {value:#x}"));
    }
    Ok((
        i32::try_from(value).expect("Unicode code point fits i32"),
        consumed,
    ))
}

#[cfg(test)]
mod tests {
    use antlr4_runtime::atn::IntervalSet;

    use super::*;

    #[test]
    fn antlr_char_literal_for_char_matches_java() {
        assert_eq!(get_antlr_char_literal_for_char(-1), "'<INVALID>'");
        assert_eq!(get_antlr_char_literal_for_char(i32::from(b'\n')), "'\\n'");
        assert_eq!(get_antlr_char_literal_for_char(i32::from(b'\\')), "'\\\\'");
        assert_eq!(get_antlr_char_literal_for_char(i32::from(b'\'')), "'\\''");
        assert_eq!(get_antlr_char_literal_for_char(i32::from(b'b')), "'b'");
        assert_eq!(get_antlr_char_literal_for_char(0xffff), "'\\uFFFF'");
        assert_eq!(get_antlr_char_literal_for_char(0x10_ffff), "'\\u{10FFFF}'");
    }

    #[test]
    fn char_value_from_grammar_char_literal_matches_java() {
        assert_eq!(get_char_value_from_grammar_char_literal(None), -1);
        assert_eq!(get_char_value_from_grammar_char_literal(Some("")), -1);
        assert_eq!(get_char_value_from_grammar_char_literal(Some("b")), -1);
        assert_eq!(get_char_value_from_grammar_char_literal(Some("foo")), 111);
    }

    #[test]
    fn string_from_grammar_string_literal_matches_java() {
        assert_eq!(get_string_from_grammar_string_literal("foo\\u{bbb"), None);
        assert_eq!(get_string_from_grammar_string_literal("foo\\u{[]bb"), None);
        assert_eq!(get_string_from_grammar_string_literal("foo\\u[]bb"), None);
        assert_eq!(get_string_from_grammar_string_literal("foo\\ubb"), None);
        assert_eq!(
            get_string_from_grammar_string_literal("foo\\u{bb}bb"),
            Some("oo\u{bb}b".to_owned())
        );
    }

    #[test]
    fn char_value_from_char_in_grammar_literal_matches_java() {
        assert_eq!(get_char_value_from_char_in_grammar_literal("f"), 102);
        assert_eq!(get_char_value_from_char_in_grammar_literal("' "), -1);
        assert_eq!(get_char_value_from_char_in_grammar_literal("\\ "), -1);
        assert_eq!(get_char_value_from_char_in_grammar_literal("\\'"), 39);
        assert_eq!(get_char_value_from_char_in_grammar_literal("\\n"), 10);
        assert_eq!(get_char_value_from_char_in_grammar_literal("foobar"), -1);
        assert_eq!(get_char_value_from_char_in_grammar_literal("\\u1234"), 4660);
        assert_eq!(get_char_value_from_char_in_grammar_literal("\\u{12}"), 18);
        assert_eq!(get_char_value_from_char_in_grammar_literal("\\u{"), -1);
        assert_eq!(get_char_value_from_char_in_grammar_literal("foo"), -1);
    }

    #[test]
    fn parse_hex_value_matches_java() {
        assert_eq!(parse_hex_value("foobar", -1, 3), -1);
        assert_eq!(parse_hex_value("foobar", 1, -1), -1);
        assert_eq!(parse_hex_value("foobar", 1, 3), -1);
        assert_eq!(parse_hex_value("123456", 1, 3), 35);
    }

    #[test]
    fn capitalize_matches_java() {
        assert_eq!(capitalize("foo"), "Foo");
    }

    #[test]
    fn interval_set_escaped_string_matches_java() {
        assert_eq!(get_interval_set_escaped_string(&IntervalSet::new()), "");
        assert_eq!(
            get_interval_set_escaped_string(&IntervalSet::from_range(0, 0)),
            "'\\u0000'"
        );
        let mut set = IntervalSet::new();
        set.add(3);
        set.add(1);
        set.add(2);
        assert_eq!(
            get_interval_set_escaped_string(&set),
            "'\\u0001'..'\\u0003'"
        );
    }

    #[test]
    fn range_escaped_string_matches_java() {
        assert_eq!(get_range_escaped_string(2, 4), "'\\u0002'..'\\u0004'");
        assert_eq!(get_range_escaped_string(2, 2), "'\\u0002'");
    }
}