Skip to main content

cfgrammar/yacc/
ast.rs

1use std::{
2    collections::{HashMap, HashSet},
3    error::Error,
4    fmt,
5    str::FromStr,
6};
7
8use indexmap::{IndexMap, IndexSet};
9
10use super::{
11    Precedence, YaccGrammarError, YaccGrammarErrorKind, YaccGrammarWarning, YaccGrammarWarningKind,
12    YaccKind, parser::YaccParser,
13};
14
15use crate::{
16    Span,
17    header::{
18        GrmtoolsSectionParser, Header, HeaderError, HeaderErrorKind, HeaderValue, RE_CRATE_DOT,
19        Value,
20    },
21    yacc::YaccOriginalActionKind,
22};
23
24/// Any error from the Yacc parser returns an instance of this struct.
25#[derive(Debug, PartialEq, Eq, Clone)]
26pub struct ASTModificationError {
27    kind: YaccGrammarErrorKind,
28}
29
30impl Error for ASTModificationError {}
31
32impl fmt::Display for ASTModificationError {
33    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34        write!(f, "{}", self.kind)
35    }
36}
37
38/// Contains a `GrammarAST` structure produced from a grammar source file.
39/// As well as any errors which occurred during the construction of the AST.
40#[derive(Debug, Clone)]
41#[cfg_attr(test, derive(PartialEq))]
42pub struct ASTWithValidityInfo {
43    yacc_kind: YaccKind,
44    ast: GrammarAST,
45    grmtools_section: Header<Span>,
46    errs: Vec<YaccGrammarError>,
47}
48
49impl ASTWithValidityInfo {
50    /// Parses a source file into an AST, returning an ast and any errors that were
51    /// encountered during the construction of it.  The `ASTWithValidityInfo` can be
52    /// then unused to construct a `YaccGrammar`, which will either produce an
53    /// `Ok(YaccGrammar)` or an `Err` which includes these errors.
54    ///
55    /// This function ignores the `%grmtools` section entirely, assuming that the caller has
56    /// already extracted the `YaccKind` if any.
57    pub fn new(yacc_kind: YaccKind, s: &str) -> Self {
58        let mut errs = Vec::new();
59        let (ast, grmtools_section) = {
60            let mut yp = YaccParser::new(yacc_kind, s);
61            yp.parse().map_err(|e| errs.extend(e)).ok();
62            let (mut ast, grmtools_section) = yp.build();
63            ast.complete_and_validate(Some(yacc_kind))
64                .map_err(|e| errs.push(e))
65                .ok();
66            (ast, grmtools_section)
67        };
68        ASTWithValidityInfo {
69            ast,
70            errs,
71            grmtools_section,
72            yacc_kind,
73        }
74    }
75
76    /// Returns a `GrammarAST` constructed as the result of parsing a source file.
77    /// When errors have occurred and `is_valid` returns false, this AST is the
78    /// subset of the source file which parsed correctly while not encountering
79    /// any errors. As such even when an AST is not valid, it will return an AST.
80    pub fn ast(&self) -> &GrammarAST {
81        &self.ast
82    }
83
84    /// Returns whether any errors where encountered during the
85    /// parsing and validation of the AST during it's construction.
86    pub fn is_valid(&self) -> bool {
87        self.errors().is_empty()
88    }
89
90    /// Returns the `YaccKind` that was used to parse the `GrammarAST`.
91    pub fn yacc_kind(&self) -> YaccKind {
92        self.yacc_kind
93    }
94
95    /// Returns all errors which were encountered during AST construction.
96    pub fn errors(&self) -> &[YaccGrammarError] {
97        self.errs.as_slice()
98    }
99
100    pub fn clone_and_change_start_rule(&self, rule: Rule) -> Result<Self, ASTModificationError> {
101        if self.ast.get_rule(&rule.name.0).is_some() {
102            let mut ret = self.clone();
103            // The `Span`of the `start` field and the `name` field typically differ
104            // in that `start` is the parameter of a `%start` declaration, while
105            // `name` refers to the definition site of the rule itself.
106            //
107            // Lacking a better `Span` we use the definition site, for the `%start` rule here.
108            ret.ast.start = Some(rule.name);
109            Ok(ret)
110        } else {
111            Err(ASTModificationError {
112                kind: YaccGrammarErrorKind::InvalidStartRule(rule.name.0),
113            })
114        }
115    }
116
117    /// Performs a lookup in the grmtools section for an entry with the key `crate_name.key_name` and returns it.
118    pub fn header_value_get(&self, key: &str) -> Option<(Span, &Value<Span>)> {
119        if let Some(HeaderValue(span, value)) = self.grmtools_section.get(key) {
120            Some((*span, value))
121        } else {
122            None
123        }
124    }
125
126    /// Returns all the keys starting with `{prefix}.` for the `prefix` from the `%grmtools` section.
127    pub fn iter_prefix_keys(&self, prefix: &str) -> impl Iterator<Item = (&str, Span)> {
128        let prefix = format!("{prefix}.");
129        (&self.grmtools_section)
130            .into_iter()
131            .filter_map(move |(key, val)| {
132                let HeaderValue(span, _) = val;
133                if key.starts_with(&prefix) {
134                    Some((key.as_str(), *span))
135                } else {
136                    None
137                }
138            })
139    }
140
141    /// Returns all of the unique prefixes for all keys in the `%grmtools` section.
142    pub fn iter_prefixes(&self) -> impl Iterator<Item = &str> {
143        let mut prefixes = HashSet::new();
144        for (key, _) in &self.grmtools_section {
145            if let Some(prefix) = RE_CRATE_DOT.find(key) {
146                prefixes.insert(
147                    prefix
148                        .as_str()
149                        .strip_suffix('.')
150                        .expect("Regex ends in dot"),
151                );
152            }
153        }
154        prefixes.into_iter()
155    }
156
157    #[doc(hidden)]
158    pub fn header(&self) -> &Header<Span> {
159        &self.grmtools_section
160    }
161}
162
163impl FromStr for ASTWithValidityInfo {
164    type Err = Vec<YaccGrammarError>;
165    /// Parses the `%grmtools section` expecting it to contain a `yacckind` entry.
166    fn from_str(src: &str) -> Result<Self, Vec<YaccGrammarError>> {
167        let mut errs = Vec::new();
168        let (header, _) = GrmtoolsSectionParser::new(src, true)
169            .parse()
170            .map_err(|mut errs| errs.drain(..).map(|e| e.into()).collect::<Vec<_>>())?;
171        if let Some(HeaderValue(_, yk_val)) = header.get("cfgrammar.yacckind") {
172            let yacc_kind = YaccKind::try_from(yk_val).map_err(|e| vec![e.into()])?;
173            let (ast, grmtools_section) = {
174                // We don't want to strip off the header so that span's will be correct.
175                let mut yp = YaccParser::new(yacc_kind, src);
176                yp.parse().map_err(|e| errs.extend(e)).ok();
177                let (mut ast, grmtools_section) = yp.build();
178                ast.complete_and_validate(Some(yacc_kind))
179                    .map_err(|e| errs.push(e))
180                    .ok();
181                (ast, grmtools_section)
182            };
183            Ok(ASTWithValidityInfo {
184                ast,
185                errs,
186                grmtools_section,
187                yacc_kind,
188            })
189        } else {
190            Err(vec![
191                HeaderError {
192                    kind: HeaderErrorKind::InvalidEntry("cfgrammar.yacckind"),
193                    locations: vec![Span::new(0, 0)],
194                }
195                .into(),
196            ])
197        }
198    }
199}
200
201/// An AST representing a grammar. Typically these will only be constructed through [`ASTWithValidityInfo`] struct.
202#[derive(Debug, Clone)]
203#[cfg_attr(test, derive(PartialEq))]
204#[non_exhaustive]
205pub struct GrammarAST {
206    pub start: Option<(String, Span)>,
207    // map from a rule name to indexes into `prods`
208    pub rules: IndexMap<String, Rule>,
209    pub prods: Vec<Production>,
210    // A set of indexes into `tokens` for all tokens in `%token` directives.
211    // e.g. given a `%token a` and a token "b" not specified in any `%token` directive
212    // we have `self.tokens.get_index_of("a") ∈ self.token_directives`. However for
213    // token "b" we have `self.tokens.get_index_of("b") ∉ self.token_directives`.
214    pub token_directives: HashSet<usize>,
215    pub tokens: IndexSet<String>,
216    pub spans: Vec<Span>,
217    pub precs: HashMap<String, (Precedence, Span)>,
218    pub avoid_insert: Option<HashMap<String, Span>>,
219    pub implicit_tokens: Option<HashMap<String, Span>>,
220    // Error pretty-printers,
221    // The first span of the value is the span of the key,
222    // The second span in the value, is the span of the values string.
223    pub epp: HashMap<String, (Span, (String, Span))>,
224    pub expect: Option<(usize, Span)>,
225    pub expectrr: Option<(usize, Span)>,
226    pub parse_param: Option<(String, String)>,
227    pub parse_generics: Option<String>,
228    pub programs: Option<String>,
229    // The set of symbol names that, if unused in a
230    // grammar, will not cause a warning or error.
231    pub expect_unused: Vec<Symbol>,
232}
233
234#[derive(Debug, Clone)]
235#[cfg_attr(test, derive(Eq, PartialEq))]
236pub struct Rule {
237    pub name: (String, Span),
238    pub pidxs: Vec<usize>, // index into GrammarAST.prod
239    pub actiont: Option<String>,
240}
241
242#[derive(Debug, Clone)]
243#[cfg_attr(test, derive(Eq, PartialEq))]
244pub struct Production {
245    pub symbols: Vec<Symbol>,
246    pub precedence: Option<String>,
247    pub action: Option<(String, Span)>,
248    pub prod_span: Span,
249}
250
251#[derive(Clone, Debug)]
252#[cfg_attr(test, derive(Eq, PartialEq))]
253pub enum Symbol {
254    Rule(String, Span),
255    Token(String, Span),
256}
257
258/// Specifies an index into a `GrammarAst.tokens` or a `GrammarAST.rules`.
259/// Unlike `cfgrammar::Symbol` it is not parameterized by a `StorageT`.
260#[derive(Eq, PartialEq, Debug, Copy, Clone)]
261pub(crate) enum SymbolIdx {
262    Rule(usize),
263    Token(usize),
264}
265
266impl SymbolIdx {
267    pub(crate) fn symbol(self, ast: &GrammarAST) -> Symbol {
268        match self {
269            SymbolIdx::Rule(idx) => {
270                let (rule_name, rule_span) = &ast.rules[idx].name;
271                Symbol::Rule(rule_name.clone(), *rule_span)
272            }
273            SymbolIdx::Token(idx) => {
274                let tok = &ast.tokens[idx];
275                Symbol::Token(tok.clone(), ast.spans[idx])
276            }
277        }
278    }
279}
280impl fmt::Display for Symbol {
281    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
282        match *self {
283            Symbol::Rule(ref s, _) => write!(f, "{}", s),
284            Symbol::Token(ref s, _) => write!(f, "{}", s),
285        }
286    }
287}
288
289impl GrammarAST {
290    pub(crate) fn new() -> GrammarAST {
291        GrammarAST {
292            start: None,
293            rules: IndexMap::new(), // Using an IndexMap means that we retain the order
294            // of rules as they're found in the input file.
295            prods: Vec::new(),
296            spans: Vec::new(),
297            tokens: IndexSet::new(),
298            token_directives: HashSet::new(),
299            precs: HashMap::new(),
300            avoid_insert: None,
301            implicit_tokens: None,
302            epp: HashMap::new(),
303            expect: None,
304            expectrr: None,
305            parse_param: None,
306            parse_generics: None,
307            programs: None,
308            expect_unused: Vec::new(),
309        }
310    }
311
312    pub fn add_rule(&mut self, (name, name_span): (String, Span), actiont: Option<String>) {
313        self.rules.insert(
314            name.clone(),
315            Rule {
316                name: (name, name_span),
317                pidxs: Vec::new(),
318                actiont,
319            },
320        );
321    }
322
323    pub fn add_prod(
324        &mut self,
325        rule_name: String,
326        symbols: Vec<Symbol>,
327        precedence: Option<String>,
328        action: Option<(String, Span)>,
329        prod_span: Span,
330    ) {
331        self.rules[&rule_name].pidxs.push(self.prods.len());
332        self.prods.push(Production {
333            symbols,
334            precedence,
335            action,
336            prod_span,
337        });
338    }
339
340    #[deprecated(since = "0.10.2", note = "Please use set_programs instead")]
341    pub fn add_programs(&mut self, s: String) {
342        self.set_programs(s);
343    }
344
345    pub fn set_programs(&mut self, s: String) {
346        self.programs = Some(s)
347    }
348
349    pub fn get_rule(&self, key: &str) -> Option<&Rule> {
350        self.rules.get(key)
351    }
352
353    pub fn has_token(&self, s: &str) -> bool {
354        self.tokens.contains(s)
355    }
356
357    /// After the AST has been populated, perform any final operations, and validate the grammar
358    /// checking that:
359    ///   1) The start rule references a rule in the grammar
360    ///   2) Every rule reference references a rule in the grammar
361    ///   3) Every token reference references a declared token
362    ///   4) If a production has a precedence token, then it references a declared token
363    ///   5) Every token declared with %epp matches a known token
364    ///   6) If `yacc_kind` is specified, perform any kind specific validation.
365    ///      * If the kind requires an action type, check that each rule has one
366    ///      * That each production has action code
367    ///      * That `$` variables referred to in action code are recognised.
368    pub(crate) fn complete_and_validate(
369        &mut self,
370        yacc_kind: Option<YaccKind>,
371    ) -> Result<(), YaccGrammarError> {
372        let kind_requires_action_checks = matches!(
373            yacc_kind,
374            Some(YaccKind::Original(YaccOriginalActionKind::UserAction)) | Some(YaccKind::Grmtools)
375        );
376
377        match self.start {
378            None => {
379                return Err(YaccGrammarError {
380                    kind: YaccGrammarErrorKind::NoStartRule,
381                    spans: vec![Span::new(0, 0)],
382                });
383            }
384            Some((ref s, span)) => {
385                if !self.rules.contains_key(s) {
386                    return Err(YaccGrammarError {
387                        kind: YaccGrammarErrorKind::InvalidStartRule(s.clone()),
388                        spans: vec![span],
389                    });
390                }
391            }
392        }
393        for rule in self.rules.values() {
394            if kind_requires_action_checks && rule.actiont.is_none() {
395                return Err(YaccGrammarError {
396                    kind: YaccGrammarErrorKind::MissingActionType,
397                    spans: vec![rule.name.1],
398                });
399            }
400            for &pidx in &rule.pidxs {
401                let prod = &self.prods[pidx];
402                if kind_requires_action_checks {
403                    if let Some((action_code, action_span)) = prod.action.as_ref() {
404                        let mut last = 0;
405                        while let Some(off) = action_code[last..].find('$') {
406                            if !(action_code[last + off..].starts_with("$$")
407                                || action_code[last + off..].starts_with("$lexer")
408                                || action_code[last + off..].starts_with("$span")
409                                || (last + off + 1 < action_code.len()
410                                    && action_code[last + off + 1..]
411                                        .starts_with(|c: char| c.is_numeric())))
412                            {
413                                // Starting from the `$` find the end of a variable name, otherwise default to the span of the `$`
414                                let m = crate::yacc::parser::RE_NAME
415                                    .find(&action_code[last + off + 1..]);
416                                let var_start_pos = action_span.start() + last + off;
417                                let var_end_pos = m
418                                    .map(|m| var_start_pos + 1 + m.end())
419                                    .unwrap_or(var_start_pos + 1);
420                                return Err(YaccGrammarError {
421                                    kind: YaccGrammarErrorKind::UnrecognisedActionVariable,
422                                    spans: vec![Span::new(var_start_pos, var_end_pos)],
423                                });
424                            } else {
425                                last = last + off + 2;
426                            }
427                        }
428                    } else {
429                        return Err(YaccGrammarError {
430                            kind: YaccGrammarErrorKind::MissingActionCode,
431                            spans: vec![prod.prod_span],
432                        });
433                    }
434                }
435
436                if let Some(ref n) = prod.precedence {
437                    if !self.tokens.contains(n) {
438                        return Err(YaccGrammarError {
439                            kind: YaccGrammarErrorKind::UnknownToken(n.clone()),
440                            spans: vec![Span::new(0, 0)],
441                        });
442                    }
443                    if !self.precs.contains_key(n) {
444                        return Err(YaccGrammarError {
445                            kind: YaccGrammarErrorKind::NoPrecForToken(n.clone()),
446                            spans: vec![Span::new(0, 0)],
447                        });
448                    }
449                }
450                for sym in &prod.symbols {
451                    match *sym {
452                        Symbol::Rule(ref name, span) => {
453                            if !self.rules.contains_key(name) {
454                                return Err(YaccGrammarError {
455                                    kind: YaccGrammarErrorKind::UnknownRuleRef(name.clone()),
456                                    spans: vec![span],
457                                });
458                            }
459                        }
460                        Symbol::Token(ref name, span) => {
461                            if !self.tokens.contains(name) {
462                                return Err(YaccGrammarError {
463                                    kind: YaccGrammarErrorKind::UnknownToken(name.clone()),
464                                    spans: vec![span],
465                                });
466                            }
467                        }
468                    }
469                }
470            }
471        }
472
473        for (k, (sp, _)) in self.epp.iter() {
474            if self.tokens.contains(k) {
475                continue;
476            }
477            if let Some(ref it) = self.implicit_tokens
478                && it.contains_key(k)
479            {
480                continue;
481            }
482            return Err(YaccGrammarError {
483                kind: YaccGrammarErrorKind::UnknownEPP(k.clone()),
484                spans: vec![*sp],
485            });
486        }
487
488        for sym in &self.expect_unused {
489            match sym {
490                Symbol::Rule(sym_name, sym_span) => {
491                    if self.get_rule(sym_name).is_none() {
492                        return Err(YaccGrammarError {
493                            kind: YaccGrammarErrorKind::UnknownRuleRef(sym_name.clone()),
494                            spans: vec![*sym_span],
495                        });
496                    }
497                }
498                Symbol::Token(sym_name, sym_span) => {
499                    if !self.has_token(sym_name) {
500                        return Err(YaccGrammarError {
501                            kind: YaccGrammarErrorKind::UnknownToken(sym_name.clone()),
502                            spans: vec![*sym_span],
503                        });
504                    }
505                }
506            }
507        }
508        Ok(())
509    }
510
511    pub fn warnings(&self) -> Vec<YaccGrammarWarning> {
512        self.unused_symbols()
513            .map(|symidx| {
514                let (kind, span) = match symidx.symbol(self) {
515                    Symbol::Rule(_, span) => (YaccGrammarWarningKind::UnusedRule, span),
516                    Symbol::Token(_, span) => (YaccGrammarWarningKind::UnusedToken, span),
517                };
518                YaccGrammarWarning {
519                    kind,
520                    spans: vec![span],
521                }
522            })
523            .collect()
524    }
525
526    /// Return the indices of unexpectedly unused rules (relative to ast.rules)
527    /// and tokens (relative to ast.tokens) as `SymbolIdx`s.
528    pub(crate) fn unused_symbols(&self) -> impl Iterator<Item = SymbolIdx> + '_ {
529        let start_rule_name = self.start.as_ref().map(|(name, _)| name.clone());
530        let start_rule = self
531            .rules
532            .iter()
533            .find(|(rule_name, _)| start_rule_name.as_ref() == Some(rule_name));
534        let mut seen_rules = HashSet::new();
535        let mut seen_tokens = HashSet::new();
536        let mut expected_unused_tokens = HashSet::new();
537        let mut expected_unused_rules = HashSet::new();
538        for sym in &self.expect_unused {
539            match sym {
540                Symbol::Rule(sym_name, _) => {
541                    expected_unused_rules.insert(sym_name);
542                }
543                Symbol::Token(sym_name, _) => {
544                    expected_unused_tokens.insert(sym_name);
545                }
546            }
547        }
548        if let Some(implicit_tokens) = self.implicit_tokens.as_ref() {
549            expected_unused_tokens.extend(implicit_tokens.keys())
550        }
551        if let Some((start_name, start_rule)) = start_rule {
552            let mut todo = Vec::new();
553            todo.extend(start_rule.pidxs.iter().copied());
554            seen_rules.insert(start_name);
555
556            while let Some(pidx) = todo.pop() {
557                let prod = &self.prods[pidx];
558                for sym in &prod.symbols {
559                    match sym {
560                        Symbol::Rule(name, _) => {
561                            if seen_rules.insert(name)
562                                && let Some(rule) = self.rules.get(name)
563                            {
564                                todo.extend(&rule.pidxs);
565                            }
566                        }
567                        Symbol::Token(name, _) => {
568                            seen_tokens.insert(name);
569                        }
570                    };
571                }
572            }
573        }
574        self.rules
575            .iter()
576            .enumerate()
577            .filter_map(move |(rule_id, (rule_name, _))| {
578                if expected_unused_rules.contains(rule_name) || seen_rules.contains(rule_name) {
579                    None
580                } else {
581                    Some(SymbolIdx::Rule(rule_id))
582                }
583            })
584            .chain(
585                self.tokens
586                    .iter()
587                    .enumerate()
588                    .filter_map(move |(tok_idx, tok)| {
589                        if expected_unused_tokens.contains(tok) || seen_tokens.contains(tok) {
590                            None
591                        } else {
592                            Some(SymbolIdx::Token(tok_idx))
593                        }
594                    }),
595            )
596    }
597}
598
599#[cfg(test)]
600mod test {
601    use super::{
602        super::{AssocKind, Precedence},
603        GrammarAST, Span, Symbol, YaccGrammarError, YaccGrammarErrorKind,
604    };
605    use crate::{
606        header::{CFGRAMMAR_KEYS, LRPAR_KEYS},
607        test_utils::FindSpan as _,
608    };
609
610    fn rule(n: &str) -> Symbol {
611        Symbol::Rule(n.to_string(), Span::new(0, 0))
612    }
613
614    fn token(n: &str) -> Symbol {
615        Symbol::Token(n.to_string(), Span::new(0, 0))
616    }
617
618    #[test]
619    fn test_empty_grammar() {
620        let mut grm = GrammarAST::new();
621        match grm.complete_and_validate(None) {
622            Err(YaccGrammarError {
623                kind: YaccGrammarErrorKind::NoStartRule,
624                ..
625            }) => (),
626            _ => panic!("Validation error"),
627        }
628    }
629
630    #[test]
631    fn test_invalid_start_rule() {
632        let mut grm = GrammarAST::new();
633        let empty_span = Span::new(0, 0);
634        grm.start = Some(("A".to_string(), empty_span));
635        grm.add_rule(("B".to_string(), empty_span), None);
636        grm.add_prod("B".to_string(), vec![], None, None, empty_span);
637        match grm.complete_and_validate(None) {
638            Err(YaccGrammarError {
639                kind: YaccGrammarErrorKind::InvalidStartRule(_),
640                ..
641            }) => (),
642            _ => panic!("Validation error"),
643        }
644    }
645
646    #[test]
647    fn test_valid_start_rule() {
648        let mut grm = GrammarAST::new();
649        let empty_span = Span::new(0, 0);
650        grm.start = Some(("A".to_string(), empty_span));
651        grm.add_rule(("A".to_string(), empty_span), None);
652        grm.add_prod("A".to_string(), vec![], None, None, empty_span);
653        assert!(grm.complete_and_validate(None).is_ok());
654    }
655
656    #[test]
657    fn test_valid_rule_ref() {
658        let mut grm = GrammarAST::new();
659        let empty_span = Span::new(0, 0);
660        grm.start = Some(("A".to_string(), empty_span));
661        grm.add_rule(("A".to_string(), empty_span), None);
662        grm.add_rule(("B".to_string(), empty_span), None);
663        grm.add_prod("A".to_string(), vec![rule("B")], None, None, empty_span);
664        grm.add_prod("B".to_string(), vec![], None, None, empty_span);
665        assert!(grm.complete_and_validate(None).is_ok());
666    }
667
668    #[test]
669    fn test_invalid_rule_ref() {
670        let mut grm = GrammarAST::new();
671        let empty_span = Span::new(0, 0);
672        grm.start = Some(("A".to_string(), empty_span));
673        grm.add_rule(("A".to_string(), empty_span), None);
674        grm.add_prod("A".to_string(), vec![rule("B")], None, None, empty_span);
675        match grm.complete_and_validate(None) {
676            Err(YaccGrammarError {
677                kind: YaccGrammarErrorKind::UnknownRuleRef(_),
678                ..
679            }) => (),
680            _ => panic!("Validation error"),
681        }
682    }
683
684    #[test]
685    fn test_valid_token_ref() {
686        let mut grm = GrammarAST::new();
687        let empty_span = Span::new(0, 0);
688        grm.tokens.insert("b".to_string());
689        grm.start = Some(("A".to_string(), empty_span));
690        grm.add_rule(("A".to_string(), empty_span), None);
691        grm.add_prod("A".to_string(), vec![token("b")], None, None, empty_span);
692        assert!(grm.complete_and_validate(None).is_ok());
693    }
694
695    #[test]
696    fn test_redefine_rules_as_tokens() {
697        // for now we won't support the YACC feature that allows
698        // to redefine rules as tokens by adding them to '%token'
699        let mut grm = GrammarAST::new();
700        let empty_span = Span::new(0, 0);
701        grm.tokens.insert("b".to_string());
702        grm.start = Some(("A".to_string(), empty_span));
703        grm.add_rule(("A".to_string(), empty_span), None);
704        grm.add_prod("A".to_string(), vec![rule("b")], None, None, empty_span);
705        assert!(grm.complete_and_validate(None).is_err());
706    }
707
708    #[test]
709    fn test_invalid_token_ref() {
710        let mut grm = GrammarAST::new();
711        let empty_span = Span::new(0, 0);
712        grm.start = Some(("A".to_string(), empty_span));
713        grm.add_rule(("A".to_string(), empty_span), None);
714        grm.add_prod("A".to_string(), vec![token("b")], None, None, empty_span);
715        match grm.complete_and_validate(None) {
716            Err(YaccGrammarError {
717                kind: YaccGrammarErrorKind::UnknownToken(_),
718                ..
719            }) => (),
720            _ => panic!("Validation error"),
721        }
722    }
723
724    #[test]
725    fn test_invalid_rule_forgotten_token() {
726        let mut grm = GrammarAST::new();
727        let empty_span = Span::new(0, 0);
728        grm.start = Some(("A".to_string(), empty_span));
729        grm.add_rule(("A".to_string(), empty_span), None);
730        grm.add_prod(
731            "A".to_string(),
732            vec![rule("b"), token("b")],
733            None,
734            None,
735            Span::new(0, 2),
736        );
737        match grm.complete_and_validate(None) {
738            Err(YaccGrammarError {
739                kind: YaccGrammarErrorKind::UnknownRuleRef(_),
740                ..
741            }) => (),
742            _ => panic!("Validation error"),
743        }
744    }
745
746    #[test]
747    fn test_invalid_epp() {
748        let mut grm = GrammarAST::new();
749        let empty_span = Span::new(2, 3);
750        grm.start = Some(("A".to_string(), empty_span));
751        grm.add_rule(("A".to_string(), empty_span), None);
752        grm.add_prod("A".to_string(), vec![], None, None, empty_span);
753        grm.epp
754            .insert("k".to_owned(), (empty_span, ("v".to_owned(), empty_span)));
755        match grm.complete_and_validate(None) {
756            Err(YaccGrammarError {
757                kind: YaccGrammarErrorKind::UnknownEPP(_),
758                spans,
759            }) if spans.len() == 1 && spans[0] == Span::new(2, 3) => (),
760            _ => panic!("Validation error"),
761        }
762    }
763
764    #[test]
765    fn test_precedence_override() {
766        let mut grm = GrammarAST::new();
767        let empty_span = Span::new(0, 0);
768        grm.precs.insert(
769            "b".to_string(),
770            (
771                Precedence {
772                    level: 1,
773                    kind: AssocKind::Left,
774                },
775                Span::new(0, 0),
776            ),
777        );
778        grm.start = Some(("A".to_string(), empty_span));
779        grm.tokens.insert("b".to_string());
780        grm.add_rule(("A".to_string(), empty_span), None);
781        grm.add_prod(
782            "A".to_string(),
783            vec![token("b")],
784            Some("b".to_string()),
785            None,
786            empty_span,
787        );
788        assert!(grm.complete_and_validate(None).is_ok());
789    }
790
791    #[test]
792    fn test_invalid_precedence_override() {
793        let mut grm = GrammarAST::new();
794        let empty_span = Span::new(0, 0);
795        grm.start = Some(("A".to_string(), empty_span));
796        grm.add_rule(("A".to_string(), empty_span), None);
797        grm.add_prod(
798            "A".to_string(),
799            vec![token("b")],
800            Some("b".to_string()),
801            None,
802            empty_span,
803        );
804        match grm.complete_and_validate(None) {
805            Err(YaccGrammarError {
806                kind: YaccGrammarErrorKind::UnknownToken(_),
807                ..
808            }) => (),
809            _ => panic!("Validation error"),
810        }
811        grm.tokens.insert("b".to_string());
812        match grm.complete_and_validate(None) {
813            Err(YaccGrammarError {
814                kind: YaccGrammarErrorKind::NoPrecForToken(_),
815                ..
816            }) => (),
817            _ => panic!("Validation error"),
818        }
819    }
820
821    #[test]
822    fn test_ast_unused_symbols() {
823        let mut grm = GrammarAST::new();
824        let empty_span = Span::new(0, 0);
825        grm.start = Some(("A".to_string(), empty_span));
826        grm.add_rule(("A".to_string(), empty_span), None);
827        grm.add_prod("A".to_string(), vec![], None, None, empty_span);
828        grm.tokens.insert("b".to_string());
829        grm.spans.push(Span::new(4, 5));
830        grm.add_rule(("B".to_string(), Span::new(1, 2)), None);
831        grm.add_prod("B".to_string(), vec![token("b")], None, None, empty_span);
832
833        assert_eq!(
834            grm.unused_symbols()
835                .map(|sym_idx| sym_idx.symbol(&grm))
836                .collect::<Vec<Symbol>>()
837                .as_slice(),
838            &[
839                Symbol::Rule("B".to_string(), Span::new(1, 2)),
840                Symbol::Token("b".to_string(), Span::new(4, 5))
841            ]
842        )
843    }
844
845    #[test]
846    fn token_rule_confusion_issue_557() {
847        use super::*;
848        let ast_validity = ASTWithValidityInfo::new(
849            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
850            r#"
851            %start start
852            %%
853            start: "a" a;
854            a: "c";"#,
855        );
856        assert!(
857            ast_validity.ast().prods[0]
858                .symbols
859                .contains(&Symbol::Rule("a".to_string(), Span::new(64, 65)))
860        );
861        let ast_validity = ASTWithValidityInfo::new(
862            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
863            r#"
864            %start start
865            %%
866            start: "a" x;
867            x: "c";"#,
868        );
869        assert!(
870            ast_validity.ast().prods[0]
871                .symbols
872                .contains(&Symbol::Rule("x".to_string(), Span::new(64, 65)))
873        );
874        let ast_validity = ASTWithValidityInfo::new(
875            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
876            r#"
877        %start start
878        %token a
879        %%
880        start: "a" a;
881        "#,
882        );
883        assert_eq!(
884            ast_validity.ast().prods[0].symbols,
885            [
886                Symbol::Token("a".to_string(), Span::new(66, 67)),
887                Symbol::Token("a".to_string(), Span::new(69, 70))
888            ]
889        );
890    }
891
892    #[test]
893    fn test_token_directives() {
894        use super::*;
895
896        // Testing that `%token a` after `%left "a"` still ends up in
897        let ast_validity = ASTWithValidityInfo::new(
898            YaccKind::Original(YaccOriginalActionKind::GenericParseTree),
899            r#"
900                %left "a"
901                %token a
902                %start start
903                %%
904                start: "a" a "b";
905                "#,
906        );
907        assert!(
908            ast_validity
909                .ast()
910                .token_directives
911                .contains(&ast_validity.ast().tokens.get_index_of("a").unwrap())
912        );
913        assert!(
914            !ast_validity
915                .ast()
916                .token_directives
917                .contains(&ast_validity.ast().tokens.get_index_of("b").unwrap())
918        );
919    }
920
921    #[test]
922    fn clone_ast_changing_start_rule() {
923        use super::*;
924        let y_src = r#"
925        %start AStart
926        %token A B C
927        %%
928        AStart: A ':' BStart ';';
929        BStart: B ',' C | C ',' B;
930        "#;
931
932        let astart_ast_validity =
933            ASTWithValidityInfo::new(YaccKind::Original(YaccOriginalActionKind::NoAction), y_src);
934        let bstart_rule = astart_ast_validity.ast().get_rule("BStart").unwrap();
935        let bstart_ast_validity = astart_ast_validity
936            .clone_and_change_start_rule(bstart_rule.clone())
937            .unwrap();
938        assert!(astart_ast_validity.is_valid());
939        assert!(bstart_ast_validity.is_valid());
940        assert_eq!(
941            bstart_ast_validity.ast().start.as_ref(),
942            Some(&bstart_rule.name)
943        );
944    }
945
946    #[test]
947    fn test_missing_actiont() {
948        use super::*;
949        let ast_validity = ASTWithValidityInfo::new(
950            YaccKind::Original(YaccOriginalActionKind::UserAction),
951            r#"
952%token a
953%%
954start: "a";
955"#,
956        );
957        assert_eq!(
958            ast_validity.errors(),
959            vec![YaccGrammarError {
960                kind: YaccGrammarErrorKind::MissingActionType,
961                spans: vec![Span::new(13, 18)],
962            }]
963        );
964
965        let ast_validity = ASTWithValidityInfo::new(
966            YaccKind::Original(YaccOriginalActionKind::UserAction),
967            r#"
968%actiontype ()
969%token a
970%%
971start: "a" { };
972"#,
973        );
974        assert!(ast_validity.errors().is_empty());
975
976        let mut grm = GrammarAST::new();
977        let empty_span = Span::new(0, 0);
978        let rule_span = Span::new(255, 255);
979        grm.start = Some(("A".to_string(), empty_span));
980        grm.add_rule(("A".to_string(), rule_span), None);
981        grm.add_prod("A".to_string(), vec![], None, None, empty_span);
982        assert_eq!(
983            grm.complete_and_validate(Some(YaccKind::Grmtools)),
984            Err(YaccGrammarError {
985                kind: YaccGrammarErrorKind::MissingActionType,
986                spans: vec![rule_span],
987            })
988        );
989    }
990
991    #[test]
992    fn test_unrecognized_action_variable() {
993        use super::*;
994        let ast_validity = ASTWithValidityInfo::new(
995            YaccKind::Grmtools,
996            r#"
997%token a
998%%
999start -> () : "a" { $foo; };
1000"#,
1001        );
1002        assert_eq!(
1003            ast_validity.errors(),
1004            vec![YaccGrammarError {
1005                kind: YaccGrammarErrorKind::UnrecognisedActionVariable,
1006                spans: vec![Span::new(33, 37)],
1007            }]
1008        );
1009
1010        let ast_validity = ASTWithValidityInfo::new(
1011            YaccKind::Grmtools,
1012            r#"
1013%token a
1014%%
1015start -> () : "a" {$};
1016"#,
1017        );
1018        assert_eq!(
1019            ast_validity.errors(),
1020            vec![YaccGrammarError {
1021                kind: YaccGrammarErrorKind::UnrecognisedActionVariable,
1022                spans: vec![Span::new(32, 33)],
1023            }]
1024        );
1025
1026        let ast_validity = ASTWithValidityInfo::new(
1027            YaccKind::Grmtools,
1028            r#"
1029%token a
1030%%
1031start -> () : "a" {$;;;; };
1032"#,
1033        );
1034        assert_eq!(
1035            ast_validity.errors(),
1036            vec![YaccGrammarError {
1037                kind: YaccGrammarErrorKind::UnrecognisedActionVariable,
1038                spans: vec![Span::new(32, 33)],
1039            }]
1040        );
1041    }
1042
1043    #[test]
1044    fn test_grmtools_section_values() {
1045        use super::*;
1046        use crate::header::Value;
1047        let valid_test_keys: HashSet<&str> = HashSet::from_iter([
1048            "test.string",
1049            "test.vec",
1050            "test.num",
1051            "test.Negative",
1052            "test.Flag",
1053        ]);
1054        let src = r#"
1055%grmtools {
1056   yacckind: Grmtools,
1057   lrpar.recoverer: CPCTPlus,
1058   test.Flag,
1059   !test.Negative,
1060   test.string: "Foo",
1061   test.vec: ["Aaaa", "Bbbb"],
1062   test.num: 1234,
1063   test.unused: 5678
1064}
1065%token a
1066%%
1067start -> () : "a" { () };
1068"#;
1069        let ast_validity = ASTWithValidityInfo::from_str(src).unwrap();
1070        for (key, (expected_span, expected_value)) in [
1071            (
1072                "test.Flag".to_string(),
1073                (
1074                    src.find_span("test.Flag"),
1075                    Value::Bool(true, src.find_span("test.Flag")),
1076                ),
1077            ),
1078            (
1079                "test.Negative".to_string(),
1080                (
1081                    src.find_span("test.Negative"),
1082                    Value::Bool(false, src.find_span("!test.Negative")),
1083                ),
1084            ),
1085            (
1086                "test.string".to_string(),
1087                (
1088                    src.find_span("test.string"),
1089                    Value::String("Foo".to_string(), src.find_span("Foo")),
1090                ),
1091            ),
1092            (
1093                "test.vec".to_string(),
1094                (
1095                    src.find_span("test.vec"),
1096                    Value::Array(
1097                        vec![
1098                            Value::String("Aaaa".to_string(), src.find_span("Aaaa")),
1099                            Value::String("Bbbb".to_string(), src.find_span("Bbbb")),
1100                        ],
1101                        src.find_span("[\"Aaaa\", \"Bbbb\"]"),
1102                    ),
1103                ),
1104            ),
1105            (
1106                "test.num".to_string(),
1107                (
1108                    src.find_span("test.num"),
1109                    Value::Num(1234, src.find_span("1234")),
1110                ),
1111            ),
1112        ] {
1113            let value = ast_validity.header_value_get(&key);
1114            assert_eq!(value, Some((expected_span, &expected_value)));
1115        }
1116        assert_eq!(
1117            ast_validity
1118                .iter_prefix_keys("test")
1119                .filter(|(key, _)| !valid_test_keys.contains(*key))
1120                .collect::<Vec<_>>(),
1121            vec![("test.unused", src.find_span("test.unused"))]
1122        );
1123        assert_eq!(
1124            ast_validity.header_value_get("cfgrammar.yacckind"),
1125            Some((
1126                src.find_span("yacckind"),
1127                &Value::Namespaced("Grmtools".to_string(), src.find_span("Grmtools"))
1128            ))
1129        );
1130        assert!(
1131            ast_validity
1132                .iter_prefix_keys("cfgrammar")
1133                .find(|(key, _)| !CFGRAMMAR_KEYS.contains(key))
1134                .is_none()
1135        );
1136
1137        assert_eq!(
1138            ast_validity.header_value_get("lrpar.recoverer"),
1139            Some((
1140                src.find_span("lrpar.recoverer"),
1141                &Value::Namespaced("CPCTPlus".to_string(), src.find_span("CPCTPlus"))
1142            ))
1143        );
1144
1145        assert!(
1146            ast_validity
1147                .iter_prefix_keys("lrpar")
1148                .find(|(key, _)| !LRPAR_KEYS.contains(key))
1149                .is_none()
1150        );
1151
1152        let found_prefixes: HashSet<&str> = HashSet::from_iter(ast_validity.iter_prefixes());
1153        let expected_prefixes: HashSet<&str> = HashSet::from_iter(["test", "cfgrammar", "lrpar"]);
1154        assert_eq!(found_prefixes, expected_prefixes);
1155    }
1156
1157    #[test]
1158    fn test_grmtools_section_values2() {
1159        use super::*;
1160        let src = r#"
1161%grmtools {
1162   yacckind: Original(YaccOriginalActionKind::UserAction),
1163}
1164%token a
1165%actiontype ()
1166%%
1167start: "a" { () };
1168"#;
1169        let ast_validity = ASTWithValidityInfo::from_str(src).unwrap();
1170        assert_eq!(
1171            ast_validity.header_value_get("cfgrammar.yacckind"),
1172            Some((
1173                src.find_span("yacckind"),
1174                &Value::Namespaced(
1175                    "Original(YaccOriginalActionKind::UserAction)".to_string(),
1176                    src.find_span("Original(YaccOriginalActionKind::UserAction)"),
1177                ),
1178            ))
1179        );
1180        assert!(
1181            ast_validity
1182                .iter_prefix_keys("cfgrammar")
1183                .find(|(key, _)| !CFGRAMMAR_KEYS.contains(key))
1184                .is_none()
1185        );
1186    }
1187
1188    #[test]
1189    fn test_grmtools_section_values3() {
1190        use super::*;
1191        let src = r#"
1192%grmtools {
1193   yacckind: YaccKind::Original(YaccOriginalActionKind::UserAction),
1194}
1195%token a
1196%actiontype ()
1197%%
1198start: "a" { () };
1199"#;
1200        let ast_validity = ASTWithValidityInfo::from_str(src).unwrap();
1201        assert_eq!(
1202            ast_validity.header_value_get("cfgrammar.yacckind"),
1203            Some((
1204                src.find_span("yacckind"),
1205                &Value::Namespaced(
1206                    "YaccKind::Original(YaccOriginalActionKind::UserAction)".to_string(),
1207                    src.find_span("YaccKind::Original(YaccOriginalActionKind::UserAction)"),
1208                ),
1209            ))
1210        );
1211        assert!(
1212            ast_validity
1213                .iter_prefix_keys("cfgrammar")
1214                .find(|(key, _)| !CFGRAMMAR_KEYS.contains(key))
1215                .is_none()
1216        );
1217    }
1218
1219    #[test]
1220    fn test_grmtools_section_values4() {
1221        use super::*;
1222        let src = r#"
1223%grmtools {
1224   yacckind: YaccKind::Original(UserAction),
1225}
1226%token a
1227%actiontype ()
1228%%
1229start: "a" { () };
1230"#;
1231        let ast_validity = ASTWithValidityInfo::from_str(src).unwrap();
1232        assert_eq!(
1233            ast_validity.header_value_get("cfgrammar.yacckind"),
1234            Some((
1235                src.find_span("yacckind"),
1236                &Value::Namespaced(
1237                    "YaccKind::Original(UserAction)".to_string(),
1238                    src.find_span("YaccKind::Original(UserAction)"),
1239                ),
1240            ))
1241        );
1242        assert!(
1243            ast_validity
1244                .iter_prefix_keys("cfgrammar")
1245                .find(|(key, _)| !CFGRAMMAR_KEYS.contains(key))
1246                .is_none()
1247        );
1248    }
1249}