-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.rs
1677 lines (1363 loc) · 49.1 KB
/
main.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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::HashMap;
use std::fmt;
use std::fmt::{Write};
use std::cmp; //for max
use std::io; //for IO
type Addr = i32;
type Name = String;
type CoreVariable = Name;
#[derive(Clone, PartialEq, Eq, Debug)]
struct CoreLet {
is_rec: bool,
bindings: Vec<(Name, Box<CoreExpr>)>,
expr: Box<CoreExpr>
}
#[derive(Clone, PartialEq, Eq)]
enum CoreExpr {
//change this?
Variable(Name),
Num(i32),
Application(Box<CoreExpr>, Box<CoreExpr>),
Pack{tag: u32, arity: u32},
Let(CoreLet),
}
impl fmt::Debug for CoreExpr {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
&CoreExpr::Variable(ref name) => write!(fmt, "{}", name),
&CoreExpr::Num(ref num) => write!(fmt, "n_{}", num),
&CoreExpr::Application(ref e1, ref e2) =>
write!(fmt, "({:#?} $ {:#?})", *e1, *e2),
&CoreExpr::Let(CoreLet{ref is_rec, ref bindings, ref expr}) => {
if *is_rec {
try!(write!(fmt, "letrec"));
} else {
try!(write!(fmt, "let"));
}
try!(write!(fmt, " {{\n"));
for &(ref name, ref expr) in bindings {
try!(write!(fmt, "{} = {:#?}\n", name, expr));
}
try!(write!(fmt, "in\n"));
try!(write!(fmt, "{:#?}", expr));
write!(fmt, "}}")
}
&CoreExpr::Pack{ref tag, ref arity} => {
write!(fmt, "Pack(tag: {} arity: {})", tag, arity)
}
}
}
}
#[derive(Clone, PartialEq, Eq)]
struct SupercombDefn {
name: String,
args: Vec<String>,
body: CoreExpr
}
impl fmt::Debug for SupercombDefn {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "{} ", &self.name));
for arg in self.args.iter() {
try!(write!(fmt, "{} ", &arg));
}
try!(write!(fmt, "{{ {:#?} }}", self.body));
Result::Ok(())
}
}
//a core program is a list of supercombinator
//definitions
type CoreProgram = Vec<SupercombDefn>;
//primitive operations on the machine
#[derive(Clone, PartialEq, Eq, Debug)]
enum MachinePrimOp {
Add,
Sub,
Mul,
Div,
Negate,
Construct {
tag: DataTag,
num_args: u32
}
}
type DataTag = i32;
//heap nodes
#[derive(Clone, PartialEq, Eq)]
enum HeapNode {
Application {
fn_addr: Addr,
arg_addr: Addr
},
Supercombinator(SupercombDefn),
Num(i32),
Indirection(Addr),
Primitive(Name, MachinePrimOp),
Data{tag: DataTag, component_addrs: Vec<Addr>}
}
impl fmt::Debug for HeapNode {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
&HeapNode::Application{ref fn_addr, ref arg_addr} => {
write!(fmt, "H-({} $ {})", fn_addr, arg_addr)
}
&HeapNode::Supercombinator(ref sc_defn) => {
write!(fmt, "H-{:#?}", sc_defn)
},
&HeapNode::Num(ref num) => {
write!(fmt, "H-{}", num)
}
&HeapNode::Indirection(ref addr) => {
write!(fmt, "H-indirection-{}", addr)
}
&HeapNode::Primitive(ref name, ref primop) => {
write!(fmt, "H-prim-{} {:#?}", name, primop)
},
&HeapNode::Data{ref tag, ref component_addrs} => {
write!(fmt, "H-data-{} addrs: {:#?}", tag, component_addrs)
}
}
}
}
impl HeapNode {
fn is_data_node(&self) -> bool {
match self {
&HeapNode::Num(_) => true,
_ => false
}
}
}
//unsued for mark 1
// a dump is a vector of stacks
type Dump = Vec<Stack>;
//stack of addresses of nodes. "Spine"
#[derive(Clone,PartialEq,Eq,Debug)]
struct Stack {
stack: Vec<Addr>
}
impl Stack {
fn new() -> Stack {
Stack {
stack: Vec::new(),
}
}
fn len(&self) -> usize {
self.stack.len()
}
fn push(&mut self, addr: Addr) {
self.stack.push(addr)
}
fn pop(&mut self) -> Addr {
self.stack.pop().expect("top of stack is empty")
}
fn peek(&self) -> Addr {
self.stack.last().expect("top of stack is empty to peek").clone()
}
fn iter(&self) -> std::slice::Iter<Addr> {
self.stack.iter()
}
}
//maps names to addresses in the heap
type Bindings = HashMap<Name, Addr>;
//maps addresses to machine Nodes
#[derive(Clone)]
struct Heap {
heap: HashMap<Addr, HeapNode>,
next_addr: Addr
}
impl fmt::Debug for Heap {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let mut keyvals : Vec<(&Addr, &HeapNode)> = self.heap.iter().collect();
keyvals.sort_by(|a, b| a.0.cmp(b.0));
for &(key, val) in keyvals.iter().rev() {
try!(write!(fmt, "\t{} => {:#?}\n", key, val));
}
return Result::Ok(())
}
}
impl Heap {
fn new() -> Heap {
Heap {
heap: HashMap::new(),
next_addr: 0
}
}
//allocate the HeapNode on the heap
fn alloc(&mut self, node: HeapNode) -> Addr {
let addr = self.next_addr;
self.next_addr += 1;
self.heap.insert(addr, node);
addr
}
fn get(&self, addr: &Addr) -> HeapNode {
self.heap
.get(&addr)
.cloned()
.expect(&format!("expected heap node at addess: {}", addr))
}
fn rewrite(&mut self, addr: &Addr, node: HeapNode) {
assert!(self.heap.contains_key(addr),
"asked to rewrite (address: {}) with (node: {:#?}) which does not exist on heap",
addr, node);
self.heap.insert(*addr, node);
}
}
//state of the machine
#[derive(Clone)]
struct MachineOptions {
update_heap_on_sc_eval: bool,
}
#[derive(Clone)]
struct Machine {
stack : Stack,
heap : Heap,
globals: Bindings,
dump: Dump,
options: MachineOptions,
}
type MachineError = String;
fn format_heap_node(m: &Machine, env: &Bindings, node: &HeapNode) -> String {
match node {
&HeapNode::Indirection(addr) => format!("indirection: {}", addr),
&HeapNode::Num(num) => format!("{}", num),
&HeapNode::Primitive(ref name,
ref primop) => format!("prim-{}-{:#?}", name, primop),
&HeapNode::Application{ref fn_addr, ref arg_addr} =>
format!("({} $ {})",
format_heap_node(m, env, &m.heap.get(fn_addr)),
format_heap_node(m, env, &m.heap.get(arg_addr))),
&HeapNode::Supercombinator(ref sc_defn) => {
let mut sc_str = String::new();
write!(&mut sc_str, "{}", sc_defn.name).unwrap();
sc_str
}
&HeapNode::Data{ref tag, ref component_addrs} => {
let mut data_str = String::new();
data_str += &format!("data-{}", tag);
for c in component_addrs.iter() {
data_str +=
&format!("{}", format_heap_node(m, env, &m.heap.get(c)))
}
data_str
}
}
}
fn print_machine(m: &Machine, env: &Bindings) {
fn print_stack(m: &Machine, env: &Bindings, s: &Stack) {
print!( "stack:\n");
print!( "## top ##\n");
for addr in s.iter().rev() {
print!("heap[{}] : {}\n",
*addr,
format_heap_node(m,
env,
&m.heap.get(addr)));
}
print!( "## bottom ##\n");
};
print_stack(m, env, &m.stack);
print!("*** heap: ***\n");
print!("{:#?}", m.heap);
print!("*** dump: ***\n");
for stack in m.dump.iter().rev() {
print_stack(m, env, stack);
}
/*
print!( "\n*** env: ***\n");
let mut env_ordered : Vec<(&Name, &Addr)> = env.iter().collect();
env_ordered.sort_by(|e1, e2| e1.0.cmp(e2.0));
for &(name, addr) in env_ordered.iter() {
print!("{} => {}\n", name, format_heap_node(m, env, &m.heap.get(addr)));
}*/
}
fn get_prelude() -> CoreProgram {
string_to_program("I x = x;\
K x y = x;\
K1 x y = y;\
S f g x = f x (g x);\
compose f g x = f (g x);\
twice f = compose f f\
".to_string()).unwrap()
}
fn get_primitives() -> Vec<(Name, MachinePrimOp)> {
[("+".to_string(), MachinePrimOp::Add),
("-".to_string(), MachinePrimOp::Sub),
("*".to_string(), MachinePrimOp::Mul),
("/".to_string(), MachinePrimOp::Div),
("negate".to_string(), MachinePrimOp::Negate),
].iter().cloned().collect()
}
fn heap_build_initial(sc_defs: CoreProgram, prims: Vec<(Name, MachinePrimOp)>) -> (Heap, Bindings) {
let mut heap = Heap::new();
let mut globals = HashMap::new();
for sc_def in sc_defs.iter() {
//create a heap node for the supercombinator definition
//and insert it
let node = HeapNode::Supercombinator(sc_def.clone());
let addr = heap.alloc(node);
//insert it into the globals, binding the name to the
//heap address
globals.insert(sc_def.name.clone(), addr);
}
for (name, prim_op) in prims.into_iter() {
let addr = heap.alloc(HeapNode::Primitive(name.clone(),
prim_op));
globals.insert(name, addr);
}
(heap, globals)
}
//interreter
impl Machine {
fn new(program: CoreProgram) -> Machine {
//all supercombinators = program + prelude
let mut sc_defs = program.clone();
sc_defs.extend(get_prelude().iter().cloned());
let (initial_heap, globals) = heap_build_initial(sc_defs,
get_primitives());
//get main out of the heap
let main_addr : Addr = match globals.get("main") {
Some(main) => main,
None => panic!("no main found")
}.clone();
Machine {
dump: Vec::new(),
//stack has addr main on top
stack: {
let mut s = Stack::new();
s.push(main_addr);
s
},
globals: globals,
heap: initial_heap,
options: MachineOptions {
update_heap_on_sc_eval: true
}
}
}
//returns bindings of this run
fn step(&mut self) -> Result<Bindings, MachineError>{
//top of stack
let tos_addr : Addr = self.stack.peek();
let heap_val = self.heap.get(&tos_addr);
//there is something on the dump that wants to use this
//data node, so pop it back.
if heap_val.is_data_node() && self.dump.len() > 0 {
self.stack = self.dump
.pop()
.expect("dump should have at least 1 element");
Result::Ok(self.globals.clone())
} else {
self.run_step(&heap_val)
}
}
//make an environment for the execution of the supercombinator
fn make_supercombinator_env(sc_defn: &SupercombDefn,
heap: &Heap,
stack_args:&Vec<Addr>,
globals: &Bindings) -> Bindings {
assert!(stack_args.len() == sc_defn.args.len());
let mut env = globals.clone();
/*
* let f a b c = <body>
*
* if a function call of the form f x y z was made,
* the stack will look like
* ---top---
* f
* f x
* f x y
* f x y z
* --------
*
* the "f" will be popped beforehand (that is part of the contract
* of calling make_supercombinator_env)
*
*
* So, we go down the stack, removing function applications, and
* binding the RHS to the function parameter names.
*
*/
for (arg_name, application_addr) in
sc_defn.args.iter().zip(stack_args.iter()) {
let application = heap.get(application_addr);
let param_addr = match application {
HeapNode::Application{arg_addr, ..} => arg_addr,
_ => panic!(concat!("did not find application node when ",
"unwinding stack for supercombinator"))
};
env.insert(arg_name.clone(), param_addr);
}
env
}
//get a num parameter, or sets up the state of the machine
//to be able to do so
fn setup_get_number_argument(&mut self,
stack_to_dump: Stack,
ap_addr: Addr) -> Option<i32> {
let (arg_addr, fn_addr) = match self.heap.get(&ap_addr) {
HeapNode::Application{arg_addr, fn_addr} => (arg_addr, fn_addr),
other @ _ =>
panic!("expected application at {}, found {:#?}", ap_addr, other)
};
let arg = self.heap.get(&arg_addr);
match arg {
HeapNode::Num(i) => return Some(i),
HeapNode::Indirection(ind_addr) => {
//pop off the application and then create a new
//application that does into the indirection address
self.heap.rewrite(&ap_addr, HeapNode::Application{fn_addr: fn_addr,
arg_addr: ind_addr});
None
}
_ => {
self.dump_stack(stack_to_dump);
self.stack.push(arg_addr);
None
}
}
}
fn run_primitive_negate(&mut self) -> Result<(), MachineError> {
//we need a copy of the stack to push into the dump
let stack_copy = self.stack.clone();
//pop the primitive off
self.stack.pop();
//we rewrite this addres in case of
//a raw number
let neg_ap_addr = self.stack.peek();
//Apply <negprim> <argument>
//look at what argument is and dispatch work
let to_negate_val = match self.setup_get_number_argument(stack_copy,
neg_ap_addr) {
Some(val) => val,
None => return Result::Ok(())
};
self.heap.rewrite(&neg_ap_addr, HeapNode::Num(-to_negate_val));
Result::Ok(())
/*
if let HeapNode::Application{ref arg_addr, ref fn_addr} = self.heap.get(&neg_ap_addr) {
let arg = self.heap.get(arg_addr);
assert!(*fn_addr == negate_prim_addr, concat!("expected the function being called to be",
"the negate primitive"));
match arg {
HeapNode::Num(n) => {
//rewrite the function application (current thing)
self.heap.rewrite(&neg_ap_addr, HeapNode::Num(-n))
}
HeapNode::Indirection(ind_addr) => {
//pop off the application and then create a new
//application that does into the indirection address
self.heap.rewrite(&neg_ap_addr, HeapNode::Application{fn_addr: *fn_addr,
arg_addr: ind_addr});
}
_ => {
self.dump_stack(stack_copy);
self.stack.push(*arg_addr);
}
}
self.globals.clone()
}
else {
panic!("expected application node")
}*/
}
//extractor should return an error if a node cannot have data
//extracted from. It should return None
fn run_num_binop<F>(&mut self, handler: F) -> Result<(), MachineError>
where F: Fn(i32, i32) -> i32 {
let stack_copy = self.stack.clone();
//stack will be like
//top--v
//+
//(+ a)
//(+ a) b
//bottom-^
//fully eval a, b
//then do stuff
//pop off operator
self.stack.pop();
let left_value = {
//pop off left value
let left_ap_addr = self.stack.pop();
match self.setup_get_number_argument(stack_copy.clone(),
left_ap_addr) {
Some(val) => val,
None => return Result::Ok(())
}
};
//do the same process for right argument
//peek (+ a) b
//we peek, since in the case where (+ a) b can be reduced,
//we simply rewrite the node (+ a b) with the final value
//(instead of creating a fresh node)
let binop_ap_addr = self.stack.peek();
let right_value =
match self.setup_get_number_argument(stack_copy,
binop_ap_addr) {
Some(val) => val,
None => return Result::Ok(())
};
self.heap.rewrite(&binop_ap_addr,
HeapNode::Num(handler(left_value,
right_value)));
Result::Ok(())
} //close fn
//TODO: find out what happens when constructor of arity 0 is
//called
fn run_constructor(&mut self,
tag: DataTag,
num_args: u32) -> Result<Addr, MachineError> {
//pop out constructor
let _ = self.stack.pop();
if self.stack.len() < num_args as usize {
return Result::Err(format!("expected to have \
{} arguments to {} \
constructor, found {}",
num_args,
tag,
self.stack.len()));
}
let mut arg_addrs : Vec<Addr> = Vec::new();
//This will be rewritten with the data
//since the fn call would have been something like:
//##top##
//(Constructor)
//(Constructor a)
//(Constructor a $ b)
//(Constructor a b $ c) <- to rewrite
//##bottom##
let mut outermost_constructor_addr_opt = None;
for i in 0..num_args {
match self.heap.get(&self.stack.pop()) {
HeapNode::Application{arg_addr, ..} => {
arg_addrs.push(arg_addr);
outermost_constructor_addr_opt = Some(arg_addr);
},
other @ _ => {
return
Result::Err(format!("expected function application to\
get {} argument, found {:#?}",
i,
other));
}
}
};
let outermost_constructor_addr =
outermost_constructor_addr_opt.expect("expected constructor called\
with arity at least 1");
self.heap.rewrite(&outermost_constructor_addr,
HeapNode::Data{
component_addrs: arg_addrs,
tag: tag
});
Result::Ok(outermost_constructor_addr)
}
fn dump_stack(&mut self, stack: Stack) {
self.dump.push(stack);
self.stack = Stack::new();
}
//actually run_step the computation
fn run_step(&mut self, heap_val: &HeapNode) -> Result<Bindings, MachineError> {
match heap_val {
&HeapNode::Num(n) =>
panic!("number applied as a function: {}", n),
&HeapNode::Data{..} => panic!("cannot run data node, unimplemented"),
&HeapNode::Application{fn_addr, ..} => {
//push function address over the function
self.stack.push(fn_addr);
Result::Ok(self.globals.clone())
}
&HeapNode::Indirection(ref addr) => {
//simply ignore an indirection during execution, and
//push the indirected value on the stack
self.stack.pop();
self.stack.push(*addr);
Result::Ok(self.globals.clone())
}
&HeapNode::Primitive(_, ref prim) => {
match prim {
&MachinePrimOp::Negate => {
try!(self.run_primitive_negate());
Result::Ok(self.globals.clone())
}
&MachinePrimOp::Add => {
try!(self.run_num_binop(|x, y| x + y));
Result::Ok(self.globals.clone())
}
&MachinePrimOp::Sub => {
try!(self.run_num_binop(|x, y| x - y));
Result::Ok(self.globals.clone())
}
&MachinePrimOp::Mul => {
try!(self.run_num_binop(|x, y| x * y));
Result::Ok(self.globals.clone())
}
&MachinePrimOp::Div => {
try!(self.run_num_binop(|x, y| x / y));
Result::Ok(self.globals.clone())
}
&MachinePrimOp::Construct {
tag,
num_args
} => {
try!(self.run_constructor(tag, num_args));
Result::Ok(self.globals.clone())
}
}
}
&HeapNode::Supercombinator(ref sc_defn) => {
//pop the supercombinator
let sc_addr = self.stack.pop();
//the arguments are the stack
//values below the supercombinator. There
//are (n = arity of supercombinator) arguments
let arg_addrs = {
let mut addrs = Vec::new();
for _ in 0..sc_defn.args.len() {
addrs.push(self.stack.pop());
}
addrs
};
let env = Machine::make_supercombinator_env(&sc_defn,
&self.heap,
&arg_addrs,
&self.globals);
let new_alloc_addr = try!(self.instantiate(sc_defn.body.clone(), &env));
self.stack.push(new_alloc_addr);
if self.options.update_heap_on_sc_eval {
//if the function call was (f x y), the stack will be
//f
//f x
//(f x) y <- final address in arg_addrs
//we need to rewrite this heap value
let full_call_addr = {
//if the SC has 0 parameters (a constant), then eval the SC
//and replace the SC itself
if sc_defn.args.len() == 0 {
sc_addr
}
else {
*arg_addrs.last()
.expect(concat!("arguments has no final value ",
"even though the supercombinator ",
"has >= 1 parameter"))
}
};
self.heap.rewrite(&full_call_addr, HeapNode::Indirection(new_alloc_addr));
}
Result::Ok(env)
}
}
}
fn rebind_vars_to_env(old_addr: Addr,
new_addr: Addr,
edit_addr: Addr,
mut heap: &mut Heap) {
match heap.get(&edit_addr) {
HeapNode::Data{..} => panic!("unimplemented rebinding of Data node"),
HeapNode::Application{fn_addr, arg_addr} => {
let new_fn_addr = if fn_addr == old_addr {
new_addr
} else {
fn_addr
};
let new_arg_addr = if arg_addr == old_addr {
new_addr
} else {
arg_addr
};
//if we have not replaced, then recurse
//into the application calls
if fn_addr != old_addr {
Machine::rebind_vars_to_env(old_addr,
new_addr,
fn_addr,
&mut heap);
};
if arg_addr != old_addr {
Machine::rebind_vars_to_env(old_addr,
new_addr,
arg_addr,
&mut heap);
};
heap.rewrite(&edit_addr,
HeapNode::Application{
fn_addr: new_fn_addr,
arg_addr: new_arg_addr
});
},
HeapNode::Indirection(ref addr) =>
Machine::rebind_vars_to_env(old_addr,
new_addr,
*addr,
&mut heap),
HeapNode::Primitive(_, _) => {}
HeapNode::Supercombinator(_) => {}
HeapNode::Num(_) => {},
}
}
fn instantiate(&mut self, expr: CoreExpr, env: &Bindings) -> Result<Addr, MachineError> {
match expr {
CoreExpr::Let(CoreLet{expr: let_rhs, bindings, is_rec}) => {
let mut let_env : Bindings = env.clone();
if is_rec {
//TODO: change this to zip() with range
let mut addr = -1;
//first create dummy indeces for all LHS
for &(ref bind_name, _) in bindings.iter() {
let_env.insert(bind_name.clone(), addr);
addr -= 1;
}
let mut old_to_new_addr: HashMap<Addr, Addr> = HashMap::new();
//instantiate RHS, while storing legit
//LHS addresses
//TODO: cleanup, check if into_iter is sufficient
for &(ref bind_name, ref bind_expr) in bindings.iter() {
let new_addr = try!(self.instantiate(*bind_expr.clone(), &let_env));
let old_addr = try!(let_env
.get(bind_name)
.ok_or(format!("unable to find |{}| in env", bind_name)))
.clone();
old_to_new_addr.insert(old_addr, new_addr);
//insert the "correct" address into the
//let env
let_env.insert(bind_name.clone(), new_addr);
}
for (old, new) in old_to_new_addr.iter() {
for to_edit_addr in old_to_new_addr.values() {
Machine::rebind_vars_to_env(*old,
*new,
*to_edit_addr,
&mut self.heap);
}
}
print!("letrec env:\n {:#?}", let_env);
self.instantiate(*let_rhs, &let_env)
}
else {
for (bind_name, bind_expr) in bindings.into_iter() {
let addr = try!(self.instantiate(*bind_expr, &let_env));
let_env.insert(bind_name.clone(), addr);
}
self.instantiate(*let_rhs, &let_env)
}
}
CoreExpr::Num(x) => Result::Ok(self.heap.alloc(HeapNode::Num(x))),
CoreExpr::Application(fn_expr, arg_expr) => {
let fn_addr = try!(self.instantiate(*fn_expr, env));
let arg_addr = try!(self.instantiate(*arg_expr, env));
Result::Ok(self.heap.alloc(HeapNode::Application {
fn_addr: fn_addr,
arg_addr: arg_addr
}))
},
CoreExpr::Variable(vname) => {
match env.get(&vname) {
Some(addr) => Result::Ok(*addr),
None => Result::Err(format!("unable to find variable in heap: |{}|", vname))
}
},
CoreExpr::Pack{tag, arity} => panic!("instantiate unimplemented \
for CoreExpr::Pack")
}
}
}
fn machine_is_final_state(m: &Machine) -> bool {
assert!(m.stack.len() > 0, "expect stack to have at least 1 node");
if m.stack.len() > 1 {
false
} else {
let dump_empty = m.dump.len() == 0;
m.heap.get(&m.stack.peek()).is_data_node() &&
dump_empty
}
}
//parsing ---
#[derive(Clone, Debug)]
enum ParseError {
NoTokens,
UnknownSymbol,
UnexpectedToken {
expected: Vec<CoreToken>,
found: CoreToken
},
ParseErrorStr(String),
}
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
enum CoreToken {
Let,
LetRec,
In,
Case,
Ident(String),
Equals,
Semicolon,
OpenRoundBracket,
CloseRoundBracket,
OpenCurlyBracket,
CloseCurlyBracket,
Comma,
Integer(String),
Lambda,
Or,
And,
L,
LEQ,
G,
GEQ,
Plus,
Minus,
Mul,
Div,
Pack,
//when you call peek(), it returns this token
//if the token stream is empty.
PeekNoToken
}
#[derive(Clone)]
struct ParserCursor {
tokens: Vec<CoreToken>,
pos: usize,
}
impl ParserCursor {
fn new(tokens: Vec<CoreToken>) -> ParserCursor {
ParserCursor {