1use cfgrammar::{
4 header::{Header, HeaderError, HeaderErrorKind, HeaderValue, Value},
5 markmap::MergeBehavior,
6 span::{Location, Span},
7};
8use glob::glob;
9use lrpar::{
10 CTParserBuilder, LexerTypes,
11 diagnostics::{DiagnosticFormatter, SpannedDiagnosticFormatter},
12};
13use num_traits::{AsPrimitive, PrimInt, Unsigned};
14use proc_macro2::{Ident, TokenStream};
15use quote::{ToTokens, format_ident, quote};
16use std::{
17 any::type_name,
18 borrow::Borrow,
19 collections::{HashMap, HashSet},
20 env::{current_dir, var},
21 error::Error,
22 fmt::{self, Debug, Display, Write as _},
23 fs::{self, File, create_dir_all, read_to_string},
24 hash::Hash,
25 io::Write,
26 marker::PhantomData,
27 path::{Path, PathBuf},
28 sync::{LazyLock, Mutex},
29};
30use wincode::SchemaWrite;
31
32use crate::{
33 DefaultLexerTypes, LRNonStreamingLexer, LexerDef,
34 codegen::{LexerBuildEnvArgs, LexerSrcEnv, LexerSrcEnvError},
35};
36
37const RUST_FILE_EXT: &str = "rs";
38
39const ERROR: &str = "[Error]";
40const WARNING: &str = "[Warning]";
41
42static GENERATED_PATHS: LazyLock<Mutex<HashSet<PathBuf>>> =
43 LazyLock::new(|| Mutex::new(HashSet::new()));
44
45#[non_exhaustive]
46pub enum LexerKind {
47 LRNonStreamingLexer,
48}
49
50impl<T: Clone> TryFrom<&Value<T>> for LexerKind {
51 type Error = cfgrammar::header::HeaderError<T>;
52 fn try_from(it: &Value<T>) -> Result<LexerKind, Self::Error> {
53 match it {
54 Value::Namespaced(rs, loc) => match rs.as_str() {
55 "LexerKind::LRNonStreamingLexer" | "LRNonStreamingLexer" => {
56 Ok(LexerKind::LRNonStreamingLexer)
57 }
58 _ => Err(HeaderError {
59 kind: HeaderErrorKind::ConversionError("LexerKind", "Expected `LexerKind`"),
60 locations: vec![loc.clone()],
61 }),
62 },
63 val => Err(HeaderError {
64 kind: HeaderErrorKind::ConversionError("LexerKind", "Expected `LexerKind`"),
65 locations: vec![val.primary_location().clone()],
66 }),
67 }
68 }
69}
70
71#[derive(Clone, PartialEq, Eq, Debug)]
73#[non_exhaustive]
74pub enum Visibility {
75 Private,
77 Public,
79 PublicSuper,
81 PublicSelf,
83 PublicCrate,
85 PublicIn(String),
87}
88
89impl ToTokens for Visibility {
90 fn to_tokens(&self, tokens: &mut TokenStream) {
91 tokens.extend(match self {
92 Visibility::Private => quote!(),
93 Visibility::Public => quote! {pub},
94 Visibility::PublicSuper => quote! {pub(super)},
95 Visibility::PublicSelf => quote! {pub(self)},
96 Visibility::PublicCrate => quote! {pub(crate)},
97 Visibility::PublicIn(data) => {
98 let other = str::parse::<TokenStream>(data).unwrap();
99 quote! {pub(in #other)}
100 }
101 })
102 }
103}
104
105#[derive(Clone, Copy, PartialEq, Eq, Debug)]
109#[non_exhaustive]
110pub enum RustEdition {
111 Rust2015,
112 Rust2018,
113 Rust2021,
114}
115
116struct ErrorString(String);
118impl fmt::Display for ErrorString {
119 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
120 let ErrorString(s) = self;
121 write!(f, "{}", s)
122 }
123}
124impl fmt::Debug for ErrorString {
125 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
126 let ErrorString(s) = self;
127 write!(f, "{}", s)
128 }
129}
130impl Error for ErrorString {}
131
132pub struct CTLexerBuilder<'a, LexerTypesT: LexerTypes = DefaultLexerTypes<u32>>
135where
136 LexerTypesT::StorageT: Debug + Eq + Hash + ToTokens,
137 usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
138{
139 lrpar_config:
140 Option<Box<dyn Fn(CTParserBuilder<LexerTypesT>) -> CTParserBuilder<LexerTypesT> + 'a>>,
141 lexer_path: Option<PathBuf>,
142 output_path: Option<PathBuf>,
143 lexerkind: Option<LexerKind>,
144 mod_name: Option<&'a str>,
145 visibility: Visibility,
146 rust_edition: RustEdition,
147 rule_ids_map: Option<HashMap<String, LexerTypesT::StorageT>>,
148 allow_missing_terms_in_lexer: bool,
149 allow_missing_tokens_in_parser: bool,
150 warnings_are_errors: bool,
151 show_warnings: bool,
152 header: Header<Location>,
153 #[cfg(test)]
154 inspect_lexerkind_cb: Option<Box<dyn Fn(&LexerKind) -> Result<(), Box<dyn Error>>>>,
155}
156
157impl CTLexerBuilder<'_, DefaultLexerTypes<u32>> {
158 pub fn new() -> Self {
160 CTLexerBuilder::<DefaultLexerTypes<u32>>::new_with_lexemet()
161 }
162}
163type FixIntConfig = wincode::config::Configuration;
164
165type VarIntConfig = wincode::config::Configuration<
166 true,
167 4194304,
168 wincode::len::BincodeLen,
169 wincode::int_encoding::LittleEndian,
170 wincode::int_encoding::VarInt,
171>;
172impl<'a, LexerTypesT: LexerTypes<LexErrorT = crate::LRLexError> + 'static>
173 CTLexerBuilder<'a, LexerTypesT>
174where
175 LexerTypesT::StorageT: 'static
176 + Debug
177 + Eq
178 + Hash
179 + PrimInt
180 + SchemaWrite<FixIntConfig, Src = LexerTypesT::StorageT>
181 + SchemaWrite<VarIntConfig, Src = LexerTypesT::StorageT>
182 + TryFrom<usize>
183 + Unsigned
184 + ToTokens,
185 usize: AsPrimitive<LexerTypesT::StorageT>,
186{
187 pub fn new_with_lexemet() -> Self {
204 let mut header = Header::new();
205 header.set_default_merge_behavior(MergeBehavior::Ours);
206 CTLexerBuilder {
207 lrpar_config: None,
208 lexer_path: None,
209 output_path: None,
210 lexerkind: None,
211 mod_name: None,
212 visibility: Visibility::Private,
213 rust_edition: RustEdition::Rust2021,
214 rule_ids_map: None,
215 allow_missing_terms_in_lexer: false,
216 allow_missing_tokens_in_parser: false,
217 warnings_are_errors: false,
218 show_warnings: true,
219 header,
220 #[cfg(test)]
221 inspect_lexerkind_cb: None,
222 }
223 }
224
225 pub fn lrpar_config<F>(mut self, config_func: F) -> Self
244 where
245 F: Fn(CTParserBuilder<LexerTypesT>) -> CTParserBuilder<LexerTypesT> + 'a,
246 {
247 self.lrpar_config = Some(Box::new(config_func));
248 self
249 }
250
251 pub fn lexer_in_src_dir<P>(mut self, srcp: P) -> Result<Self, Box<dyn Error>>
269 where
270 P: AsRef<Path>,
271 {
272 if !srcp.as_ref().is_relative() {
273 return Err(format!(
274 "Lexer path '{}' must be a relative path.",
275 srcp.as_ref().to_str().unwrap_or("<invalid UTF-8>")
276 )
277 .into());
278 }
279
280 let mut lexp = current_dir()?;
281 lexp.push("src");
282 lexp.push(srcp.as_ref());
283 self.lexer_path = Some(lexp);
284
285 let mut outp = PathBuf::new();
286 outp.push(var("OUT_DIR").unwrap());
287 outp.push(srcp.as_ref().parent().unwrap().to_str().unwrap());
288 create_dir_all(&outp)?;
289 let mut leaf = srcp
290 .as_ref()
291 .file_name()
292 .unwrap()
293 .to_str()
294 .unwrap()
295 .to_owned();
296 write!(leaf, ".{}", RUST_FILE_EXT).ok();
297 outp.push(leaf);
298 Ok(self.output_path(outp))
299 }
300
301 pub fn lexer_path<P>(mut self, inp: P) -> Self
305 where
306 P: AsRef<Path>,
307 {
308 self.lexer_path = Some(inp.as_ref().to_owned());
309 self
310 }
311
312 pub fn output_path<P>(mut self, outp: P) -> Self
317 where
318 P: AsRef<Path>,
319 {
320 self.output_path = Some(outp.as_ref().to_owned());
321 self
322 }
323
324 pub fn lexerkind(mut self, lexerkind: LexerKind) -> Self {
326 self.lexerkind = Some(lexerkind);
327 self
328 }
329
330 pub fn mod_name(mut self, mod_name: &'a str) -> Self {
334 self.mod_name = Some(mod_name);
335 self
336 }
337
338 pub fn visibility(mut self, vis: Visibility) -> Self {
340 self.visibility = vis;
341 self
342 }
343
344 pub fn rust_edition(mut self, edition: RustEdition) -> Self {
347 self.rust_edition = edition;
348 self
349 }
350
351 pub fn rule_ids_map<T: std::borrow::Borrow<HashMap<String, LexerTypesT::StorageT>> + Clone>(
356 mut self,
357 rule_ids_map: T,
358 ) -> Self {
359 self.rule_ids_map = Some(rule_ids_map.borrow().to_owned());
360 self
361 }
362
363 pub fn build(mut self) -> Result<CTLexer, Box<dyn Error>> {
383 let lexerp = self
384 .lexer_path
385 .as_ref()
386 .expect("lexer_path must be specified before processing.");
387 let outp = self
388 .output_path
389 .as_ref()
390 .expect("output_path must be specified before processing.");
391
392 {
393 let mut lk = GENERATED_PATHS.lock().unwrap();
394 if lk.contains(outp.as_path()) {
395 return Err(format!("Generating two lexers to the same path ('{}') is not allowed: use CTLexerBuilder::output_path (and, optionally, CTLexerBuilder::mod_name) to differentiate them.", outp.to_str().unwrap()).into());
396 }
397 lk.insert(outp.clone());
398 }
399 let lex_src = read_to_string(lexerp)
400 .map_err(|e| format!("When reading '{}': {e}", lexerp.display()))?;
401 let lex_diag = SpannedDiagnosticFormatter::new(&lex_src, lexerp);
402 let args = LexerBuildEnvArgs::new()
403 .mod_name(self.mod_name.map(|s| s.to_string()))
404 .lexerkind(self.lexerkind)
405 .visibility(self.visibility);
406 let mut build_env =
407 LexerSrcEnv::<LexerTypesT>::new_with_header(&lex_src, Some(lexerp), self.header)
408 .build_env(args)
409 .map_err(|e| match e {
410 LexerSrcEnvError::GrmtoolsSectionParseError(es) => {
411 let mut out = String::new();
412 out.push_str(&format!(
413 "\n{ERROR}{}\n",
414 lex_diag.file_location_msg(" parsing the `%grmtools` section", None)
415 ));
416 for e in es {
417 out.push_str(&indent(" ", &lex_diag.format_error(e).to_string()));
418 out.push('\n');
419 }
420 ErrorString(out)
421 }
422 LexerSrcEnvError::LexBuildErrors(errs) => {
423 let mut out = String::new();
424 out.push_str(&format!(
425 "\n{ERROR}{}\n",
426 lex_diag.file_location_msg(" building the lexer", None)
427 ));
428 for e in errs {
429 out.push_str(&indent(" ", &lex_diag.format_error(e).to_string()));
430 out.push('\n');
431 }
432 ErrorString(out)
433 }
434 e => ErrorString(e.to_string()),
435 })?;
436
437 #[cfg(test)]
438 if let Some(inspect_lexerkind_cb) = self.inspect_lexerkind_cb {
439 inspect_lexerkind_cb(build_env.lexerkind())?
440 }
441
442 let ct_parser = if let Some(ref lrcfg) = self.lrpar_config {
443 let mut closure_lexerdef = build_env.lexerdef().clone();
444 let mut ctp = CTParserBuilder::<LexerTypesT>::new().inspect_rt(Box::new(
445 move |yacc_header, rtpb, rule_ids_map, grm_path| {
446 let owned_map = rule_ids_map
447 .iter()
448 .map(|(x, y)| (&**x, *y))
449 .collect::<HashMap<_, _>>();
450 closure_lexerdef.set_rule_ids(&owned_map);
451 let grammar = rtpb.grammar();
452 let test_glob = yacc_header.get("lrpar.test_files");
453 let mut err_str = None;
454 let add_error_line = |err_str: &mut Option<String>, line| {
455 if let Some(err_str) = err_str {
456 err_str.push_str(&format!("{}\n", line));
457 } else {
458 let _ = err_str.insert(format!("{}\n", line));
459 }
460 };
461 match test_glob {
462 Some(HeaderValue(_, Value::Array(test_globs, _))) => {
463 for setting in test_globs {
464 match setting {
465 Value::String(test_files, _) => {
466 let path_joined = grm_path.parent().unwrap().join(test_files);
467 let path_str = &path_joined.to_string_lossy();
468 let mut glob_paths = glob(path_str).map_err(|e| e.to_string())?.peekable();
469 if glob_paths.peek().is_none() {
470 return Err(format!("'test_files' glob '{}' matched no paths", path_str)
471 .to_string()
472 .into(),
473 );
474 }
475
476 for path in glob_paths {
477 let path = path?;
478 if let Some(ext) = path.extension()
479 && let Some(ext) = ext.to_str()
480 && ext.starts_with("grm") {
481 add_error_line(&mut err_str, "test_files extensions beginning with `grm` are reserved.".into());
482 }
483 let input = fs::read_to_string(&path)?;
484 let l: LRNonStreamingLexer<LexerTypesT> =
485 closure_lexerdef.lexer(&input);
486 let errs = rtpb.parse_map(&l, &|_| (), &|_, _| ()).1;
487 if !errs.is_empty() {
488 add_error_line(&mut err_str, format!("While parsing {}:", path.display()));
489 for e in errs {
490 let e_pp = e.pp(&l, &|t| grammar.token_epp(t));
491 let e_lines = e_pp.split("\n");
492 for e in e_lines {
493 add_error_line(&mut err_str, format!("\t{}", e));
494 }
495 }
496 }
497 }
498 }
499 _ => return Err("Invalid value for setting 'test_files'".into()),
500 }
501 }
502 if let Some(err_str) = err_str {
503 Err(ErrorString(err_str))?
504 } else {
505 Ok(())
506 }
507
508 }
509 Some(_) => Err("Invalid value for setting 'test_files'".into()),
510 None => Ok(()),
511 }
512 },
513 ));
514 ctp = lrcfg(ctp);
515 let ct_parser = ctp.build()?;
516 self.rule_ids_map = Some(ct_parser.token_map().to_owned());
517 Some(ct_parser)
518 } else {
519 None
520 };
521
522 let unused_header_values = build_env
523 .header()
524 .unused()
525 .map(|(s, _)| s.to_string())
526 .collect::<Vec<String>>();
527 if !unused_header_values.is_empty() {
528 return Err(
529 format!("Unused header values: {}", unused_header_values.join(", ")).into(),
530 );
531 }
532
533 let code_gen = build_env
534 .code_generator(self.rule_ids_map, env!("VERGEN_BUILD_TIMESTAMP"))
535 .map_err(|e| match e {})?;
536 let (mut missing_from_lexer, missing_from_parser) = {
537 let lexerdef = Box::new(build_env.lexerdef_mut());
538 match code_gen.rule_ids_map() {
539 Some(rim) => {
540 let owned_map = rim
542 .iter()
543 .map(|(x, y)| (&**x, *y))
544 .collect::<HashMap<_, _>>();
545 let (x, y) = lexerdef.set_rule_ids_spanned(&owned_map);
546 (
547 x.map(|a| a.iter().map(|&b| b.to_string()).collect::<HashSet<_>>()),
548 y.map(|a| {
549 a.iter()
550 .map(|(b, span)| (b.to_string(), *span))
551 .collect::<HashSet<_>>()
552 }),
553 )
554 }
555 None => (None, None),
556 }
557 };
558 let lexerdef = build_env.lexerdef();
559 if let Some(mut mfl) = missing_from_lexer.take() {
560 for tok in &lexerdef.expected_missing_tokens {
561 mfl.remove(tok.as_str());
562 }
563 if mfl.is_empty() {
564 missing_from_lexer = None;
565 } else {
566 missing_from_lexer = Some(mfl);
567 }
568 }
569
570 let mut has_unallowed_missing = false;
571 let err_indent = " ".repeat(ERROR.len());
572 if !self.allow_missing_terms_in_lexer
573 && let Some(ref mfl) = missing_from_lexer
574 {
575 if let Some(ct_parser) = &ct_parser {
576 let grm = ct_parser.yacc_grammar();
577 let token_spans = mfl
578 .iter()
579 .map(|name| {
580 ct_parser
581 .yacc_grammar()
582 .token_span(*grm.tokens_map().get(name.as_str()).unwrap())
583 .expect("Given token should have a span")
584 })
585 .collect::<Vec<_>>();
586
587 let yacc_diag = SpannedDiagnosticFormatter::new(
588 ct_parser.grammar_src(),
589 ct_parser.grammar_path(),
590 );
591
592 eprintln!(
593 "{ERROR} these tokens are not referenced in the lexer but defined as follows"
594 );
595 eprintln!(
596 "{err_indent} {}",
597 yacc_diag.file_location_msg("in the grammar", None)
598 );
599 for span in token_spans {
600 eprintln!(
601 "{}",
602 yacc_diag.underline_span_with_text(
603 span,
604 "Missing from lexer".to_string(),
605 '^'
606 )
607 );
608 }
609 eprintln!();
610 } else {
611 eprintln!(
612 "{ERROR} the following tokens are used in the grammar but are not defined in the lexer:"
613 );
614 for n in mfl {
615 eprintln!(" {}", n);
616 }
617 }
618 has_unallowed_missing = true;
619 }
620 if !self.allow_missing_tokens_in_parser
621 && self.show_warnings
622 && let Some(ref mfp) = missing_from_parser
623 {
624 let error_prefix = if self.warnings_are_errors {
625 ERROR
626 } else {
627 WARNING
628 };
629 let err_indent = " ".repeat(error_prefix.len());
630 let mut outs = Vec::new();
631 outs.push(format!("{error_prefix} these tokens are not referenced in the grammar but defined as follows"));
632 outs.push(format!(
633 "{err_indent} {}",
634 lex_diag.file_location_msg("in the lexer", None)
635 ));
636 for (_, span) in mfp {
637 let error_contents = lex_diag.underline_span_with_text(
638 *span,
639 "Missing from parser".to_string(),
640 '^',
641 );
642 outs.extend(error_contents.lines().map(|s| s.to_string()));
643 }
644
645 for s in outs {
646 if !self.warnings_are_errors && std::env::var("OUT_DIR").is_ok() {
647 println!("cargo:warning={}", s)
648 } else {
649 eprintln!("{}", s);
650 }
651 }
652
653 has_unallowed_missing |= self.warnings_are_errors;
654 }
655 if has_unallowed_missing {
656 fs::remove_file(outp).ok();
657 panic!();
658 }
659 let outs = code_gen
660 .generate(&build_env)
661 .map_err(|e| ErrorString(e.to_string()))?;
662 if let Ok(curs) = read_to_string(outp)
666 && curs == outs
667 {
668 return Ok(CTLexer {
669 missing_from_lexer,
670 missing_from_parser,
671 });
672 }
673 let mut f = File::create(outp)?;
674 f.write_all(outs.as_bytes())?;
675 Ok(CTLexer {
676 missing_from_lexer,
677 missing_from_parser,
678 })
679 }
680
681 #[deprecated(
688 since = "0.11.0",
689 note = "Please use lexer_in_src_dir() and build() instead"
690 )]
691 #[allow(deprecated)]
692 pub fn process_file_in_src(
693 self,
694 srcp: &str,
695 ) -> Result<(Option<HashSet<String>>, Option<HashSet<String>>), Box<dyn Error>> {
696 let mut inp = current_dir()?;
697 inp.push("src");
698 inp.push(srcp);
699 let mut outp = PathBuf::new();
700 outp.push(var("OUT_DIR").unwrap());
701 outp.push(Path::new(srcp).parent().unwrap().to_str().unwrap());
702 create_dir_all(&outp)?;
703 let mut leaf = Path::new(srcp)
704 .file_name()
705 .unwrap()
706 .to_str()
707 .unwrap()
708 .to_owned();
709 write!(leaf, ".{}", RUST_FILE_EXT).ok();
710 outp.push(leaf);
711 self.process_file(inp, outp)
712 }
713
714 #[deprecated(
732 since = "0.11.0",
733 note = "Please use lexer_in_src_dir() and build() instead"
734 )]
735 pub fn process_file<P, Q>(
736 mut self,
737 inp: P,
738 outp: Q,
739 ) -> Result<(Option<HashSet<String>>, Option<HashSet<String>>), Box<dyn Error>>
740 where
741 P: AsRef<Path>,
742 Q: AsRef<Path>,
743 {
744 self.lexer_path = Some(inp.as_ref().to_owned());
745 self.output_path = Some(outp.as_ref().to_owned());
746 let cl = self.build()?;
747 Ok((
748 cl.missing_from_lexer().map(|x| x.to_owned()),
749 cl.missing_from_parser()
750 .map(|x| x.iter().map(|(n, _)| n.to_owned()).collect::<HashSet<_>>()),
751 ))
752 }
753
754 pub fn allow_missing_terms_in_lexer(mut self, allow: bool) -> Self {
757 self.allow_missing_terms_in_lexer = allow;
758 self
759 }
760
761 pub fn allow_missing_tokens_in_parser(mut self, allow: bool) -> Self {
765 self.allow_missing_tokens_in_parser = allow;
766 self
767 }
768
769 pub fn warnings_are_errors(mut self, flag: bool) -> Self {
772 self.warnings_are_errors = flag;
773 self
774 }
775
776 pub fn show_warnings(mut self, flag: bool) -> Self {
779 self.show_warnings = flag;
780 self
781 }
782
783 pub fn allow_wholeline_comments(mut self, flag: bool) -> Self {
791 let key = "lrlex.allow_wholeline_comments".to_string();
792 self.header.insert(
793 key,
794 HeaderValue(
795 Location::Other("CTLexerBuilder".to_string()),
796 Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
797 ),
798 );
799 self
800 }
801
802 pub fn dot_matches_new_line(mut self, flag: bool) -> Self {
807 let key = "regex.dot_matches_new_line".to_string();
808 self.header.insert(
809 key,
810 HeaderValue(
811 Location::Other("CTLexerBuilder".to_string()),
812 Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
813 ),
814 );
815 self
816 }
817
818 pub fn multi_line(mut self, flag: bool) -> Self {
823 let key = "regex.multi_line".to_string();
824 self.header.insert(
825 key,
826 HeaderValue(
827 Location::Other("CTLexerBuilder".to_string()),
828 Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
829 ),
830 );
831 self
832 }
833
834 pub fn posix_escapes(mut self, flag: bool) -> Self {
839 let key = "lrlex.posix_escapes".to_string();
840 self.header.insert(
841 key,
842 HeaderValue(
843 Location::Other("CTLexerBuilder".to_string()),
844 Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
845 ),
846 );
847 self
848 }
849
850 pub fn octal(mut self, flag: bool) -> Self {
855 let key = "regex.octal".to_string();
856 self.header.insert(
857 key,
858 HeaderValue(
859 Location::Other("CTLexerBuilder".to_string()),
860 Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
861 ),
862 );
863 self
864 }
865
866 pub fn swap_greed(mut self, flag: bool) -> Self {
871 let key = "regex.swap_greed".to_string();
872 self.header.insert(
873 key,
874 HeaderValue(
875 Location::Other("CTLexerBuilder".to_string()),
876 Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
877 ),
878 );
879 self
880 }
881
882 pub fn ignore_whitespace(mut self, flag: bool) -> Self {
887 let key = "regex.ignore_whitespace".to_string();
888 self.header.insert(
889 key,
890 HeaderValue(
891 Location::Other("CTLexerBuilder".to_string()),
892 Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
893 ),
894 );
895 self
896 }
897
898 pub fn unicode(mut self, flag: bool) -> Self {
903 let key = "regex.unicode".to_string();
904 self.header.insert(
905 key,
906 HeaderValue(
907 Location::Other("CTLexerBuilder".to_string()),
908 Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
909 ),
910 );
911 self
912 }
913
914 pub fn case_insensitive(mut self, flag: bool) -> Self {
919 let key = "regex.case_insensitive".to_string();
920 self.header.insert(
921 key,
922 HeaderValue(
923 Location::Other("CTLexerBuilder".to_string()),
924 Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())),
925 ),
926 );
927 self
928 }
929
930 pub fn size_limit(mut self, sz: usize) -> Self {
935 let key = "regex.size_limit".to_string();
936 self.header.insert(
937 key,
938 HeaderValue(
939 Location::Other("CTLexerBuilder".to_string()),
940 Value::Num(sz as u64, Location::Other("CTLexerBuilder".to_string())),
941 ),
942 );
943 self
944 }
945
946 pub fn dfa_size_limit(mut self, sz: usize) -> Self {
951 let key = "regex.dfa_size_limit".to_string();
952 self.header.insert(
953 key,
954 HeaderValue(
955 Location::Other("CTLexerBuilder".to_string()),
956 Value::Num(sz as u64, Location::Other("CTLexerBuilder".to_string())),
957 ),
958 );
959 self
960 }
961
962 pub fn nest_limit(mut self, lim: u32) -> Self {
967 let key = "regex.nest_limit".to_string();
968 self.header.insert(
969 key,
970 HeaderValue(
971 Location::Other("CTLexerBuilder".to_string()),
972 Value::Num(lim as u64, Location::Other("CTLexerBuilder".to_string())),
973 ),
974 );
975 self
976 }
977
978 #[cfg(test)]
979 pub fn inspect_lexerkind(
980 mut self,
981 cb: Box<dyn Fn(&LexerKind) -> Result<(), Box<dyn Error>>>,
982 ) -> Self {
983 self.inspect_lexerkind_cb = Some(cb);
984 self
985 }
986}
987
988pub struct CTLexer {
990 missing_from_lexer: Option<HashSet<String>>,
991 missing_from_parser: Option<HashSet<(String, Span)>>,
992}
993
994impl CTLexer {
995 fn missing_from_lexer(&self) -> Option<&HashSet<String>> {
996 self.missing_from_lexer.as_ref()
997 }
998
999 fn missing_from_parser(&self) -> Option<&HashSet<(String, Span)>> {
1000 self.missing_from_parser.as_ref()
1001 }
1002}
1003
1004#[derive(Debug, Clone)]
1027pub struct CTTokenMapBuilder<StorageT: Display + ToTokens> {
1028 mod_name: String,
1029 token_map: Vec<(String, TokenStream)>,
1030 rename_map: Option<HashMap<String, String>>,
1031 allow_dead_code: bool,
1032 _marker: PhantomData<StorageT>,
1033}
1034
1035impl<StorageT: Display + ToTokens> CTTokenMapBuilder<StorageT> {
1036 pub fn new(
1042 mod_name: impl Into<String>,
1043 token_map: impl Borrow<HashMap<String, StorageT>>,
1044 ) -> Self {
1045 Self {
1046 mod_name: mod_name.into(),
1047 token_map: token_map
1048 .borrow()
1049 .iter()
1050 .map(|(tok_name, tok_value)| (tok_name.clone(), tok_value.to_token_stream()))
1051 .collect(),
1052 rename_map: None,
1053 allow_dead_code: false,
1054 _marker: PhantomData,
1055 }
1056 }
1057
1058 pub fn rename_map<M, I, K, V>(mut self, rename_map: Option<M>) -> Self
1072 where
1073 M: IntoIterator<Item = I>,
1074 I: Borrow<(K, V)>,
1075 K: AsRef<str>,
1076 V: AsRef<str>,
1077 {
1078 self.rename_map = rename_map.map(|rename_map| {
1079 rename_map
1080 .into_iter()
1081 .map(|it| {
1082 let (k, v) = it.borrow();
1083 let k = k.as_ref().into();
1084 let v = v.as_ref().into();
1085 (k, v)
1086 })
1087 .collect()
1088 });
1089 self
1090 }
1091
1092 pub fn allow_dead_code(mut self, allow_dead_code: bool) -> Self {
1099 self.allow_dead_code = allow_dead_code;
1100 self
1101 }
1102
1103 pub fn build(&self) -> Result<(), Box<dyn Error>> {
1105 let mut outs = String::new();
1109 let timestamp = env!("VERGEN_BUILD_TIMESTAMP");
1110 let mod_ident = format_ident!("{}", self.mod_name);
1111 write!(outs, "// lrlex build time: {}\n\n", quote!(#timestamp),).ok();
1112 let storaget = str::parse::<TokenStream>(type_name::<StorageT>()).unwrap();
1113 let mut token_map_sorted = self.token_map.clone();
1116 token_map_sorted.sort_by(|(l, _), (r, _)| l.cmp(r));
1117 let (token_array, tokens) = token_map_sorted
1118 .iter()
1119 .map(|(k, id)| {
1120 let name = match &self.rename_map {
1121 Some(rmap) => rmap.get(k).unwrap_or(k),
1122 _ => k,
1123 };
1124 let tok_ident: Ident = syn::parse_str(&format!("T_{}", name.to_ascii_uppercase()))
1125 .map_err(|e| {
1126 format!(
1127 "token name {:?} is not a valid Rust identifier: {}; \
1128 consider renaming it via `CTTokenMapBuilder::rename_map`.",
1129 name, e
1130 )
1131 })?;
1132 Ok((
1133 quote! {
1137 #id,
1138 },
1139 quote! {
1140 pub const #tok_ident: #storaget = #id;
1141 },
1142 ))
1143 })
1144 .collect::<Result<(TokenStream, TokenStream), Box<dyn Error>>>()?;
1145 let unused_annotation = if self.allow_dead_code {
1146 quote! {#[allow(dead_code)]}
1147 } else {
1148 quote! {}
1149 };
1150 let unformatted = quote! {
1153 #unused_annotation
1154 mod #mod_ident {
1155 #tokens
1156 #[allow(dead_code)]
1157 pub const TOK_IDS: &[#storaget] = &[#token_array];
1158 }
1159 }
1160 .to_string();
1161 let out_mod = syn::parse_str(&unformatted)
1162 .map(|syntax_tree| prettyplease::unparse(&syntax_tree))
1163 .unwrap_or(unformatted);
1164 outs.push_str(&out_mod);
1165 let mut outp = PathBuf::from(var("OUT_DIR")?);
1166 outp.push(&self.mod_name);
1167 outp.set_extension("rs");
1168
1169 if let Ok(curs) = read_to_string(&outp)
1173 && curs == outs
1174 {
1175 return Ok(());
1176 }
1177
1178 let mut f = File::create(outp)?;
1179 f.write_all(outs.as_bytes())?;
1180 Ok(())
1181 }
1182}
1183
1184#[deprecated(since = "0.14.0", note = "use `lrlex::CTTokenMapBuilder` instead")]
1189pub fn ct_token_map<StorageT: Display + ToTokens>(
1190 mod_name: &str,
1191 token_map: impl Borrow<HashMap<String, StorageT>>,
1192 rename_map: Option<&HashMap<&str, &str>>,
1193) -> Result<(), Box<dyn Error>> {
1194 CTTokenMapBuilder::new(mod_name, token_map)
1195 .rename_map(rename_map)
1196 .allow_dead_code(true)
1197 .build()
1198}
1199
1200fn indent(indent: &str, s: &str) -> String {
1211 format!("{indent}{}\n", s.trim_end_matches('\n')).replace('\n', &format!("\n{}", indent))
1212}
1213
1214#[cfg(all(not(target_arch = "wasm32"), test))]
1218mod test {
1219 use std::fs::File;
1220 use std::io::Write;
1221
1222 use super::{CTLexerBuilder, LexerKind};
1223 #[test]
1224 fn test_grmtools_section_lexerkind() {
1225 let lexerkinds = ["LRNonStreamingLexer", "LexerKind::LRNonStreamingLexer"];
1226 for (i, kind) in lexerkinds.iter().enumerate() {
1227 let lex_src = format!(
1228 "
1229%grmtools{{lexerkind: {}}}
1230%%
1231. ;
1232",
1233 kind
1234 );
1235 let lex_path = format!(
1236 "{}/test_grmtools_section_lexerkind_{}.l",
1237 env!("OUT_DIR"),
1238 i
1239 );
1240 let mut l_file = File::create(lex_path.clone()).unwrap();
1241 l_file.write_all(lex_src.as_bytes()).unwrap();
1242 CTLexerBuilder::new()
1243 .output_path(format!("{}.rs", lex_path.clone()))
1244 .lexer_path(lex_path.clone())
1245 .inspect_lexerkind(Box::new(move |lexerkind| {
1246 assert!(matches!(lexerkind, &LexerKind::LRNonStreamingLexer));
1247 Ok(())
1248 }))
1249 .build()
1250 .unwrap();
1251 }
1252 }
1253
1254 #[test]
1255 fn test_invalid_identifier_in_derived_mod_name() {
1258 let mut lex_path = std::path::PathBuf::from(env!("OUT_DIR"));
1259 lex_path.push("contains-a-dash.l");
1260 let mut f = File::create(&lex_path).unwrap();
1261 let _ = f.write_all(
1262 r#"
1263%%
1264A "A"
1265"#
1266 .as_bytes(),
1267 );
1268 match CTLexerBuilder::new()
1269 .output_path(format!("{}.rs", lex_path.display()))
1270 .lexer_path(lex_path.clone())
1271 .build()
1272 {
1273 Ok(_) => panic!("Expected error"),
1274 Err(e) => {
1275 let err_string = e.to_string();
1276 assert_eq!(
1277 err_string,
1278 "mod_name 'contains-a-dash_l' is not a valid rust identifier due to 'unexpected token'"
1279 );
1280 }
1281 }
1282 }
1283}