diff --git a/cfgrammar/src/lib/header.rs b/cfgrammar/src/lib/header.rs index 2b6e8f00d..619319e38 100644 --- a/cfgrammar/src/lib/header.rs +++ b/cfgrammar/src/lib/header.rs @@ -20,7 +20,6 @@ use std::{ /// * An error during parsing the section. /// * An error resulting from a value in the section having an invalid value. #[derive(Debug, Clone, PartialEq, Eq)] -#[doc(hidden)] pub struct HeaderError { pub kind: HeaderErrorKind, pub locations: Vec, @@ -59,7 +58,6 @@ pub struct HeaderValue(pub T, pub Value); #[derive(Debug, Eq, PartialEq, Clone)] #[non_exhaustive] -#[doc(hidden)] pub enum HeaderErrorKind { MissingGrmtoolsSection, IllegalName, @@ -195,8 +193,10 @@ impl HeaderError { } } +#[doc(hidden)] static RE_LEADING_WS: LazyLock = LazyLock::new(|| Regex::new(r"^[\p{Pattern_White_Space}]*").unwrap()); +#[doc(hidden)] static RE_NAME: LazyLock = LazyLock::new(|| { RegexBuilder::new(r"^[A-Z][A-Z_\.]*") .case_insensitive(true) @@ -210,7 +210,9 @@ pub static RE_CRATE_DOT: LazyLock = LazyLock::new(|| { .build() .unwrap() }); +#[doc(hidden)] static RE_DIGITS: LazyLock = LazyLock::new(|| Regex::new(r"^[0-9]+").unwrap()); +#[doc(hidden)] static RE_STRING: LazyLock = LazyLock::new(|| Regex::new(r#"^\"(\\.|[^"\\])*\""#).unwrap()); #[doc(hidden)] pub static KEY_CRATE_MAP: LazyLock> = LazyLock::new(|| { @@ -284,8 +286,10 @@ pub static REGEX_KEYS: LazyLock> = LazyLock::new(|| { ]) }); +#[doc(hidden)] const MAGIC: &str = "%grmtools"; +#[doc(hidden)] fn add_duplicate_occurrence( errs: &mut Vec>, kind: HeaderErrorKind, diff --git a/cfgrammar/src/lib/mod.rs b/cfgrammar/src/lib/mod.rs index f5bd84065..dd563cd93 100644 --- a/cfgrammar/src/lib/mod.rs +++ b/cfgrammar/src/lib/mod.rs @@ -56,7 +56,6 @@ use serde::{Deserialize, Serialize}; #[cfg(feature = "wincode")] use wincode::{SchemaRead, SchemaWrite}; -#[doc(hidden)] pub mod header; mod idxnewtype; pub mod newlinecache; diff --git a/lrpar/src/lib/codegen.rs b/lrpar/src/lib/codegen.rs index 19278c4d1..00a682a94 100644 --- a/lrpar/src/lib/codegen.rs +++ b/lrpar/src/lib/codegen.rs @@ -1,3 +1,20 @@ +//! The `codegen` module provides a *Sans-I/O* builder for code generation, and grammar construction. +//! +//! **Note:** [`CTParserBuilder`](crate::CTParserBuilder) presents a simpler interface when generating code from cargo. +//! +//! The code generation process has three phases, each phase is represented by a type. +//! +//! 1. [`ParserSrcEnv`] Owns and collects arguments needed to generate an AST from a grammar source string. +//! 2. [`ParserBuildEnv`] Owns an AST generated from the previous phase and collects arguments needed for code generation. +//! 3. [`ParserCodegen`] Owns a grammar generated from an AST, it's state table and state graph, which can be +//! used to generate a `String` value containing rust source code representation of the parser. +//! +//! In addition to generating code it can be used as a general purpose builder for reading the `%grmtools` section +//! and inferring any unspecified values from it, building an AST representation of the grammar and constructing +//! a `YaccGrammar`. +//! +//! Tools like `nimbleparse` can use this as an API for reading the `%grmtools` header before passing the `YaccGrammar` on to +//! an `RTParserBuilder`. So code generation is an important but optional stage within this process. use std::{ any::type_name, collections::HashSet, @@ -34,7 +51,8 @@ const ACTIONS_KIND_HIDDEN: &str = "__GtActionsKindHidden"; #[derive(Debug)] #[non_exhaustive] -pub(crate) enum ParserSrcEnvError { +/// Errors produced by the parser source environment. +pub enum ParserSrcEnvError { GrmtoolsSectionParseError(Vec>), GrmtoolsSectionLookupError(HeaderError), MissingYaccKind, @@ -43,7 +61,8 @@ pub(crate) enum ParserSrcEnvError { #[derive(Debug)] #[non_exhaustive] -pub(crate) enum ParserBuildEnvError +/// Errors produced by the build environment. +pub enum ParserBuildEnvError where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, @@ -56,7 +75,8 @@ where #[derive(Debug)] #[non_exhaustive] -pub(crate) enum CodegenError { +/// Errors produced during code generation. +pub enum CodegenError { ProcMacro2Error(proc_macro2::LexError), InvalidRustIdentifierModName(syn::Error, String), InvalidParseGenerics(syn::Error), @@ -159,7 +179,8 @@ impl fmt::Display for CodegenError { } } -pub(crate) struct ParserSrcEnv<'a, LexerTypesT> +/// A parser source environment owns a grammars source string, and collects args needed to generate an AST. +pub struct ParserSrcEnv<'a, LexerTypesT> where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, @@ -172,7 +193,8 @@ where phantom: PhantomData, } -pub(crate) struct ParserBuildEnvArgs<'a> { +/// Arguments that may be specified when construcing a `ParserBuildEnv` +pub struct ParserBuildEnvArgs<'a> { /// If the input came from a preparsed AST, this will be Some ast_with_validity_info: Option<&'a ASTWithValidityInfo>, mod_name: Option, @@ -183,7 +205,8 @@ pub(crate) struct ParserBuildEnvArgs<'a> { warnings_are_errors: bool, } -pub(crate) struct ParserBuildEnv<'a, LexerTypesT> +/// Owns an AST generated from a [`ParserSrcEnv`] and collects arguments relevant to grammar construction and code generation. +pub struct ParserBuildEnv<'a, LexerTypesT> where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, @@ -199,7 +222,8 @@ where registered_prefixes: HashSet, } -pub(crate) struct ParserCodegen +/// Obtained from a [`ParserBuildEnv`], owns everything needed to generate a rust source representation of a parser. +pub struct ParserCodegen where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, @@ -211,7 +235,7 @@ where } impl<'a> ParserBuildEnvArgs<'a> { - pub(crate) fn new() -> Self { + pub fn new() -> Self { ParserBuildEnvArgs { ast_with_validity_info: None, mod_name: None, @@ -225,33 +249,33 @@ impl<'a> ParserBuildEnvArgs<'a> { /// Set this to `Some(ast)` if the the parser should be built from a pre-parsed AST /// instead of from parsing a source string. - pub(crate) fn ast_with_validity_info(mut self, ast: Option<&'a ASTWithValidityInfo>) -> Self { + pub fn ast_with_validity_info(mut self, ast: Option<&'a ASTWithValidityInfo>) -> Self { self.ast_with_validity_info = ast; self } - pub(crate) fn mod_name(mut self, mod_name: Option<&str>) -> Self { + pub fn mod_name(mut self, mod_name: Option<&str>) -> Self { self.mod_name = mod_name.map(|s| s.to_string()); self } - pub(crate) fn rust_edition(mut self, rust_edition: RustEdition) -> Self { + pub fn rust_edition(mut self, rust_edition: RustEdition) -> Self { self.rust_edition = rust_edition; self } - pub(crate) fn visibility(mut self, visibility: Visibility) -> Self { + pub fn visibility(mut self, visibility: Visibility) -> Self { self.visibility = visibility; self } - pub(crate) fn error_on_conflicts(mut self, error_on_conflicts: bool) -> Self { + pub fn error_on_conflicts(mut self, error_on_conflicts: bool) -> Self { self.error_on_conflicts = error_on_conflicts; self } - pub(crate) fn show_warnings(mut self, show_warnings: bool) -> Self { + pub fn show_warnings(mut self, show_warnings: bool) -> Self { self.show_warnings = show_warnings; self } - pub(crate) fn warnings_are_errors(mut self, warnings_are_errors: bool) -> Self { + pub fn warnings_are_errors(mut self, warnings_are_errors: bool) -> Self { self.warnings_are_errors = warnings_are_errors; self } @@ -262,7 +286,7 @@ where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, { - pub(crate) fn new(src: &'a str, path: Option<&Path>) -> ParserSrcEnv<'a, LexerTypesT> { + pub fn new(src: &'a str, path: Option<&Path>) -> ParserSrcEnv<'a, LexerTypesT> { let fallback_modname = if let Some(path) = path { // When the user hasn't specified a module name, so we create one automatically: what we // do is strip off all the filename extensions (note that it's likely that inp ends @@ -291,12 +315,12 @@ where } } - pub(crate) fn yacckind(mut self, yacckind: Option) -> Self { + pub fn yacckind(mut self, yacckind: Option) -> Self { self.yacckind = yacckind; self } - pub(crate) fn recoverer(mut self, recoverykind: Option) -> Self { + pub fn recoverer(mut self, recoverykind: Option) -> Self { self.recoverer = recoverykind; self } @@ -372,7 +396,7 @@ where } } - pub(crate) fn build_env( + pub fn build_env( mut self, args: ParserBuildEnvArgs<'a>, ) -> Result, ParserSrcEnvError> @@ -408,47 +432,47 @@ where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, { - pub(crate) fn ast_with_validity_info(&self) -> &ASTWithValidityInfo { + pub fn ast_with_validity_info(&self) -> &ASTWithValidityInfo { &self.ast_with_validity_info } - pub(crate) fn serialisation_format(&self) -> &SerialisationFormat { + pub fn serialisation_format(&self) -> &SerialisationFormat { &self.serialisation_format } - pub(crate) fn derived_mod_name(&self) -> &str { + pub fn derived_mod_name(&self) -> &str { &self.mod_name } - pub(crate) fn specified_mod_name(&self) -> Option<&str> { + pub fn specified_mod_name(&self) -> Option<&str> { self.cache_args.mod_name.as_deref() } - pub(crate) fn recoverer(&self) -> RecoveryKind { + pub fn recoverer(&self) -> RecoveryKind { self.recoverer } - pub(crate) fn rust_edition(&self) -> RustEdition { + pub fn rust_edition(&self) -> RustEdition { self.cache_args.rust_edition } - pub(crate) fn visibility(&self) -> &Visibility { + pub fn visibility(&self) -> &Visibility { &self.cache_args.visibility } - pub(crate) fn show_warnings(&self) -> bool { + pub fn show_warnings(&self) -> bool { self.cache_args.show_warnings } - pub(crate) fn warnings_are_errors(&self) -> bool { + pub fn warnings_are_errors(&self) -> bool { self.cache_args.warnings_are_errors } - pub(crate) fn error_on_conflicts(&self) -> bool { + pub fn error_on_conflicts(&self) -> bool { self.cache_args.error_on_conflicts } - pub(crate) fn yacc_kind(&self) -> YaccKind { + pub fn yacc_kind(&self) -> YaccKind { self.ast_with_validity_info.yacc_kind() } @@ -462,7 +486,7 @@ where /// let registered_set = HashSet::from_iter(build_env.registered_header_prefixes()); /// assert!(prefixes_set.difference(registered_set).next().is_none()) /// ``` - pub(crate) fn register_prefix( + pub fn register_prefix( &mut self, crate_prefix: &str, ) -> Result<(), ParserBuildEnvError> { @@ -476,8 +500,7 @@ where } /// Returns the unique set of key prefixes that have been registered by calling `register_header_prefix`. - #[allow(unused)] - pub(crate) fn registered_prefixes(&self) -> impl Iterator { + pub fn registered_prefixes(&self) -> impl Iterator { self.registered_prefixes.iter().map(|s| s.as_str()) } @@ -505,7 +528,7 @@ where Ok(()) } - pub(crate) fn code_generator( + pub fn code_generator( &self, timestamp: &str, ) -> Result, ParserBuildEnvError> { @@ -548,7 +571,7 @@ where &self.sgraph } - pub(crate) fn finish( + pub fn finish( self, ) -> ( YaccGrammar, @@ -558,7 +581,7 @@ where (self.grm, self.sgraph, self.stable) } - pub(crate) fn generate( + pub fn generate( &self, build_env: &ParserBuildEnv, ) -> Result { diff --git a/lrpar/src/lib/mod.rs b/lrpar/src/lib/mod.rs index da84e843a..2bfe0e50c 100644 --- a/lrpar/src/lib/mod.rs +++ b/lrpar/src/lib/mod.rs @@ -203,7 +203,7 @@ pub mod lex_api; #[doc(hidden)] pub mod parser; -mod codegen; +pub mod codegen; #[cfg(test)] pub mod test_utils; diff --git a/nimbleparse/src/main.rs b/nimbleparse/src/main.rs index 0295c501d..43b8ec5ea 100644 --- a/nimbleparse/src/main.rs +++ b/nimbleparse/src/main.rs @@ -1,18 +1,17 @@ use cfgrammar::{ RIdx, Span, TIdx, - header::{ - CFGRAMMAR_KEYS, GrmtoolsSectionParser, Header, HeaderError, HeaderValue, LRPAR_KEYS, Value, - }, + header::Value, yacc::{YaccGrammar, YaccKind, YaccOriginalActionKind, ast::ASTWithValidityInfo}, }; use getopts::Options; use lrlex::{DefaultLexerTypes, LRLexError, LRNonStreamingLexerDef, LexerDef}; use lrpar::{ Lexeme, LexerTypes, + codegen::{ParserBuildEnvArgs, ParserBuildEnvError, ParserSrcEnv, ParserSrcEnvError}, diagnostics::{DiagnosticFormatter, SpannedDiagnosticFormatter}, parser::{RTParserBuilder, RecoveryKind}, }; -use lrtable::{Minimiser, StateTable, from_yacc}; +use lrtable::StateTable; use num_traits::ToPrimitive as _; use num_traits::{AsPrimitive, PrimInt, Unsigned}; use std::{ @@ -207,134 +206,79 @@ fn main() { let yacc_y_path = PathBuf::from(&matches.free[1]); let yacc_src = read_file(&yacc_y_path); let yacc_diag = SpannedDiagnosticFormatter::new(&yacc_src, &yacc_y_path); - // If we were given no yk_arg on the command line, require a grmtools section. - let parsed_header = GrmtoolsSectionParser::new(&yacc_src, yk_arg.is_none()).parse(); - let parsed_header = match parsed_header { - Ok((parsed_header, _)) => parsed_header, - Err(errs) => { - eprintln!( - "{ERROR}{}", - yacc_diag.file_location_msg(" parsing the `%grmtools` section:", None) - ); - for e in errs { - eprintln!("{}", indent(" ", &yacc_diag.format_error(e).to_string())); - } - std::process::exit(1); - } - }; - let yk_header_val = parsed_header - .get("cfgrammar.yacckind") - .map(|HeaderValue(_, value)| match YaccKind::try_from(value) { - Err(e) => { - eprintln!( - "{ERROR}{}", - yacc_diag.file_location_msg(" parsing the `%grmtools` section:", None) - ); - let spanned_e: HeaderError = HeaderError { - kind: e.kind, - locations: e.locations.to_vec(), - }; + // We'll use the codegen process to parse and validate the %grmtools section. + let build_env = ParserSrcEnv::>::new(&yacc_src, Some(&yacc_y_path)) + .yacckind(yk_arg) + .recoverer(rk_arg) + .build_env(ParserBuildEnvArgs::new()); + if let Err(e) = &build_env { + match e { + ParserSrcEnvError::GrmtoolsSectionLookupError(e) => { + eprintln!("{ERROR}{}", yacc_diag.file_location_msg("", None)); eprintln!( "{}", - indent(" ", &yacc_diag.format_error(spanned_e).to_string()) + indent(" ", &yacc_diag.format_error(e.clone()).to_string()) ); - std::process::exit(1); } - - Ok(yacc_kind) => yacc_kind, - }); - let yacc_kind = yk_arg.unwrap_or(yk_header_val.unwrap_or(YaccKind::Grmtools)); - let ast_validation = ASTWithValidityInfo::new(yacc_kind, &yacc_src); - let mut unused_keys = Vec::new(); - // FIXME stop using hidden API - unused_keys.extend( - ast_validation - .iter_prefix_keys("cfgrammar") - .filter(|(key, _)| !CFGRAMMAR_KEYS.contains(key)), - ); - unused_keys.extend( - ast_validation - .iter_prefix_keys("lrpar") - .filter(|(key, _)| !LRPAR_KEYS.contains(key)), - ); - - if !unused_keys.is_empty() { - eprintln!( - "{ERROR}{}", - yacc_diag.file_location_msg(" parsing the `%grmtools` section:", None) - ); - for (_, span) in unused_keys { - eprintln!( - "{}", - indent( - " ", - &yacc_diag - .underline_span_with_text( - span, - "Unused key in grmtools section".to_string(), - '^' - ) - .to_string() - ) - ); - } - process::exit(1) - } - let rk_header_val = parsed_header - .get("lrpar.recoverer") - .map( - |HeaderValue(_, value)| match RecoveryKind::try_from(value) { - Err(e) => { + ParserSrcEnvError::GrmtoolsSectionParseError(errs) => { + eprintln!("{ERROR}{}", yacc_diag.file_location_msg("", None)); + for e in errs { eprintln!( - "{ERROR}{}", - yacc_diag.file_location_msg(" parsing the `%grmtools` section:", None) + "{}", + indent(" ", &yacc_diag.format_error(e.clone()).to_string()) ); - let spanned_e: HeaderError = HeaderError { - kind: e.kind, - locations: e.locations.to_vec(), - }; + } + } + e => { + eprintln!("{}", e); + } + } + eprintln!("{}", e); + std::process::exit(1); + } + let build_env = build_env.unwrap(); + let ast_validation = build_env.ast_with_validity_info(); + let warnings = ast_validation.ast().warnings(); + let codegen = build_env.code_generator(""); + if let Err(e) = &codegen { + match e { + ParserBuildEnvError::YaccGrammarErrors(errs) => { + eprintln!("{ERROR}{}", yacc_diag.file_location_msg("", None)); + for e in errs { eprintln!( "{}", - indent(" ", &yacc_diag.format_error(spanned_e).to_string()) + indent(" ", &yacc_diag.format_error(e.clone()).to_string()) ); - process::exit(1) } - Ok(rk) => rk, - }, - ); - let recoverykind = rk_arg.unwrap_or(rk_header_val.unwrap_or(RecoveryKind::CPCTPlus)); - let warnings = ast_validation.ast().warnings(); - let res = YaccGrammar::new_from_ast_with_validity_info(&ast_validation); - let grm = match res { - Ok(x) => { - if !warnings.is_empty() { - eprintln!("{WARNING}{}", yacc_diag.file_location_msg("", None)); - for w in warnings { - eprintln!("{}", indent(" ", &yacc_diag.format_warning(w))); + if !warnings.is_empty() { + eprintln!("{WARNING}{}", yacc_diag.file_location_msg("", None)); + for w in warnings { + eprintln!("{}", indent(" ", &yacc_diag.format_warning(w))); + } } } - x - } - Err(errs) => { - eprintln!("{ERROR}{}", yacc_diag.file_location_msg("", None)); - for e in errs { - eprintln!("{}", indent(" ", &yacc_diag.format_error(e).to_string())); + e @ ParserBuildEnvError::GrmtoolsSectionUnusedKeys(errs) => { + eprintln!("{ERROR}{}", yacc_diag.file_location_msg("", None)); + for (_, span) in errs { + eprintln!( + "{}", + yacc_diag.underline_span_with_text(*span, e.to_string(), '^') + ); + } } - eprintln!("{WARNING}{}", yacc_diag.file_location_msg("", None)); - for w in warnings { - eprintln!("{}", indent(" ", &yacc_diag.format_warning(w))); + e => { + eprintln!("{}", e); } - process::exit(1); } - }; - let (sgraph, stable) = match from_yacc(&grm, Minimiser::Pager) { - Ok(x) => x, - Err(s) => { - eprintln!("{}: {}", yacc_y_path.display(), s); - process::exit(1); + process::exit(1); + } + if !warnings.is_empty() { + eprintln!("{WARNING}{}", yacc_diag.file_location_msg("", None)); + for w in warnings { + eprintln!("{}", indent(" ", &yacc_diag.format_warning(w))); } - }; - + } + let (grm, sgraph, stable) = codegen.unwrap().finish(); if dump_state_graph { println!("Stategraph:\n{}\n", sgraph.pp_core_states(&grm)); } @@ -420,12 +364,12 @@ fn main() { } let parser_build_ctxt = ParserBuildCtxt { - header: parsed_header, + ast_validation, lexerdef, grm, stable, yacc_y_path, - recoverykind, + recoverykind: build_env.recoverer(), }; if matches.free.len() == 3 { @@ -449,12 +393,12 @@ fn main() { } } -struct ParserBuildCtxt +struct ParserBuildCtxt<'a, LexerTypesT> where LexerTypesT: LexerTypes, usize: AsPrimitive, { - header: Header, + ast_validation: &'a ASTWithValidityInfo, lexerdef: LRNonStreamingLexerDef, grm: YaccGrammar, yacc_y_path: PathBuf, @@ -518,7 +462,7 @@ impl fmt::Display for NimbleparseError { } } -impl ParserBuildCtxt +impl ParserBuildCtxt<'_, LexerTypesT> where LexerTypesT: LexerTypes, usize: AsPrimitive, @@ -557,8 +501,8 @@ where ); } else { // If given no input paths, try to find some with `test_files` in the header. - match self.header.get("lrpar.test_files") { - Some(HeaderValue(_, Value::Array(test_globs, _))) => { + match self.ast_validation.header_value_get("lrpar.test_files") { + Some((_, Value::Array(test_globs, _))) => { for setting in test_globs { match setting { Value::String(s, _) => {