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
/*
* Copyright 2022 Arnaud Golfouse
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
//! Computation of data specific to the grammar.
//!
//! This includes nullables nodes, or the FIRST₁ sets.
mod conflict_resolution;
mod first_set;
mod nullable;
use self::{first_set::FirstSets, nullable::Nullables};
use crate::{
input::{Grammar, Node, ProdIdx, Symbol, Token},
output::error::CycleError,
structures::{Map, Set},
};
use std::ops;
pub(crate) use self::conflict_resolution::{
ConflictResolutionCache, ContributionIndex, ContributionSelection, ReduceIdx, ShiftOrReduce,
};
#[derive(Debug)]
pub(crate) struct GrammarData<'a> {
/// Reference to the grammar.
pub(crate) grammar: &'a Grammar,
/// Which nodes are nullable.
pub(crate) nullables: Nullables,
first_sets: FirstSets,
}
impl<'a> GrammarData<'a> {
pub(crate) fn new(grammar: &'a Grammar) -> Result<Self, CycleError> {
let nullables = Nullables::new(grammar);
Self::check_cycles(grammar, &nullables)?;
let first_sets = FirstSets::new(grammar, &nullables);
Ok(Self {
grammar,
nullables,
first_sets,
})
}
/// Returns `{ t ∈ Tokens ∣ symbols ⇒* tα }`
///
/// FIXME: precedence may forbid some derived tokens. This is very unlikely to
/// happen in real life grammars though.
///
/// Precision : for example, if the precedence of an hypothetical prefix operator
/// `'@'` is weaker than `'+'`, then we can't derive `E → E + E → @ E + E` : thus
/// `E + E` should not derive `@`.
pub(crate) fn derived_tokens(&self, symbols: &[Symbol]) -> Set<Token> {
let mut result = Set::default();
for symbol in symbols {
match symbol {
Symbol::Token(t) => {
result.insert(*t);
break;
}
Symbol::Node(n) => {
if let Some(set) = self.first_sets.get(n) {
result.extend(set);
}
if !self.nullables.is_nullable(*n) {
break;
}
}
}
}
result
}
/// Check for `A ⇒+ A` derivations.
// TODO: use conflict_resolution::graph_has_cycle ?
fn check_cycles(grammar: &Grammar, nullables: &Nullables) -> Result<(), CycleError> {
// Map `A` to `{ B ∣ A ⇒ αBβ, with α ⇒* ε, β ⇒* ε }`.
let mut matches_single_node: Map<Node, Set<(Node, ProdIdx)>> = Map::default();
'prod: for (prod_idx, rhs) in grammar.get_all_productions() {
let lhs = prod_idx.lhs;
let mut matched_nodes = Set::default();
let mut nullable = true;
for symbol in rhs {
match *symbol {
Symbol::Token(_) => continue 'prod,
Symbol::Node(n) => {
let is_nullable = nullables.is_nullable(n);
if nullable {
matched_nodes.insert(n);
nullable = is_nullable;
} else if !is_nullable {
continue 'prod;
}
}
}
}
matches_single_node
.entry(lhs)
.or_default()
.extend(matched_nodes.into_iter().map(|node| (node, prod_idx)));
}
/// By using `matches_single_node`, go through the graph of `A ⇒ B` nodes, and
/// tries to find `node`.
///
/// # Returns
/// The path necessary to derive `node ⇒+ node`.
fn find_self_match(
matches_single_node: &Map<Node, Set<(Node, ProdIdx)>>,
node: Node,
at: Node,
visited: &mut Set<Node>,
) -> Option<Vec<ProdIdx>> {
let matched = matches_single_node.get(&at)?;
for &(n, prod) in matched {
if n == node {
return Some(vec![prod]);
}
if visited.insert(n) {
if let Some(mut path) = find_self_match(matches_single_node, node, n, visited) {
path.push(prod);
return Some(path);
}
}
}
None
}
for &node in matches_single_node.keys() {
if let Some(mut path) =
find_self_match(&matches_single_node, node, node, &mut Set::default())
{
path.reverse();
return Err(CycleError { node, path });
}
}
Ok(())
}
}
impl<'a> ops::Deref for GrammarData<'a> {
type Target = Grammar;
fn deref(&self) -> &Self::Target {
self.grammar
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
input::Symbol::{Node as N, Token as T},
test_common::{
nodes::{N1, N2, N3, START},
tokens::T1,
},
};
#[test]
fn cycle_error() {
let mut grammar = Grammar::new();
let prod = grammar.add_production(START, vec![N(START)]).unwrap();
assert_eq!(
GrammarData::new(&grammar).unwrap_err(),
CycleError {
node: START,
path: vec![prod]
}
);
let mut grammar = Grammar::new();
for (lhs, rhs) in [
(START, vec![N(N1)]),
(N1, vec![N(N2), T(T1)]),
(N1, vec![N(N2), N(N3)]),
(N2, vec![N(N3)]),
(N3, vec![]),
(N3, vec![N(N1)]),
] {
grammar.add_production(lhs, rhs).unwrap();
}
assert!(GrammarData::new(&grammar).is_err());
}
}