topdown-rs 0.3.3

A top-down parsing library
Documentation
use super::{CharSeq, ParserResult, Parser, Succ, Error, Fail};

pub struct Keyword<'a> {
    keyword: &'a str,
}

static ASCII_LETTERS: &'static str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";

pub fn keyword<'a>(k: &'a str) -> Keyword {
    return Keyword{keyword: k};
}

impl<'a> Parser<String> for Keyword<'a> {
    fn parse(&self, cs: &mut CharSeq) -> ParserResult<String> {
        let h = cs.enable_hook;
        cs.enable_hook = false;
        match cs.accept(&self.keyword) {
            Succ(r) => {
                cs.enable_hook = h;
                if ASCII_LETTERS.contains(cs.current()) {
                    return cs.fail(cs.current().to_string().as_str());
                }
                if cs.enable_hook {
                    cs.do_hook();
                }
                Succ(r)
            },
            Fail(m, l) => {cs.enable_hook = h; Fail(m, l)},
            Error(m, l) => {cs.enable_hook = h; Error(m, l)}
        }
    }

    #[allow(unused_variables)]
    fn _parse(&self, cs: &mut CharSeq) -> ParserResult<String> {
        return Succ("".to_string()); // unused
    }
}

#[cfg(test)]
#[allow(unused_variables)]
#[allow(unused_imports)]
mod tests {
    use super::keyword;
    use super::super::{CharSeq, skip, ParserResult, Parser, Succ, Fail, Error};

    #[test]
    fn test_keyword() {
        let mut cs = CharSeq::new("keyword keywordxxx", "");
        let k = keyword("keyword");
        let s = skip(" ");
        cs.add_hook(&s);
        match cs.accept(&k) {
            Succ(r) => (),
            _ => assert!(false)
        }
        match cs.accept(&k) {
            Fail(m, l) => (),
            _ => assert!(false)
        }
    }

}