Skip to main content

cfgrammar/yacc/
parser.rs

1// Note: this is the parser for both YaccKind::Original(YaccOriginalActionKind::GenericParseTree) and YaccKind::Eco yacc kinds.
2
3use num_traits::PrimInt;
4use regex::Regex;
5#[cfg(feature = "serde")]
6use serde::{Deserialize, Serialize};
7use std::{
8    collections::{HashMap, hash_map::Entry},
9    error::Error,
10    fmt,
11    str::FromStr,
12    sync::LazyLock,
13};
14#[cfg(feature = "wincode")]
15use wincode::{SchemaRead, SchemaWrite};
16
17use crate::{
18    Span, Spanned,
19    header::{GrmtoolsSectionParser, Header, HeaderErrorKind, KEY_CRATE_MAP},
20};
21
22pub type YaccGrammarResult<T> = Result<T, Vec<YaccGrammarError>>;
23
24use super::{
25    AssocKind, Precedence, YaccKind,
26    ast::{GrammarAST, Symbol},
27};
28
29/// The various different possible Yacc parser errors.
30#[derive(Debug, PartialEq, Eq, Clone)]
31#[non_exhaustive]
32pub enum YaccGrammarErrorKind {
33    IllegalInteger,
34    IllegalName,
35    IllegalString,
36    IncompleteRule,
37    IncompleteComment,
38    IncompleteAction,
39    MissingActionCode,
40    MissingActionType,
41    MissingColon,
42    MissingRightArrow,
43    MismatchedBrace,
44    NonEmptyProduction,
45    PrematureEnd,
46    ProductionNotTerminated,
47    ProgramsNotSupported,
48    UnknownDeclaration,
49    PrecNotFollowedByToken,
50    DuplicatePrecedence,
51    DuplicateAvoidInsertDeclaration,
52    DuplicateImplicitTokensDeclaration,
53    DuplicateExpectDeclaration,
54    DuplicateExpectRRDeclaration,
55    DuplicateStartDeclaration,
56    DuplicateActiontypeDeclaration,
57    DuplicateEPP,
58    ReachedEOL,
59    InvalidString,
60    NoStartRule,
61    UnknownSymbol,
62    UnrecognisedActionVariable,
63    InvalidStartRule(String),
64    UnknownRuleRef(String),
65    UnknownToken(String),
66    NoPrecForToken(String),
67    UnknownEPP(String),
68    ExpectedInput(char),
69    InvalidYaccKind,
70    Header(HeaderErrorKind, SpansKind),
71}
72
73/// Any error from the Yacc parser returns an instance of this struct.
74#[derive(Debug, PartialEq, Eq, Clone)]
75pub struct YaccGrammarError {
76    /// Uniquely identifies each error.
77    pub(crate) kind: YaccGrammarErrorKind,
78    /// Always contains at least 1 span.
79    ///
80    /// Refer to [SpansKind] via [spanskind](Self::spanskind)
81    /// For meaning and interpretation of spans and their ordering.
82    pub(crate) spans: Vec<Span>,
83}
84
85impl Error for YaccGrammarError {}
86
87impl fmt::Display for YaccGrammarError {
88    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
89        write!(f, "{}", self.kind)
90    }
91}
92
93impl fmt::Display for YaccGrammarErrorKind {
94    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
95        let s = match self {
96            YaccGrammarErrorKind::ExpectedInput(c) => &format!("Expected input '{c}'"),
97            YaccGrammarErrorKind::IllegalInteger => "Illegal integer",
98            YaccGrammarErrorKind::IllegalName => "Illegal name",
99            YaccGrammarErrorKind::IllegalString => "Illegal string",
100            YaccGrammarErrorKind::IncompleteRule => "Incomplete rule",
101            YaccGrammarErrorKind::IncompleteComment => "Incomplete comment",
102            YaccGrammarErrorKind::IncompleteAction => "Incomplete action",
103            YaccGrammarErrorKind::MissingActionCode => "Production is missing action code",
104            YaccGrammarErrorKind::MissingActionType => "Missing action type",
105            YaccGrammarErrorKind::MissingColon => "Missing ':'",
106            YaccGrammarErrorKind::MissingRightArrow => "Missing '->'",
107            YaccGrammarErrorKind::MismatchedBrace => "Mismatched brace",
108            YaccGrammarErrorKind::NonEmptyProduction => "%empty used in non-empty production",
109            YaccGrammarErrorKind::PrematureEnd => "File ends prematurely",
110            YaccGrammarErrorKind::ProductionNotTerminated => "Production not terminated correctly",
111            YaccGrammarErrorKind::ProgramsNotSupported => "Programs not currently supported",
112            YaccGrammarErrorKind::UnknownDeclaration => "Unknown declaration",
113            YaccGrammarErrorKind::DuplicatePrecedence => "Token has multiple precedences specified",
114            YaccGrammarErrorKind::PrecNotFollowedByToken => "%prec not followed by token name",
115            YaccGrammarErrorKind::UnrecognisedActionVariable => {
116                "Unrecognised action variable following '$'"
117            }
118            YaccGrammarErrorKind::DuplicateAvoidInsertDeclaration => {
119                "Duplicated %avoid_insert declaration"
120            }
121            YaccGrammarErrorKind::DuplicateExpectDeclaration => "Duplicated %expect declaration",
122            YaccGrammarErrorKind::DuplicateExpectRRDeclaration => {
123                "Duplicate %expect-rr declaration"
124            }
125            YaccGrammarErrorKind::DuplicateImplicitTokensDeclaration => {
126                "Duplicated %implicit_tokens declaration"
127            }
128            YaccGrammarErrorKind::DuplicateStartDeclaration => "Duplicated %start declaration",
129            YaccGrammarErrorKind::DuplicateActiontypeDeclaration => {
130                "Duplicate %actiontype declaration"
131            }
132            YaccGrammarErrorKind::DuplicateEPP => "Duplicate %epp declaration for this token",
133            YaccGrammarErrorKind::ReachedEOL => {
134                "Reached end of line without finding expected content"
135            }
136            YaccGrammarErrorKind::InvalidString => "Invalid string",
137            YaccGrammarErrorKind::NoStartRule => return write!(f, "No start rule specified"),
138            YaccGrammarErrorKind::UnknownSymbol => "Unknown symbol, expected a rule or token",
139            YaccGrammarErrorKind::InvalidStartRule(name) => {
140                return write!(f, "Start rule '{}' does not appear in grammar", name);
141            }
142            YaccGrammarErrorKind::UnknownRuleRef(name) => {
143                return write!(f, "Unknown reference to rule '{}'", name);
144            }
145            YaccGrammarErrorKind::UnknownToken(name) => {
146                return write!(f, "Unknown token '{}'", name);
147            }
148            YaccGrammarErrorKind::NoPrecForToken(name) => {
149                return write!(
150                    f,
151                    "Token '{}' used in %prec has no precedence attached",
152                    name
153                );
154            }
155            YaccGrammarErrorKind::UnknownEPP(name) => {
156                return write!(
157                    f,
158                    "Token '{}' in %epp declaration is not referenced in the grammar",
159                    name
160                );
161            }
162            YaccGrammarErrorKind::InvalidYaccKind => "Invalid yacc kind",
163            YaccGrammarErrorKind::Header(hk, _) => &format!("Error in '%grmtools' {}", hk),
164        };
165        write!(f, "{}", s)
166    }
167}
168
169/// The various different possible Yacc parser errors.
170#[derive(Debug, PartialEq, Eq, Clone)]
171#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
172#[cfg_attr(feature = "wincode", derive(SchemaRead, SchemaWrite))]
173#[non_exhaustive]
174pub enum YaccGrammarWarningKind {
175    UnusedRule,
176    UnusedToken,
177}
178
179/// Any Warning from the Yacc parser returns an instance of this struct.
180#[derive(Debug, PartialEq, Eq, Clone)]
181#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
182#[cfg_attr(feature = "wincode", derive(SchemaRead, SchemaWrite))]
183pub struct YaccGrammarWarning {
184    /// The specific kind of warning.
185    pub(crate) kind: YaccGrammarWarningKind,
186    /// Always contains at least 1 span.
187    ///
188    /// Refer to [SpansKind] via [spanskind](Self::spanskind)
189    /// For meaning and interpretation of spans and their ordering.
190    pub(crate) spans: Vec<Span>,
191}
192
193impl fmt::Display for YaccGrammarWarning {
194    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
195        write!(f, "{}", self.kind)
196    }
197}
198
199impl fmt::Display for YaccGrammarWarningKind {
200    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
201        let s = match self {
202            YaccGrammarWarningKind::UnusedRule => "Unused rule",
203            YaccGrammarWarningKind::UnusedToken => "Unused token",
204        };
205        write!(f, "{}", s)
206    }
207}
208
209impl Spanned for YaccGrammarWarning {
210    /// Returns the spans associated with the error, always containing at least 1 span.
211    ///
212    /// Refer to [SpansKind] via [spanskind](Self::spanskind)
213    /// for the meaning and interpretation of spans and their ordering.
214    fn spans(&self) -> &[Span] {
215        self.spans.as_slice()
216    }
217
218    /// Returns the [SpansKind] associated with this error.
219    fn spanskind(&self) -> SpansKind {
220        match self.kind {
221            YaccGrammarWarningKind::UnusedRule | YaccGrammarWarningKind::UnusedToken => {
222                SpansKind::Error
223            }
224        }
225    }
226}
227
228/// Indicates how to interpret the spans of an error.
229#[derive(Debug, PartialEq, Eq, Copy, Clone)]
230#[non_exhaustive]
231pub enum SpansKind {
232    /// The first span is the first occurrence, and a span for each subsequent occurrence.
233    DuplicationError,
234    /// Contains a single span at the site of the error.
235    Error,
236}
237
238impl Spanned for YaccGrammarError {
239    /// Returns the spans associated with the error, always containing at least 1 span.
240    ///
241    /// Refer to [SpansKind] via [spanskind](Self::spanskind)
242    /// for the meaning and interpretation of spans and their ordering.
243    fn spans(&self) -> &[Span] {
244        self.spans.as_slice()
245    }
246
247    /// Returns the [SpansKind] associated with this error.
248    fn spanskind(&self) -> SpansKind {
249        match self.kind {
250            YaccGrammarErrorKind::IllegalInteger
251            | YaccGrammarErrorKind::IllegalName
252            | YaccGrammarErrorKind::IllegalString
253            | YaccGrammarErrorKind::IncompleteRule
254            | YaccGrammarErrorKind::IncompleteComment
255            | YaccGrammarErrorKind::IncompleteAction
256            | YaccGrammarErrorKind::MissingActionCode
257            | YaccGrammarErrorKind::MissingActionType
258            | YaccGrammarErrorKind::MissingColon
259            | YaccGrammarErrorKind::MissingRightArrow
260            | YaccGrammarErrorKind::MismatchedBrace
261            | YaccGrammarErrorKind::NonEmptyProduction
262            | YaccGrammarErrorKind::PrematureEnd
263            | YaccGrammarErrorKind::ProductionNotTerminated
264            | YaccGrammarErrorKind::PrecNotFollowedByToken
265            | YaccGrammarErrorKind::ProgramsNotSupported
266            | YaccGrammarErrorKind::UnknownDeclaration
267            | YaccGrammarErrorKind::ReachedEOL
268            | YaccGrammarErrorKind::InvalidString
269            | YaccGrammarErrorKind::NoStartRule
270            | YaccGrammarErrorKind::UnknownSymbol
271            | YaccGrammarErrorKind::UnrecognisedActionVariable
272            | YaccGrammarErrorKind::InvalidStartRule(_)
273            | YaccGrammarErrorKind::UnknownRuleRef(_)
274            | YaccGrammarErrorKind::UnknownToken(_)
275            | YaccGrammarErrorKind::NoPrecForToken(_)
276            | YaccGrammarErrorKind::InvalidYaccKind
277            | YaccGrammarErrorKind::ExpectedInput(_)
278            | YaccGrammarErrorKind::UnknownEPP(_) => SpansKind::Error,
279            YaccGrammarErrorKind::DuplicatePrecedence
280            | YaccGrammarErrorKind::DuplicateAvoidInsertDeclaration
281            | YaccGrammarErrorKind::DuplicateExpectDeclaration
282            | YaccGrammarErrorKind::DuplicateExpectRRDeclaration
283            | YaccGrammarErrorKind::DuplicateImplicitTokensDeclaration
284            | YaccGrammarErrorKind::DuplicateStartDeclaration
285            | YaccGrammarErrorKind::DuplicateActiontypeDeclaration
286            | YaccGrammarErrorKind::DuplicateEPP => SpansKind::DuplicationError,
287            YaccGrammarErrorKind::Header(_, spanskind) => spanskind,
288        }
289    }
290}
291
292pub(crate) struct YaccParser<'a> {
293    yacc_kind: YaccKind,
294    src: &'a str,
295    num_newlines: usize,
296    ast: GrammarAST,
297    header: Option<Header<Span>>,
298    global_actiontype: Option<(String, Span)>,
299}
300
301pub(crate) static RE_NAME: LazyLock<Regex> =
302    LazyLock::new(|| Regex::new(r"^[a-zA-Z_.][a-zA-Z0-9_.]*").unwrap());
303static RE_TOKEN: LazyLock<Regex> =
304    LazyLock::new(|| Regex::new("^(?:(\".+?\")|('.+?')|([a-zA-Z_][a-zA-Z_0-9]*))").unwrap());
305
306fn add_duplicate_occurrence(
307    errs: &mut Vec<YaccGrammarError>,
308    kind: YaccGrammarErrorKind,
309    orig_span: Span,
310    dup_span: Span,
311) {
312    if !errs.iter_mut().any(|e| {
313        if e.kind == kind && e.spans[0] == orig_span {
314            e.spans.push(dup_span);
315            true
316        } else {
317            false
318        }
319    }) {
320        errs.push(YaccGrammarError {
321            kind,
322            spans: vec![orig_span, dup_span],
323        });
324    }
325}
326
327/// The actual parser is intended to be entirely opaque from outside users.
328impl YaccParser<'_> {
329    pub(crate) fn new(yacc_kind: YaccKind, src: &str) -> YaccParser<'_> {
330        YaccParser {
331            yacc_kind,
332            src,
333            num_newlines: 0,
334            ast: GrammarAST::new(),
335            header: None,
336            global_actiontype: None,
337        }
338    }
339
340    pub(crate) fn parse(&mut self) -> YaccGrammarResult<usize> {
341        let mut errs = Vec::new();
342        let (header, pos) = GrmtoolsSectionParser::new(self.src, false)
343            .parse()
344            .map_err(|mut errs| errs.drain(..).map(|e| e.into()).collect::<Vec<_>>())?;
345        self.header = Some(header);
346        // We pass around an index into the *bytes* of self.src. We guarantee that at all times
347        // this points to the beginning of a UTF-8 character (since multibyte characters exist, not
348        // every byte within the string is also a valid character).
349        let mut result = self.parse_declarations(pos, &mut errs);
350        result = self.parse_rules(match result {
351            Ok(i) => i,
352            Err(e) => {
353                errs.push(e);
354                return Err(errs);
355            }
356        });
357        result = self.parse_programs(
358            match result {
359                Ok(i) => i,
360                Err(e) => {
361                    errs.push(e);
362                    return Err(errs);
363                }
364            },
365            &mut errs,
366        );
367        match result {
368            Ok(i) if errs.is_empty() => Ok(i),
369            Err(e) => {
370                errs.push(e);
371                Err(errs)
372            }
373            _ => Err(errs),
374        }
375    }
376
377    pub(crate) fn build(self) -> (GrammarAST, Header<Span>) {
378        let mut header = self.header.expect("set by parse()");
379        // At this point we still have mutable access to the header, so it is a convenient place
380        // to mark keys used. It would be less error prone if we did this at the point where keys
381        // are used. However at some points where we do lookups, there are shared references to the
382        // header making it difficult to get mutable access.
383        for (key_name, crate_name) in KEY_CRATE_MAP.iter() {
384            if ["cfgrammar", "lrpar"].contains(crate_name) {
385                header.mark_used(&format!("{crate_name}.{key_name}"));
386            }
387        }
388        (self.ast, header)
389    }
390
391    fn parse_declarations(
392        &mut self,
393        mut i: usize,
394        errs: &mut Vec<YaccGrammarError>,
395    ) -> Result<usize, YaccGrammarError> {
396        i = self.parse_ws(i, true)?;
397        let mut prec_level = 0;
398        while i < self.src.len() {
399            if self.lookahead_is("%%", i).is_some() {
400                return Ok(i);
401            }
402            if let Some(j) = self.lookahead_is("%token", i) {
403                i = self.parse_ws(j, false)?;
404                while i < self.src.len() && self.lookahead_is("%", i).is_none() {
405                    let (j, n, span, _) = self.parse_token(i)?;
406                    let (idx, new_tok) = self.ast.tokens.insert_full(n);
407                    if new_tok {
408                        self.ast.spans.push(span);
409                    }
410                    self.ast.token_directives.insert(idx);
411                    i = self.parse_ws(j, true)?;
412                }
413                continue;
414            }
415            if let YaccKind::Original(_) = self.yacc_kind
416                && let Some(j) = self.lookahead_is("%actiontype", i)
417            {
418                i = self.parse_ws(j, false)?;
419                let (j, n) = self.parse_to_eol(i)?;
420                let span = Span::new(i, j);
421                if let Some((_, orig_span)) = self.global_actiontype {
422                    add_duplicate_occurrence(
423                        errs,
424                        YaccGrammarErrorKind::DuplicateActiontypeDeclaration,
425                        orig_span,
426                        span,
427                    );
428                } else {
429                    self.global_actiontype = Some((n, span));
430                }
431                i = self.parse_ws(j, true)?;
432                continue;
433            }
434            if let Some(j) = self.lookahead_is("%start", i) {
435                i = self.parse_ws(j, false)?;
436                let (j, n) = self.parse_name(i)?;
437                let span = Span::new(i, j);
438                if let Some((_, orig_span)) = self.ast.start {
439                    add_duplicate_occurrence(
440                        errs,
441                        YaccGrammarErrorKind::DuplicateStartDeclaration,
442                        orig_span,
443                        span,
444                    );
445                } else {
446                    self.ast.start = Some((n, span));
447                }
448                i = self.parse_ws(j, true)?;
449                continue;
450            }
451            if let Some(j) = self.lookahead_is("%epp", i) {
452                i = self.parse_ws(j, false)?;
453                let (j, n, _, _) = self.parse_token(i)?;
454                let span = Span::new(i, j);
455                i = self.parse_ws(j, false)?;
456                let (j, v) = self.parse_string(i)?;
457                let vspan = Span::new(i, j);
458                match self.ast.epp.entry(n) {
459                    Entry::Occupied(orig) => {
460                        let (orig_span, _) = orig.get();
461                        add_duplicate_occurrence(
462                            errs,
463                            YaccGrammarErrorKind::DuplicateEPP,
464                            *orig_span,
465                            span,
466                        )
467                    }
468                    Entry::Vacant(epp) => {
469                        epp.insert((span, (v, vspan)));
470                    }
471                }
472                i = self.parse_ws(j, true)?;
473                continue;
474            }
475            if let Some(j) = self.lookahead_is("%expect-rr", i) {
476                i = self.parse_ws(j, false)?;
477                let (j, n) = self.parse_int(i)?;
478                let span = Span::new(i, j);
479                if let Some((_, orig_span)) = self.ast.expectrr {
480                    add_duplicate_occurrence(
481                        errs,
482                        YaccGrammarErrorKind::DuplicateExpectRRDeclaration,
483                        orig_span,
484                        span,
485                    );
486                } else {
487                    self.ast.expectrr = Some((n, span));
488                }
489                i = self.parse_ws(j, true)?;
490                continue;
491            }
492            if let Some(j) = self.lookahead_is("%expect-unused", i) {
493                i = self.parse_ws(j, false)?;
494                while i < self.src.len() && self.lookahead_is("%", i).is_none() {
495                    let j = match self.parse_name(i) {
496                        Ok((j, n)) => {
497                            self.ast
498                                .expect_unused
499                                .push(Symbol::Rule(n, Span::new(i, j)));
500                            j
501                        }
502                        Err(_) => match self.parse_token(i) {
503                            Ok((j, n, span, _)) => {
504                                self.ast.expect_unused.push(Symbol::Token(n, span));
505                                j
506                            }
507                            Err(_) => {
508                                return Err(self.mk_error(YaccGrammarErrorKind::UnknownSymbol, i));
509                            }
510                        },
511                    };
512                    i = self.parse_ws(j, true)?;
513                }
514                continue;
515            }
516            if let Some(j) = self.lookahead_is("%expect", i) {
517                i = self.parse_ws(j, false)?;
518                let (j, n) = self.parse_int(i)?;
519                let span = Span::new(i, j);
520                if let Some((_, orig_span)) = self.ast.expect {
521                    add_duplicate_occurrence(
522                        errs,
523                        YaccGrammarErrorKind::DuplicateExpectDeclaration,
524                        orig_span,
525                        span,
526                    );
527                } else {
528                    self.ast.expect = Some((n, span));
529                }
530                i = self.parse_ws(j, true)?;
531                continue;
532            }
533            if let Some(j) = self.lookahead_is("%avoid_insert", i) {
534                i = self.parse_ws(j, false)?;
535                let num_newlines = self.num_newlines;
536                if self.ast.avoid_insert.is_none() {
537                    self.ast.avoid_insert = Some(HashMap::new());
538                }
539                while j < self.src.len() && self.num_newlines == num_newlines {
540                    let (j, n, span, _) = self.parse_token(i)?;
541                    if self.ast.tokens.insert(n.clone()) {
542                        self.ast.spans.push(span);
543                    }
544
545                    match self.ast.avoid_insert.as_mut().unwrap().entry(n) {
546                        Entry::Occupied(occupied) => {
547                            add_duplicate_occurrence(
548                                errs,
549                                YaccGrammarErrorKind::DuplicateAvoidInsertDeclaration,
550                                *occupied.get(),
551                                span,
552                            );
553                        }
554                        Entry::Vacant(vacant) => {
555                            vacant.insert(span);
556                        }
557                    }
558                    i = self.parse_ws(j, true)?;
559                }
560                continue;
561            }
562            if let Some(j) = self.lookahead_is("%parse-param", i) {
563                i = self.parse_ws(j, false)?;
564                let (j, name) = self.parse_to_single_colon(i)?;
565                match self.lookahead_is(":", j) {
566                    Some(j) => i = self.parse_ws(j, false)?,
567                    None => {
568                        return Err(self.mk_error(YaccGrammarErrorKind::MissingColon, j));
569                    }
570                }
571                let (j, ty) = self.parse_to_eol(i)?;
572                self.ast.parse_param = Some((name, ty));
573                i = self.parse_ws(j, true)?;
574                continue;
575            }
576            if let Some(j) = self.lookahead_is("%parse-generics", i) {
577                i = self.parse_ws(j, false)?;
578                let (j, ty) = self.parse_to_eol(i)?;
579                self.ast.parse_generics = Some(ty);
580                i = self.parse_ws(j, true)?;
581                continue;
582            }
583            if let YaccKind::Eco = self.yacc_kind
584                && let Some(j) = self.lookahead_is("%implicit_tokens", i)
585            {
586                i = self.parse_ws(j, false)?;
587                let num_newlines = self.num_newlines;
588                if self.ast.implicit_tokens.is_none() {
589                    self.ast.implicit_tokens = Some(HashMap::new());
590                }
591                while j < self.src.len() && self.num_newlines == num_newlines {
592                    let (j, n, span, _) = self.parse_token(i)?;
593                    if self.ast.tokens.insert(n.clone()) {
594                        self.ast.spans.push(span);
595                    }
596                    match self.ast.implicit_tokens.as_mut().unwrap().entry(n) {
597                        Entry::Occupied(entry) => {
598                            let orig_span = *entry.get();
599                            add_duplicate_occurrence(
600                                errs,
601                                YaccGrammarErrorKind::DuplicateImplicitTokensDeclaration,
602                                orig_span,
603                                span,
604                            );
605                        }
606                        Entry::Vacant(entry) => {
607                            entry.insert(span);
608                        }
609                    }
610                    i = self.parse_ws(j, true)?;
611                }
612                continue;
613            }
614            {
615                let k;
616                let kind;
617                if let Some(j) = self.lookahead_is("%left", i) {
618                    kind = AssocKind::Left;
619                    k = j;
620                } else if let Some(j) = self.lookahead_is("%right", i) {
621                    kind = AssocKind::Right;
622                    k = j;
623                } else if let Some(j) = self.lookahead_is("%nonassoc", i) {
624                    kind = AssocKind::Nonassoc;
625                    k = j;
626                } else {
627                    return Err(self.mk_error(YaccGrammarErrorKind::UnknownDeclaration, i));
628                }
629
630                i = self.parse_ws(k, false)?;
631                let num_newlines = self.num_newlines;
632                while i < self.src.len() && num_newlines == self.num_newlines {
633                    let (j, n, span, _) = self.parse_token(i)?;
634                    match self.ast.precs.entry(n) {
635                        Entry::Occupied(orig) => {
636                            let (_, orig_span) = orig.get();
637                            add_duplicate_occurrence(
638                                errs,
639                                YaccGrammarErrorKind::DuplicatePrecedence,
640                                *orig_span,
641                                span,
642                            );
643                        }
644                        Entry::Vacant(entry) => {
645                            let prec = Precedence {
646                                level: prec_level,
647                                kind,
648                            };
649                            entry.insert((prec, span));
650                        }
651                    }
652
653                    i = self.parse_ws(j, true)?;
654                }
655                prec_level += 1;
656            }
657        }
658        debug_assert!(i == self.src.len());
659        Err(self.mk_error(YaccGrammarErrorKind::PrematureEnd, i))
660    }
661
662    fn parse_rules(&mut self, mut i: usize) -> Result<usize, YaccGrammarError> {
663        // self.parse_declarations should have left the input at '%%'
664        i = self.lookahead_is("%%", i).unwrap();
665        i = self.parse_ws(i, true)?;
666        while i < self.src.len() && self.lookahead_is("%%", i).is_none() {
667            i = self.parse_rule(i)?;
668            i = self.parse_ws(i, true)?;
669        }
670        Ok(i)
671    }
672
673    fn parse_rule(&mut self, mut i: usize) -> Result<usize, YaccGrammarError> {
674        let (j, rn) = self.parse_name(i)?;
675        let span = Span::new(i, j);
676        if self.ast.start.is_none() {
677            self.ast.start = Some((rn.clone(), span));
678        }
679        match self.yacc_kind {
680            YaccKind::Original(_) | YaccKind::Eco => {
681                if self.ast.get_rule(&rn).is_none() {
682                    self.ast.add_rule(
683                        (rn.clone(), span),
684                        self.global_actiontype.clone().map(|(s, _)| s),
685                    );
686                }
687                i = j;
688            }
689            YaccKind::Grmtools => {
690                i = self.parse_ws(j, true)?;
691                if let Some(j) = self.lookahead_is("->", i) {
692                    i = j;
693                } else {
694                    return Err(self.mk_error(YaccGrammarErrorKind::MissingRightArrow, i));
695                }
696                i = self.parse_ws(i, true)?;
697                let (j, actiont) = self.parse_to_single_colon(i)?;
698                if self.ast.get_rule(&rn).is_none() {
699                    self.ast.add_rule((rn.clone(), span), Some(actiont));
700                }
701                i = j;
702            }
703        }
704        i = self.parse_ws(i, true)?;
705        match self.lookahead_is(":", i) {
706            Some(j) => i = j,
707            None => {
708                return Err(self.mk_error(YaccGrammarErrorKind::MissingColon, i));
709            }
710        }
711        let mut syms = Vec::new();
712        let mut prec = None;
713        let mut action = None;
714        i = self.parse_ws(i, true)?;
715        let mut pos_prod_start = i;
716        let mut pos_prod_end = None;
717        while i < self.src.len() {
718            if let Some(j) = self.lookahead_is("|", i) {
719                self.ast.add_prod(
720                    rn.clone(),
721                    syms,
722                    prec,
723                    action,
724                    Span::new(pos_prod_start, pos_prod_end.take().unwrap_or(i)),
725                );
726                syms = Vec::new();
727                prec = None;
728                action = None;
729                i = self.parse_ws(j, true)?;
730                pos_prod_start = i;
731                continue;
732            } else if let Some(j) = self.lookahead_is(";", i) {
733                self.ast.add_prod(
734                    rn,
735                    syms,
736                    prec,
737                    action,
738                    Span::new(pos_prod_start, pos_prod_end.take().unwrap_or(i)),
739                );
740                return Ok(j);
741            }
742
743            if self.lookahead_is("\"", i).is_some() || self.lookahead_is("'", i).is_some() {
744                let (j, sym, span, _) = self.parse_token(i)?;
745                pos_prod_end = Some(j);
746                i = self.parse_ws(j, true)?;
747                if self.ast.tokens.insert(sym.clone()) {
748                    self.ast.spans.push(span);
749                }
750                syms.push(Symbol::Token(sym, span));
751            } else if let Some(j) = self.lookahead_is("%prec", i) {
752                i = self.parse_ws(j, true)?;
753                let (k, sym, span, _) = self.parse_token(i)?;
754                if self.ast.tokens.insert(sym.clone()) {
755                    self.ast.spans.push(span);
756                }
757                prec = Some(sym);
758                pos_prod_end = Some(k);
759                i = k;
760            } else if self.lookahead_is("{", i).is_some() {
761                let pos_action_start = i + 1;
762                pos_prod_end = Some(i);
763                // With j the location of the right brace, i the location of the left brace.
764                let (j, a) = self.parse_action(i)?;
765                i = self.parse_ws(j, true)?;
766                let action_span = Span::new(pos_action_start, pos_action_start + a.len());
767                action = Some((a, action_span));
768
769                if !(self.lookahead_is("|", i).is_some() || self.lookahead_is(";", i).is_some()) {
770                    return Err(self.mk_error(YaccGrammarErrorKind::ProductionNotTerminated, i));
771                }
772            } else if let Some(j) = self.lookahead_is("%empty", i) {
773                let k = self.parse_ws(j, true)?;
774                // %empty could be followed by all sorts of weird syntax errors: all we try and do
775                // is say "does this production look like it's finished" and trust that the other
776                // errors will be caught by other parts of the parser.
777                if !syms.is_empty()
778                    | !(self.lookahead_is("|", k).is_some()
779                        || self.lookahead_is(";", k).is_some()
780                        || self.lookahead_is("{", k).is_some()
781                        || self.lookahead_is("%prec", k).is_some())
782                {
783                    return Err(self.mk_error(YaccGrammarErrorKind::NonEmptyProduction, i));
784                }
785                pos_prod_end = Some(j);
786                i = k;
787            } else {
788                let (j, sym, span, quoted) = self.parse_token(i)?;
789                pos_prod_end = Some(j);
790                if self
791                    .ast
792                    .tokens
793                    .get_index_of(&sym)
794                    .is_some_and(|idx| quoted || self.ast.token_directives.contains(&idx))
795                {
796                    syms.push(Symbol::Token(sym, span));
797                } else {
798                    syms.push(Symbol::Rule(sym, span));
799                }
800                i = j;
801            }
802            i = self.parse_ws(i, true)?;
803        }
804        Err(self.mk_error(YaccGrammarErrorKind::IncompleteRule, i))
805    }
806
807    fn parse_name(&self, i: usize) -> Result<(usize, String), YaccGrammarError> {
808        match RE_NAME.find(&self.src[i..]) {
809            Some(m) => {
810                assert_eq!(m.start(), 0);
811                Ok((i + m.end(), self.src[i..i + m.end()].to_string()))
812            }
813            None => Err(self.mk_error(YaccGrammarErrorKind::IllegalName, i)),
814        }
815    }
816
817    fn parse_token(&self, i: usize) -> Result<(usize, String, Span, bool), YaccGrammarError> {
818        match RE_TOKEN.find(&self.src[i..]) {
819            Some(m) => {
820                assert!(m.start() == 0 && m.end() > 0);
821                match self.src[i..].chars().next().unwrap() {
822                    '"' | '\'' => {
823                        debug_assert!('"'.len_utf8() == 1 && '\''.len_utf8() == 1);
824                        let start_cidx = i + 1;
825                        let end_cidx = i + m.end() - 1;
826                        Ok((
827                            i + m.end(),
828                            self.src[start_cidx..end_cidx].to_string(),
829                            Span::new(start_cidx, end_cidx),
830                            true,
831                        ))
832                    }
833                    _ => Ok((
834                        i + m.end(),
835                        self.src[i..i + m.end()].to_string(),
836                        Span::new(i, i + m.end()),
837                        false,
838                    )),
839                }
840            }
841            None => Err(self.mk_error(YaccGrammarErrorKind::IllegalString, i)),
842        }
843    }
844
845    fn parse_action(&mut self, i: usize) -> Result<(usize, String), YaccGrammarError> {
846        debug_assert!(self.lookahead_is("{", i).is_some());
847        let mut j = i;
848        let mut c = 0; // Count braces
849        while j < self.src.len() {
850            let ch = self.src[j..].chars().next().unwrap();
851            match ch {
852                '{' => c += 1,
853                '}' if c == 1 => {
854                    c = 0;
855                    break;
856                }
857                '}' => c -= 1,
858                '\n' | '\r' => {
859                    self.num_newlines += 1;
860                }
861                _ => (),
862            };
863            j += ch.len_utf8();
864        }
865        if c > 0 {
866            Err(self.mk_error(YaccGrammarErrorKind::IncompleteAction, i))
867        } else {
868            debug_assert!(self.lookahead_is("}", j).is_some());
869            let s = self.src[i + '{'.len_utf8()..j].to_string();
870            Ok((j + '}'.len_utf8(), s))
871        }
872    }
873
874    fn parse_programs(
875        &mut self,
876        mut i: usize,
877        _: &mut Vec<YaccGrammarError>,
878    ) -> Result<usize, YaccGrammarError> {
879        if let Some(j) = self.lookahead_is("%%", i) {
880            i = self.parse_ws(j, true)?;
881            let prog = self.src[i..].to_string();
882            i += prog.len();
883            self.ast.set_programs(prog);
884        }
885        Ok(i)
886    }
887
888    /// Parse up to (but do not include) the end of line (or, if it comes sooner, the end of file).
889    fn parse_to_eol(&mut self, i: usize) -> Result<(usize, String), YaccGrammarError> {
890        let mut j = i;
891        while j < self.src.len() {
892            let c = self.src[j..].chars().next().unwrap();
893            match c {
894                '\n' | '\r' => break,
895                _ => j += c.len_utf8(),
896            }
897        }
898        Ok((j, self.src[i..j].to_string()))
899    }
900
901    /// Parse up to (but do not include) a single colon (double colons are allowed so that strings
902    /// like `a::b::c:` treat `a::b::c` as a single name. Errors if EOL encountered.
903    fn parse_to_single_colon(&mut self, i: usize) -> Result<(usize, String), YaccGrammarError> {
904        let mut j = i;
905        while j < self.src.len() {
906            let c = self.src[j..].chars().next().unwrap();
907            match c {
908                ':' => {
909                    let k = j + ':'.len_utf8();
910                    if k == self.src.len() || !self.src[k..].starts_with(':') {
911                        return Ok((j, self.src[i..j].trim().to_string()));
912                    }
913                    j += 2 * ':'.len_utf8();
914                }
915                '\n' | '\r' => {
916                    self.num_newlines += 1;
917                    j += c.len_utf8();
918                }
919                _ => j += c.len_utf8(),
920            }
921        }
922        Err(self.mk_error(YaccGrammarErrorKind::ReachedEOL, j))
923    }
924
925    /// Parse a quoted string, allowing escape characters.
926    fn parse_int<T: FromStr + PrimInt>(
927        &mut self,
928        i: usize,
929    ) -> Result<(usize, T), YaccGrammarError> {
930        let mut j = i;
931        while j < self.src.len() {
932            let c = self.src[j..].chars().next().unwrap();
933            match c {
934                '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => j += 1,
935                _ => break,
936            }
937        }
938        match self.src[i..j].parse::<T>() {
939            Ok(x) => Ok((j, x)),
940            Err(_) => Err(self.mk_error(YaccGrammarErrorKind::IllegalInteger, i)),
941        }
942    }
943
944    /// Parse a quoted string, allowing escape characters.
945    fn parse_string(&mut self, mut i: usize) -> Result<(usize, String), YaccGrammarError> {
946        let qc = if self.lookahead_is("'", i).is_some() {
947            '\''
948        } else if self.lookahead_is("\"", i).is_some() {
949            '"'
950        } else {
951            return Err(self.mk_error(YaccGrammarErrorKind::InvalidString, i));
952        };
953
954        debug_assert!('"'.len_utf8() == 1 && '\''.len_utf8() == 1);
955        // Because we can encounter escape characters, we can't simply match text and slurp it into
956        // a String in one go (otherwise we'd include the escape characters). Conceptually we have
957        // to build the String up byte by byte, skipping escape characters, but that's slow.
958        // Instead we append chunks of the string up to (but excluding) escape characters.
959        let mut s = String::new();
960        i += 1;
961        let mut j = i;
962        while j < self.src.len() {
963            let c = self.src[j..].chars().next().unwrap();
964            match c {
965                '\n' | '\r' => {
966                    return Err(self.mk_error(YaccGrammarErrorKind::InvalidString, j));
967                }
968                x if x == qc => {
969                    s.push_str(&self.src[i..j]);
970                    return Ok((j + 1, s));
971                }
972                '\\' => {
973                    debug_assert!('\\'.len_utf8() == 1);
974                    match self.src[j + 1..].chars().next() {
975                        Some(c) if c == '\'' || c == '"' => {
976                            s.push_str(&self.src[i..j]);
977                            i = j + 1;
978                            j += 2;
979                        }
980                        _ => {
981                            return Err(self.mk_error(YaccGrammarErrorKind::InvalidString, j));
982                        }
983                    }
984                }
985                _ => j += c.len_utf8(),
986            }
987        }
988        Err(self.mk_error(YaccGrammarErrorKind::InvalidString, j))
989    }
990
991    /// Skip whitespace from `i` onwards. If `inc_newlines` is `false`, will return `Err` if a
992    /// newline is encountered; otherwise newlines are consumed and skipped.
993    fn parse_ws(&mut self, mut i: usize, inc_newlines: bool) -> Result<usize, YaccGrammarError> {
994        while i < self.src.len() {
995            let c = self.src[i..].chars().next().unwrap();
996            match c {
997                ' ' | '\t' => i += c.len_utf8(),
998                '\n' | '\r' => {
999                    if !inc_newlines {
1000                        return Err(self.mk_error(YaccGrammarErrorKind::ReachedEOL, i));
1001                    }
1002                    self.num_newlines += 1;
1003                    i += c.len_utf8();
1004                }
1005                '/' => {
1006                    if i + c.len_utf8() == self.src.len() {
1007                        break;
1008                    } else {
1009                        let j = i + c.len_utf8();
1010                        let c = self.src[j..].chars().next().unwrap();
1011                        match c {
1012                            '/' => {
1013                                i = j + c.len_utf8();
1014                                for c in self.src[i..].chars() {
1015                                    i += c.len_utf8();
1016                                    if c == '\n' || c == '\r' {
1017                                        self.num_newlines += 1;
1018                                        break;
1019                                    }
1020                                }
1021                            }
1022                            '*' => {
1023                                // This is complicated by the fact that we need to deal with
1024                                // unclosed comments (i.e. '/*' without a corresponding '*/').
1025                                let mut k = j + c.len_utf8();
1026                                let mut found = false;
1027                                while k < self.src.len() {
1028                                    let c = self.src[k..].chars().next().unwrap();
1029                                    k += c.len_utf8();
1030                                    match c {
1031                                        '\n' | '\r' => {
1032                                            if !inc_newlines {
1033                                                return Err(self.mk_error(
1034                                                    YaccGrammarErrorKind::ReachedEOL,
1035                                                    i,
1036                                                ));
1037                                            }
1038                                            self.num_newlines += 1;
1039                                        }
1040                                        '*' => (),
1041                                        _ => continue,
1042                                    }
1043                                    if k < self.src.len() {
1044                                        let c = self.src[k..].chars().next().unwrap();
1045                                        if c == '/' {
1046                                            i = k + c.len_utf8();
1047                                            found = true;
1048                                            break;
1049                                        }
1050                                    }
1051                                }
1052                                if !found {
1053                                    return Err(
1054                                        self.mk_error(YaccGrammarErrorKind::IncompleteComment, i)
1055                                    );
1056                                }
1057                            }
1058                            _ => break,
1059                        }
1060                    }
1061                }
1062                _ => break,
1063            }
1064        }
1065        Ok(i)
1066    }
1067
1068    fn lookahead_is(&self, s: &'static str, i: usize) -> Option<usize> {
1069        if self.src[i..].starts_with(s) {
1070            Some(i + s.len())
1071        } else {
1072            None
1073        }
1074    }
1075
1076    fn mk_error(&self, k: YaccGrammarErrorKind, off: usize) -> YaccGrammarError {
1077        let span = Span::new(off, off);
1078        YaccGrammarError {
1079            kind: k,
1080            spans: vec![span],
1081        }
1082    }
1083}
1084
1085#[cfg(test)]
1086mod test {
1087    use super::{
1088        super::{
1089            AssocKind, Precedence, YaccKind, YaccOriginalActionKind,
1090            ast::{GrammarAST, Production, Symbol},
1091        },
1092        Span, Spanned, YaccGrammarError, YaccGrammarErrorKind, YaccParser,
1093    };
1094    use std::collections::HashSet;
1095
1096    fn parse(yacc_kind: YaccKind, s: &str) -> Result<GrammarAST, Vec<YaccGrammarError>> {
1097        let mut yp = YaccParser::new(yacc_kind, s);
1098        yp.parse()?;
1099        let (ast, _) = yp.build();
1100        Ok(ast)
1101    }
1102
1103    fn rule(n: &str) -> Symbol {
1104        Symbol::Rule(n.to_string(), Span::new(0, 0))
1105    }
1106
1107    fn rule_span(n: &str, span: Span) -> Symbol {
1108        Symbol::Rule(n.to_string(), span)
1109    }
1110
1111    fn token(n: &str) -> Symbol {
1112        Symbol::Token(n.to_string(), Span::new(0, 0))
1113    }
1114    fn token_span(n: &str, span: Span) -> Symbol {
1115        Symbol::Token(n.to_string(), span)
1116    }
1117
1118    fn line_of_offset(s: &str, off: usize) -> usize {
1119        s[..off].lines().count()
1120    }
1121
1122    macro_rules! line_col {
1123        ($src:ident, $span: expr) => {{
1124            let mut line_cache = crate::newlinecache::NewlineCache::new();
1125            line_cache.feed(&$src);
1126            line_cache
1127                .byte_to_line_num_and_col_num(&$src, $span.start())
1128                .unwrap()
1129        }};
1130    }
1131
1132    trait ErrorsHelper {
1133        fn expect_error_at_line(self, src: &str, kind: YaccGrammarErrorKind, line: usize);
1134        fn expect_error_at_line_col(
1135            self,
1136            src: &str,
1137            kind: YaccGrammarErrorKind,
1138            line: usize,
1139            col: usize,
1140        );
1141        fn expect_error_at_lines_cols(
1142            self,
1143            src: &str,
1144            kind: YaccGrammarErrorKind,
1145            lines_cols: &mut dyn Iterator<Item = (usize, usize)>,
1146        );
1147        fn expect_multiple_errors(
1148            self,
1149            src: &str,
1150            expected: &mut dyn Iterator<Item = (YaccGrammarErrorKind, Vec<(usize, usize)>)>,
1151        );
1152    }
1153
1154    impl ErrorsHelper for Result<GrammarAST, Vec<YaccGrammarError>> {
1155        #[track_caller]
1156        fn expect_error_at_line(self, src: &str, kind: YaccGrammarErrorKind, line: usize) {
1157            let errs = self
1158                .as_ref()
1159                .map_err(Vec::as_slice)
1160                .expect_err("Parsed ok while expecting error");
1161            assert_eq!(errs.len(), 1);
1162            let e = &errs[0];
1163            assert_eq!(e.kind, kind);
1164            assert_eq!(line_of_offset(src, e.spans()[0].start()), line);
1165            assert_eq!(e.spans.len(), 1);
1166        }
1167
1168        #[track_caller]
1169        fn expect_error_at_line_col(
1170            self,
1171            src: &str,
1172            kind: YaccGrammarErrorKind,
1173            line: usize,
1174            col: usize,
1175        ) {
1176            self.expect_error_at_lines_cols(src, kind, &mut std::iter::once((line, col)))
1177        }
1178
1179        #[track_caller]
1180        fn expect_error_at_lines_cols(
1181            self,
1182            src: &str,
1183            kind: YaccGrammarErrorKind,
1184            lines_cols: &mut dyn Iterator<Item = (usize, usize)>,
1185        ) {
1186            let errs = self
1187                .as_ref()
1188                .map_err(Vec::as_slice)
1189                .expect_err("Parsed ok while expecting error");
1190            assert_eq!(errs.len(), 1);
1191            let e = &errs[0];
1192            assert_eq!(e.kind, kind);
1193            assert_eq!(
1194                e.spans()
1195                    .iter()
1196                    .map(|span| line_col!(src, span))
1197                    .collect::<Vec<(usize, usize)>>(),
1198                lines_cols.collect::<Vec<(usize, usize)>>()
1199            );
1200            // Check that it is valid to slice.
1201            for span in e.spans() {
1202                let _ = &src[span.start()..span.end()];
1203            }
1204        }
1205
1206        #[track_caller]
1207        fn expect_multiple_errors(
1208            self,
1209            src: &str,
1210            expected: &mut dyn Iterator<Item = (YaccGrammarErrorKind, Vec<(usize, usize)>)>,
1211        ) {
1212            let errs = self.expect_err("Parsed ok while expecting error");
1213            for e in &errs {
1214                // Check that it is valid to slice the source with the spans.
1215                for span in e.spans() {
1216                    let _ = &src[span.start()..span.end()];
1217                }
1218            }
1219
1220            assert_eq!(
1221                errs.iter()
1222                    .map(|e| {
1223                        (
1224                            e.kind.clone(),
1225                            e.spans()
1226                                .iter()
1227                                .map(|span| line_col!(src, span))
1228                                .collect::<Vec<_>>(),
1229                        )
1230                    })
1231                    .collect::<Vec<_>>(),
1232                expected.collect::<Vec<_>>()
1233            );
1234        }
1235    }
1236
1237    #[test]
1238    fn test_helper_fn() {
1239        assert_eq!(Symbol::Token("A".to_string(), Span::new(0, 0)), token("A"));
1240    }
1241
1242    #[test]
1243    fn test_symbol_eq() {
1244        assert_eq!(rule("A"), rule("A"));
1245        assert_ne!(rule("A"), rule("B"));
1246        assert_ne!(rule("A"), token("A"));
1247    }
1248
1249    #[test]
1250    fn test_rule() {
1251        let src = "
1252            %%
1253            A : 'a';
1254        "
1255        .to_string();
1256        let grm = parse(
1257            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1258            &src,
1259        )
1260        .unwrap();
1261        assert_eq!(grm.get_rule("A").unwrap().pidxs, vec![0]);
1262        let a_span = Span::new(33, 34);
1263        assert_eq!(
1264            grm.prods[grm.get_rule("A").unwrap().pidxs[0]],
1265            Production {
1266                symbols: vec![token_span("a", a_span)],
1267                precedence: None,
1268                action: None,
1269                prod_span: Span::new(32, 35),
1270            }
1271        );
1272        assert_eq!(&src[a_span.start()..a_span.end()], "a");
1273    }
1274
1275    #[test]
1276    fn test_rule_production_simple() {
1277        let src = "
1278            %%
1279            A : 'a';
1280            A : 'b';
1281        "
1282        .to_string();
1283        let grm = parse(
1284            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1285            &src,
1286        )
1287        .unwrap();
1288        let a_span = Span::new(33, 34);
1289        assert_eq!(
1290            grm.prods[grm.get_rule("A").unwrap().pidxs[0]],
1291            Production {
1292                symbols: vec![token_span("a", a_span)],
1293                precedence: None,
1294                action: None,
1295                prod_span: Span::new(32, 35),
1296            }
1297        );
1298        assert_eq!(&src[a_span.start()..a_span.end()], "a");
1299        let b_span = Span::new(54, 55);
1300        assert_eq!(
1301            grm.prods[grm.get_rule("A").unwrap().pidxs[1]],
1302            Production {
1303                symbols: vec![token_span("b", Span::new(54, 55))],
1304                precedence: None,
1305                action: None,
1306                prod_span: Span::new(53, 56),
1307            }
1308        );
1309        assert_eq!(&src[b_span.start()..b_span.end()], "b");
1310    }
1311
1312    #[test]
1313    fn test_rule_empty() {
1314        let src = "
1315            %%
1316            A : ;
1317            B : 'b' | ;
1318            C : | 'c';
1319        "
1320        .to_string();
1321        let grm = parse(
1322            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1323            &src,
1324        )
1325        .unwrap();
1326
1327        assert_eq!(
1328            grm.prods[grm.get_rule("A").unwrap().pidxs[0]],
1329            Production {
1330                symbols: vec![],
1331                precedence: None,
1332                action: None,
1333                prod_span: Span::new(32, 32),
1334            }
1335        );
1336
1337        let b_span = Span::new(51, 52);
1338        assert_eq!(
1339            grm.prods[grm.get_rule("B").unwrap().pidxs[0]],
1340            Production {
1341                symbols: vec![token_span("b", b_span)],
1342                precedence: None,
1343                action: None,
1344                prod_span: Span::new(50, 53),
1345            }
1346        );
1347        assert_eq!(&src[b_span.start()..b_span.end()], "b");
1348        assert_eq!(
1349            grm.prods[grm.get_rule("B").unwrap().pidxs[1]],
1350            Production {
1351                symbols: vec![],
1352                precedence: None,
1353                action: None,
1354                prod_span: Span::new(56, 56),
1355            }
1356        );
1357
1358        assert_eq!(
1359            grm.prods[grm.get_rule("C").unwrap().pidxs[0]],
1360            Production {
1361                symbols: vec![],
1362                precedence: None,
1363                action: None,
1364                prod_span: Span::new(74, 74),
1365            }
1366        );
1367        let c_span = Span::new(77, 78);
1368        assert_eq!(
1369            grm.prods[grm.get_rule("C").unwrap().pidxs[1]],
1370            Production {
1371                symbols: vec![token_span("c", c_span)],
1372                precedence: None,
1373                action: None,
1374                prod_span: Span::new(76, 79),
1375            }
1376        );
1377        assert_eq!(&src[c_span.start()..c_span.end()], "c");
1378    }
1379
1380    #[test]
1381    fn test_empty_program() {
1382        let src = "%%\nA : 'a';\n%%".to_string();
1383        parse(
1384            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1385            &src,
1386        )
1387        .unwrap();
1388    }
1389
1390    #[test]
1391    fn test_multiple_symbols() {
1392        let src = "%%\nA : 'a' B;".to_string();
1393        let grm = parse(
1394            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1395            &src,
1396        )
1397        .unwrap();
1398        let a_span = Span::new(8, 9);
1399        let b_span = Span::new(11, 12);
1400        assert_eq!(
1401            grm.prods[grm.get_rule("A").unwrap().pidxs[0]],
1402            Production {
1403                symbols: vec![token_span("a", a_span), rule_span("B", b_span)],
1404                precedence: None,
1405                action: None,
1406                prod_span: Span::new(7, 12),
1407            }
1408        );
1409        assert_eq!(&src[a_span.start()..a_span.end()], "a");
1410        assert_eq!(&src[b_span.start()..b_span.end()], "B");
1411    }
1412
1413    #[test]
1414    fn test_token_types() {
1415        let src = "%%\nA : 'a' \"b\";".to_string();
1416        let grm = parse(
1417            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1418            &src,
1419        )
1420        .unwrap();
1421        let a_span = Span::new(8, 9);
1422        let b_span = Span::new(12, 13);
1423        assert_eq!(
1424            grm.prods[grm.get_rule("A").unwrap().pidxs[0]],
1425            Production {
1426                symbols: vec![token_span("a", a_span), token_span("b", b_span)],
1427                precedence: None,
1428                action: None,
1429                prod_span: Span::new(7, 14),
1430            }
1431        );
1432        assert_eq!(&src[a_span.start()..a_span.end()], "a");
1433        assert_eq!(&src[b_span.start()..b_span.end()], "b");
1434    }
1435
1436    #[test]
1437    fn test_declaration_start() {
1438        let src = "%start   A\n%%\nA : a;".to_string();
1439        let grm = parse(
1440            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1441            &src,
1442        )
1443        .unwrap();
1444        assert_eq!(grm.start.unwrap(), ("A".to_string(), Span::new(9, 10)));
1445    }
1446
1447    #[test]
1448    fn test_declaration_token() {
1449        let src = "%token   a\n%%\nA : a;".to_string();
1450        let grm = parse(
1451            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1452            &src,
1453        )
1454        .unwrap();
1455        assert!(grm.has_token("a"));
1456    }
1457
1458    #[test]
1459    fn test_declaration_token_literal() {
1460        let src = "%token   'a'\n%%\nA : 'a';".to_string();
1461        let grm = parse(
1462            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1463            &src,
1464        )
1465        .unwrap();
1466        assert!(grm.has_token("a"));
1467    }
1468
1469    #[test]
1470    fn test_declaration_tokens() {
1471        let src = "%token   a b c 'd'\n%%\nA : a;".to_string();
1472        let grm = parse(
1473            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1474            &src,
1475        )
1476        .unwrap();
1477        assert!(grm.has_token("a"));
1478        assert!(grm.has_token("b"));
1479        assert!(grm.has_token("c"));
1480    }
1481
1482    #[test]
1483    fn test_auto_add_tokens() {
1484        let src = "%%\nA : 'a';".to_string();
1485        let grm = parse(
1486            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1487            &src,
1488        )
1489        .unwrap();
1490        assert!(grm.has_token("a"));
1491    }
1492
1493    #[test]
1494    fn test_token_non_literal() {
1495        let src = "%token T %%\nA : T;".to_string();
1496        let grm = parse(
1497            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1498            &src,
1499        )
1500        .unwrap();
1501        assert!(grm.has_token("T"));
1502        let t_span = Span::new(16, 17);
1503        assert_eq!(
1504            grm.prods[grm.get_rule("A").unwrap().pidxs[0]],
1505            Production {
1506                symbols: vec![token_span("T", t_span)],
1507                precedence: None,
1508                action: None,
1509                prod_span: t_span,
1510            }
1511        );
1512        assert_eq!(&src[t_span.start()..t_span.end() + 1], "T;");
1513    }
1514
1515    #[test]
1516    fn test_token_unicode() {
1517        let src = "%token '❤' %%\nA : '❤';".to_string();
1518        let grm = parse(
1519            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1520            &src,
1521        )
1522        .unwrap();
1523        assert!(grm.has_token("❤"));
1524    }
1525
1526    #[test]
1527    fn test_unicode_err1() {
1528        let src = "%token '❤' ❤;".to_string();
1529        parse(
1530            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1531            &src,
1532        )
1533        .expect_error_at_line_col(&src, YaccGrammarErrorKind::IllegalString, 1, 12);
1534    }
1535
1536    #[test]
1537    fn test_unicode_err2() {
1538        let src = "%token '❤'\n%%\nA : '❤' | ❤;".to_string();
1539        parse(
1540            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1541            &src,
1542        )
1543        .expect_error_at_line_col(&src, YaccGrammarErrorKind::IllegalString, 3, 11);
1544    }
1545
1546    #[test]
1547    fn test_missing_end_quote() {
1548        let src = "%epp X \"f\\".to_string();
1549        parse(
1550            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1551            &src,
1552        )
1553        .expect_error_at_line_col(&src, YaccGrammarErrorKind::InvalidString, 1, 10);
1554    }
1555
1556    #[test]
1557    fn test_simple_decl_fail() {
1558        let src = "%fail x\n%%\nA : a".to_string();
1559        parse(
1560            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1561            &src,
1562        )
1563        .expect_error_at_line_col(&src, YaccGrammarErrorKind::UnknownDeclaration, 1, 1);
1564    }
1565
1566    #[test]
1567    fn test_empty() {
1568        let src = "".to_string();
1569        parse(
1570            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1571            &src,
1572        )
1573        .expect_error_at_line_col("", YaccGrammarErrorKind::PrematureEnd, 1, 1);
1574    }
1575
1576    #[test]
1577    fn test_incomplete_rule1() {
1578        let src = "%%A:".to_string();
1579        parse(
1580            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1581            &src,
1582        )
1583        .expect_error_at_line_col(&src, YaccGrammarErrorKind::IncompleteRule, 1, 5);
1584    }
1585
1586    #[test]
1587    fn test_line_col_report1() {
1588        let src = "%%
1589A:"
1590        .to_string();
1591        parse(
1592            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1593            &src,
1594        )
1595        .expect_error_at_line_col(&src, YaccGrammarErrorKind::IncompleteRule, 2, 3);
1596    }
1597
1598    #[test]
1599    fn test_line_col_report2() {
1600        let src = "%%
1601A:
1602"
1603        .to_string();
1604        parse(
1605            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1606            &src,
1607        )
1608        .expect_error_at_line_col(&src, YaccGrammarErrorKind::IncompleteRule, 3, 1);
1609    }
1610
1611    #[test]
1612    fn test_line_col_report3() {
1613        let src = "
1614
1615        %woo"
1616            .to_string();
1617        parse(
1618            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1619            &src,
1620        )
1621        .expect_error_at_line_col(&src, YaccGrammarErrorKind::UnknownDeclaration, 3, 9);
1622    }
1623
1624    #[test]
1625    fn test_missing_colon() {
1626        let src = "%%A x;".to_string();
1627        parse(
1628            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1629            &src,
1630        )
1631        .expect_error_at_line_col(&src, YaccGrammarErrorKind::MissingColon, 1, 5);
1632    }
1633
1634    #[test]
1635    fn test_premature_end() {
1636        let src = "%token x".to_string();
1637        parse(
1638            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1639            &src,
1640        )
1641        .expect_error_at_line_col(&src, YaccGrammarErrorKind::PrematureEnd, 1, 9);
1642    }
1643
1644    #[test]
1645    fn test_premature_end_multibyte() {
1646        let src = "%actiontype 🦀".to_string();
1647        parse(
1648            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1649            &src,
1650        )
1651        .expect_error_at_line_col(&src, YaccGrammarErrorKind::PrematureEnd, 1, 14);
1652        let src = "%parse-param c:🦀".to_string();
1653        parse(
1654            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1655            &src,
1656        )
1657        .expect_error_at_line_col(&src, YaccGrammarErrorKind::PrematureEnd, 1, 17);
1658        let src = "// 🦀".to_string();
1659        parse(
1660            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1661            &src,
1662        )
1663        .expect_error_at_line_col(&src, YaccGrammarErrorKind::PrematureEnd, 1, 5);
1664    }
1665
1666    #[test]
1667    fn test_same_line() {
1668        let src = "%token
1669x"
1670        .to_string();
1671        parse(
1672            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1673            &src,
1674        )
1675        .expect_error_at_line_col(&src, YaccGrammarErrorKind::ReachedEOL, 1, 7);
1676    }
1677
1678    #[test]
1679    fn test_unknown_declaration() {
1680        let src = "%woo".to_string();
1681        parse(
1682            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1683            &src,
1684        )
1685        .expect_error_at_line_col(&src, YaccGrammarErrorKind::UnknownDeclaration, 1, 1);
1686    }
1687
1688    #[test]
1689    fn test_grmtools_format() {
1690        let src = "
1691          %start A
1692          %%
1693          A -> T: 'b';
1694          B -> Result<(), T>: 'c';
1695          C -> ::std::result::Result<(), T>: 'd';
1696          "
1697        .to_string();
1698        let grm = parse(YaccKind::Grmtools, &src).unwrap();
1699        assert_eq!(grm.rules["A"].actiont, Some("T".to_string()));
1700        assert_eq!(grm.rules["B"].actiont, Some("Result<(), T>".to_string()));
1701        assert_eq!(
1702            grm.rules["C"].actiont,
1703            Some("::std::result::Result<(), T>".to_string())
1704        );
1705    }
1706
1707    #[test]
1708    #[rustfmt::skip]
1709    fn test_precs() {
1710        let src = "
1711          %left '+' '-'
1712          %left '*'
1713          %right '/'
1714          %right '^'
1715          %nonassoc '~'
1716          %%
1717          ".to_string();
1718        let grm = parse(YaccKind::Original(YaccOriginalActionKind::GenericParseTree), &src).unwrap();
1719        assert_eq!(grm.precs.len(), 6);
1720        assert_eq!(grm.precs["+"], (Precedence{level: 0, kind: AssocKind::Left}, Span::new(18, 19)));
1721        assert_eq!(grm.precs["-"], (Precedence{level: 0, kind: AssocKind::Left}, Span::new(22, 23)));
1722        assert_eq!(grm.precs["*"], (Precedence{level: 1, kind: AssocKind::Left}, Span::new(42, 43)));
1723        assert_eq!(grm.precs["/"], (Precedence{level: 2, kind: AssocKind::Right}, Span::new(63, 64)));
1724        assert_eq!(grm.precs["^"], (Precedence{level: 3, kind: AssocKind::Right}, Span::new(84, 85)));
1725        assert_eq!(grm.precs["~"], (Precedence{level: 4, kind: AssocKind::Nonassoc}, Span::new(108, 109)));
1726    }
1727
1728    #[test]
1729    fn test_dup_precs() {
1730        #[rustfmt::skip]
1731        let srcs = [
1732            ("
1733          %left 'x'
1734          %left 'x'
1735          %%
1736          ", ((2, 18), (3, 18))),
1737            ("
1738          %left 'x'
1739          %right 'x'
1740          %%
1741          ", ((2, 18), (3, 19))),
1742            ("
1743          %right 'x'
1744          %right 'x'
1745          %%
1746          ", ((2, 19), (3, 19))),
1747            ("
1748          %nonassoc 'x'
1749          %nonassoc 'x'
1750          %%
1751          ", ((2, 22), (3, 22))),
1752            ("
1753          %left 'x'
1754          %nonassoc 'x'
1755          %%
1756          ", ((2, 18), (3, 22))),
1757            ("
1758          %right 'x'
1759          %nonassoc 'x'
1760          %%
1761          ", ((2, 19), (3, 22)))
1762        ];
1763        for (src, (expected_origin, expected_dup)) in srcs.iter() {
1764            parse(
1765                YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1766                src,
1767            )
1768            .expect_error_at_lines_cols(
1769                src,
1770                YaccGrammarErrorKind::DuplicatePrecedence,
1771                &mut [*expected_origin, *expected_dup].into_iter(),
1772            );
1773        }
1774    }
1775
1776    #[test]
1777    fn test_multiple_dup_precs() {
1778        let src = "
1779          %left 'x'
1780          %left 'x'
1781          %right 'x'
1782          %nonassoc 'x'
1783          %left 'y'
1784          %nonassoc 'y'
1785          %right 'y'
1786          %%";
1787
1788        parse(
1789            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1790            src,
1791        )
1792        .expect_multiple_errors(
1793            src,
1794            &mut [
1795                (
1796                    YaccGrammarErrorKind::DuplicatePrecedence,
1797                    vec![(2, 18), (3, 18), (4, 19), (5, 22)],
1798                ),
1799                (
1800                    YaccGrammarErrorKind::DuplicatePrecedence,
1801                    vec![(6, 18), (7, 22), (8, 19)],
1802                ),
1803            ]
1804            .into_iter(),
1805        );
1806    }
1807
1808    #[test]
1809    #[rustfmt::skip]
1810    fn test_prec_override() {
1811        // Taken from the Yacc manual
1812        let src = "
1813            %left '+' '-'
1814            %left '*' '/'
1815            %%
1816            expr : expr '+' expr
1817                 | expr '-' expr
1818                 | expr '*' expr
1819                 | expr '/' expr
1820                 | '-'  expr %prec '*'
1821                 | NAME ;
1822        ";
1823        let grm = parse(YaccKind::Original(YaccOriginalActionKind::GenericParseTree), src).unwrap();
1824        assert_eq!(grm.precs.len(), 4);
1825        assert_eq!(grm.prods[grm.rules["expr"].pidxs[0]].precedence, None);
1826        assert_eq!(grm.prods[grm.rules["expr"].pidxs[3]].symbols.len(), 3);
1827        assert_eq!(grm.prods[grm.rules["expr"].pidxs[4]].symbols.len(), 2);
1828        assert_eq!(grm.prods[grm.rules["expr"].pidxs[4]].precedence, Some("*".to_string()));
1829    }
1830
1831    #[test]
1832    fn test_prec_empty() {
1833        let src = "
1834        %%
1835        expr : 'a'
1836             | %empty %prec 'a';
1837        ";
1838        let grm = parse(YaccKind::Original(YaccOriginalActionKind::NoAction), src).unwrap();
1839        assert_eq!(
1840            grm.prods[grm.rules["expr"].pidxs[1]].precedence,
1841            Some("a".to_string())
1842        );
1843    }
1844
1845    #[test]
1846    fn test_bad_prec_overrides() {
1847        let src = "
1848        %%
1849        S: 'A' %prec ;
1850        ";
1851        parse(
1852            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1853            src,
1854        )
1855        .expect_error_at_line(src, YaccGrammarErrorKind::IllegalString, 3);
1856    }
1857
1858    #[test]
1859    fn test_parse_avoid_insert() {
1860        let ast = parse(
1861            YaccKind::Eco,
1862            "
1863          %avoid_insert ws1 ws2
1864          %start R
1865          %%
1866          R: 'a';
1867          ",
1868        )
1869        .unwrap();
1870        assert_eq!(
1871            ast.avoid_insert,
1872            Some(
1873                [
1874                    ("ws1".to_string(), Span::new(25, 28)),
1875                    ("ws2".to_string(), Span::new(29, 32))
1876                ]
1877                .iter()
1878                .cloned()
1879                .collect()
1880            )
1881        );
1882        assert!(ast.tokens.get("ws1").is_some());
1883        assert!(ast.tokens.get("ws2").is_some());
1884    }
1885
1886    #[test]
1887    fn test_multiple_avoid_insert() {
1888        let ast = parse(
1889            YaccKind::Eco,
1890            "
1891          %avoid_insert X
1892          %avoid_insert Y
1893          %%
1894          ",
1895        )
1896        .unwrap();
1897        assert_eq!(
1898            ast.avoid_insert,
1899            Some(
1900                [
1901                    ("X".to_string(), Span::new(25, 26)),
1902                    ("Y".to_string(), Span::new(51, 52))
1903                ]
1904                .iter()
1905                .cloned()
1906                .collect()
1907            )
1908        );
1909    }
1910
1911    #[test]
1912    fn test_duplicate_avoid_insert() {
1913        let src = "
1914          %avoid_insert X Y
1915          %avoid_insert Y
1916          %%
1917          ";
1918        parse(YaccKind::Eco, src).expect_error_at_lines_cols(
1919            src,
1920            YaccGrammarErrorKind::DuplicateAvoidInsertDeclaration,
1921            &mut [(2usize, 27usize), (3, 25)].into_iter(),
1922        );
1923    }
1924
1925    #[test]
1926    fn test_duplicate_avoid_insert2() {
1927        let src = "
1928        %avoid_insert X
1929        %avoid_insert Y Y
1930        %%
1931        ";
1932        parse(YaccKind::Eco, src).expect_error_at_lines_cols(
1933            src,
1934            YaccGrammarErrorKind::DuplicateAvoidInsertDeclaration,
1935            &mut [(3, 23), (3, 25)].into_iter(),
1936        );
1937    }
1938
1939    #[test]
1940    fn test_multiple_duplicate_avoid_insert() {
1941        let src = "
1942        %avoid_insert X
1943        %avoid_insert Y Y X
1944        %%
1945        ";
1946        parse(YaccKind::Eco, src).expect_multiple_errors(
1947            src,
1948            &mut [
1949                (
1950                    YaccGrammarErrorKind::DuplicateAvoidInsertDeclaration,
1951                    vec![(3, 23), (3, 25)],
1952                ),
1953                (
1954                    YaccGrammarErrorKind::DuplicateAvoidInsertDeclaration,
1955                    vec![(2, 23), (3, 27)],
1956                ),
1957            ]
1958            .into_iter(),
1959        );
1960    }
1961
1962    #[test]
1963    fn test_no_implicit_tokens_in_original_yacc() {
1964        let src = "
1965        %implicit_tokens X
1966        %%
1967        ";
1968        parse(
1969            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
1970            src,
1971        )
1972        .expect_error_at_line(src, YaccGrammarErrorKind::UnknownDeclaration, 2);
1973    }
1974
1975    #[test]
1976    fn test_parse_implicit_tokens() {
1977        let ast = parse(
1978            YaccKind::Eco,
1979            "
1980          %implicit_tokens ws1 ws2
1981          %start R
1982          %%
1983          R: 'a';
1984          ",
1985        )
1986        .unwrap();
1987        assert_eq!(
1988            ast.implicit_tokens,
1989            Some(
1990                [
1991                    ("ws1".to_string(), Span::new(28, 31)),
1992                    ("ws2".to_string(), Span::new(32, 35))
1993                ]
1994                .iter()
1995                .cloned()
1996                .collect()
1997            )
1998        );
1999        assert!(ast.tokens.get("ws1").is_some());
2000        assert!(ast.tokens.get("ws2").is_some());
2001    }
2002
2003    #[test]
2004    fn test_multiple_implicit_tokens() {
2005        let ast = parse(
2006            YaccKind::Eco,
2007            "
2008          %implicit_tokens X
2009          %implicit_tokens Y
2010          %%
2011          ",
2012        )
2013        .unwrap();
2014        assert_eq!(
2015            ast.implicit_tokens,
2016            Some(
2017                [
2018                    ("X".to_string(), Span::new(28, 29)),
2019                    ("Y".to_string(), Span::new(57, 58))
2020                ]
2021                .iter()
2022                .cloned()
2023                .collect()
2024            )
2025        );
2026    }
2027
2028    #[test]
2029    fn test_duplicate_implicit_tokens() {
2030        let src = "
2031        %implicit_tokens X
2032        %implicit_tokens X Y
2033        %%
2034        ";
2035        parse(YaccKind::Eco, src).expect_error_at_lines_cols(
2036            src,
2037            YaccGrammarErrorKind::DuplicateImplicitTokensDeclaration,
2038            &mut [(2, 26), (3, 26)].into_iter(),
2039        );
2040    }
2041
2042    #[test]
2043    fn test_duplicate_implicit_tokens2() {
2044        let src = "
2045        %implicit_tokens X X
2046        %implicit_tokens Y
2047        %%
2048        ";
2049        parse(YaccKind::Eco, src).expect_error_at_lines_cols(
2050            src,
2051            YaccGrammarErrorKind::DuplicateImplicitTokensDeclaration,
2052            &mut [(2, 26), (2, 28)].into_iter(),
2053        );
2054    }
2055
2056    #[test]
2057    fn test_multiple_duplicate_implicit_tokens_and_invalid_rule() {
2058        let src = "
2059        %implicit_tokens X
2060        %implicit_tokens X Y
2061        %implicit_tokens Y
2062        %%
2063        IncompleteRule: ";
2064        parse(YaccKind::Eco, src).expect_multiple_errors(
2065            src,
2066            &mut [
2067                (
2068                    YaccGrammarErrorKind::DuplicateImplicitTokensDeclaration,
2069                    vec![(2, 26), (3, 26)],
2070                ),
2071                (
2072                    YaccGrammarErrorKind::DuplicateImplicitTokensDeclaration,
2073                    vec![(3, 28), (4, 26)],
2074                ),
2075                (YaccGrammarErrorKind::IncompleteRule, vec![(6, 25)]),
2076            ]
2077            .into_iter(),
2078        );
2079    }
2080
2081    #[test]
2082    #[rustfmt::skip]
2083    fn test_parse_epp() {
2084        let ast = parse(
2085            YaccKind::Eco,
2086            r#"
2087          %epp A "a"
2088          %epp B 'a'
2089          %epp C '"'
2090          %epp D "'"
2091          %epp E "\""
2092          %epp F '\''
2093          %epp G "a\"b"
2094          %%
2095          R: 'A';
2096          "#,
2097        )
2098        .unwrap();
2099        assert_eq!(ast.epp.len(), 7);
2100        assert_eq!(ast.epp["A"], (Span::new(16, 17),   ("a".to_string(),   Span::new(18, 21))));
2101        assert_eq!(ast.epp["B"], (Span::new(37, 38),   ("a".to_string(),   Span::new(39, 42))));
2102        assert_eq!(ast.epp["C"], (Span::new(58, 59),   ("\"".to_string(),  Span::new(60, 63))));
2103        assert_eq!(ast.epp["D"], (Span::new(79, 80),   ("'".to_string(),   Span::new(81, 84))));
2104        assert_eq!(ast.epp["E"], (Span::new(100, 101), ("\"".to_string(),  Span::new(102, 106))));
2105        assert_eq!(ast.epp["F"], (Span::new(122, 123), ("'".to_string(),   Span::new(124, 128))));
2106        assert_eq!(ast.epp["G"], (Span::new(144, 145), ("a\"b".to_string(),Span::new(146, 152))));
2107    }
2108
2109    #[test]
2110    fn test_duplicate_epp() {
2111        let src = "
2112        %epp A \"a\"
2113        %epp A \"a\"
2114        %epp A \"a\"
2115        %%
2116        ";
2117        parse(YaccKind::Eco, src).expect_error_at_lines_cols(
2118            src,
2119            YaccGrammarErrorKind::DuplicateEPP,
2120            &mut [(2, 14), (3, 14), (4, 14)].into_iter(),
2121        );
2122    }
2123
2124    #[test]
2125    fn test_multiple_duplicate_epp() {
2126        let src = "
2127        %epp A \"a1\"
2128        %epp A \"a2\"
2129        %epp A \"a3\"
2130        %epp B \"b1\"
2131        %epp B \"b2\"
2132        %epp B \"b3\"
2133        %%
2134        ";
2135        parse(YaccKind::Eco, src).expect_multiple_errors(
2136            src,
2137            &mut [
2138                (
2139                    YaccGrammarErrorKind::DuplicateEPP,
2140                    vec![(2, 14), (3, 14), (4, 14)],
2141                ),
2142                (
2143                    YaccGrammarErrorKind::DuplicateEPP,
2144                    vec![(5, 14), (6, 14), (7, 14)],
2145                ),
2146            ]
2147            .into_iter(),
2148        );
2149    }
2150
2151    #[test]
2152    fn test_broken_string() {
2153        let src = "
2154          %epp A \"a
2155          %%
2156          ";
2157        parse(YaccKind::Eco, src).expect_error_at_line(src, YaccGrammarErrorKind::InvalidString, 2);
2158
2159        let src = "
2160        %epp A \"a";
2161        parse(YaccKind::Eco, src).expect_error_at_line(src, YaccGrammarErrorKind::InvalidString, 2);
2162    }
2163
2164    #[test]
2165    fn test_duplicate_start() {
2166        let src = "
2167          %start X
2168          %start X
2169          %%
2170          ";
2171        parse(YaccKind::Eco, src).expect_error_at_lines_cols(
2172            src,
2173            YaccGrammarErrorKind::DuplicateStartDeclaration,
2174            &mut [(2, 18), (3, 18)].into_iter(),
2175        );
2176    }
2177
2178    #[test]
2179    fn test_duplicate_start_premature_end() {
2180        let src = "
2181          %start X
2182          %start X";
2183        parse(YaccKind::Eco, src).expect_multiple_errors(
2184            src,
2185            &mut [
2186                (
2187                    YaccGrammarErrorKind::DuplicateStartDeclaration,
2188                    vec![(2, 18), (3, 18)],
2189                ),
2190                (YaccGrammarErrorKind::PrematureEnd, vec![(3, 19)]),
2191            ]
2192            .into_iter(),
2193        );
2194    }
2195
2196    #[test]
2197    fn test_duplicate_expect() {
2198        let src = "
2199          %expect 1
2200          %expect 2
2201          %expect 3
2202          %%
2203          ";
2204        parse(
2205            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
2206            src,
2207        )
2208        .expect_error_at_lines_cols(
2209            src,
2210            YaccGrammarErrorKind::DuplicateExpectDeclaration,
2211            &mut [(2, 19), (3, 19), (4, 19)].into_iter(),
2212        )
2213    }
2214
2215    #[test]
2216    fn test_duplicate_expect_and_missing_colon() {
2217        let src = "
2218          %expect 1
2219          %expect 2
2220          %expect 3
2221          %%
2222          A ;";
2223        parse(
2224            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
2225            src,
2226        )
2227        .expect_multiple_errors(
2228            src,
2229            &mut [
2230                (
2231                    YaccGrammarErrorKind::DuplicateExpectDeclaration,
2232                    vec![(2, 19), (3, 19), (4, 19)],
2233                ),
2234                (YaccGrammarErrorKind::MissingColon, vec![(6, 13)]),
2235            ]
2236            .into_iter(),
2237        )
2238    }
2239
2240    #[test]
2241    fn test_duplicate_expectrr() {
2242        let src = "
2243          %expect-rr 1
2244          %expect-rr 2
2245          %expect-rr 3
2246          %%
2247          ";
2248        parse(
2249            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
2250            src,
2251        )
2252        .expect_error_at_lines_cols(
2253            src,
2254            YaccGrammarErrorKind::DuplicateExpectRRDeclaration,
2255            &mut [(2, 22), (3, 22), (4, 22)].into_iter(),
2256        );
2257    }
2258
2259    #[test]
2260    fn test_duplicate_expectrr_illegal_name() {
2261        let src = "
2262          %expect-rr 1
2263          %expect-rr 2
2264          %expect-rr 3
2265          %%
2266          +IllegalRuleName+:;";
2267        parse(
2268            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
2269            src,
2270        )
2271        .expect_multiple_errors(
2272            src,
2273            &mut [
2274                (
2275                    YaccGrammarErrorKind::DuplicateExpectRRDeclaration,
2276                    vec![(2, 22), (3, 22), (4, 22)],
2277                ),
2278                (YaccGrammarErrorKind::IllegalName, vec![(6, 11)]),
2279            ]
2280            .into_iter(),
2281        );
2282    }
2283
2284    #[test]
2285    fn test_implicit_start() {
2286        let ast = parse(
2287            YaccKind::Eco,
2288            "
2289          %%
2290          R: ;
2291          R2: ;
2292          R3: ;
2293          ",
2294        )
2295        .unwrap();
2296        assert_eq!(ast.start, Some(("R".to_string(), Span::new(24, 25))));
2297    }
2298
2299    #[test]
2300    fn test_action() {
2301        let grm = parse(
2302            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
2303            "
2304          %%
2305          A: 'a' B { println!(\"test\"); }
2306           ;
2307          B: 'b' 'c' { add($1, $2); }
2308           | 'd'
2309           ;
2310          D: 'd' {}
2311           ;
2312          ",
2313        )
2314        .unwrap();
2315        let action_str = " println!(\"test\"); ".to_string();
2316        assert_eq!(
2317            grm.prods[grm.rules["A"].pidxs[0]].action,
2318            Some((action_str.clone(), Span::new(34, 34 + action_str.len())))
2319        );
2320        let action_str = " add($1, $2); ".to_string();
2321        assert_eq!(
2322            grm.prods[grm.rules["B"].pidxs[0]].action,
2323            Some((action_str.clone(), Span::new(90, 90 + action_str.len())))
2324        );
2325        assert_eq!(grm.prods[grm.rules["B"].pidxs[1]].action, None);
2326    }
2327
2328    #[test]
2329    fn test_action_ends_in_multibyte() {
2330        let grm = parse(
2331            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
2332            "%%A: '_' {(); // 🦀};",
2333        )
2334        .unwrap();
2335        let action_str = "(); // 🦀".to_string();
2336        assert_eq!(
2337            grm.prods[grm.rules["A"].pidxs[0]].action,
2338            Some((action_str.clone(), Span::new(10, 10 + action_str.len())))
2339        );
2340    }
2341
2342    #[test]
2343    fn test_programs() {
2344        let grm = parse(
2345            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
2346            "
2347         %%
2348         A: 'a';
2349         %%
2350         fn foo() {}",
2351        )
2352        .unwrap();
2353        assert_eq!(grm.programs, Some("fn foo() {}".to_string()));
2354    }
2355
2356    #[test]
2357    fn test_actions_with_newlines() {
2358        let src = "
2359        %%
2360        A: 'a' { foo();
2361                 bar(); }
2362        ;
2363        B: b';";
2364        parse(
2365            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
2366            src,
2367        )
2368        .expect_error_at_line(src, YaccGrammarErrorKind::IllegalString, 6);
2369    }
2370
2371    #[test]
2372    fn test_comments() {
2373        let src = "
2374            // A valid comment
2375            %token   a
2376            /* Another valid comment */
2377            %%\n
2378            A : a;";
2379        let grm = parse(
2380            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
2381            src,
2382        )
2383        .unwrap();
2384        assert!(grm.has_token("a"));
2385
2386        let src = "
2387        /* An invalid comment * /
2388        %token   a
2389        %%\n
2390        A : a;";
2391        parse(
2392            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
2393            src,
2394        )
2395        .expect_error_at_line(src, YaccGrammarErrorKind::IncompleteComment, 2);
2396
2397        let src = "
2398        %token   a
2399        %%
2400        /* A valid
2401         * multi-line comment
2402         */
2403        /* An invalid comment * /
2404        A : a;";
2405        parse(
2406            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
2407            src,
2408        )
2409        .expect_error_at_line(src, YaccGrammarErrorKind::IncompleteComment, 7);
2410
2411        let src = "
2412        %token   a
2413        %%
2414        // Valid comment
2415        A : a";
2416        parse(
2417            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
2418            src,
2419        )
2420        .expect_error_at_line(src, YaccGrammarErrorKind::IncompleteRule, 5);
2421    }
2422
2423    #[test]
2424    fn test_action_type() {
2425        let grm = parse(
2426            YaccKind::Original(YaccOriginalActionKind::UserAction),
2427            "
2428         %actiontype T
2429         %%
2430         A: 'a';
2431         %%
2432         fn foo() {}",
2433        )
2434        .unwrap();
2435        assert_eq!(grm.rules["A"].actiont, Some("T".to_string()));
2436    }
2437
2438    #[test]
2439    fn test_only_one_type() {
2440        let src = "
2441         %actiontype T1
2442         %actiontype T2
2443         %actiontype T3
2444         %%
2445         A: 'a';";
2446        parse(
2447            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
2448            src,
2449        )
2450        .expect_error_at_lines_cols(
2451            src,
2452            YaccGrammarErrorKind::DuplicateActiontypeDeclaration,
2453            &mut [(2, 22), (3, 22), (4, 22)].into_iter(),
2454        );
2455    }
2456
2457    #[test]
2458    fn test_duplicate_actiontype_and_premature_end() {
2459        let src = "
2460         %actiontype T1
2461         %actiontype T2
2462         %actiontype T3";
2463        parse(
2464            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
2465            src,
2466        )
2467        .expect_multiple_errors(
2468            src,
2469            &mut [
2470                (
2471                    YaccGrammarErrorKind::DuplicateActiontypeDeclaration,
2472                    vec![(2, 22), (3, 22), (4, 22)],
2473                ),
2474                (YaccGrammarErrorKind::PrematureEnd, vec![(4, 24)]),
2475            ]
2476            .into_iter(),
2477        )
2478    }
2479
2480    #[test]
2481    fn test_parse_param() {
2482        let src = "
2483          %parse-param a::b: (u64, u64)
2484          %%
2485          A: 'a';
2486         ";
2487        let grm = parse(YaccKind::Original(YaccOriginalActionKind::UserAction), src).unwrap();
2488
2489        assert_eq!(
2490            grm.parse_param,
2491            Some(("a::b".to_owned(), "(u64, u64)".to_owned()))
2492        );
2493    }
2494
2495    #[test]
2496    fn test_parse_generics() {
2497        let src = "
2498          %parse-generics 'a, K, V
2499          %%
2500          A: 'a';
2501         ";
2502        let grm = parse(YaccKind::Original(YaccOriginalActionKind::UserAction), src).unwrap();
2503
2504        assert_eq!(grm.parse_generics, Some("'a, K, V".to_owned()));
2505    }
2506
2507    #[test]
2508    fn test_duplicate_rule() {
2509        let ast = parse(
2510            YaccKind::Grmtools,
2511            "%token A B D
2512%%
2513Expr -> () : %empty | A;
2514Expr -> () : B | 'C';
2515Expr -> () : D;
2516",
2517        )
2518        .unwrap();
2519        let expr_rule = ast.get_rule("Expr").unwrap();
2520        let mut prod_names = HashSet::new();
2521        for pidx in &expr_rule.pidxs {
2522            for sym in &ast.prods[*pidx].symbols {
2523                let name = match sym {
2524                    Symbol::Token(name, _) | Symbol::Rule(name, _) => name.clone(),
2525                };
2526                prod_names.insert(name);
2527            }
2528        }
2529        assert_eq!(ast.prods.len(), 5);
2530        assert_eq!(
2531            prod_names,
2532            HashSet::from_iter(["A", "B", "C", "D"].map(|s| s.to_owned()))
2533        );
2534    }
2535
2536    #[test]
2537    fn test_duplicate_start_and_missing_arrow() {
2538        let src = "%start A
2539%start A
2540%start A
2541%%
2542A -> () : 'a1';
2543B";
2544        parse(YaccKind::Grmtools, src).expect_multiple_errors(
2545            src,
2546            &mut [
2547                (
2548                    YaccGrammarErrorKind::DuplicateStartDeclaration,
2549                    vec![(1, 8), (2, 8), (3, 8)],
2550                ),
2551                (YaccGrammarErrorKind::MissingRightArrow, vec![(6, 2)]),
2552            ]
2553            .into_iter(),
2554        )
2555    }
2556
2557    #[test]
2558    fn test_routines_multiple_errors() {
2559        let mut src = String::from(
2560            "
2561        %start A
2562        %start B
2563        %expect 1
2564        %expect 2
2565        %%
2566        A -> () : 'a';
2567        %%
2568        ",
2569        );
2570        let mut expected_errs = vec![
2571            (
2572                YaccGrammarErrorKind::DuplicateStartDeclaration,
2573                vec![(2, 16), (3, 16)],
2574            ),
2575            (
2576                YaccGrammarErrorKind::DuplicateExpectDeclaration,
2577                vec![(4, 17), (5, 17)],
2578            ),
2579        ];
2580        parse(YaccKind::Grmtools, &src)
2581            .expect_multiple_errors(&src, &mut expected_errs.clone().into_iter());
2582
2583        src.push_str(
2584            "
2585                /* Incomplete comment
2586        ",
2587        );
2588        expected_errs.push((YaccGrammarErrorKind::IncompleteComment, vec![(10, 17)]));
2589        parse(YaccKind::Grmtools, &src)
2590            .expect_multiple_errors(&src, &mut expected_errs.clone().into_iter());
2591    }
2592
2593    #[test]
2594    fn test_expect_unused() {
2595        let src = r#"
2596        %expect-unused A 'b' "c"
2597        %%
2598        A: ;
2599        "#;
2600        let grm = parse(YaccKind::Original(YaccOriginalActionKind::NoAction), src).unwrap();
2601        assert!(
2602            grm.expect_unused
2603                .contains(&Symbol::Rule("A".to_string(), Span::new(24, 25)))
2604        );
2605        assert!(
2606            grm.expect_unused
2607                .contains(&Symbol::Token("b".to_string(), Span::new(27, 28)))
2608        );
2609        assert!(
2610            grm.expect_unused
2611                .contains(&Symbol::Token("c".to_string(), Span::new(31, 32)))
2612        );
2613    }
2614
2615    #[test]
2616    fn test_bad_expect_unused() {
2617        let src = "
2618        %expect-unused %
2619        %%
2620        A: ;
2621        ";
2622        parse(YaccKind::Original(YaccOriginalActionKind::NoAction), src).expect_error_at_line_col(
2623            src,
2624            YaccGrammarErrorKind::UnknownDeclaration,
2625            2,
2626            24,
2627        );
2628    }
2629
2630    #[test]
2631    fn test_unused_symbols() {
2632        let ast = parse(
2633            YaccKind::Original(YaccOriginalActionKind::NoAction),
2634            "
2635        %expect-unused UnusedAllowed 'b'
2636        %token a b
2637        %start Start
2638        %%
2639        Unused: ;
2640        Start: ;
2641        UnusedAllowed: ;
2642        ",
2643        )
2644        .unwrap();
2645
2646        assert_eq!(
2647            ast.unused_symbols()
2648                .map(|sym_idx| { sym_idx.symbol(&ast) })
2649                .collect::<Vec<Symbol>>()
2650                .as_slice(),
2651            &[
2652                Symbol::Rule("Unused".to_string(), Span::new(101, 107)),
2653                Symbol::Token("a".to_string(), Span::new(57, 58))
2654            ]
2655        );
2656
2657        let ast = parse(
2658            YaccKind::Original(YaccOriginalActionKind::NoAction),
2659            "
2660        %start A
2661        %%
2662        A: ;
2663        Rec: Rec | ;
2664        ",
2665        )
2666        .unwrap();
2667        assert_eq!(
2668            ast.unused_symbols()
2669                .map(|sym_idx| sym_idx.symbol(&ast))
2670                .collect::<Vec<Symbol>>()
2671                .as_slice(),
2672            &[Symbol::Rule("Rec".to_string(), Span::new(50, 53))]
2673        );
2674
2675        let ast = parse(
2676            YaccKind::Original(YaccOriginalActionKind::NoAction),
2677            "
2678        %%
2679        A: 'a' | 'z' ;
2680        B: 'a' | 'c' ;
2681        ",
2682        )
2683        .unwrap();
2684        // Check that we warn on B and 'c' but not 'a'
2685        assert_eq!(
2686            ast.unused_symbols()
2687                .map(|sym_idx| sym_idx.symbol(&ast))
2688                .collect::<Vec<Symbol>>()
2689                .as_slice(),
2690            &[
2691                Symbol::Rule("B".to_string(), Span::new(43, 44)),
2692                Symbol::Token("c".to_string(), Span::new(53, 54))
2693            ]
2694        );
2695    }
2696
2697    #[test]
2698    fn test_percent_empty() {
2699        parse(
2700            YaccKind::Original(YaccOriginalActionKind::NoAction),
2701            r#"
2702        %token a
2703        %start A
2704        %%
2705        A: %empty | "a";
2706        "#,
2707        )
2708        .unwrap();
2709
2710        let src = r#"
2711        %token a b
2712        %start A
2713        %%
2714        A: "a" | %empty | "b";
2715        B: %empty | "b";
2716        "#;
2717        parse(YaccKind::Original(YaccOriginalActionKind::NoAction), src).unwrap();
2718
2719        let src = r#"
2720        %token a
2721        %start A
2722        %%
2723        A: %empty "a";
2724        "#;
2725        parse(YaccKind::Original(YaccOriginalActionKind::NoAction), src).expect_error_at_line_col(
2726            src,
2727            YaccGrammarErrorKind::NonEmptyProduction,
2728            5,
2729            12,
2730        );
2731
2732        let src = r#"
2733        %token a
2734        %start A
2735        %%
2736        A: "a" %empty;
2737        "#;
2738        parse(YaccKind::Original(YaccOriginalActionKind::NoAction), src).expect_error_at_line_col(
2739            src,
2740            YaccGrammarErrorKind::NonEmptyProduction,
2741            5,
2742            16,
2743        );
2744    }
2745
2746    #[test]
2747    fn test_action_successor() {
2748        let src = "
2749        %%
2750        A: B {} B;
2751        B: ;
2752        ";
2753        parse(YaccKind::Original(YaccOriginalActionKind::NoAction), src).expect_error_at_line_col(
2754            src,
2755            YaccGrammarErrorKind::ProductionNotTerminated,
2756            3,
2757            17,
2758        );
2759
2760        let src = "
2761        %%
2762        A: B B {};
2763        B: {} ;
2764        ";
2765        parse(YaccKind::Original(YaccOriginalActionKind::NoAction), src).unwrap();
2766    }
2767
2768    #[test]
2769    fn test_empty_production_spans_issue_473() {
2770        let empty_prod_conflicts = [
2771            (
2772                "%start Expr
2773%%
2774Expr: %empty | Factor;
2775Factor: ')' Expr ')';
2776",
2777                (0, Span::new(21, 27)),
2778            ),
2779            (
2780                "%start Expr
2781%%
2782Expr: | Factor;
2783Factor: ')' Expr ')';
2784",
2785                (0, Span::new(21, 21)),
2786            ),
2787            (
2788                "%start Expr
2789%%
2790Expr:| Factor;
2791Factor: ')' Expr ')';
2792",
2793                (0, Span::new(20, 20)),
2794            ),
2795            (
2796                "%start Expr
2797%%
2798Expr: Factor | %empty;
2799Factor: ')' Expr ')';
2800",
2801                (1, Span::new(30, 36)),
2802            ),
2803            (
2804                "%start Expr
2805%%
2806Expr: Factor | ;
2807Factor: ')' Expr ')';
2808",
2809                (1, Span::new(30, 30)),
2810            ),
2811            (
2812                "%start Expr
2813%%
2814Expr: Factor|;
2815Factor: ')' Expr ')';
2816",
2817                (1, Span::new(28, 28)),
2818            ),
2819        ];
2820
2821        for (i, (src, (empty_pidx, empty_span))) in empty_prod_conflicts.iter().enumerate() {
2822            eprintln!("{}", i);
2823            let ast = parse(YaccKind::Original(YaccOriginalActionKind::NoAction), src).unwrap();
2824            assert_eq!(
2825                ast.prods[ast.get_rule("Expr").unwrap().pidxs[*empty_pidx]],
2826                Production {
2827                    symbols: vec![],
2828                    precedence: None,
2829                    action: None,
2830                    prod_span: *empty_span,
2831                }
2832            );
2833        }
2834    }
2835}