1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
use crate::lexer::{SpannedToken, Token};
use crate::num::ParseIntError;
use crate::string::UnescapeError;
use logos::Span;
use source_span::{
    fmt::{Color, Formatter, Style},
    DefaultMetrics, Position, SourceBuffer, Span as SourceSpan,
};
use std::error::Error;
use std::fmt::{self, Debug, Display};
use std::num::ParseFloatError;
use std::str::ParseBoolError;
use thiserror::Error;

/// An error and related source span
///
/// You can pretty-print the error with the offending source by using `with_source`
///
/// ## Example
///
/// ```text
/// . |
/// 2 |     [
/// 3 |         "broken"
/// 4 |         "array"                                                                                         
///   |         ^^^^^^^^ Unexpected token, found LiteralString expected one of [SquareClose, Comma, Arrow]
/// 5 |     ]
/// 6 |
/// ```
///
#[derive(Debug)]
pub struct ParseError {
    span: Option<Span>,
    error: RawParseError,
}

impl serde::de::Error for ParseError {
    fn custom<T>(msg: T) -> Self
    where
        T: Display,
    {
        ParseError {
            span: None,
            error: RawParseError::custom(msg),
        }
    }
}

impl ParseError {
    pub fn new(error: RawParseError, span: Span) -> Self {
        ParseError {
            span: Some(span),
            error,
        }
    }

    pub fn error(&self) -> &RawParseError {
        &self.error
    }

    pub fn with_source(self, source: &str) -> SourceSpannedError {
        SourceSpannedError {
            span: self.span,
            error: self.error,
            source,
        }
    }
}

impl Error for ParseError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.error)
    }
}

impl Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        <RawParseError as Display>::fmt(&self.error, f)
    }
}

impl From<RawParseError> for ParseError {
    fn from(err: RawParseError) -> Self {
        ParseError {
            span: None,
            error: err,
        }
    }
}

pub struct SourceSpannedError<'source> {
    span: Option<Span>,
    error: RawParseError,
    source: &'source str,
}

impl<'source> SourceSpannedError<'source> {
    pub fn into_inner(self) -> ParseError {
        ParseError {
            span: self.span,
            error: self.error,
        }
    }
}

const METRICS: DefaultMetrics = DefaultMetrics::with_tab_stop(4);

impl<'source> Display for SourceSpannedError<'source> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.span.as_ref() {
            Some(span) => {
                let start = get_position(self.source, span.start);
                let end = get_position(self.source, span.end);
                let span = SourceSpan::new(start, end, end.next_line());

                let mut fmt = Formatter::with_margin_color(Color::Blue);
                let buffer = SourceBuffer::new(
                    self.source.chars().map(|char| Result::<char, ()>::Ok(char)),
                    Position::default(),
                    METRICS,
                );
                fmt.add(span, Some(format!("{}", self.error)), Style::Error);
                let formatted = fmt
                    .render(
                        buffer.iter(),
                        SourceSpan::new(
                            Position::default(),
                            Position::new(usize::max_value() - 1, usize::max_value()),
                            Position::end(),
                        ),
                        &METRICS,
                    )
                    .unwrap();
                write!(f, "{}", formatted)?;
            }
            None => write!(f, "{}", self.error)?,
        }
        Ok(())
    }
}

fn get_position(text: &str, index: usize) -> Position {
    let mut pos = Position::default();
    for char in text.chars().take(index) {
        pos = pos.next(char, &METRICS);
    }

    pos
}

#[derive(Error, Debug)]
pub enum RawParseError {
    #[error("{0}")]
    UnexpectedToken(#[from] UnexpectedTokenError),
    #[error("Invalid boolean literal: {0}")]
    InvalidBoolLiteral(#[from] ParseBoolError),
    #[error("Invalid integer literal: {0}")]
    InvalidIntLiteral(#[from] ParseIntError),
    #[error("Invalid float literal: {0}")]
    InvalidFloatLiteral(#[from] ParseFloatError),
    #[error("Invalid string literal")]
    InvalidStringLiteral,
    #[error("Array key not valid for this position")]
    UnexpectedArrayKey,
    #[error("Trailing characters after parsing")]
    TrailingCharacters,
    #[error("{0}")]
    Custom(String),
}

impl serde::de::Error for RawParseError {
    fn custom<T>(msg: T) -> Self
    where
        T: Display,
    {
        RawParseError::Custom(msg.to_string())
    }
}

impl From<UnescapeError> for RawParseError {
    fn from(_: UnescapeError) -> Self {
        RawParseError::InvalidStringLiteral
    }
}

#[derive(Debug)]
pub struct UnexpectedTokenError {
    pub expected: Vec<Token>,
    pub found: Option<Token>,
}

impl UnexpectedTokenError {
    pub fn new(expected: &[Token], found: Option<Token>) -> Self {
        UnexpectedTokenError {
            expected: expected.to_vec(),
            found,
        }
    }
}

impl Display for UnexpectedTokenError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.found {
            Some(Token::Error) => write!(
                f,
                "No valid token found, expected one of {:?}",
                self.expected
            ),
            Some(token) => write!(
                f,
                "Unexpected token, found {:?} expected one of {:?}",
                token, self.expected
            ),
            None => write!(
                f,
                "Unexpected token, found None expected one of {:?}",
                self.expected
            ),
        }
    }
}

impl Error for UnexpectedTokenError {}

pub trait ExpectToken<'source> {
    fn expect_token(self, expected: &[Token]) -> Result<SpannedToken<'source>, ParseError>;
}

impl<'source> ExpectToken<'source> for Option<SpannedToken<'source>> {
    fn expect_token(self, expected: &[Token]) -> Result<SpannedToken<'source>, ParseError> {
        self.ok_or_else(|| UnexpectedTokenError {
            expected: expected.to_vec(),
            found: None,
        })
        .with_span(usize::max_value()..usize::max_value())
        .and_then(|token| token.expect_token(expected))
    }
}

impl<'a, 'source> ExpectToken<'source> for Option<&'a SpannedToken<'source>> {
    fn expect_token(self, expected: &[Token]) -> Result<SpannedToken<'source>, ParseError> {
        self.ok_or_else(|| UnexpectedTokenError {
            expected: expected.to_vec(),
            found: None,
        })
        .with_span(usize::max_value()..usize::max_value())
        .and_then(|token| token.clone().expect_token(expected))
    }
}

impl<'source> ExpectToken<'source> for SpannedToken<'source> {
    fn expect_token(self, expected: &[Token]) -> Result<SpannedToken<'source>, ParseError> {
        if expected.iter().any(|expect| self.token.eq(expect)) {
            Ok(self)
        } else {
            Err(UnexpectedTokenError {
                expected: expected.to_vec(),
                found: Some(self.token),
            })
            .with_span(self.span)
        }
    }
}

pub trait ResultExt<T> {
    fn with_span(self, span: Span) -> Result<T, ParseError>;
}

impl<T, E: Into<RawParseError>> ResultExt<T> for Result<T, E> {
    fn with_span(self, span: Span) -> Result<T, ParseError> {
        self.map_err(|error| ParseError {
            span: Some(span),
            error: error.into(),
        })
    }
}