Skip to main content

antlr4_runtime/
recognizer.rs

1use crate::vocabulary::Vocabulary;
2
3#[derive(Clone, Debug)]
4pub struct RecognizerData {
5    grammar_file_name: String,
6    rule_names: Vec<String>,
7    channel_names: Vec<String>,
8    mode_names: Vec<String>,
9    vocabulary: Vocabulary,
10    state: isize,
11}
12
13impl RecognizerData {
14    pub fn new(grammar_file_name: impl Into<String>, vocabulary: Vocabulary) -> Self {
15        Self {
16            grammar_file_name: grammar_file_name.into(),
17            rule_names: Vec::new(),
18            channel_names: Vec::new(),
19            mode_names: Vec::new(),
20            vocabulary,
21            state: -1,
22        }
23    }
24
25    #[must_use]
26    pub fn with_rule_names(
27        mut self,
28        rule_names: impl IntoIterator<Item = impl Into<String>>,
29    ) -> Self {
30        self.rule_names = rule_names.into_iter().map(Into::into).collect();
31        self
32    }
33
34    #[must_use]
35    pub fn with_channel_names(
36        mut self,
37        channel_names: impl IntoIterator<Item = impl Into<String>>,
38    ) -> Self {
39        self.channel_names = channel_names.into_iter().map(Into::into).collect();
40        self
41    }
42
43    #[must_use]
44    pub fn with_mode_names(
45        mut self,
46        mode_names: impl IntoIterator<Item = impl Into<String>>,
47    ) -> Self {
48        self.mode_names = mode_names.into_iter().map(Into::into).collect();
49        self
50    }
51
52    /// Rule names owned by this recognizer's metadata.
53    ///
54    /// Also available through [`Recognizer::rule_names`]; this inherent
55    /// accessor lets callers that already hold a `RecognizerData` field
56    /// borrow rule names without borrowing the whole recognizer.
57    #[must_use]
58    pub fn rule_names(&self) -> &[String] {
59        &self.rule_names
60    }
61
62    pub const fn state(&self) -> isize {
63        self.state
64    }
65
66    pub const fn set_state(&mut self, state: isize) {
67        self.state = state;
68    }
69}
70
71pub trait Recognizer {
72    fn data(&self) -> &RecognizerData;
73    fn data_mut(&mut self) -> &mut RecognizerData;
74
75    fn grammar_file_name(&self) -> &str {
76        &self.data().grammar_file_name
77    }
78
79    fn rule_names(&self) -> &[String] {
80        &self.data().rule_names
81    }
82
83    fn channel_names(&self) -> &[String] {
84        &self.data().channel_names
85    }
86
87    fn mode_names(&self) -> &[String] {
88        &self.data().mode_names
89    }
90
91    fn vocabulary(&self) -> &Vocabulary {
92        &self.data().vocabulary
93    }
94
95    fn state(&self) -> isize {
96        self.data().state()
97    }
98
99    fn set_state(&mut self, state: isize) {
100        self.data_mut().set_state(state);
101    }
102
103    fn sempred(&mut self, _rule_index: usize, _pred_index: usize) -> bool {
104        true
105    }
106
107    fn action(&mut self, _rule_index: usize, _action_index: usize) {}
108}