antlr-rust-runtime 0.20.1

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
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
439
440
use std::fmt;
use std::sync::{Arc, Mutex};

use crate::errors::{AntlrError, ConsoleErrorListener, ErrorListener};
use crate::token::TokenView;
use crate::vocabulary::Vocabulary;

#[derive(Clone)]
struct ErrorListenerSlot(Arc<Mutex<dyn for<'a> ErrorListener<dyn Recognizer + 'a> + Send>>);

impl ErrorListenerSlot {
    fn new<L>(listener: L) -> Self
    where
        L: for<'a> ErrorListener<dyn Recognizer + 'a> + Send + 'static,
    {
        Self(Arc::new(Mutex::new(listener)))
    }

    #[allow(clippy::too_many_arguments)] // mirrors ANTLR's canonical syntaxError signature
    fn syntax_error(
        &self,
        recognizer: &(dyn Recognizer + '_),
        offending: Option<TokenView<'_>>,
        line: usize,
        column: usize,
        message: &str,
        error: Option<&AntlrError>,
    ) {
        self.0
            .lock()
            .expect("error listener lock poisoned")
            .syntax_error(recognizer, offending, line, column, message, error);
    }
}

impl fmt::Debug for ErrorListenerSlot {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("ErrorListener")
    }
}

#[derive(Clone, Debug)]
pub(crate) struct RecognizerMetadata {
    grammar_file_name: String,
    rule_names: Vec<String>,
    channel_names: Vec<String>,
    mode_names: Vec<String>,
    vocabulary: Vocabulary,
}

impl RecognizerMetadata {
    pub(crate) fn from_static(
        grammar_file_name: &'static str,
        rule_names: &'static [&'static str],
        channel_names: &'static [&'static str],
        mode_names: &'static [&'static str],
        vocabulary: Vocabulary,
    ) -> Self {
        Self {
            grammar_file_name: grammar_file_name.to_owned(),
            rule_names: rule_names.iter().map(|name| (*name).to_owned()).collect(),
            channel_names: channel_names
                .iter()
                .map(|name| (*name).to_owned())
                .collect(),
            mode_names: mode_names.iter().map(|name| (*name).to_owned()).collect(),
            vocabulary,
        }
    }
}

#[derive(Clone, Debug)]
pub struct RecognizerData {
    metadata: Arc<RecognizerMetadata>,
    state: isize,
    console_error_listener: bool,
    error_listeners: Vec<ErrorListenerSlot>,
}

impl RecognizerData {
    pub fn new(grammar_file_name: impl Into<String>, vocabulary: Vocabulary) -> Self {
        Self {
            metadata: Arc::new(RecognizerMetadata {
                grammar_file_name: grammar_file_name.into(),
                rule_names: Vec::new(),
                channel_names: Vec::new(),
                mode_names: Vec::new(),
                vocabulary,
            }),
            state: -1,
            console_error_listener: true,
            error_listeners: Vec::new(),
        }
    }

    pub(crate) const fn from_shared(metadata: Arc<RecognizerMetadata>) -> Self {
        Self {
            metadata,
            state: -1,
            console_error_listener: true,
            error_listeners: Vec::new(),
        }
    }

    #[must_use]
    pub fn with_rule_names(
        mut self,
        rule_names: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Arc::make_mut(&mut self.metadata).rule_names =
            rule_names.into_iter().map(Into::into).collect();
        self
    }

    #[must_use]
    pub fn with_channel_names(
        mut self,
        channel_names: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Arc::make_mut(&mut self.metadata).channel_names =
            channel_names.into_iter().map(Into::into).collect();
        self
    }

    #[must_use]
    pub fn with_mode_names(
        mut self,
        mode_names: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Arc::make_mut(&mut self.metadata).mode_names =
            mode_names.into_iter().map(Into::into).collect();
        self
    }

    /// Rule names owned by this recognizer's metadata.
    ///
    /// Also available through [`Recognizer::rule_names`]; this inherent
    /// accessor lets callers that already hold a `RecognizerData` field
    /// borrow rule names without borrowing the whole recognizer.
    #[must_use]
    pub fn rule_names(&self) -> &[String] {
        &self.metadata.rule_names
    }

    /// The token vocabulary for literal/symbolic name resolution.
    #[must_use]
    pub fn vocabulary(&self) -> &Vocabulary {
        &self.metadata.vocabulary
    }

    pub const fn state(&self) -> isize {
        self.state
    }

    pub const fn set_state(&mut self, state: isize) {
        self.state = state;
    }

    fn add_error_listener<L>(&mut self, listener: L)
    where
        L: for<'a> ErrorListener<dyn Recognizer + 'a> + Send + 'static,
    {
        self.error_listeners.push(ErrorListenerSlot::new(listener));
    }

    fn remove_error_listeners(&mut self) {
        self.console_error_listener = false;
        self.error_listeners.clear();
    }

    #[allow(clippy::too_many_arguments)] // mirrors ANTLR's canonical syntaxError signature
    fn notify_error_listeners(
        &self,
        recognizer: &dyn Recognizer,
        offending: Option<TokenView<'_>>,
        line: usize,
        column: usize,
        message: &str,
        error: Option<&AntlrError>,
    ) {
        if self.console_error_listener {
            ConsoleErrorListener.syntax_error(recognizer, offending, line, column, message, error);
        }
        for listener in &self.error_listeners {
            listener.syntax_error(recognizer, offending, line, column, message, error);
        }
    }
}

pub trait Recognizer {
    fn data(&self) -> &RecognizerData;
    fn data_mut(&mut self) -> &mut RecognizerData;

    fn grammar_file_name(&self) -> &str {
        &self.data().metadata.grammar_file_name
    }

    fn rule_names(&self) -> &[String] {
        &self.data().metadata.rule_names
    }

    fn channel_names(&self) -> &[String] {
        &self.data().metadata.channel_names
    }

    fn mode_names(&self) -> &[String] {
        &self.data().metadata.mode_names
    }

    fn vocabulary(&self) -> &Vocabulary {
        &self.data().metadata.vocabulary
    }

    fn state(&self) -> isize {
        self.data().state()
    }

    fn set_state(&mut self, state: isize) {
        self.data_mut().set_state(state);
    }

    /// Adds a listener for syntax and prediction diagnostics.
    ///
    /// Recognizers start with one [`ConsoleErrorListener`]. Call
    /// [`Self::remove_error_listeners`] before adding a replacement when
    /// diagnostics should not also be written to stderr.
    fn add_error_listener<L>(&mut self, listener: L)
    where
        Self: Sized,
        L: for<'a> ErrorListener<dyn Recognizer + 'a> + Send + 'static,
    {
        self.data_mut().add_error_listener(listener);
    }

    /// Removes every error listener, including the default console listener.
    fn remove_error_listeners(&mut self) {
        self.data_mut().remove_error_listeners();
    }

    /// Sends one diagnostic to every registered error listener.
    ///
    /// `offending` is the token the diagnostic is anchored to, when one
    /// exists — parser diagnostics resolve it from the token store; lexer
    /// diagnostics pass `None` because no token was produced.
    fn notify_error_listeners(
        &self,
        offending: Option<TokenView<'_>>,
        line: usize,
        column: usize,
        message: &str,
        error: Option<&AntlrError>,
    ) where
        Self: Sized,
    {
        self.data()
            .notify_error_listeners(self, offending, line, column, message, error);
    }

    fn sempred(&mut self, _rule_index: usize, _pred_index: usize) -> bool {
        true
    }

    fn action(&mut self, _rule_index: usize, _action_index: usize) {}
}

#[cfg(test)]
#[allow(clippy::disallowed_methods)] // `insta` assertion macros unwrap internal I/O.
mod tests {
    use std::mem::size_of;

    use super::*;
    use crate::generated::GrammarMetadata;

    static SHARED_METADATA: GrammarMetadata = GrammarMetadata::new(
        "Shared.g4",
        &["start"],
        &[None, Some("'x'")],
        &[None, Some("X")],
        &[None, None],
        &["DEFAULT_TOKEN_CHANNEL", "HIDDEN"],
        &["DEFAULT_MODE"],
        &[],
    );

    #[derive(Clone, Debug, Eq, PartialEq)]
    struct RecordedError {
        grammar_file_name: String,
        offending_text: Option<String>,
        line: usize,
        column: usize,
        message: String,
        error: Option<AntlrError>,
    }

    #[derive(Clone, Debug)]
    struct RecordingErrorListener {
        errors: Arc<Mutex<Vec<RecordedError>>>,
    }

    impl<R> ErrorListener<R> for RecordingErrorListener
    where
        R: Recognizer + ?Sized,
    {
        fn syntax_error(
            &mut self,
            recognizer: &R,
            offending: Option<TokenView<'_>>,
            line: usize,
            column: usize,
            message: &str,
            error: Option<&AntlrError>,
        ) {
            self.errors
                .lock()
                .expect("recorded errors lock")
                .push(RecordedError {
                    grammar_file_name: recognizer.grammar_file_name().to_owned(),
                    offending_text: offending.and_then(|token| token.text().map(str::to_owned)),
                    line,
                    column,
                    message: message.to_owned(),
                    error: error.cloned(),
                });
        }
    }

    #[derive(Clone, Debug)]
    struct TestRecognizer {
        data: RecognizerData,
    }

    impl Recognizer for TestRecognizer {
        fn data(&self) -> &RecognizerData {
            &self.data
        }

        fn data_mut(&mut self) -> &mut RecognizerData {
            &mut self.data
        }
    }

    fn test_recognizer() -> TestRecognizer {
        TestRecognizer {
            data: RecognizerData::new(
                "Test.g4",
                Vocabulary::new(
                    std::iter::empty::<Option<&str>>(),
                    std::iter::empty::<Option<&str>>(),
                    std::iter::empty::<Option<&str>>(),
                ),
            ),
        }
    }

    #[test]
    fn recognizers_replace_the_default_console_error_listener() {
        let mut recognizer = test_recognizer();
        assert!(recognizer.data.console_error_listener);
        assert!(recognizer.data.error_listeners.is_empty());

        recognizer.remove_error_listeners();
        assert!(!recognizer.data.console_error_listener);
        assert!(recognizer.data.error_listeners.is_empty());

        let errors = Arc::new(Mutex::new(Vec::new()));
        recognizer.add_error_listener(RecordingErrorListener {
            errors: Arc::clone(&errors),
        });
        let error = AntlrError::ParserError {
            line: 3,
            column: 5,
            message: "unexpected token".to_owned(),
            offending: None,
        };
        recognizer.notify_error_listeners(None, 3, 5, "unexpected token", Some(&error));

        insta::assert_debug_snapshot!(
            "recognizers_replace_the_default_console_error_listener",
            *errors.lock().expect("recorded errors lock")
        );
    }

    #[test]
    fn recognizer_data_remains_send_and_sync() {
        fn assert_send_and_sync<T: Send + Sync>() {}

        assert_send_and_sync::<RecognizerData>();
    }

    #[test]
    fn recognizer_data_keeps_shared_metadata_out_of_line() {
        assert!(size_of::<RecognizerData>() < size_of::<RecognizerMetadata>());
    }

    #[test]
    fn cloned_recognizers_can_reconfigure_their_listener_lists_independently() {
        let mut original = test_recognizer();
        let clone = original.clone();

        original.remove_error_listeners();

        assert!(!original.data.console_error_listener);
        assert!(original.data.error_listeners.is_empty());
        assert!(clone.data.console_error_listener);
        assert!(clone.data.error_listeners.is_empty());
    }

    #[test]
    fn generated_recognizers_share_metadata_but_not_instance_state() {
        let mut first = SHARED_METADATA.recognizer_data();
        let second = SHARED_METADATA.recognizer_data();

        assert!(std::ptr::eq(first.rule_names(), second.rule_names()));
        assert!(std::ptr::eq(first.vocabulary(), second.vocabulary()));
        assert!(first.console_error_listener);
        assert!(second.console_error_listener);

        first.set_state(7);
        first.remove_error_listeners();

        assert_eq!(first.state(), 7);
        assert_eq!(second.state(), -1);
        assert!(!first.console_error_listener);
        assert!(first.error_listeners.is_empty());
        assert!(second.console_error_listener);
        assert!(second.error_listeners.is_empty());
    }

    #[test]
    fn customizing_shared_metadata_detaches_only_that_recognizer() {
        let customized = SHARED_METADATA
            .recognizer_data()
            .with_rule_names(["replacement"]);
        let shared = SHARED_METADATA.recognizer_data();

        assert_eq!(customized.rule_names(), ["replacement"]);
        assert_eq!(shared.rule_names(), ["start"]);
        assert!(!std::ptr::eq(customized.rule_names(), shared.rule_names()));
    }
}