1use std::{
4 collections::{HashMap, HashSet},
5 env::{current_dir, var},
6 error::Error,
7 fmt::{self, Debug, Write as fmtWrite},
8 fs::{self, File, create_dir_all, read_to_string},
9 hash::Hash,
10 io::Write,
11 marker::PhantomData,
12 path::{Path, PathBuf},
13 sync::{LazyLock, Mutex},
14};
15
16use crate::{
17 LexerTypes, RTParserBuilder, RecoveryKind,
18 codegen::{
19 ParserBuildEnv, ParserBuildEnvArgs, ParserBuildEnvError, ParserCodegen, ParserSrcEnv,
20 ParserSrcEnvError,
21 },
22 diagnostics::{DiagnosticFormatter, SpannedDiagnosticFormatter},
23};
24
25#[cfg(feature = "_unstable_api")]
26use crate::unstable_api::UnstableApi;
27
28use cfgrammar::{
29 Span,
30 header::{Header, HeaderError, HeaderErrorKind, Value},
31 yacc::{YaccGrammar, YaccKind, ast::ASTWithValidityInfo},
32};
33use filetime::FileTime;
34use lrtable::{StateGraph, StateTable, statetable::Conflicts};
35use num_traits::{AsPrimitive, PrimInt, Unsigned};
36use wincode::{SchemaRead, SchemaReadOwned, SchemaWrite};
37
38const RUST_FILE_EXT: &str = "rs";
39const WARNING: &str = "[Warning]";
40pub(crate) const ERROR: &str = "[Error]";
41
42static GENERATED_PATHS: LazyLock<Mutex<HashSet<PathBuf>>> =
43 LazyLock::new(|| Mutex::new(HashSet::new()));
44
45pub(crate) struct CTConflictsError<StorageT: Eq + Hash> {
46 pub(crate) conflicts_diagnostic: String,
47 #[cfg(test)]
48 #[cfg_attr(test, allow(dead_code))]
49 pub(crate) stable: StateTable<StorageT>,
50 pub(crate) phantom: PhantomData<StorageT>,
51}
52
53impl<StorageT> fmt::Display for CTConflictsError<StorageT>
54where
55 StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
56 usize: AsPrimitive<StorageT>,
57{
58 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59 write!(f, "{}", self.conflicts_diagnostic)
60 }
61}
62
63impl<StorageT> fmt::Debug for CTConflictsError<StorageT>
64where
65 StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
66 usize: AsPrimitive<StorageT>,
67{
68 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 write!(f, "{}", self.conflicts_diagnostic)
70 }
71}
72
73impl<StorageT> Error for CTConflictsError<StorageT>
74where
75 StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
76 usize: AsPrimitive<StorageT>,
77{
78}
79
80struct ErrorString(String);
82impl fmt::Display for ErrorString {
83 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84 let ErrorString(s) = self;
85 write!(f, "{}", s)
86 }
87}
88impl fmt::Debug for ErrorString {
89 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90 let ErrorString(s) = self;
91 write!(f, "{}", s)
92 }
93}
94impl Error for ErrorString {}
95
96#[derive(Clone, PartialEq, Eq, Debug)]
98#[non_exhaustive]
99pub enum Visibility {
100 Private,
102 Public,
104 PublicSuper,
106 PublicSelf,
108 PublicCrate,
110 PublicIn(String),
112}
113
114#[derive(Clone, Copy, PartialEq, Eq, Debug)]
118#[non_exhaustive]
119pub enum RustEdition {
120 Rust2015,
121 Rust2018,
122 Rust2021,
123}
124
125#[non_exhaustive]
129#[derive(SchemaRead, SchemaWrite, Debug, Clone, Copy)]
130pub enum SerialisationFormat {
131 FixedSizeInteger,
133 VariableSizedInteger,
135}
136
137impl TryFrom<&Value<Span>> for SerialisationFormat {
138 type Error = HeaderError<Span>;
139 fn try_from(value: &Value<Span>) -> Result<SerialisationFormat, HeaderError<Span>> {
140 match value {
141 Value::Namespaced(serialisation_fmt, span) => match serialisation_fmt.as_str() {
142 "SerialisationFormat::FixedSizeInteger" | "FixedSizeInteger" => {
143 Ok(SerialisationFormat::FixedSizeInteger)
144 }
145 "SerialisationFormat::VariableSizedInteger" | "VariableSizedInteger" => {
146 Ok(SerialisationFormat::VariableSizedInteger)
147 }
148 _ => Err(HeaderError {
149 kind: HeaderErrorKind::InvalidEntry("serialisation_format"),
150 locations: vec![*span],
151 }),
152 },
153 val => Err(HeaderError {
154 kind: HeaderErrorKind::InvalidEntry("serialisation_format"),
155 locations: vec![*val.primary_location()],
156 }),
157 }
158 }
159}
160
161#[doc(hidden)]
163pub use wincode;
164
165pub struct CTParserBuilder<'a, LexerTypesT: LexerTypes>
168where
169 LexerTypesT::StorageT: Eq + Hash,
170 usize: AsPrimitive<LexerTypesT::StorageT>,
171{
172 grammar_path: Option<PathBuf>,
176 grammar_src: Option<String>,
178 from_ast: Option<ASTWithValidityInfo>,
180 output_path: Option<PathBuf>,
181 mod_name: Option<&'a str>,
182 recoverer: Option<RecoveryKind>,
183 yacckind: Option<YaccKind>,
184 error_on_conflicts: bool,
185 warnings_are_errors: bool,
186 show_warnings: bool,
187 visibility: Visibility,
188 rust_edition: RustEdition,
189 inspect_rt: Option<
190 Box<
191 dyn for<'b> FnMut(
192 &'b Header<Span>,
193 RTParserBuilder<LexerTypesT::StorageT, LexerTypesT>,
194 &'b HashMap<String, LexerTypesT::StorageT>,
195 &PathBuf,
196 ) -> Result<(), Box<dyn Error>>,
197 >,
198 >,
199 serialisation_format: Option<SerialisationFormat>,
200 #[cfg(test)]
202 inspect_callback: Option<Box<dyn Fn(RecoveryKind) -> Result<(), Box<dyn Error>>>>,
203 phantom: PhantomData<LexerTypesT>,
204}
205
206pub(crate) type FixIntConfig = wincode::config::Configuration;
208pub(crate) type VarIntConfig = wincode::config::Configuration<
210 true,
211 4194304,
212 wincode::len::BincodeLen,
213 wincode::int_encoding::LittleEndian,
214 wincode::int_encoding::VarInt,
215>;
216
217impl<
218 'a,
219 StorageT: 'static
220 + Debug
221 + Hash
222 + PrimInt
223 + SchemaWrite<FixIntConfig, Src = StorageT>
224 + SchemaWrite<VarIntConfig, Src = StorageT>
225 + Unsigned,
226 LexerTypesT: LexerTypes<StorageT = StorageT>,
227> CTParserBuilder<'a, LexerTypesT>
228where
229 usize: AsPrimitive<StorageT>,
230{
231 pub fn new() -> Self {
253 CTParserBuilder {
254 grammar_path: None,
255 grammar_src: None,
256 from_ast: None,
257 output_path: None,
258 mod_name: None,
259 recoverer: None,
260 yacckind: None,
261 error_on_conflicts: true,
262 warnings_are_errors: true,
263 show_warnings: true,
264 visibility: Visibility::Private,
265 rust_edition: RustEdition::Rust2021,
266 inspect_rt: None,
267 serialisation_format: None,
268 #[cfg(test)]
269 inspect_callback: None,
270 phantom: PhantomData,
271 }
272 }
273
274 pub fn grammar_in_src_dir<P>(mut self, srcp: P) -> Result<Self, Box<dyn Error>>
291 where
292 P: AsRef<Path>,
293 {
294 if !srcp.as_ref().is_relative() {
295 return Err(format!(
296 "Grammar path '{}' must be a relative path.",
297 srcp.as_ref().to_str().unwrap_or("<invalid UTF-8>")
298 )
299 .into());
300 }
301
302 let mut grmp = current_dir()?;
303 grmp.push("src");
304 grmp.push(srcp.as_ref());
305 self.grammar_path = Some(grmp);
306
307 let mut outp = PathBuf::new();
308 outp.push(var("OUT_DIR").unwrap());
309 outp.push(srcp.as_ref().parent().unwrap().to_str().unwrap());
310 create_dir_all(&outp)?;
311 let mut leaf = srcp
312 .as_ref()
313 .file_name()
314 .unwrap()
315 .to_str()
316 .unwrap()
317 .to_owned();
318 write!(leaf, ".{}", RUST_FILE_EXT).ok();
319 outp.push(leaf);
320 Ok(self.output_path(outp))
321 }
322
323 #[cfg(feature = "_unstable_api")]
326 pub fn grammar_ast(mut self, valid_ast: ASTWithValidityInfo, _api_key: UnstableApi) -> Self {
327 self.from_ast = Some(valid_ast);
328 self
329 }
330
331 pub fn grammar_path<P>(mut self, inp: P) -> Self
335 where
336 P: AsRef<Path>,
337 {
338 self.grammar_path = Some(inp.as_ref().to_owned());
339 self
340 }
341
342 #[cfg(feature = "_unstable_api")]
343 pub fn with_grammar_src(mut self, src: String, _api_key: UnstableApi) -> Self {
344 self.grammar_src = Some(src);
345 self
346 }
347
348 pub fn output_path<P>(mut self, outp: P) -> Self
353 where
354 P: AsRef<Path>,
355 {
356 self.output_path = Some(outp.as_ref().to_owned());
357 self
358 }
359
360 pub fn mod_name(mut self, mod_name: &'a str) -> Self {
364 self.mod_name = Some(mod_name);
365 self
366 }
367
368 pub fn visibility(mut self, vis: Visibility) -> Self {
370 self.visibility = vis;
371 self
372 }
373
374 pub fn recoverer(mut self, rk: RecoveryKind) -> Self {
376 self.recoverer = Some(rk);
377 self
378 }
379
380 pub fn yacckind(mut self, yk: YaccKind) -> Self {
382 self.yacckind = Some(yk);
383 self
384 }
385
386 pub fn error_on_conflicts(mut self, b: bool) -> Self {
389 self.error_on_conflicts = b;
390 self
391 }
392
393 pub fn warnings_are_errors(mut self, b: bool) -> Self {
396 self.warnings_are_errors = b;
397 self
398 }
399
400 pub fn show_warnings(mut self, b: bool) -> Self {
403 self.show_warnings = b;
404 self
405 }
406
407 pub fn rust_edition(mut self, edition: RustEdition) -> Self {
410 self.rust_edition = edition;
411 self
412 }
413
414 pub fn serialisation_format(mut self, serialisation_format: SerialisationFormat) -> Self {
415 self.serialisation_format = Some(serialisation_format);
416 self
417 }
418
419 #[cfg(test)]
420 pub fn inspect_recoverer(
421 mut self,
422 cb: Box<dyn for<'h, 'y> Fn(RecoveryKind) -> Result<(), Box<dyn Error>>>,
423 ) -> Self {
424 self.inspect_callback = Some(cb);
425 self
426 }
427
428 #[doc(hidden)]
429 pub fn inspect_rt(
430 mut self,
431 cb: Box<
432 dyn for<'b, 'y> FnMut(
433 &'b Header<Span>,
434 RTParserBuilder<'y, StorageT, LexerTypesT>,
435 &'b HashMap<String, StorageT>,
436 &PathBuf,
437 ) -> Result<(), Box<dyn Error>>,
438 >,
439 ) -> Self {
440 self.inspect_rt = Some(cb);
441 self
442 }
443
444 pub fn build(mut self) -> Result<CTParser<StorageT>, Box<dyn Error>> {
497 let grmp = self
498 .grammar_path
499 .as_ref()
500 .expect("grammar_path must be specified before processing.");
501 let outp = self
502 .output_path
503 .as_ref()
504 .expect("output_path must be specified before processing.");
505
506 if let Some(YaccKind::Eco) = self.yacckind {
507 panic!("Eco compile-time grammar generation not supported.")
508 }
509
510 {
511 let mut lk = GENERATED_PATHS.lock().unwrap();
512 if lk.contains(outp.as_path()) {
513 return Err(format!("Generating two parsers to the same path ('{}') is not allowed: use CTParserBuilder::output_path (and, optionally, CTParserBuilder::mod_name) to differentiate them.", outp.to_str().unwrap()).into());
514 }
515 lk.insert(outp.clone());
516 }
517
518 let inc = if let Some(grammar_src) = &self.grammar_src {
519 grammar_src.clone()
520 } else {
521 read_to_string(grmp).map_err(|e| format!("When reading '{}': {e}", grmp.display()))?
522 };
523
524 let src_env = ParserSrcEnv::new(&inc, Some(grmp))
525 .yacckind(self.yacckind)
526 .recoverer(self.recoverer);
527 let yacc_diag = SpannedDiagnosticFormatter::new(&inc, grmp);
528 let build_args = ParserBuildEnvArgs::new()
529 .ast_with_validity_info(self.from_ast.as_ref())
530 .mod_name(self.mod_name)
531 .show_warnings(self.show_warnings)
532 .error_on_conflicts(self.error_on_conflicts)
533 .warnings_are_errors(self.warnings_are_errors)
534 .visibility(self.visibility.clone())
535 .rust_edition(self.rust_edition);
536 let build_env = src_env.build_env(build_args).map_err(|e| match e {
537 ParserSrcEnvError::GrmtoolsSectionParseError(es) => {
538 let mut out = String::new();
539 out.push_str(&format!(
540 "\n{ERROR}{}\n",
541 yacc_diag.file_location_msg(" parsing the `%grmtools` section", None)
542 ));
543 for e in es {
544 out.push_str(&indent(" ", &yacc_diag.format_error(e).to_string()));
545 out.push('\n');
546 }
547 Box::<dyn Error>::from(ErrorString(out))
548 }
549 e => e.to_string().into(),
550 })?;
551 self.recoverer = Some(build_env.recoverer());
554 self.yacckind = Some(build_env.yacc_kind());
555
556 let warnings = build_env.ast_with_validity_info().ast().warnings();
557 if self.warnings_are_errors && !warnings.is_empty() {
558 let mut out = String::new();
559 out.push_str(&format!(
560 "\n{ERROR}{}\n",
561 yacc_diag.file_location_msg("", None)
562 ));
563 for e in warnings {
564 out.push_str(&format!(
565 "{}\n",
566 indent(" ", &yacc_diag.format_warning(e).to_string())
567 ));
568 }
569 return Err(ErrorString(out).into());
570 } else if !warnings.is_empty() {
571 for w in warnings {
572 let ws_loc = yacc_diag.file_location_msg("", None);
573 let ws = indent(" ", &yacc_diag.format_warning(w).to_string());
574 if std::env::var("OUT_DIR").is_ok() && self.show_warnings {
576 for line in ws_loc.lines().chain(ws.lines()) {
577 println!("cargo:warning={}", line);
578 }
579 } else if self.show_warnings {
580 eprintln!("{}", ws_loc);
581 eprintln!("{WARNING} {}", ws);
582 }
583 }
584 }
585
586 #[cfg(test)]
587 if let Some(cb) = &self.inspect_callback {
588 cb(build_env.recoverer())?;
589 }
590
591 let timestamp = env!("VERGEN_BUILD_TIMESTAMP");
592 let code_gen = build_env.code_generator(timestamp).map_err(|e| match e {
593 ParserBuildEnvError::YaccGrammarErrors(errs) => {
594 let mut out = String::new();
595 out.push_str(&format!(
596 "\n{ERROR}{}\n",
597 yacc_diag.file_location_msg("", None)
598 ));
599 for e in errs {
600 out.push_str(&indent(" ", &yacc_diag.format_error(e).to_string()));
601 out.push('\n');
602 }
603 ErrorString(out)
604 }
605 e => ErrorString(e.to_string()),
606 })?;
607 let grm = code_gen.grm();
608 let rule_ids = grm
609 .tokens_map()
610 .iter()
611 .map(|(&n, &i)| (n.to_owned(), i.as_storaget()))
612 .collect::<HashMap<_, _>>();
613
614 let cache = code_gen.cache_str(&build_env);
615
616 if let Ok(ref inmd) = fs::metadata(grmp)
624 && let Ok(ref out_rs_md) = fs::metadata(outp)
625 && FileTime::from_last_modification_time(out_rs_md)
626 > FileTime::from_last_modification_time(inmd)
627 && let Ok(outc) = read_to_string(outp)
628 {
629 if outc.contains(&cache) {
630 let (grm, _, _) = code_gen.finish();
631
632 return Ok(CTParser {
633 regenerated: false,
634 rule_ids,
635 yacc_grammar: grm,
636 grammar_src: inc,
637 grammar_path: self.grammar_path.unwrap(),
638 conflicts: None,
639 });
640 } else {
641 #[cfg(grmtools_extra_checks)]
642 if std::env::var("CACHE_EXPECTED").is_ok() {
643 eprintln!("outc: {}", outc);
644 eprintln!("using cache: {}", cache,);
645 panic!("The cache regenerated however, it was expected to match");
647 }
648 }
649 }
650
651 fs::remove_file(outp).ok();
658
659 let stable = code_gen.stable();
660 if self.error_on_conflicts
661 && let Some(c) = stable.conflicts()
662 {
663 match (grm.expect(), grm.expectrr()) {
664 (Some(i), Some(j)) if i == c.sr_len() && j == c.rr_len() => (),
665 (Some(i), None) if i == c.sr_len() && 0 == c.rr_len() => (),
666 (None, Some(j)) if 0 == c.sr_len() && j == c.rr_len() => (),
667 (None, None) if 0 == c.rr_len() && 0 == c.sr_len() => (),
668 _ => {
669 let conflicts_diagnostic = yacc_diag.format_conflicts::<LexerTypesT>(
670 grm,
671 build_env.ast_with_validity_info().ast(),
672 c,
673 code_gen.sgraph(),
674 stable,
675 );
676 #[cfg(test)]
677 let (_, _, stable) = code_gen.finish();
678 return Err(Box::new(CTConflictsError {
679 conflicts_diagnostic,
680 phantom: PhantomData,
681 #[cfg(test)]
682 stable,
683 }));
684 }
685 }
686 }
687
688 if let Some(inspector_rt) = &mut self.inspect_rt {
689 let rt: RTParserBuilder<'_, StorageT, LexerTypesT> = RTParserBuilder::new(grm, stable);
690 let rt = if let Some(rk) = self.recoverer {
691 rt.recoverer(rk)
692 } else {
693 rt
694 };
695 inspector_rt(
696 build_env.ast_with_validity_info().header(),
697 rt,
698 &rule_ids,
699 grmp,
700 )?
701 }
702
703 self.output_file(
704 &code_gen,
705 outp,
706 &format!("/* CACHE INFORMATION {} */\n", cache),
707 &build_env,
708 )?;
709 let (grm, sgraph, stable) = code_gen.finish();
710 let conflicts = if stable.conflicts().is_some() {
711 Some((sgraph, stable))
712 } else {
713 None
714 };
715 Ok(CTParser {
716 regenerated: true,
717 rule_ids,
718 yacc_grammar: grm,
719 grammar_src: inc,
720 grammar_path: self.grammar_path.unwrap(),
721 conflicts,
722 })
723 }
724
725 #[deprecated(
732 since = "0.11.0",
733 note = "Please use grammar_in_src_dir(), build(), and token_map() instead"
734 )]
735 #[allow(deprecated)]
736 pub fn process_file_in_src(
737 &mut self,
738 srcp: &str,
739 ) -> Result<HashMap<String, StorageT>, Box<dyn Error>> {
740 let mut inp = current_dir()?;
741 inp.push("src");
742 inp.push(srcp);
743 let mut outp = PathBuf::new();
744 outp.push(var("OUT_DIR").unwrap());
745 outp.push(Path::new(srcp).parent().unwrap().to_str().unwrap());
746 create_dir_all(&outp)?;
747 let mut leaf = Path::new(srcp)
748 .file_name()
749 .unwrap()
750 .to_str()
751 .unwrap()
752 .to_owned();
753 write!(leaf, ".{}", RUST_FILE_EXT).ok();
754 outp.push(leaf);
755 self.process_file(inp, outp)
756 }
757
758 #[deprecated(
794 since = "0.11.0",
795 note = "Please use grammar_path(), output_path(), build(), and token_map() instead"
796 )]
797 pub fn process_file<P, Q>(
798 &mut self,
799 inp: P,
800 outp: Q,
801 ) -> Result<HashMap<String, StorageT>, Box<dyn Error>>
802 where
803 P: AsRef<Path>,
804 Q: AsRef<Path>,
805 {
806 self.grammar_path = Some(inp.as_ref().to_owned());
807 self.output_path = Some(outp.as_ref().to_owned());
808 let cl: CTParserBuilder<LexerTypesT> = CTParserBuilder {
809 grammar_path: self.grammar_path.clone(),
810 grammar_src: None,
811 from_ast: None,
812 output_path: self.output_path.clone(),
813 mod_name: self.mod_name,
814 recoverer: self.recoverer,
815 yacckind: self.yacckind,
816 error_on_conflicts: self.error_on_conflicts,
817 warnings_are_errors: self.warnings_are_errors,
818 show_warnings: self.show_warnings,
819 visibility: self.visibility.clone(),
820 rust_edition: self.rust_edition,
821 inspect_rt: None,
822 serialisation_format: self.serialisation_format,
823 #[cfg(test)]
824 inspect_callback: None,
825 phantom: PhantomData,
826 };
827 Ok(cl.build()?.rule_ids)
828 }
829
830 fn output_file<P: AsRef<Path>>(
831 &self,
832 code_gen: &ParserCodegen<LexerTypesT>,
833 outp_rs: P,
834 cache: &str,
835 build_env: &ParserBuildEnv<'_, LexerTypesT>,
836 ) -> Result<(), Box<dyn Error>> {
837 let outs = code_gen
838 .generate(build_env)
839 .map_err(|e| ErrorString(e.to_string()))?;
840 let mut f = File::create(outp_rs)?;
841 f.write_all(outs.as_bytes())?;
842 f.write_all(cache.as_bytes())?;
843 Ok(())
844 }
845}
846
847#[doc(hidden)]
850pub struct ParserData<StorageT: Eq + Hash> {
851 grm: YaccGrammar<StorageT>,
852 stable: StateTable<StorageT>,
853}
854
855impl<StorageT: Eq + Hash> ParserData<StorageT> {
856 pub fn grm(&self) -> &YaccGrammar<StorageT> {
857 &self.grm
858 }
859
860 pub fn stable(&self) -> &StateTable<StorageT> {
861 &self.stable
862 }
863}
864
865#[doc(hidden)]
868pub fn _reconstitute<
869 C: wincode::config::Config + Clone + Copy,
870 StorageT: SchemaReadOwned<C, Dst = StorageT> + Eq + Hash + PrimInt + Unsigned + 'static,
871>(
872 grm_buf: &[u8],
873 stable_buf: &[u8],
874 config: C,
875) -> ParserData<StorageT> {
876 let grm: YaccGrammar<StorageT> = wincode::config::deserialize_from(grm_buf, config).unwrap();
877 let stable = wincode::config::deserialize_from(stable_buf, config).unwrap();
878 ParserData { grm, stable }
879}
880
881pub struct CTParser<StorageT = u32>
883where
884 StorageT: Eq + Hash,
885{
886 regenerated: bool,
887 rule_ids: HashMap<String, StorageT>,
888 yacc_grammar: YaccGrammar<StorageT>,
889 grammar_src: String,
890 grammar_path: PathBuf,
891 conflicts: Option<(StateGraph<StorageT>, StateTable<StorageT>)>,
892}
893
894impl<StorageT> CTParser<StorageT>
895where
896 StorageT: 'static + Debug + Hash + PrimInt + Unsigned,
897 usize: AsPrimitive<StorageT>,
898{
899 pub fn regenerated(&self) -> bool {
901 self.regenerated
902 }
903
904 pub fn token_map(&self) -> &HashMap<String, StorageT> {
907 &self.rule_ids
908 }
909
910 #[allow(private_interfaces)]
916 pub fn conflicts(
917 &self,
918 _: crate::unstable::UnstableApi,
919 ) -> Option<(
920 &YaccGrammar<StorageT>,
921 &StateGraph<StorageT>,
922 &StateTable<StorageT>,
923 &Conflicts<StorageT>,
924 )> {
925 if let Some((sgraph, stable)) = &self.conflicts {
926 return Some((
927 &self.yacc_grammar,
928 sgraph,
929 stable,
930 stable.conflicts().unwrap(),
931 ));
932 }
933 None
934 }
935
936 #[doc(hidden)]
937 pub fn yacc_grammar(&self) -> &YaccGrammar<StorageT> {
938 &self.yacc_grammar
939 }
940 #[doc(hidden)]
941 pub fn grammar_src(&self) -> &str {
942 &self.grammar_src
943 }
944 #[doc(hidden)]
945 pub fn grammar_path(&self) -> &Path {
946 self.grammar_path.as_path()
947 }
948}
949
950pub(crate) fn indent(indent: &str, s: &str) -> String {
961 format!("{indent}{}\n", s.trim_end_matches('\n')).replace('\n', &format!("\n{}", indent))
962}
963
964#[cfg(all(not(target_arch = "wasm32"), test))]
966mod test {
967 use std::{fs::File, io::Write, path::PathBuf};
968
969 use super::{CTConflictsError, CTParserBuilder};
970 use crate::test_utils::TestLexerTypes;
971 use cfgrammar::yacc::{YaccKind, YaccOriginalActionKind};
972 use tempfile::TempDir;
973
974 #[test]
975 fn test_conflicts() {
976 let temp = TempDir::new().unwrap();
977 let mut file_path = PathBuf::from(temp.as_ref());
978 file_path.push("grm.y");
979 let mut f = File::create(&file_path).unwrap();
980 let _ = f.write_all(
981 "%start A
982%%
983A : 'a' 'b' | B 'b';
984B : 'a' | C;
985C : 'a';"
986 .as_bytes(),
987 );
988
989 match CTParserBuilder::<TestLexerTypes>::new()
990 .error_on_conflicts(false)
991 .yacckind(YaccKind::Original(YaccOriginalActionKind::GenericParseTree))
992 .grammar_path(file_path.to_str().unwrap())
993 .output_path(file_path.with_extension("ignored"))
994 .build()
995 .unwrap()
996 .conflicts(crate::unstable::UnstableApi)
997 {
998 Some((_, _, _, conflicts)) => {
999 assert_eq!(conflicts.sr_len(), 1);
1000 assert_eq!(conflicts.rr_len(), 1);
1001 }
1002 None => panic!("Expected error data"),
1003 }
1004 }
1005
1006 #[test]
1007 fn test_conflicts_error() {
1008 let temp = TempDir::new().unwrap();
1009 let mut file_path = PathBuf::from(temp.as_ref());
1010 file_path.push("grm.y");
1011 let mut f = File::create(&file_path).unwrap();
1012 let _ = f.write_all(
1013 "%start A
1014%%
1015A : 'a' 'b' | B 'b';
1016B : 'a' | C;
1017C : 'a';"
1018 .as_bytes(),
1019 );
1020
1021 match CTParserBuilder::<TestLexerTypes>::new()
1022 .yacckind(YaccKind::Original(YaccOriginalActionKind::GenericParseTree))
1023 .grammar_path(file_path.to_str().unwrap())
1024 .output_path(file_path.with_extension("ignored"))
1025 .build()
1026 {
1027 Ok(_) => panic!("Expected error"),
1028 Err(e) => {
1029 let cs = e.downcast_ref::<CTConflictsError<u16>>();
1030 assert_eq!(cs.unwrap().stable.conflicts().unwrap().rr_len(), 1);
1031 assert_eq!(cs.unwrap().stable.conflicts().unwrap().sr_len(), 1);
1032 }
1033 }
1034 }
1035
1036 #[test]
1037 fn test_expect_error() {
1038 let temp = TempDir::new().unwrap();
1039 let mut file_path = PathBuf::from(temp.as_ref());
1040 file_path.push("grm.y");
1041 let mut f = File::create(&file_path).unwrap();
1042 let _ = f.write_all(
1043 "%start A
1044%expect 2
1045%%
1046A: 'a' 'b' | B 'b';
1047B: 'a';"
1048 .as_bytes(),
1049 );
1050
1051 match CTParserBuilder::<TestLexerTypes>::new()
1052 .yacckind(YaccKind::Original(YaccOriginalActionKind::GenericParseTree))
1053 .grammar_path(file_path.to_str().unwrap())
1054 .output_path(file_path.with_extension("ignored"))
1055 .build()
1056 {
1057 Ok(_) => panic!("Expected error"),
1058 Err(e) => {
1059 let cs = e.downcast_ref::<CTConflictsError<u16>>();
1060 assert_eq!(cs.unwrap().stable.conflicts().unwrap().rr_len(), 0);
1061 assert_eq!(cs.unwrap().stable.conflicts().unwrap().sr_len(), 1);
1062 }
1063 }
1064 }
1065
1066 #[test]
1067 fn test_expectrr_error() {
1068 let temp = TempDir::new().unwrap();
1069 let mut file_path = PathBuf::from(temp.as_ref());
1070 file_path.push("grm.y");
1071 let mut f = File::create(&file_path).unwrap();
1072 let _ = f.write_all(
1073 "%start A
1074%expect 1
1075%expect-rr 2
1076%%
1077A : 'a' 'b' | B 'b';
1078B : 'a' | C;
1079C : 'a';"
1080 .as_bytes(),
1081 );
1082
1083 match CTParserBuilder::<TestLexerTypes>::new()
1084 .yacckind(YaccKind::Original(YaccOriginalActionKind::GenericParseTree))
1085 .grammar_path(file_path.to_str().unwrap())
1086 .output_path(file_path.with_extension("ignored"))
1087 .build()
1088 {
1089 Ok(_) => panic!("Expected error"),
1090 Err(e) => {
1091 let cs = e.downcast_ref::<CTConflictsError<u16>>();
1092 assert_eq!(cs.unwrap().stable.conflicts().unwrap().rr_len(), 1);
1093 assert_eq!(cs.unwrap().stable.conflicts().unwrap().sr_len(), 1);
1094 }
1095 }
1096 }
1097
1098 #[test]
1099 fn test_invalid_identifier_in_derived_mod_name() {
1102 let temp = TempDir::new().unwrap();
1103 let mut file_path = PathBuf::from(temp.as_ref());
1104 file_path.push("contains-a-dash.y");
1105 let mut f = File::create(&file_path).unwrap();
1106 let _ = f.write_all(
1107 "%start A
1108%%
1109A : 'a';"
1110 .as_bytes(),
1111 );
1112 match CTParserBuilder::<TestLexerTypes>::new()
1113 .yacckind(YaccKind::Original(YaccOriginalActionKind::GenericParseTree))
1114 .grammar_path(file_path.to_str().unwrap())
1115 .output_path(file_path.with_extension("ignored"))
1116 .build()
1117 {
1118 Ok(_) => panic!("Expected error"),
1119 Err(e) => {
1120 let err_string = e.to_string();
1121 assert_eq!(
1122 err_string,
1123 "mod_name \'contains-a-dash_y\' is not a valid rust identifier due to 'unexpected token'"
1124 );
1125 }
1126 }
1127 }
1128
1129 #[cfg(test)]
1130 #[test]
1131 fn test_recoverer_header() -> Result<(), Box<dyn std::error::Error>> {
1132 use crate::RecoveryKind as RK;
1133 #[rustfmt::skip]
1134 let recovery_kinds = [
1135 (Some(RK::None), Some(RK::None), Some(RK::None)),
1138 (Some(RK::None), Some(RK::CPCTPlus), Some(RK::None)),
1139 (Some(RK::CPCTPlus), Some(RK::CPCTPlus), Some(RK::CPCTPlus)),
1140 (Some(RK::CPCTPlus), Some(RK::None), Some(RK::CPCTPlus)),
1141 (None, Some(RK::CPCTPlus), Some(RK::CPCTPlus)),
1142 (None, Some(RK::None), Some(RK::None)),
1143 (None, None, Some(RK::CPCTPlus)),
1144 (Some(RK::None), None, Some(RK::None)),
1145 (Some(RK::CPCTPlus), None, Some(RK::CPCTPlus)),
1146 ];
1147
1148 for (i, (builder_arg, header_arg, expected_rk)) in
1149 recovery_kinds.iter().cloned().enumerate()
1150 {
1151 let y_src = if let Some(header_arg) = header_arg {
1152 format!(
1153 "\
1154 %grmtools{{yacckind: Original(NoAction), recoverer: {}}} \
1155 %% \
1156 start: ; \
1157 ",
1158 match header_arg {
1159 RK::None => "RecoveryKind::None",
1160 RK::CPCTPlus => "RecoveryKind::CPCTPlus",
1161 }
1162 )
1163 } else {
1164 r#"
1165 %grmtools{yacckind: Original(NoAction)}
1166 %%
1167 Start: ;
1168 "#
1169 .to_string()
1170 };
1171 let out_dir = std::env::var("OUT_DIR").unwrap();
1172 let y_path = format!("{out_dir}/recoverykind_test_{i}.y");
1173 let y_out_path = format!("{y_path}.rs");
1174 std::fs::File::create(y_path.clone()).unwrap();
1175 std::fs::write(y_path.clone(), y_src).unwrap();
1176 let mut cp_builder = CTParserBuilder::<TestLexerTypes>::new();
1177 cp_builder = cp_builder
1178 .output_path(y_out_path.clone())
1179 .grammar_path(y_path.clone());
1180 cp_builder = if let Some(builder_arg) = builder_arg {
1181 cp_builder.recoverer(builder_arg)
1182 } else {
1183 cp_builder
1184 }
1185 .inspect_recoverer(Box::new(move |rk| {
1186 if matches!(
1187 (rk, expected_rk),
1188 (RK::None, Some(RK::None)) | (RK::CPCTPlus, Some(RK::CPCTPlus))
1189 ) {
1190 Ok(())
1191 } else {
1192 panic!("Unexpected recovery kind")
1193 }
1194 }));
1195 cp_builder.build()?;
1196 }
1197 Ok(())
1198 }
1199}