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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use std::mem::transmute;

use libquickjs_ng_sys::JSContext;
use serde::de::{
    self, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess,
    Visitor,
};
use serde::{forward_to_deserialize_any, Deserialize};

use crate::utils::deserialize_borrowed_str;
use crate::value::{JsTag, OwnedJsArray, OwnedJsObject, OwnedJsPropertyIterator, OwnedJsValue};

use super::error::{Error, Result};

/// A structure that deserializes JS values into Rust values.
pub struct Deserializer<'de> {
    context: *mut JSContext,
    root: &'de OwnedJsValue,
    paths: Vec<(OwnedJsValue, u32, Option<OwnedJsPropertyIterator>)>,
    current: Option<OwnedJsValue>,
}

impl<'de> Deserializer<'de> {
    fn from_js(context: *mut JSContext, root: &'de OwnedJsValue) -> Self {
        Deserializer {
            context,
            root,
            paths: Vec::new(),
            current: Some(root.clone()),
        }
    }
}

/// Deserialize an instance of type `T` from a JS value.
pub fn from_js<'a, T>(context: *mut JSContext, value: &'a OwnedJsValue) -> Result<T>
where
    T: Deserialize<'a>,
{
    let mut deserializer = Deserializer::from_js(context, value);
    let t = T::deserialize(&mut deserializer)?;
    Ok(t)
}

impl<'de> Deserializer<'de> {
    fn get_current(&self) -> &OwnedJsValue {
        if let Some(current) = self.current.as_ref() {
            current
        } else {
            self.root
        }
    }

    fn next(&mut self) -> Result<Option<()>> {
        let (current, index, obj_iter) = self.paths.last_mut().expect("current must be Some");

        let next = if current.is_array() {
            let current = OwnedJsArray::try_from_value(current.clone()).unwrap();
            let item = current.get_index(*index)?;
            if item.is_some() {
                self.current = item;
                *index += 1;
                Some(())
            } else {
                None
            }
        } else if current.is_object() {
            let obj_iter = obj_iter.as_mut().expect("obj_iter must be Some");
            if let Some(ret) = obj_iter.next() {
                self.current = Some(ret?);
                // index here is useless, but we just keep it for consistency
                *index += 1;
                Some(())
            } else {
                None
            }
        } else {
            return Err(Error::ExpectedArrayOrObject);
        };

        if next.is_some() {
            Ok(next)
        } else {
            Ok(None)
        }
    }

    fn guard_circular_reference(&self, current: &OwnedJsValue) -> Result<()> {
        if let Some(_) = self.paths.iter().find(|(p, _, _)| p == current) {
            Err(Error::CircularReference)
        } else {
            Ok(())
        }
    }

    fn enter_array(&mut self) -> Result<()> {
        let current = self.get_current().clone();

        if current.is_array() {
            self.guard_circular_reference(&current)?;
            self.paths.push((current, 0, None));
            Ok(())
        } else {
            Err(Error::ExpectedArray)
        }
    }

    fn enter_object(&mut self) -> Result<()> {
        let current = self.get_current().clone();

        if current.is_object() {
            let obj = OwnedJsObject::try_from_value(current.clone()).unwrap();
            self.guard_circular_reference(&current)?;
            self.paths.push((current, 0, Some(obj.properties_iter()?)));
            Ok(())
        } else {
            Err(Error::ExpectedObject)
        }
    }

    fn leave(&mut self) {
        if let Some((current, _, _)) = self.paths.pop() {
            self.current = Some(current);
        }
    }

    fn parse_string(&mut self) -> Result<String> {
        let current = self.get_current();
        if current.is_string() {
            current.to_string().map_err(|err| err.into())
        } else {
            Err(Error::ExpectedString)
        }
    }

    fn parse_borrowed_str(&mut self) -> Result<&'de str> {
        let current = self.get_current();
        if current.is_string() {
            let s = deserialize_borrowed_str(self.context, &current.value).unwrap();

            // in this case, 'de is equal to '1
            // so force transmute lifetime
            let s = unsafe { transmute(s) };

            Ok(s)
        } else {
            Err(Error::ExpectedString)
        }
    }
}

impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
    type Error = Error;

    // Look at the input data to decide what Serde data model type to
    // deserialize as. Not all data formats are able to support this operation.
    // Formats that support `deserialize_any` are known as self-describing.
    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        let current = self.get_current();

        match current.tag() {
            JsTag::Undefined => visitor.visit_unit(),
            JsTag::Int => visitor.visit_i32(current.to_int()?),
            JsTag::Bool => visitor.visit_bool(current.to_bool()?),
            JsTag::Null => visitor.visit_unit(),
            JsTag::String => visitor.visit_string(current.to_string()?),
            JsTag::Float64 => visitor.visit_f64(current.to_float()?),
            JsTag::Object => {
                if current.is_array() {
                    self.deserialize_seq(visitor)
                } else {
                    self.deserialize_map(visitor)
                }
            }
            JsTag::Symbol => visitor.visit_unit(),
            JsTag::Module => visitor.visit_unit(),
            JsTag::Exception => self.deserialize_map(visitor),
            JsTag::CatchOffset => visitor.visit_unit(),
            JsTag::Uninitialized => visitor.visit_unit(),
            JsTag::FunctionBytecode => visitor.visit_unit(),
            #[cfg(feature = "bigint")]
            JsTag::BigInt => {
                let bigint = current.to_bigint()?;
                visitor.visit_i64(bigint.as_i64().ok_or(Error::BigIntOverflow)?)
            } // _ => {
              //     #[cfg(debug_assertions)]
              //     {
              //         println!("current type: {:?}", current.tag());
              //         println!("current: {}", current.to_json_string(0).unwrap());
              //     }
              //     unreachable!("unreachable tag: {:?}", current.tag());
              // }
        }
    }

    forward_to_deserialize_any! {
        bool
        i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64
        string char
        unit
        identifier ignored_any
    }

    fn deserialize_str<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_borrowed_str(self.parse_borrowed_str()?)
    }

    fn deserialize_seq<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        self.enter_array()?;
        let r = visitor.visit_seq(&mut *self);
        self.leave();
        r
    }

    fn deserialize_bytes<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        self.deserialize_byte_buf(visitor)
    }

    // for some type like &[u8]
    fn deserialize_byte_buf<V>(self, _: V) -> std::result::Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        unimplemented!("borrowed bytes not supported yet")
        // self.deserialize_seq(visitor)
    }

    fn deserialize_tuple<V>(
        self,
        _len: usize,
        visitor: V,
    ) -> std::result::Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        self.deserialize_seq(visitor)
    }

    fn deserialize_tuple_struct<V>(
        self,
        _name: &'static str,
        _len: usize,
        visitor: V,
    ) -> std::result::Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        self.deserialize_seq(visitor)
    }

    fn deserialize_option<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        if self.get_current().is_null() || self.get_current().is_undefined() {
            visitor.visit_none()
        } else {
            visitor.visit_some(self)
        }
    }

    fn deserialize_newtype_struct<V>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> std::result::Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_newtype_struct(self)
    }

    fn deserialize_map<V>(self, visitor: V) -> std::result::Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        self.enter_object()?;
        let r = visitor.visit_map(&mut *self);
        self.leave();
        r
    }

    // Structs look just like maps in JSON.
    //
    // Notice the `fields` parameter - a "struct" in the Serde data model means
    // that the `Deserialize` implementation is required to know what the fields
    // are before even looking at the input data. Any key-value pairing in which
    // the fields cannot be known ahead of time is probably a map.
    fn deserialize_struct<V>(
        self,
        _name: &'static str,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> std::result::Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        self.deserialize_map(visitor)
    }

    fn deserialize_enum<V>(
        self,
        _name: &'static str,
        _variants: &'static [&'static str],
        visitor: V,
    ) -> std::result::Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        if self.get_current().is_object() {
            // Visit a newtype variant, tuple variant, or struct variant.
            self.enter_object()?;
            self.next()?;
            let r = visitor.visit_enum(Enum::new(self));
            self.leave();
            r
        } else {
            // Visit a unit variant.
            visitor.visit_enum(self.parse_string()?.into_deserializer())
        }
    }

    fn deserialize_unit_struct<V>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> std::result::Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        self.deserialize_unit(visitor)
    }
}

impl<'de, 'a> SeqAccess<'de> for Deserializer<'de> {
    type Error = Error;

    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
    where
        T: DeserializeSeed<'de>,
    {
        if let Some(_) = self.next()? {
            seed.deserialize(self).map(Some)
        } else {
            Ok(None)
        }
    }
}

impl<'de, 'a> MapAccess<'de> for Deserializer<'de> {
    type Error = Error;

    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
    where
        K: DeserializeSeed<'de>,
    {
        if let Some(_) = self.next()? {
            seed.deserialize(self).map(Some)
        } else {
            Ok(None)
        }
    }

    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
    where
        V: DeserializeSeed<'de>,
    {
        // It doesn't make a difference whether the colon is parsed at the end
        // of `next_key_seed` or at the beginning of `next_value_seed`. In this
        // case the code is a bit simpler having it here.
        // if self.de.next_char()? != ':' {
        //     return Err(Error::ExpectedMapColon);
        // }
        // Deserialize a map value.
        self.next()?;
        seed.deserialize(self)
    }
}

struct Enum<'a, 'de: 'a> {
    de: &'a mut Deserializer<'de>,
}

impl<'a, 'de> Enum<'a, 'de> {
    fn new(de: &'a mut Deserializer<'de>) -> Self {
        Enum { de }
    }
}

// `EnumAccess` is provided to the `Visitor` to give it the ability to determine
// which variant of the enum is supposed to be deserialized.
//
// Note that all enum deserialization methods in Serde refer exclusively to the
// "externally tagged" enum representation.
impl<'de, 'a> EnumAccess<'de> for Enum<'a, 'de> {
    type Error = Error;
    type Variant = Self;

    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
    where
        V: DeserializeSeed<'de>,
    {
        // The `deserialize_enum` method parsed a `{` character so we are
        // currently inside of a map. The seed will be deserializing itself from
        // the key of the map.

        let val = seed.deserialize(&mut *self.de)?;
        self.de.next()?;
        // Parse the colon separating map key from value.
        // if self.de.next_char()? == ':' {
        Ok((val, self))
        // } else {
        //     Err(Error::ExpectedMapColon)
        // }
    }
}

// `VariantAccess` is provided to the `Visitor` to give it the ability to see
// the content of the single variant that it decided to deserialize.
impl<'de, 'a> VariantAccess<'de> for Enum<'a, 'de> {
    type Error = Error;

    // If the `Visitor` expected this variant to be a unit variant, the input
    // should have been the plain string case handled in `deserialize_enum`.
    fn unit_variant(self) -> Result<()> {
        Err(Error::ExpectedString)
    }

    // Newtype variants are represented in JSON as `{ NAME: VALUE }` so
    // deserialize the value here.
    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
    where
        T: DeserializeSeed<'de>,
    {
        seed.deserialize(self.de)
    }

    // Tuple variants are represented in JSON as `{ NAME: [DATA...] }` so
    // deserialize the sequence of data here.
    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        de::Deserializer::deserialize_seq(self.de, visitor)
    }

    // Struct variants are represented in JSON as `{ NAME: { K: V, ... } }` so
    // deserialize the inner map here.
    fn struct_variant<V>(self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
    where
        V: Visitor<'de>,
    {
        de::Deserializer::deserialize_map(self.de, visitor)
    }
}