1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use pest::iterators::{Pair, Pairs};
use pest::Parser;

use crate::parser::{RhizParser, Rule};

#[derive(Debug, PartialEq)]
pub enum RhizValue {
    Program(Vec<RhizValue>),
    SExpr(Vec<RhizValue>),
    Symbol(String),
    String(String),
}

impl std::convert::From<&RhizValue> for String {
    fn from(v: &RhizValue) -> String {
        match v {
            RhizValue::String(s) => format!("\"{}\"", s),
            RhizValue::Symbol(s) => s.to_owned(),
            RhizValue::SExpr(contents) => {
                let mut outp = String::new();
                let items = contents.iter();
                for i in items {
                    let s: String = i.into();
                    outp.push_str(&s);
                    outp.push(' ');
                }
                outp
            }
            RhizValue::Program(sexprs) => {
                let mut outp = String::new();
                let items = sexprs.iter();
                for i in items {
                    let s: String = i.into();
                    outp.push_str(&s);
                    outp.push(' ');
                }
                outp
            }
        }
    }
}

fn collect_or_first_error(pairs: Pairs<Rule>) -> Result<Vec<RhizValue>, String> {
    let mut result = Vec::new();
    for p in pairs {
        match parse_value(p) {
            Ok(v) => result.push(v),
            Err(e) => return Err(e),
        }
    }
    Ok(result)
}

fn parse_value(pair: Pair<Rule>) -> Result<RhizValue, String> {
    match pair.as_rule() {
        Rule::program => {
            let exprs = collect_or_first_error(pair.into_inner())?;
            Ok(RhizValue::Program(exprs))
        }
        Rule::sexpr => {
            let exprs = collect_or_first_error(pair.into_inner())?;
            Ok(RhizValue::SExpr(exprs))
        }
        Rule::symbol => {
            let raw = pair.as_str().to_owned();
            Ok(RhizValue::Symbol(raw))
        }
        Rule::string => {
            let raw = pair.as_str();
            // Drop opening and closing " from string source
            let contents = raw[1..raw.len() - 1].to_owned();
            Ok(RhizValue::String(contents))
        }
        _ => unreachable!("{:?}", pair),
    }
}

pub fn parse_rhiz_program(src: &str) -> Result<RhizValue, String> {
    let mut parse_tree =
        RhizParser::parse(Rule::file, src).map_err(|e| format!("Parsing error: {}", e))?;
    let prog = parse_tree.next().expect("Expected a program");
    parse_value(prog)
}

#[test]
fn test_parse_values() {
    let example_src = r#"(Once there was) (a "way" to get "back home")"#;
    assert!(parse_rhiz_program(example_src).is_ok())
}