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
extern crate serde;
use crate::util::GeneratorIterator;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::Generator;
use std::slice::{Iter, IterMut};

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Float(pub f32);

#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum Prim {
  Integer(i32),
  Float(Float),
  String(String),
}

#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum Value {
  Splice(usize),
  Prim(Prim),
  Record { head: String, props: Vec<Value> },
}

impl PartialEq for Float {
  fn eq(&self, other: &Float) -> bool {
    return self.0.to_bits() == other.0.to_bits();
  }
}

impl Eq for Float {}

impl Hash for Float {
  fn hash<H: Hasher>(&self, hasher: &mut H) {
    self.0.to_bits().hash(hasher);
  }
}

impl Display for Float {
  fn fmt(&self, f: &mut Formatter) -> fmt::Result {
    return self.0.fmt(f);
  }
}

impl Display for Prim {
  fn fmt(&self, f: &mut Formatter) -> fmt::Result {
    match self {
      Prim::Integer(x) => x.fmt(f),
      Prim::Float(x) => x.fmt(f),
      Prim::String(x) => write!(
        f,
        "\"{}\"",
        x.chars()
          .flat_map(|c| c.escape_default())
          .collect::<String>()
      ),
    }
  }
}

impl Prim {
  pub fn type_str(&self) -> &'static str {
    match self {
      Prim::Integer(_) => "integer",
      Prim::Float(_) => "float",
      Prim::String(_) => "string",
    }
  }
}

impl Display for Value {
  fn fmt(&self, f: &mut Formatter) -> fmt::Result {
    match self {
      Value::Splice(idx) => write!(f, "\\{}", idx),
      Value::Prim(prim) => prim.fmt(f),
      Value::Record { head, props } => {
        write!(f, "{}[", head)?;
        let mut first = true;
        for prop in props {
          if first {
            first = false;
          } else {
            write!(f, ", ")?;
          }
          prop.fmt(f)?;
        }
        return write!(f, "]");
      }
    }
  }
}

#[allow(dead_code)]
impl Value {
  pub fn unit() -> Value {
    return Value::Record {
      head: String::from("Unit"),
      props: Vec::default(),
    };
  }

  pub fn true_() -> Value {
    return Value::Record {
      head: String::from("True"),
      props: Vec::default(),
    };
  }

  pub fn false_() -> Value {
    return Value::Record {
      head: String::from("False"),
      props: Vec::default(),
    };
  }

  pub fn nil() -> Value {
    return Value::Record {
      head: String::from("Nil"),
      props: Vec::default(),
    };
  }

  pub fn bool(x: bool) -> Value {
    if x {
      return Value::true_();
    } else {
      return Value::false_();
    }
  }

  pub fn cons(first: Value, rest: Value) -> Value {
    return Value::Record {
      head: String::from("Cons"),
      props: vec![first, rest],
    };
  }

  pub fn hole(idx: i32) -> Value {
    return Value::Record {
      head: String::from("Hole"),
      props: vec![Value::Prim(Prim::Integer(idx))],
    };
  }

  pub fn option(val: Option<Value>) -> Value {
    match val {
      None => {
        return Value::Record {
          head: String::from("None"),
          props: Vec::default(),
        };
      }
      Some(val) => {
        return Value::Record {
          head: String::from("Some"),
          props: vec![val],
        };
      }
    };
  }

  pub fn list<I: Iterator<Item = Value>>(vals: &mut I) -> Value {
    match vals.next() {
      None => return Value::nil(),
      Some(fst) => return Value::cons(fst, Value::list(vals)),
    };
  }

  pub fn record_head_to_fun(head: &String) -> Option<(String, String)> {
    if let Some(sep_pos) = head.chars().position(|c| c == '_') {
      let (lib, name) = head.split_at(sep_pos);
      let name = &name[1..];
      return Some((String::from(lib), String::from(name)));
    } else {
      return None;
    }
  }

  pub fn is_splice(&self) -> bool {
    if let Value::Splice(_) = self {
      return true;
    } else {
      return false;
    }
  }

  pub fn is_hole(&self) -> bool {
    if let Value::Record { head, .. } = self {
      return head == "Hole";
    } else {
      return false;
    }
  }

  pub fn matches(&self, other: &Value) -> bool {
    if self.is_hole() {
      return true;
    }
    if let Value::Record { head, props } = self {
      if let Value::Record {
        head: other_head,
        props: other_props,
      } = other
      {
        return head == other_head
          && Iterator::zip(props.iter(), other_props.iter())
            .all(|(prop, other_prop)| prop.matches(other_prop));
      }
    } else {
      return self == other;
    }
    return false;
  }

  pub fn subst(&mut self, old: &Value, new: &Value) {
    if self == old {
      *self = new.clone();
    } else if let Value::Record { props, .. } = self {
      for prop in props {
        prop.subst(old, new);
      }
    }
  }

  pub fn fill_splices<F: Copy + Fn(usize) -> Value>(&mut self, f: F) {
    match self {
      Value::Splice(idx) => *self = f(*idx),
      Value::Prim(_) => (),
      Value::Record { head: _, props } => {
        for prop in props {
          prop.fill_splices(f);
        }
      }
    };
  }

  pub fn flush(&mut self) {
    self.fill_splices(|idx| Value::hole(idx as i32));
  }

  pub fn modify_children<F: FnMut(&mut Value) -> bool>(&mut self, f: &mut F) {
    if let Value::Record { props, .. } = self {
      for prop in props {
        if f(prop) {
          prop.modify_children(f);
        }
      }
    }
  }

  pub fn breadth_first(&self) -> GeneratorIterator<impl Generator<Yield = &Value, Return = ()>> {
    return GeneratorIterator(move || {
      if let Value::Record { props, .. } = self {
        let mut yielded = true;
        let mut level = 0;
        let mut props_stack: Vec<Iter<Value>> = Vec::new();
        while yielded {
          yielded = false;
          level = level + 1;
          props_stack.push(props.iter());
          while let Option::Some(top_props) = props_stack.last_mut() {
            if let Option::Some(top_prop) = top_props.next() {
              if props_stack.len() == level {
                yield top_prop;
                yielded = true;
              } else {
                if let Value::Record {
                  props: top_sub_props,
                  ..
                } = top_prop
                {
                  props_stack.push(top_sub_props.iter())
                }
              }
            } else {
              props_stack.pop();
            }
          }
        }
      }
    });
  }

  pub fn breadth_first_mut(
    &mut self,
  ) -> GeneratorIterator<impl Generator<Yield = &mut Value, Return = ()>> {
    return GeneratorIterator(move || unsafe {
      if let Value::Record { props, .. } = self {
        let props = props as *mut Vec<Value>;
        let mut yielded = true;
        let mut level = 0;
        let mut props_stack: Vec<IterMut<Value>> = Vec::new();
        while yielded {
          yielded = false;
          level = level + 1;
          props_stack.push((&mut *props).iter_mut());
          while let Option::Some(top_props) = props_stack.last_mut() {
            if let Option::Some(top_prop) = top_props.next() {
              if props_stack.len() == level {
                yield top_prop;
                yielded = true;
              } else {
                if let Value::Record {
                  props: top_sub_props,
                  ..
                } = top_prop
                {
                  props_stack.push(top_sub_props.iter_mut())
                }
              }
            } else {
              props_stack.pop();
            }
          }
        }
      }
    });
  }

  pub fn sub_splices(&self) -> Vec<usize> {
    let mut res: Vec<usize> = Vec::new();
    if let Value::Splice(idx) = self {
      res.push(*idx);
    }
    for child in self.breadth_first() {
      if let Value::Splice(idx) = child {
        res.push(*idx);
      }
    }
    return res;
  }

  pub fn any_sub<F: Fn(&Value) -> bool>(&self, pred: F) -> bool {
    if pred(self) {
      return true;
    }
    for child in self.breadth_first() {
      if pred(child) {
        return true;
      }
    }
    return false;
  }
}

#[test]
fn test_breadth_first_mut() {
  let mut x = Value::Record {
    head: String::from("Foo"),
    props: vec![
      Value::Record {
        head: String::from("Bar"),
        props: vec![
          Value::Record {
            head: String::from("Baz"),
            props: vec![Value::Prim(Prim::Integer(2)), Value::Prim(Prim::Integer(3))],
          },
          Value::Prim(Prim::Integer(1)),
          Value::Record {
            head: String::from("Qux"),
            props: vec![Value::Prim(Prim::Integer(4))],
          },
        ],
      },
      Value::Prim(Prim::Integer(0)),
    ],
  };
  for i in 0..5 {
    let mut cur_idx = i;
    for prop in x.breadth_first_mut() {
      if let Value::Prim(Prim::Integer(idx)) = prop {
        if *idx >= 0 {
          assert_eq!(cur_idx, *idx);
          *prop = Value::Record {
            head: String::from("Lower"),
            props: vec![Value::Prim(Prim::Integer(-(*idx + 1)))],
          };
          cur_idx = cur_idx + 1;
        }
      }
    }
    for prop in x.breadth_first_mut() {
      if let Value::Prim(Prim::Integer(idx)) = prop {
        if *idx < 0 {
          *idx = -*idx;
        }
      }
    }
  }
}