Skip to main content

lrpar/
codegen.rs

1use std::{
2    any::type_name,
3    collections::HashSet,
4    fmt::{self, Write},
5    hash::Hash,
6    marker::PhantomData,
7    path::Path,
8};
9
10use crate::{
11    LexerTypes, RecoveryKind, RustEdition, SerialisationFormat, Visibility,
12    ctbuilder::{FixIntConfig, VarIntConfig},
13};
14
15use cfgrammar::{
16    RIdx, Span, Symbol,
17    header::{CFGRAMMAR_KEYS, GrmtoolsSectionParser, Header, HeaderError, HeaderValue, LRPAR_KEYS},
18    yacc::{
19        YaccGrammar, YaccGrammarError, YaccKind, YaccOriginalActionKind, ast::ASTWithValidityInfo,
20    },
21};
22
23use lrtable::{Minimiser, StateGraph, StateTable, StateTableError, from_yacc};
24use proc_macro2::{Literal, TokenStream};
25use quote::{ToTokens, TokenStreamExt, format_ident, quote};
26use syn::{Generics, parse_quote};
27use wincode::SchemaWrite;
28
29const ACTION_PREFIX: &str = "__gt_";
30const GLOBAL_PREFIX: &str = "__GT_";
31const ACTIONS_KIND: &str = "__GtActionsKind";
32const ACTIONS_KIND_PREFIX: &str = "Ak";
33const ACTIONS_KIND_HIDDEN: &str = "__GtActionsKindHidden";
34
35#[derive(Debug)]
36#[non_exhaustive]
37pub(crate) enum ParserSrcEnvError {
38    GrmtoolsSectionParseError(Vec<HeaderError<Span>>),
39    GrmtoolsSectionLookupError(HeaderError<Span>),
40    MissingYaccKind,
41    MissingModName,
42}
43
44#[derive(Debug)]
45#[non_exhaustive]
46pub(crate) enum ParserBuildEnvError<LexerTypesT>
47where
48    LexerTypesT: LexerTypes,
49    usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
50{
51    StateTableError(StateTableError<LexerTypesT::StorageT>),
52    YaccGrammarErrors(Vec<YaccGrammarError>),
53    GrmtoolsSectionUnusedKeys(Vec<(String, Span)>),
54    DuplicatePrefixRegistrationError(String),
55}
56
57#[derive(Debug)]
58#[non_exhaustive]
59pub(crate) enum CodegenError {
60    ProcMacro2Error(proc_macro2::LexError),
61    InvalidRustIdentifierModName(syn::Error, String),
62    InvalidParseGenerics(syn::Error),
63    WincodeError(wincode::WriteError),
64}
65
66impl From<Vec<HeaderError<Span>>> for ParserSrcEnvError {
67    fn from(it: Vec<HeaderError<Span>>) -> Self {
68        ParserSrcEnvError::GrmtoolsSectionParseError(it)
69    }
70}
71
72impl From<HeaderError<Span>> for ParserSrcEnvError {
73    fn from(it: HeaderError<Span>) -> Self {
74        ParserSrcEnvError::GrmtoolsSectionLookupError(it)
75    }
76}
77
78impl<LexerTypesT> From<Vec<YaccGrammarError>> for ParserBuildEnvError<LexerTypesT>
79where
80    LexerTypesT: LexerTypes,
81    usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
82{
83    fn from(it: Vec<YaccGrammarError>) -> Self {
84        ParserBuildEnvError::YaccGrammarErrors(it)
85    }
86}
87
88impl<LexerTypesT> From<StateTableError<LexerTypesT::StorageT>> for ParserBuildEnvError<LexerTypesT>
89where
90    LexerTypesT: LexerTypes,
91    usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
92{
93    fn from(it: StateTableError<LexerTypesT::StorageT>) -> Self {
94        ParserBuildEnvError::StateTableError(it)
95    }
96}
97
98impl From<proc_macro2::LexError> for CodegenError {
99    fn from(it: proc_macro2::LexError) -> Self {
100        CodegenError::ProcMacro2Error(it)
101    }
102}
103
104impl From<wincode::WriteError> for CodegenError {
105    fn from(it: wincode::WriteError) -> Self {
106        CodegenError::WincodeError(it)
107    }
108}
109
110impl fmt::Display for ParserSrcEnvError {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        f.write_str(&match self {
113            Self::GrmtoolsSectionParseError(errs) => errs
114                .iter()
115                .map(|e| e.to_string())
116                .collect::<Vec<_>>()
117                .join("\n"),
118            Self::GrmtoolsSectionLookupError(e) => e.to_string(),
119            Self::MissingYaccKind => "Code generator cannot resolve yacc kind".to_string(),
120            Self::MissingModName => "Code generator requires a mod name".to_string(),
121        })
122    }
123}
124
125impl<LexerTypesT> fmt::Display for ParserBuildEnvError<LexerTypesT>
126where
127    LexerTypesT: LexerTypes,
128    usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
129{
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        f.write_str(&match self {
132            Self::StateTableError(e) => format!("{}", e).to_string(),
133            Self::YaccGrammarErrors(errs) => errs
134                .iter()
135                .map(|e| e.to_string())
136                .collect::<Vec<_>>()
137                .join("\n"),
138            Self::GrmtoolsSectionUnusedKeys(keys) => {
139                let keys = keys.iter().cloned().map(|(s, _)| s).collect::<Vec<_>>();
140                format!("Unused keys in %grmtools section: {}", keys.join(", "))
141            }
142            Self::DuplicatePrefixRegistrationError(prefix) => {
143                format!("Registered duplicate prefix: \"{prefix}\"")
144            }
145        })
146    }
147}
148impl fmt::Display for CodegenError {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        f.write_str(&match self {
151            Self::ProcMacro2Error(e) => e.to_string(),
152            Self::InvalidRustIdentifierModName(e, s) => format!(
153                "mod_name '{}' is not a valid rust identifier due to '{}'",
154                s, e
155            ),
156            Self::InvalidParseGenerics(e) => format!("Unable to parse %parse-generics '{e}'"),
157            Self::WincodeError(e) => format!("Unable to serialize parser {e}"),
158        })
159    }
160}
161
162pub(crate) struct ParserSrcEnv<'a, LexerTypesT>
163where
164    LexerTypesT: LexerTypes,
165    usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
166{
167    src: &'a str,
168    fallback_modname: Option<String>,
169    grammar_path_cache_entry: Option<String>,
170    yacckind: Option<YaccKind>,
171    recoverer: Option<RecoveryKind>,
172    phantom: PhantomData<LexerTypesT::StorageT>,
173}
174
175pub(crate) struct ParserBuildEnvArgs<'a> {
176    /// If the input came from a preparsed AST, this will be Some
177    ast_with_validity_info: Option<&'a ASTWithValidityInfo>,
178    mod_name: Option<String>,
179    rust_edition: RustEdition,
180    visibility: Visibility,
181    error_on_conflicts: bool,
182    show_warnings: bool,
183    warnings_are_errors: bool,
184}
185
186pub(crate) struct ParserBuildEnv<'a, LexerTypesT>
187where
188    LexerTypesT: LexerTypes,
189    usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
190{
191    ast_with_validity_info: ASTWithValidityInfo,
192    recoverer: RecoveryKind,
193    serialisation_format: SerialisationFormat,
194    // Preserve the args for generating the cache.
195    cache_args: ParserBuildEnvArgs<'a>,
196    phantom_storaget: PhantomData<LexerTypesT::StorageT>,
197    mod_name: String,
198    grammar_path: Option<String>,
199    registered_prefixes: HashSet<String>,
200}
201
202pub(crate) struct ParserCodegen<LexerTypesT>
203where
204    LexerTypesT: LexerTypes,
205    usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
206{
207    grm: YaccGrammar<LexerTypesT::StorageT>,
208    stable: StateTable<LexerTypesT::StorageT>,
209    sgraph: StateGraph<LexerTypesT::StorageT>,
210    timestamp: String,
211}
212
213impl<'a> ParserBuildEnvArgs<'a> {
214    pub(crate) fn new() -> Self {
215        ParserBuildEnvArgs {
216            ast_with_validity_info: None,
217            mod_name: None,
218            visibility: Visibility::Private,
219            rust_edition: RustEdition::Rust2021,
220            error_on_conflicts: true,
221            show_warnings: true,
222            warnings_are_errors: true,
223        }
224    }
225
226    /// Set this to `Some(ast)` if the the parser should be built from a pre-parsed AST
227    /// instead of from parsing a source string.
228    pub(crate) fn ast_with_validity_info(mut self, ast: Option<&'a ASTWithValidityInfo>) -> Self {
229        self.ast_with_validity_info = ast;
230        self
231    }
232
233    pub(crate) fn mod_name(mut self, mod_name: Option<&str>) -> Self {
234        self.mod_name = mod_name.map(|s| s.to_string());
235        self
236    }
237
238    pub(crate) fn rust_edition(mut self, rust_edition: RustEdition) -> Self {
239        self.rust_edition = rust_edition;
240        self
241    }
242    pub(crate) fn visibility(mut self, visibility: Visibility) -> Self {
243        self.visibility = visibility;
244        self
245    }
246    pub(crate) fn error_on_conflicts(mut self, error_on_conflicts: bool) -> Self {
247        self.error_on_conflicts = error_on_conflicts;
248        self
249    }
250    pub(crate) fn show_warnings(mut self, show_warnings: bool) -> Self {
251        self.show_warnings = show_warnings;
252        self
253    }
254    pub(crate) fn warnings_are_errors(mut self, warnings_are_errors: bool) -> Self {
255        self.warnings_are_errors = warnings_are_errors;
256        self
257    }
258}
259
260impl<'a, LexerTypesT> ParserSrcEnv<'a, LexerTypesT>
261where
262    LexerTypesT: LexerTypes,
263    usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
264{
265    pub(crate) fn new(src: &'a str, path: Option<&Path>) -> ParserSrcEnv<'a, LexerTypesT> {
266        let fallback_modname = if let Some(path) = path {
267            // When the user hasn't specified a module name, so we create one automatically: what we
268            // do is strip off all the filename extensions (note that it's likely that inp ends
269            // with `y.rs`, so we potentially have to strip off more than one extension) and
270            // then add `_y` to the end.
271            let mut stem = path.to_str().unwrap();
272            loop {
273                let new_stem = Path::new(stem).file_stem().unwrap().to_str().unwrap();
274                if stem == new_stem {
275                    break;
276                }
277                stem = new_stem;
278            }
279            Some(format!("{}_y", stem))
280        } else {
281            None
282        };
283        let grammar_path_cache_entry = path.map(|s| s.to_string_lossy().to_string());
284        ParserSrcEnv {
285            src,
286            fallback_modname,
287            grammar_path_cache_entry,
288            phantom: PhantomData,
289            recoverer: None,
290            yacckind: None,
291        }
292    }
293
294    pub(crate) fn yacckind(mut self, yacckind: Option<YaccKind>) -> Self {
295        self.yacckind = yacckind;
296        self
297    }
298
299    pub(crate) fn recoverer(mut self, recoverykind: Option<RecoveryKind>) -> Self {
300        self.recoverer = recoverykind;
301        self
302    }
303
304    /// Looks up the `yacckind` field from the header, marks the field
305    /// as used then constructs AST of that kind.
306    fn resolve_ast_with_validity_info(
307        &mut self,
308        from_ast: Option<&ASTWithValidityInfo>,
309        header: &Header<Span>,
310    ) -> Result<ASTWithValidityInfo, ParserSrcEnvError> {
311        if let Some(ast) = from_ast {
312            Ok(ast.clone())
313        } else if let Some(yk) = self.yacckind {
314            Ok(ASTWithValidityInfo::new(yk, self.src))
315        } else if let Some(yk) = header
316            .get("cfgrammar.yacckind")
317            .map(|HeaderValue(_, val)| val)
318            .map(YaccKind::try_from)
319            .transpose()?
320        {
321            Ok(ASTWithValidityInfo::new(yk, self.src))
322        } else {
323            Err(ParserSrcEnvError::MissingYaccKind)?
324        }
325    }
326
327    /// Looks up the `recoverer` field in the header, marks the field
328    /// as used, and defaulting to `CPCTPlus` if unfound.
329    fn resolve_recoverer(
330        &mut self,
331        header: &Header<Span>,
332    ) -> Result<RecoveryKind, ParserSrcEnvError> {
333        let rk_val = header
334            .get("lrpar.recoverer")
335            .map(|HeaderValue(_, rk_val)| rk_val);
336        if let Some(rk) = self.recoverer {
337            Ok(rk)
338        } else if let Some(rk_val) = rk_val {
339            Ok(RecoveryKind::try_from(rk_val)?)
340        } else {
341            // Fallback to the default recoverykind.
342            Ok(RecoveryKind::CPCTPlus)
343        }
344    }
345
346    /// Looks up the `serialisation_format` field in the header, marks the field
347    /// as used, and defaults to `VariableSizedInteger` if unfound.
348    fn resolve_serialisation_format(
349        &mut self,
350        header: &Header<Span>,
351    ) -> Result<SerialisationFormat, ParserSrcEnvError> {
352        if let Some(ec_val) = header
353            .get("lrpar.serialisation_format")
354            .map(|HeaderValue(_, ec_val)| ec_val)
355        {
356            Ok(SerialisationFormat::try_from(ec_val)?)
357        } else {
358            Ok(SerialisationFormat::VariableSizedInteger)
359        }
360    }
361
362    /// Looks up the `mod_name` from the `args`, and defaults to
363    /// the `{filename}_y` with any file extenstion stripped off.
364    fn resolve_mod_name(&self, args: &ParserBuildEnvArgs) -> Result<String, ParserSrcEnvError> {
365        match &args.mod_name {
366            Some(s) => Ok(s.to_owned()),
367            None => self
368                .fallback_modname
369                .as_ref()
370                .ok_or(ParserSrcEnvError::MissingModName)
371                .map(|s| s.to_string()),
372        }
373    }
374
375    pub(crate) fn build_env(
376        mut self,
377        args: ParserBuildEnvArgs<'a>,
378    ) -> Result<ParserBuildEnv<'a, LexerTypesT>, ParserSrcEnvError>
379    where
380        LexerTypesT: LexerTypes,
381        usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
382    {
383        let (header, _) = GrmtoolsSectionParser::new(self.src, false).parse()?;
384        let ast_with_validity_info =
385            self.resolve_ast_with_validity_info(args.ast_with_validity_info, &header)?;
386        let recoverer = self.resolve_recoverer(&header)?;
387        let serialisation_format = self.resolve_serialisation_format(&header)?;
388        let mod_name = self.resolve_mod_name(&args)?;
389
390        let mut build_env = ParserBuildEnv {
391            ast_with_validity_info,
392            cache_args: args,
393            registered_prefixes: HashSet::new(),
394            recoverer,
395            serialisation_format,
396            mod_name,
397            grammar_path: self.grammar_path_cache_entry,
398            phantom_storaget: PhantomData,
399        };
400        build_env.register_prefix("cfgrammar").expect("unreachable");
401        build_env.register_prefix("lrpar").expect("unreachable");
402        Ok(build_env)
403    }
404}
405
406impl<'a, LexerTypesT> ParserBuildEnv<'a, LexerTypesT>
407where
408    LexerTypesT: LexerTypes,
409    usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
410{
411    pub(crate) fn ast_with_validity_info(&self) -> &ASTWithValidityInfo {
412        &self.ast_with_validity_info
413    }
414
415    pub(crate) fn serialisation_format(&self) -> &SerialisationFormat {
416        &self.serialisation_format
417    }
418
419    pub(crate) fn derived_mod_name(&self) -> &str {
420        &self.mod_name
421    }
422
423    pub(crate) fn specified_mod_name(&self) -> Option<&str> {
424        self.cache_args.mod_name.as_deref()
425    }
426
427    pub(crate) fn recoverer(&self) -> RecoveryKind {
428        self.recoverer
429    }
430
431    pub(crate) fn rust_edition(&self) -> RustEdition {
432        self.cache_args.rust_edition
433    }
434
435    pub(crate) fn visibility(&self) -> &Visibility {
436        &self.cache_args.visibility
437    }
438
439    pub(crate) fn show_warnings(&self) -> bool {
440        self.cache_args.show_warnings
441    }
442
443    pub(crate) fn warnings_are_errors(&self) -> bool {
444        self.cache_args.warnings_are_errors
445    }
446
447    pub(crate) fn error_on_conflicts(&self) -> bool {
448        self.cache_args.error_on_conflicts
449    }
450
451    pub(crate) fn yacc_kind(&self) -> YaccKind {
452        self.ast_with_validity_info.yacc_kind()
453    }
454
455    /// Adds the `crate_prefix` to the list of registered prefixes.
456    /// The intent is that the user can check the registered keys against `ast_with_validity_info.iter_prefixes()`
457    /// So that all the values in `ast_with_validity_info.iter_prefixes()` are also in `self.registered_header_prefixes()`
458    /// for example
459    ///
460    /// ```ignore
461    /// let prefixes_set = HashSet::from_iter(build_env.ast_with_validity_info().iter_prefixes());
462    /// let registered_set = HashSet::from_iter(build_env.registered_header_prefixes());
463    /// assert!(prefixes_set.difference(registered_set).next().is_none())
464    /// ```
465    pub(crate) fn register_prefix(
466        &mut self,
467        crate_prefix: &str,
468    ) -> Result<(), ParserBuildEnvError<LexerTypesT>> {
469        if !self.registered_prefixes.insert(crate_prefix.to_string()) {
470            Err(ParserBuildEnvError::DuplicatePrefixRegistrationError(
471                crate_prefix.to_string(),
472            ))
473        } else {
474            Ok(())
475        }
476    }
477
478    /// Returns the unique set of key prefixes that have been registered by calling `register_header_prefix`.
479    #[allow(unused)]
480    pub(crate) fn registered_prefixes(&self) -> impl Iterator<Item = &str> {
481        self.registered_prefixes.iter().map(|s| s.as_str())
482    }
483
484    /// Checks all the keys staring with `crate_prefixes`. If any of them are `unused`, return an error.
485    /// If `crate_prefixes` contains the empty string, returns an arror if any key is unused.
486    fn check_unused_grmtools_header_values(&self) -> Result<(), ParserBuildEnvError<LexerTypesT>> {
487        let mut unrecognized_keys = Vec::new();
488        unrecognized_keys.extend(
489            self.ast_with_validity_info()
490                .iter_prefix_keys("cfgrammar")
491                .filter(|(key, _)| !CFGRAMMAR_KEYS.contains(key))
492                .map(|(s, span)| (s.to_string(), span)),
493        );
494        unrecognized_keys.extend(
495            self.ast_with_validity_info()
496                .iter_prefix_keys("lrpar")
497                .filter(|(key, _)| !LRPAR_KEYS.contains(key))
498                .map(|(s, span)| (s.to_string(), span)),
499        );
500        if !unrecognized_keys.is_empty() {
501            return Err(ParserBuildEnvError::GrmtoolsSectionUnusedKeys(
502                unrecognized_keys,
503            ));
504        }
505        Ok(())
506    }
507
508    pub(crate) fn code_generator(
509        &self,
510        timestamp: &str,
511    ) -> Result<ParserCodegen<LexerTypesT>, ParserBuildEnvError<LexerTypesT>> {
512        self.check_unused_grmtools_header_values()?;
513        let grm = YaccGrammar::<LexerTypesT::StorageT>::new_from_ast_with_validity_info(
514            &self.ast_with_validity_info,
515        )?;
516        let (sgraph, stable) = from_yacc(&grm, Minimiser::Pager)?;
517        Ok(ParserCodegen {
518            grm,
519            stable,
520            sgraph,
521            timestamp: timestamp.to_string(),
522        })
523    }
524}
525
526impl<LexerTypesT> ParserCodegen<LexerTypesT>
527where
528    LexerTypesT: LexerTypes,
529    usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
530    LexerTypesT::StorageT: 'static
531        + fmt::Debug
532        + Hash
533        + num_traits::PrimInt
534        + SchemaWrite<FixIntConfig, Src = LexerTypesT::StorageT>
535        + SchemaWrite<VarIntConfig, Src = LexerTypesT::StorageT>
536        + num_traits::Unsigned,
537    LexerTypesT: LexerTypes,
538{
539    pub(crate) fn grm(&self) -> &YaccGrammar<LexerTypesT::StorageT> {
540        &self.grm
541    }
542
543    pub(crate) fn stable(&self) -> &StateTable<LexerTypesT::StorageT> {
544        &self.stable
545    }
546
547    pub(crate) fn sgraph(&self) -> &StateGraph<LexerTypesT::StorageT> {
548        &self.sgraph
549    }
550
551    pub(crate) fn finish(
552        self,
553    ) -> (
554        YaccGrammar<LexerTypesT::StorageT>,
555        StateGraph<LexerTypesT::StorageT>,
556        StateTable<LexerTypesT::StorageT>,
557    ) {
558        (self.grm, self.sgraph, self.stable)
559    }
560
561    pub(crate) fn generate(
562        &self,
563        build_env: &ParserBuildEnv<LexerTypesT>,
564    ) -> Result<String, CodegenError> {
565        let mod_name = build_env.derived_mod_name();
566        let visibility = build_env.visibility();
567        let user_actions = if let YaccKind::Original(YaccOriginalActionKind::UserAction)
568        | YaccKind::Grmtools = build_env.yacc_kind()
569        {
570            Some(self.gen_user_actions()?)
571        } else {
572            None
573        };
574        let rule_consts = self.gen_rule_consts()?;
575        let token_epp = self.gen_token_epp()?;
576        let parse_function = self.gen_parse_function(build_env)?;
577        let action_wrappers = match build_env.yacc_kind() {
578            YaccKind::Original(YaccOriginalActionKind::UserAction) | YaccKind::Grmtools => {
579                Some(self.gen_wrappers(build_env)?)
580            }
581            YaccKind::Original(YaccOriginalActionKind::NoAction)
582            | YaccKind::Original(YaccOriginalActionKind::GenericParseTree) => None,
583            _ => unreachable!(),
584        };
585
586        let additional_decls = if let YaccKind::Original(YaccOriginalActionKind::GenericParseTree) =
587            build_env.yacc_kind()
588        {
589            // `lrpar::Node`` is deprecated within the lrpar crate, but not from within this module,
590            // Once it is removed from `lrpar`, we should move the declaration here entirely.
591            Some(quote! {
592                #[allow(unused_imports)]
593                pub use ::lrpar::parser::_deprecated_moved_::Node;
594            })
595        } else {
596            None
597        };
598
599        let mod_name = match syn::parse_str::<proc_macro2::Ident>(mod_name) {
600            Ok(s) => s,
601            Err(e) => {
602                return Err(CodegenError::InvalidRustIdentifierModName(
603                    e,
604                    mod_name.to_string(),
605                ));
606            }
607        };
608        let out_tokens = quote! {
609            #visibility mod #mod_name {
610                // At the top so that `user_actions` may contain #![inner_attribute]
611                #user_actions
612                mod _parser_ {
613                    #![allow(clippy::type_complexity)]
614                    #![allow(clippy::unnecessary_wraps)]
615                    #![deny(unsafe_code)]
616                    #[allow(unused_imports)]
617                    use super::*;
618                    #additional_decls
619                    #parse_function
620                    #rule_consts
621                    #token_epp
622                    #action_wrappers
623                } // End of `mod _parser_`
624                #[allow(unused_imports)]
625                pub use _parser_::*;
626                #[allow(unused_imports)]
627                use ::lrpar::Lexeme;
628            } // End of `mod #mod_name`
629        };
630        // Try and run a code formatter on the generated code.
631        let unformatted = out_tokens.to_string();
632        Ok(syn::parse_str(&unformatted)
633            .map(|syntax_tree| prettyplease::unparse(&syntax_tree))
634            .unwrap_or(unformatted))
635    }
636
637    /// Generate the cache, which determines if anything's changed enough that we need to
638    /// regenerate outputs and force rustc to recompile.
639    fn gen_cache(&self, build_env: &ParserBuildEnv<LexerTypesT>) -> TokenStream {
640        let grm = self.grm();
641        let build_time = &self.timestamp;
642        let grammar_path = &build_env.grammar_path;
643        let mod_name = QuoteOption(build_env.specified_mod_name());
644        let visibility = build_env.visibility().to_variant_tokens();
645        let rust_edition = build_env.rust_edition().to_variant_tokens();
646        let yacckind = build_env.yacc_kind();
647        let rule_map = grm
648            .iter_tidxs()
649            .map(|tidx| {
650                QuoteTuple((
651                    usize::from(tidx),
652                    grm.token_name(tidx).unwrap_or("<unknown>"),
653                ))
654            })
655            .collect::<Vec<_>>();
656        let derived_mod_name = build_env.derived_mod_name();
657        let serialisation_format = build_env.serialisation_format();
658        let recoverer = build_env.recoverer();
659        let error_on_conflicts = build_env.error_on_conflicts();
660        let show_warnings = build_env.show_warnings();
661        let warnings_are_errors = build_env.warnings_are_errors();
662        let cache_info = quote! {
663            BUILD_TIME = #build_time
664            DERIVED_MOD_NAME = #derived_mod_name
665            ENCODING_CONFIG = #serialisation_format
666            GRAMMAR_PATH = #grammar_path
667            MOD_NAME = #mod_name
668            RECOVERER = #recoverer
669            YACC_KIND = #yacckind
670            ERROR_ON_CONFLICTS = #error_on_conflicts
671            SHOW_WARNINGS = #show_warnings
672            WARNINGS_ARE_ERRORS = #warnings_are_errors
673            RUST_EDITION = #rust_edition
674            RULE_IDS_MAP = [#(#rule_map,)*]
675            VISIBILITY = #visibility
676        };
677        let cache_info_str = cache_info.to_string();
678        quote!(#cache_info_str)
679    }
680
681    pub(crate) fn cache_str(&self, build_env: &ParserBuildEnv<LexerTypesT>) -> String {
682        self.gen_cache(build_env).to_string()
683    }
684
685    /// Generate the user action functions (if any).
686    fn gen_user_actions(&self) -> Result<TokenStream, CodegenError> {
687        let grm = self.grm();
688        let programs = grm
689            .programs()
690            .as_ref()
691            .map(|s| str::parse::<TokenStream>(s))
692            .transpose()?;
693        let mut action_fns = TokenStream::new();
694        // Convert actions to functions
695        let parsed_parse_generics = make_generics(grm.parse_generics().as_deref())?;
696        let (generics, _, where_clause) = parsed_parse_generics.split_for_impl();
697        let (parse_paramname, parse_paramdef, parse_param_unit);
698        match grm.parse_param() {
699            Some((name, tyname)) => {
700                parse_param_unit = tyname.trim() == "()";
701                parse_paramname = str::parse::<TokenStream>(name)?;
702                let ty = str::parse::<TokenStream>(tyname)?;
703                parse_paramdef = quote!(#parse_paramname: #ty);
704            }
705            None => {
706                parse_param_unit = true;
707                parse_paramname = quote!(());
708                parse_paramdef = quote! {_: ()};
709            }
710        };
711        for pidx in grm.iter_pidxs() {
712            if pidx == grm.start_prod() {
713                continue;
714            }
715
716            // Work out the right type for each argument
717            let mut args = Vec::with_capacity(grm.prod(pidx).len());
718            for i in 0..grm.prod(pidx).len() {
719                let argt = match grm.prod(pidx)[i] {
720                    Symbol::Rule(ref_ridx) => {
721                        let action_type = grm.actiontype(ref_ridx)
722                           .as_ref()
723                           .expect("actiontype should have been checked during complete_and_validate for this YaccKind");
724                        str::parse::<TokenStream>(action_type)?
725                    }
726                    Symbol::Token(_) => {
727                        let lexemet =
728                            str::parse::<TokenStream>(type_name::<LexerTypesT::LexemeT>())?;
729                        quote!(::std::result::Result<#lexemet, #lexemet>)
730                    }
731                };
732                let arg = format_ident!("{}arg_{}", ACTION_PREFIX, i + 1);
733                args.push(quote!(mut #arg: #argt));
734            }
735
736            // If this rule's `actiont` is `()` then Clippy will warn that the return type `-> ()`
737            // is pointless (which is true). We therefore avoid outputting a return type if actiont
738            // is the unit type.
739            let returnt = {
740                let actiont = grm.actiontype(grm.prod_to_rule(pidx)).as_ref().unwrap();
741                if actiont == "()" {
742                    None
743                } else {
744                    let actiont = str::parse::<TokenStream>(actiont)?;
745                    Some(quote!( -> #actiont))
746                }
747            };
748            let action_fn = format_ident!("{}action_{}", ACTION_PREFIX, usize::from(pidx));
749            let lexer_var = format_ident!("{}lexer", ACTION_PREFIX);
750            let span_var = format_ident!("{}span", ACTION_PREFIX);
751            let ridx_var = format_ident!("{}ridx", ACTION_PREFIX);
752            let storaget = str::parse::<TokenStream>(type_name::<LexerTypesT::StorageT>())?;
753            let lexertypest = str::parse::<TokenStream>(type_name::<LexerTypesT>())?;
754            let bind_parse_param = if !parse_param_unit {
755                Some(quote! {let _ = #parse_paramname;})
756            } else {
757                None
758            };
759
760            // Iterate over all $-arguments and replace them with their respective
761            // element from the argument vector (e.g. $1 is replaced by args[0]).
762            let pre_action = grm.action(pidx).as_ref().expect("action code should have been checked during complete_and_validate for this YaccKind");
763            let mut last = 0;
764            let mut outs = String::new();
765            loop {
766                match pre_action[last..].find('$') {
767                    Some(off) => {
768                        if pre_action[last + off..].starts_with("$$") {
769                            outs.push_str(&pre_action[last..last + off + "$".len()]);
770                            last = last + off + "$$".len();
771                        } else if pre_action[last + off..].starts_with("$lexer") {
772                            outs.push_str(&pre_action[last..last + off]);
773                            write!(outs, "{prefix}lexer", prefix = ACTION_PREFIX).ok();
774                            last = last + off + "$lexer".len();
775                        } else if pre_action[last + off..].starts_with("$span") {
776                            outs.push_str(&pre_action[last..last + off]);
777                            write!(outs, "{prefix}span", prefix = ACTION_PREFIX).ok();
778                            last = last + off + "$span".len();
779                        } else if last + off + 1 < pre_action.len()
780                            && pre_action[last + off + 1..].starts_with(|c: char| c.is_numeric())
781                        {
782                            outs.push_str(&pre_action[last..last + off]);
783                            write!(outs, "{prefix}arg_", prefix = ACTION_PREFIX).ok();
784                            last = last + off + "$".len();
785                        } else {
786                            unreachable!("action variables checked during complete_and_validate");
787                        }
788                    }
789                    None => {
790                        outs.push_str(&pre_action[last..]);
791                        break;
792                    }
793                }
794            }
795
796            let action_body = str::parse::<TokenStream>(&outs)?;
797            action_fns.extend(quote! {
798                #[allow(clippy::too_many_arguments)]
799                fn #action_fn #generics (
800                    #ridx_var: ::cfgrammar::RIdx<#storaget>,
801                    #lexer_var: &'lexer dyn ::lrpar::NonStreamingLexer<'input, #lexertypest>,
802                    #span_var: ::cfgrammar::Span,
803                    #parse_paramdef,
804                    #(#args,)*
805                ) #returnt
806                #where_clause
807                {
808                    #bind_parse_param
809                    #action_body
810                }
811            })
812        }
813        Ok(quote! {
814            #programs
815            #action_fns
816        })
817    }
818
819    fn gen_rule_consts(&self) -> Result<TokenStream, proc_macro2::LexError> {
820        let grm = self.grm();
821        let mut toks = TokenStream::new();
822        for ridx in grm.iter_rules() {
823            if !grm.rule_to_prods(ridx).contains(&grm.start_prod()) {
824                let r_const = format_ident!("R_{}", grm.rule_name_str(ridx).to_ascii_uppercase());
825                let storage_ty = str::parse::<TokenStream>(type_name::<LexerTypesT::StorageT>())?;
826                let ridx = UnsuffixedUsize(usize::from(ridx));
827                toks.extend(quote! {
828                    #[allow(dead_code)]
829                    pub const #r_const: #storage_ty = #ridx;
830                });
831            }
832        }
833        Ok(toks)
834    }
835
836    fn gen_token_epp(&self) -> Result<TokenStream, proc_macro2::LexError> {
837        let grm = self.grm();
838        let mut tidxs = Vec::new();
839        for tidx in grm.iter_tidxs() {
840            tidxs.push(QuoteOption(grm.token_epp(tidx)));
841        }
842        let const_epp_ident = format_ident!("{}EPP", GLOBAL_PREFIX);
843        let storage_ty = str::parse::<TokenStream>(type_name::<LexerTypesT::StorageT>())?;
844        Ok(quote! {
845            const #const_epp_ident: &[::std::option::Option<&str>] = &[
846                #(#tidxs,)*
847            ];
848
849            /// Return the %epp entry for token `tidx` (where `None` indicates \"the token has no
850            /// pretty-printed value\"). Panics if `tidx` doesn't exist.
851            #[allow(dead_code)]
852            pub fn token_epp<'a>(tidx: ::cfgrammar::TIdx<#storage_ty>) -> ::std::option::Option<&'a str> {
853                #const_epp_ident[usize::from(tidx)]
854            }
855        })
856    }
857
858    /// Generate the main parse() function for the output file.
859    fn gen_parse_function(
860        &self,
861        build_env: &ParserBuildEnv<LexerTypesT>,
862    ) -> Result<TokenStream, CodegenError> {
863        let stable = self.stable();
864        let grm = self.grm();
865        let storaget = str::parse::<TokenStream>(type_name::<LexerTypesT::StorageT>())?;
866        let lexertypest = str::parse::<TokenStream>(type_name::<LexerTypesT>())?;
867        let recoverer = build_env.recoverer();
868        let run_parser = match build_env.yacc_kind() {
869            YaccKind::Original(YaccOriginalActionKind::GenericParseTree) => {
870                quote! {
871                    ::lrpar::RTParserBuilder::new(grm, stable)
872                        .recoverer(#recoverer)
873                        .parse_map(
874                            lexer,
875                            &|lexeme| Node::Term{lexeme},
876                            &|ridx, nodes| Node::Nonterm{ridx, nodes}
877                        )
878                }
879            }
880            YaccKind::Original(YaccOriginalActionKind::NoAction) => {
881                quote! {
882                    ::lrpar::RTParserBuilder::new(grm, stable)
883                        .recoverer(#recoverer)
884                        .parse_map(lexer, &|_| (), &|_, _| ()).1
885                }
886            }
887            YaccKind::Original(YaccOriginalActionKind::UserAction) | YaccKind::Grmtools => {
888                let actionskind = str::parse::<TokenStream>(ACTIONS_KIND)?;
889                let parsed_parse_generics = make_generics(grm.parse_generics().as_deref())?;
890                let (_, type_generics, _) = parsed_parse_generics.split_for_impl();
891                // actions always have a parse_param argument, and when the `parse` function lacks one
892                // that parameter will be unit.
893                let (action_fn_parse_param, action_fn_parse_param_ty) = match grm.parse_param() {
894                    Some((name, ty)) => {
895                        let name = str::parse::<TokenStream>(name)?;
896                        let ty = str::parse::<TokenStream>(ty)?;
897                        (quote!(#name), quote!(#ty))
898                    }
899                    None => (quote!(()), quote!(())),
900                };
901                let wrappers = grm.iter_pidxs().map(|pidx| {
902                    let pidx = usize::from(pidx);
903                    format_ident!("{}wrapper_{}", ACTION_PREFIX, pidx)
904                });
905                let edition_lifetime = if build_env.rust_edition() != RustEdition::Rust2015 {
906                    quote!('_,)
907                } else {
908                    quote!()
909                };
910                let ridx = usize::from(self.user_start_ridx());
911                let action_ident = format_ident!("{}{}", ACTIONS_KIND_PREFIX, ridx);
912
913                quote! {
914                    let actions: ::std::vec::Vec<
915                            &dyn Fn(
916                                    ::cfgrammar::RIdx<#storaget>,
917                                    &'lexer dyn ::lrpar::NonStreamingLexer<'input, #lexertypest>,
918                                    ::cfgrammar::Span,
919                                    ::std::vec::Drain<#edition_lifetime ::lrpar::parser::AStackType<<#lexertypest as ::lrpar::LexerTypes>::LexemeT, #actionskind #type_generics>>,
920                                    #action_fn_parse_param_ty
921                            ) -> #actionskind #type_generics
922                        > = ::std::vec![#(&#wrappers,)*];
923                    match ::lrpar::RTParserBuilder::new(grm, stable)
924                        .recoverer(#recoverer)
925                        .parse_actions(lexer, &actions, #action_fn_parse_param) {
926                            (Some(#actionskind::#action_ident(x)), y) => (Some(x), y),
927                            (None, y) => (None, y),
928                            _ => unreachable!()
929                    }
930                }
931            }
932            kind => panic!("YaccKind {:?} not supported", kind),
933        };
934
935        let parsed_parse_generics: Generics = match build_env.yacc_kind() {
936            YaccKind::Original(YaccOriginalActionKind::UserAction) | YaccKind::Grmtools => {
937                make_generics(grm.parse_generics().as_deref())?
938            }
939            _ => make_generics(None)?,
940        };
941        let (generics, _, where_clause) = parsed_parse_generics.split_for_impl();
942
943        // `parse()` may or may not have an argument for `%parseparam`.
944        let parse_fn_parse_param = match build_env.yacc_kind() {
945            YaccKind::Original(YaccOriginalActionKind::UserAction) | YaccKind::Grmtools => {
946                if let Some((name, tyname)) = grm.parse_param() {
947                    let name = str::parse::<TokenStream>(name)?;
948                    let tyname = str::parse::<TokenStream>(tyname)?;
949                    Some(quote! {#name: #tyname})
950                } else {
951                    None
952                }
953            }
954            _ => None,
955        };
956        let parse_fn_return_ty = match build_env.yacc_kind() {
957            YaccKind::Original(YaccOriginalActionKind::UserAction) | YaccKind::Grmtools => {
958                let actiont = grm
959                    .actiontype(self.user_start_ridx())
960                    .as_ref()
961                    .map(|at| str::parse::<TokenStream>(at))
962                    .transpose()?;
963                quote! {
964                    (::std::option::Option<#actiont>, ::std::vec::Vec<::lrpar::LexParseError<#storaget, #lexertypest>>)
965                }
966            }
967            YaccKind::Original(YaccOriginalActionKind::GenericParseTree) => quote! {
968                (::std::option::Option<Node<<#lexertypest as ::lrpar::LexerTypes>::LexemeT, #storaget>>,
969                    ::std::vec::Vec<::lrpar::LexParseError<#storaget, #lexertypest>>)
970            },
971            YaccKind::Original(YaccOriginalActionKind::NoAction) => quote! {
972                ::std::vec::Vec<::lrpar::LexParseError<#storaget, #lexertypest>>
973            },
974            _ => unreachable!(),
975        };
976
977        let serialisation_format = build_env.serialisation_format();
978        // Note that the configuration types use associated consts, and thus these configurations represent distinct types.
979        let (grm_data, stable_data): (Vec<u8>, Vec<u8>) = match serialisation_format {
980            SerialisationFormat::FixedSizeInteger => {
981                let config = wincode::config::Configuration::default().with_fixint_encoding();
982                let grm = wincode::config::serialize(grm, config)?;
983                let stable = wincode::config::serialize(stable, config)?;
984                (grm, stable)
985            }
986            SerialisationFormat::VariableSizedInteger => {
987                let config = wincode::config::Configuration::default().with_varint_encoding();
988                let grm = wincode::config::serialize(grm, config)?;
989                let stable = wincode::config::serialize(stable, config)?;
990                (grm, stable)
991            }
992        };
993        let serialisation_format_str = quote!(serialisation_format).to_string();
994        Ok(quote! {
995            const __GRM_DATA: &[u8] = &[#(#grm_data,)*];
996            const __STABLE_DATA: &[u8] = &[#(#stable_data,)*];
997            const __SERIALISATION_FORMAT: ::lrpar::ctbuilder::SerialisationFormat = #serialisation_format;
998
999            fn __lrpar_parser_data() -> &'static ::lrpar::ParserData<#storaget> {
1000                static DATA: ::std::sync::OnceLock<::lrpar::ParserData<#storaget>>
1001                    = ::std::sync::OnceLock::new();
1002                DATA.get_or_init(
1003                    || {
1004                        // We have to call reconstitute like this because the config parameter takes a trait
1005                        // which uses const generics. Thus the two config parameters here are not actually of the same type.
1006                        match __SERIALISATION_FORMAT {
1007                            ::lrpar::ctbuilder::SerialisationFormat::FixedSizeInteger => {
1008                                ::lrpar::ctbuilder::_reconstitute(__GRM_DATA, __STABLE_DATA, ::lrpar::ctbuilder::wincode::config::Configuration::default().with_fixint_encoding())
1009                            }
1010                            ::lrpar::ctbuilder::SerialisationFormat::VariableSizedInteger => {
1011                                ::lrpar::ctbuilder::_reconstitute(__GRM_DATA, __STABLE_DATA, ::lrpar::ctbuilder::wincode::config::Configuration::default().with_varint_encoding())
1012                            }
1013                            _ => {
1014                                panic!("Parser source was generated using unknown `SerialisationFormat`: {:?}", #serialisation_format_str)
1015                            }
1016                        }
1017                    }
1018                )
1019            }
1020
1021            #[allow(dead_code)]
1022            pub fn parse #generics (
1023                 lexer: &'lexer dyn ::lrpar::NonStreamingLexer<'input, #lexertypest>,
1024                 #parse_fn_parse_param
1025            ) -> #parse_fn_return_ty
1026            #where_clause
1027            {
1028                let __data = __lrpar_parser_data();
1029                let grm = __data.grm();
1030                let stable = __data.stable();
1031                #run_parser
1032            }
1033        })
1034    }
1035
1036    /// Generate the wrappers that call user actions
1037    fn gen_wrappers(
1038        &self,
1039        build_env: &ParserBuildEnv<LexerTypesT>,
1040    ) -> Result<TokenStream, CodegenError> {
1041        let grm = self.grm();
1042        let parsed_parse_generics = make_generics(grm.parse_generics().as_deref())?;
1043        let (generics, type_generics, where_clause) = parsed_parse_generics.split_for_impl();
1044
1045        let (parse_paramname, parse_paramdef);
1046        match grm.parse_param() {
1047            Some((name, tyname)) => {
1048                parse_paramname = str::parse::<TokenStream>(name)?;
1049                let ty = str::parse::<TokenStream>(tyname)?;
1050                parse_paramdef = quote!(#parse_paramname: #ty);
1051            }
1052            None => {
1053                parse_paramname = quote!(());
1054                parse_paramdef = quote! {_: ()};
1055            }
1056        };
1057
1058        let mut wrappers = TokenStream::new();
1059        for pidx in grm.iter_pidxs() {
1060            let ridx = grm.prod_to_rule(pidx);
1061
1062            // Iterate over all $-arguments and replace them with their respective
1063            // element from the argument vector (e.g. $1 is replaced by args[0]). At
1064            // the same time extract &str from tokens and actiontype from nonterminals.
1065            let wrapper_fn = format_ident!("{}wrapper_{}", ACTION_PREFIX, usize::from(pidx));
1066            let ridx_var = format_ident!("{}ridx", ACTION_PREFIX);
1067            let lexer_var = format_ident!("{}lexer", ACTION_PREFIX);
1068            let span_var = format_ident!("{}span", ACTION_PREFIX);
1069            let args_var = format_ident!("{}args", ACTION_PREFIX);
1070            let storaget = str::parse::<TokenStream>(type_name::<LexerTypesT::StorageT>())?;
1071            let lexertypest = str::parse::<TokenStream>(type_name::<LexerTypesT>())?;
1072            let actionskind = str::parse::<TokenStream>(ACTIONS_KIND)?;
1073            let edition_lifetime = if build_env.rust_edition() != RustEdition::Rust2015 {
1074                Some(quote!('_,))
1075            } else {
1076                None
1077            };
1078            let mut wrapper_fn_body = TokenStream::new();
1079            if grm.action(pidx).is_some() {
1080                // Unpack the arguments passed to us by the drain
1081                for i in 0..grm.prod(pidx).len() {
1082                    let arg = format_ident!("{}arg_{}", ACTION_PREFIX, i + 1);
1083                    wrapper_fn_body.extend(match grm.prod(pidx)[i] {
1084                        Symbol::Rule(ref_ridx) => {
1085                            let ref_ridx = usize::from(ref_ridx);
1086                            let actionvariant = format_ident!("{}{}", ACTIONS_KIND_PREFIX, ref_ridx);
1087                            quote! {
1088                                #[allow(clippy::let_unit_value)]
1089                                let #arg = match #args_var.next().unwrap() {
1090                                    ::lrpar::parser::AStackType::ActionType(#actionskind::#type_generics::#actionvariant(x)) => x,
1091                                    _ => unreachable!()
1092                                };
1093                            }
1094                        }
1095                        Symbol::Token(_) => {
1096                            quote! {
1097                                let #arg = match #args_var.next().unwrap() {
1098                                    ::lrpar::parser::AStackType::Lexeme(l) => {
1099                                        if l.faulty() {
1100                                            Err(l)
1101                                        } else {
1102                                            Ok(l)
1103                                        }
1104                                    },
1105                                    ::lrpar::parser::AStackType::ActionType(_) => unreachable!()
1106                                };
1107                            }
1108                        }
1109                    })
1110                }
1111
1112                // Call the user code
1113                let args = (0..grm.prod(pidx).len())
1114                    .map(|i| format_ident!("{}arg_{}", ACTION_PREFIX, i + 1))
1115                    .collect::<Vec<_>>();
1116                let action_fn = format_ident!("{}action_{}", ACTION_PREFIX, usize::from(pidx));
1117                let actionsvariant = format_ident!("{}{}", ACTIONS_KIND_PREFIX, usize::from(ridx));
1118
1119                wrapper_fn_body.extend(match grm.actiontype(ridx) {
1120                    Some(s) if s == "()" => {
1121                        // If the rule `r` that we're calling has the unit type then Clippy will warn that
1122                        // `enum::A(wrapper_r())` is pointless. We thus have to split it into two:
1123                        // `wrapper_r(); enum::A(())`.
1124                        quote! {
1125                            #action_fn(#ridx_var, #lexer_var, #span_var, #parse_paramname, #(#args,)*);
1126                            #actionskind::#type_generics::#actionsvariant(())
1127                        }
1128                    }
1129                    _ => {
1130                        quote! {
1131                            #actionskind::#type_generics::#actionsvariant(#action_fn(#ridx_var, #lexer_var, #span_var, #parse_paramname, #(#args,)*))
1132                        }
1133                    }
1134                })
1135            } else if pidx == grm.start_prod() {
1136                wrapper_fn_body.extend(quote!(unreachable!()));
1137            } else {
1138                unreachable!(
1139                    "Production in rule '{}' must have an action body, which should have been handled by gen_user_actions.",
1140                    grm.rule_name_str(grm.prod_to_rule(pidx))
1141                );
1142            };
1143
1144            let attrib = if pidx == grm.start_prod() {
1145                // The start prod has an unreachable body so it doesn't use it's variables.
1146                Some(quote!(#[allow(unused_variables)]))
1147            } else {
1148                None
1149            };
1150            wrappers.extend(quote! {
1151                #attrib
1152                fn #wrapper_fn #generics (
1153                    #ridx_var: ::cfgrammar::RIdx<#storaget>,
1154                    #lexer_var: &'lexer dyn ::lrpar::NonStreamingLexer<'input, #lexertypest>,
1155                    #span_var: ::cfgrammar::Span,
1156                    mut #args_var: ::std::vec::Drain<#edition_lifetime ::lrpar::parser::AStackType<<#lexertypest as ::lrpar::LexerTypes>::LexemeT, #actionskind #type_generics>>,
1157                    #parse_paramdef
1158                ) -> #actionskind #type_generics
1159                #where_clause
1160                {
1161                    #wrapper_fn_body
1162                }
1163             })
1164        }
1165        let mut actionskindvariants = Vec::new();
1166        let actionskindhidden = format_ident!("_{}", ACTIONS_KIND_HIDDEN);
1167        let actionskind = str::parse::<TokenStream>(ACTIONS_KIND).unwrap();
1168        let mut phantom_data_type = Vec::new();
1169        for ridx in grm.iter_rules() {
1170            if let Some(actiont) = grm.actiontype(ridx) {
1171                let actionskindvariant =
1172                    format_ident!("{}{}", ACTIONS_KIND_PREFIX, usize::from(ridx));
1173                let actiont = str::parse::<TokenStream>(actiont).unwrap();
1174                actionskindvariants.push(quote! {
1175                    #actionskindvariant(#actiont)
1176                })
1177            }
1178        }
1179        for lifetime in parsed_parse_generics.lifetimes() {
1180            let lifetime = &lifetime.lifetime;
1181            phantom_data_type.push(quote! { &#lifetime () });
1182        }
1183        for type_param in parsed_parse_generics.type_params() {
1184            let ident = &type_param.ident;
1185            phantom_data_type.push(quote! { #ident });
1186        }
1187        actionskindvariants.push(quote! {
1188            #actionskindhidden(::std::marker::PhantomData<(#(#phantom_data_type,)*)>)
1189        });
1190        wrappers.extend(quote! {
1191            #[allow(dead_code)]
1192            enum #actionskind #generics #where_clause {
1193                #(#actionskindvariants,)*
1194            }
1195        });
1196        Ok(wrappers)
1197    }
1198
1199    /// Return the `RIdx` of the %start rule in the grammar (which will not be the same as
1200    /// grm.start_rule_idx because the latter has an additional rule insert by cfgrammar
1201    /// which then calls the user's %start rule).
1202    fn user_start_ridx(&self) -> RIdx<LexerTypesT::StorageT> {
1203        let grm = self.grm();
1204        debug_assert_eq!(grm.prod(grm.start_prod()).len(), 1);
1205        match grm.prod(grm.start_prod())[0] {
1206            Symbol::Rule(ridx) => ridx,
1207            _ => unreachable!(),
1208        }
1209    }
1210}
1211
1212/// The quote impl of `ToTokens` for `Option` prints an empty string for `None`
1213/// and the inner value for `Some(inner_value)`.
1214///
1215/// This wrapper instead emits both `Some` and `None` variants.
1216/// See: [quote #20](https://github.com/dtolnay/quote/issues/20)
1217struct QuoteOption<T>(Option<T>);
1218
1219impl<T: ToTokens> ToTokens for QuoteOption<T> {
1220    fn to_tokens(&self, tokens: &mut TokenStream) {
1221        tokens.append_all(match self.0 {
1222            Some(ref t) => quote! { ::std::option::Option::Some(#t) },
1223            None => quote! { ::std::option::Option::None },
1224        });
1225    }
1226}
1227
1228/// This wrapper adds a missing impl of `ToTokens` for tuples.
1229/// For a tuple `(a, b)` emits `(a.to_tokens(), b.to_tokens())`
1230struct QuoteTuple<T>(T);
1231
1232impl<A: ToTokens, B: ToTokens> ToTokens for QuoteTuple<(A, B)> {
1233    fn to_tokens(&self, tokens: &mut TokenStream) {
1234        let (a, b) = &self.0;
1235        tokens.append_all(quote!((#a, #b)));
1236    }
1237}
1238
1239/// The wrapped `&str` value will be emitted with a call to `to_string()`
1240struct QuoteToString<'a>(&'a str);
1241
1242impl ToTokens for QuoteToString<'_> {
1243    fn to_tokens(&self, tokens: &mut TokenStream) {
1244        let x = &self.0;
1245        tokens.append_all(quote! { #x.to_string() });
1246    }
1247}
1248
1249/// The quote impl of `ToTokens` for `usize` prints literal values
1250/// including a type suffix for example `0usize`.
1251///
1252/// This wrapper omits the type suffix emitting `0` instead.
1253struct UnsuffixedUsize(usize);
1254
1255impl ToTokens for UnsuffixedUsize {
1256    fn to_tokens(&self, tokens: &mut TokenStream) {
1257        tokens.append(Literal::usize_unsuffixed(self.0))
1258    }
1259}
1260
1261impl RustEdition {
1262    fn to_variant_tokens(self) -> TokenStream {
1263        match self {
1264            RustEdition::Rust2015 => quote!(::lrpar::RustEdition::Rust2015),
1265            RustEdition::Rust2018 => quote!(::lrpar::RustEdition::Rust2018),
1266            RustEdition::Rust2021 => quote!(::lrpar::RustEdition::Rust2021),
1267        }
1268    }
1269}
1270
1271impl ToTokens for Visibility {
1272    fn to_tokens(&self, tokens: &mut TokenStream) {
1273        tokens.extend(match self {
1274            Visibility::Private => quote!(),
1275            Visibility::Public => quote! {pub},
1276            Visibility::PublicSuper => quote! {pub(super)},
1277            Visibility::PublicSelf => quote! {pub(self)},
1278            Visibility::PublicCrate => quote! {pub(crate)},
1279            Visibility::PublicIn(data) => {
1280                let other = str::parse::<TokenStream>(data).unwrap();
1281                quote! {pub(in #other)}
1282            }
1283        })
1284    }
1285}
1286
1287impl Visibility {
1288    fn to_variant_tokens(&self) -> TokenStream {
1289        match self {
1290            Visibility::Private => quote!(::lrpar::Visibility::Private),
1291            Visibility::Public => quote!(::lrpar::Visibility::Public),
1292            Visibility::PublicSuper => quote!(::lrpar::Visibility::PublicSuper),
1293            Visibility::PublicSelf => quote!(::lrpar::Visibility::PublicSelf),
1294            Visibility::PublicCrate => quote!(::lrpar::Visibility::PublicCrate),
1295            Visibility::PublicIn(data) => {
1296                let data = QuoteToString(data);
1297                quote!(::lrpar::Visibility::PublicIn(#data))
1298            }
1299        }
1300    }
1301}
1302
1303impl ToTokens for SerialisationFormat {
1304    fn to_tokens(&self, tokens: &mut TokenStream) {
1305        tokens.extend(match self {
1306            SerialisationFormat::FixedSizeInteger => {
1307                quote! {::lrpar::ctbuilder::SerialisationFormat::FixedSizeInteger}
1308            }
1309            SerialisationFormat::VariableSizedInteger => {
1310                quote! {::lrpar::ctbuilder::SerialisationFormat::VariableSizedInteger}
1311            }
1312        })
1313    }
1314}
1315
1316pub(crate) fn make_generics(parse_generics: Option<&str>) -> Result<Generics, CodegenError> {
1317    if let Some(parse_generics) = parse_generics {
1318        let tokens = str::parse::<TokenStream>(parse_generics)?;
1319        match syn::parse2(quote!(<'lexer, 'input: 'lexer, #tokens>)) {
1320            Ok(res) => Ok(res),
1321            Err(err) => Err(CodegenError::InvalidParseGenerics(err)),
1322        }
1323    } else {
1324        Ok(parse_quote!(<'lexer, 'input: 'lexer>))
1325    }
1326}
1327
1328#[cfg(test)]
1329mod test {
1330    use super::*;
1331    use crate::test_utils::{FindSpan as _, TestLexerTypes};
1332    use cfgrammar::header::HeaderErrorKind;
1333    #[test]
1334    fn test_unused_header_entry() {
1335        let src = r#"
1336        %grmtools{
1337            yacckind: Grmtools,
1338            testfoo: "non-grmtools values which do not specify a crate origin should produce errors",
1339        }
1340        %%
1341        start -> () : "A" { () };
1342        "#;
1343        let src_env = ParserSrcEnv::<TestLexerTypes>::new(src, None);
1344        let expected_errs = vec![HeaderError {
1345            kind: HeaderErrorKind::IllegalName,
1346            locations: vec![src.find_span("testfoo")],
1347        }];
1348        match src_env.build_env(ParserBuildEnvArgs::new().mod_name(Some("test_module"))) {
1349            Err(ParserSrcEnvError::GrmtoolsSectionParseError(errs)) => {
1350                assert_eq!(errs, expected_errs)
1351            }
1352            _ => panic!("Unexpected err"),
1353        }
1354    }
1355
1356    #[test]
1357    fn test_unused_grmtools_header_entry() {
1358        let src = r#"
1359        %grmtools{
1360            yacckind: Grmtools,
1361            cfgrammar.unknown: "should be unused",
1362            lrpar.unknown: "should be unused",
1363        }
1364        %%
1365        start -> () : "A" { () };
1366        "#;
1367        let src_env = ParserSrcEnv::<TestLexerTypes>::new(src, None);
1368        let build_env = src_env
1369            .build_env(ParserBuildEnvArgs::new().mod_name(Some("test_module")))
1370            .unwrap();
1371        match build_env.code_generator("timestamp") {
1372            Err(ParserBuildEnvError::GrmtoolsSectionUnusedKeys(keys)) => {
1373                assert_eq!(
1374                    &keys,
1375                    &[
1376                        (
1377                            "cfgrammar.unknown".to_string(),
1378                            src.find_span("cfgrammar.unknown")
1379                        ),
1380                        ("lrpar.unknown".to_string(), src.find_span("lrpar.unknown"))
1381                    ]
1382                );
1383            }
1384            _ => panic!("Unexpected error result"),
1385        }
1386    }
1387
1388    #[test]
1389    fn test_unregistered_grmtools_prefix() {
1390        let src = r#"
1391        %grmtools{
1392            yacckind: Grmtools,
1393            unregistered.key: "unknown prefix should be unregistered",
1394            registered.key: "should be registered",
1395        }
1396        %%
1397        start -> () : "A" { () };
1398        "#;
1399        let src_env = ParserSrcEnv::<TestLexerTypes>::new(src, None);
1400        let mut build_env = src_env
1401            .build_env(ParserBuildEnvArgs::new().mod_name(Some("test_module")))
1402            .unwrap();
1403        build_env.register_prefix("registered").unwrap();
1404        let found_prefixes = build_env
1405            .ast_with_validity_info()
1406            .iter_prefixes()
1407            .collect::<HashSet<_>>();
1408        let registered_prefixes = build_env.registered_prefixes().collect::<HashSet<_>>();
1409        let expected_unregistered: HashSet<&str> = HashSet::from_iter(["unregistered"]);
1410        let unregistered_prefixes: HashSet<&str> = found_prefixes
1411            .difference(&registered_prefixes)
1412            .copied()
1413            .collect::<HashSet<_>>();
1414        assert_eq!(expected_unregistered, unregistered_prefixes);
1415    }
1416}