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
use super::Node;
use gc::{Finalize, Trace};
use std::fmt;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Trace, Finalize, PartialEq)]
pub struct If {
cond: Box<Node>,
body: Box<Node>,
else_node: Option<Box<Node>>,
}
impl If {
pub fn cond(&self) -> &Node {
&self.cond
}
pub fn body(&self) -> &Node {
&self.body
}
pub fn else_node(&self) -> Option<&Node> {
self.else_node.as_ref().map(Box::as_ref)
}
pub fn new<C, B, E, OE>(condition: C, body: B, else_node: OE) -> Self
where
C: Into<Node>,
B: Into<Node>,
E: Into<Node>,
OE: Into<Option<E>>,
{
Self {
cond: Box::new(condition.into()),
body: Box::new(body.into()),
else_node: else_node.into().map(E::into).map(Box::new),
}
}
pub(super) fn display(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result {
write!(f, "if ({}) ", self.cond())?;
match self.else_node() {
Some(else_e) => {
self.body().display(f, indent)?;
f.write_str(" else ")?;
else_e.display(f, indent)
}
None => self.body().display(f, indent),
}
}
}
impl fmt::Display for If {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.display(f, 0)
}
}
impl From<If> for Node {
fn from(if_stm: If) -> Node {
Self::If(if_stm)
}
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Trace, Finalize, PartialEq)]
pub struct ConditionalOp {
condition: Box<Node>,
if_true: Box<Node>,
if_false: Box<Node>,
}
impl ConditionalOp {
pub fn cond(&self) -> &Node {
&self.condition
}
pub fn if_true(&self) -> &Node {
&self.if_true
}
pub fn if_false(&self) -> &Node {
&self.if_false
}
pub fn new<C, T, F>(condition: C, if_true: T, if_false: F) -> Self
where
C: Into<Node>,
T: Into<Node>,
F: Into<Node>,
{
Self {
condition: Box::new(condition.into()),
if_true: Box::new(if_true.into()),
if_false: Box::new(if_false.into()),
}
}
}
impl fmt::Display for ConditionalOp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} ? {} : {}",
self.cond(),
self.if_true(),
self.if_false()
)
}
}
impl From<ConditionalOp> for Node {
fn from(cond_op: ConditionalOp) -> Node {
Self::ConditionalOp(cond_op)
}
}