pub trait Grammar<'a>: ParseLiteral {
type Type: Clone + Debug;
// Required method
fn parse_type(input: InputSpan<'a>) -> NomResult<'a, Self::Type>;
}
Expand description
Extension of ParseLiteral
that parses type annotations.
§Examples
Use a Typed
wrapper to create a parser from the grammar, which will support all
parsing Features
:
/// Grammar that parses `u64` numbers and has a single type annotation, `Num`.
#[derive(Debug)]
struct IntegerGrammar;
impl ParseLiteral for IntegerGrammar {
type Lit = u64;
fn parse_literal(input: InputSpan<'_>) -> NomResult<'_, Self::Lit> {
use nom::{character::complete::digit1, combinator::map_res};
let parser = |s: InputSpan<'_>| {
s.fragment().parse().map_err(ErrorKind::literal)
};
map_res(digit1, parser)(input)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Num;
impl Grammar<'_> for IntegerGrammar {
type Type = Num;
fn parse_type(input: InputSpan<'_>) -> NomResult<'_, Self::Type> {
use nom::{bytes::complete::tag, combinator::map};
map(tag("Num"), |_| Num)(input)
}
}
// Here's how a grammar can be used.
let program = r#"
x = 1 + 2 * 3 + sin(a^3 / b^2);
some_function = |a, b: Num| (a + b, a - b);
other_function = |x| {
r = min(rand(), 0);
r * x
};
(y, z: Num) = some_function({ x = x - 1; x }, x);
other_function(y - z)
"#;
let parsed = Typed::<IntegerGrammar>::parse_statements(program)?;
println!("{:#?}", parsed);
Required Associated Types§
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.