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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
|
use crate::ast::*;
#[derive(Debug, PartialEq)]
enum Token {
LParen,
RParen,
Word(String),
}
struct Parser {
tokens: Vec<Token>,
index: usize,
}
impl Parser {
fn expect(&self, token: Token) -> Result<(), String> {
if self.tokens.get(self.index) == Some(&token) {
Ok(())
} else {
Err(format!(
"Expected {:?}, got {:?}",
token,
self.tokens.get(self.index)
))
}
}
fn next(&mut self) {
self.index += 1;
}
}
pub fn parse(arg: &str) -> Value {
let tokens = tokenize(arg);
let mut parser = Parser { tokens, index: 0 };
parse_expression(&mut parser)
.map_err(|e| panic!("Syntax error: {}", e))
.unwrap()
}
fn parse_expression(parser: &mut Parser) -> Result<Value, String> {
parse_application(parser).or(parse_value(parser))
}
fn parse_application(parser: &mut Parser) -> Result<Value, String> {
parser.expect(Token::LParen)?;
parser.next();
let left = parse_expression(parser)?;
let right = parse_expression(parser)?;
parser.expect(Token::RParen)?;
Ok(Value::App(Box::new(left), Box::new(right)))
}
fn parse_value(parser: &mut Parser) -> Result<Value, String> {
let token = parser.tokens.get(parser.index).ok_or("Expected a value")?;
let val = parse_number(token)
.or(parse_bool(token))
.or(parse_symbol(token))?;
parser.next();
Ok(val)
}
fn tokenize(arg: &str) -> Vec<Token> {
let mut result = Vec::new();
let mut word = String::new();
for c in arg.chars() {
match c {
'(' => {
terminate(&mut result, &mut word);
result.push(Token::LParen)
}
')' => {
terminate(&mut result, &mut word);
result.push(Token::RParen)
}
c if c.is_whitespace() => terminate(&mut result, &mut word),
c => word.push(c),
}
}
terminate(&mut result, &mut word);
result
}
fn terminate(result: &mut Vec<Token>, word: &mut String) {
if !word.is_empty() {
let w = word.clone();
if w == "lam" {
result.push(Token::Lambda);
} else {
result.push(Token::Word(w));
}
word.clear();
}
}
fn parse_symbol(token: &Token) -> Result<Value, String> {
match token {
Token::Word(s) => Ok(Value::Sym(s.clone())),
_ => Err("Expected a symbol".to_string()),
}
}
fn parse_bool(token: &Token) -> Result<Value, String> {
match token {
Token::Word(s) => s
.parse::<bool>()
.map(Value::Bool)
.map_err(|e| e.to_string()),
_ => Err("Expected a boolean".to_string()),
}
}
fn parse_number(token: &Token) -> Result<Value, String> {
match token {
Token::Word(s) => s.parse::<i32>().map(Value::Num).map_err(|e| e.to_string()),
_ => Err("Expected an integer".to_string()),
}
}
#[cfg(test)]
mod tests {
use super::Token::*;
use super::Value;
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![
Word("42".to_string()),
Word("foo".to_string()),
Word("true".to_string())
],
tokenize("42 foo \ntrue ")
);
}
#[test]
fn tokenize_string_with_parens() {
assert_eq!(
vec![
LParen,
LParen,
RParen,
Word("42".to_string()),
RParen,
Word("true".to_string()),
LParen,
],
tokenize("( \r() 42) \ntrue( ")
);
}
#[test]
fn tokenize_lambda_symbol() {
assert_eq!(vec![Lambda, LParen,], tokenize("lam ("));
}
#[test]
fn parse_application_of_two_values() {
assert_eq!(
App(Box::new(Sym("foo".to_string())), Box::new(Num(42))),
parse("(foo 42)")
);
}
impl Arbitrary for Value {
type Parameters = ();
type Strategy = BoxedStrategy<Self>;
fn arbitrary_with(_args: ()) -> Self::Strategy {
prop_oneof![
any::<i32>().prop_map(Num),
any::<bool>().prop_map(Bool),
// see https://unicode.org/reports/tr18/#General_Category_Property for one letter unicode categories
"\\pL(\\pL|\\pN)*".prop_map(Sym),
]
.boxed()
}
}
proptest! {
#[test]
fn parse_is_inverse_to_display(values in any::<Vec<Value>>()) {
let result : Vec<String> = values.iter().map(|v:&Value| v.to_string()).collect();
assert_eq!(values, result.iter().map(|s| parse(s)).collect::<Vec<Value>>());
}
}
}
|