From 4fbb042efff3316530b117b335be4af7d6292205 Mon Sep 17 00:00:00 2001 From: matt rice Date: Sun, 29 Nov 2026 03:26:17 -0800 Subject: [PATCH 1/6] Make codegen public --- lrpar/src/lib/codegen.rs | 71 ++++++++++++++++++++-------------------- lrpar/src/lib/mod.rs | 2 +- 2 files changed, 36 insertions(+), 37 deletions(-) diff --git a/lrpar/src/lib/codegen.rs b/lrpar/src/lib/codegen.rs index 19278c4d1..00575637b 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() -> 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,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 +291,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 +372,7 @@ where } } - pub(crate) fn build_env( + pub fn build_env( mut self, args: ParserBuildEnvArgs<'a>, ) -> Result, ParserSrcEnvError> @@ -408,47 +408,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 +462,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 +476,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 +504,7 @@ where Ok(()) } - pub(crate) fn code_generator( + pub fn code_generator( &self, timestamp: &str, ) -> Result, ParserBuildEnvError> { @@ -548,7 +547,7 @@ where &self.sgraph } - pub(crate) fn finish( + pub fn finish( self, ) -> ( YaccGrammar, @@ -558,7 +557,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; From beb59398ebe073ad0cbaeb3ecaf83e28be5617c3 Mon Sep 17 00:00:00 2001 From: matt rice Date: Sun, 29 Nov 2026 03:28:57 -0800 Subject: [PATCH 2/6] Unhide parts of the header module. This leaves `Value`, `HeaderError`, and `HeaderErrorKind` publicly visible. --- cfgrammar/src/lib/header.rs | 8 ++++++-- cfgrammar/src/lib/mod.rs | 4 ++-- 2 files changed, 8 insertions(+), 4 deletions(-) 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..9874f279e 100644 --- a/cfgrammar/src/lib/mod.rs +++ b/cfgrammar/src/lib/mod.rs @@ -56,9 +56,9 @@ use serde::{Deserialize, Serialize}; #[cfg(feature = "wincode")] use wincode::{SchemaRead, SchemaWrite}; -#[doc(hidden)] -pub mod header; + mod idxnewtype; +pub mod header; pub mod newlinecache; pub mod span; pub mod yacc; From e1b0141cc482d6ab822128a56385267b6f0accad Mon Sep 17 00:00:00 2001 From: matt rice Date: Sun, 29 Nov 2026 03:26:31 -0800 Subject: [PATCH 3/6] Replace nimbleparse usage of hidden api with codegen. --- nimbleparse/src/main.rs | 190 ++++++++++++++-------------------------- 1 file changed, 67 insertions(+), 123 deletions(-) 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, _) => { From e567d49a81b8825bc304243ae6640c753af8a90d Mon Sep 17 00:00:00 2001 From: matt rice Date: Sun, 29 Nov 2026 04:48:59 -0800 Subject: [PATCH 4/6] rustfmt --- cfgrammar/src/lib/mod.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cfgrammar/src/lib/mod.rs b/cfgrammar/src/lib/mod.rs index 9874f279e..dd563cd93 100644 --- a/cfgrammar/src/lib/mod.rs +++ b/cfgrammar/src/lib/mod.rs @@ -56,9 +56,8 @@ use serde::{Deserialize, Serialize}; #[cfg(feature = "wincode")] use wincode::{SchemaRead, SchemaWrite}; - -mod idxnewtype; pub mod header; +mod idxnewtype; pub mod newlinecache; pub mod span; pub mod yacc; From adbb9b7afab8116ac08b353daad5dd6b82626335 Mon Sep 17 00:00:00 2001 From: matt rice Date: Sun, 29 Nov 2026 04:49:26 -0800 Subject: [PATCH 5/6] initial attempt at Struct docs for codegen --- lrpar/src/lib/codegen.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/lrpar/src/lib/codegen.rs b/lrpar/src/lib/codegen.rs index 00575637b..4cf5dfe14 100644 --- a/lrpar/src/lib/codegen.rs +++ b/lrpar/src/lib/codegen.rs @@ -34,6 +34,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 +44,7 @@ pub enum ParserSrcEnvError { #[derive(Debug)] #[non_exhaustive] +/// Errors produced by the build environment. pub enum ParserBuildEnvError where LexerTypesT: LexerTypes, @@ -56,6 +58,7 @@ where #[derive(Debug)] #[non_exhaustive] +/// Errors produced during code generation. pub enum CodegenError { ProcMacro2Error(proc_macro2::LexError), InvalidRustIdentifierModName(syn::Error, String), @@ -159,6 +162,19 @@ impl fmt::Display for CodegenError { } } +/// A Parser source environment is the first step in a *Sans-I/O* interface to source code generation. +/// +/// Typically users of cargo will want to prefer the simpler `CTParserBuilder` interface. +/// +/// `ParserSrcEnv`` takes grammar source as a `String` it begins the process of code generation, +/// by parsing the `%grmtools` header out of the grammar. Some of the fields +/// in the grmtools section may be specified explicitly outside of the grammar source, +/// by builder methods. +/// +/// Options to the parser source environment affect grammar construction and anything required +/// to build a GrammarAST from grammar source . +/// +/// From a parser source environment, you can obtain a parser build environment pub struct ParserSrcEnv<'a, LexerTypesT> where LexerTypesT: LexerTypes, @@ -172,6 +188,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 +200,10 @@ pub struct ParserBuildEnvArgs<'a> { warnings_are_errors: bool, } +/// A Parser build environment is obtained from a `ParserSrcEnv` as the second step the code generation process. +/// +/// It owns the AST built from the source envrironment, and collects arguments that affect source code generation. +/// From a build environment, you can obtain a code generator. pub struct ParserBuildEnv<'a, LexerTypesT> where LexerTypesT: LexerTypes, @@ -199,6 +220,10 @@ where registered_prefixes: HashSet, } +/// A Parser code generator is obtained from a `ParserBuildEnv` as the last step in the code generation process. +/// +/// It owns a grammar built from the AST, and everything needed to construct a source code +/// representation of the grammar. pub struct ParserCodegen where LexerTypesT: LexerTypes, From a43306584e531c1503b6857d04b41ef8c4989903 Mon Sep 17 00:00:00 2001 From: matt rice Date: Sun, 29 Nov 2026 08:23:18 -0800 Subject: [PATCH 6/6] Second pass at lrpar::codegen docs --- lrpar/src/lib/codegen.rs | 41 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/lrpar/src/lib/codegen.rs b/lrpar/src/lib/codegen.rs index 4cf5dfe14..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, @@ -162,19 +179,7 @@ impl fmt::Display for CodegenError { } } -/// A Parser source environment is the first step in a *Sans-I/O* interface to source code generation. -/// -/// Typically users of cargo will want to prefer the simpler `CTParserBuilder` interface. -/// -/// `ParserSrcEnv`` takes grammar source as a `String` it begins the process of code generation, -/// by parsing the `%grmtools` header out of the grammar. Some of the fields -/// in the grmtools section may be specified explicitly outside of the grammar source, -/// by builder methods. -/// -/// Options to the parser source environment affect grammar construction and anything required -/// to build a GrammarAST from grammar source . -/// -/// From a parser source environment, you can obtain a parser build environment +/// 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, @@ -200,10 +205,7 @@ pub struct ParserBuildEnvArgs<'a> { warnings_are_errors: bool, } -/// A Parser build environment is obtained from a `ParserSrcEnv` as the second step the code generation process. -/// -/// It owns the AST built from the source envrironment, and collects arguments that affect source code generation. -/// From a build environment, you can obtain a code generator. +/// 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, @@ -220,10 +222,7 @@ where registered_prefixes: HashSet, } -/// A Parser code generator is obtained from a `ParserBuildEnv` as the last step in the code generation process. -/// -/// It owns a grammar built from the AST, and everything needed to construct a source code -/// representation of the grammar. +/// Obtained from a [`ParserBuildEnv`], owns everything needed to generate a rust source representation of a parser. pub struct ParserCodegen where LexerTypesT: LexerTypes,