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
use std::collections::{HashSet};
use std::default::{Default};
use std::fmt;
use std::hash;
use environment::{ActivationPtr, RootedActivationPtr};
use eval::{Meaning, TrampolineResult};
use heap::{ArenaPtr, GcThing, Heap, IterGcThing, Rooted, RootedStringPtr,
StringPtr, ToGcThing, Trace};
use primitives::{PrimitiveFunction};
#[derive(Copy, Eq, Hash, PartialEq)]
pub struct Cons {
car: Value,
cdr: Value,
}
impl Default for Cons {
fn default() -> Cons {
Cons {
car: Value::EmptyList,
cdr: Value::EmptyList,
}
}
}
impl Cons {
pub fn car(&self, heap: &mut Heap) -> RootedValue {
Rooted::new(heap, self.car)
}
pub fn cdr(&self, heap: &mut Heap) -> RootedValue {
Rooted::new(heap, self.cdr)
}
pub fn set_car(&mut self, car: &RootedValue) {
self.car = **car;
}
pub fn set_cdr(&mut self, cdr: &RootedValue) {
self.cdr = **cdr;
}
}
impl Trace for Cons {
fn trace(&self) -> IterGcThing {
let mut results = vec!();
if let Some(car) = self.car.to_gc_thing() {
results.push(car);
}
if let Some(cdr) = self.cdr.to_gc_thing() {
results.push(cdr);
}
results.into_iter()
}
}
pub type ConsPtr = ArenaPtr<Cons>;
impl ToGcThing for ConsPtr {
fn to_gc_thing(&self) -> Option<GcThing> {
Some(GcThing::from_cons_ptr(*self))
}
}
pub type RootedConsPtr = Rooted<ConsPtr>;
pub struct Procedure {
pub arity: u32,
pub body: Option<Box<Meaning>>,
pub act: Option<ActivationPtr>,
}
impl Default for Procedure {
fn default() -> Procedure {
Procedure {
body: None,
act: None,
arity: 0,
}
}
}
impl Trace for Procedure {
fn trace(&self) -> IterGcThing {
vec!(GcThing::from_activation_ptr(self.act.expect(
"Should never trace an uninitialized Procedure"))).into_iter()
}
}
impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for Procedure {
fn hash(&self, state: &mut S) {
self.arity.hash(state);
self.act.hash(state);
self.body.as_ref()
.expect("Should never hash an uninitialized Procedure")
.hash(state);
}
}
pub type ProcedurePtr = ArenaPtr<Procedure>;
impl ToGcThing for ProcedurePtr {
fn to_gc_thing(&self) -> Option<GcThing> {
Some(GcThing::from_procedure_ptr(*self))
}
}
pub type RootedProcedurePtr = Rooted<ProcedurePtr>;
#[derive(Copy)]
pub struct Primitive {
function: PrimitiveFunction,
name: &'static str,
}
impl PartialEq for Primitive {
fn eq(&self, rhs: &Self) -> bool {
self.function as usize == rhs.function as usize
}
}
impl Eq for Primitive { }
impl<S: hash::Writer + hash::Hasher> hash::Hash<S> for Primitive {
fn hash(&self, state: &mut S) {
let u = self.function as usize;
u.hash(state);
}
}
impl Primitive {
#[inline]
pub fn call(&self, heap: &mut Heap, args: Vec<RootedValue>) -> TrampolineResult {
(self.function)(heap, args)
}
}
impl fmt::Debug for Primitive {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name)
}
}
#[derive(Copy, Eq, Hash, PartialEq, Debug)]
pub enum Value {
EmptyList,
Pair(ConsPtr),
String(StringPtr),
Symbol(StringPtr),
Integer(i64),
Boolean(bool),
Character(char),
Procedure(ProcedurePtr),
Primitive(Primitive),
}
impl Value {
pub fn new_integer(i: i64) -> Value {
Value::Integer(i)
}
pub fn new_boolean(b: bool) -> Value {
Value::Boolean(b)
}
pub fn new_character(c: char) -> Value {
Value::Character(c)
}
pub fn new_pair(heap: &mut Heap,
car: &RootedValue,
cdr: &RootedValue) -> RootedValue {
let mut cons = heap.allocate_cons();
cons.set_car(car);
cons.set_cdr(cdr);
Rooted::new(heap, Value::Pair(*cons))
}
pub fn new_procedure(heap: &mut Heap,
arity: u32,
act: &RootedActivationPtr,
body: Meaning) -> RootedValue {
let mut procedure = heap.allocate_procedure();
procedure.arity = arity;
procedure.act = Some(**act);
procedure.body = Some(Box::new(body));
Rooted::new(heap, Value::Procedure(*procedure))
}
pub fn new_primitive(name: &'static str,
function: PrimitiveFunction) -> Value {
Value::Primitive(Primitive {
name: name,
function: function
})
}
pub fn new_string(heap: &mut Heap, str: String) -> RootedValue {
let mut value = heap.allocate_string();
value.clear();
value.push_str(str.as_slice());
Rooted::new(heap, Value::String(*value))
}
pub fn new_symbol(heap: &mut Heap, str: RootedStringPtr) -> RootedValue {
Rooted::new(heap, Value::Symbol(*str))
}
}
impl Value {
pub fn car(&self, heap: &mut Heap) -> Option<RootedValue> {
match *self {
Value::Pair(ref cons) => Some(cons.car(heap)),
_ => None,
}
}
pub fn cdr(&self, heap: &mut Heap) -> Option<RootedValue> {
match *self {
Value::Pair(ref cons) => Some(cons.cdr(heap)),
_ => None,
}
}
pub fn is_pair(&self) -> bool {
match *self {
Value::Pair(_) => true,
_ => false,
}
}
pub fn is_atom(&self) -> bool {
!self.is_pair()
}
pub fn to_symbol(&self, heap: &mut Heap) -> Option<RootedStringPtr> {
match *self {
Value::Symbol(sym) => Some(Rooted::new(heap, sym)),
_ => None,
}
}
pub fn to_pair(&self, heap: &mut Heap) -> Option<RootedConsPtr> {
match *self {
Value::Pair(cons) => Some(Rooted::new(heap, cons)),
_ => None,
}
}
pub fn to_procedure(&self, heap: &mut Heap) -> Option<RootedProcedurePtr> {
match *self {
Value::Procedure(p) => Some(Rooted::new(heap, p)),
_ => None,
}
}
pub fn to_integer(&self) -> Option<i64> {
match *self {
Value::Integer(ref i) => Some(*i),
_ => None,
}
}
pub fn len(&self) -> Result<u64, ()> {
match *self {
Value::EmptyList => Ok(0),
Value::Pair(p) => {
let cdr_len = try!(p.cdr.len());
Ok(cdr_len + 1)
},
_ => Err(()),
}
}
pub fn iter(&self) -> ConsIterator {
ConsIterator {
val: *self
}
}
}
impl ToGcThing for Value {
fn to_gc_thing(&self) -> Option<GcThing> {
match *self {
Value::String(str) => Some(GcThing::from_string_ptr(str)),
Value::Symbol(sym) => Some(GcThing::from_string_ptr(sym)),
Value::Pair(cons) => Some(GcThing::from_cons_ptr(cons)),
Value::Procedure(p) => Some(GcThing::from_procedure_ptr(p)),
_ => None,
}
}
}
fn print(f: &mut fmt::Formatter, val: &Value, seen: &mut HashSet<ConsPtr>) -> fmt::Result {
match *val {
Value::EmptyList => write!(f, "()"),
Value::Pair(ref cons) => {
try!(write!(f, "("));
try!(print_pair(f, cons, seen));
write!(f, ")")
},
Value::String(ref str) => {
try!(write!(f, "\""));
try!(write!(f, "{}", **str));
write!(f, "\"")
},
Value::Symbol(ref s) => write!(f, "{}", **s),
Value::Integer(ref i) => write!(f, "{}", i),
Value::Boolean(ref b) => {
write!(f, "{}", if *b {
"#t"
} else {
"#f"
})
},
Value::Character(ref c) => match *c {
'\n' => write!(f, "#\\newline"),
'\t' => write!(f, "#\\tab"),
' ' => write!(f, "#\\space"),
_ => write!(f, "#\\{}", c),
},
Value::Procedure(ref p) => write!(f, "#<procedure {:?}>", p),
Value::Primitive(ref p) => write!(f, "#<procedure {:?}>", p),
}
}
fn print_pair(f: &mut fmt::Formatter, cons: &ConsPtr, seen: &mut HashSet<ConsPtr>) -> fmt::Result {
if seen.contains(cons) {
return write!(f, "<cyclic value>");
}
seen.insert(*cons);
try!(print(f, &cons.car, seen));
if let Value::Pair(rest) = cons.cdr {
if seen.contains(&rest) {
return write!(f, " . <cyclic value>");
}
}
match cons.cdr {
Value::EmptyList => Ok(()),
Value::Pair(ref cdr) => {
try!(write!(f, " "));
print_pair(f, cdr, seen)
},
ref val => {
try!(write!(f, " . "));
print(f, val, seen)
},
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
print(f, self, &mut HashSet::new())
}
}
pub type RootedValue = Rooted<Value>;
pub type SchemeResult = Result<RootedValue, String>;
#[derive(Copy)]
pub struct ConsIterator {
val: Value
}
impl Iterator for ConsIterator {
type Item = Result<Value, ()>;
fn next(&mut self) -> Option<Result<Value, ()>> {
match self.val {
Value::EmptyList => None,
Value::Pair(cons) => {
let Cons { car, cdr } = *cons;
self.val = cdr;
Some(Ok(car))
},
_ => Some(Err(())),
}
}
}
pub fn list(heap: &mut Heap, values: &[RootedValue]) -> RootedValue {
list_helper(heap, &mut values.iter())
}
fn list_helper<'a, T: Iterator<Item=&'a RootedValue>>(heap: &mut Heap,
values: &mut T) -> RootedValue {
match values.next() {
None => Rooted::new(heap, Value::EmptyList),
Some(car) => {
let rest = list_helper(heap, values);
Value::new_pair(heap, car, &rest)
},
}
}
impl Cons {
pub fn cddr(&self, heap: &mut Heap) -> SchemeResult {
self.cdr.cdr(heap).ok_or("bad cddr".to_string())
}
pub fn cdddr(&self, heap: &mut Heap) -> SchemeResult {
let cddr = try!(self.cddr(heap));
cddr.cdr(heap).ok_or("bad cdddr".to_string())
}
pub fn cadr(&self, heap: &mut Heap) -> SchemeResult {
self.cdr.car(heap).ok_or("bad cadr".to_string())
}
pub fn caddr(&self, heap: &mut Heap) -> SchemeResult {
let cddr = try!(self.cddr(heap));
cddr.car(heap).ok_or("bad caddr".to_string())
}
pub fn cadddr(&self, heap: &mut Heap) -> SchemeResult {
let cdddr = try!(self.cdddr(heap));
cdddr.car(heap).ok_or("bad caddr".to_string())
}
}
#[cfg(test)]
mod tests {
use eval::{evaluate_file};
use heap::{Heap};
#[test]
fn test_print_cycle() {
let heap = &mut Heap::new();
evaluate_file(heap, "./tests/test_print_cycle.scm")
.ok()
.expect("Should be able to eval a file.");
assert!(true, "Shouldn't get stuck in an infinite loop printing a cyclic value");
}
}