Trait arithmetic_parser::grammars::Grammar
source · pub trait Grammar: ParseLiteral {
type Type<'a>: 'a + Clone + Debug;
// Required method
fn parse_type(input: InputSpan<'_>) -> NomResult<'_, 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<'a> = 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 = "
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§
Object Safety§
This trait is not object safe.