Skip to main content

dbt_yaml/
de.rs

1use crate::error::{self, Error, ErrorImpl};
2use crate::libyaml::error::Mark;
3use crate::libyaml::parser::{MappingStart, Scalar, ScalarStyle, SequenceStart};
4use crate::libyaml::tag::Tag;
5use crate::loader::{Document, Loader};
6use crate::path::Path;
7use crate::spanned;
8use serde::de::value::StrDeserializer;
9use serde::de::{
10    self, Deserialize, DeserializeOwned, DeserializeSeed, Expected, IgnoredAny, Unexpected, Visitor,
11};
12use std::fmt;
13use std::io;
14use std::mem;
15use std::num::ParseIntError;
16use std::str;
17use std::sync::Arc;
18
19type Result<T, E = Error> = std::result::Result<T, E>;
20
21/// A structure that deserializes YAML into Rust values.
22///
23/// # Examples
24///
25/// Deserializing a single document:
26///
27/// ```
28/// use anyhow::Result;
29/// use serde::Deserialize;
30/// use dbt_yaml::Value;
31///
32/// fn main() -> Result<()> {
33///     let input = "k: 107\n";
34///     let de = dbt_yaml::Deserializer::from_str(input);
35///     let value = Value::deserialize(de)?;
36///     println!("{:?}", value);
37///     Ok(())
38/// }
39/// ```
40///
41/// Deserializing multi-doc YAML:
42///
43/// ```
44/// use anyhow::Result;
45/// use serde::Deserialize;
46/// use dbt_yaml::Value;
47///
48/// fn main() -> Result<()> {
49///     let input = "---\nk: 107\n...\n---\nj: 106\n";
50///
51///     for document in dbt_yaml::Deserializer::from_str(input) {
52///         let value = Value::deserialize(document)?;
53///         println!("{:?}", value);
54///     }
55///
56///     Ok(())
57/// }
58/// ```
59pub struct Deserializer<'de> {
60    progress: Progress<'de>,
61}
62
63pub(crate) enum Progress<'de> {
64    Str(&'de str),
65    Slice(&'de [u8]),
66    Read(Box<dyn io::Read + 'de>),
67    Iterable(Loader<'de>),
68    Document(Document<'de>),
69    Fail(Arc<ErrorImpl>),
70}
71
72impl<'de> Deserializer<'de> {
73    /// Creates a YAML deserializer from a `&str`.
74    pub fn from_str(s: &'de str) -> Self {
75        let progress = Progress::Str(s);
76        Deserializer { progress }
77    }
78
79    /// Creates a YAML deserializer from a `&[u8]`.
80    pub fn from_slice(v: &'de [u8]) -> Self {
81        let progress = Progress::Slice(v);
82        Deserializer { progress }
83    }
84
85    /// Creates a YAML deserializer from an `io::Read`.
86    ///
87    /// Reader-based deserializers do not support deserializing borrowed types
88    /// like `&str`, since the `std::io::Read` trait has no non-copying methods
89    /// -- everything it does involves copying bytes out of the data source.
90    pub fn from_reader<R>(rdr: R) -> Self
91    where
92        R: io::Read + 'de,
93    {
94        let progress = Progress::Read(Box::new(rdr));
95        Deserializer { progress }
96    }
97
98    fn de<T>(
99        self,
100        f: impl for<'document> FnOnce(&mut DeserializerFromEvents<'de, 'document>) -> Result<T>,
101    ) -> Result<T> {
102        let mut pos = 0;
103        let mut jumpcount = 0;
104
105        match self.progress {
106            Progress::Iterable(_) => return Err(error::new(ErrorImpl::MoreThanOneDocument)),
107            Progress::Document(document) => {
108                let t = f(&mut DeserializerFromEvents {
109                    document: &document,
110                    pos: &mut pos,
111                    jumpcount: &mut jumpcount,
112                    path: Path::Root,
113                    remaining_depth: 128,
114                    current_enum: None,
115                })?;
116                if let Some(parse_error) = document.error {
117                    return Err(error::shared(parse_error));
118                }
119                return Ok(t);
120            }
121            _ => {}
122        }
123
124        let mut loader = Loader::new(self.progress)?;
125        let document = match loader.next_document() {
126            Some(document) => document,
127            None => return Err(error::new(ErrorImpl::EndOfStream)),
128        };
129        let t = f(&mut DeserializerFromEvents {
130            document: &document,
131            pos: &mut pos,
132            jumpcount: &mut jumpcount,
133            path: Path::Root,
134            remaining_depth: 128,
135            current_enum: None,
136        })?;
137        if let Some(parse_error) = document.error {
138            return Err(error::shared(parse_error));
139        }
140        if loader.next_document().is_none() {
141            Ok(t)
142        } else {
143            Err(error::new(ErrorImpl::MoreThanOneDocument))
144        }
145    }
146}
147
148impl Iterator for Deserializer<'_> {
149    type Item = Self;
150
151    fn next(&mut self) -> Option<Self> {
152        match &mut self.progress {
153            Progress::Iterable(loader) => {
154                let document = loader.next_document()?;
155                return Some(Deserializer {
156                    progress: Progress::Document(document),
157                });
158            }
159            Progress::Document(_) => return None,
160            Progress::Fail(err) => {
161                return Some(Deserializer {
162                    progress: Progress::Fail(Arc::clone(err)),
163                });
164            }
165            _ => {}
166        }
167
168        let dummy = Progress::Str("");
169        let input = mem::replace(&mut self.progress, dummy);
170        match Loader::new(input) {
171            Ok(loader) => {
172                self.progress = Progress::Iterable(loader);
173                self.next()
174            }
175            Err(err) => {
176                let fail = err.shared();
177                self.progress = Progress::Fail(Arc::clone(&fail));
178                Some(Deserializer {
179                    progress: Progress::Fail(fail),
180                })
181            }
182        }
183    }
184}
185
186impl<'de> de::Deserializer<'de> for Deserializer<'de> {
187    type Error = Error;
188
189    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
190    where
191        V: Visitor<'de>,
192    {
193        self.de(|state| state.deserialize_any(visitor))
194    }
195
196    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
197    where
198        V: Visitor<'de>,
199    {
200        self.de(|state| state.deserialize_bool(visitor))
201    }
202
203    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
204    where
205        V: Visitor<'de>,
206    {
207        self.de(|state| state.deserialize_i8(visitor))
208    }
209
210    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value>
211    where
212        V: Visitor<'de>,
213    {
214        self.de(|state| state.deserialize_i16(visitor))
215    }
216
217    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value>
218    where
219        V: Visitor<'de>,
220    {
221        self.de(|state| state.deserialize_i32(visitor))
222    }
223
224    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value>
225    where
226        V: Visitor<'de>,
227    {
228        self.de(|state| state.deserialize_i64(visitor))
229    }
230
231    fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value>
232    where
233        V: Visitor<'de>,
234    {
235        self.de(|state| state.deserialize_i128(visitor))
236    }
237
238    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
239    where
240        V: Visitor<'de>,
241    {
242        self.de(|state| state.deserialize_u8(visitor))
243    }
244
245    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value>
246    where
247        V: Visitor<'de>,
248    {
249        self.de(|state| state.deserialize_u16(visitor))
250    }
251
252    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value>
253    where
254        V: Visitor<'de>,
255    {
256        self.de(|state| state.deserialize_u32(visitor))
257    }
258
259    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value>
260    where
261        V: Visitor<'de>,
262    {
263        self.de(|state| state.deserialize_u64(visitor))
264    }
265
266    fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value>
267    where
268        V: Visitor<'de>,
269    {
270        self.de(|state| state.deserialize_u128(visitor))
271    }
272
273    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value>
274    where
275        V: Visitor<'de>,
276    {
277        self.de(|state| state.deserialize_f32(visitor))
278    }
279
280    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value>
281    where
282        V: Visitor<'de>,
283    {
284        self.de(|state| state.deserialize_f64(visitor))
285    }
286
287    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
288    where
289        V: Visitor<'de>,
290    {
291        self.de(|state| state.deserialize_char(visitor))
292    }
293
294    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
295    where
296        V: Visitor<'de>,
297    {
298        self.de(|state| state.deserialize_str(visitor))
299    }
300
301    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
302    where
303        V: Visitor<'de>,
304    {
305        self.de(|state| state.deserialize_string(visitor))
306    }
307
308    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value>
309    where
310        V: Visitor<'de>,
311    {
312        self.de(|state| state.deserialize_bytes(visitor))
313    }
314
315    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value>
316    where
317        V: Visitor<'de>,
318    {
319        self.de(|state| state.deserialize_byte_buf(visitor))
320    }
321
322    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
323    where
324        V: Visitor<'de>,
325    {
326        self.de(|state| state.deserialize_option(visitor))
327    }
328
329    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
330    where
331        V: Visitor<'de>,
332    {
333        self.de(|state| state.deserialize_unit(visitor))
334    }
335
336    fn deserialize_unit_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value>
337    where
338        V: Visitor<'de>,
339    {
340        self.de(|state| state.deserialize_unit_struct(name, visitor))
341    }
342
343    fn deserialize_newtype_struct<V>(self, name: &'static str, visitor: V) -> Result<V::Value>
344    where
345        V: Visitor<'de>,
346    {
347        self.de(|state| state.deserialize_newtype_struct(name, visitor))
348    }
349
350    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
351    where
352        V: Visitor<'de>,
353    {
354        self.de(|state| state.deserialize_seq(visitor))
355    }
356
357    fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value>
358    where
359        V: Visitor<'de>,
360    {
361        self.de(|state| state.deserialize_tuple(len, visitor))
362    }
363
364    fn deserialize_tuple_struct<V>(
365        self,
366        name: &'static str,
367        len: usize,
368        visitor: V,
369    ) -> Result<V::Value>
370    where
371        V: Visitor<'de>,
372    {
373        self.de(|state| state.deserialize_tuple_struct(name, len, visitor))
374    }
375
376    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
377    where
378        V: Visitor<'de>,
379    {
380        self.de(|state| state.deserialize_map(visitor))
381    }
382
383    fn deserialize_struct<V>(
384        self,
385        name: &'static str,
386        fields: &'static [&'static str],
387        visitor: V,
388    ) -> Result<V::Value>
389    where
390        V: Visitor<'de>,
391    {
392        self.de(|state| state.deserialize_struct(name, fields, visitor))
393    }
394
395    fn deserialize_enum<V>(
396        self,
397        name: &'static str,
398        variants: &'static [&'static str],
399        visitor: V,
400    ) -> Result<V::Value>
401    where
402        V: Visitor<'de>,
403    {
404        self.de(|state| state.deserialize_enum(name, variants, visitor))
405    }
406
407    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value>
408    where
409        V: Visitor<'de>,
410    {
411        self.de(|state| state.deserialize_identifier(visitor))
412    }
413
414    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>
415    where
416        V: Visitor<'de>,
417    {
418        self.de(|state| state.deserialize_ignored_any(visitor))
419    }
420}
421
422#[derive(Debug)]
423pub(crate) enum Event<'de> {
424    Alias(usize),
425    Scalar(Scalar<'de>),
426    SequenceStart(SequenceStart),
427    SequenceEnd,
428    MappingStart(MappingStart),
429    MappingEnd,
430    Void,
431}
432
433struct DeserializerFromEvents<'de, 'document> {
434    document: &'document Document<'de>,
435    pos: &'document mut usize,
436    jumpcount: &'document mut usize,
437    path: Path<'document>,
438    remaining_depth: u8,
439    current_enum: Option<CurrentEnum<'document>>,
440}
441
442#[derive(Copy, Clone)]
443struct CurrentEnum<'document> {
444    name: Option<&'static str>,
445    tag: &'document str,
446}
447
448impl<'de, 'document> DeserializerFromEvents<'de, 'document> {
449    fn peek_event(&self) -> Result<&'document Event<'de>> {
450        self.peek_event_mark().map(|(event, _mark)| event)
451    }
452
453    fn peek_event_mark(&self) -> Result<(&'document Event<'de>, Mark)> {
454        match self.document.events.get(*self.pos) {
455            Some((event, mark)) => Ok((event, *mark)),
456            None => Err(match &self.document.error {
457                Some(parse_error) => error::shared(Arc::clone(parse_error)),
458                None => error::new(ErrorImpl::EndOfStream),
459            }),
460        }
461    }
462
463    fn next_event(&mut self) -> Result<&'document Event<'de>> {
464        self.next_event_mark().map(|(event, _mark)| event)
465    }
466
467    fn next_event_mark(&mut self) -> Result<(&'document Event<'de>, Mark)> {
468        let res = self.peek_event_mark().map(|(event, mark)| {
469            *self.pos += 1;
470            self.current_enum = None;
471            (event, mark)
472        });
473        if let Ok((_, mark)) = self.peek_event_mark() {
474            spanned::set_marker(mark);
475        }
476        res
477    }
478
479    fn jump<'anchor>(
480        &'anchor mut self,
481        pos: &'anchor mut usize,
482    ) -> Result<DeserializerFromEvents<'de, 'anchor>> {
483        *self.jumpcount += 1;
484        if *self.jumpcount > self.document.events.len() * 100 {
485            return Err(error::new(ErrorImpl::RepetitionLimitExceeded));
486        }
487        match self.document.aliases.get(pos) {
488            Some(found) => {
489                *pos = *found;
490                Ok(DeserializerFromEvents {
491                    document: self.document,
492                    pos,
493                    jumpcount: self.jumpcount,
494                    path: Path::Alias { parent: &self.path },
495                    remaining_depth: self.remaining_depth,
496                    current_enum: None,
497                })
498            }
499            None => panic!("unresolved alias: {}", *pos),
500        }
501    }
502
503    fn ignore_any(&mut self) -> Result<()> {
504        enum Nest {
505            Sequence,
506            Mapping,
507        }
508
509        let mut stack = Vec::new();
510
511        loop {
512            match self.next_event()? {
513                Event::Alias(_) | Event::Scalar(_) | Event::Void => {}
514                Event::SequenceStart(_) => {
515                    stack.push(Nest::Sequence);
516                }
517                Event::MappingStart(_) => {
518                    stack.push(Nest::Mapping);
519                }
520                Event::SequenceEnd => match stack.pop() {
521                    Some(Nest::Sequence) => {}
522                    None | Some(Nest::Mapping) => {
523                        panic!("unexpected end of sequence");
524                    }
525                },
526                Event::MappingEnd => match stack.pop() {
527                    Some(Nest::Mapping) => {}
528                    None | Some(Nest::Sequence) => {
529                        panic!("unexpected end of mapping");
530                    }
531                },
532            }
533            if stack.is_empty() {
534                return Ok(());
535            }
536        }
537    }
538
539    fn visit_sequence<V>(&mut self, visitor: V, mark: Mark) -> Result<V::Value>
540    where
541        V: Visitor<'de>,
542    {
543        let (value, len) = self.recursion_check(mark, |de| {
544            let mut seq = SeqAccess {
545                empty: false,
546                de,
547                len: 0,
548            };
549            let value = visitor.visit_seq(&mut seq)?;
550            Ok((value, seq.len))
551        })?;
552        self.end_sequence(len)?;
553        Ok(value)
554    }
555
556    fn visit_mapping<V>(&mut self, visitor: V, mark: Mark) -> Result<V::Value>
557    where
558        V: Visitor<'de>,
559    {
560        let (value, len) = self.recursion_check(mark, |de| {
561            let mut map = MapAccess {
562                empty: false,
563                de,
564                len: 0,
565                key: None,
566            };
567            let value = visitor.visit_map(&mut map)?;
568            Ok((value, map.len))
569        })?;
570        self.end_mapping(len)?;
571        Ok(value)
572    }
573
574    fn end_sequence(&mut self, len: usize) -> Result<()> {
575        let total = {
576            let mut seq = SeqAccess {
577                empty: false,
578                de: self,
579                len,
580            };
581            while de::SeqAccess::next_element::<IgnoredAny>(&mut seq)?.is_some() {}
582            seq.len
583        };
584        match self.next_event()? {
585            Event::SequenceEnd | Event::Void => {}
586            _ => panic!("expected a SequenceEnd event"),
587        }
588        if total == len {
589            Ok(())
590        } else {
591            struct ExpectedSeq(usize);
592            impl Expected for ExpectedSeq {
593                fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
594                    if self.0 == 1 {
595                        write!(formatter, "sequence of 1 element")
596                    } else {
597                        write!(formatter, "sequence of {} elements", self.0)
598                    }
599                }
600            }
601            Err(de::Error::invalid_length(total, &ExpectedSeq(len)))
602        }
603    }
604
605    fn end_mapping(&mut self, len: usize) -> Result<()> {
606        let total = {
607            let mut map = MapAccess {
608                empty: false,
609                de: self,
610                len,
611                key: None,
612            };
613            while de::MapAccess::next_entry::<IgnoredAny, IgnoredAny>(&mut map)?.is_some() {}
614            map.len
615        };
616        match self.next_event()? {
617            Event::MappingEnd | Event::Void => {}
618            _ => panic!("expected a MappingEnd event"),
619        }
620        if total == len {
621            Ok(())
622        } else {
623            struct ExpectedMap(usize);
624            impl Expected for ExpectedMap {
625                fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
626                    if self.0 == 1 {
627                        write!(formatter, "map containing 1 entry")
628                    } else {
629                        write!(formatter, "map containing {} entries", self.0)
630                    }
631                }
632            }
633            Err(de::Error::invalid_length(total, &ExpectedMap(len)))
634        }
635    }
636
637    fn recursion_check<F: FnOnce(&mut Self) -> Result<T>, T>(
638        &mut self,
639        mark: Mark,
640        f: F,
641    ) -> Result<T> {
642        let previous_depth = self.remaining_depth;
643        self.remaining_depth = match previous_depth.checked_sub(1) {
644            Some(depth) => depth,
645            None => return Err(error::new(ErrorImpl::RecursionLimitExceeded(mark.into()))),
646        };
647        let result = f(self);
648        self.remaining_depth = previous_depth;
649        result
650    }
651}
652
653struct SeqAccess<'de, 'document, 'seq> {
654    empty: bool,
655    de: &'seq mut DeserializerFromEvents<'de, 'document>,
656    len: usize,
657}
658
659impl<'de> de::SeqAccess<'de> for SeqAccess<'de, '_, '_> {
660    type Error = Error;
661
662    fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>>
663    where
664        T: DeserializeSeed<'de>,
665    {
666        if self.empty {
667            return Ok(None);
668        }
669        match self.de.peek_event()? {
670            Event::SequenceEnd | Event::Void => Ok(None),
671            _ => {
672                let mut element_de = DeserializerFromEvents {
673                    document: self.de.document,
674                    pos: self.de.pos,
675                    jumpcount: self.de.jumpcount,
676                    path: Path::Seq {
677                        parent: &self.de.path,
678                        index: self.len,
679                    },
680                    remaining_depth: self.de.remaining_depth,
681                    current_enum: None,
682                };
683                self.len += 1;
684                seed.deserialize(&mut element_de).map(Some)
685            }
686        }
687    }
688}
689
690struct MapAccess<'de, 'document, 'map> {
691    empty: bool,
692    de: &'map mut DeserializerFromEvents<'de, 'document>,
693    len: usize,
694    key: Option<&'document [u8]>,
695}
696
697impl<'de> de::MapAccess<'de> for MapAccess<'de, '_, '_> {
698    type Error = Error;
699
700    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>>
701    where
702        K: DeserializeSeed<'de>,
703    {
704        if self.empty {
705            return Ok(None);
706        }
707        match self.de.peek_event()? {
708            Event::MappingEnd | Event::Void => Ok(None),
709            Event::Scalar(scalar) => {
710                self.len += 1;
711                self.key = Some(&scalar.value);
712                seed.deserialize(&mut *self.de).map(Some)
713            }
714            _ => {
715                self.len += 1;
716                self.key = None;
717                seed.deserialize(&mut *self.de).map(Some)
718            }
719        }
720    }
721
722    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value>
723    where
724        V: DeserializeSeed<'de>,
725    {
726        let mut value_de = DeserializerFromEvents {
727            document: self.de.document,
728            pos: self.de.pos,
729            jumpcount: self.de.jumpcount,
730            path: if let Some(key) = self.key.and_then(|key| str::from_utf8(key).ok()) {
731                Path::Map {
732                    parent: &self.de.path,
733                    key,
734                }
735            } else {
736                Path::Unknown {
737                    parent: &self.de.path,
738                }
739            },
740            remaining_depth: self.de.remaining_depth,
741            current_enum: None,
742        };
743        seed.deserialize(&mut value_de)
744    }
745}
746
747struct EnumAccess<'de, 'document, 'variant> {
748    de: &'variant mut DeserializerFromEvents<'de, 'document>,
749    name: Option<&'static str>,
750    tag: &'document str,
751}
752
753impl<'de, 'variant> de::EnumAccess<'de> for EnumAccess<'de, '_, 'variant> {
754    type Error = Error;
755    type Variant = DeserializerFromEvents<'de, 'variant>;
756
757    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
758    where
759        V: DeserializeSeed<'de>,
760    {
761        let str_de = StrDeserializer::<Error>::new(self.tag);
762        let variant = seed.deserialize(str_de)?;
763        let visitor = DeserializerFromEvents {
764            document: self.de.document,
765            pos: self.de.pos,
766            jumpcount: self.de.jumpcount,
767            path: self.de.path,
768            remaining_depth: self.de.remaining_depth,
769            current_enum: Some(CurrentEnum {
770                name: self.name,
771                tag: self.tag,
772            }),
773        };
774        Ok((variant, visitor))
775    }
776}
777
778impl<'de> de::VariantAccess<'de> for DeserializerFromEvents<'de, '_> {
779    type Error = Error;
780
781    fn unit_variant(mut self) -> Result<()> {
782        Deserialize::deserialize(&mut self)
783    }
784
785    fn newtype_variant_seed<T>(mut self, seed: T) -> Result<T::Value>
786    where
787        T: DeserializeSeed<'de>,
788    {
789        seed.deserialize(&mut self)
790    }
791
792    fn tuple_variant<V>(mut self, _len: usize, visitor: V) -> Result<V::Value>
793    where
794        V: Visitor<'de>,
795    {
796        de::Deserializer::deserialize_seq(&mut self, visitor)
797    }
798
799    fn struct_variant<V>(mut self, fields: &'static [&'static str], visitor: V) -> Result<V::Value>
800    where
801        V: Visitor<'de>,
802    {
803        de::Deserializer::deserialize_struct(&mut self, "", fields, visitor)
804    }
805}
806
807struct UnitVariantAccess<'de, 'document, 'variant> {
808    de: &'variant mut DeserializerFromEvents<'de, 'document>,
809}
810
811impl<'de> de::EnumAccess<'de> for UnitVariantAccess<'de, '_, '_> {
812    type Error = Error;
813    type Variant = Self;
814
815    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)>
816    where
817        V: DeserializeSeed<'de>,
818    {
819        Ok((seed.deserialize(&mut *self.de)?, self))
820    }
821}
822
823impl<'de> de::VariantAccess<'de> for UnitVariantAccess<'de, '_, '_> {
824    type Error = Error;
825
826    fn unit_variant(self) -> Result<()> {
827        Ok(())
828    }
829
830    fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value>
831    where
832        T: DeserializeSeed<'de>,
833    {
834        Err(de::Error::invalid_type(
835            Unexpected::UnitVariant,
836            &"newtype variant",
837        ))
838    }
839
840    fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value>
841    where
842        V: Visitor<'de>,
843    {
844        Err(de::Error::invalid_type(
845            Unexpected::UnitVariant,
846            &"tuple variant",
847        ))
848    }
849
850    fn struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value>
851    where
852        V: Visitor<'de>,
853    {
854        Err(de::Error::invalid_type(
855            Unexpected::UnitVariant,
856            &"struct variant",
857        ))
858    }
859}
860
861fn visit_scalar<'de, V>(visitor: V, scalar: &Scalar<'de>, tagged_already: bool) -> Result<V::Value>
862where
863    V: Visitor<'de>,
864{
865    let v = match str::from_utf8(&scalar.value) {
866        Ok(v) => v,
867        Err(_) => {
868            return Err(de::Error::invalid_type(
869                Unexpected::Bytes(&scalar.value),
870                &visitor,
871            ))
872        }
873    };
874    if let (Some(tag), false) = (&scalar.tag, tagged_already) {
875        if tag == Tag::BOOL {
876            return match parse_bool(v) {
877                Some(v) => visitor.visit_bool(v),
878                None => Err(de::Error::invalid_value(Unexpected::Str(v), &"a boolean")),
879            };
880        } else if tag == Tag::INT {
881            return match visit_int(visitor, v) {
882                Ok(result) => result,
883                Err(_) => Err(de::Error::invalid_value(Unexpected::Str(v), &"an integer")),
884            };
885        } else if tag == Tag::FLOAT {
886            return match parse_f64(v) {
887                Some(v) => visitor.visit_f64(v),
888                None => Err(de::Error::invalid_value(Unexpected::Str(v), &"a float")),
889            };
890        } else if tag == Tag::NULL {
891            return match parse_null(v.as_bytes()) {
892                Some(()) => visitor.visit_unit(),
893                None => Err(de::Error::invalid_value(Unexpected::Str(v), &"null")),
894            };
895        } else if tag.starts_with("!") && scalar.style == ScalarStyle::Plain {
896            return visit_untagged_scalar(visitor, v, scalar.repr, scalar.style);
897        }
898    } else if scalar.style == ScalarStyle::Plain {
899        return visit_untagged_scalar(visitor, v, scalar.repr, scalar.style);
900    }
901    if let Some(borrowed) = parse_borrowed_str(v, scalar.repr, scalar.style) {
902        visitor.visit_borrowed_str(borrowed)
903    } else {
904        visitor.visit_str(v)
905    }
906}
907
908fn parse_borrowed_str<'de>(
909    utf8_value: &str,
910    repr: Option<&'de [u8]>,
911    style: ScalarStyle,
912) -> Option<&'de str> {
913    let borrowed_repr = repr?;
914    let expected_offset = match style {
915        ScalarStyle::Plain => 0,
916        ScalarStyle::SingleQuoted | ScalarStyle::DoubleQuoted => 1,
917        ScalarStyle::Literal | ScalarStyle::Folded => return None,
918    };
919    let expected_end = borrowed_repr.len().checked_sub(expected_offset)?;
920    let expected_start = expected_end.checked_sub(utf8_value.len())?;
921    let borrowed_bytes = borrowed_repr.get(expected_start..expected_end)?;
922    if borrowed_bytes == utf8_value.as_bytes() {
923        return Some(unsafe { str::from_utf8_unchecked(borrowed_bytes) });
924    }
925    None
926}
927
928fn parse_null(scalar: &[u8]) -> Option<()> {
929    match scalar {
930        b"null" | b"Null" | b"NULL" | b"~" => Some(()),
931        _ => None,
932    }
933}
934
935fn parse_bool(scalar: &str) -> Option<bool> {
936    match scalar {
937        "true" | "True" | "TRUE" => Some(true),
938        "false" | "False" | "FALSE" => Some(false),
939        _ => None,
940    }
941}
942
943fn parse_unsigned_int<T>(
944    scalar: &str,
945    from_str_radix: fn(&str, radix: u32) -> Result<T, ParseIntError>,
946) -> Option<T> {
947    let unpositive = scalar.strip_prefix('+').unwrap_or(scalar);
948    if let Some(rest) = unpositive.strip_prefix("0x") {
949        if rest.starts_with(['+', '-']) {
950            return None;
951        }
952        if let Ok(int) = from_str_radix(rest, 16) {
953            return Some(int);
954        }
955    }
956    if let Some(rest) = unpositive.strip_prefix("0o") {
957        if rest.starts_with(['+', '-']) {
958            return None;
959        }
960        if let Ok(int) = from_str_radix(rest, 8) {
961            return Some(int);
962        }
963    }
964    if let Some(rest) = unpositive.strip_prefix("0b") {
965        if rest.starts_with(['+', '-']) {
966            return None;
967        }
968        if let Ok(int) = from_str_radix(rest, 2) {
969            return Some(int);
970        }
971    }
972    if unpositive.starts_with(['+', '-']) {
973        return None;
974    }
975    if digits_but_not_number(scalar) {
976        return None;
977    }
978    from_str_radix(unpositive, 10).ok()
979}
980
981fn parse_signed_int<T>(
982    scalar: &str,
983    from_str_radix: fn(&str, radix: u32) -> Result<T, ParseIntError>,
984) -> Option<T> {
985    let unpositive = if let Some(unpositive) = scalar.strip_prefix('+') {
986        if unpositive.starts_with(['+', '-']) {
987            return None;
988        }
989        unpositive
990    } else {
991        scalar
992    };
993    if let Some(rest) = unpositive.strip_prefix("0x") {
994        if rest.starts_with(['+', '-']) {
995            return None;
996        }
997        if let Ok(int) = from_str_radix(rest, 16) {
998            return Some(int);
999        }
1000    }
1001    if let Some(rest) = scalar.strip_prefix("-0x") {
1002        let negative = format!("-{}", rest);
1003        if let Ok(int) = from_str_radix(&negative, 16) {
1004            return Some(int);
1005        }
1006    }
1007    if let Some(rest) = unpositive.strip_prefix("0o") {
1008        if rest.starts_with(['+', '-']) {
1009            return None;
1010        }
1011        if let Ok(int) = from_str_radix(rest, 8) {
1012            return Some(int);
1013        }
1014    }
1015    if let Some(rest) = scalar.strip_prefix("-0o") {
1016        let negative = format!("-{}", rest);
1017        if let Ok(int) = from_str_radix(&negative, 8) {
1018            return Some(int);
1019        }
1020    }
1021    if let Some(rest) = unpositive.strip_prefix("0b") {
1022        if rest.starts_with(['+', '-']) {
1023            return None;
1024        }
1025        if let Ok(int) = from_str_radix(rest, 2) {
1026            return Some(int);
1027        }
1028    }
1029    if let Some(rest) = scalar.strip_prefix("-0b") {
1030        let negative = format!("-{}", rest);
1031        if let Ok(int) = from_str_radix(&negative, 2) {
1032            return Some(int);
1033        }
1034    }
1035    if digits_but_not_number(scalar) {
1036        return None;
1037    }
1038    from_str_radix(unpositive, 10).ok()
1039}
1040
1041fn parse_negative_int<T>(
1042    scalar: &str,
1043    from_str_radix: fn(&str, radix: u32) -> Result<T, ParseIntError>,
1044) -> Option<T> {
1045    if let Some(rest) = scalar.strip_prefix("-0x") {
1046        let negative = format!("-{}", rest);
1047        if let Ok(int) = from_str_radix(&negative, 16) {
1048            return Some(int);
1049        }
1050    }
1051    if let Some(rest) = scalar.strip_prefix("-0o") {
1052        let negative = format!("-{}", rest);
1053        if let Ok(int) = from_str_radix(&negative, 8) {
1054            return Some(int);
1055        }
1056    }
1057    if let Some(rest) = scalar.strip_prefix("-0b") {
1058        let negative = format!("-{}", rest);
1059        if let Ok(int) = from_str_radix(&negative, 2) {
1060            return Some(int);
1061        }
1062    }
1063    if digits_but_not_number(scalar) {
1064        return None;
1065    }
1066    from_str_radix(scalar, 10).ok()
1067}
1068
1069pub(crate) fn parse_f64(scalar: &str) -> Option<f64> {
1070    let unpositive = if let Some(unpositive) = scalar.strip_prefix('+') {
1071        if unpositive.starts_with(['+', '-']) {
1072            return None;
1073        }
1074        unpositive
1075    } else {
1076        scalar
1077    };
1078    if let ".inf" | ".Inf" | ".INF" = unpositive {
1079        return Some(f64::INFINITY);
1080    }
1081    if let "-.inf" | "-.Inf" | "-.INF" = scalar {
1082        return Some(f64::NEG_INFINITY);
1083    }
1084    if let ".nan" | ".NaN" | ".NAN" = scalar {
1085        return Some(f64::NAN.copysign(1.0));
1086    }
1087    if let Ok(float) = unpositive.parse::<f64>() {
1088        if float.is_finite() {
1089            return Some(float);
1090        }
1091    }
1092    None
1093}
1094
1095pub(crate) fn digits_but_not_number(scalar: &str) -> bool {
1096    // Leading zero(s) followed by numeric characters is a string according to
1097    // the YAML 1.2 spec. https://yaml.org/spec/1.2/spec.html#id2761292
1098    let scalar = scalar.strip_prefix(['-', '+']).unwrap_or(scalar);
1099    scalar.len() > 1 && scalar.starts_with('0') && scalar[1..].bytes().all(|b| b.is_ascii_digit())
1100}
1101
1102pub(crate) fn visit_int<'de, V>(visitor: V, v: &str) -> Result<Result<V::Value>, V>
1103where
1104    V: Visitor<'de>,
1105{
1106    if let Some(int) = parse_unsigned_int(v, u64::from_str_radix) {
1107        return Ok(visitor.visit_u64(int));
1108    }
1109    if let Some(int) = parse_negative_int(v, i64::from_str_radix) {
1110        return Ok(visitor.visit_i64(int));
1111    }
1112    if let Some(int) = parse_unsigned_int(v, u128::from_str_radix) {
1113        return Ok(visitor.visit_u128(int));
1114    }
1115    if let Some(int) = parse_negative_int(v, i128::from_str_radix) {
1116        return Ok(visitor.visit_i128(int));
1117    }
1118    Err(visitor)
1119}
1120
1121pub(crate) fn visit_untagged_scalar<'de, V>(
1122    visitor: V,
1123    v: &str,
1124    repr: Option<&'de [u8]>,
1125    style: ScalarStyle,
1126) -> Result<V::Value>
1127where
1128    V: Visitor<'de>,
1129{
1130    if v.is_empty() || parse_null(v.as_bytes()) == Some(()) {
1131        return visitor.visit_unit();
1132    }
1133    if let Some(boolean) = parse_bool(v) {
1134        return visitor.visit_bool(boolean);
1135    }
1136    let visitor = match visit_int(visitor, v) {
1137        Ok(result) => return result,
1138        Err(visitor) => visitor,
1139    };
1140    if !digits_but_not_number(v) {
1141        if let Some(float) = parse_f64(v) {
1142            return visitor.visit_f64(float);
1143        }
1144    }
1145    if let Some(borrowed) = parse_borrowed_str(v, repr, style) {
1146        visitor.visit_borrowed_str(borrowed)
1147    } else {
1148        visitor.visit_str(v)
1149    }
1150}
1151
1152fn is_plain_or_tagged_literal_scalar(
1153    expected: &str,
1154    scalar: &Scalar,
1155    tagged_already: bool,
1156) -> bool {
1157    match (scalar.style, &scalar.tag, tagged_already) {
1158        (ScalarStyle::Plain, _, _) => true,
1159        (ScalarStyle::Literal, Some(tag), false) => tag == expected,
1160        _ => false,
1161    }
1162}
1163
1164fn invalid_type(event: &Event, exp: &dyn Expected) -> Error {
1165    enum Void {}
1166
1167    struct InvalidType<'a> {
1168        exp: &'a dyn Expected,
1169    }
1170
1171    impl Visitor<'_> for InvalidType<'_> {
1172        type Value = Void;
1173
1174        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1175            self.exp.fmt(formatter)
1176        }
1177    }
1178
1179    match event {
1180        Event::Alias(_) => unreachable!(),
1181        Event::Scalar(scalar) => {
1182            let get_type = InvalidType { exp };
1183            match visit_scalar(get_type, scalar, false) {
1184                Ok(void) => match void {},
1185                Err(invalid_type) => invalid_type,
1186            }
1187        }
1188        Event::SequenceStart(_) => de::Error::invalid_type(Unexpected::Seq, exp),
1189        Event::MappingStart(_) => de::Error::invalid_type(Unexpected::Map, exp),
1190        Event::SequenceEnd => panic!("unexpected end of sequence"),
1191        Event::MappingEnd => panic!("unexpected end of mapping"),
1192        Event::Void => error::new(ErrorImpl::EndOfStream),
1193    }
1194}
1195
1196fn parse_tag(libyaml_tag: &Option<Tag>) -> Option<&str> {
1197    let mut bytes: &[u8] = libyaml_tag.as_ref()?;
1198    if let (b'!', rest) = bytes.split_first()? {
1199        if !rest.is_empty() {
1200            bytes = rest;
1201        }
1202        str::from_utf8(bytes).ok()
1203    } else {
1204        None
1205    }
1206}
1207
1208impl<'de> de::Deserializer<'de> for &mut DeserializerFromEvents<'de, '_> {
1209    type Error = Error;
1210
1211    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
1212    where
1213        V: Visitor<'de>,
1214    {
1215        let tagged_already = self.current_enum.is_some();
1216        let (next, mark) = self.next_event_mark()?;
1217        fn enum_tag(tag: &Option<Tag>, tagged_already: bool) -> Option<&str> {
1218            if tagged_already {
1219                return None;
1220            }
1221            parse_tag(tag)
1222        }
1223        loop {
1224            match next {
1225                Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_any(visitor),
1226                Event::Scalar(scalar) => {
1227                    if let Some(tag) = enum_tag(&scalar.tag, tagged_already) {
1228                        *self.pos -= 1;
1229                        break visitor.visit_enum(EnumAccess {
1230                            de: self,
1231                            name: None,
1232                            tag,
1233                        });
1234                    }
1235                    break visit_scalar(visitor, scalar, tagged_already);
1236                }
1237                Event::SequenceStart(sequence) => {
1238                    if let Some(tag) = enum_tag(&sequence.tag, tagged_already) {
1239                        *self.pos -= 1;
1240                        break visitor.visit_enum(EnumAccess {
1241                            de: self,
1242                            name: None,
1243                            tag,
1244                        });
1245                    }
1246                    break self.visit_sequence(visitor, mark);
1247                }
1248                Event::MappingStart(mapping) => {
1249                    if let Some(tag) = enum_tag(&mapping.tag, tagged_already) {
1250                        *self.pos -= 1;
1251                        break visitor.visit_enum(EnumAccess {
1252                            de: self,
1253                            name: None,
1254                            tag,
1255                        });
1256                    }
1257                    break self.visit_mapping(visitor, mark);
1258                }
1259                Event::SequenceEnd => panic!("unexpected end of sequence"),
1260                Event::MappingEnd => panic!("unexpected end of mapping"),
1261                Event::Void => break visitor.visit_none(),
1262            }
1263        }
1264        // The de::Error impl creates errors with unknown line and column. Fill
1265        // in the position here by looking at the current index in the input.
1266        .map_err(|err| error::fix_mark(err, mark, self.path))
1267    }
1268
1269    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value>
1270    where
1271        V: Visitor<'de>,
1272    {
1273        let tagged_already = self.current_enum.is_some();
1274        let (next, mark) = self.next_event_mark()?;
1275        loop {
1276            match next {
1277                Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_bool(visitor),
1278                Event::Scalar(scalar)
1279                    if is_plain_or_tagged_literal_scalar(Tag::BOOL, scalar, tagged_already) =>
1280                {
1281                    if let Ok(value) = str::from_utf8(&scalar.value) {
1282                        if let Some(boolean) = parse_bool(value) {
1283                            break visitor.visit_bool(boolean);
1284                        }
1285                    }
1286                }
1287                _ => {}
1288            }
1289            break Err(invalid_type(next, &visitor));
1290        }
1291        .map_err(|err| error::fix_mark(err, mark, self.path))
1292    }
1293
1294    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value>
1295    where
1296        V: Visitor<'de>,
1297    {
1298        self.deserialize_i64(visitor)
1299    }
1300
1301    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value>
1302    where
1303        V: Visitor<'de>,
1304    {
1305        self.deserialize_i64(visitor)
1306    }
1307
1308    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value>
1309    where
1310        V: Visitor<'de>,
1311    {
1312        self.deserialize_i64(visitor)
1313    }
1314
1315    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value>
1316    where
1317        V: Visitor<'de>,
1318    {
1319        let tagged_already = self.current_enum.is_some();
1320        let (next, mark) = self.next_event_mark()?;
1321        loop {
1322            match next {
1323                Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_i64(visitor),
1324                Event::Scalar(scalar)
1325                    if is_plain_or_tagged_literal_scalar(Tag::INT, scalar, tagged_already) =>
1326                {
1327                    if let Ok(value) = str::from_utf8(&scalar.value) {
1328                        if let Some(int) = parse_signed_int(value, i64::from_str_radix) {
1329                            break visitor.visit_i64(int);
1330                        }
1331                    }
1332                }
1333                _ => {}
1334            }
1335            break Err(invalid_type(next, &visitor));
1336        }
1337        .map_err(|err| error::fix_mark(err, mark, self.path))
1338    }
1339
1340    fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value>
1341    where
1342        V: Visitor<'de>,
1343    {
1344        let tagged_already = self.current_enum.is_some();
1345        let (next, mark) = self.next_event_mark()?;
1346        loop {
1347            match next {
1348                Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_i128(visitor),
1349                Event::Scalar(scalar)
1350                    if is_plain_or_tagged_literal_scalar(Tag::INT, scalar, tagged_already) =>
1351                {
1352                    if let Ok(value) = str::from_utf8(&scalar.value) {
1353                        if let Some(int) = parse_signed_int(value, i128::from_str_radix) {
1354                            break visitor.visit_i128(int);
1355                        }
1356                    }
1357                }
1358                _ => {}
1359            }
1360            break Err(invalid_type(next, &visitor));
1361        }
1362        .map_err(|err| error::fix_mark(err, mark, self.path))
1363    }
1364
1365    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value>
1366    where
1367        V: Visitor<'de>,
1368    {
1369        self.deserialize_u64(visitor)
1370    }
1371
1372    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value>
1373    where
1374        V: Visitor<'de>,
1375    {
1376        self.deserialize_u64(visitor)
1377    }
1378
1379    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value>
1380    where
1381        V: Visitor<'de>,
1382    {
1383        self.deserialize_u64(visitor)
1384    }
1385
1386    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value>
1387    where
1388        V: Visitor<'de>,
1389    {
1390        let tagged_already = self.current_enum.is_some();
1391        let (next, mark) = self.next_event_mark()?;
1392        loop {
1393            match next {
1394                Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_u64(visitor),
1395                Event::Scalar(scalar)
1396                    if is_plain_or_tagged_literal_scalar(Tag::INT, scalar, tagged_already) =>
1397                {
1398                    if let Ok(value) = str::from_utf8(&scalar.value) {
1399                        if let Some(int) = parse_unsigned_int(value, u64::from_str_radix) {
1400                            break visitor.visit_u64(int);
1401                        }
1402                    }
1403                }
1404                _ => {}
1405            }
1406            break Err(invalid_type(next, &visitor));
1407        }
1408        .map_err(|err| error::fix_mark(err, mark, self.path))
1409    }
1410
1411    fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value>
1412    where
1413        V: Visitor<'de>,
1414    {
1415        let tagged_already = self.current_enum.is_some();
1416        let (next, mark) = self.next_event_mark()?;
1417        loop {
1418            match next {
1419                Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_u128(visitor),
1420                Event::Scalar(scalar)
1421                    if is_plain_or_tagged_literal_scalar(Tag::INT, scalar, tagged_already) =>
1422                {
1423                    if let Ok(value) = str::from_utf8(&scalar.value) {
1424                        if let Some(int) = parse_unsigned_int(value, u128::from_str_radix) {
1425                            break visitor.visit_u128(int);
1426                        }
1427                    }
1428                }
1429                _ => {}
1430            }
1431            break Err(invalid_type(next, &visitor));
1432        }
1433        .map_err(|err| error::fix_mark(err, mark, self.path))
1434    }
1435
1436    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value>
1437    where
1438        V: Visitor<'de>,
1439    {
1440        self.deserialize_f64(visitor)
1441    }
1442
1443    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value>
1444    where
1445        V: Visitor<'de>,
1446    {
1447        let tagged_already = self.current_enum.is_some();
1448        let (next, mark) = self.next_event_mark()?;
1449        loop {
1450            match next {
1451                Event::Alias(mut pos) => break self.jump(&mut pos)?.deserialize_f64(visitor),
1452                Event::Scalar(scalar)
1453                    if is_plain_or_tagged_literal_scalar(Tag::FLOAT, scalar, tagged_already) =>
1454                {
1455                    if let Ok(value) = str::from_utf8(&scalar.value) {
1456                        if let Some(float) = parse_f64(value) {
1457                            break visitor.visit_f64(float);
1458                        }
1459                    }
1460                }
1461                _ => {}
1462            }
1463            break Err(invalid_type(next, &visitor));
1464        }
1465        .map_err(|err| error::fix_mark(err, mark, self.path))
1466    }
1467
1468    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value>
1469    where
1470        V: Visitor<'de>,
1471    {
1472        self.deserialize_str(visitor)
1473    }
1474
1475    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value>
1476    where
1477        V: Visitor<'de>,
1478    {
1479        let (next, mark) = self.next_event_mark()?;
1480        match next {
1481            Event::Scalar(scalar) => {
1482                if let Ok(v) = str::from_utf8(&scalar.value) {
1483                    if let Some(borrowed) = parse_borrowed_str(v, scalar.repr, scalar.style) {
1484                        visitor.visit_borrowed_str(borrowed)
1485                    } else {
1486                        visitor.visit_str(v)
1487                    }
1488                } else {
1489                    Err(invalid_type(next, &visitor))
1490                }
1491            }
1492            Event::Alias(mut pos) => self.jump(&mut pos)?.deserialize_str(visitor),
1493            other => Err(invalid_type(other, &visitor)),
1494        }
1495        .map_err(|err: Error| error::fix_mark(err, mark, self.path))
1496    }
1497
1498    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value>
1499    where
1500        V: Visitor<'de>,
1501    {
1502        self.deserialize_str(visitor)
1503    }
1504
1505    fn deserialize_bytes<V>(self, _visitor: V) -> Result<V::Value>
1506    where
1507        V: Visitor<'de>,
1508    {
1509        Err(error::new(ErrorImpl::BytesUnsupported))
1510    }
1511
1512    fn deserialize_byte_buf<V>(self, _visitor: V) -> Result<V::Value>
1513    where
1514        V: Visitor<'de>,
1515    {
1516        Err(error::new(ErrorImpl::BytesUnsupported))
1517    }
1518
1519    /// Parses `null` as None and any other values as `Some(...)`.
1520    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
1521    where
1522        V: Visitor<'de>,
1523    {
1524        let is_some = match self.peek_event()? {
1525            Event::Alias(mut pos) => {
1526                *self.pos += 1;
1527                return self.jump(&mut pos)?.deserialize_option(visitor);
1528            }
1529            Event::Scalar(scalar) => {
1530                let tagged_already = self.current_enum.is_some();
1531                if scalar.style != ScalarStyle::Plain {
1532                    true
1533                } else if let (Some(tag), false) = (&scalar.tag, tagged_already) {
1534                    if tag == Tag::NULL {
1535                        if let Some(()) = parse_null(&scalar.value) {
1536                            false
1537                        } else if let Ok(v) = str::from_utf8(&scalar.value) {
1538                            return Err(de::Error::invalid_value(Unexpected::Str(v), &"null"));
1539                        } else {
1540                            return Err(de::Error::invalid_value(
1541                                Unexpected::Bytes(&scalar.value),
1542                                &"null",
1543                            ));
1544                        }
1545                    } else {
1546                        true
1547                    }
1548                } else {
1549                    !scalar.value.is_empty() && parse_null(&scalar.value).is_none()
1550                }
1551            }
1552            Event::SequenceStart(_) | Event::MappingStart(_) => true,
1553            Event::SequenceEnd => panic!("unexpected end of sequence"),
1554            Event::MappingEnd => panic!("unexpected end of mapping"),
1555            Event::Void => false,
1556        };
1557        if is_some {
1558            visitor.visit_some(self)
1559        } else {
1560            *self.pos += 1;
1561            self.current_enum = None;
1562            visitor.visit_unit()
1563        }
1564    }
1565
1566    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value>
1567    where
1568        V: Visitor<'de>,
1569    {
1570        let tagged_already = self.current_enum.is_some();
1571        let (next, mark) = self.next_event_mark()?;
1572        match next {
1573            Event::Scalar(scalar) => {
1574                let is_null = if scalar.style != ScalarStyle::Plain {
1575                    false
1576                } else if let (Some(tag), false) = (&scalar.tag, tagged_already) {
1577                    tag == Tag::NULL && parse_null(&scalar.value).is_some()
1578                } else {
1579                    scalar.value.is_empty() || parse_null(&scalar.value).is_some()
1580                };
1581                if is_null {
1582                    visitor.visit_unit()
1583                } else if let Ok(v) = str::from_utf8(&scalar.value) {
1584                    Err(de::Error::invalid_value(Unexpected::Str(v), &"null"))
1585                } else {
1586                    Err(de::Error::invalid_value(
1587                        Unexpected::Bytes(&scalar.value),
1588                        &"null",
1589                    ))
1590                }
1591            }
1592            Event::Alias(mut pos) => self.jump(&mut pos)?.deserialize_unit(visitor),
1593            Event::Void => visitor.visit_unit(),
1594            other => Err(invalid_type(other, &visitor)),
1595        }
1596        .map_err(|err| error::fix_mark(err, mark, self.path))
1597    }
1598
1599    fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
1600    where
1601        V: Visitor<'de>,
1602    {
1603        self.deserialize_unit(visitor)
1604    }
1605
1606    /// Parses a newtype struct as the underlying value.
1607    fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>
1608    where
1609        V: Visitor<'de>,
1610    {
1611        let (_event, mark) = self.peek_event_mark()?;
1612        self.recursion_check(mark, |de| visitor.visit_newtype_struct(de))
1613    }
1614
1615    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value>
1616    where
1617        V: Visitor<'de>,
1618    {
1619        let (next, mark) = self.next_event_mark()?;
1620        match next {
1621            Event::Alias(mut pos) => self.jump(&mut pos)?.deserialize_seq(visitor),
1622            Event::SequenceStart(_) => self.visit_sequence(visitor, mark),
1623            other => {
1624                if match other {
1625                    Event::Void => true,
1626                    Event::Scalar(scalar) => {
1627                        scalar.value.is_empty() && scalar.style == ScalarStyle::Plain
1628                    }
1629                    _ => false,
1630                } {
1631                    visitor.visit_seq(SeqAccess {
1632                        empty: true,
1633                        de: self,
1634                        len: 0,
1635                    })
1636                } else {
1637                    Err(invalid_type(other, &visitor))
1638                }
1639            }
1640        }
1641        .map_err(|err| error::fix_mark(err, mark, self.path))
1642    }
1643
1644    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value>
1645    where
1646        V: Visitor<'de>,
1647    {
1648        self.deserialize_seq(visitor)
1649    }
1650
1651    fn deserialize_tuple_struct<V>(
1652        self,
1653        _name: &'static str,
1654        _len: usize,
1655        visitor: V,
1656    ) -> Result<V::Value>
1657    where
1658        V: Visitor<'de>,
1659    {
1660        self.deserialize_seq(visitor)
1661    }
1662
1663    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
1664    where
1665        V: Visitor<'de>,
1666    {
1667        let (next, mark) = self.next_event_mark()?;
1668        match next {
1669            Event::Alias(mut pos) => self.jump(&mut pos)?.deserialize_map(visitor),
1670            Event::MappingStart(_) => self.visit_mapping(visitor, mark),
1671            other => {
1672                if match other {
1673                    Event::Void => true,
1674                    Event::Scalar(scalar) => {
1675                        scalar.value.is_empty() && scalar.style == ScalarStyle::Plain
1676                    }
1677                    _ => false,
1678                } {
1679                    visitor.visit_map(MapAccess {
1680                        empty: true,
1681                        de: self,
1682                        len: 0,
1683                        key: None,
1684                    })
1685                } else {
1686                    Err(invalid_type(other, &visitor))
1687                }
1688            }
1689        }
1690        .map_err(|err| error::fix_mark(err, mark, self.path))
1691    }
1692
1693    fn deserialize_struct<V>(
1694        self,
1695        _name: &'static str,
1696        _fields: &'static [&'static str],
1697        visitor: V,
1698    ) -> Result<V::Value>
1699    where
1700        V: Visitor<'de>,
1701    {
1702        self.deserialize_map(visitor)
1703    }
1704
1705    /// Parses an enum as a single key:value pair where the key identifies the
1706    /// variant and the value gives the content. A String will also parse correctly
1707    /// to a unit enum value.
1708    fn deserialize_enum<V>(
1709        self,
1710        name: &'static str,
1711        variants: &'static [&'static str],
1712        visitor: V,
1713    ) -> Result<V::Value>
1714    where
1715        V: Visitor<'de>,
1716    {
1717        let (next, mark) = self.peek_event_mark()?;
1718        loop {
1719            if let Some(current_enum) = self.current_enum {
1720                if let Event::Scalar(scalar) = next {
1721                    if !scalar.value.is_empty() {
1722                        break visitor.visit_enum(UnitVariantAccess { de: self });
1723                    }
1724                }
1725                let message = if let Some(name) = current_enum.name {
1726                    format!(
1727                        "deserializing nested enum in {}::{} from YAML is not supported yet",
1728                        name, current_enum.tag,
1729                    )
1730                } else {
1731                    format!(
1732                        "deserializing nested enum in !{} from YAML is not supported yet",
1733                        current_enum.tag,
1734                    )
1735                };
1736                break Err(error::new(ErrorImpl::Message(message, None)));
1737            }
1738            break match next {
1739                Event::Alias(mut pos) => {
1740                    *self.pos += 1;
1741                    self.jump(&mut pos)?
1742                        .deserialize_enum(name, variants, visitor)
1743                }
1744                Event::Scalar(scalar) => {
1745                    if let Some(tag) = parse_tag(&scalar.tag) {
1746                        return visitor.visit_enum(EnumAccess {
1747                            de: self,
1748                            name: Some(name),
1749                            tag,
1750                        });
1751                    }
1752                    visitor.visit_enum(UnitVariantAccess { de: self })
1753                }
1754                Event::MappingStart(mapping) => {
1755                    if let Some(tag) = parse_tag(&mapping.tag) {
1756                        return visitor.visit_enum(EnumAccess {
1757                            de: self,
1758                            name: Some(name),
1759                            tag,
1760                        });
1761                    }
1762                    let err =
1763                        de::Error::invalid_type(Unexpected::Map, &"a YAML tag starting with '!'");
1764                    Err(error::fix_mark(err, mark, self.path))
1765                }
1766                Event::SequenceStart(sequence) => {
1767                    if let Some(tag) = parse_tag(&sequence.tag) {
1768                        return visitor.visit_enum(EnumAccess {
1769                            de: self,
1770                            name: Some(name),
1771                            tag,
1772                        });
1773                    }
1774                    let err =
1775                        de::Error::invalid_type(Unexpected::Seq, &"a YAML tag starting with '!'");
1776                    Err(error::fix_mark(err, mark, self.path))
1777                }
1778                Event::SequenceEnd => panic!("unexpected end of sequence"),
1779                Event::MappingEnd => panic!("unexpected end of mapping"),
1780                Event::Void => Err(error::new(ErrorImpl::EndOfStream)),
1781            };
1782        }
1783        .map_err(|err| error::fix_mark(err, mark, self.path))
1784    }
1785
1786    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value>
1787    where
1788        V: Visitor<'de>,
1789    {
1790        self.deserialize_str(visitor)
1791    }
1792
1793    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value>
1794    where
1795        V: Visitor<'de>,
1796    {
1797        self.ignore_any()?;
1798        visitor.visit_unit()
1799    }
1800}
1801
1802/// Deserialize an instance of type `T` from a string of YAML text.
1803///
1804/// This conversion can fail if the structure of the Value does not match the
1805/// structure expected by `T`, for example if `T` is a struct type but the Value
1806/// contains something other than a YAML map. It can also fail if the structure
1807/// is correct but `T`'s implementation of `Deserialize` decides that something
1808/// is wrong with the data, for example required struct fields are missing from
1809/// the YAML map or some number is too big to fit in the expected primitive
1810/// type.
1811pub fn from_str<'de, T>(s: &'de str) -> Result<T>
1812where
1813    T: Deserialize<'de>,
1814{
1815    spanned::set_marker(spanned::Marker::start());
1816    let res = T::deserialize(Deserializer::from_str(s));
1817    spanned::reset_marker();
1818    res
1819}
1820
1821/// Deserialize an instance of type `T` from an IO stream of YAML.
1822///
1823/// This conversion can fail if the structure of the Value does not match the
1824/// structure expected by `T`, for example if `T` is a struct type but the Value
1825/// contains something other than a YAML map. It can also fail if the structure
1826/// is correct but `T`'s implementation of `Deserialize` decides that something
1827/// is wrong with the data, for example required struct fields are missing from
1828/// the YAML map or some number is too big to fit in the expected primitive
1829/// type.
1830pub fn from_reader<R, T>(rdr: R) -> Result<T>
1831where
1832    R: io::Read,
1833    T: DeserializeOwned,
1834{
1835    spanned::set_marker(spanned::Marker::start());
1836    let res = T::deserialize(Deserializer::from_reader(rdr));
1837    spanned::reset_marker();
1838    res
1839}
1840
1841/// Deserialize an instance of type `T` from bytes of YAML text.
1842///
1843/// This conversion can fail if the structure of the Value does not match the
1844/// structure expected by `T`, for example if `T` is a struct type but the Value
1845/// contains something other than a YAML map. It can also fail if the structure
1846/// is correct but `T`'s implementation of `Deserialize` decides that something
1847/// is wrong with the data, for example required struct fields are missing from
1848/// the YAML map or some number is too big to fit in the expected primitive
1849/// type.
1850pub fn from_slice<'de, T>(v: &'de [u8]) -> Result<T>
1851where
1852    T: Deserialize<'de>,
1853{
1854    spanned::set_marker(spanned::Marker::start());
1855    let res = T::deserialize(Deserializer::from_slice(v));
1856    spanned::reset_marker();
1857    res
1858}