Trait arithmetic_parser::grammars::Grammar[][src]

pub trait Grammar<'a>: ParseLiteral {
    type Type: Clone + Debug;
    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);

Associated Types

type Type: Clone + Debug[src]

Type of the type annotation used in the grammar.

Required methods

fn parse_type(input: InputSpan<'a>) -> NomResult<'a, Self::Type>[src]

Attempts to parse a type annotation.

Return value

The output should follow nom conventions on errors / failures.

Implementors

impl<T: ParseLiteral> Grammar<'_> for Untyped<T>[src]

type Type = ()

fn parse_type(input: InputSpan<'_>) -> NomResult<'_, Self::Type>[src]

impl<T: ParseLiteral, Ty: MockTypes> Grammar<'_> for WithMockedTypes<T, Ty>[src]

type Type = ()

fn parse_type(input: InputSpan<'_>) -> NomResult<'_, Self::Type>[src]