forked from kanaka/mal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypes.rs
240 lines (214 loc) · 6.27 KB
/
types.rs
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
use std::cell::RefCell;
use std::rc::Rc;
//use std::collections::HashMap;
use fnv::FnvHashMap;
use itertools::Itertools;
use crate::env::{env_bind, Env};
use crate::types::MalErr::{ErrMalVal, ErrString};
use crate::types::MalVal::{Atom, Bool, Func, Hash, Int, List, MalFunc, Nil, Str, Sym, Vector};
#[derive(Debug, Clone)]
pub enum MalVal {
Nil,
Bool(bool),
Int(i64),
//Float(f64),
Str(String),
Sym(String),
List(Rc<Vec<MalVal>>, Rc<MalVal>),
Vector(Rc<Vec<MalVal>>, Rc<MalVal>),
Hash(Rc<FnvHashMap<String, MalVal>>, Rc<MalVal>),
Func(fn(MalArgs) -> MalRet, Rc<MalVal>),
MalFunc {
eval: fn(ast: MalVal, env: Env) -> MalRet,
ast: Rc<MalVal>,
env: Env,
params: Rc<MalVal>,
is_macro: bool,
meta: Rc<MalVal>,
},
Atom(Rc<RefCell<MalVal>>),
}
#[derive(Debug)]
pub enum MalErr {
ErrString(String),
ErrMalVal(MalVal),
}
pub type MalArgs = Vec<MalVal>;
pub type MalRet = Result<MalVal, MalErr>;
// type utility macros
macro_rules! list {
($seq:expr) => {{
List(Rc::new($seq),Rc::new(Nil))
}};
[$($args:expr),*] => {{
let v: Vec<MalVal> = vec![$($args),*];
List(Rc::new(v),Rc::new(Nil))
}}
}
macro_rules! vector {
($seq:expr) => {{
Vector(Rc::new($seq),Rc::new(Nil))
}};
[$($args:expr),*] => {{
let v: Vec<MalVal> = vec![$($args),*];
Vector(Rc::new(v),Rc::new(Nil))
}}
}
// type utility functions
pub fn error(s: &str) -> MalRet {
Err(ErrString(s.to_string()))
}
pub fn format_error(e: MalErr) -> String {
match e {
ErrString(s) => s.clone(),
ErrMalVal(mv) => mv.pr_str(true),
}
}
pub fn atom(mv: &MalVal) -> MalVal {
Atom(Rc::new(RefCell::new(mv.clone())))
}
impl MalVal {
pub fn keyword(&self) -> MalRet {
match self {
Str(s) if s.starts_with("\u{29e}") => Ok(Str(s.to_string())),
Str(s) => Ok(Str(format!("\u{29e}{}", s))),
_ => error("invalid type for keyword"),
}
}
pub fn empty_q(&self) -> MalRet {
match self {
List(l, _) | Vector(l, _) => Ok(Bool(l.len() == 0)),
Nil => Ok(Bool(true)),
_ => error("invalid type for empty?"),
}
}
pub fn count(&self) -> MalRet {
match self {
List(l, _) | Vector(l, _) => Ok(Int(l.len() as i64)),
Nil => Ok(Int(0)),
_ => error("invalid type for count"),
}
}
pub fn apply(&self, args: MalArgs) -> MalRet {
match *self {
Func(f, _) => f(args),
MalFunc {
eval,
ref ast,
ref env,
ref params,
..
} => {
let a = &**ast;
let p = &**params;
let fn_env = env_bind(Some(env.clone()), p.clone(), args)?;
Ok(eval(a.clone(), fn_env)?)
}
_ => error("attempt to call non-function"),
}
}
pub fn keyword_q(&self) -> bool {
match self {
Str(s) if s.starts_with("\u{29e}") => true,
_ => false,
}
}
pub fn deref(&self) -> MalRet {
match self {
Atom(a) => Ok(a.borrow().clone()),
_ => error("attempt to deref a non-Atom"),
}
}
pub fn reset_bang(&self, new: &MalVal) -> MalRet {
match self {
Atom(a) => {
*a.borrow_mut() = new.clone();
Ok(new.clone())
}
_ => error("attempt to reset! a non-Atom"),
}
}
pub fn swap_bang(&self, args: &MalArgs) -> MalRet {
match self {
Atom(a) => {
let f = &args[0];
let mut fargs = args[1..].to_vec();
fargs.insert(0, a.borrow().clone());
*a.borrow_mut() = f.apply(fargs)?;
Ok(a.borrow().clone())
}
_ => error("attempt to swap! a non-Atom"),
}
}
pub fn get_meta(&self) -> MalRet {
match self {
List(_, meta) | Vector(_, meta) | Hash(_, meta) => Ok((&**meta).clone()),
Func(_, meta) => Ok((&**meta).clone()),
MalFunc { meta, .. } => Ok((&**meta).clone()),
_ => error("meta not supported by type"),
}
}
pub fn with_meta(&mut self, new_meta: &MalVal) -> MalRet {
match self {
List(_, ref mut meta)
| Vector(_, ref mut meta)
| Hash(_, ref mut meta)
| Func(_, ref mut meta)
| MalFunc { ref mut meta, .. } => {
*meta = Rc::new((&*new_meta).clone());
}
_ => return error("with-meta not supported by type"),
};
Ok(self.clone())
}
}
impl PartialEq for MalVal {
fn eq(&self, other: &MalVal) -> bool {
match (self, other) {
(Nil, Nil) => true,
(Bool(ref a), Bool(ref b)) => a == b,
(Int(ref a), Int(ref b)) => a == b,
(Str(ref a), Str(ref b)) => a == b,
(Sym(ref a), Sym(ref b)) => a == b,
(List(ref a, _), List(ref b, _))
| (Vector(ref a, _), Vector(ref b, _))
| (List(ref a, _), Vector(ref b, _))
| (Vector(ref a, _), List(ref b, _)) => a == b,
(Hash(ref a, _), Hash(ref b, _)) => a == b,
(MalFunc { .. }, MalFunc { .. }) => false,
_ => false,
}
}
}
pub fn func(f: fn(MalArgs) -> MalRet) -> MalVal {
Func(f, Rc::new(Nil))
}
pub fn _assoc(mut hm: FnvHashMap<String, MalVal>, kvs: MalArgs) -> MalRet {
if kvs.len() % 2 != 0 {
return error("odd number of elements");
}
for (k, v) in kvs.iter().tuples() {
match k {
Str(s) => {
hm.insert(s.to_string(), v.clone());
}
_ => return error("key is not string"),
}
}
Ok(Hash(Rc::new(hm), Rc::new(Nil)))
}
pub fn _dissoc(mut hm: FnvHashMap<String, MalVal>, ks: MalArgs) -> MalRet {
for k in ks.iter() {
match k {
Str(ref s) => {
hm.remove(s);
}
_ => return error("key is not string"),
}
}
Ok(Hash(Rc::new(hm), Rc::new(Nil)))
}
pub fn hash_map(kvs: MalArgs) -> MalRet {
let hm: FnvHashMap<String, MalVal> = FnvHashMap::default();
_assoc(hm, kvs)
}