From 37a7b22a9c1a717817a712a8cfba6f4c18fd57f1 Mon Sep 17 00:00:00 2001 From: matt rice Date: Sun, 29 Nov 2026 03:26:17 -0800 Subject: [PATCH 1/8] Make the codegen module unstable API --- lrpar/src/lib/codegen.rs | 98 ++++++++++++++++++++++---------------- lrpar/src/lib/ctbuilder.rs | 4 +- lrpar/src/lib/mod.rs | 6 ++- 3 files changed, 62 insertions(+), 46 deletions(-) diff --git a/lrpar/src/lib/codegen.rs b/lrpar/src/lib/codegen.rs index 19278c4d1..3be5c71b4 100644 --- a/lrpar/src/lib/codegen.rs +++ b/lrpar/src/lib/codegen.rs @@ -34,7 +34,7 @@ const ACTIONS_KIND_HIDDEN: &str = "__GtActionsKindHidden"; #[derive(Debug)] #[non_exhaustive] -pub(crate) enum ParserSrcEnvError { +pub enum ParserSrcEnvError { GrmtoolsSectionParseError(Vec>), GrmtoolsSectionLookupError(HeaderError), MissingYaccKind, @@ -43,7 +43,7 @@ pub(crate) enum ParserSrcEnvError { #[derive(Debug)] #[non_exhaustive] -pub(crate) enum ParserBuildEnvError +pub enum ParserBuildEnvError where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, @@ -56,7 +56,7 @@ where #[derive(Debug)] #[non_exhaustive] -pub(crate) enum CodegenError { +pub enum CodegenError { ProcMacro2Error(proc_macro2::LexError), InvalidRustIdentifierModName(syn::Error, String), InvalidParseGenerics(syn::Error), @@ -159,7 +159,7 @@ impl fmt::Display for CodegenError { } } -pub(crate) struct ParserSrcEnv<'a, LexerTypesT> +pub struct ParserSrcEnv<'a, LexerTypesT> where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, @@ -172,7 +172,7 @@ where phantom: PhantomData, } -pub(crate) struct ParserBuildEnvArgs<'a> { +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 +183,7 @@ pub(crate) struct ParserBuildEnvArgs<'a> { warnings_are_errors: bool, } -pub(crate) struct ParserBuildEnv<'a, LexerTypesT> +pub struct ParserBuildEnv<'a, LexerTypesT> where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, @@ -199,7 +199,7 @@ where registered_prefixes: HashSet, } -pub(crate) struct ParserCodegen +pub struct ParserCodegen where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, @@ -211,7 +211,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 +225,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 +262,11 @@ 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>, + _: 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,12 +295,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 +376,7 @@ where } } - pub(crate) fn build_env( + pub fn build_env( mut self, args: ParserBuildEnvArgs<'a>, ) -> Result, ParserSrcEnvError> @@ -408,47 +412,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 +466,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 +480,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 +508,7 @@ where Ok(()) } - pub(crate) fn code_generator( + pub fn code_generator( &self, timestamp: &str, ) -> Result, ParserBuildEnvError> { @@ -548,7 +551,7 @@ where &self.sgraph } - pub(crate) fn finish( + pub fn finish( self, ) -> ( YaccGrammar, @@ -558,7 +561,7 @@ where (self.grm, self.sgraph, self.stable) } - pub(crate) fn generate( + pub fn generate( &self, build_env: &ParserBuildEnv, ) -> Result { @@ -1340,12 +1343,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,9 +1370,13 @@ mod test { %% start -> () : "A" { () }; "#; - let src_env = ParserSrcEnv::::new(src, None); + let src_env = + ParserSrcEnv::::new(src, None, crate::unstable_api::UnstableApi); let 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(); match build_env.code_generator("timestamp") { Err(ParserBuildEnvError::GrmtoolsSectionUnusedKeys(keys)) => { @@ -1396,9 +1406,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..5892f2109 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) 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; } From a91855fed4f9ca9ca0fc5dc98ca61e0cab24cd56 Mon Sep 17 00:00:00 2001 From: matt rice Date: Sun, 29 Nov 2026 03:28:57 -0800 Subject: [PATCH 2/8] Make parts of the header module unstable API. This marks `Value`, `HeaderError`, and `HeaderErrorKind` in the header module as unstable API. --- cfgrammar/Cargo.toml | 2 + cfgrammar/src/lib/header.rs | 7 +++- cfgrammar/src/lib/mod.rs | 71 ++++++++++++++++++++++++++++++++++- cfgrammar/src/lib/yacc/ast.rs | 19 ++++++---- 4 files changed, 89 insertions(+), 10 deletions(-) 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( From 1b3784b82f94275991b20e25d9ee3cdf51ee3074 Mon Sep 17 00:00:00 2001 From: matt rice Date: Sun, 29 Nov 2026 03:26:31 -0800 Subject: [PATCH 3/8] Replace nimbleparse usage of hidden api with unstable api. --- nimbleparse/src/main.rs | 198 +++++++++++++++------------------------- 1 file changed, 75 insertions(+), 123 deletions(-) diff --git a/nimbleparse/src/main.rs b/nimbleparse/src/main.rs index 0295c501d..e07ad7c75 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,83 @@ 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 => { + 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 +368,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 +397,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 +466,7 @@ impl fmt::Display for NimbleparseError { } } -impl ParserBuildCtxt +impl ParserBuildCtxt<'_, LexerTypesT> where LexerTypesT: LexerTypes, usize: AsPrimitive, @@ -557,8 +505,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, _) => { From 67ef570a4fd2c1581fc66ac49cf7c0a511ebf0a0 Mon Sep 17 00:00:00 2001 From: matt rice Date: Sun, 29 Nov 2026 04:49:26 -0800 Subject: [PATCH 4/8] Document the codegen module --- lrpar/src/lib/codegen.rs | 70 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 4 deletions(-) diff --git a/lrpar/src/lib/codegen.rs b/lrpar/src/lib/codegen.rs index 3be5c71b4..1891d111a 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,6 +51,7 @@ const ACTIONS_KIND_HIDDEN: &str = "__GtActionsKindHidden"; #[derive(Debug)] #[non_exhaustive] +/// Errors produced by the parser source environment. pub enum ParserSrcEnvError { GrmtoolsSectionParseError(Vec>), GrmtoolsSectionLookupError(HeaderError), @@ -43,6 +61,7 @@ pub enum ParserSrcEnvError { #[derive(Debug)] #[non_exhaustive] +/// Errors produced by the build environment. pub enum ParserBuildEnvError where LexerTypesT: LexerTypes, @@ -56,6 +75,7 @@ where #[derive(Debug)] #[non_exhaustive] +/// Errors produced during code generation. pub enum CodegenError { ProcMacro2Error(proc_macro2::LexError), InvalidRustIdentifierModName(syn::Error, String), @@ -159,6 +179,7 @@ impl fmt::Display for CodegenError { } } +/// 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, @@ -172,6 +193,7 @@ where phantom: PhantomData, } +/// 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>, @@ -183,6 +205,7 @@ pub struct ParserBuildEnvArgs<'a> { warnings_are_errors: bool, } +/// 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, @@ -199,6 +222,7 @@ where registered_prefixes: HashSet, } +/// Obtained from a [`ParserBuildEnv`], owns everything needed to generate a rust source representation of a parser. pub struct ParserCodegen where LexerTypesT: LexerTypes, @@ -230,27 +254,39 @@ impl<'a> ParserBuildEnvArgs<'a> { 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 } + /// 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 } + + /// Sets the visibility qualifier pub fn visibility(mut self, visibility: Visibility) -> Self { self.visibility = visibility; 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 } + + /// Sets whether warnings should be shown. pub fn show_warnings(mut self, show_warnings: bool) -> Self { self.show_warnings = show_warnings; 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,6 +298,11 @@ where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, { + /// 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>, @@ -295,18 +336,23 @@ where } } + /// 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 } + /// 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>, @@ -328,8 +374,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, @@ -376,6 +421,8 @@ where } } + /// 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>, @@ -412,46 +459,57 @@ where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, { + /// Returns the AST from the build environment. pub fn ast_with_validity_info(&self) -> &ASTWithValidityInfo { &self.ast_with_validity_info } + /// Returns the serialisation format to be used by the generated sources. pub fn serialisation_format(&self) -> &SerialisationFormat { &self.serialisation_format } + /// Returns the `mod_name` that will be used in the generated code. pub fn derived_mod_name(&self) -> &str { &self.mod_name } + /// 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() } + /// Returns the recoverer to be used. pub fn recoverer(&self) -> RecoveryKind { self.recoverer } + /// Returns the rust edition that will be used within the generated code. pub fn rust_edition(&self) -> RustEdition { self.cache_args.rust_edition } + /// Returns the visibility qualifier to be used within the generated code. pub fn visibility(&self) -> &Visibility { &self.cache_args.visibility } + /// Returns whether warnings should be shown. pub fn show_warnings(&self) -> bool { self.cache_args.show_warnings } + /// Returns whether warnings should be treated as errors. pub fn warnings_are_errors(&self) -> bool { self.cache_args.warnings_are_errors } + /// Returns whether conflicts should be treated as errors. pub fn error_on_conflicts(&self) -> bool { self.cache_args.error_on_conflicts } + /// Returns the `YaccKind` of the generated AST. pub fn yacc_kind(&self) -> YaccKind { self.ast_with_validity_info.yacc_kind() } @@ -508,6 +566,8 @@ where Ok(()) } + /// 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, @@ -551,6 +611,7 @@ where &self.sgraph } + /// Takes ownership of self, and returns the `YaccGrammar` it's state graph and table. pub fn finish( self, ) -> ( @@ -561,6 +622,7 @@ where (self.grm, self.sgraph, self.stable) } + /// Generates a rust source `String` representation of the grammar. pub fn generate( &self, build_env: &ParserBuildEnv, From 1a5a362ced93352c678e73abd77e85d5e5ff146d Mon Sep 17 00:00:00 2001 From: matt rice Date: Mon, 30 Nov 2026 22:45:39 -0800 Subject: [PATCH 5/8] Bring lrlex unstable module up to date --- lrlex/src/lib/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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; } From 0fea24b2bf521ed0b5df85a6af664102bba6aaa0 Mon Sep 17 00:00:00 2001 From: matt rice Date: Tue, 1 Dec 2026 02:24:55 -0800 Subject: [PATCH 6/8] Delay the ability to get the AST until after all error checking. Previously you could get an `ASTWithValidityInfo` before calling `ParserBuildEnv::code_generator` where errors in the `ast.grmtools_section` were checked. This patch delays the ability to obtain an `ASTWithValidityInfo` until later. Add a `warnings()` method to `ParserBuildEnv` that returns the ast's warnings, so that you can still handle warnings alongside errors. --- lrpar/src/lib/codegen.rs | 26 +++++++++++++++++--------- lrpar/src/lib/ctbuilder.rs | 6 +++--- nimbleparse/src/main.rs | 7 ++++--- 3 files changed, 24 insertions(+), 15 deletions(-) diff --git a/lrpar/src/lib/codegen.rs b/lrpar/src/lib/codegen.rs index 1891d111a..193576d01 100644 --- a/lrpar/src/lib/codegen.rs +++ b/lrpar/src/lib/codegen.rs @@ -34,6 +34,7 @@ use cfgrammar::{ header::{CFGRAMMAR_KEYS, GrmtoolsSectionParser, Header, HeaderError, HeaderValue, LRPAR_KEYS}, yacc::{ YaccGrammar, YaccGrammarError, YaccKind, YaccOriginalActionKind, ast::ASTWithValidityInfo, + YaccGrammarWarning, }, }; @@ -459,11 +460,6 @@ where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, { - /// Returns the AST from the build environment. - pub fn ast_with_validity_info(&self) -> &ASTWithValidityInfo { - &self.ast_with_validity_info - } - /// Returns the serialisation format to be used by the generated sources. pub fn serialisation_format(&self) -> &SerialisationFormat { &self.serialisation_format @@ -514,6 +510,11 @@ where 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()` @@ -547,13 +548,13 @@ where fn check_unused_grmtools_header_values(&self) -> Result<(), ParserBuildEnvError> { let mut unrecognized_keys = Vec::new(); unrecognized_keys.extend( - self.ast_with_validity_info() + 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() + self.ast_with_validity_info .iter_prefix_keys("lrpar") .filter(|(key, _)| !LRPAR_KEYS.contains(key)) .map(|(s, span)| (s.to_string(), span)), @@ -599,6 +600,11 @@ where + num_traits::Unsigned, LexerTypesT: LexerTypes, { + /// Obtains the AST from the build environment. + pub fn ast_with_validity_info<'a>(&'_ self, build_env: &'a ParserBuildEnv) -> &'a ASTWithValidityInfo { + &build_env.ast_with_validity_info + } + pub(crate) fn grm(&self) -> &YaccGrammar { &self.grm } @@ -1476,9 +1482,11 @@ mod test { .mod_name(Some("test_module")), ) .unwrap(); + + let codegen = build_env.code_generator("").unwrap(); build_env.register_prefix("registered").unwrap(); - let found_prefixes = build_env - .ast_with_validity_info() + let ast_with_validity_info = codegen.ast_with_validity_info(&build_env); + let found_prefixes = ast_with_validity_info .iter_prefixes() .collect::>(); let registered_prefixes = build_env.registered_prefixes().collect::>(); diff --git a/lrpar/src/lib/ctbuilder.rs b/lrpar/src/lib/ctbuilder.rs index 5892f2109..9600e15b6 100644 --- a/lrpar/src/lib/ctbuilder.rs +++ b/lrpar/src/lib/ctbuilder.rs @@ -553,7 +553,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!( @@ -668,7 +668,7 @@ where _ => { let conflicts_diagnostic = yacc_diag.format_conflicts::( grm, - build_env.ast_with_validity_info().ast(), + code_gen.ast_with_validity_info(&build_env).ast(), c, code_gen.sgraph(), stable, @@ -693,7 +693,7 @@ where rt }; inspector_rt( - build_env.ast_with_validity_info().header(), + code_gen.ast_with_validity_info(&build_env).header(), rt, &rule_ids, grmp, diff --git a/nimbleparse/src/main.rs b/nimbleparse/src/main.rs index e07ad7c75..a8f8f2a9a 100644 --- a/nimbleparse/src/main.rs +++ b/nimbleparse/src/main.rs @@ -241,8 +241,7 @@ fn main() { 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 warnings = build_env.warnings(); let codegen = build_env.code_generator(""); if let Err(e) = &codegen { match e { @@ -276,13 +275,15 @@ fn main() { } process::exit(1); } + let codegen = codegen.unwrap(); + let ast_validation = &codegen.ast_with_validity_info(&build_env); 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(); + let (grm, sgraph, stable) = codegen.finish(); if dump_state_graph { println!("Stategraph:\n{}\n", sgraph.pp_core_states(&grm)); } From d5d4b6f5c5c5a26f0226b45d55d971d23a20cbbe Mon Sep 17 00:00:00 2001 From: matt rice Date: Tue, 1 Dec 2026 04:21:47 -0800 Subject: [PATCH 7/8] Move error check so it happens earlier --- lrpar/src/lib/codegen.rs | 95 ++++++++++++++++++-------------------- lrpar/src/lib/ctbuilder.rs | 14 +++++- nimbleparse/src/main.rs | 20 ++++---- 3 files changed, 68 insertions(+), 61 deletions(-) diff --git a/lrpar/src/lib/codegen.rs b/lrpar/src/lib/codegen.rs index 193576d01..d61b63a44 100644 --- a/lrpar/src/lib/codegen.rs +++ b/lrpar/src/lib/codegen.rs @@ -33,8 +33,8 @@ use cfgrammar::{ RIdx, Span, Symbol, header::{CFGRAMMAR_KEYS, GrmtoolsSectionParser, Header, HeaderError, HeaderValue, LRPAR_KEYS}, yacc::{ - YaccGrammar, YaccGrammarError, YaccKind, YaccOriginalActionKind, ast::ASTWithValidityInfo, - YaccGrammarWarning, + YaccGrammar, YaccGrammarError, YaccGrammarWarning, YaccKind, YaccOriginalActionKind, + ast::ASTWithValidityInfo, }, }; @@ -56,6 +56,7 @@ const ACTIONS_KIND_HIDDEN: &str = "__GtActionsKindHidden"; pub enum ParserSrcEnvError { GrmtoolsSectionParseError(Vec>), GrmtoolsSectionLookupError(HeaderError), + GrmtoolsSectionUnusedKeys(Vec<(String, Span)>), MissingYaccKind, MissingModName, } @@ -70,7 +71,6 @@ where { StateTableError(StateTableError), YaccGrammarErrors(Vec), - GrmtoolsSectionUnusedKeys(Vec<(String, Span)>), DuplicatePrefixRegistrationError(String), } @@ -137,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(), }) @@ -156,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}\"") } @@ -422,6 +422,33 @@ where } } + /// 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, + 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( @@ -435,6 +462,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)?; @@ -460,6 +488,11 @@ where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, { + /// Returns the AST from the build environment. + pub fn ast_with_validity_info(&self) -> &ASTWithValidityInfo { + &self.ast_with_validity_info + } + /// Returns the serialisation format to be used by the generated sources. pub fn serialisation_format(&self) -> &SerialisationFormat { &self.serialisation_format @@ -543,37 +576,12 @@ where 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(()) - } - /// 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, )?; @@ -600,11 +608,6 @@ where + num_traits::Unsigned, LexerTypesT: LexerTypes, { - /// Obtains the AST from the build environment. - pub fn ast_with_validity_info<'a>(&'_ self, build_env: &'a ParserBuildEnv) -> &'a ASTWithValidityInfo { - &build_env.ast_with_validity_info - } - pub(crate) fn grm(&self) -> &YaccGrammar { &self.grm } @@ -1440,14 +1443,10 @@ mod test { "#; let src_env = ParserSrcEnv::::new(src, None, crate::unstable_api::UnstableApi); - let build_env = src_env - .build_env( - ParserBuildEnvArgs::new(crate::unstable_api::UnstableApi) - .mod_name(Some("test_module")), - ) - .unwrap(); - match build_env.code_generator("timestamp") { - Err(ParserBuildEnvError::GrmtoolsSectionUnusedKeys(keys)) => { + match src_env.build_env( + ParserBuildEnvArgs::new(crate::unstable_api::UnstableApi).mod_name(Some("test_module")), + ) { + Err(ParserSrcEnvError::GrmtoolsSectionUnusedKeys(keys)) => { assert_eq!( &keys, &[ @@ -1482,11 +1481,9 @@ mod test { .mod_name(Some("test_module")), ) .unwrap(); - - let codegen = build_env.code_generator("").unwrap(); build_env.register_prefix("registered").unwrap(); - let ast_with_validity_info = codegen.ast_with_validity_info(&build_env); - let found_prefixes = ast_with_validity_info + let found_prefixes = build_env + .ast_with_validity_info() .iter_prefixes() .collect::>(); let registered_prefixes = build_env.registered_prefixes().collect::>(); diff --git a/lrpar/src/lib/ctbuilder.rs b/lrpar/src/lib/ctbuilder.rs index 9600e15b6..4959dc49a 100644 --- a/lrpar/src/lib/ctbuilder.rs +++ b/lrpar/src/lib/ctbuilder.rs @@ -546,6 +546,16 @@ 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 @@ -668,7 +678,7 @@ where _ => { let conflicts_diagnostic = yacc_diag.format_conflicts::( grm, - code_gen.ast_with_validity_info(&build_env).ast(), + build_env.ast_with_validity_info().ast(), c, code_gen.sgraph(), stable, @@ -693,7 +703,7 @@ where rt }; inspector_rt( - code_gen.ast_with_validity_info(&build_env).header(), + build_env.ast_with_validity_info().header(), rt, &rule_ids, grmp, diff --git a/nimbleparse/src/main.rs b/nimbleparse/src/main.rs index a8f8f2a9a..90886de0e 100644 --- a/nimbleparse/src/main.rs +++ b/nimbleparse/src/main.rs @@ -233,6 +233,15 @@ fn main() { ); } } + e @ ParserSrcEnvError::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(), '^') + ); + } + } e => { eprintln!("{}", e); } @@ -260,15 +269,6 @@ fn main() { } } } - 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(), '^') - ); - } - } e => { eprintln!("{}", e); } @@ -276,7 +276,7 @@ fn main() { process::exit(1); } let codegen = codegen.unwrap(); - let ast_validation = &codegen.ast_with_validity_info(&build_env); + 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 { From ff63cdace0bc5d684d9901a30d463245bcca107e Mon Sep 17 00:00:00 2001 From: matt rice Date: Wed, 2 Dec 2026 01:10:26 -0800 Subject: [PATCH 8/8] Update comment to reflect current state. --- lrpar/src/lib/codegen.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lrpar/src/lib/codegen.rs b/lrpar/src/lib/codegen.rs index d61b63a44..a7d65f2b7 100644 --- a/lrpar/src/lib/codegen.rs +++ b/lrpar/src/lib/codegen.rs @@ -422,8 +422,7 @@ where } } - /// 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. + /// 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,