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
#![deny(warnings)]
use grammar::{Symbol, Grammar};
use items::{Item, StateSet};
use std::iter::FromIterator;
use std::rc::Rc;
#[derive(PartialEq,Debug)]
pub struct ParseError;
pub struct EarleyParser {
pub g: Grammar,
}
#[derive(Debug)]
pub struct ParseTrees(pub Vec<Rc<Item>>);
impl EarleyParser {
pub fn new(grammar: Grammar) -> EarleyParser { EarleyParser{g: grammar} }
pub fn parse<S>(&self, tok: S) -> Result<ParseTrees, ParseError>
where S: Iterator<Item=String> { self._parse(tok, false) }
pub fn debug<S>(&self, tok: S) -> Result<ParseTrees, ParseError>
where S: Iterator<Item=String> { self._parse(tok, true) }
fn _parse<S>(&self, mut tok: S, debug: bool)
-> Result<ParseTrees, ParseError> where S: Iterator<Item=String> {
let mut states = Vec::new();
states.push(StateSet::from_iter(
self.g.rules_for(&self.g.start)
.into_iter()
.map(|r| Item::predict_new(&r, 0))));
let mut state_idx = 0;
while states.len() > state_idx {
let mut prev_size = -1;
while (states[state_idx].len() as isize) != prev_size {
prev_size = states[state_idx].len() as isize;
let mut new_items = Vec::new();
for itm in states[state_idx].iter() {
new_items.extend(match itm.next_symbol() {
Some(&Symbol::NonTerm(ref name)) =>
self.g.rules_for(name.as_ref())
.into_iter()
.map(|r| Item::predict_new(&r, state_idx))
.collect(),
None => states[itm.start].completed_by(&itm, state_idx),
_ => Vec::new(),
});
}
states[state_idx].extend(new_items);
}
if let Some(lexeme) = tok.next() {
let scans =
states[state_idx].advanced_by_scan(&lexeme, state_idx+1);
states.push(StateSet::from_iter(scans));
assert_eq!(states.len(), state_idx + 2);
}
state_idx += 1;
}
if debug {
for (idx, stateset) in states.iter().enumerate() {
eprintln!("=== {} ===", idx);
for item in stateset.iter() { eprintln!("{:?}", item); }
}
eprintln!("=========");
}
let parse_trees = states
.last().ok_or(ParseError)?
.filter_rule_head(self.g.start.as_ref())
.filter(|item| item.start == 0 && item.complete())
.cloned()
.collect::<Vec<_>>();
match parse_trees.is_empty() {
true => Err(ParseError),
false => Ok(ParseTrees(parse_trees)),
}
}
}
#[cfg(test)]
mod tests {
extern crate lexers;
use grammar::GrammarBuilder;
use self::lexers::{Scanner, DelimTokenizer};
use super::{EarleyParser, ParseError};
#[test]
fn partial_parse() {
let g = GrammarBuilder::new()
.symbol("Start")
.symbol(("+", |n: &str| n == "+"))
.rule("Start", &["+", "+"])
.into_grammar("Start")
.expect("Bad Grammar");
let mut input = DelimTokenizer::from_str("+++", "+", false);
let out = EarleyParser::new(g).parse(&mut input);
assert_eq!(out.unwrap_err(), ParseError);
}
#[test]
fn badparse() {
let g = GrammarBuilder::new()
.symbol("Sum")
.symbol("Num")
.symbol(("Number", |n: &str| n.chars().all(|c| "1234".contains(c))))
.symbol(("[+-]", |n: &str| n.len() == 1 && "+-".contains(n)))
.rule("Sum", &["Sum", "[+-]", "Num"])
.rule("Sum", &["Num"])
.rule("Num", &["Number"])
.into_grammar("Sum")
.expect("Bad Grammar");
let mut input = DelimTokenizer::from_str("1+", "+*", false);
let out = EarleyParser::new(g).parse(&mut input);
assert_eq!(out.unwrap_err(), ParseError);
}
#[test]
fn grammar_ambiguous() {
let grammar = GrammarBuilder::new()
.symbol("S")
.symbol(("b", |n: &str| n == "b"))
.rule("S", &["S", "S"])
.rule("S", &["b"])
.into_grammar("S")
.expect("Bad Grammar");
let mut input = DelimTokenizer::from_str("b b b", " ", true);
EarleyParser::new(grammar).parse(&mut input)
.expect("Broken Parser");
}
#[test]
fn left_recurse() {
let grammar = GrammarBuilder::new()
.symbol("S")
.symbol("N")
.symbol(("[+]", |n: &str| n == "+"))
.symbol(("[0-9]", |n: &str| "1234567890".contains(n)))
.rule("S", &["S", "[+]", "N"])
.rule("S", &["N"])
.rule("N", &["[0-9]"])
.into_grammar("S")
.expect("Bad grammar");
let mut input = DelimTokenizer::from_str("1+2", "+", false);
EarleyParser::new(grammar).parse(&mut input)
.expect("Broken Parser");
}
#[test]
fn test_right_recurse() {
let grammar = GrammarBuilder::new()
.symbol("P")
.symbol("N")
.symbol(("[^]", |n: &str| n == "^"))
.symbol(("[0-9]", |n: &str| "1234567890".contains(n)))
.rule("P", &["N", "[^]", "P"])
.rule("P", &["N"])
.rule("N", &["[0-9]"])
.into_grammar("P")
.expect("Bad grammar");
let mut input = DelimTokenizer::from_str("1^2", "^", false);
EarleyParser::new(grammar).parse(&mut input)
.expect("Broken Parser");
}
#[test]
fn bogus_empty() {
let grammar = GrammarBuilder::new()
.symbol("A")
.symbol("B")
.rule::<_, &str>("A", &[])
.rule("A", &vec!["B"])
.rule("B", &vec!["A"])
.into_grammar("A")
.expect("Bad grammar");
let mut input = DelimTokenizer::from_str("", "-", false);
EarleyParser::new(grammar).parse(&mut input)
.expect("Broken Parser");
}
#[test]
fn bogus_epsilon() {
let grammar = GrammarBuilder::new()
.symbol("P")
.symbol(("(", |l: &str| l == "("))
.symbol((")", |l: &str| l == ")"))
.rule("P", &["(", "P", ")"])
.rule("P", &["P", "P"])
.rule::<_, &str>("P", &[])
.into_grammar("P")
.expect("Bad grammar");
let mut input = Scanner::from_buf("".split_whitespace()
.map(|s| s.to_string()));
EarleyParser::new(grammar).parse(&mut input)
.expect("Broken Parser");
}
}