-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathobject.rs
More file actions
359 lines (326 loc) · 11.1 KB
/
Copy pathobject.rs
File metadata and controls
359 lines (326 loc) · 11.1 KB
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
use std::fmt;
use std::collections::HashMap;
use std::hash::{Hash,Hasher};
use std::cell::RefCell;
use std::rc::Rc;
use crate::ast;
use crate::code;
use code::InstructionsFns;
use enum_iterator::IntoEnumIterator;
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
pub enum Object {
Int(i64),
Bool(bool),
String(String),
Return(Rc<Return>),
Function(Rc<Function>),
Builtin(Builtin),
Array(Rc<Array>),
Hash(Rc<MonkeyHash>),
Null,
CompiledFunction(Rc<CompiledFunction>),
Closure(Rc<Closure>),
}
impl Object {
pub fn inspect(&self) -> String {
match self {
Object::Int(i) => i.to_string(),
Object::Bool(b) => b.to_string(),
Object::String(s) => s.clone(),
Object::Return(r) => r.value.inspect(),
Object::Function(f) => f.inspect(),
Object::Builtin(b) => b.inspect(),
Object::Array(a) => a.inspect(),
Object::Hash(h) => h.inspect(),
Object::Null => String::from("null"),
Object::CompiledFunction(f) => f.inspect(),
Object::Closure(c) => c.inspect(),
}
}
}
impl fmt::Display for Object {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "{}", self.inspect())
}
}
#[derive(Eq, PartialEq, Clone, Debug)]
pub struct MonkeyHash {
pub pairs: HashMap<Rc<Object>,Rc<Object>>,
}
impl MonkeyHash {
fn inspect(&self) -> String {
let pairs: Vec<String> = (&self.pairs).into_iter().map(|(key, value)| format!("{}: {}", key.inspect(), value.inspect())).collect();
format!("{{{}}}", pairs.join(", "))
}
}
impl Hash for MonkeyHash {
fn hash<H: Hasher>(&self, _state: &mut H) {
// should never happen
panic!("hash not implmented for monkey hash");
}
}
#[derive(Eq, PartialEq, Clone, Debug)]
pub struct Array {
pub elements: Vec<Rc<Object>>,
}
impl Array {
fn inspect(&self) -> String {
let elements: Vec<String> = (&self.elements).into_iter().map(|e| e.to_string()).collect();
format!("[{}]", elements.join(", "))
}
}
impl Hash for Array {
fn hash<H: Hasher>(&self, _state: &mut H) {
// we should never hash an array so should be fine
panic!("hash for array not supported");
}
}
#[repr(u8)]
#[derive(Hash, Eq, PartialEq, Clone, Debug, IntoEnumIterator, Copy)]
pub enum Builtin {
Len,
Puts,
First,
Last,
Rest,
Push,
}
impl Builtin {
pub fn lookup(name: &str) -> Option<Object> {
match name {
"len" => Some(Object::Builtin(Builtin::Len)),
"first" => Some(Object::Builtin(Builtin::First)),
"last" => Some(Object::Builtin(Builtin::Last)),
"rest" => Some(Object::Builtin(Builtin::Rest)),
"push" => Some(Object::Builtin(Builtin::Push)),
"puts" => Some(Object::Builtin(Builtin::Puts)),
_ => None,
}
}
pub fn apply(&self, args: &Vec<Rc<Object>>) -> Result<Rc<Object>, String> {
match self {
Builtin::Len => {
if args.len() != 1 {
return Err("len takes only 1 array or string argument".to_string())
}
let arg = &*Rc::clone(args.first().unwrap());
match arg {
Object::String(s) => Ok(Rc::new(Object::Int(s.len() as i64))),
Object::Array(a) => Ok(Rc::new(Object::Int(a.elements.len() as i64))),
obj => Err(format!("object {:?} not supported as an argument for len", obj))
}
},
Builtin::First => {
if args.len() != 1 {
return Err("first takes only 1 array argument".to_string())
}
let arg = &*Rc::clone( args.first().unwrap());
match arg {
Object::Array(a) => {
match a.elements.first() {
Some(el) => Ok(Rc::clone(el)),
None => Ok(Rc::new(Object::Null)),
}
},
obj => Err(format!("object {:?} not supported as an argument for first", obj))
}
},
Builtin::Last => {
if args.len() != 1 {
return Err("last takes only 1 array argument".to_string())
}
let arg = &*Rc::clone(args.first().unwrap());
match arg {
Object::Array(a) => {
match a.elements.last() {
Some(el) => Ok(Rc::clone(el)),
None => Ok(Rc::new(Object::Null)),
}
},
obj => Err(format!("object {:?} not supported as an argument for last", obj))
}
},
Builtin::Rest => {
if args.len() != 1 {
return Err("rest takes only 1 array argument".to_string())
}
let arg = &*Rc::clone(args.first().unwrap());
match arg {
Object::Array(a) => {
if a.elements.len() <= 1 {
Ok(Rc::new(Object::Array(Rc::new(Array{elements: vec![]}))))
} else {
let mut elements = a.elements.clone();
elements.remove(0);
Ok(Rc::new(Object::Array(Rc::new(Array{elements}))))
}
},
obj => Err(format!("object {:?} is not supported as an argument for rest", obj))
}
},
Builtin::Push => {
if args.len() != 2 {
return Err("push takes an array and an object".to_string())
}
let array = &*Rc::clone(args.first().unwrap());
let obj = Rc::clone(args.last().unwrap());
// TODO: handle pushing objects like an array onto an array
match array {
Object::Array(a) => {
let mut elements = a.elements.clone();
elements.push(obj);
Ok(Rc::new(Object::Array(Rc::new(Array{elements}))))
},
_ => Err("first argument to push must be an array".to_string())
}
},
Builtin::Puts => {
for arg in args {
println!("{}", arg.inspect())
}
Ok(Rc::new(Object::Null))
}
}
}
pub fn string(&self) -> String {
self.inspect()
}
fn inspect(&self) -> String {
match self {
Builtin::Len => "len".to_string(),
Builtin::First => "first".to_string(),
Builtin::Last => "last".to_string(),
Builtin::Rest => "rest".to_string(),
Builtin::Push => "push".to_string(),
Builtin::Puts => "puts".to_string(),
}
}
}
#[derive(Clone, Debug)]
pub struct Function {
pub parameters: Vec<ast::IdentifierExpression>,
pub body: ast::BlockStatement,
pub env: Rc<RefCell<Environment>>,
}
impl Function {
fn inspect(&self) -> String {
let params: Vec<String> = (&self.parameters).into_iter().map(|p| p.to_string()).collect();
format!("fn({}) {{\n{}\n}}", params.join(", "), self.body.to_string())
}
}
impl PartialEq for Function {
fn eq(&self, _other: &Function) -> bool {
// TODO: implement this, but it should never get used
panic!("partial eq not implemented for function");
}
}
impl Eq for Function {}
impl Hash for Function {
fn hash<H: Hasher>(&self, _state: &mut H) {
// we should never hash an array so should be fine
panic!("hash for function not supported");
}
}
#[derive(Eq, PartialEq, Clone, Debug)]
pub struct CompiledFunction {
pub instructions: code::Instructions,
pub num_locals: usize,
pub num_parameters: usize,
}
impl CompiledFunction {
fn inspect(&self) -> String {
format!("CompiledFunction[{}]", self.instructions.string())
}
}
impl Hash for CompiledFunction {
fn hash<H: Hasher>(&self, _state: &mut H) {
panic!("hash for compiled function not supported")
}
}
#[derive(Eq, PartialEq, Debug)]
pub struct Closure {
pub func: Rc<CompiledFunction>,
pub free: Vec<Rc<Object>>,
}
impl Closure {
fn inspect(&self) -> String { format!("Closure[{:?}]", self) }
}
impl Hash for Closure {
fn hash<H: Hasher>(&self, _state: &mut H) {
panic!("hash for closure not supported")
}
}
#[derive(Clone, Debug)]
pub struct Return {
pub value: Rc<Object>,
}
impl PartialEq for Return {
fn eq(&self, _other: &Return) -> bool {
// TODO: implement this, but it should never get used
panic!("partial eq not implemented for Return");
}
}
impl Eq for Return {}
impl Hash for Return {
fn hash<H: Hasher>(&self, _state: &mut H) {
// we should never hash an array so should be fine
panic!("hash for return not supported");
}
}
#[derive(Clone, Debug)]
pub struct Environment {
pub store: HashMap<String, Rc<Object>>,
pub outer: Option<Rc<RefCell<Environment>>>,
}
impl Environment {
pub fn new() -> Environment {
Environment{store: HashMap::new(), outer: None}
}
pub fn new_enclosed(env: Rc<RefCell<Environment>>) -> Environment {
Environment{store: HashMap::new(), outer: Some(Rc::clone(&env))}
}
pub fn get(&self, name: &str) -> Option<Rc<Object>> {
match self.store.get(name) {
Some(obj) => {
Some(Rc::clone(obj))
},
None => {
match &self.outer {
Some(o) => o.borrow().get(name),
_ => None,
}
},
}
}
pub fn set(&mut self, name: String, obj: Rc<Object>) {
self.store.insert(name, obj);
}
}
#[cfg(test)]
mod test {
use super::*;
use std::collections::hash_map::DefaultHasher;
#[test]
// this test is unnecessary, but here for completeness with the Monkey book.
fn string_hash_key() {
let hello1 = Object::String(String::from("Hello World"));
let hello2 = Object::String(String::from("Hello World"));
let diff1 = Object::String(String::from("my name is johnny"));
let diff2 = Object::String(String::from("my name is johnny"));
let mut hasher1 = DefaultHasher::new();
hello1.hash(&mut hasher1);
let mut hasher2 = DefaultHasher::new();
hello2.hash(&mut hasher2);
assert_eq!(hasher1.finish(), hasher2.finish());
let mut hasher1 = DefaultHasher::new();
diff1.hash(&mut hasher1);
let mut hasher2 = DefaultHasher::new();
diff2.hash(&mut hasher2);
assert_eq!(hasher1.finish(), hasher2.finish());
let mut hasher1 = DefaultHasher::new();
hello1.hash(&mut hasher1);
let mut hasher2 = DefaultHasher::new();
diff1.hash(&mut hasher2);
assert_ne!(hasher1.finish(), hasher2.finish());
}
}