1
/// Deserialization module.
2
use std::{
3
    io::{self, Write},
4
    str,
5
};
6

            
7
use serde::{
8
    de::{self, DeserializeSeed, Deserializer as _, Visitor},
9
    Deserialize,
10
};
11

            
12
pub use crate::error::{Error, Position, SpannedError};
13
use crate::{
14
    error::{Result, SpannedResult},
15
    extensions::Extensions,
16
    options::Options,
17
    parse::{NewtypeMode, ParsedByteStr, ParsedStr, Parser, StructType, TupleMode},
18
};
19

            
20
mod id;
21
mod tag;
22
#[cfg(test)]
23
mod tests;
24
mod value;
25

            
26
const SERDE_CONTENT_CANARY: &str = "serde::__private::de::content::Content";
27
const SERDE_TAG_KEY_CANARY: &str = "serde::__private::de::content::TagOrContent";
28

            
29
/// The RON deserializer.
30
///
31
/// If you just want to simply deserialize a value,
32
/// you can use the [`from_str`] convenience function.
33
pub struct Deserializer<'de> {
34
    pub(crate) parser: Parser<'de>,
35
    newtype_variant: bool,
36
    serde_content_newtype: bool,
37
    last_identifier: Option<&'de str>,
38
    recursion_limit: Option<usize>,
39
}
40

            
41
impl<'de> Deserializer<'de> {
42
    // Cannot implement trait here since output is tied to input lifetime 'de.
43
    #[allow(clippy::should_implement_trait)]
44
21702
    pub fn from_str(input: &'de str) -> SpannedResult<Self> {
45
21702
        Self::from_str_with_options(input, &Options::default())
46
21702
    }
47

            
48
274
    pub fn from_bytes(input: &'de [u8]) -> SpannedResult<Self> {
49
274
        Self::from_bytes_with_options(input, &Options::default())
50
274
    }
51

            
52
532161
    pub fn from_str_with_options(input: &'de str, options: &Options) -> SpannedResult<Self> {
53
531577
        let mut deserializer = Deserializer {
54
532161
            parser: Parser::new(input)?,
55
            newtype_variant: false,
56
            serde_content_newtype: false,
57
531577
            last_identifier: None,
58
531577
            recursion_limit: options.recursion_limit,
59
531577
        };
60
531577

            
61
531577
        deserializer.parser.exts |= options.default_extensions;
62
531577

            
63
531577
        Ok(deserializer)
64
532161
    }
65

            
66
    // FIXME: panic is not actually possible, remove once utf8_chunks is stabilized
67
    #[allow(clippy::missing_panics_doc)]
68
1680
    pub fn from_bytes_with_options(input: &'de [u8], options: &Options) -> SpannedResult<Self> {
69
1680
        let err = match str::from_utf8(input) {
70
1132
            Ok(input) => return Self::from_str_with_options(input, options),
71
548
            Err(err) => err,
72
548
        };
73
548

            
74
548
        // FIXME: use [`utf8_chunks`](https://github.com/rust-lang/rust/issues/99543) once stabilised
75
548
        #[allow(clippy::expect_used)]
76
548
        let valid_input =
77
548
            str::from_utf8(&input[..err.valid_up_to()]).expect("source is valid up to error");
78
548

            
79
548
        Err(SpannedError {
80
548
            code: err.into(),
81
548
            position: Position::from_src_end(valid_input),
82
548
        })
83
1680
    }
84

            
85
    #[must_use]
86
8
    pub fn remainder(&self) -> &'de str {
87
8
        self.parser.src()
88
8
    }
89

            
90
    #[must_use]
91
104597
    pub fn span_error(&self, code: Error) -> SpannedError {
92
104597
        self.parser.span_error(code)
93
104597
    }
94

            
95
    #[must_use]
96
9590
    pub fn extensions(&self) -> Extensions {
97
9590
        self.parser.exts
98
9590
    }
99
}
100

            
101
/// A convenience function for building a deserializer
102
/// and deserializing a value of type `T` from a reader.
103
296
pub fn from_reader<R, T>(rdr: R) -> SpannedResult<T>
104
296
where
105
296
    R: io::Read,
106
296
    T: de::DeserializeOwned,
107
296
{
108
296
    Options::default().from_reader(rdr)
109
296
}
110

            
111
/// A convenience function for building a deserializer
112
/// and deserializing a value of type `T` from a string.
113
7726
pub fn from_str<'a, T>(s: &'a str) -> SpannedResult<T>
114
7726
where
115
7726
    T: de::Deserialize<'a>,
116
7726
{
117
7726
    Options::default().from_str(s)
118
7726
}
119

            
120
/// A convenience function for building a deserializer
121
/// and deserializing a value of type `T` from bytes.
122
312
pub fn from_bytes<'a, T>(s: &'a [u8]) -> SpannedResult<T>
123
312
where
124
312
    T: de::Deserialize<'a>,
125
312
{
126
312
    Options::default().from_bytes(s)
127
312
}
128

            
129
macro_rules! guard_recursion {
130
    ($self:expr => $expr:expr) => {{
131
        if let Some(limit) = &mut $self.recursion_limit {
132
            if let Some(new_limit) = limit.checked_sub(1) {
133
                *limit = new_limit;
134
            } else {
135
                return Err(Error::ExceededRecursionLimit);
136
            }
137
        }
138

            
139
        let result = $expr;
140

            
141
        if let Some(limit) = &mut $self.recursion_limit {
142
            *limit = limit.saturating_add(1);
143
        }
144

            
145
        result
146
    }};
147
}
148

            
149
impl<'de> Deserializer<'de> {
150
    /// Check if the remaining bytes are whitespace only,
151
    /// otherwise return an error.
152
425066
    pub fn end(&mut self) -> Result<()> {
153
425066
        self.parser.skip_ws()?;
154

            
155
424518
        if self.parser.src().is_empty() {
156
419578
            Ok(())
157
        } else {
158
4940
            Err(Error::TrailingCharacters)
159
        }
160
425066
    }
161

            
162
    /// Called from [`deserialize_any`][serde::Deserializer::deserialize_any]
163
    /// when a struct was detected. Decides if there is a unit, tuple or usual
164
    /// struct and deserializes it accordingly.
165
    ///
166
    /// This method assumes there is no identifier left.
167
20980
    fn handle_any_struct<V>(&mut self, visitor: V, ident: Option<&str>) -> Result<V::Value>
168
20980
    where
169
20980
        V: Visitor<'de>,
170
20980
    {
171
        // HACK: switch to JSON enum semantics for JSON content
172
        // Robust impl blocked on https://github.com/serde-rs/serde/pull/2420
173
20980
        let is_serde_content = std::any::type_name::<V::Value>() == SERDE_CONTENT_CANARY
174
20358
            || std::any::type_name::<V::Value>() == SERDE_TAG_KEY_CANARY;
175

            
176
20980
        let old_serde_content_newtype = self.serde_content_newtype;
177
20980
        self.serde_content_newtype = false;
178
20980

            
179
20980
        match (
180
20980
            self.parser.check_struct_type(
181
20980
                NewtypeMode::NoParensMeanUnit,
182
20980
                if old_serde_content_newtype {
183
128
                    TupleMode::DifferentiateNewtype // separate match on NewtypeOrTuple below
184
                } else {
185
20852
                    TupleMode::ImpreciseTupleOrNewtype // Tuple and NewtypeOrTuple match equally
186
                },
187
16
            )?,
188
20964
            ident,
189
        ) {
190
52
            (StructType::Unit, Some(ident)) if is_serde_content => {
191
52
                // serde's Content type needs the ident for unit variants
192
52
                visitor.visit_str(ident)
193
            }
194
8498
            (StructType::Unit, _) => visitor.visit_unit(),
195
136
            (_, Some(ident)) if is_serde_content => {
196
136
                // serde's Content type uses a singleton map encoding for enums
197
136
                visitor.visit_map(SerdeEnumContent {
198
136
                    de: self,
199
136
                    ident: Some(ident),
200
136
                })
201
            }
202
            (StructType::Named, _) => {
203
                // giving no name results in worse errors but is necessary here
204
3910
                self.handle_struct_after_name("", visitor)
205
            }
206
68
            (StructType::NewtypeTuple, _) if old_serde_content_newtype => {
207
68
                // deserialize a newtype struct or variant
208
68
                self.parser.consume_char('(');
209
68
                self.parser.skip_ws()?;
210
68
                let result = self.deserialize_any(visitor);
211
68
                self.parser.skip_ws()?;
212
68
                self.parser.consume_char(')');
213
68

            
214
68
                result
215
            }
216
            (
217
                StructType::AnyTuple
218
                | StructType::EmptyTuple
219
                | StructType::NewtypeTuple
220
                | StructType::NonNewtypeTuple,
221
                _,
222
            ) => {
223
                // first argument is technically incorrect, but ignored anyway
224
4996
                self.deserialize_tuple(0, visitor)
225
            }
226
        }
227
17676
    }
228

            
229
    /// Called from
230
    /// [`deserialize_struct`][serde::Deserializer::deserialize_struct],
231
    /// [`struct_variant`][serde::de::VariantAccess::struct_variant], and
232
    /// [`handle_any_struct`][Self::handle_any_struct]. Handles
233
    /// deserialising the enclosing parentheses and everything in between.
234
    ///
235
    /// This method assumes there is no struct name identifier left.
236
5178
    fn handle_struct_after_name<V>(
237
5178
        &mut self,
238
5178
        name_for_pretty_errors_only: &'static str,
239
5178
        visitor: V,
240
5178
    ) -> Result<V::Value>
241
5178
    where
242
5178
        V: Visitor<'de>,
243
5178
    {
244
5178
        if self.newtype_variant || self.parser.consume_char('(') {
245
5158
            let old_newtype_variant = self.newtype_variant;
246
5158
            self.newtype_variant = false;
247

            
248
5158
            let value = guard_recursion! { self =>
249
5158
                visitor
250
5158
                    .visit_map(CommaSeparated::new(Terminator::Struct, self))
251
5158
                    .map_err(|err| {
252
962
                        struct_error_name(
253
962
                            err,
254
962
                            if !old_newtype_variant && !name_for_pretty_errors_only.is_empty() {
255
242
                                Some(name_for_pretty_errors_only)
256
                            } else {
257
720
                                None
258
                            },
259
                        )
260
5158
                    })?
261
            };
262

            
263
4196
            self.parser.skip_ws()?;
264

            
265
4196
            if old_newtype_variant || self.parser.consume_char(')') {
266
4184
                Ok(value)
267
            } else {
268
12
                Err(Error::ExpectedStructLikeEnd)
269
            }
270
20
        } else if name_for_pretty_errors_only.is_empty() {
271
4
            Err(Error::ExpectedStructLike)
272
        } else {
273
16
            Err(Error::ExpectedNamedStructLike(name_for_pretty_errors_only))
274
        }
275
5178
    }
276
}
277

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

            
281
390059
    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
282
390059
    where
283
390059
        V: Visitor<'de>,
284
390059
    {
285
390059
        if self.newtype_variant {
286
2196
            if self.parser.check_char(')') {
287
                // newtype variant wraps the unit type / a unit struct without name
288
274
                return self.deserialize_unit(visitor);
289
1922
            }
290
1922

            
291
1922
            #[allow(clippy::wildcard_in_or_patterns)]
292
1922
            match self
293
1922
                .parser
294
1922
                .check_struct_type(NewtypeMode::InsideNewtype, TupleMode::DifferentiateNewtype)?
295
            {
296
                StructType::Named => {
297
                    // newtype variant wraps a named struct
298
                    // giving no name results in worse errors but is necessary here
299
274
                    return self.handle_struct_after_name("", visitor);
300
                }
301
                StructType::EmptyTuple | StructType::NonNewtypeTuple => {
302
                    // newtype variant wraps a tuple (struct)
303
                    // first argument is technically incorrect, but ignored anyway
304
274
                    return self.deserialize_tuple(0, visitor);
305
                }
306
                // StructType::Unit is impossible with NewtypeMode::InsideNewtype
307
                // StructType::AnyTuple is impossible with TupleMode::DifferentiateNewtype
308
1374
                StructType::NewtypeTuple | _ => {
309
1374
                    // continue as usual with the inner content of the newtype variant
310
1374
                    self.newtype_variant = false;
311
1374
                }
312
            }
313
387863
        }
314

            
315
389237
        if self.parser.consume_ident("true") {
316
1422
            return visitor.visit_bool(true);
317
387815
        } else if self.parser.consume_ident("false") {
318
1382
            return visitor.visit_bool(false);
319
386433
        } else if self.parser.check_ident("Some") {
320
3916
            return self.deserialize_option(visitor);
321
382517
        } else if self.parser.consume_ident("None") {
322
7406
            return visitor.visit_none();
323
375111
        } else if self.parser.consume_str("()") {
324
648
            return visitor.visit_unit();
325
374463
        } else if self.parser.consume_ident("inf") || self.parser.consume_ident("inff32") {
326
830
            return visitor.visit_f32(std::f32::INFINITY);
327
373633
        } else if self.parser.consume_ident("inff64") {
328
548
            return visitor.visit_f64(std::f64::INFINITY);
329
373085
        } else if self.parser.consume_ident("NaN") || self.parser.consume_ident("NaNf32") {
330
830
            return visitor.visit_f32(std::f32::NAN);
331
372255
        } else if self.parser.consume_ident("NaNf64") {
332
548
            return visitor.visit_f64(std::f64::NAN);
333
371707
        }
334

            
335
        // `skip_identifier` does not change state if it fails
336
371707
        if let Some(ident) = self.parser.skip_identifier() {
337
10898
            self.parser.skip_ws()?;
338

            
339
10898
            return self.handle_any_struct(visitor, Some(ident));
340
360809
        }
341
360809

            
342
360809
        match self.parser.peek_char_or_eof()? {
343
10082
            '(' => self.handle_any_struct(visitor, None),
344
1666
            '[' => self.deserialize_seq(visitor),
345
72918
            '{' => self.deserialize_map(visitor),
346
52204
            '0'..='9' | '+' | '-' | '.' => self.parser.any_number()?.visit(visitor),
347
5650
            '"' | 'r' => self.deserialize_string(visitor),
348
213462
            'b' if self.parser.src().starts_with("b'") => self.parser.any_number()?.visit(visitor),
349
2208
            'b' => self.deserialize_byte_buf(visitor),
350
1676
            '\'' => self.deserialize_char(visitor),
351
822
            other => Err(Error::UnexpectedChar(other)),
352
        }
353
390059
    }
354

            
355
540
    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
356
540
    where
357
540
        V: Visitor<'de>,
358
540
    {
359
540
        visitor.visit_bool(self.parser.bool()?)
360
540
    }
361

            
362
92
    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
363
92
    where
364
92
        V: Visitor<'de>,
365
92
    {
366
92
        visitor.visit_i8(self.parser.integer()?)
367
92
    }
368

            
369
52
    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value>
370
52
    where
371
52
        V: Visitor<'de>,
372
52
    {
373
52
        visitor.visit_i16(self.parser.integer()?)
374
52
    }
375

            
376
1068
    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value>
377
1068
    where
378
1068
        V: Visitor<'de>,
379
1068
    {
380
1068
        visitor.visit_i32(self.parser.integer()?)
381
1068
    }
382

            
383
118
    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value>
384
118
    where
385
118
        V: Visitor<'de>,
386
118
    {
387
118
        visitor.visit_i64(self.parser.integer()?)
388
118
    }
389

            
390
    #[cfg(feature = "integer128")]
391
32
    fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value>
392
32
    where
393
32
        V: Visitor<'de>,
394
32
    {
395
32
        visitor.visit_i128(self.parser.integer()?)
396
32
    }
397

            
398
23358
    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
399
23358
    where
400
23358
        V: Visitor<'de>,
401
23358
    {
402
23358
        visitor.visit_u8(self.parser.integer()?)
403
23358
    }
404

            
405
56
    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value>
406
56
    where
407
56
        V: Visitor<'de>,
408
56
    {
409
56
        visitor.visit_u16(self.parser.integer()?)
410
56
    }
411

            
412
464
    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value>
413
464
    where
414
464
        V: Visitor<'de>,
415
464
    {
416
464
        visitor.visit_u32(self.parser.integer()?)
417
464
    }
418

            
419
58
    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value>
420
58
    where
421
58
        V: Visitor<'de>,
422
58
    {
423
58
        visitor.visit_u64(self.parser.integer()?)
424
58
    }
425

            
426
    #[cfg(feature = "integer128")]
427
38
    fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value>
428
38
    where
429
38
        V: Visitor<'de>,
430
38
    {
431
38
        visitor.visit_u128(self.parser.integer()?)
432
38
    }
433

            
434
604
    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value>
435
604
    where
436
604
        V: Visitor<'de>,
437
604
    {
438
604
        visitor.visit_f32(self.parser.float()?)
439
604
    }
440

            
441
248
    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value>
442
248
    where
443
248
        V: Visitor<'de>,
444
248
    {
445
248
        visitor.visit_f64(self.parser.float()?)
446
248
    }
447

            
448
2376
    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
449
2376
    where
450
2376
        V: Visitor<'de>,
451
2376
    {
452
2376
        visitor.visit_char(self.parser.char()?)
453
2376
    }
454

            
455
6916
    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
456
6916
    where
457
6916
        V: Visitor<'de>,
458
6916
    {
459
6916
        match self.parser.string()? {
460
104
            ParsedStr::Allocated(s) => visitor.visit_string(s),
461
6724
            ParsedStr::Slice(s) => visitor.visit_borrowed_str(s),
462
        }
463
6916
    }
464

            
465
6030
    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
466
6030
    where
467
6030
        V: Visitor<'de>,
468
6030
    {
469
6030
        self.deserialize_str(visitor)
470
6030
    }
471

            
472
20
    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
473
20
    where
474
20
        V: Visitor<'de>,
475
20
    {
476
20
        self.deserialize_byte_buf(visitor)
477
20
    }
478

            
479
2360
    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
480
2360
    where
481
2360
        V: Visitor<'de>,
482
2360
    {
483
2360
        if self.parser.check_char('[') {
484
4
            let bytes = Vec::<u8>::deserialize(self)?;
485
4
            return visitor.visit_byte_buf(bytes);
486
2356
        }
487
2356

            
488
2356
        match self.parser.byte_string()? {
489
608
            ParsedByteStr::Allocated(byte_buf) => visitor.visit_byte_buf(byte_buf),
490
1700
            ParsedByteStr::Slice(bytes) => visitor.visit_borrowed_bytes(bytes),
491
        }
492
2360
    }
493

            
494
4376
    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
495
4376
    where
496
4376
        V: Visitor<'de>,
497
4376
    {
498
4376
        if self.parser.consume_ident("None") {
499
112
            visitor.visit_none()
500
4264
        } else if self.parser.consume_ident("Some") && {
501
4096
            self.parser.skip_ws()?;
502
4096
            self.parser.consume_char('(')
503
        } {
504
4096
            self.parser.skip_ws()?;
505

            
506
4096
            self.newtype_variant = self
507
4096
                .parser
508
4096
                .exts
509
4096
                .contains(Extensions::UNWRAP_VARIANT_NEWTYPES);
510

            
511
4096
            let v = guard_recursion! { self => visitor.visit_some(&mut *self)? };
512

            
513
4092
            self.newtype_variant = false;
514
4092

            
515
4092
            self.parser.comma()?;
516

            
517
4092
            if self.parser.consume_char(')') {
518
3814
                Ok(v)
519
            } else {
520
278
                Err(Error::ExpectedOptionEnd)
521
            }
522
168
        } else if self.parser.exts.contains(Extensions::IMPLICIT_SOME) {
523
164
            guard_recursion! { self => visitor.visit_some(&mut *self) }
524
        } else {
525
4
            Err(Error::ExpectedOption)
526
        }
527
4376
    }
528

            
529
    // In Serde, unit means an anonymous value containing no data.
530
434
    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
531
434
    where
532
434
        V: Visitor<'de>,
533
434
    {
534
434
        if self.newtype_variant || self.parser.consume_str("()") {
535
430
            self.newtype_variant = false;
536
430

            
537
430
            visitor.visit_unit()
538
        } else {
539
4
            Err(Error::ExpectedUnit)
540
        }
541
434
    }
542

            
543
160
    fn deserialize_unit_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value>
544
160
    where
545
160
        V: Visitor<'de>,
546
160
    {
547
160
        if self.newtype_variant || self.parser.consume_struct_name(name)? {
548
56
            self.newtype_variant = false;
549
56

            
550
56
            visitor.visit_unit()
551
        } else {
552
84
            self.deserialize_unit(visitor)
553
        }
554
160
    }
555

            
556
13366
    fn deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value>
557
13366
    where
558
13366
        V: Visitor<'de>,
559
13366
    {
560
13366
        if name == crate::value::raw::RAW_VALUE_TOKEN {
561
12958
            let src_before = self.parser.pre_ws_src();
562
12958
            self.parser.skip_ws()?;
563
12958
            let _ignored = self.deserialize_ignored_any(serde::de::IgnoredAny)?;
564
12136
            self.parser.skip_ws()?;
565
12136
            let src_after = self.parser.src();
566
12136

            
567
12136
            if self.parser.has_unclosed_line_comment() {
568
1096
                return Err(Error::UnclosedLineComment);
569
11040
            }
570
11040

            
571
11040
            let ron_str = &src_before[..src_before.len() - src_after.len()];
572
11040

            
573
11040
            return visitor
574
11040
                .visit_borrowed_str::<Error>(ron_str)
575
11040
                .map_err(|_| Error::ExpectedRawValue);
576
408
        }
577
408

            
578
408
        if self.parser.exts.contains(Extensions::UNWRAP_NEWTYPES) || self.newtype_variant {
579
96
            self.newtype_variant = false;
580
96

            
581
96
            return guard_recursion! { self => visitor.visit_newtype_struct(&mut *self) };
582
312
        }
583
312

            
584
312
        self.parser.consume_struct_name(name)?;
585

            
586
288
        self.parser.skip_ws()?;
587

            
588
288
        if self.parser.consume_char('(') {
589
264
            self.parser.skip_ws()?;
590
264
            let value = guard_recursion! { self => visitor.visit_newtype_struct(&mut *self)? };
591
264
            self.parser.comma()?;
592

            
593
264
            if self.parser.consume_char(')') {
594
260
                Ok(value)
595
            } else {
596
4
                Err(Error::ExpectedStructLikeEnd)
597
            }
598
24
        } else if name.is_empty() {
599
12
            Err(Error::ExpectedStructLike)
600
        } else {
601
12
            Err(Error::ExpectedNamedStructLike(name))
602
        }
603
13366
    }
604

            
605
7052
    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
606
7052
    where
607
7052
        V: Visitor<'de>,
608
7052
    {
609
7052
        self.newtype_variant = false;
610
7052

            
611
7052
        if self.parser.consume_char('[') {
612
7040
            let value = guard_recursion! { self =>
613
7040
                visitor.visit_seq(CommaSeparated::new(Terminator::Seq, self))?
614
            };
615
6758
            self.parser.skip_ws()?;
616

            
617
6758
            if self.parser.consume_char(']') {
618
6746
                Ok(value)
619
            } else {
620
12
                Err(Error::ExpectedArrayEnd)
621
            }
622
        } else {
623
12
            Err(Error::ExpectedArray)
624
        }
625
7052
    }
626

            
627
9050
    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value>
628
9050
    where
629
9050
        V: Visitor<'de>,
630
9050
    {
631
9050
        if self.newtype_variant || self.parser.consume_char('(') {
632
8994
            let old_newtype_variant = self.newtype_variant;
633
8994
            self.newtype_variant = false;
634

            
635
8994
            let value = guard_recursion! { self =>
636
8994
                visitor.visit_seq(CommaSeparated::new(Terminator::Tuple, self))?
637
            };
638
8136
            self.parser.skip_ws()?;
639

            
640
8136
            if old_newtype_variant || self.parser.consume_char(')') {
641
8124
                Ok(value)
642
            } else {
643
12
                Err(Error::ExpectedStructLikeEnd)
644
            }
645
        } else {
646
56
            Err(Error::ExpectedStructLike)
647
        }
648
9050
    }
649

            
650
220
    fn deserialize_tuple_struct<V>(
651
220
        self,
652
220
        name: &'static str,
653
220
        len: usize,
654
220
        visitor: V,
655
220
    ) -> Result<V::Value>
656
220
    where
657
220
        V: Visitor<'de>,
658
220
    {
659
220
        if !self.newtype_variant {
660
204
            self.parser.consume_struct_name(name)?;
661
16
        }
662

            
663
196
        self.deserialize_tuple(len, visitor).map_err(|e| match e {
664
24
            Error::ExpectedStructLike if !name.is_empty() => Error::ExpectedNamedStructLike(name),
665
24
            e => e,
666
196
        })
667
220
    }
668

            
669
73338
    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
670
73338
    where
671
73338
        V: Visitor<'de>,
672
73338
    {
673
        // Detect `#[serde(flatten)]` as a struct deserialised as a map
674
        const SERDE_FLATTEN_CANARY: &[u8] = b"struct ";
675

            
676
        struct VisitorExpecting<V>(V);
677
        impl<'de, V: Visitor<'de>> std::fmt::Display for VisitorExpecting<&'_ V> {
678
73338
            fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
679
73338
                self.0.expecting(fmt)
680
73338
            }
681
        }
682

            
683
73338
        self.newtype_variant = false;
684
73338

            
685
73338
        let mut canary_buffer = [0u8; SERDE_FLATTEN_CANARY.len()];
686
73338
        std::mem::drop(write!(
687
73338
            canary_buffer.as_mut(),
688
73338
            "{}",
689
73338
            VisitorExpecting(&visitor)
690
73338
        ));
691
73338
        let terminator = if canary_buffer == SERDE_FLATTEN_CANARY {
692
276
            Terminator::MapAsStruct
693
        } else {
694
73062
            Terminator::Map
695
        };
696

            
697
73338
        if self.parser.consume_char('{') {
698
73326
            let value = guard_recursion! { self =>
699
72230
                visitor.visit_map(CommaSeparated::new(terminator, self))?
700
            };
701
2442
            self.parser.skip_ws()?;
702

            
703
2442
            if self.parser.consume_char('}') {
704
2430
                Ok(value)
705
            } else {
706
12
                Err(Error::ExpectedMapEnd)
707
            }
708
        } else {
709
12
            Err(Error::ExpectedMap)
710
        }
711
73338
    }
712

            
713
922
    fn deserialize_struct<V>(
714
922
        self,
715
922
        name: &'static str,
716
922
        _fields: &'static [&'static str],
717
922
        visitor: V,
718
922
    ) -> Result<V::Value>
719
922
    where
720
922
        V: Visitor<'de>,
721
922
    {
722
922
        if !self.newtype_variant {
723
866
            self.parser.consume_struct_name(name)?;
724
56
        }
725

            
726
886
        self.parser.skip_ws()?;
727

            
728
886
        self.handle_struct_after_name(name, visitor)
729
922
    }
730

            
731
1010
    fn deserialize_enum<V>(
732
1010
        self,
733
1010
        name: &'static str,
734
1010
        _variants: &'static [&'static str],
735
1010
        visitor: V,
736
1010
    ) -> Result<V::Value>
737
1010
    where
738
1010
        V: Visitor<'de>,
739
1010
    {
740
1010
        self.newtype_variant = false;
741
1010

            
742
1010
        match guard_recursion! { self => visitor.visit_enum(Enum::new(self)) } {
743
784
            Ok(value) => Ok(value),
744
            Err(Error::NoSuchEnumVariant {
745
12
                expected,
746
12
                found,
747
                outer: None,
748
12
            }) if !name.is_empty() => Err(Error::NoSuchEnumVariant {
749
12
                expected,
750
12
                found,
751
12
                outer: Some(String::from(name)),
752
12
            }),
753
214
            Err(e) => Err(e),
754
        }
755
1010
    }
756

            
757
9076
    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value>
758
9076
    where
759
9076
        V: Visitor<'de>,
760
9076
    {
761
9076
        let identifier = self.parser.identifier()?;
762

            
763
9008
        self.last_identifier = Some(identifier);
764
9008

            
765
9008
        visitor.visit_borrowed_str(identifier)
766
9076
    }
767

            
768
54252
    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>
769
54252
    where
770
54252
        V: Visitor<'de>,
771
54252
    {
772
54252
        self.deserialize_any(visitor)
773
54252
    }
774
}
775

            
776
enum Terminator {
777
    Map,
778
    MapAsStruct,
779
    Tuple,
780
    Struct,
781
    Seq,
782
}
783

            
784
impl Terminator {
785
544391
    fn as_char(&self) -> char {
786
544391
        match self {
787
157906
            Terminator::Map | Terminator::MapAsStruct => '}',
788
342693
            Terminator::Tuple | Terminator::Struct => ')',
789
43792
            Terminator::Seq => ']',
790
        }
791
544391
    }
792
}
793

            
794
struct CommaSeparated<'a, 'de: 'a> {
795
    de: &'a mut Deserializer<'de>,
796
    terminator: Terminator,
797
    had_comma: bool,
798
    inside_internally_tagged_enum: bool,
799
}
800

            
801
impl<'a, 'de> CommaSeparated<'a, 'de> {
802
251777
    fn new(terminator: Terminator, de: &'a mut Deserializer<'de>) -> Self {
803
251777
        CommaSeparated {
804
251777
            de,
805
251777
            terminator,
806
251777
            had_comma: true,
807
251777
            inside_internally_tagged_enum: false,
808
251777
        }
809
251777
    }
810

            
811
544391
    fn has_element(&mut self) -> Result<bool> {
812
544391
        self.de.parser.skip_ws()?;
813

            
814
544391
        match (
815
544391
            self.had_comma,
816
544391
            !self.de.parser.check_char(self.terminator.as_char()),
817
544391
        ) {
818
            // Trailing comma, maybe has a next element
819
477012
            (true, has_element) => Ok(has_element),
820
            // No trailing comma but terminator
821
66283
            (false, false) => Ok(false),
822
            // No trailing comma or terminator
823
1096
            (false, true) => Err(Error::ExpectedComma),
824
        }
825
544391
    }
826
}
827

            
828
impl<'de, 'a> de::SeqAccess<'de> for CommaSeparated<'a, 'de> {
829
    type Error = Error;
830

            
831
44850
    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
832
44850
    where
833
44850
        T: DeserializeSeed<'de>,
834
44850
    {
835
44850
        if self.has_element()? {
836
30344
            let res = guard_recursion! { self.de => seed.deserialize(&mut *self.de)? };
837

            
838
29216
            self.had_comma = self.de.parser.comma()?;
839

            
840
29216
            Ok(Some(res))
841
        } else {
842
14498
            Ok(None)
843
        }
844
44850
    }
845
}
846

            
847
impl<'de, 'a> de::MapAccess<'de> for CommaSeparated<'a, 'de> {
848
    type Error = Error;
849

            
850
87656
    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
851
87656
    where
852
87656
        K: DeserializeSeed<'de>,
853
87656
    {
854
87656
        if self.has_element()? {
855
80886
            self.inside_internally_tagged_enum =
856
80886
                std::any::type_name::<K::Value>() == SERDE_TAG_KEY_CANARY;
857
80886

            
858
80886
            match self.terminator {
859
8166
                Terminator::Struct => guard_recursion! { self.de =>
860
8166
                    seed.deserialize(&mut id::Deserializer::new(&mut *self.de, false)).map(Some)
861
                },
862
612
                Terminator::MapAsStruct => guard_recursion! { self.de =>
863
612
                    seed.deserialize(&mut id::Deserializer::new(&mut *self.de, true)).map(Some)
864
                },
865
72108
                _ => guard_recursion! { self.de => seed.deserialize(&mut *self.de).map(Some) },
866
            }
867
        } else {
868
6762
            Ok(None)
869
        }
870
87656
    }
871

            
872
11872
    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
873
11872
    where
874
11872
        V: DeserializeSeed<'de>,
875
11872
    {
876
11872
        self.de.parser.skip_ws()?;
877

            
878
11872
        if self.de.parser.consume_char(':') {
879
11590
            self.de.parser.skip_ws()?;
880

            
881
11590
            let res = if self.inside_internally_tagged_enum
882
370
                && std::any::type_name::<V::Value>() != SERDE_CONTENT_CANARY
883
            {
884
214
                guard_recursion! { self.de =>
885
214
                    seed.deserialize(&mut tag::Deserializer::new(&mut *self.de))?
886
                }
887
            } else {
888
11376
                guard_recursion! { self.de =>
889
11376
                    seed.deserialize(&mut *self.de)?
890
                }
891
            };
892

            
893
10860
            self.had_comma = self.de.parser.comma()?;
894

            
895
10860
            Ok(res)
896
        } else {
897
282
            Err(Error::ExpectedMapColon)
898
        }
899
11872
    }
900
}
901

            
902
struct Enum<'a, 'de: 'a> {
903
    de: &'a mut Deserializer<'de>,
904
}
905

            
906
impl<'a, 'de> Enum<'a, 'de> {
907
61895
    fn new(de: &'a mut Deserializer<'de>) -> Self {
908
61895
        Enum { de }
909
61895
    }
910
}
911

            
912
impl<'de, 'a> de::EnumAccess<'de> for Enum<'a, 'de> {
913
    type Error = Error;
914
    type Variant = Self;
915

            
916
1010
    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
917
1010
    where
918
1010
        V: DeserializeSeed<'de>,
919
1010
    {
920
1010
        self.de.parser.skip_ws()?;
921

            
922
1010
        let value = guard_recursion! { self.de => seed.deserialize(&mut *self.de)? };
923

            
924
978
        Ok((value, self))
925
1010
    }
926
}
927

            
928
impl<'de, 'a> de::VariantAccess<'de> for Enum<'a, 'de> {
929
    type Error = Error;
930

            
931
15928
    fn unit_variant(self) -> Result<()> {
932
15928
        Ok(())
933
15928
    }
934

            
935
506
    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value>
936
506
    where
937
506
        T: DeserializeSeed<'de>,
938
506
    {
939
506
        let newtype_variant = self.de.last_identifier;
940
506

            
941
506
        self.de.parser.skip_ws()?;
942

            
943
506
        if self.de.parser.consume_char('(') {
944
494
            self.de.parser.skip_ws()?;
945

            
946
494
            self.de.newtype_variant = self
947
494
                .de
948
494
                .parser
949
494
                .exts
950
494
                .contains(Extensions::UNWRAP_VARIANT_NEWTYPES);
951

            
952
494
            let val = guard_recursion! { self.de =>
953
494
                seed
954
494
                    .deserialize(&mut *self.de)
955
494
                    .map_err(|err| struct_error_name(err, newtype_variant))?
956
            };
957

            
958
372
            self.de.newtype_variant = false;
959
372

            
960
372
            self.de.parser.comma()?;
961

            
962
372
            if self.de.parser.consume_char(')') {
963
360
                Ok(val)
964
            } else {
965
12
                Err(Error::ExpectedStructLikeEnd)
966
            }
967
        } else {
968
12
            Err(Error::ExpectedStructLike)
969
        }
970
506
    }
971

            
972
96
    fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value>
973
96
    where
974
96
        V: Visitor<'de>,
975
96
    {
976
96
        self.de.parser.skip_ws()?;
977

            
978
96
        self.de.deserialize_tuple(len, visitor)
979
96
    }
980

            
981
108
    fn struct_variant<V>(self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
982
108
    where
983
108
        V: Visitor<'de>,
984
108
    {
985
108
        let struct_variant = self.de.last_identifier;
986
108

            
987
108
        self.de.parser.skip_ws()?;
988

            
989
108
        self.de
990
108
            .handle_struct_after_name("", visitor)
991
108
            .map_err(|err| struct_error_name(err, struct_variant))
992
108
    }
993
}
994

            
995
38110
fn struct_error_name(error: Error, name: Option<&str>) -> Error {
996
2192
    match error {
997
        Error::NoSuchStructField {
998
2192
            expected,
999
2192
            found,
2192
            outer: None,
2192
        } => Error::NoSuchStructField {
2192
            expected,
2192
            found,
2192
            outer: name.map(ToOwned::to_owned),
2192
        },
3014
        Error::MissingStructField { field, outer: None } => Error::MissingStructField {
3014
            field,
3014
            outer: name.map(ToOwned::to_owned),
3014
        },
2192
        Error::DuplicateStructField { field, outer: None } => Error::DuplicateStructField {
2192
            field,
2192
            outer: name.map(ToOwned::to_owned),
2192
        },
30712
        e => e,
    }
38110
}
struct SerdeEnumContent<'a, 'de: 'a> {
    de: &'a mut Deserializer<'de>,
    ident: Option<&'a str>,
}
impl<'de, 'a> de::MapAccess<'de> for SerdeEnumContent<'a, 'de> {
    type Error = Error;
260
    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
260
    where
260
        K: DeserializeSeed<'de>,
260
    {
260
        self.ident
260
            .take()
260
            .map(|ident| seed.deserialize(serde::de::value::StrDeserializer::new(ident)))
260
            .transpose()
260
    }
136
    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
136
    where
136
        V: DeserializeSeed<'de>,
136
    {
136
        self.de.parser.skip_ws()?;
136
        let old_serde_content_newtype = self.de.serde_content_newtype;
136
        self.de.serde_content_newtype = true;
136
        let result = seed.deserialize(&mut *self.de);
136
        self.de.serde_content_newtype = old_serde_content_newtype;
136

            
136
        result
136
    }
}