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
#[macro_use]
extern crate lazy_static;

mod primes;

use cirru_parser::{Cirru, CirruWriterOptions};
pub use primes::Edn;
use regex::Regex;
use std::collections::HashMap;
use std::collections::HashSet;

/// parse Cirru code into data
pub fn parse(s: &str) -> Result<Edn, String> {
  match cirru_parser::parse(s) {
    Ok(xs) => {
      if xs.len() == 1 {
        match &xs[0] {
          Cirru::Leaf(s) => Err(format!("expected expr for data, got leaf: {}", s)),
          Cirru::List(_) => extract_cirru_edn(&xs[0]),
        }
      } else {
        Err(format!("Expected 1 expr for edn, got length {}: {:?} ", xs.len(), xs))
      }
    }
    Err(e) => Err(e),
  }
}

fn extract_cirru_edn(node: &Cirru) -> Result<Edn, String> {
  match node {
    Cirru::Leaf(s) => match s.as_str() {
      "nil" => Ok(Edn::Nil),
      "true" => Ok(Edn::Bool(true)),
      "false" => Ok(Edn::Bool(false)),
      "" => Err(String::from("empty string is invalid for edn")),
      s1 => match s1.chars().next().unwrap() {
        '\'' => Ok(Edn::Symbol(s1[1..].to_owned())),
        ':' => Ok(Edn::Keyword(s1[1..].to_owned())),
        '"' | '|' => Ok(Edn::Str(s1[1..].to_owned())),
        _ => {
          if matches_float(s1) {
            let f: f64 = s1.parse().unwrap();
            Ok(Edn::Number(f))
          } else {
            Err(format!("unknown token for edn value: {:?}", s1))
          }
        }
      },
    },
    Cirru::List(xs) => {
      if xs.is_empty() {
        Err(String::from("empty expr is invalid for edn"))
      } else {
        match &xs[0] {
          Cirru::Leaf(s) => match s.as_str() {
            "quote" => {
              if xs.len() == 2 {
                Ok(Edn::Quote(xs[1].to_owned()))
              } else {
                Err(String::from("missing edn quote value"))
              }
            }
            "do" => {
              if xs.len() == 2 {
                extract_cirru_edn(&xs[1])
              } else {
                Err(String::from("missing edn do value"))
              }
            }
            "::" => {
              if xs.len() == 3 {
                Ok(Edn::Tuple(
                  Box::new(extract_cirru_edn(&xs[1])?),
                  Box::new(extract_cirru_edn(&xs[2])?),
                ))
              } else {
                Err(String::from("tuple expected 2 values"))
              }
            }
            "[]" => {
              let mut ys: Vec<Edn> = vec![];
              for (idx, x) in xs.iter().enumerate() {
                if idx > 0 {
                  match extract_cirru_edn(x) {
                    Ok(v) => ys.push(v),
                    Err(v) => return Err(v),
                  }
                }
              }
              Ok(Edn::List(ys))
            }
            "#{}" => {
              let mut ys: HashSet<Edn> = HashSet::new();
              for (idx, x) in xs.iter().enumerate() {
                if idx > 0 {
                  match extract_cirru_edn(x) {
                    Ok(v) => {
                      ys.insert(v);
                    }
                    Err(v) => return Err(v),
                  }
                }
              }
              Ok(Edn::Set(ys))
            }
            "{}" => {
              let mut zs: HashMap<Edn, Edn> = HashMap::new();
              for (idx, x) in xs.iter().enumerate() {
                if idx > 0 {
                  match x {
                    Cirru::Leaf(s) => return Err(format!("expected a pair, invalid map entry: {}", s)),
                    Cirru::List(ys) => {
                      if ys.len() == 2 {
                        match (extract_cirru_edn(&ys[0]), extract_cirru_edn(&ys[1])) {
                          (Ok(k), Ok(v)) => {
                            zs.insert(k, v);
                          }
                          (Err(e), _) => return Err(format!("invalid map entry `{}` from `{}`", e, &ys[0])),
                          (Ok(k), Err(e)) => return Err(format!("invalid map entry for `{}`, got {}", k, e)),
                        }
                      }
                    }
                  }
                }
              }
              Ok(Edn::Map(zs))
            }
            "%{}" => {
              if xs.len() >= 3 {
                let name = match xs[1].to_owned() {
                  Cirru::Leaf(s) => s,
                  Cirru::List(e) => return Err(format!("expected record name in string: {:?}", e)),
                };
                let mut fields: Vec<String> = vec![];
                let mut values: Vec<Edn> = vec![];
                for (idx, x) in xs.iter().enumerate() {
                  if idx > 1 {
                    match x {
                      Cirru::Leaf(s) => return Err(format!("expected record, invalid record entry: {}", s)),
                      Cirru::List(ys) => {
                        if ys.len() == 2 {
                          match (&ys[0], extract_cirru_edn(&ys[1])) {
                            (Cirru::Leaf(s), Ok(v)) => {
                              fields.push(s.to_owned());
                              values.push(v);
                            }
                            (Cirru::Leaf(s), Err(e)) => {
                              return Err(format!("invalid record value for `{}`, got: {}", s, e))
                            }
                            (Cirru::List(zs), _) => return Err(format!("invalid list as record key: {:?}", zs)),
                          }
                        }
                      }
                    }
                  }
                }
                Ok(Edn::Record(name, fields, values))
              } else {
                Err(String::from("insufficient items for edn record"))
              }
            }
            a => Err(format!("invalid operator for edn: {}", a)),
          },
          Cirru::List(a) => Err(format!("invalid nodes for edn: {:?}", a)),
        }
      }
    }
  }
}

lazy_static! {
  static ref RE_FLOAT: Regex = Regex::new("^-?[\\d]+(\\.[\\d]+)?$").unwrap(); // TODO special cases not handled
}

fn matches_float(x: &str) -> bool {
  RE_FLOAT.is_match(x)
}

fn assemble_cirru_node(data: &Edn) -> Cirru {
  match data {
    Edn::Nil => Cirru::Leaf(String::from("nil")),
    Edn::Bool(v) => {
      let mut leaf = String::from("");
      leaf.push_str(&v.to_string());
      Cirru::Leaf(leaf)
    }
    Edn::Number(n) => {
      let mut leaf = String::from("");
      leaf.push_str(&n.to_string());
      Cirru::Leaf(leaf)
    }
    Edn::Symbol(s) => {
      let mut leaf = String::from("'");
      leaf.push_str(s);
      Cirru::Leaf(leaf)
    }
    Edn::Keyword(s) => {
      let mut leaf = String::from(":");
      leaf.push_str(s);
      Cirru::Leaf(leaf)
    }
    Edn::Str(s) => {
      let mut leaf = String::from("|");
      leaf.push_str(s);
      Cirru::Leaf(leaf)
    }
    Edn::Quote(v) => Cirru::List(vec![Cirru::Leaf(String::from("quote")), (*v).to_owned()]),
    Edn::List(xs) => {
      let mut ys: Vec<Cirru> = vec![Cirru::Leaf(String::from("[]"))];
      for x in xs {
        ys.push(assemble_cirru_node(x));
      }
      Cirru::List(ys)
    }
    Edn::Set(xs) => {
      let mut ys: Vec<Cirru> = vec![Cirru::Leaf(String::from("#{}"))];
      for x in xs {
        ys.push(assemble_cirru_node(x));
      }
      Cirru::List(ys)
    }
    Edn::Map(xs) => {
      let mut ys: Vec<Cirru> = vec![Cirru::Leaf(String::from("{}"))];
      for (k, v) in xs {
        ys.push(Cirru::List(vec![assemble_cirru_node(k), assemble_cirru_node(v)]))
      }
      Cirru::List(ys)
    }
    Edn::Record(name, fields, values) => {
      let mut ys: Vec<Cirru> = vec![Cirru::Leaf(String::from("%{}")), Cirru::Leaf(String::from(name))];
      for idx in 0..fields.len() {
        let v = &values[idx];
        ys.push(Cirru::List(vec![
          Cirru::Leaf(fields[idx].to_owned()),
          assemble_cirru_node(v),
        ]));
      }

      Cirru::List(ys)
    }
    Edn::Tuple(tag, v) => {
      let mut ys: Vec<Cirru> = vec![Cirru::Leaf(String::from("::"))];
      ys.push(assemble_cirru_node(&*tag.to_owned()));
      ys.push(assemble_cirru_node(&*v.to_owned()));
      Cirru::List(ys)
    }
  }
}

/// generate string fro, Edn
pub fn format(data: &Edn, use_inline: bool) -> Result<String, String> {
  let options = CirruWriterOptions { use_inline };
  match assemble_cirru_node(data) {
    Cirru::Leaf(s) => cirru_parser::format(
      &[(Cirru::List(vec![Cirru::Leaf(String::from("do")), Cirru::Leaf(s)]))],
      options,
    ),
    Cirru::List(xs) => cirru_parser::format(&[(Cirru::List(xs))], options),
  }
}