Skip to content

Instantly share code, notes, and snippets.

@m4rw3r
Forked from anonymous/playground.rs
Last active February 11, 2017 12:15
Show Gist options
  • Save m4rw3r/2f850c5f6895d1c5562adf84a94e48f2 to your computer and use it in GitHub Desktop.
Save m4rw3r/2f850c5f6895d1c5562adf84a94e48f2 to your computer and use it in GitHub Desktop.
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