-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathreduce.rs
84 lines (81 loc) · 2.97 KB
/
reduce.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
use super::syntax::{Node};
use super::environment::{Environment};
pub trait Reduce {
fn reducible(&self) -> bool;
fn reduce(&self, environment: &mut Environment) -> Box<Node>;
}
impl Reduce for Node {
fn reducible(&self) -> bool {
match *self {
Node::Number(_) | Node::Boolean(_) | Node::DoNothing => false,
_ => true,
}
}
fn reduce(&self, environment: &mut Environment) -> Box<Node> {
match *self {
Node::Add(ref l, ref r) => {
if l.reducible() {
Node::add(l.reduce(environment), r.clone())
} else if r.reducible() {
Node::add(l.clone(), r.reduce(environment))
} else {
Node::number(l.value() + r.value())
}
}
Node::Multiply(ref l, ref r) => {
if l.reducible() {
Node::multiply(l.reduce(environment), r.clone())
} else if r.reducible() {
Node::multiply(l.clone(), r.reduce(environment))
} else {
Node::number(l.value() * r.value())
}
}
Node::LessThan(ref l, ref r) => {
if l.reducible() {
Node::lessthan(l.reduce(environment), r.clone())
} else if r.reducible() {
Node::lessthan(l.clone(), r.reduce(environment))
} else {
Node::boolean(l.value() < r.value())
}
}
Node::Variable(ref name) => {
environment.get(&name)
}
Node::Assign(ref name, ref expr) => {
if expr.reducible() {
Node::assign(name, expr.reduce(environment))
} else {
environment.add(name, expr.clone());
Node::donothing()
}
}
Node::If(ref condition, ref consequence, ref alternative) => {
if condition.reducible() {
Node::if_cond_else(condition.reduce(environment), consequence.clone(), alternative.clone())
} else {
if condition.condition() {
consequence.clone()
} else {
alternative.clone()
}
}
}
Node::Sequence(ref head, ref more) => {
match **head {
Node::DoNothing => more.clone(),
_ => Node::sequence(head.reduce(environment), more.clone()),
}
}
Node::While(ref cond, ref body) => {
Node::if_cond_else(
cond.clone(),
Node::sequence(body.clone(), Box::new(self.clone())),
Node::donothing()
)
}
_ => panic!("Non reducible type found: {}", *self)
}
}
}