[][src]Function combine_language::expression_parser

pub fn expression_parser<O, P, F, T>(
    term: P,
    op: O,
    f: F
) -> Expression<O, P, F> where
    O: Parser<Output = (T, Assoc)>,
    P: Parser<Input = O::Input>,
    F: Fn(P::Output, T, P::Output) -> P::Output

Constructs an expression parser out of a term parser, an operator parser and a function which combines a binary expression to new expressions.

use self::Expr::*;
#[derive(PartialEq, Debug)]
enum Expr {
     Id(String),
     Op(Box<Expr>, &'static str, Box<Expr>)
}
fn op(l: Expr, o: &'static str, r: Expr) -> Expr {
    Op(Box::new(l), o, Box::new(r))
}
fn id(s: &str) -> Expr {
    Id(String::from(s))
}
let op_parser = string("+").or(string("*"))
    .map(|op| {
        let prec = match op {
            "+" => 6,
            "*" => 7,
            _ => unreachable!()
        };
        (op, Assoc { precedence: prec, fixity: Fixity::Left })
    })
    .skip(spaces());
let term = many(letter())
    .map(Id)
    .skip(spaces());
let mut parser = expression_parser(term, op_parser, op);
let result = parser.easy_parse("a + b * c + d");
assert_eq!(result, Ok((op(op(id("a"), "+", op(id("b"), "*", id("c"))), "+", id("d")), "")));