This repository has been archived by the owner on Nov 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlisplike.rs
546 lines (474 loc) · 15.4 KB
/
lisplike.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
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
extern mod std;
use std::hashmap::HashMap;
use std::to_str::ToStr;
use std::rc::Rc;
use std::io::stdio::{print, println};
use sexpr;
// A very simple LISP-like language
// Globally scoped, no closures
/// Our value types
#[deriving(Clone)]
pub enum LispValue {
List(~[LispValue]),
Atom(~str),
Str(~str),
Num(f64),
Fn(~[~str], ~sexpr::Value), // args, body
BIF(~str, int, ~[~str], fn(Rc<HashMap<~str, ~LispValue>>, ~[~LispValue])->~LispValue) // built-in function (args, closure)
}
// XXX: this is ugly but it won't automatically derive Eq because of the extern fn
impl Eq for LispValue {
fn eq(&self, other: &LispValue) -> bool {
match (self.clone(), other.clone()) {
(BIF(ref x, _, _, _), BIF(ref y, _, _, _)) if *x == *y => true,
(Str(ref x), Str(ref y)) if *x == *y => true,
(Num(ref x), Num(ref y)) if *x == *y => true,
(Atom(ref x), Atom(ref y)) if *x == *y => true,
(List(ref x), List(ref y)) if *x == *y => true,
(Fn(ref x, ref x2), Fn(ref y, ref y2)) if *x == *y && *x2 == *y2 => true,
_ => false
}
}
}
impl LispValue {
/// Coerces this Lisp value to a native boolean. Empty lists (nil) are falsey,
/// everything else is truthy.
fn as_bool(&self) -> bool {
match *self {
List([]) => false, // nil
_ => true
}
}
}
impl ToStr for LispValue {
fn to_str(&self) -> ~str {
match *self {
Atom(ref s) => s.clone(),
Str(ref s) => s.clone(),
Num(ref f) => f.to_str(),
Fn(ref args, _) => format!("<fn({:u})>", args.len()),
BIF(ref name, ref arity, _, _) => format!("<fn {:s}({:i})>", name.clone(), *arity),
List(ref v) => {
let values: ~[~str] = v.iter().map(|x: &LispValue| x.to_str()).collect();
format!("({:s})", values.connect(" "))
}
}
}
}
fn from_sexpr(sexpr: &sexpr::Value) -> ~LispValue {
match *sexpr {
sexpr::List(ref v) => ~List(v.map(|x| *from_sexpr(x))),
sexpr::Num(v) => ~Num(v),
sexpr::Str(ref v) => ~Str(v.clone()),
sexpr::Atom(ref v) => ~Atom(v.clone())
}
}
fn to_sexpr(value: &LispValue) -> sexpr::Value {
match *value {
Num(ref v) => sexpr::Num(v.clone()),
Str(ref s) => sexpr::Str(s.clone()),
Atom(ref s) => sexpr::Atom(s.clone()),
List(ref v) => sexpr::List(v.iter().map(to_sexpr).to_owned_vec()),
Fn(..) => fail!("can't convert fn to an s-expression"),
BIF(..) => fail!("can't convert BIF to an s-expression"),
}
}
/// The type of the global symbol table (string to a value mapping).
type SymbolTable = HashMap<~str, ~LispValue>;
/// Returns a value representing the empty list
#[inline]
pub fn nil() -> ~LispValue {
~List(~[])
}
/// Creates a new symbol table and returns it
pub fn new_symt() -> SymbolTable {
HashMap::new()
}
/// Binds a symbol in the symbol table. Replaces if it already exists.
pub fn bind(symt: Rc<SymbolTable>, name: ~str, value: ~LispValue) {
symt.borrow().insert(name, value);
}
/// Look up a symbol in the symbol table. Fails if not found.
pub fn lookup(symt: Rc<SymbolTable>, name: ~str) -> ~LispValue {
match symt.borrow().find(&name) {
Some(v) => v.clone(),
None => fail!("couldn't find symbol: {}", name)
}
}
/// Identity function
fn id_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue { v[0] }
fn cons_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v {
[~a, ~b, ..] => ~List(~[a, b]),
_ => fail!("cons: requires two arguments")
}
}
fn car_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v[0] {
~List(v_) => ~v_[0],
_ => fail!("car: need a list")
}
}
fn cdr_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v[0] {
~List(v_) => ~v_[1],
_ => fail!("cdr: need a list")
}
}
// Print function
fn print_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v[0] {
~Str(s) => println(s),
_ => fail!("print takes an str")
}
nil()
}
// There are several bugs in the macroing system (#8853, or, #8852 and #8851)
// that prevent us from making these functions macros. In addition, we can't
// return a closure because the type needs to be `extern "Rust" fn`, which
// closures aren't. So we have a little bit of code duplication.
fn plus_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("+ needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let add = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() + y.clone()),
(Str(ref x), &~Str(ref y)) => ~Str(x.clone() + y.clone()),
_ => fail!("invalid operands to +")
}
};
v.iter().skip(1).fold(v[0].clone(), add)
}
fn minus_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("- needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let sub = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() - y.clone()),
_ => fail!("invalid operands to -")
}
};
v.iter().skip(1).fold(v[0].clone(), sub)
}
fn mul_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("* needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let mul = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() * y.clone()),
_ => fail!("invalid operands to *")
}
};
v.iter().skip(1).fold(v[0].clone(), mul)
}
fn div_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
if(v.len() == 0) { fail!("/ needs operands"); }
else if(v.len() == 1) {
return v[0];
}
let div = |acc: ~LispValue, b: &~LispValue| {
match (*acc, b) {
(Num(ref x), &~Num(ref y)) => ~Num(x.clone() / y.clone()),
_ => fail!("invalid operands to /")
}
};
v.iter().skip(1).fold(v[0].clone(), div)
}
fn equals_(_symt: Rc<SymbolTable>, v: ~[~LispValue]) -> ~LispValue {
match v {
[a, b] => {
if a == b { ~Num(1.0) }
else { nil() }
}
_ => fail!("invalid operands to =")
}
}
/// Initializes standard library functions
pub fn init_std(symt: Rc<SymbolTable>) {
bind(symt, ~"id", ~BIF(~"id", 1, ~[~"x"], id_));
bind(symt, ~"print", ~BIF(~"print", 1, ~[~"msg"], print_));
bind(symt, ~"cons", ~BIF(~"cons", 2, ~[~"x", ~"y"], cons_));
bind(symt, ~"car", ~BIF(~"car", 1, ~[~"x"], car_));
bind(symt, ~"cdr", ~BIF(~"cdr", 1, ~[~"x"], cdr_));
bind(symt, ~"+", ~BIF(~"+", -1, ~[], plus_));
bind(symt, ~"*", ~BIF(~"*", -1, ~[], mul_));
bind(symt, ~"-", ~BIF(~"-", -1, ~[], minus_));
bind(symt, ~"/", ~BIF(~"/", -1, ~[], div_));
bind(symt, ~"=", ~BIF(~"=", 2, ~[~"x", ~"y"], equals_));
bind(symt, ~"true", ~Num(1.0));
bind(symt, ~"nil", nil());
}
fn apply(symt: Rc<SymbolTable>, f: ~LispValue, args: ~[~LispValue]) -> ~LispValue {
match *f {
BIF(name, arity, fnargs, bif) => {
// apply built-in function
if arity > 0 && fnargs.len() as int != arity {
fail!("function '{:s}' requires {:d} arguments, but it received {:u} arguments",
name, arity, args.len())
}
bif(symt, args)
}
Fn(fnargs, body) => {
// apply a defined function
if args.len() != fnargs.len() {
fail!("function requires {:u} arguments, but it received {:u} arguments",
fnargs.len(), args.len())
}
// bind its arguments in the environemnt and evaluate its body
for (name,value) in fnargs.iter().zip(args.iter()) {
bind(symt, name.clone(), value.clone());
}
eval(symt, *body)
}
v => fail!("") //fail!("apply: need function, received {}", v)
}
}
/// Evaluates an s-expression and returns a value.
pub fn eval(symt: Rc<SymbolTable>, input: sexpr::Value) -> ~LispValue {
match input {
sexpr::List(v) => {
if(v.len() == 0) {
fail!("eval given empty list")
}
// evaluate a list as a function call
match v {
[sexpr::Atom(~"quote"), arg] => from_sexpr(&arg),
[sexpr::Atom(~"def"), name, value] => {
// bind a value to an identifier
let ident = match name {
sexpr::Atom(s) => s,
sexpr::Str(s) => s,
_ => fail!("def requires an atom or a string")
};
bind(symt, ident, eval(symt, value));
nil()
},
[sexpr::Atom(~"cond"), ..conds] => {
//let conds = conds.iter().map(|x: &sexpr::Value| from_sexpr(x));
for cond in conds.iter() {
match *cond {
sexpr::List([ref c, ref e]) => {
if eval(symt, c.clone()).as_bool() {
return eval(symt, e.clone())
}
}
_ => fail!("cond: need list of (condition expression)")
}
}
nil()
}
[sexpr::Atom(~"eval"), ..args] => {
// takes an argument, evaluates it (like a function does)
// and then uses that as an argument to eval().
// e.g. (= (eval (quote (+ 1 2))) 3)
assert!(args.len() == 1);
eval(symt, to_sexpr(eval(symt, args[0].clone())))
}
[sexpr::Atom(~"fn"), sexpr::List(args), body] => {
// construct a function
let args_ = args.iter().map(|x| {
match x {
&sexpr::Atom(ref s) => s.clone(),
_ => fail!("fn: arguments need to be atoms")
}
}).collect();
~Fn(args_, ~body)
}
[ref fnval, ..args] => {
let f = eval(symt, fnval.clone());
let xargs = args.map(|x| eval(symt, x.clone())); // eval'd args
apply(symt, f, xargs)
}
_ => fail!("eval: requires a variable or an application"),
}
}
sexpr::Atom(v) => {
// variable
lookup(symt, v)
}
_ => from_sexpr(&input) // return non-list values as they are
}
}
#[cfg(test)]
mod test {
use super::{SymbolTable, eval, init_std, new_symt, nil, Num, Str, Fn, List, Atom};
use sexpr;
use sexpr::from_str;
use std::rc::Rc;
fn read(input: &str) -> sexpr::Value {
from_str(input).unwrap()
}
#[test]
fn test_eval() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("123")), ~Num(123.0));
assert_eq!(eval(symt, read("(id 123)")), ~Num(123.0));
assert_eq!(eval(symt, read("(id (id (id 123)))")), ~Num(123.0));
// should fail: assert_eq!(eval(&mut symt, read("(1 2 3)")), ~List(~[Num(1.0), Num(2.0), Num(3.0)]));
}
#[test]
fn test_str() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(id \"hi\")")), ~Str(~"hi"));
assert_eq!(eval(symt, read("(car (cons \"a\" \"b\"))")), ~Str(~"a"));
// string concatenation
assert_eq!(eval(symt, read("(+ \"hi\" \" there\")")), ~Str(~"hi there"));
assert_eq!(eval(symt, read("(+ \"hi\" \" there\" \" variadic\")")), ~Str(~"hi there variadic"));
}
#[test]
fn test_cons() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(cons 1 2)")), ~List(~[Num(1.0), Num(2.0)]));
assert_eq!(eval(symt, read("(cons 1 (cons 2 3))")), ~List(~[Num(1.0),
List(~[Num(2.0), Num(3.0)])]));
}
#[test]
fn test_car() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(car (cons 1 2))")), ~Num(1.0));
}
#[test]
fn test_cdr() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(cdr (cons 1 2))")), ~Num(2.0));
assert_eq!(eval(symt, read("(cdr (cons 1 (cons 2 3)))")), ~List(~[Num(2.0), Num(3.0)]));
}
#[test]
fn test_arithmetic() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(+ 1 3)")), ~Num(4.0));
assert_eq!(eval(symt, read("(+ 1.5 3)")), ~Num(4.5));
assert_eq!(eval(symt, read("(+ 5 -3)")), ~Num(2.0));
assert_eq!(eval(symt, read("(- 5 3)")), ~Num(2.0));
assert_eq!(eval(symt, read("(- 3 5)")), ~Num(-2.0));
assert_eq!(eval(symt, read("(- 5 -3)")), ~Num(8.0));
assert_eq!(eval(symt, read("(* 2 5)")), ~Num(10.0));
assert_eq!(eval(symt, read("(* 2 -5)")), ~Num(-10.0));
assert_eq!(eval(symt, read("(/ 10 2)")), ~Num(5.0));
assert_eq!(eval(symt, read("(/ 10 -2)")), ~Num(-5.0));
assert_eq!(eval(symt, read("(+ 6 (+ 1 3))")), ~Num(10.0));
assert_eq!(eval(symt, read("(- 6 (- 3 2))")), ~Num(5.0));
assert_eq!(eval(symt, read("(+ 1 (+ 2 3) 4)")), ~Num(10.0));
assert_eq!(eval(symt, read("(+ 5)")), ~Num(5.0));
assert_eq!(eval(symt, read("(+ -5)")), ~Num(-5.0));
}
#[test]
fn test_quote() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(quote 5)")), ~Num(5.0));
assert_eq!(eval(symt, read("(quote x)")), ~Atom(~"x"));
assert_eq!(eval(symt, read("(quote (1 2 3))")), ~List(~[Num(1.0), Num(2.0), Num(3.0)]));
assert_eq!(eval(symt, read("(quote (x y z))")), ~List(~[Atom(~"x"), Atom(~"y"), Atom(~"z")]))
assert_eq!(eval(symt, read("(quote (quote x))")), ~List(~[Atom(~"quote"), Atom(~"x")]));
assert_eq!(eval(symt, read("(+ (quote 1) 2)")), ~Num(3.0));
//assert_eq!(eval(symt, read("(quote 1 2 3 4 5)")), ~Num(5.0));
}
#[test]
fn test_def() {
let mut symt = Rc::new(new_symt());
init_std(symt);
eval(symt, read("(def x 5)"));
eval(symt, read("(def y 10)"));
assert_eq!(eval(symt, read("x")), ~Num(5.0));
assert_eq!(eval(symt, read("y")), ~Num(10.0));
assert_eq!(eval(symt, read("(+ x y)")), ~Num(15.0));
}
#[test]
fn test_fn() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(fn () ())")), ~Fn(~[], ~sexpr::List(~[])));
assert_eq!(eval(symt, read("(fn (x) (x))")), ~Fn(~[~"x"], ~sexpr::List(~[sexpr::Atom(~"x")])));
eval(symt, read("(def f (fn (x) (+ 1 x)))"));
assert_eq!(eval(symt, read("f")), ~Fn(~[~"x"],
~sexpr::List(~[sexpr::Atom(~"+"), sexpr::Num(1.0), sexpr::Atom(~"x")])));
assert_eq!(eval(symt, read("(f 5)")), ~Num(6.0));
}
#[test]
fn test_apply_fn() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("((fn () 0))")), ~Num(0.0));
assert_eq!(eval(symt, read("((fn (x) x) 5)")), ~Num(5.0));
}
#[test]
fn test_cond() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(cond (true 2) (nil 3))")), ~Num(2.0));
assert_eq!(eval(symt, read("(cond (nil 2) (true 3))")), ~Num(3.0));
assert_eq!(eval(symt, read("(cond (nil 2) (true 3) (true 4))")), ~Num(3.0));
}
#[test]
fn test_equals() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(= 1 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= 1.0 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= 1 2)")), nil());
assert_eq!(eval(symt, read("(= true 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= nil (quote ()))")), ~Num(1.0));
assert_eq!(eval(symt, read("(= nil nil)")), ~Num(1.0));
assert_eq!(eval(symt, read("(= nil true)")), nil());
assert_eq!(eval(symt, read("(= \"a\" \"a\")")), ~Num(1.0));
assert_eq!(eval(symt, read("(= \"a\" \"b\")")), nil());
assert_eq!(eval(symt, read("(= (quote (1 2 3)) (quote (1 2 3)))")), ~Num(1.0));
}
#[test]
fn test_factorial() {
let mut symt = Rc::new(new_symt());
init_std(symt);
eval(symt, read("(def fac (fn (n) (cond ((= n 0) 1) (true (* n (fac (- n 1)))))))"));
assert_eq!(eval(symt, read("(fac 10)")), ~Num(3628800.0));
}
#[test]
fn test_eval_fn() {
let mut symt = Rc::new(new_symt());
init_std(symt);
assert_eq!(eval(symt, read("(eval 1)")), ~Num(1.0));
assert_eq!(eval(symt, read("(eval \"hi\")")), ~Str(~"hi"));
assert_eq!(eval(symt, read("(eval (quote (+ 1 2)))")), ~Num(3.0));
assert_eq!(eval(symt, read("(eval (quote ( (fn () 0) )))")), ~Num(0.0));
}
}
#[ignore(test)]
#[main]
fn main() {
// A simple REPL
let mut stdinReader = std::io::buffered::BufferedReader::new(std::io::stdin());
let mut symt = Rc::new(new_symt());
init_std(symt);
loop {
print("> ");
let line = stdinReader.read_line();
match line {
Some(~".q") => break,
Some(~".newsym") => {
// use a fresh symbol table
symt = Rc::new(new_symt());
init_std(symt);
println("ok");
}
Some(line) => {
match sexpr::from_str(line) {
Some(sexpr) => println(eval(symt, sexpr).to_str()),
None => println("syntax error")
}
}
None => ()
}
}
}