Skip to main content

lrpar/
ctbuilder.rs

1//! Build grammars at compile-time so that they can be statically included into a binary.
2
3use std::{
4    collections::{HashMap, HashSet},
5    env::{current_dir, var},
6    error::Error,
7    fmt::{self, Debug, Write as fmtWrite},
8    fs::{self, File, create_dir_all, read_to_string},
9    hash::Hash,
10    io::Write,
11    marker::PhantomData,
12    path::{Path, PathBuf},
13    sync::{LazyLock, Mutex},
14};
15
16use crate::{
17    LexerTypes, RTParserBuilder, RecoveryKind,
18    codegen::{
19        ParserBuildEnv, ParserBuildEnvArgs, ParserBuildEnvError, ParserCodegen, ParserSrcEnv,
20        ParserSrcEnvError,
21    },
22    diagnostics::{DiagnosticFormatter, SpannedDiagnosticFormatter},
23};
24
25#[cfg(feature = "_unstable_api")]
26use crate::unstable_api::UnstableApi;
27
28use cfgrammar::{
29    Span,
30    header::{Header, HeaderError, HeaderErrorKind, Value},
31    yacc::{YaccGrammar, YaccKind, ast::ASTWithValidityInfo},
32};
33use filetime::FileTime;
34use lrtable::{StateGraph, StateTable, statetable::Conflicts};
35use num_traits::{AsPrimitive, PrimInt, Unsigned};
36use wincode::{SchemaRead, SchemaReadOwned, SchemaWrite};
37
38const RUST_FILE_EXT: &str = "rs";
39const WARNING: &str = "[Warning]";
40pub(crate) const ERROR: &str = "[Error]";
41
42static GENERATED_PATHS: LazyLock<Mutex<HashSet<PathBuf>>> =
43    LazyLock::new(|| Mutex::new(HashSet::new()));
44
45pub(crate) struct CTConflictsError<StorageT: Eq + Hash> {
46    pub(crate) conflicts_diagnostic: String,
47    #[cfg(test)]
48    #[cfg_attr(test, allow(dead_code))]
49    pub(crate) stable: StateTable<StorageT>,
50    pub(crate) phantom: PhantomData<StorageT>,
51}
52
53impl<StorageT> fmt::Display for CTConflictsError<StorageT>
54where
55    StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
56    usize: AsPrimitive<StorageT>,
57{
58    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59        write!(f, "{}", self.conflicts_diagnostic)
60    }
61}
62
63impl<StorageT> fmt::Debug for CTConflictsError<StorageT>
64where
65    StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
66    usize: AsPrimitive<StorageT>,
67{
68    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69        write!(f, "{}", self.conflicts_diagnostic)
70    }
71}
72
73impl<StorageT> Error for CTConflictsError<StorageT>
74where
75    StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
76    usize: AsPrimitive<StorageT>,
77{
78}
79
80/// A string which uses `Display` for it's `Debug` impl.
81struct ErrorString(String);
82impl fmt::Display for ErrorString {
83    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84        let ErrorString(s) = self;
85        write!(f, "{}", s)
86    }
87}
88impl fmt::Debug for ErrorString {
89    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90        let ErrorString(s) = self;
91        write!(f, "{}", s)
92    }
93}
94impl Error for ErrorString {}
95
96/// Specify the visibility of the module generated by `CTBuilder`.
97#[derive(Clone, PartialEq, Eq, Debug)]
98#[non_exhaustive]
99pub enum Visibility {
100    /// Module-level visibility only.
101    Private,
102    /// `pub`
103    Public,
104    /// `pub(super)`
105    PublicSuper,
106    /// `pub(self)`
107    PublicSelf,
108    /// `pub(crate)`
109    PublicCrate,
110    /// `pub(in {arg})`
111    PublicIn(String),
112}
113
114/// Specifies the [Rust Edition] that will be emitted during code generation.
115///
116/// [Rust Edition]: https://doc.rust-lang.org/edition-guide/rust-2021/index.html
117#[derive(Clone, Copy, PartialEq, Eq, Debug)]
118#[non_exhaustive]
119pub enum RustEdition {
120    Rust2015,
121    Rust2018,
122    Rust2021,
123}
124
125/// Sets the underlying encoding algorithm for serialising the `ParserData` into the generated source files.
126///
127/// This correlates to a specific `Configuration` of [wincode::config](https://docs.rs/wincode/latest/wincode/config/index.html).
128#[non_exhaustive]
129#[derive(SchemaRead, SchemaWrite, Debug, Clone, Copy)]
130pub enum SerialisationFormat {
131    /// See [wincode::FixedInt](https://docs.rs/wincode/latest/wincode/int_encoding/struct.FixedInt.html)
132    FixedSizeInteger,
133    /// See [wincode::VarInt](https://docs.rs/wincode/latest/wincode/int_encoding/struct.VarInt.html)
134    VariableSizedInteger,
135}
136
137impl TryFrom<&Value<Span>> for SerialisationFormat {
138    type Error = HeaderError<Span>;
139    fn try_from(value: &Value<Span>) -> Result<SerialisationFormat, HeaderError<Span>> {
140        match value {
141            Value::Namespaced(serialisation_fmt, span) => match serialisation_fmt.as_str() {
142                "SerialisationFormat::FixedSizeInteger" | "FixedSizeInteger" => {
143                    Ok(SerialisationFormat::FixedSizeInteger)
144                }
145                "SerialisationFormat::VariableSizedInteger" | "VariableSizedInteger" => {
146                    Ok(SerialisationFormat::VariableSizedInteger)
147                }
148                _ => Err(HeaderError {
149                    kind: HeaderErrorKind::InvalidEntry("serialisation_format"),
150                    locations: vec![*span],
151                }),
152            },
153            val => Err(HeaderError {
154                kind: HeaderErrorKind::InvalidEntry("serialisation_format"),
155                locations: vec![*val.primary_location()],
156            }),
157        }
158    }
159}
160
161// We export this for generated code to refer to.
162#[doc(hidden)]
163pub use wincode;
164
165/// A `CTParserBuilder` allows one to specify the criteria for building a statically generated
166/// parser.
167pub struct CTParserBuilder<'a, LexerTypesT: LexerTypes>
168where
169    LexerTypesT::StorageT: Eq + Hash,
170    usize: AsPrimitive<LexerTypesT::StorageT>,
171{
172    // Anything stored in here (except `output_path`, `conflicts`, and `error_on_conflict`) almost
173    // certainly needs to be included as part of the rebuild_cache function below so that, if it's
174    // changed, the grammar is rebuilt.
175    grammar_path: Option<PathBuf>,
176    // If specified rather than reading source from `grammar_path`, use this string directly
177    grammar_src: Option<String>,
178    // If specified along with `grammar_src`, use this rather than building an ast from `grammar_src`.
179    from_ast: Option<ASTWithValidityInfo>,
180    output_path: Option<PathBuf>,
181    mod_name: Option<&'a str>,
182    recoverer: Option<RecoveryKind>,
183    yacckind: Option<YaccKind>,
184    error_on_conflicts: bool,
185    warnings_are_errors: bool,
186    show_warnings: bool,
187    visibility: Visibility,
188    rust_edition: RustEdition,
189    inspect_rt: Option<
190        Box<
191            dyn for<'b> FnMut(
192                &'b Header<Span>,
193                RTParserBuilder<LexerTypesT::StorageT, LexerTypesT>,
194                &'b HashMap<String, LexerTypesT::StorageT>,
195                &PathBuf,
196            ) -> Result<(), Box<dyn Error>>,
197        >,
198    >,
199    serialisation_format: Option<SerialisationFormat>,
200    // test function for inspecting private state
201    #[cfg(test)]
202    inspect_callback: Option<Box<dyn Fn(RecoveryKind) -> Result<(), Box<dyn Error>>>>,
203    phantom: PhantomData<LexerTypesT>,
204}
205
206/// Defaults to `wincode::int_encoding::VarInt`.
207pub(crate) type FixIntConfig = wincode::config::Configuration;
208/// The default config with the last parameter set to `VarInt`
209pub(crate) type VarIntConfig = wincode::config::Configuration<
210    true,
211    4194304,
212    wincode::len::BincodeLen,
213    wincode::int_encoding::LittleEndian,
214    wincode::int_encoding::VarInt,
215>;
216
217impl<
218    'a,
219    StorageT: 'static
220        + Debug
221        + Hash
222        + PrimInt
223        + SchemaWrite<FixIntConfig, Src = StorageT>
224        + SchemaWrite<VarIntConfig, Src = StorageT>
225        + Unsigned,
226    LexerTypesT: LexerTypes<StorageT = StorageT>,
227> CTParserBuilder<'a, LexerTypesT>
228where
229    usize: AsPrimitive<StorageT>,
230{
231    /// Create a new `CTParserBuilder`.
232    ///
233    /// `StorageT` must be an unsigned integer type (e.g. `u8`, `u16`) which is:
234    ///   * big enough to index (separately) all the tokens, rules, productions in the grammar,
235    ///   * big enough to index the state table created from the grammar,
236    ///   * less than or equal in size to `u32`.
237    ///
238    /// In other words, if you have a grammar with 256 tokens, 256 rules, and 256 productions,
239    /// which creates a state table of 256 states you can safely specify `u8` here; but if any of
240    /// those counts becomes 257 or greater you will need to specify `u16`. If you are parsing
241    /// large files, the additional storage requirements of larger integer types can be noticeable,
242    /// and in such cases it can be worth specifying a smaller type. `StorageT` defaults to `u32`
243    /// if unspecified.
244    ///
245    /// # Examples
246    ///
247    /// ```text
248    /// CTParserBuilder::<DefaultLexerTypes<u8>>::new()
249    ///     .grammar_in_src_dir("grm.y")?
250    ///     .build()?;
251    /// ```
252    pub fn new() -> Self {
253        CTParserBuilder {
254            grammar_path: None,
255            grammar_src: None,
256            from_ast: None,
257            output_path: None,
258            mod_name: None,
259            recoverer: None,
260            yacckind: None,
261            error_on_conflicts: true,
262            warnings_are_errors: true,
263            show_warnings: true,
264            visibility: Visibility::Private,
265            rust_edition: RustEdition::Rust2021,
266            inspect_rt: None,
267            serialisation_format: None,
268            #[cfg(test)]
269            inspect_callback: None,
270            phantom: PhantomData,
271        }
272    }
273
274    /// Set the input grammar path to a file relative to this project's `src` directory. This will
275    /// also set the output path (i.e. you do not need to call [CTParserBuilder::output_path]).
276    ///
277    /// For example if `a/b.y` is passed as `inp` then [CTParserBuilder::build] will:
278    ///   * use `src/a/b.y` as the input file.
279    ///   * write output to a file which can then be imported by calling `lrpar_mod!("a/b.y")`.
280    ///   * create a module in that output file named `b_y`.
281    ///
282    /// You can override the output path and/or module name by calling [CTParserBuilder::output_path]
283    /// and/or [CTParserBuilder::mod_name], respectively, after calling this function.
284    ///
285    /// This is a convenience function that makes it easier to compile grammar files stored in a
286    /// project's `src/` directory: please see [CTParserBuilder::build] for additional constraints
287    /// and information about the generated files. Note also that each `.y` file can only be
288    /// processed once using this function: if you want to generate multiple grammars from a single
289    /// `.y` file, you will need to use [CTParserBuilder::output_path].
290    pub fn grammar_in_src_dir<P>(mut self, srcp: P) -> Result<Self, Box<dyn Error>>
291    where
292        P: AsRef<Path>,
293    {
294        if !srcp.as_ref().is_relative() {
295            return Err(format!(
296                "Grammar path '{}' must be a relative path.",
297                srcp.as_ref().to_str().unwrap_or("<invalid UTF-8>")
298            )
299            .into());
300        }
301
302        let mut grmp = current_dir()?;
303        grmp.push("src");
304        grmp.push(srcp.as_ref());
305        self.grammar_path = Some(grmp);
306
307        let mut outp = PathBuf::new();
308        outp.push(var("OUT_DIR").unwrap());
309        outp.push(srcp.as_ref().parent().unwrap().to_str().unwrap());
310        create_dir_all(&outp)?;
311        let mut leaf = srcp
312            .as_ref()
313            .file_name()
314            .unwrap()
315            .to_str()
316            .unwrap()
317            .to_owned();
318        write!(leaf, ".{}", RUST_FILE_EXT).ok();
319        outp.push(leaf);
320        Ok(self.output_path(outp))
321    }
322
323    /// If set, specifies that this grammar should be built from a pre-validated AST
324    /// instead of a `.y`` file. When this is specified, `grammar_path` will not be read.
325    #[cfg(feature = "_unstable_api")]
326    pub fn grammar_ast(mut self, valid_ast: ASTWithValidityInfo, _api_key: UnstableApi) -> Self {
327        self.from_ast = Some(valid_ast);
328        self
329    }
330
331    /// Set the input grammar path to `inp`. If specified, you must also call
332    /// [CTParserBuilder::output_path]. In general it is easier to use
333    /// [CTParserBuilder::grammar_in_src_dir].
334    pub fn grammar_path<P>(mut self, inp: P) -> Self
335    where
336        P: AsRef<Path>,
337    {
338        self.grammar_path = Some(inp.as_ref().to_owned());
339        self
340    }
341
342    #[cfg(feature = "_unstable_api")]
343    pub fn with_grammar_src(mut self, src: String, _api_key: UnstableApi) -> Self {
344        self.grammar_src = Some(src);
345        self
346    }
347
348    /// Set the output grammar path to `outp`. Note that there are no requirements on `outp`: the
349    /// file can exist anywhere you can create a valid [Path] to. However, if you wish to use
350    /// [crate::lrpar_mod!] you will need to make sure that `outp` is in
351    /// [std::env::var]`("OUT_DIR")` or one of its subdirectories.
352    pub fn output_path<P>(mut self, outp: P) -> Self
353    where
354        P: AsRef<Path>,
355    {
356        self.output_path = Some(outp.as_ref().to_owned());
357        self
358    }
359
360    /// Set the generated module name to `mod_name`. If no module name is specified,
361    /// [CTParserBuilder::build] will attempt to create a sensible default based on the grammar
362    /// filename.
363    pub fn mod_name(mut self, mod_name: &'a str) -> Self {
364        self.mod_name = Some(mod_name);
365        self
366    }
367
368    /// Set the visibility of the generated module to `vis`. Defaults to `Visibility::Private`.
369    pub fn visibility(mut self, vis: Visibility) -> Self {
370        self.visibility = vis;
371        self
372    }
373
374    /// Set the recoverer for this parser to `rk`. Defaults to `RecoveryKind::CPCTPlus`.
375    pub fn recoverer(mut self, rk: RecoveryKind) -> Self {
376        self.recoverer = Some(rk);
377        self
378    }
379
380    /// Set the `YaccKind` for this parser to `ak`.
381    pub fn yacckind(mut self, yk: YaccKind) -> Self {
382        self.yacckind = Some(yk);
383        self
384    }
385
386    /// If set to true, [CTParserBuilder::build] will return an error if the given grammar contains
387    /// any Shift/Reduce or Reduce/Reduce conflicts. Defaults to `true`.
388    pub fn error_on_conflicts(mut self, b: bool) -> Self {
389        self.error_on_conflicts = b;
390        self
391    }
392
393    /// If set to true, [CTParserBuilder::build] will return an error if the given grammar contains
394    /// any warnings. Defaults to `true`.
395    pub fn warnings_are_errors(mut self, b: bool) -> Self {
396        self.warnings_are_errors = b;
397        self
398    }
399
400    /// If set to true, [CTParserBuilder::build] will print warnings to stderr, or via cargo when
401    /// running under cargo. Defaults to `true`.
402    pub fn show_warnings(mut self, b: bool) -> Self {
403        self.show_warnings = b;
404        self
405    }
406
407    /// Sets the rust edition to be used for generated code. Defaults to the latest edition of
408    /// rust supported by grmtools.
409    pub fn rust_edition(mut self, edition: RustEdition) -> Self {
410        self.rust_edition = edition;
411        self
412    }
413
414    pub fn serialisation_format(mut self, serialisation_format: SerialisationFormat) -> Self {
415        self.serialisation_format = Some(serialisation_format);
416        self
417    }
418
419    #[cfg(test)]
420    pub fn inspect_recoverer(
421        mut self,
422        cb: Box<dyn for<'h, 'y> Fn(RecoveryKind) -> Result<(), Box<dyn Error>>>,
423    ) -> Self {
424        self.inspect_callback = Some(cb);
425        self
426    }
427
428    #[doc(hidden)]
429    pub fn inspect_rt(
430        mut self,
431        cb: Box<
432            dyn for<'b, 'y> FnMut(
433                &'b Header<Span>,
434                RTParserBuilder<'y, StorageT, LexerTypesT>,
435                &'b HashMap<String, StorageT>,
436                &PathBuf,
437            ) -> Result<(), Box<dyn Error>>,
438        >,
439    ) -> Self {
440        self.inspect_rt = Some(cb);
441        self
442    }
443
444    /// Statically compile the Yacc file specified by [CTParserBuilder::grammar_path()] into Rust,
445    /// placing the output into the file spec [CTParserBuilder::output_path()]. Note that three
446    /// additional files will be created with the same name as specified in [self.output_path] but
447    /// with the extensions `grm`, and `stable`, overwriting any existing files with those names.
448    ///
449    /// If `%parse-param` is not specified, the generated module follows the form:
450    ///
451    /// ```text
452    ///   mod <modname> {
453    ///     pub fn parse<'lexer, 'input: 'lexer>(lexer: &'lexer dyn NonStreamingLexer<...>)
454    ///       -> (Option<ActionT>, Vec<LexParseError<...>> { ... }
455    ///
456    ///     pub fn token_epp<'a>(tidx: ::cfgrammar::TIdx<StorageT>) -> ::std::option::Option<&'a str> {
457    ///       ...
458    ///     }
459    ///
460    ///     ...
461    ///   }
462    /// ```
463    ///
464    /// If `%parse-param x: t` is specified, the generated module follows the form:
465    ///
466    /// ```text
467    ///   mod <modname> {
468    ///     pub fn parse<'lexer, 'input: 'lexer>(lexer: &'lexer dyn NonStreamingLexer<...>, x: t)
469    ///       -> (Option<ActionT>, Vec<LexParseError<...>> { ... }
470    ///
471    ///     pub fn token_epp<'a>(tidx: ::cfgrammar::TIdx<StorageT>) -> ::std::option::Option<&'a str> {
472    ///       ...
473    ///     }
474    ///
475    ///     ...
476    ///   }
477    /// ```
478    ///
479    /// where:
480    ///  * `modname` is either:
481    ///    * the module name specified by [CTParserBuilder::mod_name()];
482    ///    * or, if no module name was explicitly specified, then for the file `/a/b/c.y` the
483    ///      module name is `c_y` (i.e. the file's leaf name, minus its extension, with a prefix of
484    ///      `_y`).
485    ///  * `ActionT` is either:
486    ///    * if the `yacckind` was set to `YaccKind::GrmTools` or
487    ///      `YaccKind::Original(YaccOriginalActionKind::UserAction)`, it is
488    ///      the return type of the `%start` rule;
489    ///    * or, if the `yacckind` was set to
490    ///      `YaccKind::Original(YaccOriginalActionKind::GenericParseTree)`, it
491    ///      is `Node<StorageT>` where the `Node` type is defined within your `lrpar_mod!`.
492    ///
493    /// # Panics
494    ///
495    /// If `StorageT` is not big enough to index the grammar's tokens, rules, or productions.
496    pub fn build(mut self) -> Result<CTParser<StorageT>, Box<dyn Error>> {
497        let grmp = self
498            .grammar_path
499            .as_ref()
500            .expect("grammar_path must be specified before processing.");
501        let outp = self
502            .output_path
503            .as_ref()
504            .expect("output_path must be specified before processing.");
505
506        if let Some(YaccKind::Eco) = self.yacckind {
507            panic!("Eco compile-time grammar generation not supported.")
508        }
509
510        {
511            let mut lk = GENERATED_PATHS.lock().unwrap();
512            if lk.contains(outp.as_path()) {
513                return Err(format!("Generating two parsers to the same path ('{}') is not allowed: use CTParserBuilder::output_path (and, optionally, CTParserBuilder::mod_name) to differentiate them.", outp.to_str().unwrap()).into());
514            }
515            lk.insert(outp.clone());
516        }
517
518        let inc = if let Some(grammar_src) = &self.grammar_src {
519            grammar_src.clone()
520        } else {
521            read_to_string(grmp).map_err(|e| format!("When reading '{}': {e}", grmp.display()))?
522        };
523
524        let src_env = ParserSrcEnv::new(&inc, Some(grmp))
525            .yacckind(self.yacckind)
526            .recoverer(self.recoverer);
527        let yacc_diag = SpannedDiagnosticFormatter::new(&inc, grmp);
528        let build_args = ParserBuildEnvArgs::new()
529            .ast_with_validity_info(self.from_ast.as_ref())
530            .mod_name(self.mod_name)
531            .show_warnings(self.show_warnings)
532            .error_on_conflicts(self.error_on_conflicts)
533            .warnings_are_errors(self.warnings_are_errors)
534            .visibility(self.visibility.clone())
535            .rust_edition(self.rust_edition);
536        let build_env = src_env.build_env(build_args).map_err(|e| match e {
537            ParserSrcEnvError::GrmtoolsSectionParseError(es) => {
538                let mut out = String::new();
539                out.push_str(&format!(
540                    "\n{ERROR}{}\n",
541                    yacc_diag.file_location_msg(" parsing the `%grmtools` section", None)
542                ));
543                for e in es {
544                    out.push_str(&indent("     ", &yacc_diag.format_error(e).to_string()));
545                    out.push('\n');
546                }
547                Box::<dyn Error>::from(ErrorString(out))
548            }
549            e => e.to_string().into(),
550        })?;
551        // Temporarily we update self.yacckind and self.recoverer from the build_env
552        // Until codegen reads these variables from the build_env directly.
553        self.recoverer = Some(build_env.recoverer());
554        self.yacckind = Some(build_env.yacc_kind());
555
556        let warnings = build_env.ast_with_validity_info().ast().warnings();
557        if self.warnings_are_errors && !warnings.is_empty() {
558            let mut out = String::new();
559            out.push_str(&format!(
560                "\n{ERROR}{}\n",
561                yacc_diag.file_location_msg("", None)
562            ));
563            for e in warnings {
564                out.push_str(&format!(
565                    "{}\n",
566                    indent("     ", &yacc_diag.format_warning(e).to_string())
567                ));
568            }
569            return Err(ErrorString(out).into());
570        } else if !warnings.is_empty() {
571            for w in warnings {
572                let ws_loc = yacc_diag.file_location_msg("", None);
573                let ws = indent("     ", &yacc_diag.format_warning(w).to_string());
574                // Assume if this variable is set we are running under cargo.
575                if std::env::var("OUT_DIR").is_ok() && self.show_warnings {
576                    for line in ws_loc.lines().chain(ws.lines()) {
577                        println!("cargo:warning={}", line);
578                    }
579                } else if self.show_warnings {
580                    eprintln!("{}", ws_loc);
581                    eprintln!("{WARNING} {}", ws);
582                }
583            }
584        }
585
586        #[cfg(test)]
587        if let Some(cb) = &self.inspect_callback {
588            cb(build_env.recoverer())?;
589        }
590
591        let timestamp = env!("VERGEN_BUILD_TIMESTAMP");
592        let code_gen = build_env.code_generator(timestamp).map_err(|e| match e {
593            ParserBuildEnvError::YaccGrammarErrors(errs) => {
594                let mut out = String::new();
595                out.push_str(&format!(
596                    "\n{ERROR}{}\n",
597                    yacc_diag.file_location_msg("", None)
598                ));
599                for e in errs {
600                    out.push_str(&indent("     ", &yacc_diag.format_error(e).to_string()));
601                    out.push('\n');
602                }
603                ErrorString(out)
604            }
605            e => ErrorString(e.to_string()),
606        })?;
607        let grm = code_gen.grm();
608        let rule_ids = grm
609            .tokens_map()
610            .iter()
611            .map(|(&n, &i)| (n.to_owned(), i.as_storaget()))
612            .collect::<HashMap<_, _>>();
613
614        let cache = code_gen.cache_str(&build_env);
615
616        // We don't need to go through the full rigmarole of generating an output file if all of
617        // the following are true: the output file exists; it is newer than the input file; and the
618        // cache hasn't changed. The last of these might be surprising, but it's vital: we don't
619        // know, for example, what the IDs map might be from one run to the next, and it might
620        // change for reasons beyond lrpar's control. If it does change, that means that the lexer
621        // and lrpar would get out of sync, so we have to play it safe and regenerate in such
622        // cases.
623        if let Ok(ref inmd) = fs::metadata(grmp)
624            && let Ok(ref out_rs_md) = fs::metadata(outp)
625            && FileTime::from_last_modification_time(out_rs_md)
626                > FileTime::from_last_modification_time(inmd)
627            && let Ok(outc) = read_to_string(outp)
628        {
629            if outc.contains(&cache) {
630                let (grm, _, _) = code_gen.finish();
631
632                return Ok(CTParser {
633                    regenerated: false,
634                    rule_ids,
635                    yacc_grammar: grm,
636                    grammar_src: inc,
637                    grammar_path: self.grammar_path.unwrap(),
638                    conflicts: None,
639                });
640            } else {
641                #[cfg(grmtools_extra_checks)]
642                if std::env::var("CACHE_EXPECTED").is_ok() {
643                    eprintln!("outc: {}", outc);
644                    eprintln!("using cache: {}", cache,);
645                    // Primarily for use in the testsuite.
646                    panic!("The cache regenerated however, it was expected to match");
647                }
648            }
649        }
650
651        // At this point, we know we're going to generate fresh output; however, if something goes
652        // wrong in the process between now and us writing /out/blah.rs, rustc thinks that
653        // everything's gone swimmingly (even if build.rs errored!), and tries to carry on
654        // compilation, leading to weird errors. We therefore delete /out/blah.rs at this point,
655        // which means, at worse, the user gets a "file not found" error from rustc (which is less
656        // confusing than the alternatives).
657        fs::remove_file(outp).ok();
658
659        let stable = code_gen.stable();
660        if self.error_on_conflicts
661            && let Some(c) = stable.conflicts()
662        {
663            match (grm.expect(), grm.expectrr()) {
664                (Some(i), Some(j)) if i == c.sr_len() && j == c.rr_len() => (),
665                (Some(i), None) if i == c.sr_len() && 0 == c.rr_len() => (),
666                (None, Some(j)) if 0 == c.sr_len() && j == c.rr_len() => (),
667                (None, None) if 0 == c.rr_len() && 0 == c.sr_len() => (),
668                _ => {
669                    let conflicts_diagnostic = yacc_diag.format_conflicts::<LexerTypesT>(
670                        grm,
671                        build_env.ast_with_validity_info().ast(),
672                        c,
673                        code_gen.sgraph(),
674                        stable,
675                    );
676                    #[cfg(test)]
677                    let (_, _, stable) = code_gen.finish();
678                    return Err(Box::new(CTConflictsError {
679                        conflicts_diagnostic,
680                        phantom: PhantomData,
681                        #[cfg(test)]
682                        stable,
683                    }));
684                }
685            }
686        }
687
688        if let Some(inspector_rt) = &mut self.inspect_rt {
689            let rt: RTParserBuilder<'_, StorageT, LexerTypesT> = RTParserBuilder::new(grm, stable);
690            let rt = if let Some(rk) = self.recoverer {
691                rt.recoverer(rk)
692            } else {
693                rt
694            };
695            inspector_rt(
696                build_env.ast_with_validity_info().header(),
697                rt,
698                &rule_ids,
699                grmp,
700            )?
701        }
702
703        self.output_file(
704            &code_gen,
705            outp,
706            &format!("/* CACHE INFORMATION {} */\n", cache),
707            &build_env,
708        )?;
709        let (grm, sgraph, stable) = code_gen.finish();
710        let conflicts = if stable.conflicts().is_some() {
711            Some((sgraph, stable))
712        } else {
713            None
714        };
715        Ok(CTParser {
716            regenerated: true,
717            rule_ids,
718            yacc_grammar: grm,
719            grammar_src: inc,
720            grammar_path: self.grammar_path.unwrap(),
721            conflicts,
722        })
723    }
724
725    /// Given the filename `a/b.y` as input, statically compile the grammar `src/a/b.y` into a Rust
726    /// module which can then be imported using `lrpar_mod!("a/b.y")`. This is a convenience
727    /// function around [`process_file`](#method.process_file) which makes it easier to compile
728    /// grammar files stored in a project's `src/` directory: please see
729    /// [`process_file`](#method.process_file) for additional constraints and information about the
730    /// generated files.
731    #[deprecated(
732        since = "0.11.0",
733        note = "Please use grammar_in_src_dir(), build(), and token_map() instead"
734    )]
735    #[allow(deprecated)]
736    pub fn process_file_in_src(
737        &mut self,
738        srcp: &str,
739    ) -> Result<HashMap<String, StorageT>, Box<dyn Error>> {
740        let mut inp = current_dir()?;
741        inp.push("src");
742        inp.push(srcp);
743        let mut outp = PathBuf::new();
744        outp.push(var("OUT_DIR").unwrap());
745        outp.push(Path::new(srcp).parent().unwrap().to_str().unwrap());
746        create_dir_all(&outp)?;
747        let mut leaf = Path::new(srcp)
748            .file_name()
749            .unwrap()
750            .to_str()
751            .unwrap()
752            .to_owned();
753        write!(leaf, ".{}", RUST_FILE_EXT).ok();
754        outp.push(leaf);
755        self.process_file(inp, outp)
756    }
757
758    /// Statically compile the Yacc file `inp` into Rust, placing the output into the file `outp`.
759    /// Note that three additional files will be created with the same name as `outp` but with the
760    /// extensions `grm`, and `stable`, overwriting any existing files with those names.
761    ///
762    /// `outp` defines a module as follows:
763    ///
764    /// ```text
765    ///   mod modname {
766    ///     pub fn parse(lexemes: &::std::vec::Vec<::lrpar::Lexeme<StorageT>>) { ... }
767    ///         -> (::std::option::Option<ActionT>,
768    ///             ::std::vec::Vec<::lrpar::LexParseError<StorageT>>)> { ...}
769    ///
770    ///     pub fn token_epp<'a>(tidx: ::cfgrammar::TIdx<StorageT>) -> ::std::option::Option<&'a str> {
771    ///       ...
772    ///     }
773    ///
774    ///     ...
775    ///   }
776    /// ```
777    ///
778    /// where:
779    ///  * `modname` is either:
780    ///    * the module name specified [`mod_name`](#method.mod_name)
781    ///    * or, if no module name was explicitly specified, then for the file `/a/b/c.y` the
782    ///      module name is `c_y` (i.e. the file's leaf name, minus its extension, with a prefix of
783    ///      `_y`).
784    ///  * `ActionT` is either:
785    ///    * the `%actiontype` value given to the grammar
786    ///    * or, if the `yacckind` was set YaccKind::Original(YaccOriginalActionKind::UserAction),
787    ///      it is [`Node<StorageT>`](../parser/enum.Node.html)
788    ///
789    /// # Panics
790    ///
791    /// If `StorageT` is not big enough to index the grammar's tokens, rules, or
792    /// productions.
793    #[deprecated(
794        since = "0.11.0",
795        note = "Please use grammar_path(), output_path(), build(), and token_map() instead"
796    )]
797    pub fn process_file<P, Q>(
798        &mut self,
799        inp: P,
800        outp: Q,
801    ) -> Result<HashMap<String, StorageT>, Box<dyn Error>>
802    where
803        P: AsRef<Path>,
804        Q: AsRef<Path>,
805    {
806        self.grammar_path = Some(inp.as_ref().to_owned());
807        self.output_path = Some(outp.as_ref().to_owned());
808        let cl: CTParserBuilder<LexerTypesT> = CTParserBuilder {
809            grammar_path: self.grammar_path.clone(),
810            grammar_src: None,
811            from_ast: None,
812            output_path: self.output_path.clone(),
813            mod_name: self.mod_name,
814            recoverer: self.recoverer,
815            yacckind: self.yacckind,
816            error_on_conflicts: self.error_on_conflicts,
817            warnings_are_errors: self.warnings_are_errors,
818            show_warnings: self.show_warnings,
819            visibility: self.visibility.clone(),
820            rust_edition: self.rust_edition,
821            inspect_rt: None,
822            serialisation_format: self.serialisation_format,
823            #[cfg(test)]
824            inspect_callback: None,
825            phantom: PhantomData,
826        };
827        Ok(cl.build()?.rule_ids)
828    }
829
830    fn output_file<P: AsRef<Path>>(
831        &self,
832        code_gen: &ParserCodegen<LexerTypesT>,
833        outp_rs: P,
834        cache: &str,
835        build_env: &ParserBuildEnv<'_, LexerTypesT>,
836    ) -> Result<(), Box<dyn Error>> {
837        let outs = code_gen
838            .generate(build_env)
839            .map_err(|e| ErrorString(e.to_string()))?;
840        let mut f = File::create(outp_rs)?;
841        f.write_all(outs.as_bytes())?;
842        f.write_all(cache.as_bytes())?;
843        Ok(())
844    }
845}
846
847/// Bundles `YaccGrammar` + `StateTable` so that generated parsers can hold
848/// them in a `OnceLock` without naming `lrtable` directly.
849#[doc(hidden)]
850pub struct ParserData<StorageT: Eq + Hash> {
851    grm: YaccGrammar<StorageT>,
852    stable: StateTable<StorageT>,
853}
854
855impl<StorageT: Eq + Hash> ParserData<StorageT> {
856    pub fn grm(&self) -> &YaccGrammar<StorageT> {
857        &self.grm
858    }
859
860    pub fn stable(&self) -> &StateTable<StorageT> {
861        &self.stable
862    }
863}
864
865/// This function is called by generated files; it exists so that generated files don't require a
866/// direct dependency on bincode.
867#[doc(hidden)]
868pub fn _reconstitute<
869    C: wincode::config::Config + Clone + Copy,
870    StorageT: SchemaReadOwned<C, Dst = StorageT> + Eq + Hash + PrimInt + Unsigned + 'static,
871>(
872    grm_buf: &[u8],
873    stable_buf: &[u8],
874    config: C,
875) -> ParserData<StorageT> {
876    let grm: YaccGrammar<StorageT> = wincode::config::deserialize_from(grm_buf, config).unwrap();
877    let stable = wincode::config::deserialize_from(stable_buf, config).unwrap();
878    ParserData { grm, stable }
879}
880
881/// An interface to the result of [CTParserBuilder::build()].
882pub struct CTParser<StorageT = u32>
883where
884    StorageT: Eq + Hash,
885{
886    regenerated: bool,
887    rule_ids: HashMap<String, StorageT>,
888    yacc_grammar: YaccGrammar<StorageT>,
889    grammar_src: String,
890    grammar_path: PathBuf,
891    conflicts: Option<(StateGraph<StorageT>, StateTable<StorageT>)>,
892}
893
894impl<StorageT> CTParser<StorageT>
895where
896    StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
897    usize: AsPrimitive<StorageT>,
898{
899    /// Returns `true` if this compile-time parser was regenerated or `false` if it was not.
900    pub fn regenerated(&self) -> bool {
901        self.regenerated
902    }
903
904    /// Returns a [HashMap] from lexeme string types to numeric types (e.g. `INT: 2`), suitable for
905    /// handing to a lexer to coordinate the IDs of lexer and parser.
906    pub fn token_map(&self) -> &HashMap<String, StorageT> {
907        &self.rule_ids
908    }
909
910    /// If there are any conflicts in the grammar, return a tuple which allows users to inspect and
911    /// pretty print them; otherwise returns `None`. If the grammar was not regenerated, this will
912    /// always return `None`, even if the grammar actually has conflicts.
913    ///
914    /// **Note: The conflicts feature is currently unstable and may change in the future.**
915    #[allow(private_interfaces)]
916    pub fn conflicts(
917        &self,
918        _: crate::unstable::UnstableApi,
919    ) -> Option<(
920        &YaccGrammar<StorageT>,
921        &StateGraph<StorageT>,
922        &StateTable<StorageT>,
923        &Conflicts<StorageT>,
924    )> {
925        if let Some((sgraph, stable)) = &self.conflicts {
926            return Some((
927                &self.yacc_grammar,
928                sgraph,
929                stable,
930                stable.conflicts().unwrap(),
931            ));
932        }
933        None
934    }
935
936    #[doc(hidden)]
937    pub fn yacc_grammar(&self) -> &YaccGrammar<StorageT> {
938        &self.yacc_grammar
939    }
940    #[doc(hidden)]
941    pub fn grammar_src(&self) -> &str {
942        &self.grammar_src
943    }
944    #[doc(hidden)]
945    pub fn grammar_path(&self) -> &Path {
946        self.grammar_path.as_path()
947    }
948}
949
950/// Indents a multi-line string and trims any trailing newline.
951/// This currently assumes that indentation on blank lines does not matter.
952///
953/// The algorithm used by this function is:
954/// 1. Prefix `s` with the indentation, indenting the first line.
955/// 2. Trim any trailing newlines.
956/// 3. Replace all newlines with `\n{indent}`` to indent all lines after the first.
957///
958/// It is plausible that we should a step 4, but currently do not:
959/// 4. Replace all `\n{indent}\n` with `\n\n`
960pub(crate) fn indent(indent: &str, s: &str) -> String {
961    format!("{indent}{}\n", s.trim_end_matches('\n')).replace('\n', &format!("\n{}", indent))
962}
963
964// Tests dealing with the filesystem not supported under wasm32
965#[cfg(all(not(target_arch = "wasm32"), test))]
966mod test {
967    use std::{fs::File, io::Write, path::PathBuf};
968
969    use super::{CTConflictsError, CTParserBuilder};
970    use crate::test_utils::TestLexerTypes;
971    use cfgrammar::yacc::{YaccKind, YaccOriginalActionKind};
972    use tempfile::TempDir;
973
974    #[test]
975    fn test_conflicts() {
976        let temp = TempDir::new().unwrap();
977        let mut file_path = PathBuf::from(temp.as_ref());
978        file_path.push("grm.y");
979        let mut f = File::create(&file_path).unwrap();
980        let _ = f.write_all(
981            "%start A
982%%
983A : 'a' 'b' | B 'b';
984B : 'a' | C;
985C : 'a';"
986                .as_bytes(),
987        );
988
989        match CTParserBuilder::<TestLexerTypes>::new()
990            .error_on_conflicts(false)
991            .yacckind(YaccKind::Original(YaccOriginalActionKind::GenericParseTree))
992            .grammar_path(file_path.to_str().unwrap())
993            .output_path(file_path.with_extension("ignored"))
994            .build()
995            .unwrap()
996            .conflicts(crate::unstable::UnstableApi)
997        {
998            Some((_, _, _, conflicts)) => {
999                assert_eq!(conflicts.sr_len(), 1);
1000                assert_eq!(conflicts.rr_len(), 1);
1001            }
1002            None => panic!("Expected error data"),
1003        }
1004    }
1005
1006    #[test]
1007    fn test_conflicts_error() {
1008        let temp = TempDir::new().unwrap();
1009        let mut file_path = PathBuf::from(temp.as_ref());
1010        file_path.push("grm.y");
1011        let mut f = File::create(&file_path).unwrap();
1012        let _ = f.write_all(
1013            "%start A
1014%%
1015A : 'a' 'b' | B 'b';
1016B : 'a' | C;
1017C : 'a';"
1018                .as_bytes(),
1019        );
1020
1021        match CTParserBuilder::<TestLexerTypes>::new()
1022            .yacckind(YaccKind::Original(YaccOriginalActionKind::GenericParseTree))
1023            .grammar_path(file_path.to_str().unwrap())
1024            .output_path(file_path.with_extension("ignored"))
1025            .build()
1026        {
1027            Ok(_) => panic!("Expected error"),
1028            Err(e) => {
1029                let cs = e.downcast_ref::<CTConflictsError<u16>>();
1030                assert_eq!(cs.unwrap().stable.conflicts().unwrap().rr_len(), 1);
1031                assert_eq!(cs.unwrap().stable.conflicts().unwrap().sr_len(), 1);
1032            }
1033        }
1034    }
1035
1036    #[test]
1037    fn test_expect_error() {
1038        let temp = TempDir::new().unwrap();
1039        let mut file_path = PathBuf::from(temp.as_ref());
1040        file_path.push("grm.y");
1041        let mut f = File::create(&file_path).unwrap();
1042        let _ = f.write_all(
1043            "%start A
1044%expect 2
1045%%
1046A: 'a' 'b' | B 'b';
1047B: 'a';"
1048                .as_bytes(),
1049        );
1050
1051        match CTParserBuilder::<TestLexerTypes>::new()
1052            .yacckind(YaccKind::Original(YaccOriginalActionKind::GenericParseTree))
1053            .grammar_path(file_path.to_str().unwrap())
1054            .output_path(file_path.with_extension("ignored"))
1055            .build()
1056        {
1057            Ok(_) => panic!("Expected error"),
1058            Err(e) => {
1059                let cs = e.downcast_ref::<CTConflictsError<u16>>();
1060                assert_eq!(cs.unwrap().stable.conflicts().unwrap().rr_len(), 0);
1061                assert_eq!(cs.unwrap().stable.conflicts().unwrap().sr_len(), 1);
1062            }
1063        }
1064    }
1065
1066    #[test]
1067    fn test_expectrr_error() {
1068        let temp = TempDir::new().unwrap();
1069        let mut file_path = PathBuf::from(temp.as_ref());
1070        file_path.push("grm.y");
1071        let mut f = File::create(&file_path).unwrap();
1072        let _ = f.write_all(
1073            "%start A
1074%expect 1
1075%expect-rr 2
1076%%
1077A : 'a' 'b' | B 'b';
1078B : 'a' | C;
1079C : 'a';"
1080                .as_bytes(),
1081        );
1082
1083        match CTParserBuilder::<TestLexerTypes>::new()
1084            .yacckind(YaccKind::Original(YaccOriginalActionKind::GenericParseTree))
1085            .grammar_path(file_path.to_str().unwrap())
1086            .output_path(file_path.with_extension("ignored"))
1087            .build()
1088        {
1089            Ok(_) => panic!("Expected error"),
1090            Err(e) => {
1091                let cs = e.downcast_ref::<CTConflictsError<u16>>();
1092                assert_eq!(cs.unwrap().stable.conflicts().unwrap().rr_len(), 1);
1093                assert_eq!(cs.unwrap().stable.conflicts().unwrap().sr_len(), 1);
1094            }
1095        }
1096    }
1097
1098    #[test]
1099    /// Tests a yacc .y filename containing a dash character leading to an invalid rust identifier
1100    /// when that dash is subsequently used as the default `CTParserBuilder::mod_name`.
1101    fn test_invalid_identifier_in_derived_mod_name() {
1102        let temp = TempDir::new().unwrap();
1103        let mut file_path = PathBuf::from(temp.as_ref());
1104        file_path.push("contains-a-dash.y");
1105        let mut f = File::create(&file_path).unwrap();
1106        let _ = f.write_all(
1107            "%start A
1108%%
1109A : 'a';"
1110                .as_bytes(),
1111        );
1112        match CTParserBuilder::<TestLexerTypes>::new()
1113            .yacckind(YaccKind::Original(YaccOriginalActionKind::GenericParseTree))
1114            .grammar_path(file_path.to_str().unwrap())
1115            .output_path(file_path.with_extension("ignored"))
1116            .build()
1117        {
1118            Ok(_) => panic!("Expected error"),
1119            Err(e) => {
1120                let err_string = e.to_string();
1121                assert_eq!(
1122                    err_string,
1123                    "mod_name \'contains-a-dash_y\' is not a valid rust identifier due to 'unexpected token'"
1124                );
1125            }
1126        }
1127    }
1128
1129    #[cfg(test)]
1130    #[test]
1131    fn test_recoverer_header() -> Result<(), Box<dyn std::error::Error>> {
1132        use crate::RecoveryKind as RK;
1133        #[rustfmt::skip]
1134            let recovery_kinds = [
1135                //  Builder,          Header setting,     Expected result.
1136                // -----------       ------------------  -------------------
1137                (Some(RK::None),      Some(RK::None),     Some(RK::None)),
1138                (Some(RK::None),      Some(RK::CPCTPlus), Some(RK::None)),
1139                (Some(RK::CPCTPlus),  Some(RK::CPCTPlus), Some(RK::CPCTPlus)),
1140                (Some(RK::CPCTPlus),  Some(RK::None),     Some(RK::CPCTPlus)),
1141                (None,                Some(RK::CPCTPlus), Some(RK::CPCTPlus)),
1142                (None,                Some(RK::None),     Some(RK::None)),
1143                (None,                None,               Some(RK::CPCTPlus)),
1144                (Some(RK::None),      None,               Some(RK::None)),
1145                (Some(RK::CPCTPlus),  None,               Some(RK::CPCTPlus)),
1146            ];
1147
1148        for (i, (builder_arg, header_arg, expected_rk)) in
1149            recovery_kinds.iter().cloned().enumerate()
1150        {
1151            let y_src = if let Some(header_arg) = header_arg {
1152                format!(
1153                    "\
1154                    %grmtools{{yacckind: Original(NoAction), recoverer: {}}} \
1155                    %% \
1156                    start: ; \
1157                    ",
1158                    match header_arg {
1159                        RK::None => "RecoveryKind::None",
1160                        RK::CPCTPlus => "RecoveryKind::CPCTPlus",
1161                    }
1162                )
1163            } else {
1164                r#"
1165                    %grmtools{yacckind: Original(NoAction)}
1166                    %%
1167                    Start: ;
1168                    "#
1169                .to_string()
1170            };
1171            let out_dir = std::env::var("OUT_DIR").unwrap();
1172            let y_path = format!("{out_dir}/recoverykind_test_{i}.y");
1173            let y_out_path = format!("{y_path}.rs");
1174            std::fs::File::create(y_path.clone()).unwrap();
1175            std::fs::write(y_path.clone(), y_src).unwrap();
1176            let mut cp_builder = CTParserBuilder::<TestLexerTypes>::new();
1177            cp_builder = cp_builder
1178                .output_path(y_out_path.clone())
1179                .grammar_path(y_path.clone());
1180            cp_builder = if let Some(builder_arg) = builder_arg {
1181                cp_builder.recoverer(builder_arg)
1182            } else {
1183                cp_builder
1184            }
1185            .inspect_recoverer(Box::new(move |rk| {
1186                if matches!(
1187                    (rk, expected_rk),
1188                    (RK::None, Some(RK::None)) | (RK::CPCTPlus, Some(RK::CPCTPlus))
1189                ) {
1190                    Ok(())
1191                } else {
1192                    panic!("Unexpected recovery kind")
1193                }
1194            }));
1195            cp_builder.build()?;
1196        }
1197        Ok(())
1198    }
1199}