pub struct Grammar { /* private fields */ }Expand description
A Grammar is comprised of any number of Productions.
When parsing from text (e.g. str::parse or Grammar::parse_from), extended
syntax such as (A / B) and [A] is accepted and normalized into additional
named nonterminals (e.g. __anon0), so that the resulting grammar uses only
Term::Terminal and Term::Nonterminal.
§Normalization (before and after)
Input text may use parentheses and brackets; the stored grammar is always in normalized form (plain nonterminals and terminals only). Formatting the grammar back to a string shows the normalized form:
use bnf::Grammar;
// Before: extended syntax in the input string
let input = r#"<s> ::= (<a> | <b>) [<c>]
<a> ::= 'a'
<b> ::= 'b'
<c> ::= 'c'"#;
let grammar: Grammar = input.parse().unwrap();
// After: normalization replaces ( ) and [ ] with __anon* nonterminals
let normalized = format!("{}", grammar);
assert!(normalized.contains("__anon"));
assert!(!normalized.contains('(')); // no groups in output
assert!(!normalized.contains('[')); // no optionals in outputThe library fully supports Unicode throughout all operations, including Unicode characters in terminals, nonterminals, input strings, and generated output.
Implementations§
Source§impl Grammar
impl Grammar
Sourcepub const fn from_parts(v: Vec<Production>) -> Grammar
pub const fn from_parts(v: Vec<Production>) -> Grammar
Construct a Grammar from Productions
Sourcepub fn parse_from<F: Format>(input: &str) -> Result<Self, Error>
pub fn parse_from<F: Format>(input: &str) -> Result<Self, Error>
parse a grammar given a format
Sourcepub fn add_production(&mut self, prod: Production)
pub fn add_production(&mut self, prod: Production)
Add Production to the Grammar
Sourcepub fn remove_production(&mut self, prod: &Production) -> Option<Production>
pub fn remove_production(&mut self, prod: &Production) -> Option<Production>
Remove Production from the Grammar
Sourcepub fn productions_iter(&self) -> impl Iterator<Item = &Production>
pub fn productions_iter(&self) -> impl Iterator<Item = &Production>
Get iterator of the Grammar’s Productions
Sourcepub fn productions_iter_mut(&mut self) -> impl Iterator<Item = &mut Production>
pub fn productions_iter_mut(&mut self) -> impl Iterator<Item = &mut Production>
Get mutable iterator of the Grammar’s Productions
Sourcepub fn validate(&self) -> Result<(), Error>
pub fn validate(&self) -> Result<(), Error>
Validate the Grammar has no undefined nonterminals
No need to call this method before building a parser, as the parser will validate the grammar at construction time.
§Errors
Returns Error::ValidationError if the grammar has no productions or has undefined nonterminals.
Sourcepub fn build_parser(&self) -> Result<GrammarParser<'_>, Error>
pub fn build_parser(&self) -> Result<GrammarParser<'_>, Error>
Build a reusable parser from this grammar, validating that all nonterminals are defined.
This method validates the grammar and creates a crate::GrammarParser that can be
reused to parse multiple input strings efficiently.
§Errors
Returns Error::ValidationError if any nonterminal used in the RHS of
productions lacks a definition in the grammar, or if the grammar has no productions.
§Example
use bnf::Grammar;
let grammar: Grammar = "<dna> ::= <base> | <base> <dna>
<base> ::= 'A' | 'C' | 'G' | 'T'"
.parse()
.unwrap();
let parser = grammar.build_parser()?;
let parse_trees: Vec<_> = parser.parse_input("GATTACA").collect();Sourcepub fn parse_input<'gram>(
&'gram self,
input: &'gram str,
) -> impl Iterator<Item = ParseTree<'gram>>
👎Deprecated since 0.6.0: Use Grammar::build_parser() and GrammarParser::parse_input() instead for validation and reusability
pub fn parse_input<'gram>( &'gram self, input: &'gram str, ) -> impl Iterator<Item = ParseTree<'gram>>
Parse input strings according to Grammar
§Deprecated
This method is deprecated. Use crate::GrammarParser instead, which validates
all nonterminals at construction time and allows reusing the parser for
multiple inputs.
let parser = grammar.build_parser()?;
let parse_trees: Vec<_> = parser.parse_input("input").collect();Sourcepub fn parse_input_starting_with<'gram>(
&'gram self,
input: &'gram str,
starting_term: &'gram Term,
) -> impl Iterator<Item = ParseTree<'gram>>
👎Deprecated since 0.6.0: Use Grammar::build_parser() and GrammarParser::parse_input_starting_with() instead for validation and reusability
pub fn parse_input_starting_with<'gram>( &'gram self, input: &'gram str, starting_term: &'gram Term, ) -> impl Iterator<Item = ParseTree<'gram>>
Parse input strings according to Grammar, starting with given production
§Deprecated
This method is deprecated. Use crate::GrammarParser instead, which validates
all nonterminals at construction time and allows reusing the parser for
multiple inputs.
let parser = grammar.build_parser()?;
let start = Term::Nonterminal("dna".to_string());
let parse_trees: Vec<_> = parser.parse_input_starting_with("input", &start).collect();Sourcepub fn generate_seeded(&self, rng: &mut StdRng) -> Result<String, Error>
pub fn generate_seeded(&self, rng: &mut StdRng) -> Result<String, Error>
Generate a random sentence from self and seed for random. Use if interested in reproducing the output generated. Begins from lhs of first production.
§Random Number Generation
This method uses the provided RNG for random number generation. The cryptographic
security of the generated sentences depends entirely on the RNG implementation
provided by the caller. For cryptographically secure generation, use a secure
RNG like StdRng from the rand crate. For deterministic output for testing
or reproducibility, use any seedable RNG with a fixed seed.
§Example
use bnf::rand::{SeedableRng, rngs::StdRng};
use bnf::Grammar;
let input =
"<dna> ::= <base> | <base> <dna>
<base> ::= 'A' | 'C' | 'G' | 'T'";
let grammar: Grammar = input.parse().unwrap();
let seed: [u8; 32] = [0; 32];
let mut rng: StdRng = SeedableRng::from_seed(seed);
let sentence = grammar.generate_seeded(&mut rng);
match sentence {
Ok(s) => println!("random sentence: {}", s),
Err(e) => println!("something went wrong: {}!", e)
}
Sourcepub fn generate_seeded_callback(
&self,
rng: &mut StdRng,
f: impl Fn(&str, &str) -> bool,
) -> Result<String, Error>
pub fn generate_seeded_callback( &self, rng: &mut StdRng, f: impl Fn(&str, &str) -> bool, ) -> Result<String, Error>
Does the same as Grammar::generate_seeded, except it takes a callback which is
executed on every production that is generated to check if it is okay.
When the callback returns true, the generation continues as normal,
but when the callback returns false, a new random option is tried.
§Random Number Generation
This method uses the provided RNG for random number generation. The cryptographic
security of the generated sentences depends entirely on the RNG implementation
provided by the caller. For cryptographically secure generation, use a secure
RNG like StdRng from the rand crate. For deterministic output for testing
or reproducibility, use any seedable RNG with a fixed seed.
The first parameter to the callback is the current production name, and the second parameter is the value that was attempted to be generated, but may be rejected.
Sourcepub fn generate_seeded_with_strategy<S: GenerationStrategy>(
&self,
strategy: &mut S,
) -> Result<String, Error>
pub fn generate_seeded_with_strategy<S: GenerationStrategy>( &self, strategy: &mut S, ) -> Result<String, Error>
Generate a random sentence using the given strategy.
Same preconditions as Grammar::generate_seeded; uses the provided
GenerationStrategy to choose which production expression to expand at each step.
Sourcepub fn generate_seeded_callback_with_strategy<S: GenerationStrategy>(
&self,
f: impl Fn(&str, &str) -> bool,
strategy: &mut S,
) -> Result<String, Error>
pub fn generate_seeded_callback_with_strategy<S: GenerationStrategy>( &self, f: impl Fn(&str, &str) -> bool, strategy: &mut S, ) -> Result<String, Error>
Generate a random sentence with a callback and strategy.
Same as Grammar::generate_seeded_callback, but uses the given
GenerationStrategy instead of uniform random choice.
Sourcepub fn generate(&self) -> Result<String, Error>
pub fn generate(&self) -> Result<String, Error>
Generate a random sentence from self. Begins from lhs of first production.
§Example
use bnf::Grammar;
let input =
"<dna> ::= <base> | <base> <dna>
<base> ::= 'A' | 'C' | 'G' | 'T'";
let grammar: Grammar = input.parse().unwrap();
let sentence = grammar.generate();
match sentence {
Ok(s) => println!("random sentence: {}", s),
Err(e) => println!("something went wrong: {}!", e)
}
Sourcepub fn generate_callback(
&self,
f: impl Fn(&str, &str) -> bool,
) -> Result<String, Error>
pub fn generate_callback( &self, f: impl Fn(&str, &str) -> bool, ) -> Result<String, Error>
Does the same as Grammar::generate, except it takes a callback which is
executed on every production that is generated to check if it is okay.
When the callback returns true, the generation continues as normal,
but when the callback returns false, a new random option is tried.
§Random Number Generation
This method uses the system’s default random number generator. The cryptographic
security of the generated sentences depends on the system’s RNG implementation.
For applications requiring cryptographically secure generation, consider using
Grammar::generate_seeded_callback with a secure RNG like StdRng from the rand crate.
The first parameter to the callback is the current production name, and the second parameter is the value that was attempted to be generated, but may be rejected.
Trait Implementations§
Source§impl<'de> Deserialize<'de> for Grammar
impl<'de> Deserialize<'de> for Grammar
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
impl Eq for Grammar
impl StructuralPartialEq for Grammar
Auto Trait Implementations§
impl Freeze for Grammar
impl RefUnwindSafe for Grammar
impl Send for Grammar
impl Sync for Grammar
impl Unpin for Grammar
impl UnwindSafe for Grammar
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.