lrlex/
ctbuilder.rs

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