diff --git a/cfgrammar/Cargo.toml b/cfgrammar/Cargo.toml index 468ce87a1..97218b93b 100644 --- a/cfgrammar/Cargo.toml +++ b/cfgrammar/Cargo.toml @@ -12,6 +12,8 @@ keywords = ["yacc", "grammar"] [features] serde = ["dep:serde", "serde/derive", "vob/serde"] wincode = ["dep:wincode", "vob/wincode"] +_unstable_api = [] +_unsealed_unstable_traits = ["_unstable_api"] [lib] name = "cfgrammar" diff --git a/cfgrammar/src/lib/header.rs b/cfgrammar/src/lib/header.rs index 2b6e8f00d..7ab69377f 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, @@ -197,12 +195,14 @@ impl HeaderError { static RE_LEADING_WS: LazyLock = LazyLock::new(|| Regex::new(r"^[\p{Pattern_White_Space}]*").unwrap()); + static RE_NAME: LazyLock = LazyLock::new(|| { RegexBuilder::new(r"^[A-Z][A-Z_\.]*") .case_insensitive(true) .build() .unwrap() }); + #[doc(hidden)] pub static RE_CRATE_DOT: LazyLock = LazyLock::new(|| { RegexBuilder::new(r"^[A-Z][A-Z_]*\.") @@ -210,8 +210,11 @@ pub static RE_CRATE_DOT: LazyLock = LazyLock::new(|| { .build() .unwrap() }); + static RE_DIGITS: LazyLock = LazyLock::new(|| Regex::new(r"^[0-9]+").unwrap()); + static RE_STRING: LazyLock = LazyLock::new(|| Regex::new(r#"^\"(\\.|[^"\\])*\""#).unwrap()); + #[doc(hidden)] pub static KEY_CRATE_MAP: LazyLock> = LazyLock::new(|| { let mut map = HashMap::new(); diff --git a/cfgrammar/src/lib/mod.rs b/cfgrammar/src/lib/mod.rs index f5bd84065..99284998d 100644 --- a/cfgrammar/src/lib/mod.rs +++ b/cfgrammar/src/lib/mod.rs @@ -56,8 +56,9 @@ use serde::{Deserialize, Serialize}; #[cfg(feature = "wincode")] use wincode::{SchemaRead, SchemaWrite}; -#[doc(hidden)] +#[cfg_attr(not(feature = "_unstable_api"), doc(hidden))] pub mod header; + mod idxnewtype; pub mod newlinecache; pub mod span; @@ -79,3 +80,71 @@ pub enum Symbol { Rule(RIdx), Token(TIdx), } + +/// This private module with pub items which is directly related to +/// the "Sealed trait" pattern. These items are used within the current +/// crate. See `unstable_api` module for enabling usage outside the crate. +mod unstable { + #![allow(unused)] + #![allow(unreachable_pub)] + pub struct UnstableApi; + pub trait UnstableTrait {} +} + +/// A module for lifting restrictions on visibility by enabling unstable features. +/// +/// See the sources for a complete list of features, and members. +pub mod unstable_api { + /// Unstable functions that take a value `UnstableApi` require + /// the "_unstable_api" feature. This feature controls + /// whether the value has `pub` visibility outside the crate. + #[cfg_attr(not(feature = "_unstable_api"), doc(hidden))] + pub use crate::unstable::UnstableApi; + + /// This is a a supertrait for traits that are considered to be Unstable. + /// Unstable traits do not provide any semver guarantees. + /// + /// Enabling the `_unsealed_unstable traits` makes this supertrait publicly + /// Visible. + /// + /// + /// Declaring an unstable Api within the crate: + /// ```ignore_rust + /// // Within the crate use `crate::unstable::` . + /// pub trait Foo: crate::unstable::UnstableTrait { + /// fn foo(key: crate::unstable::UnstableApi); + /// } + /// ``` + /// + /// Deriving the trait outside the crate (requires feature `_unsealed_unstable_traits`) + /// ```ignore_rust + /// struct Bar; + /// impl unstable_api::UnstableTrait for Bar{} + /// impl Foo for Bar { + /// fn foo(key: unstable_api::UnstableApi) { + /// ... + /// } + /// } + /// ``` + /// + /// + /// Calling an implementation of the trait outside the crate (requires feature `_unstable_api`: + /// ```ignore_rust + /// let x: &dyn Foo = ...; + /// x.foo(unstable_api::UnstableApi); + /// ``` + #[cfg(feature = "_unsealed_unstable_traits")] + pub use crate::unstable::UnstableTrait; + + /// An value that acts as a key to inform callers that they are + /// calling an unstable internal api. This value is public by default. + /// Access to it does not require any features to be enabled. + /// + /// Q. When this should be used? + /// + /// A. When generated code needs to call internal api within it, + /// where you do not want the caller to have to enable any features + /// to use the generated code. + #[doc(hidden)] + pub struct InternalPublicApi; +} diff --git a/cfgrammar/src/lib/yacc/ast.rs b/cfgrammar/src/lib/yacc/ast.rs index a54f5f816..348a05960 100644 --- a/cfgrammar/src/lib/yacc/ast.rs +++ b/cfgrammar/src/lib/yacc/ast.rs @@ -114,8 +114,13 @@ impl ASTWithValidityInfo { } } + #[cfg_attr(not(feature = "_unstable_api"), doc(hidden))] /// Performs a lookup in the grmtools section for an entry with the key `crate_name.key_name` and returns it. - pub fn header_value_get(&self, key: &str) -> Option<(Span, &Value)> { + pub fn header_value_get( + &self, + key: &str, + _: crate::unstable_api::UnstableApi, + ) -> Option<(Span, &Value)> { if let Some(HeaderValue(span, value)) = self.grmtools_section.get(key) { Some((*span, value)) } else { @@ -1108,7 +1113,7 @@ start -> () : "a" { () }; ), ), ] { - let value = ast_validity.header_value_get(&key); + let value = ast_validity.header_value_get(&key, crate::unstable_api::UnstableApi); assert_eq!(value, Some((expected_span, &expected_value))); } assert_eq!( @@ -1119,7 +1124,7 @@ start -> () : "a" { () }; vec![("test.unused", src.find_span("test.unused"))] ); assert_eq!( - ast_validity.header_value_get("cfgrammar.yacckind"), + ast_validity.header_value_get("cfgrammar.yacckind", crate::unstable_api::UnstableApi), Some(( src.find_span("yacckind"), &Value::Namespaced("Grmtools".to_string(), src.find_span("Grmtools")) @@ -1133,7 +1138,7 @@ start -> () : "a" { () }; ); assert_eq!( - ast_validity.header_value_get("lrpar.recoverer"), + ast_validity.header_value_get("lrpar.recoverer", crate::unstable_api::UnstableApi), Some(( src.find_span("lrpar.recoverer"), &Value::Namespaced("CPCTPlus".to_string(), src.find_span("CPCTPlus")) @@ -1166,7 +1171,7 @@ start: "a" { () }; "#; let ast_validity = ASTWithValidityInfo::from_str(src).unwrap(); assert_eq!( - ast_validity.header_value_get("cfgrammar.yacckind"), + ast_validity.header_value_get("cfgrammar.yacckind", crate::unstable_api::UnstableApi), Some(( src.find_span("yacckind"), &Value::Namespaced( @@ -1197,7 +1202,7 @@ start: "a" { () }; "#; let ast_validity = ASTWithValidityInfo::from_str(src).unwrap(); assert_eq!( - ast_validity.header_value_get("cfgrammar.yacckind"), + ast_validity.header_value_get("cfgrammar.yacckind", crate::unstable_api::UnstableApi), Some(( src.find_span("yacckind"), &Value::Namespaced( @@ -1228,7 +1233,7 @@ start: "a" { () }; "#; let ast_validity = ASTWithValidityInfo::from_str(src).unwrap(); assert_eq!( - ast_validity.header_value_get("cfgrammar.yacckind"), + ast_validity.header_value_get("cfgrammar.yacckind", crate::unstable_api::UnstableApi), Some(( src.find_span("yacckind"), &Value::Namespaced( diff --git a/lrlex/src/lib/mod.rs b/lrlex/src/lib/mod.rs index 6d806f79d..d78cde59c 100644 --- a/lrlex/src/lib/mod.rs +++ b/lrlex/src/lib/mod.rs @@ -241,7 +241,7 @@ pub mod unstable_api { /// Unstable functions that take a value `UnstableApi` require /// the "_unstable_api" feature. This feature controls /// whether the value has `pub` visibility outside the crate. - #[cfg(feature = "_unstable_api")] + #[cfg_attr(not(feature = "_unstable_api"), doc(hidden))] pub use crate::unstable::UnstableApi; /// This is a a supertrait for traits that are considered to be Unstable. @@ -288,5 +288,6 @@ pub mod unstable_api { /// A. When generated code needs to call internal api within it, /// where you do not want the caller to have to enable any features /// to use the generated code. + #[doc(hidden)] pub struct InternalPublicApi; } diff --git a/lrpar/src/lib/codegen.rs b/lrpar/src/lib/codegen.rs index 19278c4d1..a7d65f2b7 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, @@ -16,7 +33,8 @@ use cfgrammar::{ RIdx, Span, Symbol, header::{CFGRAMMAR_KEYS, GrmtoolsSectionParser, Header, HeaderError, HeaderValue, LRPAR_KEYS}, yacc::{ - YaccGrammar, YaccGrammarError, YaccKind, YaccOriginalActionKind, ast::ASTWithValidityInfo, + YaccGrammar, YaccGrammarError, YaccGrammarWarning, YaccKind, YaccOriginalActionKind, + ast::ASTWithValidityInfo, }, }; @@ -34,29 +52,32 @@ 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), + GrmtoolsSectionUnusedKeys(Vec<(String, Span)>), MissingYaccKind, MissingModName, } #[derive(Debug)] #[non_exhaustive] -pub(crate) enum ParserBuildEnvError +/// Errors produced by the build environment. +pub enum ParserBuildEnvError where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, { StateTableError(StateTableError), YaccGrammarErrors(Vec), - GrmtoolsSectionUnusedKeys(Vec<(String, Span)>), DuplicatePrefixRegistrationError(String), } #[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), @@ -116,6 +137,10 @@ impl fmt::Display for ParserSrcEnvError { .collect::>() .join("\n"), Self::GrmtoolsSectionLookupError(e) => e.to_string(), + Self::GrmtoolsSectionUnusedKeys(keys) => { + let keys = keys.iter().cloned().map(|(s, _)| s).collect::>(); + format!("Unused keys in %grmtools section: {}", keys.join(", ")) + } Self::MissingYaccKind => "Code generator cannot resolve yacc kind".to_string(), Self::MissingModName => "Code generator requires a mod name".to_string(), }) @@ -135,10 +160,6 @@ where .map(|e| e.to_string()) .collect::>() .join("\n"), - Self::GrmtoolsSectionUnusedKeys(keys) => { - let keys = keys.iter().cloned().map(|(s, _)| s).collect::>(); - format!("Unused keys in %grmtools section: {}", keys.join(", ")) - } Self::DuplicatePrefixRegistrationError(prefix) => { format!("Registered duplicate prefix: \"{prefix}\"") } @@ -159,7 +180,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 +194,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 +206,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 +223,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 +236,7 @@ where } impl<'a> ParserBuildEnvArgs<'a> { - pub(crate) fn new() -> Self { + pub fn new(_: crate::unstable_api::UnstableApi) -> Self { ParserBuildEnvArgs { ast_with_validity_info: None, mod_name: None, @@ -225,33 +250,45 @@ 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 { + /// Set the module name to use for the generated parser sources. + /// + /// If not speciied a module name will attempt to be derived from the grammar path name. + 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 { + /// Sets the rust edition to use for the generated sources + 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 { + + /// Sets the visibility qualifier + 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 { + + /// Sets whether conflicts should be considered an error. + 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 { + + /// Sets whether warnings should be shown. + 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 { + + /// Sets whether warnings should be treated as errors. + pub fn warnings_are_errors(mut self, warnings_are_errors: bool) -> Self { self.warnings_are_errors = warnings_are_errors; self } @@ -262,7 +299,16 @@ where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, { - pub(crate) fn new(src: &'a str, path: Option<&Path>) -> ParserSrcEnv<'a, LexerTypesT> { + /// Constructs a new `ParserSrcEnv` given the contents of a `.y` file as a `String` + /// and an optional path to the grammar. + /// + /// The path is only used as information, there will not be any filesystem interactions + /// involving the path. + pub fn new( + src: &'a str, + path: Option<&Path>, + _: crate::unstable_api::UnstableApi, + ) -> 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,18 +337,23 @@ where } } - pub(crate) fn yacckind(mut self, yacckind: Option) -> Self { + /// Explicitly sets the [`YaccKind`] to be used. + /// + /// If `None` a `YaccKind` will attempt to be derived from the `yacckind` field in the `%grmtools` header. + pub fn yacckind(mut self, yacckind: Option) -> Self { self.yacckind = yacckind; self } - pub(crate) fn recoverer(mut self, recoverykind: Option) -> Self { + /// Explicitly sets the [`RecoveryKind`] to be used. + /// + /// If `None` a `RecoveryKind` will attempt to be derived from the `recoverer` field in the `%grmtools` header. + pub fn recoverer(mut self, recoverykind: Option) -> Self { self.recoverer = recoverykind; self } - /// Looks up the `yacckind` field from the header, marks the field - /// as used then constructs AST of that kind. + /// Looks up the `yacckind` field from the header then constructs AST of that kind. fn resolve_ast_with_validity_info( &mut self, from_ast: Option<&ASTWithValidityInfo>, @@ -324,8 +375,7 @@ where } } - /// Looks up the `recoverer` field in the header, marks the field - /// as used, and defaulting to `CPCTPlus` if unfound. + /// Looks up the `recoverer` field in the header defaults to `CPCTPlus` if unfound. fn resolve_recoverer( &mut self, header: &Header, @@ -372,7 +422,35 @@ where } } - pub(crate) fn build_env( + /// Checks all the keys staring with grmtools crate prefixes. If any of them are unrecognized returns an error. + fn check_unused_grmtools_header_values( + &self, + ast_with_validity_info: &ASTWithValidityInfo, + ) -> Result<(), ParserSrcEnvError> { + let mut unrecognized_keys = Vec::new(); + unrecognized_keys.extend( + ast_with_validity_info + .iter_prefix_keys("cfgrammar") + .filter(|(key, _)| !CFGRAMMAR_KEYS.contains(key)) + .map(|(s, span)| (s.to_string(), span)), + ); + unrecognized_keys.extend( + ast_with_validity_info + .iter_prefix_keys("lrpar") + .filter(|(key, _)| !LRPAR_KEYS.contains(key)) + .map(|(s, span)| (s.to_string(), span)), + ); + if !unrecognized_keys.is_empty() { + return Err(ParserSrcEnvError::GrmtoolsSectionUnusedKeys( + unrecognized_keys, + )); + } + Ok(()) + } + + /// Generates an [`ASTWithValidityInfo`] from the given sources resolving any unset values to their defaults. + /// Constructs a [`ParserBuildEnv`] to own the AST with the given arguments. + pub fn build_env( mut self, args: ParserBuildEnvArgs<'a>, ) -> Result, ParserSrcEnvError> @@ -383,6 +461,7 @@ where let (header, _) = GrmtoolsSectionParser::new(self.src, false).parse()?; let ast_with_validity_info = self.resolve_ast_with_validity_info(args.ast_with_validity_info, &header)?; + self.check_unused_grmtools_header_values(&ast_with_validity_info)?; let recoverer = self.resolve_recoverer(&header)?; let serialisation_format = self.resolve_serialisation_format(&header)?; let mod_name = self.resolve_mod_name(&args)?; @@ -408,50 +487,66 @@ where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, { - pub(crate) fn ast_with_validity_info(&self) -> &ASTWithValidityInfo { + /// Returns the AST from the build environment. + pub fn ast_with_validity_info(&self) -> &ASTWithValidityInfo { &self.ast_with_validity_info } - pub(crate) fn serialisation_format(&self) -> &SerialisationFormat { + /// Returns the serialisation format to be used by the generated sources. + pub fn serialisation_format(&self) -> &SerialisationFormat { &self.serialisation_format } - pub(crate) fn derived_mod_name(&self) -> &str { + /// Returns the `mod_name` that will be used in the generated code. + pub fn derived_mod_name(&self) -> &str { &self.mod_name } - pub(crate) fn specified_mod_name(&self) -> Option<&str> { + /// Returns an explicitly specified `mod_name` if one was given. + pub fn specified_mod_name(&self) -> Option<&str> { self.cache_args.mod_name.as_deref() } - pub(crate) fn recoverer(&self) -> RecoveryKind { + /// Returns the recoverer to be used. + pub fn recoverer(&self) -> RecoveryKind { self.recoverer } - pub(crate) fn rust_edition(&self) -> RustEdition { + /// Returns the rust edition that will be used within the generated code. + pub fn rust_edition(&self) -> RustEdition { self.cache_args.rust_edition } - pub(crate) fn visibility(&self) -> &Visibility { + /// Returns the visibility qualifier to be used within the generated code. + pub fn visibility(&self) -> &Visibility { &self.cache_args.visibility } - pub(crate) fn show_warnings(&self) -> bool { + /// Returns whether warnings should be shown. + pub fn show_warnings(&self) -> bool { self.cache_args.show_warnings } - pub(crate) fn warnings_are_errors(&self) -> bool { + /// Returns whether warnings should be treated as errors. + pub fn warnings_are_errors(&self) -> bool { self.cache_args.warnings_are_errors } - pub(crate) fn error_on_conflicts(&self) -> bool { + /// Returns whether conflicts should be treated as errors. + pub fn error_on_conflicts(&self) -> bool { self.cache_args.error_on_conflicts } - pub(crate) fn yacc_kind(&self) -> YaccKind { + /// Returns the `YaccKind` of the generated AST. + pub fn yacc_kind(&self) -> YaccKind { self.ast_with_validity_info.yacc_kind() } + /// Returns all the warnings discovered while constructing the AST + pub fn warnings(&self) -> Vec { + self.ast_with_validity_info.ast().warnings() + } + /// Adds the `crate_prefix` to the list of registered prefixes. /// The intent is that the user can check the registered keys against `ast_with_validity_info.iter_prefixes()` /// So that all the values in `ast_with_validity_info.iter_prefixes()` are also in `self.registered_header_prefixes()` @@ -462,7 +557,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,40 +571,16 @@ 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()) } - /// Checks all the keys staring with `crate_prefixes`. If any of them are `unused`, return an error. - /// If `crate_prefixes` contains the empty string, returns an arror if any key is unused. - fn check_unused_grmtools_header_values(&self) -> Result<(), ParserBuildEnvError> { - let mut unrecognized_keys = Vec::new(); - unrecognized_keys.extend( - self.ast_with_validity_info() - .iter_prefix_keys("cfgrammar") - .filter(|(key, _)| !CFGRAMMAR_KEYS.contains(key)) - .map(|(s, span)| (s.to_string(), span)), - ); - unrecognized_keys.extend( - self.ast_with_validity_info() - .iter_prefix_keys("lrpar") - .filter(|(key, _)| !LRPAR_KEYS.contains(key)) - .map(|(s, span)| (s.to_string(), span)), - ); - if !unrecognized_keys.is_empty() { - return Err(ParserBuildEnvError::GrmtoolsSectionUnusedKeys( - unrecognized_keys, - )); - } - Ok(()) - } - - pub(crate) fn code_generator( + /// Generates a `YaccGrammar`, `StateTable`, and `StateGraph` from the AST owned by this build environment. + /// Returns a `ParserCodegen` which can be used to generate a rust source `String` representation of the grammar. + pub fn code_generator( &self, timestamp: &str, ) -> Result, ParserBuildEnvError> { - self.check_unused_grmtools_header_values()?; let grm = YaccGrammar::::new_from_ast_with_validity_info( &self.ast_with_validity_info, )?; @@ -548,7 +619,8 @@ where &self.sgraph } - pub(crate) fn finish( + /// Takes ownership of self, and returns the `YaccGrammar` it's state graph and table. + pub fn finish( self, ) -> ( YaccGrammar, @@ -558,7 +630,8 @@ where (self.grm, self.sgraph, self.stable) } - pub(crate) fn generate( + /// Generates a rust source `String` representation of the grammar. + pub fn generate( &self, build_env: &ParserBuildEnv, ) -> Result { @@ -1340,12 +1413,15 @@ mod test { %% start -> () : "A" { () }; "#; - let src_env = ParserSrcEnv::::new(src, None); + let src_env = + ParserSrcEnv::::new(src, None, crate::unstable_api::UnstableApi); let expected_errs = vec![HeaderError { kind: HeaderErrorKind::IllegalName, locations: vec![src.find_span("testfoo")], }]; - match src_env.build_env(ParserBuildEnvArgs::new().mod_name(Some("test_module"))) { + match src_env.build_env( + ParserBuildEnvArgs::new(crate::unstable_api::UnstableApi).mod_name(Some("test_module")), + ) { Err(ParserSrcEnvError::GrmtoolsSectionParseError(errs)) => { assert_eq!(errs, expected_errs) } @@ -1364,12 +1440,12 @@ mod test { %% start -> () : "A" { () }; "#; - let src_env = ParserSrcEnv::::new(src, None); - let build_env = src_env - .build_env(ParserBuildEnvArgs::new().mod_name(Some("test_module"))) - .unwrap(); - match build_env.code_generator("timestamp") { - Err(ParserBuildEnvError::GrmtoolsSectionUnusedKeys(keys)) => { + let src_env = + ParserSrcEnv::::new(src, None, crate::unstable_api::UnstableApi); + match src_env.build_env( + ParserBuildEnvArgs::new(crate::unstable_api::UnstableApi).mod_name(Some("test_module")), + ) { + Err(ParserSrcEnvError::GrmtoolsSectionUnusedKeys(keys)) => { assert_eq!( &keys, &[ @@ -1396,9 +1472,13 @@ mod test { %% start -> () : "A" { () }; "#; - let src_env = ParserSrcEnv::::new(src, None); + let src_env = + ParserSrcEnv::::new(src, None, crate::unstable_api::UnstableApi); let mut build_env = src_env - .build_env(ParserBuildEnvArgs::new().mod_name(Some("test_module"))) + .build_env( + ParserBuildEnvArgs::new(crate::unstable_api::UnstableApi) + .mod_name(Some("test_module")), + ) .unwrap(); build_env.register_prefix("registered").unwrap(); let found_prefixes = build_env diff --git a/lrpar/src/lib/ctbuilder.rs b/lrpar/src/lib/ctbuilder.rs index e534789e3..a9dd175d7 100644 --- a/lrpar/src/lib/ctbuilder.rs +++ b/lrpar/src/lib/ctbuilder.rs @@ -521,11 +521,11 @@ where read_to_string(grmp).map_err(|e| format!("When reading '{}': {e}", grmp.display()))? }; - let src_env = ParserSrcEnv::new(&inc, Some(grmp)) + let src_env = ParserSrcEnv::new(&inc, Some(grmp), crate::unstable_api::UnstableApi) .yacckind(self.yacckind) .recoverer(self.recoverer); let yacc_diag = SpannedDiagnosticFormatter::new(&inc, grmp); - let build_args = ParserBuildEnvArgs::new() + let build_args = ParserBuildEnvArgs::new(crate::unstable_api::UnstableApi) .ast_with_validity_info(self.from_ast.as_ref()) .mod_name(self.mod_name) .show_warnings(self.show_warnings) @@ -546,6 +546,17 @@ where } Box::::from(ErrorString(out)) } + ref e @ ParserSrcEnvError::GrmtoolsSectionUnusedKeys(ref errs) => { + let mut out = String::new(); + out.push_str(&format!("{ERROR}{}", yacc_diag.file_location_msg("", None))); + for (_, span) in errs { + out.push_str(&indent( + " ", + &yacc_diag.underline_span_with_text(*span, e.to_string(), '^'), + )); + } + Box::::from(ErrorString(out)) + } e => e.to_string().into(), })?; // Temporarily we update self.yacckind and self.recoverer from the build_env @@ -553,7 +564,7 @@ where self.recoverer = Some(build_env.recoverer()); self.yacckind = Some(build_env.yacc_kind()); - let warnings = build_env.ast_with_validity_info().ast().warnings(); + let warnings = build_env.warnings(); if self.warnings_are_errors && !warnings.is_empty() { let mut out = String::new(); out.push_str(&format!( diff --git a/lrpar/src/lib/mod.rs b/lrpar/src/lib/mod.rs index da84e843a..7dcb4be9e 100644 --- a/lrpar/src/lib/mod.rs +++ b/lrpar/src/lib/mod.rs @@ -203,7 +203,8 @@ pub mod lex_api; #[doc(hidden)] pub mod parser; -mod codegen; +#[cfg_attr(not(feature = "_unstable_api"), doc(hidden))] +pub mod codegen; #[cfg(test)] pub mod test_utils; @@ -258,7 +259,7 @@ pub mod unstable_api { /// Unstable functions that take a value `UnstableApi` require /// the "_unstable_api" feature. This feature controls /// whether the value has `pub` visibility outside the crate. - #[cfg(feature = "_unstable_api")] + #[cfg_attr(not(feature = "_unstable_api"), doc(hidden))] pub use crate::unstable::UnstableApi; /// This is a a supertrait for traits that are considered to be Unstable. @@ -305,5 +306,6 @@ pub mod unstable_api { /// A. When generated code needs to call internal api within it, /// where you do not want the caller to have to enable any features /// to use the generated code. + #[doc(hidden)] pub struct InternalPublicApi; } diff --git a/nimbleparse/src/main.rs b/nimbleparse/src/main.rs index 0295c501d..90886de0e 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,84 @@ 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), + lrpar::unstable_api::UnstableApi, + ) + .yacckind(yk_arg) + .recoverer(rk_arg) + .build_env(ParserBuildEnvArgs::new(lrpar::unstable_api::UnstableApi)); + 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 @ ParserSrcEnvError::GrmtoolsSectionUnusedKeys(errs) => { + eprintln!("{ERROR}{}", yacc_diag.file_location_msg("", None)); + for (_, span) in errs { eprintln!( "{}", - indent(" ", &yacc_diag.format_error(spanned_e).to_string()) + yacc_diag.underline_span_with_text(*span, e.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))); } } - x + e => { + eprintln!("{}", e); + } } - Err(errs) => { - eprintln!("{ERROR}{}", yacc_diag.file_location_msg("", None)); - for e in errs { - eprintln!("{}", indent(" ", &yacc_diag.format_error(e).to_string())); + eprintln!("{}", e); + std::process::exit(1); + } + let build_env = build_env.unwrap(); + let warnings = build_env.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(e.clone()).to_string()) + ); + } + if !warnings.is_empty() { + eprintln!("{WARNING}{}", yacc_diag.file_location_msg("", None)); + for w in warnings { + eprintln!("{}", indent(" ", &yacc_diag.format_warning(w))); + } + } } - 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); + } + let codegen = codegen.unwrap(); + let ast_validation = build_env.ast_with_validity_info(); + 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.finish(); if dump_state_graph { println!("Stategraph:\n{}\n", sgraph.pp_core_states(&grm)); } @@ -420,12 +369,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 +398,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 +467,7 @@ impl fmt::Display for NimbleparseError { } } -impl ParserBuildCtxt +impl ParserBuildCtxt<'_, LexerTypesT> where LexerTypesT: LexerTypes, usize: AsPrimitive, @@ -557,8 +506,12 @@ 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", + // To enable this unstable api from an external crate see the `_unstable_api feature`, + cfgrammar::unstable_api::UnstableApi, + ) { + Some((_, Value::Array(test_globs, _))) => { for setting in test_globs { match setting { Value::String(s, _) => {