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
#![allow(clippy::result_unit_err)]
use crate::parser::peg::parse_error::{Expect, PEGParseError};
use crate::parser::peg::parse_result::ParseResult;
use crate::parser::peg::parser_core::{ParserContext, ParserState};
use crate::parser::peg::parser_core_ast::{CoreExpression, CoreSort, ParsePairRaw};
use crate::parser::peg::parser_sugar_ast::Annotation;
use crate::sources::source_file::SourceFileIterator;
use crate::sources::span::Span;
pub struct ExpressionContext<'src> {
pub name: Option<&'src str>,
pub error: Option<&'src String>,
}
impl<'src> ExpressionContext<'src> {
pub fn empty() -> Self {
Self {
name: None,
error: None,
}
}
}
/// Given an expression and the current position, attempts to parse this constructor.
pub fn parse_expression_name<'src>(
state: &ParserContext<'src>,
cache: &mut ParserState<'src>,
expr_name: &'src str,
pos: SourceFileIterator<'src>,
) -> ParseResult<'src, ParsePairRaw> {
let sort: &'src CoreSort = state
.ast
.sorts
.get(expr_name)
.expect("name is guaranteed to exist");
let expr = &sort.expr;
let sort_context = ExpressionContext {
name: Some(sort.name),
error: sort.annotations.iter().find_map(|i| {
if let Annotation::Error(e) = i {
Some(e)
} else {
None
}
}),
};
//Check if this result is cached
let key = (pos.position(), expr_name);
if let Some(cached) = cache.get_mut(&key) {
return cached.clone();
}
//Before executing, put a value for the current position in the cache.
//This value is used if the rule is left-recursive
let cache_state = cache.state_current();
cache.insert(
key,
ParseResult::new_err(
ParsePairRaw::Error(Span::from_length(state.file, pos.position(), 0)),
pos.clone(),
pos.clone(),
),
);
//Now execute the actual rule, taking into account left recursion
//The way this is done is heavily inspired by http://web.cs.ucla.edu/~todd/research/pepm08.pdf
//A quick summary
//- First put an error value for the current (rule, position) in the cache
//- Try to parse the current (rule, position). If this fails, there is definitely no left recursion. Otherwise, we now have a seed.
//- Put the new seed in the cache, and rerun on the current (rule, position). Make sure to revert the cache to the previous state.
//- At some point, the above will fail. Either because no new input is parsed, or because the entire parse now failed. At this point, we have reached the maximum size.
let mut res = parse_expression(state, cache, expr, pos.clone(), &sort_context);
let res = if res.ok {
//Do we have a leftrec case?
if !cache.is_read(&key).unwrap() {
//There was no leftrec, just return the value
res
} else {
//There was leftrec, we need to grow the seed
loop {
//Insert the current seed into the cache
cache.state_revert(cache_state);
cache.insert(key, res.clone());
//Grow the seed
let new_res = parse_expression(state, cache, expr, pos.clone(), &sort_context);
if !new_res.ok {
break;
}
if new_res.pos.position() <= res.pos.position() {
break;
}
res = new_res;
}
//The seed is at its maximum size
cache.insert(key, res.clone());
res
}
} else {
// Left recursion value was used, but did not make a seed.
// This is an illegal grammar!
if cache.is_read(&key).unwrap() {
cache.add_error(PEGParseError::fail_left_recursion(Span::from_length(
state.file,
pos.position(),
0,
)));
}
res
};
cache.insert(key, res.clone());
//Return result
res
}
pub fn parse_expression<'src>(
state: &ParserContext<'src>,
cache: &mut ParserState<'src>,
expr: &'src CoreExpression,
mut pos: SourceFileIterator<'src>,
sort_context: &ExpressionContext<'src>,
) -> ParseResult<'src, ParsePairRaw> {
match expr {
//To parse a sort, call parse_sort recursively.
CoreExpression::Name(sort_name) => {
let res = parse_expression_name(state, cache, sort_name, pos);
res.map(|s| ParsePairRaw::Name(s.span(), Box::new(s)))
}
//To parse a character class, check if the character is accepted, and make an ok/error based on that.
CoreExpression::CharacterClass(characters) => {
while cache.allow_layout && !pos.clone().accept(characters) {
let (ok, after_layout_pos) =
skip_single_layout(state, cache, pos.clone(), sort_context);
if !ok {
break;
};
pos = after_layout_pos;
}
let span = Span::from_length(state.file, pos.position(), 1);
if pos.accept(characters) {
if cache.no_layout_nest_count > 0 {
cache.allow_layout = false;
}
ParseResult::new_ok(ParsePairRaw::Empty(span), pos.clone(), pos, false)
} else {
cache.add_error(PEGParseError::expect(
span.clone(),
Expect::ExpectCharClass(characters.clone()),
sort_context,
));
ParseResult::new_err(ParsePairRaw::Error(span), pos.clone(), pos)
}
}
//To parse a sequence, parse each constructor in the sequence.
//The results are added to `results`, and the best error and position are updated each time.
//Finally, construct a `ParsePairConstructor::List` with the results.
CoreExpression::Sequence(subexprs) => {
let mut results = vec![];
let start_pos = pos.position();
let mut pos_err = pos.clone();
let mut recovered = false;
//Parse all subconstructors in sequence
for (i, subexpr) in subexprs.iter().enumerate() {
let res = parse_expression(state, cache, subexpr, pos, sort_context);
pos = res.pos;
pos_err.max_pos(res.pos_err.clone());
results.push(res.result);
recovered |= res.recovered;
if !res.ok {
if let Some(&offset) = state.errors.get(&res.pos_err.position()) {
//The first token of the sequence can not be skipped, otherwise we can just parse a lot of empty sequences, if a sequence happens in a repeat
if i != 0 && cache.no_errors_nest_count == 0 {
pos = res.pos_err;
//If we're at the end of the file, don't try
if pos.peek().is_none() {
let span = Span::from_end(state.file, start_pos, pos.position());
return ParseResult::new_err(
ParsePairRaw::List(span, results),
pos,
pos_err,
);
}
pos.skip_n(offset);
recovered = true;
continue;
}
}
let start_pos = results
.get(0)
.map(|pp| pp.span().position)
.unwrap_or(start_pos);
let span = Span::from_end(state.file, start_pos, pos.position());
return ParseResult::new_err(ParsePairRaw::List(span, results), pos, pos_err);
}
}
//Construct result
let start_pos = results
.get(0)
.map(|pp| pp.span().position)
.unwrap_or(start_pos);
let span = Span::from_end(state.file, start_pos, pos.position());
ParseResult::new_ok(ParsePairRaw::List(span, results), pos, pos_err, recovered)
}
//To parse a sequence, first parse the minimum amount that is needed.
//Then keep trying to parse the constructor until the maximum is reached.
//The results are added to `results`, and the best error and position are updated each time.
//Finally, construct a `ParsePairConstructor::List` with the results.
CoreExpression::Repeat { subexpr, min, max } => {
let mut results = vec![];
let start_pos = pos.position();
let mut last_pos = pos.position();
let mut pos_err = pos.clone();
let mut recovered = false;
//Parse at most maximum times
for i in 0..max.unwrap_or(u64::MAX) {
let res =
parse_expression(state, cache, subexpr.as_ref(), pos.clone(), sort_context);
pos_err.max_pos(res.pos_err.clone());
recovered |= res.recovered;
if res.ok {
pos = res.pos;
results.push(res.result);
} else {
//If we know about this error, try to continue?
//Don't try to continue if we haven't made any progress (already failed on first character), since we will just fail again
//Also don't try to continue if we don't allow errors at the moment, since we don't want to try to recover inside of an no-errors segment
if let Some(&offset) = state.errors.get(&res.pos_err.position()) {
if (offset > 0 || pos.position() != res.pos_err.position())
&& cache.no_errors_nest_count == 0
{
pos = res.pos_err.clone();
//If we're at the end of the file, don't try
if pos.peek().is_none() {
let span = Span::from_end(state.file, start_pos, pos.position());
return ParseResult::new_err(
ParsePairRaw::List(span, results),
pos,
pos_err,
);
}
pos.skip_n(offset);
results.push(res.result);
recovered = true;
continue;
}
}
//If we have not yet reached the minimum, we error.
//Otherwise, we break and ok after the loop body.
//In case we reached the minimum, we don't push the error, even though the failure might've been an error.
//This is because it's probably OK, and we want no Error pairs in the parse tree when it's OK.
if i < *min {
pos = res.pos;
results.push(res.result);
let start_pos = results
.get(0)
.map(|pp| pp.span().position)
.unwrap_or(start_pos);
let span = Span::from_end(state.file, start_pos, pos.position());
return ParseResult::new_err(
ParsePairRaw::List(span, results),
pos,
pos_err,
);
} else {
break;
}
}
//If the position hasn't changed, then we're in an infinite loop
if last_pos == pos.position() {
let span = Span::from_length(state.file, pos.position(), 0);
cache.add_error(PEGParseError::fail_loop(span.clone()));
return ParseResult::new_err(ParsePairRaw::List(span, results), pos, pos_err);
}
last_pos = pos.position();
}
//Construct result
let start_pos = results
.get(0)
.map(|pp| pp.span().position)
.unwrap_or(start_pos);
let span = Span::from_end(state.file, start_pos, pos.position());
ParseResult::new_ok(
ParsePairRaw::List(span, results),
pos.clone(),
pos_err,
recovered,
)
}
//To parse a choice, try each constructor, keeping track of the best error that occurred while doing so.
//If none of the constructors succeed, we will return this error.
CoreExpression::Choice(subexprs) => {
//Try each constructor, keeping track of the best error that occurred while doing so.
//If none of the constructors succeed, we will return this error.
let mut results = vec![];
assert!(!subexprs.is_empty());
for (i, subexpr) in subexprs.iter().enumerate() {
let res = parse_expression(state, cache, subexpr, pos.clone(), sort_context);
if res.ok && !res.recovered {
return ParseResult::new_ok(
ParsePairRaw::Choice(res.result.span(), i, Box::new(res.result)),
res.pos,
res.pos_err,
res.recovered,
);
}
results.push(res);
}
//Chose best candidate
let (i, res) = results
.into_iter()
.enumerate()
.max_by_key(|(_, r)| r.pos_err.position())
.unwrap();
ParseResult::new(
ParsePairRaw::Choice(res.result.span(), i, Box::new(res.result)),
res.pos,
res.pos_err,
res.ok,
res.recovered,
)
}
//No layout is parsed by setting the no layout flag during parsing
//After the block is completed, if no layout nest count is 0, re-allow layout.
CoreExpression::FlagNoLayout(subexpr) => {
cache.no_layout_nest_count += 1;
let res = parse_expression(state, cache, subexpr, pos, sort_context);
cache.no_layout_nest_count -= 1;
if cache.no_layout_nest_count == 0 {
cache.allow_layout = true;
}
res
}
//No errors is parsed by setting the no errors flag during parsing
//After the block is completed, is not ok, produce an error.
CoreExpression::FlagNoErrors(subexpr, name) => {
cache.no_errors_nest_count += 1;
let start_pos = pos.position();
let res = parse_expression(state, cache, subexpr, pos.clone(), sort_context);
cache.no_errors_nest_count -= 1;
if !res.ok {
let mut next_pos = res.pos.clone();
next_pos.skip_n(1);
let span = Span::from_end(state.file, start_pos, next_pos.position());
let err =
PEGParseError::expect(span, Expect::ExpectSort(name.to_string()), sort_context);
cache.add_error(err);
}
res
}
CoreExpression::Error(e, msg) => {
let pos_backup = pos.clone();
let start_pos = pos.position();
let mut res = parse_expression(state, cache, e, pos.clone(), sort_context);
if res.ok {
let mut next_pos = res.pos.clone();
next_pos.skip_n(1);
let span = Span::from_end(state.file, start_pos, next_pos.position());
let err =
PEGParseError::expect(span, Expect::Custom(msg.to_string()), sort_context);
cache.add_error(err);
res.pos = pos_backup;
}
res
}
}
}
pub fn skip_single_layout<'src>(
state: &ParserContext<'src>,
cache: &mut ParserState<'src>,
pos: SourceFileIterator<'src>,
sort_context: &ExpressionContext<'src>,
) -> (bool, SourceFileIterator<'src>) {
//Automatically make layout rule no-layout and no-errors
let prev_allow_layout = cache.allow_layout;
cache.no_layout_nest_count += 1;
cache.no_errors_nest_count += 1;
cache.allow_layout = false;
let layout_sort = state.ast.sorts.get("layout").expect("Layout exists");
let layout_expr = &layout_sort.expr;
let layout_res = parse_expression(state, cache, layout_expr, pos.clone(), sort_context);
cache.no_layout_nest_count -= 1;
cache.no_errors_nest_count -= 1;
cache.allow_layout = prev_allow_layout;
(layout_res.ok, layout_res.pos)
}