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

/// The result type used by this crate.
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// The error type used by this crate.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// Represents a generic error message with optional location.
    Message {
        /// The error message.
        msg: String,
        /// An optional location context where the error happened in the input.
        location: Option<Location>,
    },

    /// Represents the error emitted when the `Deserializer` hits an unexpected end of input.
    Eof,

    /// Represents an error that resulted from invalid UTF8 input.
    Utf8(Utf8Error),

    /// Represents generic IO errors.
    Io(io::Error),
}

impl Error {
    pub(crate) fn new<T>(msg: T) -> Error
    where
        T: Display,
    {
        Error::Message {
            msg: msg.to_string(),
            location: None,
        }
    }

    /// Returns the `Location` in the input where the error happened, if available.
    pub fn location(&self) -> Option<&Location> {
        match self {
            Error::Message { location, .. } => location.as_ref(),
            _ => None,
        }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Eof => write!(f, "unexpected end of input"),
            Error::Io(err) => Display::fmt(err, f),
            Error::Utf8(err) => Display::fmt(err, f),
            Error::Message { msg, location } => match location {
                Some(loc) => {
                    write!(f, "{} in line {}, col {}", msg, loc.line, loc.col)
                }
                None => write!(f, "{}", msg),
            },
        }
    }
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Self {
        Error::Io(err)
    }
}

impl From<Utf8Error> for Error {
    fn from(err: Utf8Error) -> Self {
        Error::Utf8(err)
    }
}

impl From<pest::error::Error<Rule>> for Error {
    fn from(err: pest::error::Error<Rule>) -> Self {
        let (line, col) = match err.line_col {
            LineColLocation::Pos((l, c)) => (l, c),
            LineColLocation::Span((l, c), (_, _)) => (l, c),
        };

        Error::Message {
            msg: err.to_string(),
            location: Some(Location { line, col }),
        }
    }
}

impl std::error::Error for Error {}

impl ser::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
        Error::new(msg)
    }
}

impl de::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
        Error::new(msg)
    }
}

/// One-based line and column at which the error was detected.
#[derive(Clone, Debug, PartialEq)]
pub struct Location {
    /// The one-based line number of the error.
    pub line: usize,
    /// The one-based column number of the error.
    pub col: usize,
}

impl From<Span<'_>> for Location {
    fn from(span: Span<'_>) -> Self {
        let (line, col) = span.start_pos().line_col();
        Location { line, col }
    }
}