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
//! A spanned error is the error type returned by `Parser::parse*` functions.

use std::fmt::Display;

use annotate_snippets::*;
use itertools::Itertools;
use thiserror::Error;

use crate::lexer::Token;

#[derive(Error, Clone, Debug, Default, PartialEq)]
pub enum Error {
    #[default]
    #[error("syntax error")]
    SyntaxError,
    #[error("invalid diagnostic severity")]
    ParseDiagnosticSeverity,
}

type ParseError = lalrpop_util::ParseError<usize, Token, (usize, Error, usize)>;

#[derive(Clone, Debug, PartialEq)]
pub struct SpannedError<'s> {
    inner: ParseError,
    source: &'s str,
}

impl<'s> SpannedError<'s> {
    pub(crate) fn new(inner: ParseError, source: &'s str) -> Self {
        Self { inner, source }
    }
}

impl<'s> std::error::Error for SpannedError<'s> {}

impl<'s> Display for SpannedError<'s> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let err = &self.inner;
        let source = &self.source;
        let renderer = Renderer::styled();
        match err {
            ParseError::InvalidToken { location } => {
                let end = (*location + 1..)
                    .find(|e| source.is_char_boundary(*e))
                    .unwrap_or(*location);
                let message = Level::Error.title("invalid token").snippet(
                    Snippet::source(source).fold(true).annotation(
                        Level::Error
                            .span(*location..end)
                            .label("this token is unknown"),
                    ),
                );
                write!(f, "{}", renderer.render(message))
            }
            ParseError::UnrecognizedEof { location, expected } => {
                let annot = format!("expected {}", expected.iter().format(", "));
                let message = Level::Error.title("unexpected end of file").snippet(
                    Snippet::source(source)
                        .fold(true)
                        .annotation(Level::Error.span(*location..*location).label(&annot)),
                );
                let rendered = renderer.render(message);
                write!(f, "{}", rendered)
            }
            ParseError::UnrecognizedToken { token, expected } => {
                let title = format!("unexpected token `{}`", &source[token.0..token.2]);
                let annot = format!(
                    "expected {}, found {}",
                    expected.iter().format(", "),
                    token.1
                );
                let message = Level::Error.title(&title).snippet(
                    Snippet::source(source)
                        .fold(true)
                        .annotation(Level::Error.span(token.0..token.2).label(&annot)),
                );
                let rendered = renderer.render(message);
                write!(f, "{}", rendered)
            }
            ParseError::ExtraToken { token } => {
                let title = format!("extra token `{}`", &source[token.0..token.2]);
                let annot = format!("extra {} here", token.1);
                let message = Level::Error.title(&title).snippet(
                    Snippet::source(source)
                        .fold(true)
                        .annotation(Level::Error.span(token.0..token.2).label(&annot)),
                );
                let rendered = renderer.render(message);
                write!(f, "{}", rendered)
            }
            ParseError::User {
                error: (start, error, end),
            } => {
                let title = error.to_string();
                let message = Level::Error.title(&title).snippet(
                    Snippet::source(source).fold(true).annotation(
                        Level::Error
                            .span(*start..*end)
                            .label("while parsing this token"),
                    ),
                );
                let rendered = renderer.render(message);
                write!(f, "{}", rendered)
            }
        }
    }
}