Skip to main content

lrlex/
ctbuilder.rs

1//! Build grammars at run-time.
2
3use cfgrammar::{
4    header::{Header, HeaderError, HeaderErrorKind, HeaderValue, Value},
5    markmap::MergeBehavior,
6    span::{Location, Span},
7};
8use glob::glob;
9use lrpar::{
10    CTParserBuilder, LexerTypes,
11    diagnostics::{DiagnosticFormatter, SpannedDiagnosticFormatter},
12};
13use num_traits::{AsPrimitive, PrimInt, Unsigned};
14use proc_macro2::{Ident, TokenStream};
15use quote::{ToTokens, format_ident, quote};
16use std::{
17    any::type_name,
18    borrow::Borrow,
19    collections::{HashMap, HashSet},
20    env::{current_dir, var},
21    error::Error,
22    fmt::{self, Debug, Display, Write as _},
23    fs::{self, File, create_dir_all, read_to_string},
24    hash::Hash,
25    io::Write,
26    marker::PhantomData,
27    path::{Path, PathBuf},
28    sync::{LazyLock, Mutex},
29};
30use wincode::SchemaWrite;
31
32use crate::{
33    DefaultLexerTypes, LRNonStreamingLexer, LexerDef,
34    codegen::{LexerBuildEnvArgs, LexerSrcEnv, LexerSrcEnvError},
35};
36
37const RUST_FILE_EXT: &str = "rs";
38
39const ERROR: &str = "[Error]";
40const WARNING: &str = "[Warning]";
41
42static GENERATED_PATHS: LazyLock<Mutex<HashSet<PathBuf>>> =
43    LazyLock::new(|| Mutex::new(HashSet::new()));
44
45#[non_exhaustive]
46pub enum LexerKind {
47    LRNonStreamingLexer,
48}
49
50impl<T: Clone> TryFrom<&Value<T>> for LexerKind {
51    type Error = cfgrammar::header::HeaderError<T>;
52    fn try_from(it: &Value<T>) -> Result<LexerKind, Self::Error> {
53        match it {
54            Value::Namespaced(rs, loc) => match rs.as_str() {
55                "LexerKind::LRNonStreamingLexer" | "LRNonStreamingLexer" => {
56                    Ok(LexerKind::LRNonStreamingLexer)
57                }
58                _ => Err(HeaderError {
59                    kind: HeaderErrorKind::ConversionError("LexerKind", "Expected `LexerKind`"),
60                    locations: vec![loc.clone()],
61                }),
62            },
63            val => Err(HeaderError {
64                kind: HeaderErrorKind::ConversionError("LexerKind", "Expected `LexerKind`"),
65                locations: vec![val.primary_location().clone()],
66            }),
67        }
68    }
69}
70
71/// Specify the visibility of the module generated by [CTLexerBuilder].
72#[derive(Clone, PartialEq, Eq, Debug)]
73#[non_exhaustive]
74pub enum Visibility {
75    /// Module-level visibility only.
76    Private,
77    /// `pub`
78    Public,
79    /// `pub(super)`
80    PublicSuper,
81    /// `pub(self)`
82    PublicSelf,
83    /// `pub(crate)`
84    PublicCrate,
85    /// `pub(in {arg})`
86    PublicIn(String),
87}
88
89impl ToTokens for Visibility {
90    fn to_tokens(&self, tokens: &mut TokenStream) {
91        tokens.extend(match self {
92            Visibility::Private => quote!(),
93            Visibility::Public => quote! {pub},
94            Visibility::PublicSuper => quote! {pub(super)},
95            Visibility::PublicSelf => quote! {pub(self)},
96            Visibility::PublicCrate => quote! {pub(crate)},
97            Visibility::PublicIn(data) => {
98                let other = str::parse::<TokenStream>(data).unwrap();
99                quote! {pub(in #other)}
100            }
101        })
102    }
103}
104
105/// Specifies the [Rust Edition] that will be emitted during code generation.
106///
107/// [Rust Edition]: https://doc.rust-lang.org/edition-guide/rust-2021/index.html
108#[derive(Clone, Copy, PartialEq, Eq, Debug)]
109#[non_exhaustive]
110pub enum RustEdition {
111    Rust2015,
112    Rust2018,
113    Rust2021,
114}
115
116/// A string which uses `Display` for it's `Debug` impl.
117struct ErrorString(String);
118impl fmt::Display for ErrorString {
119    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
120        let ErrorString(s) = self;
121        write!(f, "{}", s)
122    }
123}
124impl fmt::Debug for ErrorString {
125    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
126        let ErrorString(s) = self;
127        write!(f, "{}", s)
128    }
129}
130impl Error for ErrorString {}
131
132/// A `CTLexerBuilder` allows one to specify the criteria for building a statically generated
133/// lexer.
134pub struct CTLexerBuilder<'a, LexerTypesT: LexerTypes = DefaultLexerTypes<u32>>
135where
136    LexerTypesT::StorageT: Debug + Eq + Hash + ToTokens,
137    usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
138{
139    lrpar_config:
140        Option<Box<dyn Fn(CTParserBuilder<LexerTypesT>) -> CTParserBuilder<LexerTypesT> + 'a>>,
141    lexer_path: Option<PathBuf>,
142    output_path: Option<PathBuf>,
143    lexerkind: Option<LexerKind>,
144    mod_name: Option<&'a str>,
145    visibility: Visibility,
146    rust_edition: RustEdition,
147    rule_ids_map: Option<HashMap<String, LexerTypesT::StorageT>>,
148    allow_missing_terms_in_lexer: bool,
149    allow_missing_tokens_in_parser: bool,
150    warnings_are_errors: bool,
151    show_warnings: bool,
152    header: Header<Location>,
153    #[cfg(test)]
154    inspect_lexerkind_cb: Option<Box<dyn Fn(&LexerKind) -> Result<(), Box<dyn Error>>>>,
155}
156
157impl CTLexerBuilder<'_, DefaultLexerTypes<u32>> {
158    /// Create a new [CTLexerBuilder].
159    pub fn new() -> Self {
160        CTLexerBuilder::<DefaultLexerTypes<u32>>::new_with_lexemet()
161    }
162}
163type FixIntConfig = wincode::config::Configuration;
164
165type VarIntConfig = wincode::config::Configuration<
166    true,
167    4194304,
168    wincode::len::BincodeLen,
169    wincode::int_encoding::LittleEndian,
170    wincode::int_encoding::VarInt,
171>;
172impl<'a, LexerTypesT: LexerTypes<LexErrorT = crate::LRLexError> + 'static>
173    CTLexerBuilder<'a, LexerTypesT>
174where
175    LexerTypesT::StorageT: 'static
176        + Debug
177        + Eq
178        + Hash
179        + PrimInt
180        + SchemaWrite<FixIntConfig, Src = LexerTypesT::StorageT>
181        + SchemaWrite<VarIntConfig, Src = LexerTypesT::StorageT>
182        + TryFrom<usize>
183        + Unsigned
184        + ToTokens,
185    usize: AsPrimitive<LexerTypesT::StorageT>,
186{
187    /// Create a new [CTLexerBuilder].
188    ///
189    /// `LexerTypesT::StorageT` must be an unsigned integer type (e.g. `u8`, `u16`) which is big enough
190    /// to index all the tokens, rules, and productions in the lexer and less than or equal in size
191    /// to `usize` (e.g. on a 64-bit machine `u128` would be too big). If you are lexing large
192    /// files, the additional storage requirements of larger integer types can be noticeable, and
193    /// in such cases it can be worth specifying a smaller type. `StorageT` defaults to `u32` if
194    /// unspecified.
195    ///
196    /// # Examples
197    ///
198    /// ```text
199    /// CTLexerBuilder::<DefaultLexerTypes<u8>>::new_with_lexemet()
200    ///     .lexer_in_src_dir("grm.l", None)?
201    ///     .build()?;
202    /// ```
203    pub fn new_with_lexemet() -> Self {
204        let mut header = Header::new();
205        header.set_default_merge_behavior(MergeBehavior::Ours);
206        CTLexerBuilder {
207            lrpar_config: None,
208            lexer_path: None,
209            output_path: None,
210            lexerkind: None,
211            mod_name: None,
212            visibility: Visibility::Private,
213            rust_edition: RustEdition::Rust2021,
214            rule_ids_map: None,
215            allow_missing_terms_in_lexer: false,
216            allow_missing_tokens_in_parser: false,
217            warnings_are_errors: false,
218            show_warnings: true,
219            header,
220            #[cfg(test)]
221            inspect_lexerkind_cb: None,
222        }
223    }
224
225    /// An optional convenience function to make it easier to create an (lrlex) lexer and (lrpar)
226    /// parser in one shot. The closure passed to this function will be called during
227    /// [CTLexerBuilder::build]: it will be passed an lrpar `CTParserBuilder` instance upon which
228    /// it can set whatever lrpar options are desired. [`CTLexerBuilder`] will then create both the
229    /// compiler and lexer and link them together as required.
230    ///
231    /// # Examples
232    ///
233    /// ```text
234    /// CTLexerBuilder:::new()
235    ///     .lrpar_config(|ctp| {
236    ///         ctp.yacckind(YaccKind::Grmtools)
237    ///             .grammar_in_src_dir("calc.y")
238    ///             .unwrap()
239    ///     })
240    ///     .lexer_in_src_dir("calc.l")?
241    ///     .build()?;
242    /// ```
243    pub fn lrpar_config<F>(mut self, config_func: F) -> Self
244    where
245        F: Fn(CTParserBuilder<LexerTypesT>) -> CTParserBuilder<LexerTypesT> + 'a,
246    {
247        self.lrpar_config = Some(Box::new(config_func));
248        self
249    }
250
251    /// Set the input lexer path to a file relative to this project's `src` directory. This will
252    /// also set the output path (i.e. you do not need to call [CTLexerBuilder::output_path]).
253    ///
254    /// For example if `a/b.l` is passed as `inp` then [CTLexerBuilder::build] will:
255    ///   * use `src/a/b.l` as the input file.
256    ///   * write output to a file which can then be imported by calling `lrlex_mod!("a/b.l")`.
257    ///   * create a module in that output file named `b_l`.
258    ///
259    /// You can override the output path and/or module name by calling
260    /// [CTLexerBuilder::output_path] and/or [CTLexerBuilder::mod_name], respectively, after
261    /// calling this function.
262    ///
263    /// This is a convenience function that makes it easier to compile lexer files stored in a
264    /// project's `src/` directory: please see [CTLexerBuilder::build] for additional constraints
265    /// and information about the generated files. Note also that each `.l` file can only be
266    /// processed once using this function: if you want to generate multiple lexers from a single
267    /// `.l` file, you will need to use [CTLexerBuilder::output_path].
268    pub fn lexer_in_src_dir<P>(mut self, srcp: P) -> Result<Self, Box<dyn Error>>
269    where
270        P: AsRef<Path>,
271    {
272        if !srcp.as_ref().is_relative() {
273            return Err(format!(
274                "Lexer path '{}' must be a relative path.",
275                srcp.as_ref().to_str().unwrap_or("<invalid UTF-8>")
276            )
277            .into());
278        }
279
280        let mut lexp = current_dir()?;
281        lexp.push("src");
282        lexp.push(srcp.as_ref());
283        self.lexer_path = Some(lexp);
284
285        let mut outp = PathBuf::new();
286        outp.push(var("OUT_DIR").unwrap());
287        outp.push(srcp.as_ref().parent().unwrap().to_str().unwrap());
288        create_dir_all(&outp)?;
289        let mut leaf = srcp
290            .as_ref()
291            .file_name()
292            .unwrap()
293            .to_str()
294            .unwrap()
295            .to_owned();
296        write!(leaf, ".{}", RUST_FILE_EXT).ok();
297        outp.push(leaf);
298        Ok(self.output_path(outp))
299    }
300
301    /// Set the input lexer path to `inp`. If specified, you must also call
302    /// [CTLexerBuilder::output_path]. In general it is easier to use
303    /// [CTLexerBuilder::lexer_in_src_dir].
304    pub fn lexer_path<P>(mut self, inp: P) -> Self
305    where
306        P: AsRef<Path>,
307    {
308        self.lexer_path = Some(inp.as_ref().to_owned());
309        self
310    }
311
312    /// Set the output lexer path to `outp`. Note that there are no requirements on `outp`: the
313    /// file can exist anywhere you can create a valid [Path] to. However, if you wish to use
314    /// [crate::lrlex_mod!] you will need to make sure that `outp` is in
315    /// [std::env::var]`("OUT_DIR")` or one of its subdirectories.
316    pub fn output_path<P>(mut self, outp: P) -> Self
317    where
318        P: AsRef<Path>,
319    {
320        self.output_path = Some(outp.as_ref().to_owned());
321        self
322    }
323
324    /// Set the type of lexer to be generated to `lexerkind`.
325    pub fn lexerkind(mut self, lexerkind: LexerKind) -> Self {
326        self.lexerkind = Some(lexerkind);
327        self
328    }
329
330    /// Set the generated module name to `mod_name`. If no module name is specified,
331    /// [`process_file`](#method.process_file) will attempt to create a sensible default based on
332    /// the input filename.
333    pub fn mod_name(mut self, mod_name: &'a str) -> Self {
334        self.mod_name = Some(mod_name);
335        self
336    }
337
338    /// Set the visibility of the generated module to `vis`. Defaults to `Visibility::Private`.
339    pub fn visibility(mut self, vis: Visibility) -> Self {
340        self.visibility = vis;
341        self
342    }
343
344    /// Sets the rust edition to be used for generated code. Defaults to the latest edition of
345    /// rust supported by grmtools.
346    pub fn rust_edition(mut self, edition: RustEdition) -> Self {
347        self.rust_edition = edition;
348        self
349    }
350
351    /// Set this lexer builder's map of rule IDs to `rule_ids_map`. By default, lexing rules have
352    /// arbitrary, but distinct, IDs. Setting the map of rule IDs (from rule names to `StorageT`)
353    /// allows users to synchronise a lexer and parser and to check that all rules are used by both
354    /// parts).
355    pub fn rule_ids_map<T: std::borrow::Borrow<HashMap<String, LexerTypesT::StorageT>> + Clone>(
356        mut self,
357        rule_ids_map: T,
358    ) -> Self {
359        self.rule_ids_map = Some(rule_ids_map.borrow().to_owned());
360        self
361    }
362
363    /// Statically compile the `.l` file specified by [CTLexerBuilder::lexer_path()] into Rust,
364    /// placing the output into the file specified by [CTLexerBuilder::output_path()].
365    ///
366    /// The generated module follows the form:
367    ///
368    /// ```text
369    ///    mod modname {
370    ///      pub fn lexerdef() -> LexerDef<LexerTypesT> { ... }
371    ///
372    ///      ...
373    ///    }
374    /// ```
375    ///
376    /// where:
377    ///  * `modname` is either:
378    ///    * the module name specified by [CTLexerBuilder::mod_name()]
379    ///    * or, if no module name was explicitly specified, then for the file `/a/b/c.l` the
380    ///      module name is `c_l` (i.e. the file's leaf name, minus its extension, with a prefix of
381    ///      `_l`).
382    pub fn build(mut self) -> Result<CTLexer, Box<dyn Error>> {
383        let lexerp = self
384            .lexer_path
385            .as_ref()
386            .expect("lexer_path must be specified before processing.");
387        let outp = self
388            .output_path
389            .as_ref()
390            .expect("output_path must be specified before processing.");
391
392        {
393            let mut lk = GENERATED_PATHS.lock().unwrap();
394            if lk.contains(outp.as_path()) {
395                return Err(format!("Generating two lexers to the same path ('{}') is not allowed: use CTLexerBuilder::output_path (and, optionally, CTLexerBuilder::mod_name) to differentiate them.", outp.to_str().unwrap()).into());
396            }
397            lk.insert(outp.clone());
398        }
399        let lex_src = read_to_string(lexerp)
400            .map_err(|e| format!("When reading '{}': {e}", lexerp.display()))?;
401        let lex_diag = SpannedDiagnosticFormatter::new(&lex_src, lexerp);
402        let args = LexerBuildEnvArgs::new()
403            .mod_name(self.mod_name.map(|s| s.to_string()))
404            .lexerkind(self.lexerkind)
405            .visibility(self.visibility);
406        let mut build_env =
407            LexerSrcEnv::<LexerTypesT>::new_with_header(&lex_src, Some(lexerp), self.header)
408                .build_env(args)
409                .map_err(|e| match e {
410                    LexerSrcEnvError::GrmtoolsSectionParseError(es) => {
411                        let mut out = String::new();
412                        out.push_str(&format!(
413                            "\n{ERROR}{}\n",
414                            lex_diag.file_location_msg(" parsing the `%grmtools` section", None)
415                        ));
416                        for e in es {
417                            out.push_str(&indent("     ", &lex_diag.format_error(e).to_string()));
418                            out.push('\n');
419                        }
420                        ErrorString(out)
421                    }
422                    LexerSrcEnvError::LexBuildErrors(errs) => {
423                        let mut out = String::new();
424                        out.push_str(&format!(
425                            "\n{ERROR}{}\n",
426                            lex_diag.file_location_msg(" building the lexer", None)
427                        ));
428                        for e in errs {
429                            out.push_str(&indent("     ", &lex_diag.format_error(e).to_string()));
430                            out.push('\n');
431                        }
432                        ErrorString(out)
433                    }
434                    e => ErrorString(e.to_string()),
435                })?;
436
437        #[cfg(test)]
438        if let Some(inspect_lexerkind_cb) = self.inspect_lexerkind_cb {
439            inspect_lexerkind_cb(build_env.lexerkind())?
440        }
441
442        let ct_parser = if let Some(ref lrcfg) = self.lrpar_config {
443            let mut closure_lexerdef = build_env.lexerdef().clone();
444            let mut ctp = CTParserBuilder::<LexerTypesT>::new().inspect_rt(Box::new(
445                move |yacc_header, rtpb, rule_ids_map, grm_path| {
446                    let owned_map = rule_ids_map
447                        .iter()
448                        .map(|(x, y)| (&**x, *y))
449                        .collect::<HashMap<_, _>>();
450                    closure_lexerdef.set_rule_ids(&owned_map);
451                    let grammar = rtpb.grammar();
452                    let test_glob = yacc_header.get("lrpar.test_files");
453                    let mut err_str = None;
454                    let add_error_line = |err_str: &mut Option<String>, line| {
455                        if let Some(err_str) = err_str {
456                            err_str.push_str(&format!("{}\n", line));
457                        } else {
458                            let _ = err_str.insert(format!("{}\n", line));
459                        }
460                    };
461                    match test_glob {
462                        Some(HeaderValue(_, Value::Array(test_globs, _))) => {
463                            for setting in test_globs {
464                                match setting {
465                                    Value::String(test_files, _) => {
466                                        let path_joined = grm_path.parent().unwrap().join(test_files);
467                                        let path_str = &path_joined.to_string_lossy();
468                                        let mut glob_paths = glob(path_str).map_err(|e| e.to_string())?.peekable();
469                                        if glob_paths.peek().is_none() {
470                                            return Err(format!("'test_files' glob '{}' matched no paths", path_str)
471                                                .to_string()
472                                                .into(),
473                                            );
474                                        }
475
476                                        for path in glob_paths {
477                                            let path = path?;
478                                            if let Some(ext) = path.extension()
479                                                && let Some(ext) = ext.to_str()
480                                                    && ext.starts_with("grm") {
481                                                        add_error_line(&mut err_str, "test_files extensions beginning with `grm` are reserved.".into());
482                                                    }
483                                            let input = fs::read_to_string(&path)?;
484                                            let l: LRNonStreamingLexer<LexerTypesT> =
485                                                closure_lexerdef.lexer(&input);
486                                            let errs = rtpb.parse_map(&l, &|_| (), &|_, _| ()).1;
487                                            if !errs.is_empty() {
488                                                add_error_line(&mut err_str, format!("While parsing {}:", path.display()));
489                                                for e in errs {
490                                                    let e_pp = e.pp(&l, &|t| grammar.token_epp(t));
491                                                    let e_lines = e_pp.split("\n");
492                                                    for e in e_lines {
493                                                        add_error_line(&mut err_str, format!("\t{}", e));
494                                                    }
495                                                }
496                                            }
497                                        }
498                                    }
499                                    _ => return Err("Invalid value for setting 'test_files'".into()),
500                                }
501                            }
502                            if let Some(err_str) = err_str {
503                                Err(ErrorString(err_str))?
504                            } else {
505                                Ok(())
506                            }
507
508                        }
509                        Some(_) => Err("Invalid value for setting 'test_files'".into()),
510                        None => Ok(()),
511                    }
512                },
513            ));
514            ctp = lrcfg(ctp);
515            let ct_parser = ctp.build()?;
516            self.rule_ids_map = Some(ct_parser.token_map().to_owned());
517            Some(ct_parser)
518        } else {
519            None
520        };
521
522        let unused_header_values = build_env
523            .header()
524            .unused()
525            .map(|(s, _)| s.to_string())
526            .collect::<Vec<String>>();
527        if !unused_header_values.is_empty() {
528            return Err(
529                format!("Unused header values: {}", unused_header_values.join(", ")).into(),
530            );
531        }
532
533        let code_gen = build_env
534            .code_generator(self.rule_ids_map, env!("VERGEN_BUILD_TIMESTAMP"))
535            .map_err(|e| match e {})?;
536        let (mut missing_from_lexer, missing_from_parser) = {
537            let lexerdef = Box::new(build_env.lexerdef_mut());
538            match code_gen.rule_ids_map() {
539                Some(rim) => {
540                    // Convert from HashMap<String, _> to HashMap<&str, _>
541                    let owned_map = rim
542                        .iter()
543                        .map(|(x, y)| (&**x, *y))
544                        .collect::<HashMap<_, _>>();
545                    let (x, y) = lexerdef.set_rule_ids_spanned(&owned_map);
546                    (
547                        x.map(|a| a.iter().map(|&b| b.to_string()).collect::<HashSet<_>>()),
548                        y.map(|a| {
549                            a.iter()
550                                .map(|(b, span)| (b.to_string(), *span))
551                                .collect::<HashSet<_>>()
552                        }),
553                    )
554                }
555                None => (None, None),
556            }
557        };
558        let lexerdef = build_env.lexerdef();
559        if let Some(mut mfl) = missing_from_lexer.take() {
560            for tok in &lexerdef.expected_missing_tokens {
561                mfl.remove(tok.as_str());
562            }
563            if mfl.is_empty() {
564                missing_from_lexer = None;
565            } else {
566                missing_from_lexer = Some(mfl);
567            }
568        }
569
570        let mut has_unallowed_missing = false;
571        let err_indent = " ".repeat(ERROR.len());
572        if !self.allow_missing_terms_in_lexer
573            && let Some(ref mfl) = missing_from_lexer
574        {
575            if let Some(ct_parser) = &ct_parser {
576                let grm = ct_parser.yacc_grammar();
577                let token_spans = mfl
578                    .iter()
579                    .map(|name| {
580                        ct_parser
581                            .yacc_grammar()
582                            .token_span(*grm.tokens_map().get(name.as_str()).unwrap())
583                            .expect("Given token should have a span")
584                    })
585                    .collect::<Vec<_>>();
586
587                let yacc_diag = SpannedDiagnosticFormatter::new(
588                    ct_parser.grammar_src(),
589                    ct_parser.grammar_path(),
590                );
591
592                eprintln!(
593                    "{ERROR} these tokens are not referenced in the lexer but defined as follows"
594                );
595                eprintln!(
596                    "{err_indent} {}",
597                    yacc_diag.file_location_msg("in the grammar", None)
598                );
599                for span in token_spans {
600                    eprintln!(
601                        "{}",
602                        yacc_diag.underline_span_with_text(
603                            span,
604                            "Missing from lexer".to_string(),
605                            '^'
606                        )
607                    );
608                }
609                eprintln!();
610            } else {
611                eprintln!(
612                    "{ERROR} the following tokens are used in the grammar but are not defined in the lexer:"
613                );
614                for n in mfl {
615                    eprintln!("    {}", n);
616                }
617            }
618            has_unallowed_missing = true;
619        }
620        if !self.allow_missing_tokens_in_parser
621            && self.show_warnings
622            && let Some(ref mfp) = missing_from_parser
623        {
624            let error_prefix = if self.warnings_are_errors {
625                ERROR
626            } else {
627                WARNING
628            };
629            let err_indent = " ".repeat(error_prefix.len());
630            let mut outs = Vec::new();
631            outs.push(format!("{error_prefix} these tokens are not referenced in the grammar but defined as follows"));
632            outs.push(format!(
633                "{err_indent} {}",
634                lex_diag.file_location_msg("in the lexer", None)
635            ));
636            for (_, span) in mfp {
637                let error_contents = lex_diag.underline_span_with_text(
638                    *span,
639                    "Missing from parser".to_string(),
640                    '^',
641                );
642                outs.extend(error_contents.lines().map(|s| s.to_string()));
643            }
644
645            for s in outs {
646                if !self.warnings_are_errors && std::env::var("OUT_DIR").is_ok() {
647                    println!("cargo:warning={}", s)
648                } else {
649                    eprintln!("{}", s);
650                }
651            }
652
653            has_unallowed_missing |= self.warnings_are_errors;
654        }
655        if has_unallowed_missing {
656            fs::remove_file(outp).ok();
657            panic!();
658        }
659        let outs = code_gen
660            .generate(&build_env)
661            .map_err(|e| ErrorString(e.to_string()))?;
662        // If the file we're about to write out already exists with the same contents, then we
663        // don't overwrite it (since that will force a recompile of the file, and relinking of the
664        // binary etc).
665        if let Ok(curs) = read_to_string(outp)
666            && curs == outs
667        {
668            return Ok(CTLexer {
669                missing_from_lexer,
670                missing_from_parser,
671            });
672        }
673        let mut f = File::create(outp)?;
674        f.write_all(outs.as_bytes())?;
675        Ok(CTLexer {
676            missing_from_lexer,
677            missing_from_parser,
678        })
679    }
680
681    /// Given the filename `a/b.l` as input, statically compile the file `src/a/b.l` into a Rust
682    /// module which can then be imported using `lrlex_mod!("a/b.l")`. This is a convenience
683    /// function around [`process_file`](struct.CTLexerBuilder.html#method.process_file) which makes
684    /// it easier to compile `.l` files stored in a project's `src/` directory: please see
685    /// [`process_file`](#method.process_file) for additional constraints and information about the
686    /// generated files.
687    #[deprecated(
688        since = "0.11.0",
689        note = "Please use lexer_in_src_dir() and build() instead"
690    )]
691    #[allow(deprecated)]
692    pub fn process_file_in_src(
693        self,
694        srcp: &str,
695    ) -> Result<(Option<HashSet<String>>, Option<HashSet<String>>), Box<dyn Error>> {
696        let mut inp = current_dir()?;
697        inp.push("src");
698        inp.push(srcp);
699        let mut outp = PathBuf::new();
700        outp.push(var("OUT_DIR").unwrap());
701        outp.push(Path::new(srcp).parent().unwrap().to_str().unwrap());
702        create_dir_all(&outp)?;
703        let mut leaf = Path::new(srcp)
704            .file_name()
705            .unwrap()
706            .to_str()
707            .unwrap()
708            .to_owned();
709        write!(leaf, ".{}", RUST_FILE_EXT).ok();
710        outp.push(leaf);
711        self.process_file(inp, outp)
712    }
713
714    /// Statically compile the `.l` file `inp` into Rust, placing the output into the file `outp`.
715    /// The latter defines a module as follows:
716    ///
717    /// ```text
718    ///    mod modname {
719    ///      pub fn lexerdef() -> LexerDef<LexerTypesT::StorageT> { ... }
720    ///
721    ///      ...
722    ///    }
723    /// ```
724    ///
725    /// where:
726    ///  * `modname` is either:
727    ///    * the module name specified [`mod_name`](#method.mod_name)
728    ///    * or, if no module name was explicitly specified, then for the file `/a/b/c.l` the
729    ///      module name is `c_l` (i.e. the file's leaf name, minus its extension, with a prefix of
730    ///      `_l`).
731    #[deprecated(
732        since = "0.11.0",
733        note = "Please use lexer_in_src_dir() and build() instead"
734    )]
735    pub fn process_file<P, Q>(
736        mut self,
737        inp: P,
738        outp: Q,
739    ) -> Result<(Option<HashSet<String>>, Option<HashSet<String>>), Box<dyn Error>>
740    where
741        P: AsRef<Path>,
742        Q: AsRef<Path>,
743    {
744        self.lexer_path = Some(inp.as_ref().to_owned());
745        self.output_path = Some(outp.as_ref().to_owned());
746        let cl = self.build()?;
747        Ok((
748            cl.missing_from_lexer().map(|x| x.to_owned()),
749            cl.missing_from_parser()
750                .map(|x| x.iter().map(|(n, _)| n.to_owned()).collect::<HashSet<_>>()),
751        ))
752    }
753
754    /// If passed false, tokens used in the grammar but not defined in the lexer will cause a
755    /// panic at lexer generation time. Defaults to false.
756    pub fn allow_missing_terms_in_lexer(mut self, allow: bool) -> Self {
757        self.allow_missing_terms_in_lexer = allow;
758        self
759    }
760
761    /// If passed false, tokens defined in the lexer but not used in the grammar will cause a
762    /// warning at lexer generation time. Defaults to false (since lexers sometimes define tokens such
763    /// as reserved words, which are intentionally not in the grammar).
764    pub fn allow_missing_tokens_in_parser(mut self, allow: bool) -> Self {
765        self.allow_missing_tokens_in_parser = allow;
766        self
767    }
768
769    /// If set to true, [CTLexerBuilder::build] will return an error if the given lexer contains
770    /// any warnings. Defaults to `true`.
771    pub fn warnings_are_errors(mut self, flag: bool) -> Self {
772        self.warnings_are_errors = flag;
773        self
774    }
775
776    /// If set to true, [CTParserBuilder::build] will print warnings to stderr, or via cargo when
777    /// running under cargo. Defaults to `true`.
778    pub fn show_warnings(mut self, flag: bool) -> Self {
779        self.show_warnings = flag;
780        self
781    }
782
783    /// Enables `// comment` style parsing according to `flag``.
784    /// When enabled comments can appear at the beginning of a line,
785    /// and regular expressions with the `/` character should be escaped via `\/`.
786    ///
787    /// The default value is `false`.
788    ///
789    /// Setting this flag will override the same flag within a `%grmtools` section.
790    pub fn allow_wholeline_comments(mut self, flag: bool) -> Self {
791        let key = "lrlex.allow_wholeline_comments".to_string();
792        self.header.insert(
793            key,
794            HeaderValue(
795                Location::Other("CTLexerBuilder".to_string()),
796                Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
797            ),
798        );
799        self
800    }
801
802    /// Sets the `regex::RegexBuilder` option of the same name.
803    /// The default value is `true`.
804    ///
805    /// Setting this flag will override the same flag within a `%grmtools` section.
806    pub fn dot_matches_new_line(mut self, flag: bool) -> Self {
807        let key = "regex.dot_matches_new_line".to_string();
808        self.header.insert(
809            key,
810            HeaderValue(
811                Location::Other("CTLexerBuilder".to_string()),
812                Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
813            ),
814        );
815        self
816    }
817
818    /// Sets the `regex::RegexBuilder` option of the same name.
819    /// The default value is `true`.
820    ///
821    /// Setting this flag will override the same flag within a `%grmtools` section.
822    pub fn multi_line(mut self, flag: bool) -> Self {
823        let key = "regex.multi_line".to_string();
824        self.header.insert(
825            key,
826            HeaderValue(
827                Location::Other("CTLexerBuilder".to_string()),
828                Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
829            ),
830        );
831        self
832    }
833
834    /// Enables posix lex compatible escape sequences according to `flag`.
835    /// The default value is `false`.
836    ///
837    /// Setting this flag will override the same flag within a `%grmtools` section.
838    pub fn posix_escapes(mut self, flag: bool) -> Self {
839        let key = "lrlex.posix_escapes".to_string();
840        self.header.insert(
841            key,
842            HeaderValue(
843                Location::Other("CTLexerBuilder".to_string()),
844                Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
845            ),
846        );
847        self
848    }
849
850    /// Sets the `regex::RegexBuilder` option of the same name.
851    /// The default value is `true`.
852    ///
853    /// Setting this flag will override the same flag within a `%grmtools` section.
854    pub fn octal(mut self, flag: bool) -> Self {
855        let key = "regex.octal".to_string();
856        self.header.insert(
857            key,
858            HeaderValue(
859                Location::Other("CTLexerBuilder".to_string()),
860                Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
861            ),
862        );
863        self
864    }
865
866    /// Sets the `regex::RegexBuilder` option of the same name.
867    /// Default value is specified by regex.
868    ///
869    /// Setting this flag will override the same flag within a `%grmtools` section.
870    pub fn swap_greed(mut self, flag: bool) -> Self {
871        let key = "regex.swap_greed".to_string();
872        self.header.insert(
873            key,
874            HeaderValue(
875                Location::Other("CTLexerBuilder".to_string()),
876                Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
877            ),
878        );
879        self
880    }
881
882    /// Sets the `regex::RegexBuilder` option of the same name.
883    /// Default value is specified by regex.
884    ///
885    /// Setting this flag will override the same flag within a `%grmtools` section.
886    pub fn ignore_whitespace(mut self, flag: bool) -> Self {
887        let key = "regex.ignore_whitespace".to_string();
888        self.header.insert(
889            key,
890            HeaderValue(
891                Location::Other("CTLexerBuilder".to_string()),
892                Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
893            ),
894        );
895        self
896    }
897
898    /// Sets the `regex::RegexBuilder` option of the same name.
899    /// Default value is specified by regex.
900    ///
901    /// Setting this flag will override the same flag within a `%grmtools` section.
902    pub fn unicode(mut self, flag: bool) -> Self {
903        let key = "regex.unicode".to_string();
904        self.header.insert(
905            key,
906            HeaderValue(
907                Location::Other("CTLexerBuilder".to_string()),
908                Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
909            ),
910        );
911        self
912    }
913
914    /// Sets the `regex::RegexBuilder` option of the same name.
915    /// Default value is specified by regex.
916    ///
917    /// Setting this flag will override the same flag within a `%grmtools` section.
918    pub fn case_insensitive(mut self, flag: bool) -> Self {
919        let key = "regex.case_insensitive".to_string();
920        self.header.insert(
921            key,
922            HeaderValue(
923                Location::Other("CTLexerBuilder".to_string()),
924                Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
925            ),
926        );
927        self
928    }
929
930    /// Sets the `regex::RegexBuilder` option of the same name.
931    /// Default value is specified by regex.
932    ///
933    /// Setting this flag will override the same flag within a `%grmtools` section.
934    pub fn size_limit(mut self, sz: usize) -> Self {
935        let key = "regex.size_limit".to_string();
936        self.header.insert(
937            key,
938            HeaderValue(
939                Location::Other("CTLexerBuilder".to_string()),
940                Value::Num(sz as u64, Location::Other("CTLexerBuilder".to_string())),
941            ),
942        );
943        self
944    }
945
946    /// Sets the `regex::RegexBuilder` option of the same name.
947    /// Default value is specified by regex.
948    ///
949    /// Setting this flag will override the same flag within a `%grmtools` section.
950    pub fn dfa_size_limit(mut self, sz: usize) -> Self {
951        let key = "regex.dfa_size_limit".to_string();
952        self.header.insert(
953            key,
954            HeaderValue(
955                Location::Other("CTLexerBuilder".to_string()),
956                Value::Num(sz as u64, Location::Other("CTLexerBuilder".to_string())),
957            ),
958        );
959        self
960    }
961
962    /// Sets the `regex::RegexBuilder` option of the same name.
963    /// Default value is specified by regex.
964    ///
965    /// Setting this flag will override the same flag within a `%grmtools` section.
966    pub fn nest_limit(mut self, lim: u32) -> Self {
967        let key = "regex.nest_limit".to_string();
968        self.header.insert(
969            key,
970            HeaderValue(
971                Location::Other("CTLexerBuilder".to_string()),
972                Value::Num(lim as u64, Location::Other("CTLexerBuilder".to_string())),
973            ),
974        );
975        self
976    }
977
978    #[cfg(test)]
979    pub fn inspect_lexerkind(
980        mut self,
981        cb: Box<dyn Fn(&LexerKind) -> Result<(), Box<dyn Error>>>,
982    ) -> Self {
983        self.inspect_lexerkind_cb = Some(cb);
984        self
985    }
986}
987
988/// An interface to the result of [CTLexerBuilder::build()].
989pub struct CTLexer {
990    missing_from_lexer: Option<HashSet<String>>,
991    missing_from_parser: Option<HashSet<(String, Span)>>,
992}
993
994impl CTLexer {
995    fn missing_from_lexer(&self) -> Option<&HashSet<String>> {
996        self.missing_from_lexer.as_ref()
997    }
998
999    fn missing_from_parser(&self) -> Option<&HashSet<(String, Span)>> {
1000        self.missing_from_parser.as_ref()
1001    }
1002}
1003
1004/// Exports all token IDs used by a parser as a separate Rust module.
1005///
1006/// This builder will create a Rust module named `mod_name`
1007/// that can be imported with [`lrlex_mod!(mod_name)`](crate::lrlex_mod).
1008/// The module will contain one `const` `StorageT` per token in `token_map`,
1009/// with the token prefixed by `T_`. In addition, it will contain
1010/// an array of all token IDs `TOK_IDS`.
1011///
1012/// For example, if `StorageT` is `u8`, `mod_name` is `x`, and `token_map` is
1013/// `HashMap{"ID": 0, "INT": 1}` the generated module will look roughly as follows:
1014///
1015/// ```rust,ignore
1016/// mod x {
1017///   pub const T_ID: u8 = 0;
1018///   pub const T_INT: u8 = 1;
1019///   pub const TOK_IDS: &[u8] = &[T_ID, T_INT];
1020/// }
1021/// ```
1022///
1023/// See the [custom lexer example] for more usage details.
1024///
1025/// [custom lexer example]: https://github.com/softdevteam/grmtools/tree/master/lrlex/examples/calc_manual_lex
1026#[derive(Debug, Clone)]
1027pub struct CTTokenMapBuilder<StorageT: Display + ToTokens> {
1028    mod_name: String,
1029    token_map: Vec<(String, TokenStream)>,
1030    rename_map: Option<HashMap<String, String>>,
1031    allow_dead_code: bool,
1032    _marker: PhantomData<StorageT>,
1033}
1034
1035impl<StorageT: Display + ToTokens> CTTokenMapBuilder<StorageT> {
1036    /// Create a new token map builder.
1037    ///
1038    /// See the [builder documentation] for more info.
1039    ///
1040    /// [builder documentation]: CTTokenMapBuilder
1041    pub fn new(
1042        mod_name: impl Into<String>,
1043        token_map: impl Borrow<HashMap<String, StorageT>>,
1044    ) -> Self {
1045        Self {
1046            mod_name: mod_name.into(),
1047            token_map: token_map
1048                .borrow()
1049                .iter()
1050                .map(|(tok_name, tok_value)| (tok_name.clone(), tok_value.to_token_stream()))
1051                .collect(),
1052            rename_map: None,
1053            allow_dead_code: false,
1054            _marker: PhantomData,
1055        }
1056    }
1057
1058    /// Set a token rename map.
1059    ///
1060    /// Rename map is used to specify identifier names for tokens whose names
1061    /// are not valid Rust identifiers. For example, if `token_map`
1062    /// is `HashMap{"+": 0, "ID": 1}` and `rename_map` is `HashMap{"+": "PLUS"}`
1063    /// then the generated module will look roughly as follows:
1064    ///
1065    /// ```rust,ignore
1066    /// mod x {
1067    ///   pub const T_PLUS: u8 = 0;
1068    ///   pub const T_ID: u8 = 1;
1069    /// }
1070    /// ```
1071    pub fn rename_map<M, I, K, V>(mut self, rename_map: Option<M>) -> Self
1072    where
1073        M: IntoIterator<Item = I>,
1074        I: Borrow<(K, V)>,
1075        K: AsRef<str>,
1076        V: AsRef<str>,
1077    {
1078        self.rename_map = rename_map.map(|rename_map| {
1079            rename_map
1080                .into_iter()
1081                .map(|it| {
1082                    let (k, v) = it.borrow();
1083                    let k = k.as_ref().into();
1084                    let v = v.as_ref().into();
1085                    (k, v)
1086                })
1087                .collect()
1088        });
1089        self
1090    }
1091
1092    /// Control whether the builder will add `#[allow(dead_code)]`
1093    /// to the generated module.
1094    ///
1095    /// By default, all tokens are `#[deny(dead_code)]`, meaning that you'll
1096    /// get a warning if your custom lexer doesn't use any of them.
1097    /// This function can be used to disable this behavior.
1098    pub fn allow_dead_code(mut self, allow_dead_code: bool) -> Self {
1099        self.allow_dead_code = allow_dead_code;
1100        self
1101    }
1102
1103    /// Build the token map module.
1104    pub fn build(&self) -> Result<(), Box<dyn Error>> {
1105        // Record the time that this version of lrlex was built. If the source code changes and rustc
1106        // forces a recompile, this will change this value, causing anything which depends on this
1107        // build of lrlex to be recompiled too.
1108        let mut outs = String::new();
1109        let timestamp = env!("VERGEN_BUILD_TIMESTAMP");
1110        let mod_ident = format_ident!("{}", self.mod_name);
1111        write!(outs, "// lrlex build time: {}\n\n", quote!(#timestamp),).ok();
1112        let storaget = str::parse::<TokenStream>(type_name::<StorageT>()).unwrap();
1113        // Sort the tokens so that they're always in the same order.
1114        // This will prevent unneeded rebuilds.
1115        let mut token_map_sorted = self.token_map.clone();
1116        token_map_sorted.sort_by(|(l, _), (r, _)| l.cmp(r));
1117        let (token_array, tokens) = token_map_sorted
1118            .iter()
1119            .map(|(k, id)| {
1120                let name = match &self.rename_map {
1121                    Some(rmap) => rmap.get(k).unwrap_or(k),
1122                    _ => k,
1123                };
1124                let tok_ident: Ident = syn::parse_str(&format!("T_{}", name.to_ascii_uppercase()))
1125                    .map_err(|e| {
1126                        format!(
1127                            "token name {:?} is not a valid Rust identifier: {}; \
1128                            consider renaming it via `CTTokenMapBuilder::rename_map`.",
1129                            name, e
1130                        )
1131                    })?;
1132                Ok((
1133                    // Note: the array of all tokens can't use `tok_ident` because
1134                    // it will confuse the dead code checker. For this reason,
1135                    // we use `id` here.
1136                    quote! {
1137                        #id,
1138                    },
1139                    quote! {
1140                        pub const #tok_ident: #storaget = #id;
1141                    },
1142                ))
1143            })
1144            .collect::<Result<(TokenStream, TokenStream), Box<dyn Error>>>()?;
1145        let unused_annotation = if self.allow_dead_code {
1146            quote! {#[allow(dead_code)]}
1147        } else {
1148            quote! {}
1149        };
1150        // Since the formatter doesn't preserve comments and we don't want to lose build time,
1151        // just format the module contents.
1152        let unformatted = quote! {
1153            #unused_annotation
1154            mod #mod_ident {
1155                #tokens
1156                #[allow(dead_code)]
1157                pub const TOK_IDS: &[#storaget] = &[#token_array];
1158            }
1159        }
1160        .to_string();
1161        let out_mod = syn::parse_str(&unformatted)
1162            .map(|syntax_tree| prettyplease::unparse(&syntax_tree))
1163            .unwrap_or(unformatted);
1164        outs.push_str(&out_mod);
1165        let mut outp = PathBuf::from(var("OUT_DIR")?);
1166        outp.push(&self.mod_name);
1167        outp.set_extension("rs");
1168
1169        // If the file we're about to write out already exists with the same contents, then we
1170        // don't overwrite it (since that will force a recompile of the file, and relinking of the
1171        // binary etc).
1172        if let Ok(curs) = read_to_string(&outp)
1173            && curs == outs
1174        {
1175            return Ok(());
1176        }
1177
1178        let mut f = File::create(outp)?;
1179        f.write_all(outs.as_bytes())?;
1180        Ok(())
1181    }
1182}
1183
1184/// Create a Rust module named `mod_name` that can be imported with
1185/// [`lrlex_mod!(mod_name)`](crate::lrlex_mod).
1186///
1187/// This function is deprecated in favour of [`CTTokenMapBuilder`].
1188#[deprecated(since = "0.14.0", note = "use `lrlex::CTTokenMapBuilder` instead")]
1189pub fn ct_token_map<StorageT: Display + ToTokens>(
1190    mod_name: &str,
1191    token_map: impl Borrow<HashMap<String, StorageT>>,
1192    rename_map: Option<&HashMap<&str, &str>>,
1193) -> Result<(), Box<dyn Error>> {
1194    CTTokenMapBuilder::new(mod_name, token_map)
1195        .rename_map(rename_map)
1196        .allow_dead_code(true)
1197        .build()
1198}
1199
1200/// Indents a multi-line string and trims any trailing newline.
1201/// This currently assumes that indentation on blank lines does not matter.
1202///
1203/// The algorithm used by this function is:
1204/// 1. Prefix `s` with the indentation, indenting the first line.
1205/// 2. Trim any trailing newlines.
1206/// 3. Replace all newlines with `\n{indent}`` to indent all lines after the first.
1207///
1208/// It is plausible that we should a step 4, but currently do not:
1209/// 4. Replace all `\n{indent}\n` with `\n\n`
1210fn indent(indent: &str, s: &str) -> String {
1211    format!("{indent}{}\n", s.trim_end_matches('\n')).replace('\n', &format!("\n{}", indent))
1212}
1213
1214// It isn't clear to me why this test isn't working on wasm32,
1215// as the `workspace_runner` should allow access to `OUT_DIR`
1216// perhaps it is related to absolute paths
1217#[cfg(all(not(target_arch = "wasm32"), test))]
1218mod test {
1219    use std::fs::File;
1220    use std::io::Write;
1221
1222    use super::{CTLexerBuilder, LexerKind};
1223    #[test]
1224    fn test_grmtools_section_lexerkind() {
1225        let lexerkinds = ["LRNonStreamingLexer", "LexerKind::LRNonStreamingLexer"];
1226        for (i, kind) in lexerkinds.iter().enumerate() {
1227            let lex_src = format!(
1228                "
1229%grmtools{{lexerkind: {}}}
1230%%
1231. ;
1232",
1233                kind
1234            );
1235            let lex_path = format!(
1236                "{}/test_grmtools_section_lexerkind_{}.l",
1237                env!("OUT_DIR"),
1238                i
1239            );
1240            let mut l_file = File::create(lex_path.clone()).unwrap();
1241            l_file.write_all(lex_src.as_bytes()).unwrap();
1242            CTLexerBuilder::new()
1243                .output_path(format!("{}.rs", lex_path.clone()))
1244                .lexer_path(lex_path.clone())
1245                .inspect_lexerkind(Box::new(move |lexerkind| {
1246                    assert!(matches!(lexerkind, &LexerKind::LRNonStreamingLexer));
1247                    Ok(())
1248                }))
1249                .build()
1250                .unwrap();
1251        }
1252    }
1253
1254    #[test]
1255    /// Tests a yacc .y filename containing a dash character leading to an invalid rust identifier
1256    /// when that dash is subsequently used as the default `CTParserBuilder::mod_name`.
1257    fn test_invalid_identifier_in_derived_mod_name() {
1258        let mut lex_path = std::path::PathBuf::from(env!("OUT_DIR"));
1259        lex_path.push("contains-a-dash.l");
1260        let mut f = File::create(&lex_path).unwrap();
1261        let _ = f.write_all(
1262            r#"
1263%%
1264A  "A"
1265"#
1266            .as_bytes(),
1267        );
1268        match CTLexerBuilder::new()
1269            .output_path(format!("{}.rs", lex_path.display()))
1270            .lexer_path(lex_path.clone())
1271            .build()
1272        {
1273            Ok(_) => panic!("Expected error"),
1274            Err(e) => {
1275                let err_string = e.to_string();
1276                assert_eq!(
1277                    err_string,
1278                    "mod_name 'contains-a-dash_l' is not a valid rust identifier due to 'unexpected token'"
1279                );
1280            }
1281        }
1282    }
1283}