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§

source

type Type<'a>: 'a + Clone + Debug

Type of the type annotation used in the grammar. This type may be parametric by the input lifetime.

Required Methods§

source

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

Attempts to parse a type annotation.

Return value

The output should follow nom conventions on errors / failures.

Implementors§

source§

impl<T: ParseLiteral> Grammar for Untyped<T>

§

type Type<'a> = ()

source§

impl<T: ParseLiteral, Ty: MockTypes> Grammar for WithMockedTypes<T, Ty>

§

type Type<'a> = ()