Skip to content

Instantly share code, notes, and snippets.

@fero23
Last active April 23, 2016 18:50
Show Gist options
  • Save fero23/ffb7ee8ecf6230fdfbc36c12d89040dd to your computer and use it in GitHub Desktop.
Save fero23/ffb7ee8ecf6230fdfbc36c12d89040dd to your computer and use it in GitHub Desktop.
S-Expr proof of concept test on my rspc library
#[macro_use]
extern crate rspc;
use std::fmt::{Display, Formatter};
use rspc::parsers::{Parser, ParserOps, ws, character, alphanumeric};
use rspc::parsers::combinators::many1;
use rspc::context::StringSource;
#[derive(PartialEq, Debug)]
enum Tree<T> {
List(Vec<Tree<T>>),
Atom(T),
}
impl<T: Display> Display for Tree<T> {
fn fmt(&self, fmt: &mut Formatter) -> ::std::fmt::Result {
match *self {
Tree::List(ref vec) => {
write!(fmt,
"({})",
vec.iter().map(|b| b.to_string()).collect::<Vec<_>>().join(" "))
}
Tree::Atom(ref elem) => write!(fmt, "{}", elem.to_string()),
}
}
}
#[test]
fn match_sexpr() {
def_rules! {
rule atom: Tree<String> = many1(alphanumeric).collect().map(Tree::Atom);
rule expr: Tree<String> = many1(atom.or(s_expr).and_l(ws)).map(Tree::List);
rule s_expr: Tree<String> =
ws.and_r(character('(')).and_r(ws).and_r(expr).and_l(character(')')).and_l(ws);
}
assert_eq!(s_expr.parse(StringSource::new(r#"(((S) (NP VP))
((VP) (V))
((VP) (V NP))
((V) died)
((V) employed)
((NP) nurses)
((NP) patients)
((NP) Medicenter)
((NP) Dr Chan))"#))
.unwrap()
.to_string(),
"(((S) (NP VP)) ((VP) (V)) ((VP) (V NP)) ((V) died) ((V) employed) ((NP) nurses) \
((NP) patients) ((NP) Medicenter) ((NP) Dr Chan))"
.to_string());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment