[][src]Function combine::env_parser

pub fn env_parser<E, Input, O>(
    env: E,
    parser: fn(_: E, _: &mut Input) -> StdParseResult<O, Input>
) -> EnvParser<E, Input, O> where
    E: Clone,
    Input: 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<Input>(&self, input: &mut Input) -> StdParseResult<u32, Input>
        where Input: Stream<Token = char>,
              Input::Error: ParseError<Input::Token, Input::Range, Input::Position>,
    {
        many(letter())
            .map(|s: String| self.0.get(&s).cloned().unwrap_or(0))
            .parse_stream(input)
            .into_result()
    }
}

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, "")));