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
extern crate serde_json;

use std::{borrow::Borrow, fmt, result::Result as StdResult};

use crate::base::types::ArcType;

use crate::{
    api::{Getable, OpaqueValue, ValueRef, VmInt, VmType},
    thread::{ActiveThread, RootedThread, Thread, ThreadInternal},
    ExternModule, Result, Variants,
};

use crate::serde::de::{self, DeserializeState, MapAccess, SeqAccess, Visitor};

pub fn load(vm: &Thread) -> Result<ExternModule> {
    fn deserialize(value: crate::api::WithVM<&str>) -> StdResult<JsonValue, String> {
        let crate::api::WithVM { vm, value: input } = value;
        let mut context = vm.current_context();
        JsonValue::deserialize_state(&mut context, &mut serde_json::Deserializer::from_str(input))
            .map_err(|err| err.to_string())
    }

    fn serialize<F>(value: crate::api::WithVM<Value>, formatter: F) -> StdResult<String, String>
    where
        F: serde_json::ser::Formatter,
    {
        let crate::api::WithVM { vm, value: input } = value;

        let mut output = Vec::new();
        SerializeState::serialize_state(
            &input,
            &mut serde_json::Serializer::with_formatter(&mut output, formatter),
            vm,
        )
        .map_err(|err| err.to_string())?;

        // serde_json outputs valid UTF-8
        unsafe { Ok(String::from_utf8_unchecked(output)) }
    }

    ExternModule::new(
        vm,
        record! {
            deserialize => primitive!(
                1,
                "std.json.prim.deserialize",
                deserialize
            ),
            serialize => primitive!(
                1,
                "std.json.prim.serialize",
                |v| serialize(v, serde_json::ser::CompactFormatter)
            ),
            serialize_pretty => primitive!(
                1,
                "std.json.prim.serialize_pretty",
                |v| serialize(v, serde_json::ser::PrettyFormatter::new())
            ),
        },
    )
}

impl VmType for serde_json::Value {
    type Type = Self;
    fn make_type(vm: &Thread) -> ArcType {
        JsonValue::make_type(vm)
    }
}

impl<'vm> crate::api::Pushable<'vm> for serde_json::Value {
    fn vm_push(self, context: &mut ActiveThread<'vm>) -> Result<()> {
        use serde_json::Value::*;
        let tag = match self {
            Null => {
                context.context().push_new_data(0, 0)?;
                return Ok(());
            }
            Bool(b) => {
                b.vm_push(context)?;
                1
            }
            Number(n) => {
                if let Some(i) = n.as_i64() {
                    i.vm_push(context)?;
                    2
                } else if let Some(i) = n.as_u64() {
                    i.vm_push(context)?;
                    2
                } else if let Some(i) = n.as_f64() {
                    i.vm_push(context)?;
                    3
                } else {
                    return Err(format!("Unable to marshal serde_json::Number({})", n).into());
                }
            }
            String(s) => {
                s.vm_push(context)?;
                4
            }
            Array(a) => {
                a.vm_push(context)?;
                5
            }
            Object(o) => {
                crate::api::to_gluon_map(o, context)?;
                6
            }
        };
        context.context().push_new_data(tag, 1)?;
        Ok(())
    }
}

impl<'vm, 'value> crate::api::Getable<'vm, 'value> for serde_json::Value {
    impl_getable_simple!();

    fn from_value(vm: &'vm Thread, value: Variants<'value>) -> Self {
        match value.as_ref() {
            ValueRef::Data(data) => match data.tag() {
                0 => serde_json::Value::Null,
                1 => serde_json::Value::Bool(bool::from_value(vm, data.get_variant(0).unwrap())),
                2 => serde_json::Value::Number(
                    VmInt::from_value(vm, data.get_variant(0).unwrap()).into(),
                ),
                3 => serde_json::Value::Number(
                    serde_json::Number::from_f64(f64::from_value(vm, data.get_variant(0).unwrap()))
                        .unwrap(),
                ),
                4 => {
                    serde_json::Value::String(String::from_value(vm, data.get_variant(0).unwrap()))
                }
                5 => serde_json::Value::Array(Vec::from_value(vm, data.get_variant(0).unwrap())),
                6 => {
                    let mut map = Default::default();
                    let inner = data.get_variant(0).unwrap();
                    crate::api::from_gluon_map(&mut map, vm, inner);
                    serde_json::Value::Object(map)
                }
                _ => ice!("ValueRef has a wrong tag: {}", data.tag()),
            },
            _ => ice!("ValueRef is not a std.json.Value"),
        }
    }
}

#[derive(Pushable, Getable, SerializeState)]
#[serde(serialize_state = "Thread")]
#[gluon(gluon_vm)]
#[serde(untagged)]
pub enum Value {
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    String(#[serde(state)] JsonString),
    Array(#[serde(state)] Vec<JsonValue>),
    Object(#[serde(state)] ::std::collections::BTreeMap<JsonString, JsonValue>),
}

#[derive(SerializeState, Ord, Eq, PartialEq, PartialOrd, Getable, Pushable)]
#[serde(serialize_state = "Thread")]
#[gluon(gluon_vm)]
pub struct JsonString(OpaqueValue<RootedThread, str>);

impl VmType for JsonString {
    type Type = String;
}

impl ::std::ops::Deref for JsonString {
    type Target = str;

    fn deref(&self) -> &str {
        &self.0
    }
}

impl Borrow<str> for JsonString {
    fn borrow(&self) -> &str {
        self
    }
}

impl<'de> de::DeserializeState<'de, ActiveThread<'de>> for JsonString {
    fn deserialize_state<D>(
        thread: &mut ActiveThread<'de>,
        deserializer: D,
    ) -> StdResult<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        struct StringVisitor<'a, 'vm: 'a>(&'a mut ActiveThread<'vm>);

        impl<'a, 'de> Visitor<'de> for StringVisitor<'a, 'de> {
            type Value = JsonString;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a string")
            }

            #[inline]
            fn visit_str<E>(self, value: &str) -> StdResult<Self::Value, E>
            where
                E: de::Error,
            {
                crate::api::convert_with_active_thread(self.0, value).map_err(E::custom)
            }
        }

        deserializer.deserialize_string(StringVisitor(thread))
    }
}

impl VmType for Value {
    type Type = Self;
    fn make_type(vm: &Thread) -> ArcType {
        JsonValue::make_type(vm)
    }
}

#[derive(VmType)]
#[gluon(vm_type = "std.json.Value")]
#[gluon(gluon_vm)]
pub struct JsonValue(crate::vm::RootedValue<RootedThread>);

impl<'vm> crate::api::Pushable<'vm> for JsonValue {
    fn vm_push(self, context: &mut ActiveThread<'vm>) -> Result<()> {
        crate::api::Pushable::vm_push(self.0, context)
    }
}

impl<'vm, 'value> crate::api::Getable<'vm, 'value> for JsonValue {
    impl_getable_simple!();

    fn from_value(vm: &'vm Thread, value: Variants<'value>) -> Self {
        JsonValue(crate::api::Getable::from_value(vm, value))
    }
}

use crate::serde::ser::{SerializeState, Serializer};
impl SerializeState<Thread> for JsonValue {
    fn serialize_state<S>(&self, serializer: S, vm: &Thread) -> StdResult<S::Ok, S::Error>
    where
        S: Serializer,
    {
        Value::from_value(vm, self.0.get_variant()).serialize_state(serializer, vm)
    }
}

impl<'de> de::DeserializeState<'de, ActiveThread<'de>> for JsonValue {
    fn deserialize_state<D>(
        thread: &mut ActiveThread<'de>,
        deserializer: D,
    ) -> StdResult<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        struct ValueVisitor<'a, 'vm: 'a>(&'a mut ActiveThread<'vm>);

        impl<'a, 'vm> ValueVisitor<'a, 'vm> {
            fn marshal<T>(&mut self, value: T) -> JsonValue
            where
                T: crate::api::Pushable<'vm>,
            {
                let context = &mut *self.0;
                value
                    .vm_push(context)
                    .unwrap_or_else(|err| panic!("{}", err));
                let thread = context.thread();
                let value = context.pop();
                JsonValue(thread.root_value((*value).clone()))
            }
        }

        impl<'a, 'de> Visitor<'de> for ValueVisitor<'a, 'de> {
            type Value = JsonValue;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("any valid JSON value")
            }

            #[inline]
            fn visit_bool<E>(mut self, value: bool) -> StdResult<Self::Value, E> {
                Ok(self.marshal(Value::Bool(value)))
            }

            #[inline]
            fn visit_i64<E>(mut self, value: i64) -> StdResult<Self::Value, E> {
                Ok(self.marshal(Value::Int(value.into())))
            }

            #[inline]
            fn visit_u64<E>(mut self, value: u64) -> StdResult<Self::Value, E> {
                Ok(self.marshal(Value::Int(value as i64)))
            }

            #[inline]
            fn visit_f64<E>(mut self, value: f64) -> StdResult<Self::Value, E> {
                Ok(self.marshal(Value::Float(value)))
            }

            #[inline]
            fn visit_str<E>(mut self, value: &str) -> StdResult<Self::Value, E>
            where
                E: de::Error,
            {
                let value =
                    crate::api::convert_with_active_thread(self.0, value).map_err(E::custom)?;
                Ok(self.marshal(Value::String(value)))
            }

            #[inline]
            fn visit_string<E>(mut self, value: String) -> StdResult<Self::Value, E>
            where
                E: de::Error,
            {
                let value =
                    crate::api::convert_with_active_thread(self.0, value).map_err(E::custom)?;
                Ok(self.marshal(Value::String(value)))
            }

            #[inline]
            fn visit_none<E>(mut self) -> StdResult<Self::Value, E> {
                Ok(self.marshal(Value::Null))
            }

            #[inline]
            fn visit_some<D>(self, deserializer: D) -> StdResult<Self::Value, D::Error>
            where
                D: de::Deserializer<'de>,
            {
                de::DeserializeState::deserialize_state(&mut *self.0, deserializer)
            }

            #[inline]
            fn visit_unit<E>(mut self) -> StdResult<Self::Value, E> {
                Ok(self.marshal(Value::Null))
            }

            #[inline]
            fn visit_seq<V>(mut self, mut visitor: V) -> StdResult<Self::Value, V::Error>
            where
                V: SeqAccess<'de>,
            {
                let mut vec = Vec::new();

                while let Some(elem) = visitor.next_element_seed(de::Seed::new(&mut *self.0))? {
                    vec.push(elem);
                }

                Ok(self.marshal(Value::Array(vec)))
            }

            fn visit_map<V>(mut self, mut visitor: V) -> StdResult<Self::Value, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut values = ::std::collections::BTreeMap::new();

                while let Some(key) = visitor.next_key_seed(de::Seed::new(&mut *self.0))? {
                    let value = visitor.next_value_seed(de::Seed::new(&mut *self.0))?;
                    values.insert(key, value);
                }

                Ok(self.marshal(Value::Object(values)))
            }
        }

        deserializer.deserialize_any(ValueVisitor(thread))
    }
}