Skip to main content

lrpar/
parser.rs

1#![allow(clippy::derive_partial_eq_without_eq)]
2use std::{
3    error::Error,
4    fmt::{self, Debug, Display, Write as _},
5    hash::Hash,
6    marker::PhantomData,
7    vec,
8};
9
10// Can be used on non-wasm32 but to avoid the dependency.
11#[cfg(not(target_arch = "wasm32"))]
12use std::time::{Duration, Instant};
13#[cfg(target_arch = "wasm32")]
14use web_time::{Duration, Instant};
15
16use cactus::Cactus;
17use cfgrammar::{RIdx, Span, TIdx, header::Value, span::Location, yacc::YaccGrammar};
18use lrtable::{Action, StIdx, StateTable};
19use num_traits::{AsPrimitive, PrimInt, Unsigned};
20use proc_macro2::TokenStream;
21use quote::quote;
22#[cfg(feature = "serde")]
23use serde::{Deserialize, Serialize};
24
25use crate::{LexError, Lexeme, LexerTypes, NonStreamingLexer, cpctplus};
26
27#[cfg(test)]
28const RECOVERY_TIME_BUDGET: u64 = 60_000; // milliseconds
29#[cfg(not(test))]
30const RECOVERY_TIME_BUDGET: u64 = 500; // milliseconds
31
32#[deprecated(
33    since = "0.14.0",
34    note = "Use the version of `Node` exported from your `lrpar_mod!`"
35)]
36pub type Node<T, S> = _deprecated_moved_::Node<T, S>;
37
38#[doc(hidden)]
39pub mod _deprecated_moved_ {
40    use super::*;
41    /// A generic parse tree.
42    #[derive(Debug, Clone, PartialEq)]
43    pub enum Node<LexemeT: Lexeme<StorageT>, StorageT> {
44        /// Terminals store a single lexeme.
45        Term { lexeme: LexemeT },
46        /// Nonterminals reference a rule and have zero or more `Node`s as children.
47        Nonterm {
48            ridx: RIdx<StorageT>,
49            nodes: Vec<Node<LexemeT, StorageT>>,
50        },
51    }
52}
53
54#[allow(deprecated)]
55impl<LexemeT: Lexeme<StorageT>, StorageT: 'static + PrimInt + Unsigned> Node<LexemeT, StorageT>
56where
57    usize: AsPrimitive<StorageT>,
58{
59    /// Return a pretty-printed version of this node.
60    pub fn pp(&self, grm: &YaccGrammar<StorageT>, input: &str) -> String {
61        let mut st = vec![(0, self)]; // Stack of (indent level, node) pairs
62        let mut s = String::new();
63        while let Some((indent, e)) = st.pop() {
64            for _ in 0..indent {
65                s.push(' ');
66            }
67            match *e {
68                Node::Term { lexeme } => {
69                    let tidx = TIdx(lexeme.tok_id());
70                    let tn = grm.token_name(tidx).unwrap();
71                    let lt = &input[lexeme.span().start()..lexeme.span().end()];
72                    writeln!(s, "{} {}", tn, lt).ok();
73                }
74                Node::Nonterm { ridx, ref nodes } => {
75                    writeln!(s, "{}", grm.rule_name_str(ridx)).ok();
76                    for x in nodes.iter().rev() {
77                        st.push((indent + 1, x));
78                    }
79                }
80            }
81        }
82        s
83    }
84}
85
86type PStack<StorageT> = Vec<StIdx<StorageT>>; // Parse stack
87type TokenCostFn<'a, StorageT> = &'a (dyn Fn(TIdx<StorageT>) -> u8 + 'a);
88type ActionFn<'a, 'b, 'input, StorageT, LexerTypesT, ActionT, ParamT> = &'a dyn Fn(
89    RIdx<StorageT>,
90    &'b dyn NonStreamingLexer<'input, LexerTypesT>,
91    Span,
92    vec::Drain<AStackType<<LexerTypesT as LexerTypes>::LexemeT, ActionT>>,
93    ParamT,
94) -> ActionT;
95
96#[derive(Debug)]
97pub enum AStackType<LexemeT, ActionT> {
98    ActionType(ActionT),
99    Lexeme(LexemeT),
100}
101
102pub(super) struct Parser<
103    'a,
104    'b: 'a,
105    'input: 'b,
106    StorageT: 'static + Eq + Hash + PrimInt + Unsigned,
107    LexerTypesT: LexerTypes<StorageT = StorageT>,
108    ActionT: 'a,
109    ParamT: Clone,
110> where
111    usize: AsPrimitive<StorageT>,
112{
113    rcvry_kind: RecoveryKind,
114    pub(super) grm: &'a YaccGrammar<StorageT>,
115    pub(super) token_cost: TokenCostFn<'a, StorageT>,
116    pub(super) stable: &'a StateTable<StorageT>,
117    lexer: &'b dyn NonStreamingLexer<'input, LexerTypesT>,
118    // In the long term, we should remove the `lexemes` field entirely, as the `NonStreamingLexer` API is
119    // powerful enough to allow us to incrementally obtain lexemes and buffer them when necessary.
120    pub(super) lexemes: Vec<LexerTypesT::LexemeT>,
121    actions: &'a [ActionFn<'a, 'b, 'input, LexerTypesT::StorageT, LexerTypesT, ActionT, ParamT>],
122    param: ParamT,
123}
124
125impl<
126    'a,
127    'b: 'a,
128    'input: 'b,
129    StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
130    LexerTypesT: LexerTypes<StorageT = StorageT>,
131    Node,
132>
133    Parser<
134        'a,
135        'b,
136        'input,
137        StorageT,
138        LexerTypesT,
139        Node,
140        (
141            &dyn Fn(LexerTypesT::LexemeT) -> Node,
142            &dyn Fn(RIdx<StorageT>, Vec<Node>) -> Node,
143        ),
144    >
145where
146    usize: AsPrimitive<StorageT>,
147{
148    fn parse_map(
149        rcvry_kind: RecoveryKind,
150        grm: &YaccGrammar<StorageT>,
151        token_cost: TokenCostFn<'a, StorageT>,
152        stable: &StateTable<StorageT>,
153        lexer: &'b dyn NonStreamingLexer<'input, LexerTypesT>,
154        lexemes: Vec<LexerTypesT::LexemeT>,
155        fterm: &'a dyn Fn(LexerTypesT::LexemeT) -> Node,
156        fnonterm: &'a dyn Fn(RIdx<StorageT>, Vec<Node>) -> Node,
157    ) -> (Option<Node>, Vec<LexParseError<StorageT, LexerTypesT>>) {
158        for tidx in grm.iter_tidxs() {
159            assert!(token_cost(tidx) > 0);
160        }
161        let mut actions: Vec<
162            ActionFn<
163                'a,
164                'b,
165                'input,
166                StorageT,
167                LexerTypesT,
168                Node,
169                (
170                    &'a dyn Fn(LexerTypesT::LexemeT) -> Node,
171                    &'a dyn Fn(RIdx<StorageT>, Vec<Node>) -> Node,
172                ),
173            >,
174        > = Vec::new();
175        actions.resize(usize::from(grm.prods_len()), &action_map);
176        let psr = Parser {
177            rcvry_kind,
178            grm,
179            token_cost,
180            stable,
181            lexer,
182            lexemes,
183            actions: actions.as_slice(),
184            param: (fterm, fnonterm),
185        };
186        let mut pstack = vec![stable.start_state()];
187        let mut astack = Vec::new();
188        let mut errors = Vec::new();
189        let mut spans = Vec::new();
190        let accpt = psr.lr(0, &mut pstack, &mut astack, &mut errors, &mut spans);
191        (accpt, errors)
192    }
193}
194
195fn action_map<StorageT, LexerTypesT: LexerTypes, Node>(
196    ridx: RIdx<StorageT>,
197    _lexer: &dyn NonStreamingLexer<LexerTypesT>,
198    _span: Span,
199    astack: vec::Drain<AStackType<LexerTypesT::LexemeT, Node>>,
200    param: (
201        &dyn Fn(LexerTypesT::LexemeT) -> Node,
202        &dyn Fn(RIdx<StorageT>, Vec<Node>) -> Node,
203    ),
204) -> Node
205where
206    usize: AsPrimitive<LexerTypesT::StorageT>,
207    LexerTypesT::LexemeT: Lexeme<StorageT>,
208{
209    let (fterm, fnonterm) = param;
210    let mut nodes = Vec::with_capacity(astack.len());
211    for a in astack {
212        nodes.push(match a {
213            AStackType::ActionType(n) => n,
214            AStackType::Lexeme(lexeme) => fterm(lexeme),
215        });
216    }
217    fnonterm(ridx, nodes)
218}
219
220#[deprecated(
221    since = "0.14.0",
222    note = "Deprecated with `parse_generictree` there is no direct replacement, besides a custom action"
223)]
224#[allow(deprecated)]
225/// The action which implements [`cfgrammar::yacc::YaccOriginalActionKind::GenericParseTree`].
226/// Usually you should just use the action kind directly. But you can also call this from
227/// within a custom action to return a generic parse tree with custom behavior.
228pub fn action_generictree<StorageT, LexerTypesT: LexerTypes>(
229    ridx: RIdx<StorageT>,
230    _lexer: &dyn NonStreamingLexer<LexerTypesT>,
231    _span: Span,
232    astack: vec::Drain<AStackType<LexerTypesT::LexemeT, Node<LexerTypesT::LexemeT, StorageT>>>,
233    _param: (),
234) -> Node<LexerTypesT::LexemeT, StorageT>
235where
236    usize: AsPrimitive<LexerTypesT::StorageT>,
237    LexerTypesT::LexemeT: Lexeme<StorageT>,
238{
239    let mut nodes = Vec::with_capacity(astack.len());
240    for a in astack {
241        nodes.push(match a {
242            AStackType::ActionType(n) => n,
243            AStackType::Lexeme(lexeme) => Node::Term { lexeme },
244        });
245    }
246    Node::Nonterm { ridx, nodes }
247}
248
249impl<
250    'a,
251    'b: 'a,
252    'input: 'b,
253    StorageT: 'static + Debug + Eq + Hash + PrimInt + Unsigned,
254    LexerTypesT: LexerTypes<StorageT = StorageT>,
255    ActionT: 'a,
256    ParamT: Clone,
257> Parser<'a, 'b, 'input, StorageT, LexerTypesT, ActionT, ParamT>
258where
259    usize: AsPrimitive<StorageT>,
260{
261    fn parse_actions(
262        rcvry_kind: RecoveryKind,
263        grm: &'a YaccGrammar<StorageT>,
264        token_cost: TokenCostFn<'a, StorageT>,
265        stable: &'a StateTable<StorageT>,
266        lexer: &'b dyn NonStreamingLexer<'input, LexerTypesT>,
267        lexemes: Vec<LexerTypesT::LexemeT>,
268        actions: &'a [ActionFn<'a, 'b, 'input, StorageT, LexerTypesT, ActionT, ParamT>],
269        param: ParamT,
270    ) -> (Option<ActionT>, Vec<LexParseError<StorageT, LexerTypesT>>) {
271        for tidx in grm.iter_tidxs() {
272            assert!(token_cost(tidx) > 0);
273        }
274        let psr = Parser {
275            rcvry_kind,
276            grm,
277            token_cost,
278            stable,
279            lexer,
280            lexemes,
281            actions,
282            param,
283        };
284        let mut pstack = vec![stable.start_state()];
285        let mut astack = Vec::new();
286        let mut errors = Vec::new();
287        let mut spans = Vec::new();
288        let accpt = psr.lr(0, &mut pstack, &mut astack, &mut errors, &mut spans);
289        (accpt, errors)
290    }
291
292    /// Start parsing text at `laidx` (using the lexeme in `lexeme_prefix`, if it is not `None`,
293    /// as the first lexeme) up to (but excluding) `end_laidx` (if it's specified). Parsing
294    /// continues as long as possible (assuming that any errors encountered can be recovered from)
295    /// unless `end_laidx` is `None`, at which point this function returns as soon as it
296    /// encounters an error.
297    ///
298    /// Note that if `lexeme_prefix` is specified, `laidx` will still be incremented, and thus
299    /// `end_laidx` *must* be set to `laidx + 1` in order that the parser doesn't skip the real
300    /// lexeme at position `laidx`.
301    ///
302    /// Return `Some(value)` if the parse reached an accept state (i.e. all the input was consumed,
303    /// possibly after making repairs) or `None` (i.e. some of the input was not consumed, even
304    /// after possibly making repairs) otherwise.
305    fn lr(
306        &self,
307        mut laidx: usize,
308        pstack: &mut PStack<StorageT>,
309        astack: &mut Vec<AStackType<LexerTypesT::LexemeT, ActionT>>,
310        errors: &mut Vec<LexParseError<StorageT, LexerTypesT>>,
311        spans: &mut Vec<Span>,
312    ) -> Option<ActionT> {
313        let mut recoverer = None;
314        let mut recovery_budget = Duration::from_millis(RECOVERY_TIME_BUDGET);
315        loop {
316            debug_assert_eq!(astack.len(), spans.len());
317            let stidx = *pstack.last().unwrap();
318            let la_tidx = self.next_tidx(laidx);
319
320            match self.stable.action(stidx, la_tidx) {
321                Action::Reduce(pidx) => {
322                    let ridx = self.grm.prod_to_rule(pidx);
323                    let pop_idx = pstack.len() - self.grm.prod(pidx).len();
324
325                    pstack.drain(pop_idx..);
326                    let prior = *pstack.last().unwrap();
327                    pstack.push(self.stable.goto(prior, ridx).unwrap());
328
329                    let span = if spans.is_empty() {
330                        Span::new(0, 0)
331                    } else if pop_idx - 1 < spans.len() {
332                        Span::new(spans[pop_idx - 1].start(), spans[spans.len() - 1].end())
333                    } else {
334                        Span::new(spans[spans.len() - 1].start(), spans[spans.len() - 1].end())
335                    };
336                    spans.truncate(pop_idx - 1);
337                    spans.push(span);
338
339                    let v = AStackType::ActionType(self.actions[usize::from(pidx)](
340                        ridx,
341                        self.lexer,
342                        span,
343                        astack.drain(pop_idx - 1..),
344                        self.param.clone(),
345                    ));
346                    astack.push(v);
347                }
348                Action::Shift(state_id) => {
349                    let la_lexeme = self.next_lexeme(laidx);
350                    pstack.push(state_id);
351                    astack.push(AStackType::Lexeme(la_lexeme));
352
353                    spans.push(la_lexeme.span());
354                    laidx += 1;
355                }
356                Action::Accept => {
357                    debug_assert_eq!(la_tidx, self.grm.eof_token_idx());
358                    debug_assert_eq!(astack.len(), 1);
359                    match astack.drain(..).next().unwrap() {
360                        AStackType::ActionType(v) => return Some(v),
361                        _ => unreachable!(),
362                    }
363                }
364                Action::Error => {
365                    if recoverer.is_none() {
366                        recoverer = Some(match self.rcvry_kind {
367                            RecoveryKind::CPCTPlus => cpctplus::recoverer(self),
368                            RecoveryKind::None => {
369                                let la_lexeme = self.next_lexeme(laidx);
370                                errors.push(
371                                    ParseError {
372                                        stidx,
373                                        lexeme: la_lexeme,
374                                        repairs: vec![],
375                                    }
376                                    .into(),
377                                );
378                                return None;
379                            }
380                        });
381                    }
382
383                    let before = Instant::now();
384                    let finish_by = before + recovery_budget;
385                    let (new_laidx, repairs) = recoverer
386                        .as_ref()
387                        .unwrap()
388                        .as_ref()
389                        .recover(finish_by, self, laidx, pstack, astack, spans);
390                    let after = Instant::now();
391                    recovery_budget = recovery_budget
392                        .checked_sub(after - before)
393                        .unwrap_or_else(|| Duration::new(0, 0));
394                    let keep_going = !repairs.is_empty();
395                    let la_lexeme = self.next_lexeme(laidx);
396                    errors.push(
397                        ParseError {
398                            stidx,
399                            lexeme: la_lexeme,
400                            repairs,
401                        }
402                        .into(),
403                    );
404                    if !keep_going {
405                        return None;
406                    }
407                    laidx = new_laidx;
408                }
409            }
410        }
411    }
412
413    /// Parse from `laidx` up to (but excluding) `end_laidx` mutating `pstack` as parsing occurs.
414    /// Returns the index of the token it parsed up to (by definition <= end_laidx: can be less if
415    /// the input is < end_laidx, or if an error is encountered). Does not do any form of error
416    /// recovery.
417    pub(super) fn lr_upto(
418        &self,
419        lexeme_prefix: Option<LexerTypesT::LexemeT>,
420        mut laidx: usize,
421        end_laidx: usize,
422        pstack: &mut PStack<StorageT>,
423        astack: &mut Option<&mut Vec<AStackType<LexerTypesT::LexemeT, ActionT>>>,
424        spans: &mut Option<&mut Vec<Span>>,
425    ) -> usize {
426        assert!(lexeme_prefix.is_none() || end_laidx == laidx + 1);
427        while laidx != end_laidx && laidx <= self.lexemes.len() {
428            let stidx = *pstack.last().unwrap();
429            let la_tidx = if let Some(l) = lexeme_prefix {
430                TIdx(l.tok_id())
431            } else {
432                self.next_tidx(laidx)
433            };
434
435            match self.stable.action(stidx, la_tidx) {
436                Action::Reduce(pidx) => {
437                    let ridx = self.grm.prod_to_rule(pidx);
438                    let pop_idx = pstack.len() - self.grm.prod(pidx).len();
439                    if let Some(ref mut astack_uw) = *astack {
440                        if let Some(ref mut spans_uw) = *spans {
441                            let span = if spans_uw.is_empty() {
442                                Span::new(0, 0)
443                            } else if pop_idx - 1 < spans_uw.len() {
444                                Span::new(
445                                    spans_uw[pop_idx - 1].start(),
446                                    spans_uw[spans_uw.len() - 1].end(),
447                                )
448                            } else {
449                                Span::new(
450                                    spans_uw[spans_uw.len() - 1].start(),
451                                    spans_uw[spans_uw.len() - 1].end(),
452                                )
453                            };
454                            spans_uw.truncate(pop_idx - 1);
455                            spans_uw.push(span);
456
457                            let v = AStackType::ActionType(self.actions[usize::from(pidx)](
458                                ridx,
459                                self.lexer,
460                                span,
461                                astack_uw.drain(pop_idx - 1..),
462                                self.param.clone(),
463                            ));
464                            astack_uw.push(v);
465                        } else {
466                            unreachable!();
467                        }
468                    }
469
470                    pstack.drain(pop_idx..);
471                    let prior = *pstack.last().unwrap();
472                    pstack.push(self.stable.goto(prior, ridx).unwrap());
473                }
474                Action::Shift(state_id) => {
475                    if let Some(ref mut astack_uw) = *astack
476                        && let Some(spans_uw) = spans
477                    {
478                        let la_lexeme = if let Some(l) = lexeme_prefix {
479                            l
480                        } else {
481                            self.next_lexeme(laidx)
482                        };
483                        astack_uw.push(AStackType::Lexeme(la_lexeme));
484                        spans_uw.push(la_lexeme.span());
485                    }
486                    pstack.push(state_id);
487                    laidx += 1;
488                }
489                Action::Accept => {
490                    break;
491                }
492                Action::Error => {
493                    break;
494                }
495            }
496        }
497        laidx
498    }
499
500    /// Return a `Lexeme` for the next lemexe (if `laidx` == `self.lexemes.len()` this will be
501    /// a lexeme constructed to look as if contains the EOF token).
502    pub(super) fn next_lexeme(&self, laidx: usize) -> LexerTypesT::LexemeT {
503        let llen = self.lexemes.len();
504        debug_assert!(laidx <= llen);
505        if laidx < llen {
506            self.lexemes[laidx]
507        } else {
508            // We have to artificially construct a Lexeme for the EOF lexeme.
509            let last_la_end = if llen == 0 {
510                0
511            } else {
512                debug_assert!(laidx > 0);
513                let last_la = self.lexemes[laidx - 1];
514                last_la.span().end()
515            };
516
517            Lexeme::new_faulty(
518                StorageT::from(u32::from(self.grm.eof_token_idx())).unwrap(),
519                last_la_end,
520                0,
521            )
522        }
523    }
524
525    /// Return the `TIdx` of the next lexeme (if `laidx` == `self.lexemes.len()` this will be the
526    /// EOF `TIdx`).
527    pub(super) fn next_tidx(&self, laidx: usize) -> TIdx<StorageT> {
528        let ll = self.lexemes.len();
529        debug_assert!(laidx <= ll);
530        if laidx < ll {
531            TIdx(self.lexemes[laidx].tok_id())
532        } else {
533            self.grm.eof_token_idx()
534        }
535    }
536
537    /// Start parsing text at `laidx` (using the lexeme in `lexeme_prefix`, if it is not `None`,
538    /// as the first lexeme) up to (but excluding) `end_laidx`. If an error is encountered, parsing
539    /// immediately terminates (without recovery).
540    ///
541    /// Note that if `lexeme_prefix` is specified, `laidx` will still be incremented, and thus
542    /// `end_laidx` *must* be set to `laidx + 1` in order that the parser doesn't skip the real
543    /// lexeme at position `laidx`.
544    #[allow(deprecated)]
545    pub(super) fn lr_cactus(
546        &self,
547        lexeme_prefix: Option<LexerTypesT::LexemeT>,
548        mut laidx: usize,
549        end_laidx: usize,
550        mut pstack: Cactus<StIdx<StorageT>>,
551        tstack: &mut Option<&mut Vec<Node<LexerTypesT::LexemeT, StorageT>>>,
552    ) -> (usize, Cactus<StIdx<StorageT>>) {
553        assert!(lexeme_prefix.is_none() || end_laidx == laidx + 1);
554        while laidx != end_laidx {
555            let stidx = *pstack.val().unwrap();
556            let la_tidx = if let Some(l) = lexeme_prefix {
557                TIdx(l.tok_id())
558            } else {
559                self.next_tidx(laidx)
560            };
561
562            match self.stable.action(stidx, la_tidx) {
563                Action::Reduce(pidx) => {
564                    let ridx = self.grm.prod_to_rule(pidx);
565                    let pop_num = self.grm.prod(pidx).len();
566                    if let Some(ref mut tstack_uw) = *tstack {
567                        let nodes = tstack_uw
568                            .drain(pstack.len() - pop_num - 1..)
569                            .collect::<Vec<Node<LexerTypesT::LexemeT, StorageT>>>();
570                        tstack_uw.push(Node::Nonterm { ridx, nodes });
571                    }
572
573                    for _ in 0..pop_num {
574                        pstack = pstack.parent().unwrap();
575                    }
576                    let prior = *pstack.val().unwrap();
577                    pstack = pstack.child(self.stable.goto(prior, ridx).unwrap());
578                }
579                Action::Shift(state_id) => {
580                    if let Some(ref mut tstack_uw) = *tstack {
581                        let la_lexeme = if let Some(l) = lexeme_prefix {
582                            l
583                        } else {
584                            self.next_lexeme(laidx)
585                        };
586                        tstack_uw.push(Node::Term { lexeme: la_lexeme });
587                    }
588                    pstack = pstack.child(state_id);
589                    laidx += 1;
590                }
591                Action::Accept => {
592                    debug_assert_eq!(la_tidx, self.grm.eof_token_idx());
593                    if let Some(ref tstack_uw) = *tstack {
594                        debug_assert_eq!(tstack_uw.len(), 1);
595                    }
596                    break;
597                }
598                Action::Error => {
599                    break;
600                }
601            }
602        }
603        (laidx, pstack)
604    }
605}
606
607pub(super) trait Recoverer<
608    StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
609    LexerTypesT: LexerTypes<StorageT = StorageT>,
610    ActionT,
611    ParamT: Clone,
612> where
613    usize: AsPrimitive<StorageT>,
614{
615    fn recover(
616        &self,
617        finish_by: Instant,
618        parser: &Parser<StorageT, LexerTypesT, ActionT, ParamT>,
619        in_laidx: usize,
620        in_pstack: &mut PStack<StorageT>,
621        astack: &mut Vec<AStackType<LexerTypesT::LexemeT, ActionT>>,
622        spans: &mut Vec<Span>,
623    ) -> (usize, Vec<Vec<ParseRepair<LexerTypesT::LexemeT, StorageT>>>);
624}
625
626/// What recovery algorithm should be used when a syntax error is encountered?
627#[derive(Clone, Copy, Debug)]
628#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
629#[non_exhaustive]
630pub enum RecoveryKind {
631    /// The CPCT+ algorithm from Diekmann/Tratt "Don't Panic! Better, Fewer, Syntax Errors for LR
632    /// Parsers".
633    CPCTPlus,
634    /// Don't use error recovery: return as soon as the first syntax error is encountered.
635    None,
636}
637
638impl TryFrom<RecoveryKind> for Value<Location> {
639    type Error = cfgrammar::header::HeaderError<Location>;
640    fn try_from(rk: RecoveryKind) -> Result<Value<Location>, Self::Error> {
641        use cfgrammar::{
642            Location,
643            header::{Namespaced, Setting},
644        };
645        let from_loc = Location::Other("From<RecoveryKind>".to_string());
646        Ok(match rk {
647            RecoveryKind::CPCTPlus => Value::Setting(Setting::Unitary(Namespaced {
648                namespace: Some(("RecoveryKind".to_string(), from_loc.clone())),
649                member: ("CPCTPlus".to_string(), from_loc.clone()),
650            })),
651            RecoveryKind::None => Value::Setting(Setting::Unitary(Namespaced {
652                namespace: Some(("RecoveryKind".to_string(), from_loc.clone())),
653                member: ("None".to_string(), from_loc.clone()),
654            })),
655        })
656    }
657}
658
659impl TryFrom<&Value<Location>> for RecoveryKind {
660    type Error = cfgrammar::header::HeaderError<Location>;
661    fn try_from(rk: &Value<Location>) -> Result<RecoveryKind, Self::Error> {
662        use cfgrammar::header::{HeaderError, HeaderErrorKind, Namespaced, Setting};
663
664        match rk {
665            Value::Setting(Setting::Unitary(Namespaced {
666                namespace,
667                member: (kind, kind_loc),
668            })) => {
669                match namespace {
670                    Some((ns, loc)) if ns.to_lowercase() != "recoverykind" => {
671                        return Err(HeaderError {
672                            kind: HeaderErrorKind::ConversionError(
673                                "RecoveryKind",
674                                "Unknown namespace",
675                            ),
676                            locations: vec![loc.clone()],
677                        });
678                    }
679                    _ => {}
680                }
681                match kind.to_lowercase().as_ref() {
682                    "cpctplus" => Ok(RecoveryKind::CPCTPlus),
683                    "none" => Ok(RecoveryKind::None),
684                    _ => Err(HeaderError {
685                        kind: HeaderErrorKind::ConversionError("RecoveryKind", "Unknown variant"),
686                        locations: vec![kind_loc.clone()],
687                    }),
688                }
689            }
690            value => Err(HeaderError {
691                kind: HeaderErrorKind::ConversionError(
692                    "RecoveryKind",
693                    "Cannot convert to RecoveryKind",
694                ),
695                locations: vec![value.primary_location().clone()],
696            }),
697        }
698    }
699}
700
701impl quote::ToTokens for RecoveryKind {
702    fn to_tokens(&self, tokens: &mut TokenStream) {
703        tokens.extend(match *self {
704            RecoveryKind::CPCTPlus => quote!(::lrpar::RecoveryKind::CPCTPlus),
705            RecoveryKind::None => quote!(::lrpar::RecoveryKind::None),
706        })
707    }
708}
709
710/// A lexing or parsing error. Although the two are quite distinct in terms of what can be reported
711/// to users, both can (at least conceptually) occur at any point of the intertwined lexing/parsing
712/// process.
713#[derive(Debug)]
714pub enum LexParseError<
715    StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
716    LexerTypesT: LexerTypes<StorageT = StorageT>,
717> where
718    usize: AsPrimitive<StorageT>,
719{
720    LexError(LexerTypesT::LexErrorT),
721    ParseError(ParseError<LexerTypesT::LexemeT, StorageT>),
722}
723
724impl<StorageT: Debug + Hash + PrimInt + Unsigned, LexerTypesT: LexerTypes<StorageT = StorageT>>
725    LexParseError<StorageT, LexerTypesT>
726where
727    usize: AsPrimitive<StorageT>,
728{
729    /// A pretty-printer of a lexer/parser error. This isn't suitable for all purposes, but it's
730    /// often good enough. The output format is not guaranteed to be stable but is likely to be of
731    /// the form:
732    ///
733    /// ```text
734    /// Parsing error at line 3 column 8. Repair sequences found:
735    ///   1: Insert ID
736    ///   2: Delete +, Shift 3
737    /// ```
738    ///
739    /// If you are using the compile-time parse system, your `grm_y` module exposes a suitable
740    /// [`epp`](../ctbuilder/struct.CTParserBuilder.html#method.process_file) function; if you are
741    /// using the run-time system,
742    /// [`YaccGrammar`](../../cfgrammar/yacc/grammar/struct.YaccGrammar.html) exposes a suitable
743    /// [`epp`](../../cfgrammar/yacc/grammar/struct.YaccGrammar.html#method.token_epp) function,
744    /// though you will have to wrap it in a closure e.g. `&|t| grm.token_epp(t)`.
745    pub fn pp<'a>(
746        &self,
747        lexer: &dyn NonStreamingLexer<LexerTypesT>,
748        epp: &dyn Fn(TIdx<StorageT>) -> Option<&'a str>,
749    ) -> String {
750        match self {
751            LexParseError::LexError(e) => {
752                let ((line, col), _) = lexer.line_col(e.span());
753                format!("Lexing error at line {} column {}.", line, col)
754            }
755            LexParseError::ParseError(e) => {
756                let ((line, col), _) = lexer.line_col(e.lexeme().span());
757                let mut out = format!("Parsing error at line {} column {}.", line, col);
758                let repairs_len = e.repairs().len();
759                if repairs_len == 0 {
760                    out.push_str(" No repair sequences found.");
761                } else {
762                    out.push_str(" Repair sequences found:");
763                    for (i, rs) in e.repairs().iter().enumerate() {
764                        let padding = ((repairs_len as f64).log10() as usize)
765                            - (((i + 1) as f64).log10() as usize)
766                            + 1;
767                        write!(out, "\n  {}{}: ", " ".repeat(padding), i + 1).ok();
768                        let mut rs_out = Vec::new();
769
770                        // Merge together Deletes iff they are consecutive (if they are separated
771                        // by even a single character, they will not be merged).
772                        let mut i = 0;
773                        while i < rs.len() {
774                            match rs[i] {
775                                ParseRepair::Delete(l) => {
776                                    let mut j = i + 1;
777                                    let mut last_end = l.span().end();
778                                    while j < rs.len() {
779                                        if let ParseRepair::Delete(next_l) = rs[j]
780                                            && next_l.span().start() == last_end
781                                        {
782                                            last_end = next_l.span().end();
783                                            j += 1;
784                                            continue;
785                                        }
786                                        break;
787                                    }
788                                    let t = &lexer
789                                        .span_str(Span::new(l.span().start(), last_end))
790                                        .replace('\n', "\\n");
791                                    rs_out.push(format!("Delete {}", t));
792                                    i = j;
793                                }
794                                ParseRepair::Insert(tidx) => {
795                                    rs_out.push(format!("Insert {}", epp(tidx).unwrap()));
796                                    i += 1;
797                                }
798                                ParseRepair::Shift(l) => {
799                                    let t = &lexer.span_str(l.span()).replace('\n', "\\n");
800                                    rs_out.push(format!("Shift {}", t));
801                                    i += 1;
802                                }
803                            }
804                        }
805
806                        out.push_str(&rs_out.join(", "));
807                    }
808                }
809                out
810            }
811        }
812    }
813}
814
815impl<
816    StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
817    LexerTypesT: LexerTypes<StorageT = StorageT>,
818> fmt::Display for LexParseError<StorageT, LexerTypesT>
819where
820    usize: AsPrimitive<StorageT>,
821{
822    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
823        match *self {
824            LexParseError::LexError(ref e) => Display::fmt(e, f),
825            LexParseError::ParseError(ref e) => Display::fmt(e, f),
826        }
827    }
828}
829
830impl<
831    StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
832    LexerTypesT: LexerTypes<StorageT = StorageT>,
833> Error for LexParseError<StorageT, LexerTypesT>
834where
835    usize: AsPrimitive<StorageT>,
836{
837}
838
839impl<
840    StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
841    LexerTypesT: LexerTypes<StorageT = StorageT, LexErrorT = T>,
842    T: LexError,
843> From<T> for LexParseError<StorageT, LexerTypesT>
844where
845    usize: AsPrimitive<StorageT>,
846{
847    fn from(err: T) -> LexParseError<StorageT, LexerTypesT> {
848        LexParseError::LexError(err)
849    }
850}
851
852impl<
853    StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
854    LexerTypesT: LexerTypes<StorageT = StorageT>,
855> From<ParseError<LexerTypesT::LexemeT, StorageT>> for LexParseError<StorageT, LexerTypesT>
856where
857    usize: AsPrimitive<StorageT>,
858{
859    fn from(
860        err: ParseError<LexerTypesT::LexemeT, StorageT>,
861    ) -> LexParseError<StorageT, LexerTypesT> {
862        LexParseError::ParseError(err)
863    }
864}
865
866/// A run-time parser builder.
867pub struct RTParserBuilder<
868    'a,
869    StorageT: 'static + Eq + Debug + Hash + PrimInt + Unsigned,
870    LexerTypesT: LexerTypes<StorageT = StorageT>,
871> where
872    usize: AsPrimitive<StorageT>,
873{
874    grm: &'a YaccGrammar<StorageT>,
875    stable: &'a StateTable<StorageT>,
876    recoverer: RecoveryKind,
877    term_costs: &'a dyn Fn(TIdx<StorageT>) -> u8,
878    phantom: PhantomData<(StorageT, LexerTypesT)>,
879}
880
881impl<
882    'a,
883    StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
884    LexerTypesT: LexerTypes<StorageT = StorageT>,
885> RTParserBuilder<'a, StorageT, LexerTypesT>
886where
887    usize: AsPrimitive<StorageT>,
888{
889    /// Create a new run-time parser from a `YaccGrammar`, and a `StateTable`.
890    pub fn new(grm: &'a YaccGrammar<StorageT>, stable: &'a StateTable<StorageT>) -> Self {
891        RTParserBuilder {
892            grm,
893            stable,
894            recoverer: RecoveryKind::CPCTPlus,
895            term_costs: &|_| 1,
896            phantom: PhantomData,
897        }
898    }
899
900    /// Set the recoverer for this parser to `rk`.
901    pub fn recoverer(mut self, rk: RecoveryKind) -> Self {
902        self.recoverer = rk;
903        self
904    }
905
906    pub fn term_costs(mut self, f: &'a dyn Fn(TIdx<StorageT>) -> u8) -> Self {
907        self.term_costs = f;
908        self
909    }
910
911    #[deprecated(
912        since = "0.14.0",
913        note = "Use `parse_map` to return a `Node` from your `lrpar_mod!` instead"
914    )]
915    #[allow(deprecated)]
916    /// Parse input, and (if possible) return a generic parse tree. See the arguments for
917    /// [`parse_actions`](#method.parse_actions) for more details about the return value.
918    pub fn parse_generictree(
919        &self,
920        lexer: &dyn NonStreamingLexer<LexerTypesT>,
921    ) -> (
922        Option<Node<LexerTypesT::LexemeT, StorageT>>,
923        Vec<LexParseError<StorageT, LexerTypesT>>,
924    ) {
925        self.parse_map(lexer, &|lexeme| Node::Term { lexeme }, &|ridx, nodes| {
926            Node::Nonterm { ridx, nodes }
927        })
928    }
929
930    /// Parse input, and (if possible) return a generic parse tree. See the arguments for
931    /// [`parse_actions`](#method.parse_actions) for more details about the return value.
932    pub fn parse_map<Node>(
933        &self,
934        lexer: &dyn NonStreamingLexer<LexerTypesT>,
935        fterm: &dyn Fn(LexerTypesT::LexemeT) -> Node,
936        fnonterm: &dyn Fn(RIdx<StorageT>, Vec<Node>) -> Node,
937    ) -> (Option<Node>, Vec<LexParseError<StorageT, LexerTypesT>>) {
938        let lexemes = match lexer.iter().collect() {
939            Ok(lexemes) => lexemes,
940            Err(e) => return (None, vec![e.into()]),
941        };
942        Parser::<
943            StorageT,
944            LexerTypesT,
945            Node,
946            (
947                &dyn Fn(LexerTypesT::LexemeT) -> Node,
948                &dyn Fn(RIdx<StorageT>, Vec<Node>) -> Node,
949            ),
950        >::parse_map(
951            self.recoverer,
952            self.grm,
953            self.term_costs,
954            self.stable,
955            lexer,
956            lexemes,
957            fterm,
958            fnonterm,
959        )
960    }
961
962    #[deprecated(since = "0.14.0", note = "Use `parse_map` instead")]
963    /// Parse input, returning any errors found. See the arguments for
964    /// [`parse_actions`](#method.parse_actions) for more details about the return value.
965    pub fn parse_noaction(
966        &self,
967        lexer: &dyn NonStreamingLexer<LexerTypesT>,
968    ) -> Vec<LexParseError<StorageT, LexerTypesT>> {
969        self.parse_map(lexer, &|_| (), &|_, _| ()).1
970    }
971
972    /// Parse input, execute actions, and return the associated value (if possible) and/or any
973    /// lexing/parsing errors encountered. Note that the two parts of the (value, errors) return
974    /// pair are entirely independent: one can encounter errors without a value being produced
975    /// (`None, [...]`), errors and a value (`Some(...), [...]`), as well as a value and no errors
976    /// (`Some(...), []`). Errors are sorted by the position they were found in the input and can
977    /// be a mix of lexing and parsing errors.
978    pub fn parse_actions<'b: 'a, 'input: 'b, ActionT: 'a, ParamT: Clone>(
979        &self,
980        lexer: &'b dyn NonStreamingLexer<'input, LexerTypesT>,
981        actions: &'a [ActionFn<'a, 'b, 'input, StorageT, LexerTypesT, ActionT, ParamT>],
982        param: ParamT,
983    ) -> (Option<ActionT>, Vec<LexParseError<StorageT, LexerTypesT>>) {
984        let lexemes = match lexer.iter().collect() {
985            Ok(lexemes) => lexemes,
986            Err(e) => return (None, vec![e.into()]),
987        };
988        Parser::parse_actions(
989            self.recoverer,
990            self.grm,
991            self.term_costs,
992            self.stable,
993            lexer,
994            lexemes,
995            actions,
996            param,
997        )
998    }
999
1000    pub fn grammar(&self) -> &YaccGrammar<StorageT> {
1001        self.grm
1002    }
1003}
1004
1005/// After a parse error is encountered, the parser attempts to find a way of recovering. Each entry
1006/// in the sequence of repairs is represented by a `ParseRepair`.
1007#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1008pub enum ParseRepair<LexemeT: Lexeme<StorageT>, StorageT: Hash> {
1009    /// Insert a `Symbol::Token`.
1010    Insert(TIdx<StorageT>),
1011    /// Delete a symbol.
1012    Delete(LexemeT),
1013    /// Shift a symbol.
1014    Shift(LexemeT),
1015}
1016
1017/// Records a single parse error.
1018#[derive(Clone, Debug, PartialEq)]
1019pub struct ParseError<LexemeT: Lexeme<StorageT>, StorageT: Hash> {
1020    stidx: StIdx<StorageT>,
1021    lexeme: LexemeT,
1022    repairs: Vec<Vec<ParseRepair<LexemeT, StorageT>>>,
1023}
1024
1025impl<LexemeT: Lexeme<StorageT>, StorageT: Debug + Hash> Display for ParseError<LexemeT, StorageT> {
1026    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1027        write!(f, "Parse error at lexeme {:?}", self.lexeme)
1028    }
1029}
1030
1031impl<LexemeT: Lexeme<StorageT>, StorageT: Debug + Hash> Error for ParseError<LexemeT, StorageT> {}
1032
1033impl<LexemeT: Lexeme<StorageT>, StorageT: Hash + PrimInt + Unsigned> ParseError<LexemeT, StorageT> {
1034    /// Return the state table index where this error was detected.
1035    pub fn stidx(&self) -> StIdx<StorageT> {
1036        self.stidx
1037    }
1038
1039    /// Return the lexeme where this error was detected.
1040    pub fn lexeme(&self) -> &LexemeT {
1041        &self.lexeme
1042    }
1043
1044    /// Return the repairs found that would fix this error. Note that there are infinite number of
1045    /// possible repairs for any error, so this is by definition a (finite) subset.
1046    pub fn repairs(&self) -> &Vec<Vec<ParseRepair<LexemeT, StorageT>>> {
1047        &self.repairs
1048    }
1049}
1050
1051#[cfg(test)]
1052pub(crate) mod test {
1053    use std::collections::HashMap;
1054
1055    use cfgrammar::{
1056        Span,
1057        yacc::{YaccGrammar, YaccKind, YaccOriginalActionKind},
1058    };
1059    use lrtable::{Minimiser, from_yacc};
1060    use num_traits::ToPrimitive;
1061    use regex::Regex;
1062
1063    use super::*;
1064    use crate::{
1065        Lexeme, Lexer,
1066        test_utils::{TestLexError, TestLexeme, TestLexerTypes},
1067    };
1068
1069    #[allow(deprecated)]
1070    pub(crate) fn do_parse<'input>(
1071        rcvry_kind: RecoveryKind,
1072        lexs: &str,
1073        grms: &str,
1074        input: &'input str,
1075    ) -> (
1076        YaccGrammar<u16>,
1077        SmallLexer<'input>,
1078        Result<
1079            Node<TestLexeme, u16>,
1080            (
1081                Option<Node<TestLexeme, u16>>,
1082                Vec<LexParseError<u16, TestLexerTypes>>,
1083            ),
1084        >,
1085    ) {
1086        do_parse_with_costs(rcvry_kind, lexs, grms, input, &HashMap::new())
1087    }
1088
1089    #[allow(deprecated)]
1090    fn do_parse_with_costs<'input>(
1091        rcvry_kind: RecoveryKind,
1092        lexs: &str,
1093        grms: &str,
1094        input: &'input str,
1095        costs: &HashMap<&str, u8>,
1096    ) -> (
1097        YaccGrammar<u16>,
1098        SmallLexer<'input>,
1099        Result<
1100            Node<TestLexeme, u16>,
1101            (
1102                Option<Node<TestLexeme, u16>>,
1103                Vec<LexParseError<u16, TestLexerTypes>>,
1104            ),
1105        >,
1106    ) {
1107        let grm = YaccGrammar::<u16>::new_with_storaget(
1108            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1109            grms,
1110        )
1111        .unwrap();
1112        let (_, stable) = from_yacc(&grm, Minimiser::Pager).unwrap();
1113        let rule_ids = grm
1114            .tokens_map()
1115            .iter()
1116            .map(|(&n, &i)| (n.to_owned(), u32::from(i).to_u16().unwrap()))
1117            .collect();
1118        let lexer_rules = small_lexer(lexs, rule_ids);
1119        let lexemes = small_lex(lexer_rules, input);
1120        let lexer = SmallLexer { lexemes, s: input };
1121        let costs_tidx = costs
1122            .iter()
1123            .map(|(k, v)| (grm.token_idx(k).unwrap(), v))
1124            .collect::<HashMap<_, _>>();
1125        let (r, errs) = RTParserBuilder::new(&grm, &stable)
1126            .recoverer(rcvry_kind)
1127            .term_costs(&|tidx| **costs_tidx.get(&tidx).unwrap_or(&&1))
1128            .parse_generictree(&lexer);
1129        if let Some(node) = r {
1130            if errs.is_empty() {
1131                (grm, lexer, Ok(node))
1132            } else {
1133                (grm, lexer, Err((Some(node), errs)))
1134            }
1135        } else {
1136            (grm, lexer, Err((None, errs)))
1137        }
1138    }
1139
1140    fn check_parse_output(lexs: &str, grms: &str, input: &str, expected: &str) {
1141        let (grm, _, pt) = do_parse(RecoveryKind::CPCTPlus, lexs, grms, input);
1142        assert_eq!(expected, pt.unwrap().pp(&grm, input));
1143    }
1144
1145    // SmallLexer is our highly simplified version of lrlex (allowing us to avoid having to have
1146    // lrlex as a dependency of lrpar). The format is the same as lrlex *except*:
1147    //   * The initial "%%" isn't needed, and only "'" is valid as a rule name delimiter.
1148    //   * "Unnamed" rules aren't allowed (e.g. you can't have a rule which discards whitespaces).
1149    pub(crate) struct SmallLexer<'input> {
1150        lexemes: Vec<TestLexeme>,
1151        s: &'input str,
1152    }
1153
1154    impl Lexer<TestLexerTypes> for SmallLexer<'_> {
1155        fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = Result<TestLexeme, TestLexError>> + 'a> {
1156            Box::new(self.lexemes.iter().map(|x| Ok(*x)))
1157        }
1158    }
1159
1160    impl<'input> NonStreamingLexer<'input, TestLexerTypes> for SmallLexer<'input> {
1161        fn span_str(&self, span: Span) -> &'input str {
1162            &self.s[span.start()..span.end()]
1163        }
1164
1165        fn span_lines_str(&self, _: Span) -> &'input str {
1166            unreachable!();
1167        }
1168
1169        fn line_col(&self, _: Span) -> ((usize, usize), (usize, usize)) {
1170            unreachable!();
1171        }
1172    }
1173
1174    fn small_lexer(lexs: &str, ids_map: HashMap<String, u16>) -> Vec<(u16, Regex)> {
1175        let mut rules = Vec::new();
1176        for l in lexs.split('\n').map(|x| x.trim()).filter(|x| !x.is_empty()) {
1177            assert!(l.rfind('\'') == Some(l.len() - 1));
1178            let i = l[..l.len() - 1].rfind('\'').unwrap();
1179            let name = &l[i + 1..l.len() - 1];
1180            let re = &l[..i - 1].trim();
1181            rules.push((
1182                ids_map[name],
1183                Regex::new(&format!("\\A(?:{})", re)).unwrap(),
1184            ));
1185        }
1186        rules
1187    }
1188
1189    fn small_lex(rules: Vec<(u16, Regex)>, input: &str) -> Vec<TestLexeme> {
1190        let mut lexemes = vec![];
1191        let mut i = 0;
1192        while i < input.len() {
1193            let mut longest = 0; // Length of the longest match
1194            let mut longest_tok_id = 0; // This is only valid iff longest != 0
1195            for (tok_id, r) in rules.iter() {
1196                if let Some(m) = r.find(&input[i..]) {
1197                    let len = m.end();
1198                    if len > longest {
1199                        longest = len;
1200                        longest_tok_id = *tok_id;
1201                    }
1202                }
1203            }
1204            assert!(longest > 0);
1205            lexemes.push(Lexeme::new(longest_tok_id, i, longest));
1206            i += longest;
1207        }
1208        lexemes
1209    }
1210
1211    #[test]
1212    fn simple_parse() {
1213        // From p4 of https://www.cs.umd.edu/class/spring2014/cmsc430/lectures/lec07.pdf
1214        check_parse_output(
1215            "[a-zA-Z_] 'ID'
1216             \\+ '+'",
1217            "
1218%start E
1219%%
1220E: T '+' E
1221 | T;
1222T: 'ID';
1223",
1224            "a+b",
1225            "E
1226 T
1227  ID a
1228 + +
1229 E
1230  T
1231   ID b
1232",
1233        );
1234    }
1235
1236    #[test]
1237    fn parse_empty_rules() {
1238        let lexs = "[a-zA-Z_] 'ID'";
1239        let grms = "%start S
1240%%
1241S: L;
1242L: 'ID'
1243 | ;
1244";
1245        check_parse_output(
1246            lexs, grms, "", "S
1247 L
1248",
1249        );
1250
1251        check_parse_output(
1252            lexs,
1253            grms,
1254            "x",
1255            "S
1256 L
1257  ID x
1258",
1259        );
1260    }
1261
1262    #[test]
1263    fn recursive_parse() {
1264        let lexs = "\\+ '+'
1265                    \\* '*'
1266                    [0-9]+ 'INT'";
1267        let grms = "%start Expr
1268%%
1269Expr : Expr '+' Term | Term;
1270Term : Term '*' Factor | Factor;
1271Factor : 'INT';";
1272
1273        check_parse_output(
1274            lexs,
1275            grms,
1276            "2+3*4",
1277            "Expr
1278 Expr
1279  Term
1280   Factor
1281    INT 2
1282 + +
1283 Term
1284  Term
1285   Factor
1286    INT 3
1287  * *
1288  Factor
1289   INT 4
1290",
1291        );
1292        check_parse_output(
1293            lexs,
1294            grms,
1295            "2*3+4",
1296            "Expr
1297 Expr
1298  Term
1299   Term
1300    Factor
1301     INT 2
1302   * *
1303   Factor
1304    INT 3
1305 + +
1306 Term
1307  Factor
1308   INT 4
1309",
1310        );
1311    }
1312
1313    #[test]
1314    fn parse_error() {
1315        let lexs = "\\( '('
1316                    \\) ')'
1317                    [a-zA-Z_][a-zA-Z_0-9]* 'ID'";
1318        let grms = "%start Call
1319%%
1320Call: 'ID' '(' ')';";
1321
1322        check_parse_output(
1323            lexs,
1324            grms,
1325            "f()",
1326            "Call
1327 ID f
1328 ( (
1329 ) )
1330",
1331        );
1332
1333        let (grm, _, pr) = do_parse(RecoveryKind::CPCTPlus, lexs, grms, "f(");
1334        let (_, errs) = pr.unwrap_err();
1335        assert_eq!(errs.len(), 1);
1336        let err_tok_id = usize::from(grm.eof_token_idx()).to_u16().unwrap();
1337        match &errs[0] {
1338            LexParseError::ParseError(e) => {
1339                assert_eq!(e.lexeme(), &Lexeme::new_faulty(err_tok_id, 2, 0));
1340                assert!(e.lexeme().faulty());
1341            }
1342            _ => unreachable!(),
1343        }
1344
1345        let (grm, _, pr) = do_parse(RecoveryKind::CPCTPlus, lexs, grms, "f(f(");
1346        let (_, errs) = pr.unwrap_err();
1347        assert_eq!(errs.len(), 1);
1348        let err_tok_id = usize::from(grm.token_idx("ID").unwrap()).to_u16().unwrap();
1349        match &errs[0] {
1350            LexParseError::ParseError(e) => {
1351                assert_eq!(e.lexeme(), &Lexeme::new(err_tok_id, 2, 1));
1352                assert!(!e.lexeme().faulty());
1353            }
1354            _ => unreachable!(),
1355        }
1356    }
1357
1358    #[test]
1359    fn test_parse_map() {
1360        #[derive(PartialEq, Debug)]
1361        enum TestParseMap<'a> {
1362            Term(&'a str, &'a str),
1363            NonTerm(&'a str, Vec<TestParseMap<'a>>),
1364        }
1365        let lex_src = r#"[0-9]+ 'INT'
1366\+ '+'
1367\* '*'
1368"#;
1369        let grammar_src = "
1370%grmtools{YaccKind: Original(NoAction)}
1371%start Expr
1372%%
1373Expr : Expr '+' Term | Term;
1374Term : Term '*' Factor | Factor;
1375Factor : 'INT';";
1376        let input_src = "2*3+4";
1377        let grm = str::parse::<YaccGrammar<u16>>(grammar_src).unwrap();
1378        let (_, stable) = lrtable::from_yacc(&grm, lrtable::Minimiser::Pager).unwrap();
1379        let rt_parser = RTParserBuilder::new(&grm, &stable);
1380        let rule_ids = grm
1381            .tokens_map()
1382            .iter()
1383            .map(|(&n, &i)| (n.to_owned(), u32::from(i).to_u16().unwrap()))
1384            .collect();
1385        let lexer_rules = small_lexer(lex_src, rule_ids);
1386        let lexemes = small_lex(lexer_rules, input_src);
1387        let lexer = SmallLexer {
1388            lexemes,
1389            s: input_src,
1390        };
1391
1392        let (parse_map, errs) = rt_parser.parse_map(
1393            &lexer,
1394            &|lexeme: TestLexeme| {
1395                let tidx = TIdx(lexeme.tok_id());
1396                let tn = &grm.token_name(tidx).unwrap();
1397                let lt = &input_src[lexeme.span().start()..lexeme.span().end()];
1398                TestParseMap::Term(tn, lt)
1399            },
1400            &|ridx, nodes| {
1401                let rule_name = &grm.rule_name_str(ridx);
1402                TestParseMap::NonTerm(rule_name, nodes)
1403            },
1404        );
1405        assert!(parse_map.is_some() && errs.is_empty());
1406        // Sanity check the `parse_generictree` output.
1407        check_parse_output(
1408            lex_src,
1409            grammar_src,
1410            input_src,
1411            "Expr
1412 Expr
1413  Term
1414   Term
1415    Factor
1416     INT 2
1417   * *
1418   Factor
1419    INT 3
1420 + +
1421 Term
1422  Factor
1423   INT 4
1424",
1425        );
1426
1427        let expected_parse_map = {
1428            use TestParseMap::*;
1429            NonTerm(
1430                "Expr",
1431                vec![
1432                    NonTerm(
1433                        "Expr",
1434                        vec![NonTerm(
1435                            "Term",
1436                            vec![
1437                                NonTerm("Term", vec![NonTerm("Factor", vec![Term("INT", "2")])]),
1438                                Term("*", "*"),
1439                                NonTerm("Factor", vec![Term("INT", "3")]),
1440                            ],
1441                        )],
1442                    ),
1443                    Term("+", "+"),
1444                    NonTerm("Term", vec![NonTerm("Factor", vec![Term("INT", "4")])]),
1445                ],
1446            )
1447        };
1448        assert_eq!(parse_map, Some(expected_parse_map));
1449    }
1450}