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
use ketos::{Value,
FromValue,
FromValueRef,
ForeignValue,
ExecError,
};
use std::fmt::Debug;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::collections::HashMap;
use treeerror::{TreeError, TreeErrorKind};
#[derive(Clone, Debug)]
struct OptionVecWrapper<T: 'static + Sized + Clone + Debug>(Option<Vec<T>>);
impl<T: 'static + Sized + Clone + Debug> OptionVecWrapper<T> {
fn wrap(w: Option<Vec<T>>) -> OptionVecWrapper<T> {
OptionVecWrapper(w)
}
}
impl<T: 'static + Sized + Clone + Debug> Deref for OptionVecWrapper<T> {
type Target = Option<Vec<T>>;
fn deref(&self) -> &Option<Vec<T>> {
&self.0
}
}
impl<T: 'static + Sized + Clone + Debug> DerefMut for OptionVecWrapper<T> {
fn deref_mut(&mut self) -> &mut Option<Vec<T>> {
&mut self.0
}
}
impl<T: 'static + Sized + Clone + Debug> From<OptionVecWrapper<T>> for Value {
fn from(v: OptionVecWrapper<T>) -> Self {
Value::new_foreign(v)
}
}
impl<T: 'static + Sized + Clone + Debug> ForeignValue for OptionVecWrapper<T> {
fn type_name(&self) -> &'static str { "OptionVecWrapper" }
}
impl<T: 'static + Sized + Clone + Debug> FromValue for OptionVecWrapper<T> {
fn from_value(v: Value) -> Result<Self, ExecError> {
match v {
Value::Foreign(fv) => {
match ForeignValue::downcast_rc(fv) {
Ok(v) => {
match Rc::try_unwrap(v) {
Ok(v) => Ok(v),
Err(rc) => Ok((*rc).clone()),
}
}
Err(rc) => {
Err(ExecError::expected("OptionVecWrapper", &Value::Foreign(rc)))
}
}
}
ref v => Err(ExecError::expected("OptionVecWrapper", v))
}
}
}
impl<'value, T: 'static + Sized + Clone + Debug> FromValueRef<'value> for &'value OptionVecWrapper<T> {
fn from_value_ref(v: &'value Value) -> Result<Self, ExecError> {
if let Value::Foreign(ref fv) = *v {
if let Some(v) = fv.downcast_ref() {
return Ok(v);
}
}
Err(ExecError::expected("OptionVecWrapper", v))
}
}
#[derive(Clone, Debug, ForeignValue, FromValueClone, FromValueRef)]
pub enum Expression<T: 'static + Clone + Debug> {
Operator(fn(Vec<T>) -> T),
Variable(String),
Constant(T),
}
impl<T: 'static + Clone + Debug> From<Expression<T>> for Value {
fn from(v: Expression<T>) -> Self {
Value::new_foreign(v)
}
}
#[derive(Clone, Debug, ForeignValue, FromValueClone, FromValueRef)]
struct TreeBackend<T: 'static + Clone + Debug> {
data: Expression<T>,
links: OptionVecWrapper<Tree<T>>,
}
impl<T: 'static + Clone + Debug> TreeBackend<T> {
fn new(ex: Expression<T>) -> TreeBackend<T> {
TreeBackend { data: ex, links: OptionVecWrapper::<Tree<T>>::wrap(None) }
}
fn link(&mut self, b: Vec<Tree<T>>) {
self.links = OptionVecWrapper::wrap(Some(b));
}
fn data(&self) -> &Expression<T> {
&self.data
}
fn children(&self) -> &Option<Vec<Tree<T>>> {
&self.links
}
}
impl<T: 'static + Clone + Debug> From<TreeBackend<T>> for Value {
fn from(v: TreeBackend<T>) -> Self {
Value::new_foreign(v)
}
}
#[derive(Clone, Debug)]
struct RcWrapper<T: 'static + Sized + Clone + Debug>(Rc<T>);
impl<T: 'static + Sized + Clone + Debug> RcWrapper<T> {
fn wrap(w: Rc<T>) -> RcWrapper<T> {
RcWrapper(w)
}
}
impl<T: 'static + Sized + Clone + Debug> Deref for RcWrapper<T> {
type Target = Rc<T>;
fn deref(&self) -> &Rc<T> {
&self.0
}
}
impl<T: 'static + Sized + Clone + Debug> DerefMut for RcWrapper<T> {
fn deref_mut(&mut self) -> &mut Rc<T> {
&mut self.0
}
}
impl<T: 'static + Sized + Clone + Debug> From<RcWrapper<T>> for Value {
fn from(v: RcWrapper<T>) -> Self {
Value::new_foreign(v)
}
}
impl<T: 'static + Sized + Clone + Debug> ForeignValue for RcWrapper<T> {
fn type_name(&self) -> &'static str { "RcWrapper" }
}
impl<T: 'static + Sized + Clone + Debug> FromValue for RcWrapper<T> {
fn from_value(v: Value) -> Result<Self, ExecError> {
match v {
Value::Foreign(fv) => {
match ForeignValue::downcast_rc(fv) {
Ok(v) => {
match Rc::try_unwrap(v) {
Ok(v) => Ok(v),
Err(rc) => Ok((*rc).clone()),
}
}
Err(rc) => {
Err(ExecError::expected("RcWrapper", &Value::Foreign(rc)))
}
}
}
ref v => Err(ExecError::expected("RcWrapper", v))
}
}
}
impl<'value, T: 'static + Sized + Clone + Debug> FromValueRef<'value> for &'value RcWrapper<T> {
fn from_value_ref(v: &'value Value) -> Result<Self, ExecError> {
if let Value::Foreign(ref fv) = *v {
if let Some(v) = fv.downcast_ref() {
return Ok(v);
}
}
Err(ExecError::expected("RcWrapper", v))
}
}
#[derive(Clone, Debug, ForeignValue, FromValueClone, FromValueRef, StructValue)]
pub struct Tree<T: 'static + Sized + Clone + Debug> {
t: RcWrapper<TreeBackend<T>>
}
impl<T: 'static + Sized + Clone + Debug> Tree<T> {
pub fn new(ex: Expression<T>) -> Tree<T> {
Tree { t: RcWrapper::wrap(Rc::new(TreeBackend::new(ex))) }
}
pub fn accumulate(&self, vars: &HashMap<String, T>) -> Result<T, TreeError> {
let mut yeta = Vec::<T>::new();
for i in self.post_iter() {
match i.data() {
&Expression::Operator(ref f) => {
let minks = match i.children() {
&Some(ref m) => m,
&None => { panic!("Operator found no operands"); },
};
let s = yeta.len() - minks.len();
let eta = yeta.split_off(s);
yeta.push(f(eta));
},
&Expression::Variable(ref v) => match vars.get(v) {
Some(val) => yeta.push(val.clone()),
None => { return Err(TreeError::create(TreeErrorKind::VarNotFound)); },
},
&Expression::Constant(ref c) => yeta.push(c.clone()),
};
}
match yeta.pop() {
Some(r) => Ok(r),
None => { panic!("Accumulation failed unexpectedly"); },
}
}
pub fn link(&mut self, b: Vec<Tree<T>>) {
Rc::make_mut(&mut self.t).link(b);
}
pub fn data(&self) -> &Expression<T> {
&self.t.data()
}
pub fn children(&self) -> &Option<Vec<Tree<T>>> {
&self.t.children()
}
pub fn post_iter(&self) -> TreePostIter<T> {
let mut ps = Vec::<usize>::new();
ps.push(0);
let mut ts = Vec::<&Tree<T>>::new();
ts.push(self);
TreePostIter {
pos_stack: ps,
tree_stack: ts,
}
}
}
impl<T: 'static + Clone + Debug> From<Tree<T>> for Value {
fn from(v: Tree<T>) -> Self {
Value::new_foreign(v)
}
}
pub struct TreePostIter<'a, T: 'static + Clone + Debug> {
pos_stack: Vec<usize>,
tree_stack: Vec<&'a Tree<T>>,
}
impl<'a, T: 'static + Clone + Debug> Iterator for TreePostIter<'a, T> {
type Item = &'a Tree<T>;
fn next(&mut self) -> Option<&'a Tree<T>> {
loop {
let clen: usize;
{
let nbr = match self.tree_stack.last() {
Some(tr) => tr,
None => return None,
};
clen = match nbr.children() {
&Some(ref vc) => vc.len(),
&None => 0,
};
}
if self.pos_stack[self.pos_stack.len() - 1] < clen {
if let &Some(ref vc) = self.tree_stack[self.tree_stack.len() - 1].children() {
self.tree_stack.push(&vc[self.pos_stack[self.pos_stack.len() - 1]]);
self.pos_stack.push(0);
continue;
}
else {
panic!("Iteration failed unexpectedly");
}
}
else if self.pos_stack[self.pos_stack.len() - 1] == clen {
let s = self.pos_stack.len() - 1;
self.pos_stack[s] += 1;
break;
}
self.tree_stack.pop();
if 0 == self.tree_stack.len() {
return None;
}
self.pos_stack.pop();
let s = self.pos_stack.len() - 1;
self.pos_stack[s] += 1;
}
Some(self.tree_stack[self.tree_stack.len() - 1])
}
}