[][src]Function combine::env_parser

pub fn env_parser<E, I, O>(
    env: E,
    parser: fn(_: E, _: &mut I) -> ParseResult<O, I>
) -> EnvParser<E, I, O> where
    E: Clone,
    I: Stream

Constructs a parser out of an environment and a function which needs the given environment to do the parsing. This is commonly useful to allow multiple parsers to share some environment while still allowing the parsers to be written in separate functions.

struct Interner(HashMap<String, u32>);
impl Interner {
    fn string<I>(&self, input: &mut I) -> ParseResult<u32, I>
        where I: Stream<Item=char>,
              I::Error: ParseError<I::Item, I::Range, I::Position>,
    {
        many(letter())
            .map(|s: String| self.0.get(&s).cloned().unwrap_or(0))
            .parse_stream(input)
    }
}

let mut map = HashMap::new();
map.insert("hello".into(), 1);
map.insert("test".into(), 2);

let env = Interner(map);
let mut parser = env_parser(&env, Interner::string);

let result = parser.parse("hello");
assert_eq!(result, Ok((1, "")));

let result = parser.parse("world");
assert_eq!(result, Ok((0, "")));