1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
use std::fmt::{self, Display};
use std::slice;

use super::Chain;

/// Path to the error value in the input, like `dependencies.serde.typo1`.
///
/// Use `path.to_string()` to get a string representation of the path with
/// segments separated by periods, or use `path.iter()` to iterate over
/// individual segments of the path.
#[derive(Clone, Debug)]
pub struct Path {
    segments: Vec<Segment>,
}

/// Single segment of a path.
#[derive(Clone, Debug)]
pub enum Segment {
    Seq { index: usize },
    Map { key: String },
    Enum { variant: String },
    Unknown,
}

impl Path {
    /// Returns an iterator with element type [`&Segment`][Segment].
    pub fn iter(&self) -> Segments {
        Segments {
            iter: self.segments.iter(),
        }
    }
}

impl<'a> IntoIterator for &'a Path {
    type Item = &'a Segment;
    type IntoIter = Segments<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Iterator over segments of a path.
pub struct Segments<'a> {
    iter: slice::Iter<'a, Segment>,
}

impl<'a> Iterator for Segments<'a> {
    type Item = &'a Segment;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }
}

impl Display for Path {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        if self.segments.is_empty() {
            return formatter.write_str(".");
        }

        let mut separator = "";
        for segment in self {
            match segment {
                Segment::Seq { index } => {
                    write!(formatter, "[{}]", index)?;
                }
                Segment::Map { key } | Segment::Enum { variant: key } => {
                    write!(formatter, "{}{}", separator, key)?;
                }
                Segment::Unknown => {
                    write!(formatter, "{}?", separator)?;
                }
            }
            separator = ".";
        }

        Ok(())
    }
}

impl Path {
    pub(crate) fn empty() -> Self {
        Path {
            segments: Vec::new(),
        }
    }

    pub(crate) fn from_chain(mut chain: &Chain) -> Self {
        let mut segments = Vec::new();
        loop {
            match chain {
                Chain::Root => break,
                Chain::Seq { parent, index } => {
                    segments.push(Segment::Seq { index: *index });
                    chain = parent;
                }
                Chain::Map { parent, key } => {
                    segments.push(Segment::Map { key: key.clone() });
                    chain = parent;
                }
                Chain::Enum { parent, variant } => {
                    segments.push(Segment::Enum {
                        variant: variant.clone(),
                    });
                    chain = parent;
                }
                Chain::Some { parent }
                | Chain::NewtypeStruct { parent }
                | Chain::NewtypeVariant { parent } => {
                    chain = parent;
                }
                Chain::NonStringKey { parent } => {
                    segments.push(Segment::Unknown);
                    chain = parent;
                }
            }
        }
        segments.reverse();
        Path { segments }
    }
}