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
use crate::error::unexpected_token_message;
use crate::error::Error;
use crate::error::ErrorKind;
use crate::error::SingleError;
use crate::SourceFile;
use crate::Span;

use std::io;
use std::io::Write;
use std::sync::Arc;

use ariadne::Color;
use ariadne::Label;
use ariadne::ReportKind;
use ariadne::Source;

impl ariadne::Span for Span {
    type SourceId = String;

    fn source(&self) -> &Self::SourceId {
        self.source.id()
    }

    fn start(&self) -> usize {
        self.start
    }

    fn end(&self) -> usize {
        self.end
    }
}

impl From<&ErrorKind> for ReportKind<'static> {
    fn from(value: &ErrorKind) -> Self {
        match value {
            ErrorKind::Silent
            | ErrorKind::Custom { .. }
            | ErrorKind::UnknownCharacter(_)
            | ErrorKind::UnterminatedGroup { .. }
            | ErrorKind::UnterminatedChar(_)
            | ErrorKind::LongChar(_)
            | ErrorKind::UnterminatedString(_)
            | ErrorKind::UnexpectedToken { .. }
            | ErrorKind::EndOfFile(_) => ReportKind::Error,
        }
    }
}

/// A reported error, ready to be written to stderr.
///
/// This type exposes a very similar API to [`ariadne::Report`].
///
/// A `Vec<Report>` can be created from an [`Error`], but in most cases, the
/// [`Error::eprint`] method will suffice.
pub struct Report {
    report: ariadne::Report<'static, Span>,
    source: Arc<SourceFile>,
}

impl Report {
    /// Writes this diagnostic to an implementor of [`Write`].
    ///
    /// For more details, see [`ariadne::Report::write`].
    ///
    /// ## Errors
    /// Forwards any errors from `W::write`.
    pub fn write<W: Write>(&self, w: W) -> io::Result<()> {
        self.report.write(
            (
                self.source.id().to_owned(),
                Source::from(&self.source.contents),
            ),
            w,
        )
    }

    /// Writes this diagnostic to an implementor of [`Write`].
    ///
    /// For more details, see [`ariadne::Report::write_for_stdout`].
    ///
    /// ## Errors
    /// Forwards any errors from `W::write`.
    pub fn write_for_stdout<W: Write>(&self, w: W) -> io::Result<()> {
        self.report.write_for_stdout(
            (
                self.source.id().to_owned(),
                Source::from(&self.source.contents),
            ),
            w,
        )
    }

    /// Prints this diagnostic to stderr.
    ///
    /// For more details, see [`ariadne::Report::eprint`].
    ///
    /// ## Errors
    /// Returns an error if writing to stderr fails.
    pub fn eprint(&self) -> io::Result<()> {
        self.report.eprint((
            self.source.id().to_owned(),
            Source::from(&self.source.contents),
        ))
    }

    /// Prints this diagnostic to stdout. In most cases, [`Report::eprint`] is
    /// preferable to this.
    ///
    /// For more details, see [`ariadne::Report::print`].
    ///
    /// ## Errors
    /// Returns an error if writing to stdout fails.
    pub fn print(&self) -> io::Result<()> {
        self.report.print((
            self.source.id().to_owned(),
            Source::from(&self.source.contents),
        ))
    }
}

impl From<&SingleError> for Report {
    fn from(value: &SingleError) -> Self {
        let mut builder =
            ariadne::Report::build((&value.kind).into(), value.source.id(), value.kind.start())
                .with_code(value.kind.code());
        match &value.kind {
            ErrorKind::Silent => unreachable!(),
            ErrorKind::Custom { message, span, .. } => {
                builder.set_message(message);
                builder.add_label(Label::new(span.clone()).with_color(Color::Red));
            }
            ErrorKind::UnknownCharacter(span) => {
                builder.set_message("Unrecognised character");
                builder.add_label(Label::new(span.clone()).with_color(Color::Red));
            }
            ErrorKind::UnterminatedGroup { start, span } => {
                builder.set_message(format!("Unmatched '{start}'"));
                builder.add_label(Label::new(span.clone()).with_color(Color::Red));
            }
            ErrorKind::UnterminatedChar(span) => {
                builder.set_message("Expect \"'\" after character literal");
                builder.add_label(Label::new(span.clone()).with_color(Color::Red));
            }
            ErrorKind::LongChar(span) => {
                builder.set_message("Character literals must be exactly one character long");
                builder.add_label(Label::new(span.clone()).with_color(Color::Red));
            }
            ErrorKind::UnterminatedString(span) => {
                builder.set_message("Expect '\"' at end of string literal");
                builder.add_label(Label::new(span.clone()).with_color(Color::Red));
            }
            ErrorKind::UnexpectedToken { expected, span } => {
                builder.set_message("Unexpected token");
                builder.add_label(
                    Label::new(span.clone())
                        .with_color(Color::Red)
                        .with_message(unexpected_token_message(expected)),
                );
            }
            ErrorKind::EndOfFile(_) => builder.set_message("Unexpected end of file while parsing"),
        }
        Report {
            report: builder.finish(),
            source: Arc::clone(&value.source),
        }
    }
}

impl From<&Error> for Vec<Report> {
    fn from(value: &Error) -> Self {
        let mut reports = Vec::with_capacity(value.errors.len());
        for error in &value.errors {
            if !matches!(&error.kind, ErrorKind::Silent) {
                reports.push(Report::from(error));
            }
        }
        reports
    }
}

impl Error {
    /// Prints this error to stderr.
    ///
    /// ## Errors
    /// Returns an error if writing to stderr fails.
    pub fn eprint(&self) -> io::Result<()> {
        let reports: Vec<Report> = self.into();
        for report in reports {
            report.eprint()?;
        }
        Ok(())
    }

    /// Generates a series of reports from `self`.
    pub fn to_reports(&self) -> Vec<Report> {
        self.into()
    }
}