asciidork_ast/
json.rs

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
use std::collections::HashMap;
use std::fmt::{Debug, Write};
use std::ops::{Deref, DerefMut};

use crate::internal::*;

pub trait Json {
  fn to_json_in(&self, buf: &mut JsonBuf);

  fn to_json(&self) -> String {
    let mut buf = JsonBuf(String::with_capacity(self.size_hint()));
    self.to_json_in(&mut buf);
    buf.0
  }

  fn size_hint(&self) -> usize {
    256
  }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct JsonBuf(String);

impl Deref for JsonBuf {
  type Target = String;
  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

impl DerefMut for JsonBuf {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.0
  }
}

impl JsonBuf {
  pub fn begin_obj(&mut self, ty: &str) {
    self.push_str(r#"{"type":""#);
    self.push_str(ty);
    self.push('"');
  }

  pub fn finish_obj(&mut self) {
    self.push('}');
  }

  pub fn start_obj_enum_type(&mut self, ty: &str) {
    self.begin_obj(ty);
    self.push_str(r#","variant":""#);
  }

  pub fn push_obj_enum_type<V: Debug>(&mut self, ty: &str, value: V) {
    self.start_obj_enum_type(ty);
    self.push_simple_variant(value);
    self.push_str("\"}");
  }

  pub fn push_simple_variant<V: Debug>(&mut self, variant: V) {
    debug_assert!(format!("{:?}", variant)
      .chars()
      .all(|c| c.is_ascii_alphanumeric()));
    write!(self, "{:?}", variant).unwrap();
  }

  pub fn add_member<T: Json>(&mut self, name: &str, value: &T) {
    self.push_str(",\"");
    self.push_str(name);
    self.push_str("\":");
    value.to_json_in(self);
  }

  pub fn add_option_member<T: Json>(&mut self, name: &str, value: Option<&T>) {
    if let Some(value) = value {
      self.add_member(name, value);
    }
  }
}

impl Json for str {
  fn to_json_in(&self, buf: &mut JsonBuf) {
    buf.push('"');
    for c in self.chars() {
      match c {
        '"' => buf.push_str(r#"\""#),
        '\n' => buf.push_str(r#"\\n"#),
        _ => buf.push(c),
      }
    }
    buf.push('"');
  }
}

impl Json for &str {
  fn to_json_in(&self, buf: &mut JsonBuf) {
    (*self).to_json_in(buf);
  }
}

impl Json for BumpString<'_> {
  fn to_json_in(&self, buf: &mut JsonBuf) {
    self.as_str().to_json_in(buf);
  }
}

impl Json for usize {
  fn to_json_in(&self, buf: &mut JsonBuf) {
    write!(buf, "{}", self).unwrap();
  }
}

impl Json for u8 {
  fn to_json_in(&self, buf: &mut JsonBuf) {
    write!(buf, "{}", self).unwrap();
  }
}

impl Json for u16 {
  fn to_json_in(&self, buf: &mut JsonBuf) {
    write!(buf, "{}", self).unwrap();
  }
}

impl Json for bool {
  fn to_json_in(&self, buf: &mut JsonBuf) {
    buf.push_str(if *self { "true" } else { "false" });
  }
}

impl<T: Json> Json for Option<T> {
  fn to_json_in(&self, buf: &mut JsonBuf) {
    match self {
      Some(value) => value.to_json_in(buf),
      None => buf.push_str("null"),
    }
  }
}

impl<T: Json> Json for [T] {
  fn to_json_in(&self, buf: &mut JsonBuf) {
    if self.is_empty() {
      buf.push_str("[]");
      return;
    }
    buf.push('[');
    for item in self.iter() {
      item.to_json_in(buf);
      buf.push(',');
    }
    buf.pop();
    buf.push(']');
  }
}

impl<T: Json> Json for &[T] {
  fn to_json_in(&self, buf: &mut JsonBuf) {
    (*self).to_json_in(buf);
  }
}

impl Json for String {
  fn to_json_in(&self, buf: &mut JsonBuf) {
    self.as_str().to_json_in(buf);
  }
}
impl<K: Json, V: Json> Json for HashMap<K, V> {
  fn to_json_in(&self, buf: &mut JsonBuf) {
    (&self).to_json_in(buf);
  }
}

impl<K: Json, V: Json> Json for &HashMap<K, V> {
  fn to_json_in(&self, buf: &mut JsonBuf) {
    buf.push('{');
    let mut first = true;
    for (key, value) in *self {
      if first {
        first = false;
      } else {
        buf.push(',');
      }
      key.to_json_in(buf);
      buf.push(':');
      value.to_json_in(buf);
    }
    buf.push('}');
  }
}

impl<T: Json> Json for BumpVec<'_, T> {
  fn to_json_in(&self, buf: &mut JsonBuf) {
    self.as_slice().to_json_in(buf);
  }
}

#[cfg(test)]
#[macro_export]
macro_rules! assert_json {
  ($input:expr, $expected:expr$(,)?) => {{
    let json = $input.to_json();
    test_utils::expect_eq!(json, jsonxf::minimize($expected).unwrap());
    // assert that the JSON is valid
    assert!(serde_json::from_str::<serde_json::Value>(&json).is_ok());
  }};
}

#[cfg(test)]
mod tests {
  use super::*;
  use test_utils::*;

  #[test]
  fn test_inline_to_json() {
    let cases = [
      (
        Inline::Discarded,
        r#"{
          "type": "Inline",
          "variant": "Discarded"
        }"#,
      ),
      (
        Inline::CurlyQuote(CurlyKind::LeftDouble),
        r#"{
          "type": "Inline",
          "variant": "CurlyQuote",
          "kind": {
            "type": "CurlyKind",
            "variant": "LeftDouble"
          }
        }"#,
      ),
      (
        Inline::Bold(nodes![node!(Inline::Discarded, 0..1)]),
        r#"{
          "type": "Inline",
          "variant": "Bold",
          "children": [
            {
              "type": "InlineNode",
              "content": {
                "type": "Inline",
                "variant": "Discarded"
              }
            }
          ]
        }"#,
      ),
      (
        Inline::Macro(MacroNode::Image {
          flow: Flow::Block,
          target: src!("cat.jpg", 0..0),
          attrs: AttrList::new(SourceLocation::new(0, 0), leaked_bump()),
        }),
        r#"{
          "type": "Inline",
          "variant": "Macro",
          "macro": {
            "type": "MacroNode",
            "variant": "Image",
            "flow": {
              "type": "Flow",
              "variant": "Block"
            },
            "target": "cat.jpg"
          }
        }"#,
      ),
    ];
    for (input, expected) in cases.iter() {
      assert_json!(input, expected);
    }
  }
}