Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions cfgrammar/src/lib/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T> {
pub kind: HeaderErrorKind,
pub locations: Vec<T>,
Expand Down Expand Up @@ -59,7 +58,6 @@ pub struct HeaderValue<T>(pub T, pub Value<T>);

#[derive(Debug, Eq, PartialEq, Clone)]
#[non_exhaustive]
#[doc(hidden)]
pub enum HeaderErrorKind {
MissingGrmtoolsSection,
IllegalName,
Expand Down Expand Up @@ -195,8 +193,10 @@ impl<T> HeaderError<T> {
}
}

#[doc(hidden)]
static RE_LEADING_WS: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^[\p{Pattern_White_Space}]*").unwrap());
#[doc(hidden)]
static RE_NAME: LazyLock<Regex> = LazyLock::new(|| {
RegexBuilder::new(r"^[A-Z][A-Z_\.]*")
.case_insensitive(true)
Expand All @@ -210,7 +210,9 @@ pub static RE_CRATE_DOT: LazyLock<Regex> = LazyLock::new(|| {
.build()
.unwrap()
});
#[doc(hidden)]
static RE_DIGITS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[0-9]+").unwrap());
#[doc(hidden)]
static RE_STRING: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"^\"(\\.|[^"\\])*\""#).unwrap());
#[doc(hidden)]
pub static KEY_CRATE_MAP: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
Expand Down Expand Up @@ -284,8 +286,10 @@ pub static REGEX_KEYS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
])
});

#[doc(hidden)]
const MAGIC: &str = "%grmtools";

#[doc(hidden)]
fn add_duplicate_occurrence<T: Eq + PartialEq + Clone>(
errs: &mut Vec<HeaderError<T>>,
kind: HeaderErrorKind,
Expand Down
1 change: 0 additions & 1 deletion cfgrammar/src/lib/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ use serde::{Deserialize, Serialize};
#[cfg(feature = "wincode")]
use wincode::{SchemaRead, SchemaWrite};

#[doc(hidden)]
pub mod header;
mod idxnewtype;
pub mod newlinecache;
Expand Down
95 changes: 59 additions & 36 deletions lrpar/src/lib/codegen.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -34,7 +51,8 @@ const ACTIONS_KIND_HIDDEN: &str = "__GtActionsKindHidden";

#[derive(Debug)]
#[non_exhaustive]
pub(crate) enum ParserSrcEnvError {
/// Errors produced by the parser source environment.
pub enum ParserSrcEnvError {
GrmtoolsSectionParseError(Vec<HeaderError<Span>>),
GrmtoolsSectionLookupError(HeaderError<Span>),
MissingYaccKind,
Expand All @@ -43,7 +61,8 @@ pub(crate) enum ParserSrcEnvError {

#[derive(Debug)]
#[non_exhaustive]
pub(crate) enum ParserBuildEnvError<LexerTypesT>
/// Errors produced by the build environment.
pub enum ParserBuildEnvError<LexerTypesT>
where
LexerTypesT: LexerTypes,
usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
Expand All @@ -56,7 +75,8 @@ where

#[derive(Debug)]
#[non_exhaustive]
pub(crate) enum CodegenError {
/// Errors produced during code generation.
pub enum CodegenError {
ProcMacro2Error(proc_macro2::LexError),
InvalidRustIdentifierModName(syn::Error, String),
InvalidParseGenerics(syn::Error),
Expand Down Expand Up @@ -159,7 +179,8 @@ impl fmt::Display for CodegenError {
}
}

pub(crate) struct ParserSrcEnv<'a, LexerTypesT>
/// A parser source environment owns a grammars source string, and collects args needed to generate an AST.
pub struct ParserSrcEnv<'a, LexerTypesT>
where
LexerTypesT: LexerTypes,
usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
Expand All @@ -172,7 +193,8 @@ where
phantom: PhantomData<LexerTypesT::StorageT>,
}

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<String>,
Expand All @@ -183,7 +205,8 @@ pub(crate) struct ParserBuildEnvArgs<'a> {
warnings_are_errors: bool,
}

pub(crate) struct ParserBuildEnv<'a, LexerTypesT>
/// Owns an AST generated from a [`ParserSrcEnv`] and collects arguments relevant to grammar construction and code generation.
pub struct ParserBuildEnv<'a, LexerTypesT>
where
LexerTypesT: LexerTypes,
usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
Expand All @@ -199,7 +222,8 @@ where
registered_prefixes: HashSet<String>,
}

pub(crate) struct ParserCodegen<LexerTypesT>
/// Obtained from a [`ParserBuildEnv`], owns everything needed to generate a rust source representation of a parser.
pub struct ParserCodegen<LexerTypesT>
where
LexerTypesT: LexerTypes,
usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
Expand All @@ -211,7 +235,7 @@ where
}

impl<'a> ParserBuildEnvArgs<'a> {
pub(crate) fn new() -> Self {
pub fn new() -> Self {
ParserBuildEnvArgs {
ast_with_validity_info: None,
mod_name: None,
Expand All @@ -225,33 +249,33 @@ impl<'a> ParserBuildEnvArgs<'a> {

/// Set this to `Some(ast)` if the the parser should be built from a pre-parsed AST
/// instead of from parsing a source string.
pub(crate) fn ast_with_validity_info(mut self, ast: Option<&'a ASTWithValidityInfo>) -> Self {
pub fn ast_with_validity_info(mut self, ast: Option<&'a ASTWithValidityInfo>) -> Self {
self.ast_with_validity_info = ast;
self
}

pub(crate) fn mod_name(mut self, mod_name: Option<&str>) -> Self {
pub fn mod_name(mut self, mod_name: Option<&str>) -> Self {
self.mod_name = mod_name.map(|s| s.to_string());
self
}

pub(crate) fn rust_edition(mut self, rust_edition: RustEdition) -> Self {
pub fn rust_edition(mut self, rust_edition: RustEdition) -> Self {
self.rust_edition = rust_edition;
self
}
pub(crate) fn visibility(mut self, visibility: Visibility) -> Self {
pub fn visibility(mut self, visibility: Visibility) -> Self {
self.visibility = visibility;
self
}
pub(crate) fn error_on_conflicts(mut self, error_on_conflicts: bool) -> Self {
pub fn error_on_conflicts(mut self, error_on_conflicts: bool) -> Self {
self.error_on_conflicts = error_on_conflicts;
self
}
pub(crate) fn show_warnings(mut self, show_warnings: bool) -> Self {
pub fn show_warnings(mut self, show_warnings: bool) -> Self {
self.show_warnings = show_warnings;
self
}
pub(crate) fn warnings_are_errors(mut self, warnings_are_errors: bool) -> Self {
pub fn warnings_are_errors(mut self, warnings_are_errors: bool) -> Self {
self.warnings_are_errors = warnings_are_errors;
self
}
Expand All @@ -262,7 +286,7 @@ where
LexerTypesT: LexerTypes,
usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
{
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
Expand Down Expand Up @@ -291,12 +315,12 @@ where
}
}

pub(crate) fn yacckind(mut self, yacckind: Option<YaccKind>) -> Self {
pub fn yacckind(mut self, yacckind: Option<YaccKind>) -> Self {
self.yacckind = yacckind;
self
}

pub(crate) fn recoverer(mut self, recoverykind: Option<RecoveryKind>) -> Self {
pub fn recoverer(mut self, recoverykind: Option<RecoveryKind>) -> Self {
self.recoverer = recoverykind;
self
}
Expand Down Expand Up @@ -372,7 +396,7 @@ where
}
}

pub(crate) fn build_env(
pub fn build_env(
mut self,
args: ParserBuildEnvArgs<'a>,
) -> Result<ParserBuildEnv<'a, LexerTypesT>, ParserSrcEnvError>
Expand Down Expand Up @@ -408,47 +432,47 @@ where
LexerTypesT: LexerTypes,
usize: num_traits::AsPrimitive<LexerTypesT::StorageT>,
{
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()
}

Expand All @@ -462,7 +486,7 @@ where
/// let registered_set = HashSet::from_iter(build_env.registered_header_prefixes());
/// assert!(prefixes_set.difference(registered_set).next().is_none())
/// ```
pub(crate) fn register_prefix(
pub fn register_prefix(
&mut self,
crate_prefix: &str,
) -> Result<(), ParserBuildEnvError<LexerTypesT>> {
Expand All @@ -476,8 +500,7 @@ where
}

/// Returns the unique set of key prefixes that have been registered by calling `register_header_prefix`.
#[allow(unused)]
pub(crate) fn registered_prefixes(&self) -> impl Iterator<Item = &str> {
pub fn registered_prefixes(&self) -> impl Iterator<Item = &str> {
self.registered_prefixes.iter().map(|s| s.as_str())
}

Expand Down Expand Up @@ -505,7 +528,7 @@ where
Ok(())
}

pub(crate) fn code_generator(
pub fn code_generator(
&self,
timestamp: &str,
) -> Result<ParserCodegen<LexerTypesT>, ParserBuildEnvError<LexerTypesT>> {
Expand Down Expand Up @@ -548,7 +571,7 @@ where
&self.sgraph
}

pub(crate) fn finish(
pub fn finish(
self,
) -> (
YaccGrammar<LexerTypesT::StorageT>,
Expand All @@ -558,7 +581,7 @@ where
(self.grm, self.sgraph, self.stable)
}

pub(crate) fn generate(
pub fn generate(
&self,
build_env: &ParserBuildEnv<LexerTypesT>,
) -> Result<String, CodegenError> {
Expand Down
2 changes: 1 addition & 1 deletion lrpar/src/lib/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ pub mod lex_api;
#[doc(hidden)]
pub mod parser;

mod codegen;
pub mod codegen;

#[cfg(test)]
pub mod test_utils;
Expand Down
Loading