Debian Codegraph @

third_party/rust/lalrpop-util/src/state_machine.rs

raw
1 #![allow(dead_code)]
2
3 use alloc::{string::String, vec, vec::Vec};
4 use core::fmt::Debug;
5
6 #[cfg(feature = "std")]
7 const DEBUG_ENABLED: bool = false;
8
9 macro_rules! debug {
10 ($($args:expr),* $(,)*) => {
11 #[cfg(feature = "std")]
12 if DEBUG_ENABLED {
13 eprintln!($($args),*);
14 }
15 }
16 }
17
18 pub trait ParserDefinition: Sized {
19 /// Represents a location in the input text. If you are using the
20 /// default tokenizer, this will be a `usize`.
21 type Location: Clone + Debug;
22
23 /// Represents a "user error" -- this can get produced by
24 /// `reduce()` if the grammar includes `=>?` actions.
25 type Error;
26
27 /// The type emitted by the user's tokenizer (excluding the
28 /// location information).
29 type Token: Clone + Debug;
30
31 /// We assign a unique index to each token in the grammar, which
32 /// we call its *index*. When we pull in a new `Token` from the
33 /// input, we then match against it to determine its index. Note
34 /// that the actual `Token` is retained too, as it may carry
35 /// additional information (e.g., an `ID` terminal often has a
36 /// string value associated with it; this is not important to the
37 /// parser, but the semantic analyzer will want it).
38 type TokenIndex: Copy + Clone + Debug;
39
40 /// The type representing things on the LALRPOP stack. Represents
41 /// the union of terminals and nonterminals.
42 type Symbol;
43
44 /// Type produced by reducing the start symbol.
45 type Success;
46
47 /// Identifies a state. Typically an i8, i16, or i32 (depending on
48 /// how many states you have).
49 type StateIndex: Copy + Clone + Debug;
50
51 /// Identifies an action.
52 type Action: ParserAction<Self>;
53
54 /// Identifies a reduction.
55 type ReduceIndex: Copy + Clone + Debug;
56
57 /// Identifies a nonterminal.
58 type NonterminalIndex: Copy + Clone + Debug;
59
60 /// Returns a location representing the "start of the input".
61 fn start_location(&self) -> Self::Location;
62
63 /// Returns the initial state.
64 fn start_state(&self) -> Self::StateIndex;
65
66 /// Converts the user's tokens into an internal index; this index
67 /// is then used to index into actions and the like. When using an
68 /// internal tokenizer, these indices are directly produced. When
69 /// using an **external** tokenier, however, this function matches
70 /// against the patterns given by the user: it is fallible
71 /// therefore as these patterns may not be exhaustive. If a token
72 /// value is found that doesn't match any of the patterns the user
73 /// supplied, then this function returns `None`, which is
74 /// translated into a parse error by LALRPOP ("unrecognized
75 /// token").
76 fn token_to_index(&self, token: &Self::Token) -> Option<Self::TokenIndex>;
77
78 /// Given the top-most state and the pending terminal, returns an
79 /// action. This can be either SHIFT(state), REDUCE(action), or
80 /// ERROR.
81 fn action(&self, state: Self::StateIndex, token_index: Self::TokenIndex) -> Self::Action;
82
83 /// Returns the action to take if an error occurs in the given
84 /// state. This function is the same as the ordinary `action`,
85 /// except that it applies not to the user's terminals but to the
86 /// "special terminal" `!`.
87 fn error_action(&self, state: Self::StateIndex) -> Self::Action;
88
89 /// Action to take if EOF occurs in the given state. This function
90 /// is the same as the ordinary `action`, except that it applies
91 /// not to the user's terminals but to the "special terminal" `$`.
92 fn eof_action(&self, state: Self::StateIndex) -> Self::Action;
93
94 /// If we reduce to a nonterminal in the given state, what state
95 /// do we go to? This is infallible due to the nature of LR(1)
96 /// grammars.
97 fn goto(&self, state: Self::StateIndex, nt: Self::NonterminalIndex) -> Self::StateIndex;
98
99 /// "Upcast" a terminal into a symbol so we can push it onto the
100 /// parser stack.
101 fn token_to_symbol(&self, token_index: Self::TokenIndex, token: Self::Token) -> Self::Symbol;
102
103 /// Returns the expected tokens in a given state. This is used for
104 /// error reporting.
105 fn expected_tokens(&self, state: Self::StateIndex) -> Vec<String>;
106
107 /// True if this grammar supports error recovery.
108 fn uses_error_recovery(&self) -> bool;
109
110 /// Given error information, creates an error recovery symbol that
111 /// we push onto the stack (and supply to user actions).
112 fn error_recovery_symbol(&self, recovery: ErrorRecovery<Self>) -> Self::Symbol;
113
114 /// Execute a reduction in the given state: that is, execute user
115 /// code. The start location indicates the "starting point" of the
116 /// current lookahead that is triggering the reduction (it is
117 /// `None` for EOF).
118 ///
119 /// The `states` and `symbols` vectors represent the internal
120 /// state machine vectors; they are given to `reduce` so that it
121 /// can pop off states that no longer apply (and consume their
122 /// symbols). At the end, it should also push the new state and
123 /// symbol produced.
124 ///
125 /// Returns a `Some` if we reduced the start state and hence
126 /// parsing is complete, or if we encountered an irrecoverable
127 /// error.
128 ///
129 /// FIXME. It would be nice to not have so much logic live in
130 /// reduce. It should just be given an iterator of popped symbols
131 /// and return the newly produced symbol (or error). We can use
132 /// `simulate_reduce` and our own information to drive the rest,
133 /// right? This would also allow us -- I think -- to extend error
134 /// recovery to cover user-produced errors.
135 fn reduce(
136 &mut self,
137 reduce_index: Self::ReduceIndex,
138 start_location: Option<&Self::Location>,
139 states: &mut Vec<Self::StateIndex>,
140 symbols: &mut Vec<SymbolTriple<Self>>,
141 ) -> Option<ParseResult<Self>>;
142
143 /// Returns information about how many states will be popped
144 /// during a reduction, and what nonterminal would be produced as
145 /// a result.
146 fn simulate_reduce(&self, action: Self::ReduceIndex) -> SimulatedReduce<Self>;
147 }
148
149 pub trait ParserAction<D: ParserDefinition>: Copy + Clone + Debug {
150 fn as_shift(self) -> Option<D::StateIndex>;
151 fn as_reduce(self) -> Option<D::ReduceIndex>;
152 fn is_shift(self) -> bool;
153 fn is_reduce(self) -> bool;
154 fn is_error(self) -> bool;
155 }
156
157 pub enum SimulatedReduce<D: ParserDefinition> {
158 Reduce {
159 states_to_pop: usize,
160 nonterminal_produced: D::NonterminalIndex,
161 },
162
163 // This reduce is the "start" fn, so the parse is done.
164 Accept,
165 }
166
167 // These aliases are an elaborate hack to get around
168 // the warnings when you define a type alias like `type Foo<D: Trait>`
169 #[doc(hidden)]
170 pub type Location<D> = <D as ParserDefinition>::Location;
171 #[doc(hidden)]
172 pub type Token<D> = <D as ParserDefinition>::Token;
173 #[doc(hidden)]
174 pub type Error<D> = <D as ParserDefinition>::Error;
175 #[doc(hidden)]
176 pub type Success<D> = <D as ParserDefinition>::Success;
177 #[doc(hidden)]
178 pub type Symbol<D> = <D as ParserDefinition>::Symbol;
179
180 pub type ParseError<D> = crate::ParseError<Location<D>, Token<D>, Error<D>>;
181 pub type ParseResult<D> = Result<Success<D>, ParseError<D>>;
182 pub type TokenTriple<D> = (Location<D>, Token<D>, Location<D>);
183 pub type SymbolTriple<D> = (Location<D>, Symbol<D>, Location<D>);
184 pub type ErrorRecovery<D> = crate::ErrorRecovery<Location<D>, Token<D>, Error<D>>;
185
186 pub struct Parser<D, I>
187 where
188 D: ParserDefinition,
189 I: Iterator<Item = Result<TokenTriple<D>, ParseError<D>>>,
190 {
191 definition: D,
192 tokens: I,
193 states: Vec<D::StateIndex>,
194 symbols: Vec<SymbolTriple<D>>,
195 last_location: D::Location,
196 }
197
198 enum NextToken<D: ParserDefinition> {
199 FoundToken(TokenTriple<D>, D::TokenIndex),
200 EOF,
201 Done(ParseResult<D>),
202 }
203
204 impl<D, I> Parser<D, I>
205 where
206 D: ParserDefinition,
207 I: Iterator<Item = Result<TokenTriple<D>, ParseError<D>>>,
208 {
209 pub fn drive(definition: D, tokens: I) -> ParseResult<D> {
210 let last_location = definition.start_location();
211 let start_state = definition.start_state();
212 Parser {
213 definition,
214 tokens,
215 states: vec![start_state],
216 symbols: vec![],
217 last_location,
218 }
219 .parse()
220 }
221
222 fn top_state(&self) -> D::StateIndex {
223 *self.states.last().unwrap()
224 }
225
226 fn parse(&mut self) -> ParseResult<D> {
227 // Outer loop: each time we continue around this loop, we
228 // shift a new token from the input. We break from the loop
229 // when the end of the input is reached (we return early if an
230 // error occurs).
231 'shift: loop {
232 let (mut lookahead, mut token_index) = match self.next_token() {
233 NextToken::FoundToken(l, i) => (l, i),
234 NextToken::EOF => return self.parse_eof(),
235 NextToken::Done(e) => return e,
236 };
237
238 debug!("+ SHIFT: {:?}", lookahead);
239
240 debug!("\\ token_index: {:?}", token_index);
241
242 'inner: loop {
243 let top_state = self.top_state();
244 let action = self.definition.action(top_state, token_index);
245 debug!("\\ action: {:?}", action);
246
247 if let Some(target_state) = action.as_shift() {
248 debug!("\\ shift to: {:?}", target_state);
249
250 // Shift and transition to state `action - 1`
251 let symbol = self.definition.token_to_symbol(token_index, lookahead.1);
252 self.states.push(target_state);
253 self.symbols.push((lookahead.0, symbol, lookahead.2));
254 continue 'shift;
255 } else if let Some(reduce_index) = action.as_reduce() {
256 debug!("\\ reduce to: {:?}", reduce_index);
257
258 if let Some(r) = self.reduce(reduce_index, Some(&lookahead.0)) {
259 return match r {
260 // we reached eof, but still have lookahead
261 Ok(_) => Err(crate::ParseError::ExtraToken { token: lookahead }),
262 Err(e) => Err(e),
263 };
264 }
265 } else {
266 debug!("\\ error -- initiating error recovery!");
267
268 match self.error_recovery(Some(lookahead), Some(token_index)) {
269 NextToken::FoundToken(l, i) => {
270 lookahead = l;
271 token_index = i;
272 continue 'inner;
273 }
274 NextToken::EOF => return self.parse_eof(),
275 NextToken::Done(e) => return e,
276 }
277 }
278 }
279 }
280 }
281
282 /// Invoked when we have no more tokens to consume.
283 fn parse_eof(&mut self) -> ParseResult<D> {
284 loop {
285 let top_state = self.top_state();
286 let action = self.definition.eof_action(top_state);
287 if let Some(reduce_index) = action.as_reduce() {
288 if let Some(result) =
289 self.definition
290 .reduce(reduce_index, None, &mut self.states, &mut self.symbols)
291 {
292 return result;
293 }
294 } else {
295 match self.error_recovery(None, None) {
296 NextToken::FoundToken(..) => panic!("cannot find token at EOF"),
297 NextToken::Done(e) => return e,
298 NextToken::EOF => continue,
299 }
300 }
301 }
302 }
303
304 fn error_recovery(
305 &mut self,
306 mut opt_lookahead: Option<TokenTriple<D>>,
307 mut opt_token_index: Option<D::TokenIndex>,
308 ) -> NextToken<D> {
309 debug!(
310 "\\+ error_recovery(opt_lookahead={:?}, opt_token_index={:?})",
311 opt_lookahead, opt_token_index,
312 );
313
314 if !self.definition.uses_error_recovery() {
315 debug!("\\ error -- no error recovery!");
316
317 return NextToken::Done(Err(
318 self.unrecognized_token_error(opt_lookahead, self.top_state())
319 ));
320 }
321
322 let error = self.unrecognized_token_error(opt_lookahead.clone(), self.top_state());
323
324 let mut dropped_tokens = vec![];
325
326 // We are going to insert ERROR into the lookahead. So, first,
327 // perform all reductions from current state triggered by having
328 // ERROR in the lookahead.
329 loop {
330 let state = self.top_state();
331 let action = self.definition.error_action(state);
332 if let Some(reduce_index) = action.as_reduce() {
333 debug!("\\\\ reducing: {:?}", reduce_index);
334
335 if let Some(result) =
336 self.reduce(reduce_index, opt_lookahead.as_ref().map(|l| &l.0))
337 {
338 debug!("\\\\ reduced to a result");
339
340 return NextToken::Done(result);
341 }
342 } else {
343 break;
344 }
345 }
346
347 // Now try to find the recovery state.
348 let states_len = self.states.len();
349 let top = 'find_state: loop {
350 // Go backwards through the states...
351 debug!(
352 "\\\\+ error_recovery: find_state loop, {:?} states = {:?}",
353 self.states.len(),
354 self.states,
355 );
356
357 for top in (0..states_len).rev() {
358 let state = self.states[top];
359 debug!("\\\\\\ top = {:?}, state = {:?}", top, state);
360
361 // ...fetch action for error token...
362 let action = self.definition.error_action(state);
363 debug!("\\\\\\ action = {:?}", action);
364 if let Some(error_state) = action.as_shift() {
365 // If action is a shift that takes us into `error_state`,
366 // and `error_state` can accept this lookahead, we are done.
367 if self.accepts(error_state, &self.states[..=top], opt_token_index) {
368 debug!("\\\\\\ accepted!");
369 break 'find_state top;
370 }
371 } else {
372 // ...else, if action is error or reduce, go to next state.
373 continue;
374 }
375 }
376
377 // Otherwise, if we couldn't find a state that would --
378 // after shifting the error token -- accept the lookahead,
379 // then drop the lookahead and advance to next token in
380 // the input.
381 match opt_lookahead.take() {
382 // If the lookahead is EOF, we can't drop any more
383 // tokens, abort error recovery and just report the
384 // original error (it might be nice if we would
385 // propagate back the dropped tokens, though).
386 None => {
387 debug!("\\\\\\ no more lookahead, report error");
388 return NextToken::Done(Err(error));
389 }
390
391 // Else, drop the current token and shift to the
392 // next. If there is a next token, we will `continue`
393 // to the start of the `'find_state` loop.
394 Some(lookahead) => {
395 debug!("\\\\\\ dropping lookahead token");
396
397 dropped_tokens.push(lookahead);
398 match self.next_token() {
399 NextToken::FoundToken(next_lookahead, next_token_index) => {
400 opt_lookahead = Some(next_lookahead);
401 opt_token_index = Some(next_token_index);
402 }
403 NextToken::EOF => {
404 debug!("\\\\\\ reached EOF");
405 opt_lookahead = None;
406 opt_token_index = None;
407 }
408 NextToken::Done(e) => {
409 debug!("\\\\\\ no more tokens");
410 return NextToken::Done(e);
411 }
412 }
413 }
414 }
415 };
416
417 // If we get here, we are ready to push the error recovery state.
418
419 // We have to compute the span for the error recovery
420 // token. We do this first, before we pop any symbols off the
421 // stack. There are several possibilities, in order of
422 // preference.
423 //
424 // For the **start** of the message, we prefer to use the start of any
425 // popped states. This represents parts of the input we had consumed but
426 // had to roll back and ignore.
427 //
428 // Example:
429 //
430 // a + (b + /)
431 // ^ start point is here, since this `+` will be popped off
432 //
433 // If there are no popped states, but there *are* dropped tokens, we can use
434 // the start of those.
435 //
436 // Example:
437 //
438 // a + (b + c e)
439 // ^ start point would be here
440 //
441 // Finally, if there are no popped states *nor* dropped tokens, we can use
442 // the end of the top-most state.
443
444 let start = if let Some(popped_sym) = self.symbols.get(top) {
445 popped_sym.0.clone()
446 } else if let Some(dropped_token) = dropped_tokens.first() {
447 dropped_token.0.clone()
448 } else if top > 0 {
449 self.symbols[top - 1].2.clone()
450 } else {
451 self.definition.start_location()
452 };
453
454 // For the end span, here are the possibilities:
455 //
456 // We prefer to use the end of the last dropped token.
457 //
458 // Examples:
459 //
460 // a + (b + /)
461 // ---
462 // a + (b c)
463 // -
464 //
465 // But, if there are no dropped tokens, we will use the end of the popped states,
466 // if any:
467 //
468 // a + /
469 // -
470 //
471 // If there are neither dropped tokens *or* popped states,
472 // then the user is simulating insertion of an operator. In
473 // this case, we prefer the start of the lookahead, but
474 // fallback to the start if we are at EOF.
475 //
476 // Examples:
477 //
478 // a + (b c)
479 // -
480
481 let end = if let Some(dropped_token) = dropped_tokens.last() {
482 dropped_token.2.clone()
483 } else if states_len - 1 > top {
484 self.symbols.last().unwrap().2.clone()
485 } else if let Some(lookahead) = opt_lookahead.as_ref() {
486 lookahead.0.clone()
487 } else {
488 start.clone()
489 };
490
491 self.states.truncate(top + 1);
492 self.symbols.truncate(top);
493
494 let recover_state = self.states[top];
495 let error_action = self.definition.error_action(recover_state);
496 let error_state = error_action.as_shift().unwrap();
497 self.states.push(error_state);
498 let recovery = self.definition.error_recovery_symbol(crate::ErrorRecovery {
499 error,
500 dropped_tokens,
501 });
502 self.symbols.push((start, recovery, end));
503
504 match (opt_lookahead, opt_token_index) {
505 (Some(l), Some(i)) => NextToken::FoundToken(l, i),
506 (None, None) => NextToken::EOF,
507 (l, i) => panic!("lookahead and token_index mismatched: {:?}, {:?}", l, i),
508 }
509 }
510
511 /// The `accepts` function has the job of figuring out whether the
512 /// given error state would "accept" the given lookahead. We
513 /// basically trace through the LR automaton looking for one of
514 /// two outcomes:
515 ///
516 /// - the lookahead is eventually shifted
517 /// - we reduce to the end state successfully (in the case of EOF).
518 ///
519 /// If we used the pure LR(1) algorithm, we wouldn't need this
520 /// function, because we would be guaranteed to error immediately
521 /// (and not after some number of reductions). But with an LALR
522 /// (or Lane Table) generated automaton, it is possible to reduce
523 /// some number of times before encountering an error. Failing to
524 /// take this into account can lead error recovery into an
525 /// infinite loop (see the `error_recovery_lalr_loop` test) or
526 /// produce crappy results (see `error_recovery_lock_in`).
527 fn accepts(
528 &self,
529 error_state: D::StateIndex,
530 states: &[D::StateIndex],
531 opt_token_index: Option<D::TokenIndex>,
532 ) -> bool {
533 debug!(
534 "\\\\\\+ accepts(error_state={:?}, states={:?}, opt_token_index={:?})",
535 error_state, states, opt_token_index,
536 );
537
538 let mut states = states.to_vec();
539 states.push(error_state);
540 loop {
541 let mut states_len = states.len();
542 let top = states[states_len - 1];
543 let action = match opt_token_index {
544 None => self.definition.eof_action(top),
545 Some(i) => self.definition.action(top, i),
546 };
547
548 // If we encounter an error action, we do **not** accept.
549 if action.is_error() {
550 debug!("\\\\\\\\ accepts: error");
551 return false;
552 }
553
554 // If we encounter a reduce action, we need to simulate its
555 // effect on the state stack.
556 if let Some(reduce_action) = action.as_reduce() {
557 match self.definition.simulate_reduce(reduce_action) {
558 SimulatedReduce::Reduce {
559 states_to_pop,
560 nonterminal_produced,
561 } => {
562 states_len -= states_to_pop;
563 states.truncate(states_len);
564 let top = states[states_len - 1];
565 let next_state = self.definition.goto(top, nonterminal_produced);
566 states.push(next_state);
567 }
568
569 SimulatedReduce::Accept => {
570 debug!("\\\\\\\\ accepts: reduce accepts!");
571 return true;
572 }
573 }
574 } else {
575 // If we encounter a shift action, we DO accept.
576 debug!("\\\\\\\\ accepts: shift accepts!");
577 assert!(action.is_shift());
578 return true;
579 }
580 }
581 }
582
583 fn reduce(
584 &mut self,
585 action: D::ReduceIndex,
586 lookahead_start: Option<&D::Location>,
587 ) -> Option<ParseResult<D>> {
588 self.definition
589 .reduce(action, lookahead_start, &mut self.states, &mut self.symbols)
590 }
591
592 fn unrecognized_token_error(
593 &self,
594 token: Option<TokenTriple<D>>,
595 top_state: D::StateIndex,
596 ) -> ParseError<D> {
597 match token {
598 Some(token) => crate::ParseError::UnrecognizedToken {
599 token,
600 expected: self.definition.expected_tokens(top_state),
601 },
602 None => crate::ParseError::UnrecognizedEOF {
603 location: self.last_location.clone(),
604 expected: self.definition.expected_tokens(top_state),
605 },
606 }
607 }
608
609 /// Consume the next token from the input and classify it into a
610 /// token index. Classification can fail with an error. If there
611 /// are no more tokens, signal EOF.
612 fn next_token(&mut self) -> NextToken<D> {
613 let token = match self.tokens.next() {
614 Some(Ok(v)) => v,
615 Some(Err(e)) => return NextToken::Done(Err(e)),
616 None => return NextToken::EOF,
617 };
618
619 self.last_location = token.2.clone();
620
621 let token_index = match self.definition.token_to_index(&token.1) {
622 Some(i) => i,
623 None => {
624 return NextToken::Done(Err(
625 self.unrecognized_token_error(Some(token), self.top_state())
626 ))
627 }
628 };
629
630 NextToken::FoundToken(token, token_index)
631 }
632 }
633
634 /// In LALRPOP generated rules, we actually use `i32`, `i16`, or `i8`
635 /// to represent all of the various indices (we use the smallest one
636 /// that will fit). So implement `ParserAction` for each of those.
637 macro_rules! integral_indices {
638 ($t:ty) => {
639 impl<D: ParserDefinition<StateIndex = $t, ReduceIndex = $t>> ParserAction<D> for $t {
640 fn as_shift(self) -> Option<D::StateIndex> {
641 if self > 0 {
642 Some(self - 1)
643 } else {
644 None
645 }
646 }
647
648 fn as_reduce(self) -> Option<D::ReduceIndex> {
649 if self < 0 {
650 Some(-(self + 1))
651 } else {
652 None
653 }
654 }
655
656 fn is_shift(self) -> bool {
657 self > 0
658 }
659
660 fn is_reduce(self) -> bool {
661 self < 0
662 }
663
664 fn is_error(self) -> bool {
665 self == 0
666 }
667 }
668 };
669 }
670
671 integral_indices!(i32);
672 integral_indices!(i16);
673 integral_indices!(i8);