1use 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#[derive(Clone, PartialEq, Eq, Debug)]
78#[non_exhaustive]
79pub enum Visibility {
80 Private,
82 Public,
84 PublicSuper,
86 PublicSelf,
88 PublicCrate,
90 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#[derive(Clone, Copy, PartialEq, Eq, Debug)]
114#[non_exhaustive]
115pub enum RustEdition {
116 Rust2015,
117 Rust2018,
118 Rust2021,
119}
120
121struct 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
137pub 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 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 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 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 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 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 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 pub fn lexerkind(mut self, lexerkind: LexerKind) -> Self {
329 self.lexerkind = Some(lexerkind);
330 self
331 }
332
333 pub fn mod_name(mut self, mod_name: &'a str) -> Self {
337 self.mod_name = Some(mod_name);
338 self
339 }
340
341 pub fn visibility(mut self, vis: Visibility) -> Self {
343 self.visibility = vis;
344 self
345 }
346
347 pub fn rust_edition(mut self, edition: RustEdition) -> Self {
350 self.rust_edition = edition;
351 self
352 }
353
354 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 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 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 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 #[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 #[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 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 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 pub fn warnings_are_errors(mut self, flag: bool) -> Self {
764 self.warnings_are_errors = flag;
765 self
766 }
767
768 pub fn show_warnings(mut self, flag: bool) -> Self {
771 self.show_warnings = flag;
772 self
773 }
774
775 pub fn allow_wholeline_comments(mut self, flag: bool) -> Self {
783 self.lex_flags.allow_wholeline_comments = Some(flag);
784 self
785 }
786
787 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 pub fn multi_line(mut self, flag: bool) -> Self {
801 self.lex_flags.multi_line = Some(flag);
802 self
803 }
804
805 pub fn posix_escapes(mut self, flag: bool) -> Self {
810 self.lex_flags.posix_escapes = Some(flag);
811 self
812 }
813
814 pub fn octal(mut self, flag: bool) -> Self {
819 self.lex_flags.octal = Some(flag);
820 self
821 }
822
823 pub fn swap_greed(mut self, flag: bool) -> Self {
828 self.lex_flags.swap_greed = Some(flag);
829 self
830 }
831
832 pub fn ignore_whitespace(mut self, flag: bool) -> Self {
837 self.lex_flags.ignore_whitespace = Some(flag);
838 self
839 }
840
841 pub fn unicode(mut self, flag: bool) -> Self {
846 self.lex_flags.unicode = Some(flag);
847 self
848 }
849
850 pub fn case_insensitive(mut self, flag: bool) -> Self {
855 self.lex_flags.case_insensitive = Some(flag);
856 self
857 }
858
859 pub fn size_limit(mut self, sz: usize) -> Self {
864 self.lex_flags.size_limit = Some(sz);
865 self
866 }
867
868 pub fn dfa_size_limit(mut self, sz: usize) -> Self {
873 self.lex_flags.dfa_size_limit = Some(sz);
874 self
875 }
876
877 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
896pub 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#[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 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 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 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 pub fn build(&self) -> Result<(), Box<dyn Error>> {
1013 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 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 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 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 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#[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
1108fn indent(indent: &str, s: &str) -> String {
1119 format!("{indent}{}\n", s.trim_end_matches('\n')).replace('\n', &format!("\n{}", indent))
1120}
1121
1122#[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 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}