summaryrefslogtreecommitdiff
path: root/rust/src/parser.rs
blob: b3d76fb755325beeb5d218c22dc07b4de7d13532 (plain)
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
use crate::ast::*;

pub fn parse(arg: &str) -> Value {
    if let Some(token) = tokenize(arg).first() {
        return parse_number(token)
            .or(parse_bool(token))
            .or(parse_symbol(token))
            .unwrap();
    }
    panic!("No value to parse");
}

fn tokenize(arg: &str) -> Vec<String> {
    arg.split(|c: char| c.is_whitespace())
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
        .collect()
}

fn parse_symbol(token: &str) -> Result<Value, String> {
    Ok(Value::Sym(token.to_string()))
}

fn parse_bool(token: &str) -> Result<Value, String> {
    token
        .parse::<bool>()
        .map(Value::Bool)
        .map_err(|e| e.to_string())
}

fn parse_number(token: &str) -> Result<Value, String> {
    token
        .parse::<i32>()
        .map(Value::Num)
        .map_err(|e| e.to_string())
}

#[cfg(test)]
mod tests {
    use super::Value::*;
    use super::{parse, tokenize};
    use proptest::prelude::*;

    proptest! {
            #[test]
            fn parse_integer_as_number(i in -1000i32..1000) {
                let result = parse(&i.to_string());
                assert_eq!(Num(i), result);
            }

    }

    #[test]
    fn parse_truth_values_as_booleans() {
        assert_eq!(Bool(true), parse("true"));
        assert_eq!(Bool(false), parse("false"));
    }

    #[test]
    fn parse_identifiers_values_as_symbols() {
        assert_eq!(Sym("foo".to_string()), parse("foo"));
    }

    #[test]
    fn ignores_whitespace() {
        assert_eq!(Sym("foo".to_string()), parse("  foo  \n\r"));
        assert_eq!(Num(-42), parse("\n-42"));
    }

    #[test]
    fn tokenize_several_values() {
        assert_eq!(vec!["42", "foo", "true"], tokenize("42 foo    \ntrue  "));
    }
}