Skip to main content

Grammar

Struct Grammar 

Source
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 output

The library fully supports Unicode throughout all operations, including Unicode characters in terminals, nonterminals, input strings, and generated output.

Implementations§

Source§

impl Grammar

Source

pub const fn new() -> Grammar

Construct a new Grammar

Source

pub const fn from_parts(v: Vec<Production>) -> Grammar

Construct a Grammar from Productions

Source

pub fn parse_from<F: Format>(input: &str) -> Result<Self, Error>

parse a grammar given a format

Source

pub fn add_production(&mut self, prod: Production)

Add Production to the Grammar

Source

pub fn remove_production(&mut self, prod: &Production) -> Option<Production>

Remove Production from the Grammar

Source

pub fn productions_iter(&self) -> impl Iterator<Item = &Production>

Get iterator of the Grammar’s Productions

Source

pub fn productions_iter_mut(&mut self) -> impl Iterator<Item = &mut Production>

Get mutable iterator of the Grammar’s Productions

Source

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.

Source

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();
Source

pub 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

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();
Source

pub 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

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();
Source

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)
}
Source

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.

Source

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.

Source

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.

Source

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)
}
Source

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 Clone for Grammar

Source§

fn clone(&self) -> Grammar

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Grammar

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Grammar

Source§

fn default() -> Grammar

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Grammar

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Grammar

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl FromStr for Grammar

Source§

type Err = Error

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for Grammar

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Grammar

Source§

fn eq(&self, other: &Grammar) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Grammar

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for Grammar

Source§

impl StructuralPartialEq for Grammar

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,