Skip to main content

lrlex/
ctbuilder.rs

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