Skip to content

Instantly share code, notes, and snippets.

@m4rw3r m4rw3r/playground.rs forked from anonymous/playground.rs
Last active Feb 11, 2017

Embed
What would you like to do?
Shared via Rust Playground
#[macro_use]
extern crate chomp;
use std::rc::Rc;
use chomp::prelude::{token, SimpleResult, parse_only};
use chomp::ascii::{is_alphanumeric, is_whitespace};
use chomp::types::{Buffer, U8Input};
use chomp::parsers::{take_while1, skip_while};
use chomp::combinators::many;
#[derive(Debug)]
enum Svalue {
Sexpr(Rc<Sexpr>),
String(String),
}
#[derive(Debug)]
struct Sexpr {
values: Vec<Svalue>,
}
fn parse_inner_list<I: U8Input>(i: I) -> SimpleResult<I, Svalue> {
parse!{i;
token(b'(');
let values = parse_sexpr();
token(b')');
ret (Svalue::Sexpr(Rc::new(values)))
}
}
fn parse_value<I: U8Input>(i: I) -> SimpleResult<I, Svalue> {
parse!{i;
let value = take_while1(is_alphanumeric);
ret (Svalue::String(String::from_utf8(value.to_vec()).unwrap()))
}
}
fn parse_svalue<I: U8Input>(i: I) -> SimpleResult<I, Svalue> {
parse!{i;
skip_while(is_whitespace);
let value = parse_value() <|> parse_inner_list();
skip_while(is_whitespace);
ret value
}
}
fn parse_sexpr<I: U8Input>(i: I) -> SimpleResult<I, Sexpr> {
parse!{i;
let val = many(parse_svalue);
ret (Sexpr { values: val})
}
}
fn main() {
let sexpr = parse_only(parse_sexpr, b"()");
println!("Parsed: {:?}", sexpr);
let sexpr = parse_only(parse_sexpr, b"a bcd c d");
println!("Parsed: {:?}", sexpr);
let sexpr = parse_only(parse_sexpr, b"(a)");
println!("Parsed: {:?}", sexpr);
let sexpr = parse_only(parse_sexpr, b"(a bcd c d (e f))");
println!("Parsed: {:?}", sexpr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.