-
Notifications
You must be signed in to change notification settings - Fork 4
/
tables.rs
280 lines (247 loc) · 11.1 KB
/
tables.rs
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
use crate::prelude::*;
/// First table of the symbols in a grammar.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_renamed"))]
#[derive(Debug)]
pub struct FirstTable(IndexMap<Symbol, IndexSet<Token>>);
impl FirstTable {
/// Constructs the first table from the grammar.
pub fn construct(grammar: &Grammar) -> FirstTable {
let mut first_table = IndexMap::new();
let mut indirectly_empty_symbols = IndexSet::new();
let mut done = false;
while !done {
done = true;
for rule in grammar.rules().iter() {
let mut possible_first_tokens: IndexSet<Token> =
first_table.get(rule.symbol()).cloned().unwrap_or_default();
let old_possible_first_token_count = possible_first_tokens.len();
for (index, atomic_pattern) in rule.pattern().iter().enumerate() {
match atomic_pattern {
AtomicPattern::Symbol(symbol) => {
if let Some(new_possible_first_tokens) = first_table.get(symbol) {
possible_first_tokens.extend(
new_possible_first_tokens
.iter()
.filter(|&possible_token| *possible_token != Token::Empty)
.cloned(),
);
}
if !grammar.empty_symbols().contains(symbol)
&& !indirectly_empty_symbols.contains(symbol)
{
break;
}
},
AtomicPattern::Token(token) => {
possible_first_tokens.insert(token.clone());
break;
},
}
if index == rule.pattern().len() - 1 {
indirectly_empty_symbols.insert(rule.symbol());
possible_first_tokens.insert(Token::Empty);
}
}
let new_possible_first_token_count = possible_first_tokens.len();
if new_possible_first_token_count != old_possible_first_token_count {
done = false;
first_table.insert(rule.symbol().clone(), possible_first_tokens);
}
}
}
FirstTable(first_table)
}
}
impl Deref for FirstTable {
type Target = IndexMap<Symbol, IndexSet<Token>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Follow table of the symbols in a grammar.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_renamed"))]
#[derive(Debug)]
pub struct FollowTable(IndexMap<Symbol, IndexSet<Token>>);
impl FollowTable {
/// Constructs the follow table from the grammar.
pub fn construct(grammar: &Grammar, first_table: &FirstTable) -> FollowTable {
let mut follow_table =
IndexMap::from([(grammar.start_symbol().clone(), IndexSet::from([Token::Eof]))]);
let mut done = false;
while !done {
done = true;
for rule in grammar.rules() {
let rule_symbol = rule.symbol();
let rule_pattern = rule.pattern();
let last_ap_index = rule_pattern.len() - 1;
for (ap_index, ap) in rule_pattern.iter().enumerate() {
let atomic_pattern_symbol = match ap {
AtomicPattern::Symbol(symbol) => symbol,
AtomicPattern::Token(_) => continue,
};
let mut possible_follow_tokens =
follow_table.get(atomic_pattern_symbol).cloned().unwrap_or_default();
let old_possible_follow_token_count = possible_follow_tokens.len();
if ap_index != last_ap_index {
let mut rest_of_the_pattern_can_be_empty = true;
for next_atomic_pattern in &rule_pattern[ap_index + 1..] {
match next_atomic_pattern {
AtomicPattern::Symbol(next_symbol) => {
if let Some(first_set) = first_table.get(next_symbol) {
possible_follow_tokens.extend(
first_set
.iter()
.filter(|&t| *t != Token::Empty)
.cloned(),
);
if !first_set.contains(&Token::Empty) {
rest_of_the_pattern_can_be_empty = false;
break;
}
}
},
AtomicPattern::Token(token) => {
possible_follow_tokens.insert(token.clone());
rest_of_the_pattern_can_be_empty = false;
break;
},
}
}
if rest_of_the_pattern_can_be_empty {
if let Some(rule_symbol_follow) = follow_table.get(rule_symbol) {
possible_follow_tokens.extend(rule_symbol_follow.iter().cloned());
}
}
} else if let Some(rule_symbol_follow) = follow_table.get(rule_symbol) {
possible_follow_tokens.extend(rule_symbol_follow.iter().cloned());
}
let new_possible_follow_token_count = possible_follow_tokens.len();
if new_possible_follow_token_count != old_possible_follow_token_count {
done = false;
follow_table.insert(atomic_pattern_symbol.clone(), possible_follow_tokens);
}
}
}
}
FollowTable(follow_table)
}
}
impl Deref for FollowTable {
type Target = IndexMap<Symbol, IndexSet<Token>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Action (e.g., `Shift 3`, `Reduce 2`, `Accept 1`) to perform during a parsing step.
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_renamed"))]
#[cfg_attr(feature = "serde", serde(tag = "type", content = "value"))]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Action {
/// Shift the first remaining input token into symbol stack and transition to a new state.
Shift {
/// State to transition to.
next_state: usize,
},
/// Apply a rule of the grammar to the symbol and state stacks, then goto a new state.
Reduce {
/// Index of the rule to reduce.
rule_index: usize,
},
/// Accept the parse and finish parsing.
Accept {
/// Index of the rule that was matched.
rule_index: usize,
},
}
impl Display for Action {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Action::Shift { next_state } => write!(f, "s{}", next_state),
Action::Reduce { rule_index } => write!(f, "r{}", rule_index + 1),
Action::Accept { rule_index } => write!(f, "a{}", rule_index + 1),
}
}
}
/// Action and goto tables of a parser.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(crate = "serde_renamed"))]
#[derive(Debug)]
pub struct ParsingTables {
action_table: Vec<IndexMap<Token, IndexSet<Action>>>,
goto_table: Vec<IndexMap<Symbol, usize>>,
}
impl ParsingTables {
/// Constructs the parsing tables of the parser.
pub fn construct(
grammar: &Grammar,
follow_table: &FollowTable,
automaton: &Automaton,
) -> Result<ParsingTables, ParserError> {
let mut action_table = Vec::with_capacity(automaton.states().len());
let mut goto_table = Vec::with_capacity(automaton.states().len());
for state in automaton.states().iter() {
let mut actions = IndexMap::<Token, IndexSet<Action>>::new();
let mut gotos = IndexMap::<Symbol, usize>::new();
for item in state.items() {
let rule = item.rule();
if item.dot() == rule.pattern().len() || rule.is_empty_pattern() {
if let Some(follows) = follow_table.get(item.rule().symbol()) {
let rule_index =
grammar.rules().iter().position(|rule| rule == item.rule()).unwrap();
for token in follows {
if !item.lookahead().contains(token) {
continue;
}
if *token == Token::Eof
&& item.rule().symbol() == grammar.start_symbol()
{
actions
.entry(token.clone())
.or_default()
.insert(Action::Accept { rule_index });
} else {
actions
.entry(token.clone())
.or_default()
.insert(Action::Reduce { rule_index });
}
}
}
} else {
let next_atomic_pattern = &item.rule().pattern()[item.dot()];
let transition = state.transitions()[next_atomic_pattern];
match next_atomic_pattern {
AtomicPattern::Symbol(symbol) => {
gotos.insert(symbol.clone(), transition);
},
AtomicPattern::Token(token) => {
actions
.entry(token.clone())
.or_default()
.insert(Action::Shift { next_state: transition });
},
}
}
}
action_table.push(actions);
goto_table.push(gotos);
}
Ok(ParsingTables { action_table, goto_table })
}
}
impl ParsingTables {
/// Gets the action table of the parser.
pub fn action_table(&self) -> &[IndexMap<Token, IndexSet<Action>>] {
&self.action_table
}
/// Gets the goto table of the parser.
pub fn goto_table(&self) -> &[IndexMap<Symbol, usize>] {
&self.goto_table
}
}