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#[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::{
18 RIdx, Span, TIdx,
19 header::{HeaderError, HeaderErrorKind, Value},
20 yacc::YaccGrammar,
21};
22use lrtable::{Action, StIdx, StateTable};
23use num_traits::{AsPrimitive, PrimInt, Unsigned};
24use proc_macro2::TokenStream;
25use quote::quote;
26#[cfg(feature = "serde")]
27use serde::{Deserialize, Serialize};
28
29use crate::{LexError, Lexeme, LexerTypes, NonStreamingLexer, cpctplus};
30
31#[cfg(test)]
32const RECOVERY_TIME_BUDGET: u64 = 60_000; #[cfg(not(test))]
34const RECOVERY_TIME_BUDGET: u64 = 500; #[deprecated(
37 since = "0.14.0",
38 note = "Use the version of `Node` exported from your `lrpar_mod!`"
39)]
40pub type Node<T, S> = _deprecated_moved_::Node<T, S>;
41
42#[doc(hidden)]
43pub mod _deprecated_moved_ {
44 use super::*;
45 #[derive(Debug, Clone, PartialEq)]
47 pub enum Node<LexemeT: Lexeme<StorageT>, StorageT> {
48 Term { lexeme: LexemeT },
50 Nonterm {
52 ridx: RIdx<StorageT>,
53 nodes: Vec<Node<LexemeT, StorageT>>,
54 },
55 }
56}
57
58#[allow(deprecated)]
59impl<LexemeT: Lexeme<StorageT>, StorageT: 'static + PrimInt + Unsigned> Node<LexemeT, StorageT>
60where
61 usize: AsPrimitive<StorageT>,
62{
63 pub fn pp(&self, grm: &YaccGrammar<StorageT>, input: &str) -> String {
65 let mut st = vec![(0, self)]; let mut s = String::new();
67 while let Some((indent, e)) = st.pop() {
68 for _ in 0..indent {
69 s.push(' ');
70 }
71 match *e {
72 Node::Term { lexeme } => {
73 let tidx = TIdx(lexeme.tok_id());
74 let tn = grm.token_name(tidx).unwrap();
75 let lt = &input[lexeme.span().start()..lexeme.span().end()];
76 writeln!(s, "{} {}", tn, lt).ok();
77 }
78 Node::Nonterm { ridx, ref nodes } => {
79 writeln!(s, "{}", grm.rule_name_str(ridx)).ok();
80 for x in nodes.iter().rev() {
81 st.push((indent + 1, x));
82 }
83 }
84 }
85 }
86 s
87 }
88}
89
90type PStack<StorageT> = Vec<StIdx<StorageT>>; type TokenCostFn<'a, StorageT> = &'a (dyn Fn(TIdx<StorageT>) -> u8 + 'a);
92type ActionFn<'a, 'b, 'input, StorageT, LexerTypesT, ActionT, ParamT> = &'a dyn Fn(
93 RIdx<StorageT>,
94 &'b dyn NonStreamingLexer<'input, LexerTypesT>,
95 Span,
96 vec::Drain<AStackType<<LexerTypesT as LexerTypes>::LexemeT, ActionT>>,
97 ParamT,
98) -> ActionT;
99
100#[derive(Debug)]
101pub enum AStackType<LexemeT, ActionT> {
102 ActionType(ActionT),
103 Lexeme(LexemeT),
104}
105
106pub(super) struct Parser<
107 'a,
108 'b: 'a,
109 'input: 'b,
110 StorageT: 'static + Eq + Hash + PrimInt + Unsigned,
111 LexerTypesT: LexerTypes<StorageT = StorageT>,
112 ActionT: 'a,
113 ParamT: Clone,
114> where
115 usize: AsPrimitive<StorageT>,
116{
117 rcvry_kind: RecoveryKind,
118 pub(super) grm: &'a YaccGrammar<StorageT>,
119 pub(super) token_cost: TokenCostFn<'a, StorageT>,
120 pub(super) stable: &'a StateTable<StorageT>,
121 lexer: &'b dyn NonStreamingLexer<'input, LexerTypesT>,
122 pub(super) lexemes: Vec<LexerTypesT::LexemeT>,
125 actions: &'a [ActionFn<'a, 'b, 'input, LexerTypesT::StorageT, LexerTypesT, ActionT, ParamT>],
126 param: ParamT,
127}
128
129impl<
130 'a,
131 'b: 'a,
132 'input: 'b,
133 StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
134 LexerTypesT: LexerTypes<StorageT = StorageT>,
135 Node,
136>
137 Parser<
138 'a,
139 'b,
140 'input,
141 StorageT,
142 LexerTypesT,
143 Node,
144 (
145 &dyn Fn(LexerTypesT::LexemeT) -> Node,
146 &dyn Fn(RIdx<StorageT>, Vec<Node>) -> Node,
147 ),
148 >
149where
150 usize: AsPrimitive<StorageT>,
151{
152 fn parse_map(
153 rcvry_kind: RecoveryKind,
154 grm: &YaccGrammar<StorageT>,
155 token_cost: TokenCostFn<'a, StorageT>,
156 stable: &StateTable<StorageT>,
157 lexer: &'b dyn NonStreamingLexer<'input, LexerTypesT>,
158 lexemes: Vec<LexerTypesT::LexemeT>,
159 fterm: &'a dyn Fn(LexerTypesT::LexemeT) -> Node,
160 fnonterm: &'a dyn Fn(RIdx<StorageT>, Vec<Node>) -> Node,
161 ) -> (Option<Node>, Vec<LexParseError<StorageT, LexerTypesT>>) {
162 for tidx in grm.iter_tidxs() {
163 assert!(token_cost(tidx) > 0);
164 }
165 let mut actions: Vec<
166 ActionFn<
167 'a,
168 'b,
169 'input,
170 StorageT,
171 LexerTypesT,
172 Node,
173 (
174 &'a dyn Fn(LexerTypesT::LexemeT) -> Node,
175 &'a dyn Fn(RIdx<StorageT>, Vec<Node>) -> Node,
176 ),
177 >,
178 > = Vec::new();
179 actions.resize(usize::from(grm.prods_len()), &action_map);
180 let psr = Parser {
181 rcvry_kind,
182 grm,
183 token_cost,
184 stable,
185 lexer,
186 lexemes,
187 actions: actions.as_slice(),
188 param: (fterm, fnonterm),
189 };
190 let mut pstack = vec![stable.start_state()];
191 let mut astack = Vec::new();
192 let mut errors = Vec::new();
193 let mut spans = Vec::new();
194 let accpt = psr.lr(0, &mut pstack, &mut astack, &mut errors, &mut spans);
195 (accpt, errors)
196 }
197}
198
199fn action_map<StorageT, LexerTypesT: LexerTypes, Node>(
200 ridx: RIdx<StorageT>,
201 _lexer: &dyn NonStreamingLexer<LexerTypesT>,
202 _span: Span,
203 astack: vec::Drain<AStackType<LexerTypesT::LexemeT, Node>>,
204 param: (
205 &dyn Fn(LexerTypesT::LexemeT) -> Node,
206 &dyn Fn(RIdx<StorageT>, Vec<Node>) -> Node,
207 ),
208) -> Node
209where
210 usize: AsPrimitive<LexerTypesT::StorageT>,
211 LexerTypesT::LexemeT: Lexeme<StorageT>,
212{
213 let (fterm, fnonterm) = param;
214 let mut nodes = Vec::with_capacity(astack.len());
215 for a in astack {
216 nodes.push(match a {
217 AStackType::ActionType(n) => n,
218 AStackType::Lexeme(lexeme) => fterm(lexeme),
219 });
220 }
221 fnonterm(ridx, nodes)
222}
223
224#[deprecated(
225 since = "0.14.0",
226 note = "Deprecated with `parse_generictree` there is no direct replacement, besides a custom action"
227)]
228#[allow(deprecated)]
229pub fn action_generictree<StorageT, LexerTypesT: LexerTypes>(
233 ridx: RIdx<StorageT>,
234 _lexer: &dyn NonStreamingLexer<LexerTypesT>,
235 _span: Span,
236 astack: vec::Drain<AStackType<LexerTypesT::LexemeT, Node<LexerTypesT::LexemeT, StorageT>>>,
237 _param: (),
238) -> Node<LexerTypesT::LexemeT, StorageT>
239where
240 usize: AsPrimitive<LexerTypesT::StorageT>,
241 LexerTypesT::LexemeT: Lexeme<StorageT>,
242{
243 let mut nodes = Vec::with_capacity(astack.len());
244 for a in astack {
245 nodes.push(match a {
246 AStackType::ActionType(n) => n,
247 AStackType::Lexeme(lexeme) => Node::Term { lexeme },
248 });
249 }
250 Node::Nonterm { ridx, nodes }
251}
252
253impl<
254 'a,
255 'b: 'a,
256 'input: 'b,
257 StorageT: 'static + Debug + Eq + Hash + PrimInt + Unsigned,
258 LexerTypesT: LexerTypes<StorageT = StorageT>,
259 ActionT: 'a,
260 ParamT: Clone,
261> Parser<'a, 'b, 'input, StorageT, LexerTypesT, ActionT, ParamT>
262where
263 usize: AsPrimitive<StorageT>,
264{
265 fn parse_actions(
266 rcvry_kind: RecoveryKind,
267 grm: &'a YaccGrammar<StorageT>,
268 token_cost: TokenCostFn<'a, StorageT>,
269 stable: &'a StateTable<StorageT>,
270 lexer: &'b dyn NonStreamingLexer<'input, LexerTypesT>,
271 lexemes: Vec<LexerTypesT::LexemeT>,
272 actions: &'a [ActionFn<'a, 'b, 'input, StorageT, LexerTypesT, ActionT, ParamT>],
273 param: ParamT,
274 ) -> (Option<ActionT>, Vec<LexParseError<StorageT, LexerTypesT>>) {
275 for tidx in grm.iter_tidxs() {
276 assert!(token_cost(tidx) > 0);
277 }
278 let psr = Parser {
279 rcvry_kind,
280 grm,
281 token_cost,
282 stable,
283 lexer,
284 lexemes,
285 actions,
286 param,
287 };
288 let mut pstack = vec![stable.start_state()];
289 let mut astack = Vec::new();
290 let mut errors = Vec::new();
291 let mut spans = Vec::new();
292 let accpt = psr.lr(0, &mut pstack, &mut astack, &mut errors, &mut spans);
293 (accpt, errors)
294 }
295
296 fn lr(
310 &self,
311 mut laidx: usize,
312 pstack: &mut PStack<StorageT>,
313 astack: &mut Vec<AStackType<LexerTypesT::LexemeT, ActionT>>,
314 errors: &mut Vec<LexParseError<StorageT, LexerTypesT>>,
315 spans: &mut Vec<Span>,
316 ) -> Option<ActionT> {
317 let mut recoverer = None;
318 let mut recovery_budget = Duration::from_millis(RECOVERY_TIME_BUDGET);
319 loop {
320 debug_assert_eq!(astack.len(), spans.len());
321 let stidx = *pstack.last().unwrap();
322 let la_tidx = self.next_tidx(laidx);
323
324 match self.stable.action(stidx, la_tidx) {
325 Action::Reduce(pidx) => {
326 let ridx = self.grm.prod_to_rule(pidx);
327 let pop_idx = pstack.len() - self.grm.prod(pidx).len();
328
329 pstack.drain(pop_idx..);
330 let prior = *pstack.last().unwrap();
331 pstack.push(self.stable.goto(prior, ridx).unwrap());
332
333 let span = if spans.is_empty() {
334 Span::new(0, 0)
335 } else if pop_idx - 1 < spans.len() {
336 Span::new(spans[pop_idx - 1].start(), spans[spans.len() - 1].end())
337 } else {
338 Span::new(spans[spans.len() - 1].start(), spans[spans.len() - 1].end())
339 };
340 spans.truncate(pop_idx - 1);
341 spans.push(span);
342
343 let v = AStackType::ActionType(self.actions[usize::from(pidx)](
344 ridx,
345 self.lexer,
346 span,
347 astack.drain(pop_idx - 1..),
348 self.param.clone(),
349 ));
350 astack.push(v);
351 }
352 Action::Shift(state_id) => {
353 let la_lexeme = self.next_lexeme(laidx);
354 pstack.push(state_id);
355 astack.push(AStackType::Lexeme(la_lexeme));
356
357 spans.push(la_lexeme.span());
358 laidx += 1;
359 }
360 Action::Accept => {
361 debug_assert_eq!(la_tidx, self.grm.eof_token_idx());
362 debug_assert_eq!(astack.len(), 1);
363 match astack.drain(..).next().unwrap() {
364 AStackType::ActionType(v) => return Some(v),
365 _ => unreachable!(),
366 }
367 }
368 Action::Error => {
369 if recoverer.is_none() {
370 recoverer = Some(match self.rcvry_kind {
371 RecoveryKind::CPCTPlus => cpctplus::recoverer(self),
372 RecoveryKind::None => {
373 let la_lexeme = self.next_lexeme(laidx);
374 errors.push(
375 ParseError {
376 stidx,
377 lexeme: la_lexeme,
378 repairs: vec![],
379 }
380 .into(),
381 );
382 return None;
383 }
384 });
385 }
386
387 let before = Instant::now();
388 let finish_by = before + recovery_budget;
389 let (new_laidx, repairs) = recoverer
390 .as_ref()
391 .unwrap()
392 .as_ref()
393 .recover(finish_by, self, laidx, pstack, astack, spans);
394 let after = Instant::now();
395 recovery_budget = recovery_budget
396 .checked_sub(after - before)
397 .unwrap_or_else(|| Duration::new(0, 0));
398 let keep_going = !repairs.is_empty();
399 let la_lexeme = self.next_lexeme(laidx);
400 errors.push(
401 ParseError {
402 stidx,
403 lexeme: la_lexeme,
404 repairs,
405 }
406 .into(),
407 );
408 if !keep_going {
409 return None;
410 }
411 laidx = new_laidx;
412 }
413 }
414 }
415 }
416
417 pub(super) fn lr_upto(
422 &self,
423 lexeme_prefix: Option<LexerTypesT::LexemeT>,
424 mut laidx: usize,
425 end_laidx: usize,
426 pstack: &mut PStack<StorageT>,
427 astack: &mut Option<&mut Vec<AStackType<LexerTypesT::LexemeT, ActionT>>>,
428 spans: &mut Option<&mut Vec<Span>>,
429 ) -> usize {
430 assert!(lexeme_prefix.is_none() || end_laidx == laidx + 1);
431 while laidx != end_laidx && laidx <= self.lexemes.len() {
432 let stidx = *pstack.last().unwrap();
433 let la_tidx = if let Some(l) = lexeme_prefix {
434 TIdx(l.tok_id())
435 } else {
436 self.next_tidx(laidx)
437 };
438
439 match self.stable.action(stidx, la_tidx) {
440 Action::Reduce(pidx) => {
441 let ridx = self.grm.prod_to_rule(pidx);
442 let pop_idx = pstack.len() - self.grm.prod(pidx).len();
443 if let Some(ref mut astack_uw) = *astack {
444 if let Some(ref mut spans_uw) = *spans {
445 let span = if spans_uw.is_empty() {
446 Span::new(0, 0)
447 } else if pop_idx - 1 < spans_uw.len() {
448 Span::new(
449 spans_uw[pop_idx - 1].start(),
450 spans_uw[spans_uw.len() - 1].end(),
451 )
452 } else {
453 Span::new(
454 spans_uw[spans_uw.len() - 1].start(),
455 spans_uw[spans_uw.len() - 1].end(),
456 )
457 };
458 spans_uw.truncate(pop_idx - 1);
459 spans_uw.push(span);
460
461 let v = AStackType::ActionType(self.actions[usize::from(pidx)](
462 ridx,
463 self.lexer,
464 span,
465 astack_uw.drain(pop_idx - 1..),
466 self.param.clone(),
467 ));
468 astack_uw.push(v);
469 } else {
470 unreachable!();
471 }
472 }
473
474 pstack.drain(pop_idx..);
475 let prior = *pstack.last().unwrap();
476 pstack.push(self.stable.goto(prior, ridx).unwrap());
477 }
478 Action::Shift(state_id) => {
479 if let Some(ref mut astack_uw) = *astack
480 && let Some(spans_uw) = spans
481 {
482 let la_lexeme = if let Some(l) = lexeme_prefix {
483 l
484 } else {
485 self.next_lexeme(laidx)
486 };
487 astack_uw.push(AStackType::Lexeme(la_lexeme));
488 spans_uw.push(la_lexeme.span());
489 }
490 pstack.push(state_id);
491 laidx += 1;
492 }
493 Action::Accept => {
494 break;
495 }
496 Action::Error => {
497 break;
498 }
499 }
500 }
501 laidx
502 }
503
504 pub(super) fn next_lexeme(&self, laidx: usize) -> LexerTypesT::LexemeT {
507 let llen = self.lexemes.len();
508 debug_assert!(laidx <= llen);
509 if laidx < llen {
510 self.lexemes[laidx]
511 } else {
512 let last_la_end = if llen == 0 {
514 0
515 } else {
516 debug_assert!(laidx > 0);
517 let last_la = self.lexemes[laidx - 1];
518 last_la.span().end()
519 };
520
521 Lexeme::new_faulty(
522 StorageT::from(u32::from(self.grm.eof_token_idx())).unwrap(),
523 last_la_end,
524 0,
525 )
526 }
527 }
528
529 pub(super) fn next_tidx(&self, laidx: usize) -> TIdx<StorageT> {
532 let ll = self.lexemes.len();
533 debug_assert!(laidx <= ll);
534 if laidx < ll {
535 TIdx(self.lexemes[laidx].tok_id())
536 } else {
537 self.grm.eof_token_idx()
538 }
539 }
540
541 #[allow(deprecated)]
549 pub(super) fn lr_cactus(
550 &self,
551 lexeme_prefix: Option<LexerTypesT::LexemeT>,
552 mut laidx: usize,
553 end_laidx: usize,
554 mut pstack: Cactus<StIdx<StorageT>>,
555 tstack: &mut Option<&mut Vec<Node<LexerTypesT::LexemeT, StorageT>>>,
556 ) -> (usize, Cactus<StIdx<StorageT>>) {
557 assert!(lexeme_prefix.is_none() || end_laidx == laidx + 1);
558 while laidx != end_laidx {
559 let stidx = *pstack.val().unwrap();
560 let la_tidx = if let Some(l) = lexeme_prefix {
561 TIdx(l.tok_id())
562 } else {
563 self.next_tidx(laidx)
564 };
565
566 match self.stable.action(stidx, la_tidx) {
567 Action::Reduce(pidx) => {
568 let ridx = self.grm.prod_to_rule(pidx);
569 let pop_num = self.grm.prod(pidx).len();
570 if let Some(ref mut tstack_uw) = *tstack {
571 let nodes = tstack_uw
572 .drain(pstack.len() - pop_num - 1..)
573 .collect::<Vec<Node<LexerTypesT::LexemeT, StorageT>>>();
574 tstack_uw.push(Node::Nonterm { ridx, nodes });
575 }
576
577 for _ in 0..pop_num {
578 pstack = pstack.parent().unwrap();
579 }
580 let prior = *pstack.val().unwrap();
581 pstack = pstack.child(self.stable.goto(prior, ridx).unwrap());
582 }
583 Action::Shift(state_id) => {
584 if let Some(ref mut tstack_uw) = *tstack {
585 let la_lexeme = if let Some(l) = lexeme_prefix {
586 l
587 } else {
588 self.next_lexeme(laidx)
589 };
590 tstack_uw.push(Node::Term { lexeme: la_lexeme });
591 }
592 pstack = pstack.child(state_id);
593 laidx += 1;
594 }
595 Action::Accept => {
596 debug_assert_eq!(la_tidx, self.grm.eof_token_idx());
597 if let Some(ref tstack_uw) = *tstack {
598 debug_assert_eq!(tstack_uw.len(), 1);
599 }
600 break;
601 }
602 Action::Error => {
603 break;
604 }
605 }
606 }
607 (laidx, pstack)
608 }
609}
610
611pub(super) trait Recoverer<
612 StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
613 LexerTypesT: LexerTypes<StorageT = StorageT>,
614 ActionT,
615 ParamT: Clone,
616> where
617 usize: AsPrimitive<StorageT>,
618{
619 fn recover(
620 &self,
621 finish_by: Instant,
622 parser: &Parser<StorageT, LexerTypesT, ActionT, ParamT>,
623 in_laidx: usize,
624 in_pstack: &mut PStack<StorageT>,
625 astack: &mut Vec<AStackType<LexerTypesT::LexemeT, ActionT>>,
626 spans: &mut Vec<Span>,
627 ) -> (usize, Vec<Vec<ParseRepair<LexerTypesT::LexemeT, StorageT>>>);
628}
629
630#[derive(Clone, Copy, Debug)]
632#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
633#[non_exhaustive]
634pub enum RecoveryKind {
635 CPCTPlus,
638 None,
640}
641
642impl TryFrom<&Value<Span>> for RecoveryKind {
643 type Error = cfgrammar::header::HeaderError<Span>;
644 fn try_from(rk: &Value<Span>) -> Result<RecoveryKind, Self::Error> {
645 match rk {
646 Value::Namespaced(rs, loc) => match rs.as_str() {
647 "RecoveryKind::CPCTPlus" | "CPCTPlus" => Ok(RecoveryKind::CPCTPlus),
648 "RecoveryKind::None" | "None" => Ok(RecoveryKind::None),
649 _ => Err(HeaderError {
650 kind: HeaderErrorKind::ConversionError(
651 "RecoveryKind",
652 "Cannot convert to RecoveryKind",
653 ),
654 locations: vec![*loc],
655 }),
656 },
657 value => Err(HeaderError {
658 kind: HeaderErrorKind::ConversionError(
659 "RecoveryKind",
660 "Cannot convert to RecoveryKind",
661 ),
662 locations: vec![*value.primary_location()],
663 }),
664 }
665 }
666}
667
668impl quote::ToTokens for RecoveryKind {
669 fn to_tokens(&self, tokens: &mut TokenStream) {
670 tokens.extend(match *self {
671 RecoveryKind::CPCTPlus => quote!(::lrpar::RecoveryKind::CPCTPlus),
672 RecoveryKind::None => quote!(::lrpar::RecoveryKind::None),
673 })
674 }
675}
676
677#[derive(Debug)]
681pub enum LexParseError<
682 StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
683 LexerTypesT: LexerTypes<StorageT = StorageT>,
684> where
685 usize: AsPrimitive<StorageT>,
686{
687 LexError(LexerTypesT::LexErrorT),
688 ParseError(ParseError<LexerTypesT::LexemeT, StorageT>),
689}
690
691impl<StorageT: Debug + Hash + PrimInt + Unsigned, LexerTypesT: LexerTypes<StorageT = StorageT>>
692 LexParseError<StorageT, LexerTypesT>
693where
694 usize: AsPrimitive<StorageT>,
695{
696 pub fn pp<'a>(
713 &self,
714 lexer: &dyn NonStreamingLexer<LexerTypesT>,
715 epp: &dyn Fn(TIdx<StorageT>) -> Option<&'a str>,
716 ) -> String {
717 match self {
718 LexParseError::LexError(e) => {
719 let ((line, col), _) = lexer.line_col(e.span());
720 format!("Lexing error at line {} column {}.", line, col)
721 }
722 LexParseError::ParseError(e) => {
723 let ((line, col), _) = lexer.line_col(e.lexeme().span());
724 let mut out = format!("Parsing error at line {} column {}.", line, col);
725 let repairs_len = e.repairs().len();
726 if repairs_len == 0 {
727 out.push_str(" No repair sequences found.");
728 } else {
729 out.push_str(" Repair sequences found:");
730 for (i, rs) in e.repairs().iter().enumerate() {
731 let padding = ((repairs_len as f64).log10() as usize)
732 - (((i + 1) as f64).log10() as usize)
733 + 1;
734 write!(out, "\n {}{}: ", " ".repeat(padding), i + 1).ok();
735 let mut rs_out = Vec::new();
736
737 let mut i = 0;
740 while i < rs.len() {
741 match rs[i] {
742 ParseRepair::Delete(l) => {
743 let mut j = i + 1;
744 let mut last_end = l.span().end();
745 while j < rs.len() {
746 if let ParseRepair::Delete(next_l) = rs[j]
747 && next_l.span().start() == last_end
748 {
749 last_end = next_l.span().end();
750 j += 1;
751 continue;
752 }
753 break;
754 }
755 let t = &lexer
756 .span_str(Span::new(l.span().start(), last_end))
757 .replace('\n', "\\n");
758 rs_out.push(format!("Delete {}", t));
759 i = j;
760 }
761 ParseRepair::Insert(tidx) => {
762 rs_out.push(format!("Insert {}", epp(tidx).unwrap()));
763 i += 1;
764 }
765 ParseRepair::Shift(l) => {
766 let t = &lexer.span_str(l.span()).replace('\n', "\\n");
767 rs_out.push(format!("Shift {}", t));
768 i += 1;
769 }
770 }
771 }
772
773 out.push_str(&rs_out.join(", "));
774 }
775 }
776 out
777 }
778 }
779 }
780}
781
782impl<
783 StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
784 LexerTypesT: LexerTypes<StorageT = StorageT>,
785> fmt::Display for LexParseError<StorageT, LexerTypesT>
786where
787 usize: AsPrimitive<StorageT>,
788{
789 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
790 match *self {
791 LexParseError::LexError(ref e) => Display::fmt(e, f),
792 LexParseError::ParseError(ref e) => Display::fmt(e, f),
793 }
794 }
795}
796
797impl<
798 StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
799 LexerTypesT: LexerTypes<StorageT = StorageT>,
800> Error for LexParseError<StorageT, LexerTypesT>
801where
802 usize: AsPrimitive<StorageT>,
803{
804}
805
806impl<
807 StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
808 LexerTypesT: LexerTypes<StorageT = StorageT, LexErrorT = T>,
809 T: LexError,
810> From<T> for LexParseError<StorageT, LexerTypesT>
811where
812 usize: AsPrimitive<StorageT>,
813{
814 fn from(err: T) -> LexParseError<StorageT, LexerTypesT> {
815 LexParseError::LexError(err)
816 }
817}
818
819impl<
820 StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
821 LexerTypesT: LexerTypes<StorageT = StorageT>,
822> From<ParseError<LexerTypesT::LexemeT, StorageT>> for LexParseError<StorageT, LexerTypesT>
823where
824 usize: AsPrimitive<StorageT>,
825{
826 fn from(
827 err: ParseError<LexerTypesT::LexemeT, StorageT>,
828 ) -> LexParseError<StorageT, LexerTypesT> {
829 LexParseError::ParseError(err)
830 }
831}
832
833pub struct RTParserBuilder<
835 'a,
836 StorageT: 'static + Eq + Debug + Hash + PrimInt + Unsigned,
837 LexerTypesT: LexerTypes<StorageT = StorageT>,
838> where
839 usize: AsPrimitive<StorageT>,
840{
841 grm: &'a YaccGrammar<StorageT>,
842 stable: &'a StateTable<StorageT>,
843 recoverer: RecoveryKind,
844 term_costs: &'a dyn Fn(TIdx<StorageT>) -> u8,
845 phantom: PhantomData<(StorageT, LexerTypesT)>,
846}
847
848impl<
849 'a,
850 StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
851 LexerTypesT: LexerTypes<StorageT = StorageT>,
852> RTParserBuilder<'a, StorageT, LexerTypesT>
853where
854 usize: AsPrimitive<StorageT>,
855{
856 pub fn new(grm: &'a YaccGrammar<StorageT>, stable: &'a StateTable<StorageT>) -> Self {
858 RTParserBuilder {
859 grm,
860 stable,
861 recoverer: RecoveryKind::CPCTPlus,
862 term_costs: &|_| 1,
863 phantom: PhantomData,
864 }
865 }
866
867 pub fn recoverer(mut self, rk: RecoveryKind) -> Self {
869 self.recoverer = rk;
870 self
871 }
872
873 pub fn term_costs(mut self, f: &'a dyn Fn(TIdx<StorageT>) -> u8) -> Self {
874 self.term_costs = f;
875 self
876 }
877
878 #[deprecated(
879 since = "0.14.0",
880 note = "Use `parse_map` to return a `Node` from your `lrpar_mod!` instead"
881 )]
882 #[allow(deprecated)]
883 pub fn parse_generictree(
886 &self,
887 lexer: &dyn NonStreamingLexer<LexerTypesT>,
888 ) -> (
889 Option<Node<LexerTypesT::LexemeT, StorageT>>,
890 Vec<LexParseError<StorageT, LexerTypesT>>,
891 ) {
892 self.parse_map(lexer, &|lexeme| Node::Term { lexeme }, &|ridx, nodes| {
893 Node::Nonterm { ridx, nodes }
894 })
895 }
896
897 pub fn parse_map<Node>(
900 &self,
901 lexer: &dyn NonStreamingLexer<LexerTypesT>,
902 fterm: &dyn Fn(LexerTypesT::LexemeT) -> Node,
903 fnonterm: &dyn Fn(RIdx<StorageT>, Vec<Node>) -> Node,
904 ) -> (Option<Node>, Vec<LexParseError<StorageT, LexerTypesT>>) {
905 let lexemes = match lexer.iter().collect() {
906 Ok(lexemes) => lexemes,
907 Err(e) => return (None, vec![e.into()]),
908 };
909 Parser::<
910 StorageT,
911 LexerTypesT,
912 Node,
913 (
914 &dyn Fn(LexerTypesT::LexemeT) -> Node,
915 &dyn Fn(RIdx<StorageT>, Vec<Node>) -> Node,
916 ),
917 >::parse_map(
918 self.recoverer,
919 self.grm,
920 self.term_costs,
921 self.stable,
922 lexer,
923 lexemes,
924 fterm,
925 fnonterm,
926 )
927 }
928
929 #[deprecated(since = "0.14.0", note = "Use `parse_map` instead")]
930 pub fn parse_noaction(
933 &self,
934 lexer: &dyn NonStreamingLexer<LexerTypesT>,
935 ) -> Vec<LexParseError<StorageT, LexerTypesT>> {
936 self.parse_map(lexer, &|_| (), &|_, _| ()).1
937 }
938
939 pub fn parse_actions<'b: 'a, 'input: 'b, ActionT: 'a, ParamT: Clone>(
946 &self,
947 lexer: &'b dyn NonStreamingLexer<'input, LexerTypesT>,
948 actions: &'a [ActionFn<'a, 'b, 'input, StorageT, LexerTypesT, ActionT, ParamT>],
949 param: ParamT,
950 ) -> (Option<ActionT>, Vec<LexParseError<StorageT, LexerTypesT>>) {
951 let lexemes = match lexer.iter().collect() {
952 Ok(lexemes) => lexemes,
953 Err(e) => return (None, vec![e.into()]),
954 };
955 Parser::parse_actions(
956 self.recoverer,
957 self.grm,
958 self.term_costs,
959 self.stable,
960 lexer,
961 lexemes,
962 actions,
963 param,
964 )
965 }
966
967 pub fn grammar(&self) -> &YaccGrammar<StorageT> {
968 self.grm
969 }
970}
971
972#[derive(Clone, Debug, Eq, Hash, PartialEq)]
975pub enum ParseRepair<LexemeT: Lexeme<StorageT>, StorageT: Hash> {
976 Insert(TIdx<StorageT>),
978 Delete(LexemeT),
980 Shift(LexemeT),
982}
983
984#[derive(Clone, Debug, PartialEq)]
986pub struct ParseError<LexemeT: Lexeme<StorageT>, StorageT: Hash> {
987 stidx: StIdx<StorageT>,
988 lexeme: LexemeT,
989 repairs: Vec<Vec<ParseRepair<LexemeT, StorageT>>>,
990}
991
992impl<LexemeT: Lexeme<StorageT>, StorageT: Debug + Hash> Display for ParseError<LexemeT, StorageT> {
993 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
994 write!(f, "Parse error at lexeme {:?}", self.lexeme)
995 }
996}
997
998impl<LexemeT: Lexeme<StorageT>, StorageT: Debug + Hash> Error for ParseError<LexemeT, StorageT> {}
999
1000impl<LexemeT: Lexeme<StorageT>, StorageT: Hash + PrimInt + Unsigned> ParseError<LexemeT, StorageT> {
1001 pub fn stidx(&self) -> StIdx<StorageT> {
1003 self.stidx
1004 }
1005
1006 pub fn lexeme(&self) -> &LexemeT {
1008 &self.lexeme
1009 }
1010
1011 pub fn repairs(&self) -> &Vec<Vec<ParseRepair<LexemeT, StorageT>>> {
1014 &self.repairs
1015 }
1016}
1017
1018#[cfg(test)]
1019pub(crate) mod test {
1020 use std::collections::HashMap;
1021
1022 use cfgrammar::{
1023 Span,
1024 yacc::{YaccGrammar, YaccKind, YaccOriginalActionKind},
1025 };
1026 use lrtable::{Minimiser, from_yacc};
1027 use num_traits::ToPrimitive;
1028 use regex::Regex;
1029
1030 use super::*;
1031 use crate::{
1032 Lexeme, Lexer,
1033 test_utils::{TestLexError, TestLexeme, TestLexerTypes},
1034 };
1035
1036 #[allow(deprecated)]
1037 pub(crate) fn do_parse<'input>(
1038 rcvry_kind: RecoveryKind,
1039 lexs: &str,
1040 grms: &str,
1041 input: &'input str,
1042 ) -> (
1043 YaccGrammar<u16>,
1044 SmallLexer<'input>,
1045 Result<
1046 Node<TestLexeme, u16>,
1047 (
1048 Option<Node<TestLexeme, u16>>,
1049 Vec<LexParseError<u16, TestLexerTypes>>,
1050 ),
1051 >,
1052 ) {
1053 do_parse_with_costs(rcvry_kind, lexs, grms, input, &HashMap::new())
1054 }
1055
1056 #[allow(deprecated)]
1057 fn do_parse_with_costs<'input>(
1058 rcvry_kind: RecoveryKind,
1059 lexs: &str,
1060 grms: &str,
1061 input: &'input str,
1062 costs: &HashMap<&str, u8>,
1063 ) -> (
1064 YaccGrammar<u16>,
1065 SmallLexer<'input>,
1066 Result<
1067 Node<TestLexeme, u16>,
1068 (
1069 Option<Node<TestLexeme, u16>>,
1070 Vec<LexParseError<u16, TestLexerTypes>>,
1071 ),
1072 >,
1073 ) {
1074 let grm = YaccGrammar::<u16>::new_with_storaget(
1075 YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1076 grms,
1077 )
1078 .unwrap();
1079 let (_, stable) = from_yacc(&grm, Minimiser::Pager).unwrap();
1080 let rule_ids = grm
1081 .tokens_map()
1082 .iter()
1083 .map(|(&n, &i)| (n.to_owned(), u32::from(i).to_u16().unwrap()))
1084 .collect();
1085 let lexer_rules = small_lexer(lexs, rule_ids);
1086 let lexemes = small_lex(lexer_rules, input);
1087 let lexer = SmallLexer { lexemes, s: input };
1088 let costs_tidx = costs
1089 .iter()
1090 .map(|(k, v)| (grm.token_idx(k).unwrap(), v))
1091 .collect::<HashMap<_, _>>();
1092 let (r, errs) = RTParserBuilder::new(&grm, &stable)
1093 .recoverer(rcvry_kind)
1094 .term_costs(&|tidx| **costs_tidx.get(&tidx).unwrap_or(&&1))
1095 .parse_generictree(&lexer);
1096 if let Some(node) = r {
1097 if errs.is_empty() {
1098 (grm, lexer, Ok(node))
1099 } else {
1100 (grm, lexer, Err((Some(node), errs)))
1101 }
1102 } else {
1103 (grm, lexer, Err((None, errs)))
1104 }
1105 }
1106
1107 fn check_parse_output(lexs: &str, grms: &str, input: &str, expected: &str) {
1108 let (grm, _, pt) = do_parse(RecoveryKind::CPCTPlus, lexs, grms, input);
1109 assert_eq!(expected, pt.unwrap().pp(&grm, input));
1110 }
1111
1112 pub(crate) struct SmallLexer<'input> {
1117 lexemes: Vec<TestLexeme>,
1118 s: &'input str,
1119 }
1120
1121 impl Lexer<TestLexerTypes> for SmallLexer<'_> {
1122 fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = Result<TestLexeme, TestLexError>> + 'a> {
1123 Box::new(self.lexemes.iter().map(|x| Ok(*x)))
1124 }
1125 }
1126
1127 impl<'input> NonStreamingLexer<'input, TestLexerTypes> for SmallLexer<'input> {
1128 fn span_str(&self, span: Span) -> &'input str {
1129 &self.s[span.start()..span.end()]
1130 }
1131
1132 fn span_lines_str(&self, _: Span) -> &'input str {
1133 unreachable!();
1134 }
1135
1136 fn line_col(&self, _: Span) -> ((usize, usize), (usize, usize)) {
1137 unreachable!();
1138 }
1139 }
1140
1141 fn small_lexer(lexs: &str, ids_map: HashMap<String, u16>) -> Vec<(u16, Regex)> {
1142 let mut rules = Vec::new();
1143 for l in lexs.split('\n').map(|x| x.trim()).filter(|x| !x.is_empty()) {
1144 assert!(l.rfind('\'') == Some(l.len() - 1));
1145 let i = l[..l.len() - 1].rfind('\'').unwrap();
1146 let name = &l[i + 1..l.len() - 1];
1147 let re = &l[..i - 1].trim();
1148 rules.push((
1149 ids_map[name],
1150 Regex::new(&format!("\\A(?:{})", re)).unwrap(),
1151 ));
1152 }
1153 rules
1154 }
1155
1156 fn small_lex(rules: Vec<(u16, Regex)>, input: &str) -> Vec<TestLexeme> {
1157 let mut lexemes = vec![];
1158 let mut i = 0;
1159 while i < input.len() {
1160 let mut longest = 0; let mut longest_tok_id = 0; for (tok_id, r) in rules.iter() {
1163 if let Some(m) = r.find(&input[i..]) {
1164 let len = m.end();
1165 if len > longest {
1166 longest = len;
1167 longest_tok_id = *tok_id;
1168 }
1169 }
1170 }
1171 assert!(longest > 0);
1172 lexemes.push(Lexeme::new(longest_tok_id, i, longest));
1173 i += longest;
1174 }
1175 lexemes
1176 }
1177
1178 #[test]
1179 fn simple_parse() {
1180 check_parse_output(
1182 "[a-zA-Z_] 'ID'
1183 \\+ '+'",
1184 "
1185%start E
1186%%
1187E: T '+' E
1188 | T;
1189T: 'ID';
1190",
1191 "a+b",
1192 "E
1193 T
1194 ID a
1195 + +
1196 E
1197 T
1198 ID b
1199",
1200 );
1201 }
1202
1203 #[test]
1204 fn parse_empty_rules() {
1205 let lexs = "[a-zA-Z_] 'ID'";
1206 let grms = "%start S
1207%%
1208S: L;
1209L: 'ID'
1210 | ;
1211";
1212 check_parse_output(
1213 lexs, grms, "", "S
1214 L
1215",
1216 );
1217
1218 check_parse_output(
1219 lexs,
1220 grms,
1221 "x",
1222 "S
1223 L
1224 ID x
1225",
1226 );
1227 }
1228
1229 #[test]
1230 fn recursive_parse() {
1231 let lexs = "\\+ '+'
1232 \\* '*'
1233 [0-9]+ 'INT'";
1234 let grms = "%start Expr
1235%%
1236Expr : Expr '+' Term | Term;
1237Term : Term '*' Factor | Factor;
1238Factor : 'INT';";
1239
1240 check_parse_output(
1241 lexs,
1242 grms,
1243 "2+3*4",
1244 "Expr
1245 Expr
1246 Term
1247 Factor
1248 INT 2
1249 + +
1250 Term
1251 Term
1252 Factor
1253 INT 3
1254 * *
1255 Factor
1256 INT 4
1257",
1258 );
1259 check_parse_output(
1260 lexs,
1261 grms,
1262 "2*3+4",
1263 "Expr
1264 Expr
1265 Term
1266 Term
1267 Factor
1268 INT 2
1269 * *
1270 Factor
1271 INT 3
1272 + +
1273 Term
1274 Factor
1275 INT 4
1276",
1277 );
1278 }
1279
1280 #[test]
1281 fn parse_error() {
1282 let lexs = "\\( '('
1283 \\) ')'
1284 [a-zA-Z_][a-zA-Z_0-9]* 'ID'";
1285 let grms = "%start Call
1286%%
1287Call: 'ID' '(' ')';";
1288
1289 check_parse_output(
1290 lexs,
1291 grms,
1292 "f()",
1293 "Call
1294 ID f
1295 ( (
1296 ) )
1297",
1298 );
1299
1300 let (grm, _, pr) = do_parse(RecoveryKind::CPCTPlus, lexs, grms, "f(");
1301 let (_, errs) = pr.unwrap_err();
1302 assert_eq!(errs.len(), 1);
1303 let err_tok_id = usize::from(grm.eof_token_idx()).to_u16().unwrap();
1304 match &errs[0] {
1305 LexParseError::ParseError(e) => {
1306 assert_eq!(e.lexeme(), &Lexeme::new_faulty(err_tok_id, 2, 0));
1307 assert!(e.lexeme().faulty());
1308 }
1309 _ => unreachable!(),
1310 }
1311
1312 let (grm, _, pr) = do_parse(RecoveryKind::CPCTPlus, lexs, grms, "f(f(");
1313 let (_, errs) = pr.unwrap_err();
1314 assert_eq!(errs.len(), 1);
1315 let err_tok_id = usize::from(grm.token_idx("ID").unwrap()).to_u16().unwrap();
1316 match &errs[0] {
1317 LexParseError::ParseError(e) => {
1318 assert_eq!(e.lexeme(), &Lexeme::new(err_tok_id, 2, 1));
1319 assert!(!e.lexeme().faulty());
1320 }
1321 _ => unreachable!(),
1322 }
1323 }
1324
1325 #[test]
1326 fn test_parse_map() {
1327 #[derive(PartialEq, Debug)]
1328 enum TestParseMap<'a> {
1329 Term(&'a str, &'a str),
1330 NonTerm(&'a str, Vec<TestParseMap<'a>>),
1331 }
1332 let lex_src = r#"[0-9]+ 'INT'
1333\+ '+'
1334\* '*'
1335"#;
1336 let grammar_src = "
1337%grmtools{yacckind: Original(NoAction)}
1338%start Expr
1339%%
1340Expr : Expr '+' Term | Term;
1341Term : Term '*' Factor | Factor;
1342Factor : 'INT';";
1343 let input_src = "2*3+4";
1344 let grm = str::parse::<YaccGrammar<u16>>(grammar_src).unwrap();
1345 let (_, stable) = lrtable::from_yacc(&grm, lrtable::Minimiser::Pager).unwrap();
1346 let rt_parser = RTParserBuilder::new(&grm, &stable);
1347 let rule_ids = grm
1348 .tokens_map()
1349 .iter()
1350 .map(|(&n, &i)| (n.to_owned(), u32::from(i).to_u16().unwrap()))
1351 .collect();
1352 let lexer_rules = small_lexer(lex_src, rule_ids);
1353 let lexemes = small_lex(lexer_rules, input_src);
1354 let lexer = SmallLexer {
1355 lexemes,
1356 s: input_src,
1357 };
1358
1359 let (parse_map, errs) = rt_parser.parse_map(
1360 &lexer,
1361 &|lexeme: TestLexeme| {
1362 let tidx = TIdx(lexeme.tok_id());
1363 let tn = &grm.token_name(tidx).unwrap();
1364 let lt = &input_src[lexeme.span().start()..lexeme.span().end()];
1365 TestParseMap::Term(tn, lt)
1366 },
1367 &|ridx, nodes| {
1368 let rule_name = &grm.rule_name_str(ridx);
1369 TestParseMap::NonTerm(rule_name, nodes)
1370 },
1371 );
1372 assert!(parse_map.is_some() && errs.is_empty());
1373 check_parse_output(
1375 lex_src,
1376 grammar_src,
1377 input_src,
1378 "Expr
1379 Expr
1380 Term
1381 Term
1382 Factor
1383 INT 2
1384 * *
1385 Factor
1386 INT 3
1387 + +
1388 Term
1389 Factor
1390 INT 4
1391",
1392 );
1393
1394 let expected_parse_map = {
1395 use TestParseMap::*;
1396 NonTerm(
1397 "Expr",
1398 vec![
1399 NonTerm(
1400 "Expr",
1401 vec![NonTerm(
1402 "Term",
1403 vec![
1404 NonTerm("Term", vec![NonTerm("Factor", vec![Term("INT", "2")])]),
1405 Term("*", "*"),
1406 NonTerm("Factor", vec![Term("INT", "3")]),
1407 ],
1408 )],
1409 ),
1410 Term("+", "+"),
1411 NonTerm("Term", vec![NonTerm("Factor", vec![Term("INT", "4")])]),
1412 ],
1413 )
1414 };
1415 assert_eq!(parse_map, Some(expected_parse_map));
1416 }
1417}