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
use crate::primes::Cirru;
use std::fmt;
use std::str;

#[derive(PartialEq, Clone, Copy, fmt::Debug)]
enum WriterNode {
  Nil,
  Leaf,
  SimpleExpr,
  BoxedExpr,
  Expr,
}

const CHAR_CLOSE: char = ')';
const CHAR_OPEN: char = '(';
const ALLOWED_CHARS: &str = "$-:<>[]{}*=+.,\\/!?~_@#&%^|;'";

fn is_a_digit(c: char) -> bool {
  let n = c as usize;
  // ascii table https://tool.oschina.net/commons?type=4
  (48..=57).contains(&n)
}

fn is_a_letter(c: char) -> bool {
  let n = c as usize;
  if (65..=90).contains(&n) {
    return true;
  }
  if (97..=122).contains(&n) {
    return true;
  }
  false
}

fn is_simple_expr(ys: &[Cirru]) -> bool {
  for y in ys {
    match y {
      Cirru::List(_) => return false,
      Cirru::Leaf(_) => (),
    }
  }
  true
}

fn is_boxed(ys: &[Cirru]) -> bool {
  for y in ys {
    if let Cirru::Leaf(_) = y {
      return false;
    }
  }
  true
}

fn is_simple_char(x: char) -> bool {
  is_a_letter(x) || is_a_digit(x)
}

fn is_char_allowed(x: char) -> bool {
  if is_simple_char(x) {
    return true;
  }
  ALLOWED_CHARS.find(x).is_some()
}

fn generate_leaf(s: &str) -> String {
  let mut all_allowed = true;
  for x in s.chars() {
    if !is_char_allowed(x) {
      all_allowed = false;
      break;
    }
  }
  if all_allowed {
    s.to_string()
  } else {
    let mut ret = String::with_capacity(s.len() + 2);
    ret.push('"');
    for c in s.chars() {
      match c {
        '\n' => ret.push_str("\\n"),
        '\t' => ret.push_str("\\t"),
        '\"' => ret.push_str("\\\""),
        '\\' => ret.push_str("\\\\"),
        '\'' => ret.push_str("\\'"),
        _ => ret.push(c),
      }
    }
    ret.push('"');
    ret
  }
}

fn generate_empty_expr() -> String {
  String::from("()")
}

fn generate_inline_expr(xs: &[Cirru]) -> String {
  let mut result = String::from(CHAR_OPEN);

  for (idx, x) in xs.iter().enumerate() {
    if idx > 0 {
      result.push(' ');
    }
    let piece = match x {
      Cirru::Leaf(s) => generate_leaf(s),
      Cirru::List(ys) => generate_inline_expr(ys),
    };
    result.push_str(&piece)
  }

  result.push_str(&CHAR_CLOSE.to_string());
  result
}

/// by 2 spaces
fn push_spaces(buf: &mut String, n: usize) {
  for _ in 0..n {
    buf.push_str("  ");
  }
}

fn render_newline(n: usize) -> String {
  let mut ret = String::with_capacity(n * 2);
  ret.push('\n');
  push_spaces(&mut ret, n);
  ret
}

/// options for writer, `use_inline` for more compact format.
#[derive(Clone, Copy)]
pub struct CirruWriterOptions {
  pub use_inline: bool,
}

fn get_node_kind(cursor: &Cirru) -> WriterNode {
  match cursor {
    Cirru::Leaf(_) => WriterNode::Leaf,
    Cirru::List(xs) => {
      if xs.is_empty() {
        WriterNode::Leaf
      } else if is_simple_expr(xs) {
        WriterNode::SimpleExpr
      } else if is_boxed(xs) {
        WriterNode::BoxedExpr
      } else {
        WriterNode::Expr
      }
    }
  }
}

fn generate_tree(
  xs: &[Cirru],
  insist_head: bool,
  options: CirruWriterOptions,
  base_level: usize,
  in_tail: bool,
) -> Result<String, String> {
  let mut prev_kind = WriterNode::Nil;
  let mut level = base_level;
  let mut result = String::from("");

  for (idx, cursor) in xs.iter().enumerate() {
    let kind = get_node_kind(cursor);
    let next_level = level + 1;
    let child_insist_head = (prev_kind == WriterNode::BoxedExpr) || (prev_kind == WriterNode::Expr);
    let at_tail = idx != 0 && !in_tail && prev_kind == WriterNode::Leaf && idx == xs.len() - 1;

    // println!("\nloop {:?} {:?}", prev_kind, kind);
    // println!("cursor {:?} {} {}", cursor, idx, insist_head);
    // println!("{:?}", result);

    let child: String = match cursor {
      Cirru::Leaf(s) => generate_leaf(s),
      Cirru::List(ys) => {
        if at_tail {
          if ys.is_empty() {
            String::from("$")
          } else {
            let mut ret = String::from("$ ");
            ret.push_str(&generate_tree(ys, false, options, level, at_tail)?);
            ret
          }
        } else if idx == 0 && insist_head {
          generate_inline_expr(ys)
        } else if kind == WriterNode::Leaf {
          if idx == 0 {
            let mut ret = render_newline(level);
            ret.push_str(&generate_empty_expr());
            ret
          } else {
            generate_empty_expr() // special since empty expr is treated as leaf
          }
        } else if kind == WriterNode::SimpleExpr {
          if prev_kind == WriterNode::Leaf {
            generate_inline_expr(ys)
          } else if options.use_inline && prev_kind == WriterNode::SimpleExpr {
            let mut ret = String::from(" ");
            ret.push_str(&generate_inline_expr(ys));
            ret
          } else {
            let mut ret = render_newline(next_level);
            ret.push_str(&generate_tree(ys, child_insist_head, options, next_level, false)?);
            ret
          }
        } else if kind == WriterNode::Expr {
          let content = generate_tree(ys, child_insist_head, options, next_level, false)?;
          if content.starts_with('\n') {
            content
          } else {
            let mut ret = render_newline(next_level);
            ret.push_str(&content);
            ret
          }
        } else if kind == WriterNode::BoxedExpr {
          let content = generate_tree(ys, child_insist_head, options, next_level, false)?;
          if prev_kind == WriterNode::Nil || prev_kind == WriterNode::Leaf || prev_kind == WriterNode::SimpleExpr {
            content
          } else {
            let mut ret = render_newline(next_level);
            ret.push_str(&content);
            ret
          }
        } else {
          return Err(String::from("Unpected condition"));
        }
      }
    };

    let bended = kind == WriterNode::Leaf && (prev_kind == WriterNode::BoxedExpr || prev_kind == WriterNode::Expr);

    let chunk = if at_tail
      || (prev_kind == WriterNode::Leaf && kind == WriterNode::Leaf)
      || (prev_kind == WriterNode::Leaf && kind == WriterNode::SimpleExpr)
      || prev_kind == WriterNode::SimpleExpr && kind == WriterNode::Leaf
    {
      let mut ret = String::from(" ");
      ret.push_str(&child);
      ret
    } else if bended {
      let mut ret = render_newline(next_level);
      ret.push_str(", ");
      ret.push_str(&child);
      ret
    } else {
      child
    };

    result.push_str(&chunk);

    // update writer states

    if kind == WriterNode::SimpleExpr {
      if idx == 0 && insist_head {
        prev_kind = WriterNode::SimpleExpr;
      } else if options.use_inline {
        if prev_kind == WriterNode::Leaf || prev_kind == WriterNode::SimpleExpr {
          prev_kind = WriterNode::SimpleExpr;
        } else {
          prev_kind = WriterNode::Expr;
        }
      } else if prev_kind == WriterNode::Leaf {
        prev_kind = WriterNode::SimpleExpr;
      } else {
        prev_kind = WriterNode::Expr;
      }
    } else {
      prev_kind = kind;
    }

    if bended {
      level += 1;
    }

    // console.log("chunk", JSON.stringify(chunk));
    // console.log("And result", JSON.stringify(result));
  }
  Ok(result)
}

fn generate_statements(ys: &[Cirru], options: CirruWriterOptions) -> Result<String, String> {
  let mut zs = String::from("");
  for y in ys {
    match y {
      Cirru::Leaf(_) => return Err(String::from("expected an exprs at top level")),
      Cirru::List(cs) => {
        zs.push('\n');
        zs.push_str(&generate_tree(cs, true, options, 0, false)?);
        zs.push('\n');
      }
    }
  }
  Ok(zs)
}

/// format Cirru code, use options to control `use_inline` option
pub fn format(xs: &[Cirru], options: CirruWriterOptions) -> Result<String, String> {
  generate_statements(xs, options)
}