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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
pub use anyhow::Result;

use ariadne::{Config, Label, Report, ReportKind, Source};
use serde::{Deserialize, Serialize};
use std::error::Error as StdError;
use std::fmt::{self, Debug, Display, Formatter, Write};
use std::ops::{Add, Range};

use crate::parser::PestError;
#[derive(Clone, PartialEq, Eq, Copy, Serialize, Deserialize)]
pub struct Span {
    pub start: usize,
    pub end: usize,
}

#[derive(Debug, Clone)]
pub struct Error {
    pub span: Option<Span>,
    pub reason: Reason,
    pub help: Option<String>,
}

#[derive(Debug)]
pub struct SourceLocation {
    /// Line and column
    pub start: (usize, usize),

    /// Line and column
    pub end: (usize, usize),
}

#[derive(Debug, Clone)]
pub enum Reason {
    Simple(String),
    Expected {
        who: Option<String>,
        expected: String,
        found: String,
    },
    Unexpected {
        found: String,
    },
    NotFound {
        name: String,
        namespace: String,
    },
}

impl Error {
    pub fn new(reason: Reason) -> Self {
        Error {
            span: None,
            reason,
            help: None,
        }
    }

    pub fn with_help<S: Into<String>>(mut self, help: S) -> Self {
        self.help = Some(help.into());
        self
    }

    pub fn with_span(mut self, span: Option<Span>) -> Self {
        self.span = span;
        self
    }
}

pub struct FormattedError {
    pub message: String,
    pub line: String,
    pub location: Option<SourceLocation>,
}

// Needed for anyhow
impl StdError for Error {}

// Needed for StdError
impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Debug::fmt(&self, f)
    }
}

/// Convert error into human-readable message and error location.
pub fn format_error(
    error: anyhow::Error,
    source_id: &str,
    source: &str,
    color: bool,
) -> FormattedError {
    let source = Source::from(source);
    let location = location(&error, &source);

    let (line, output) = error_message_and_output(error, source_id, source, color);

    FormattedError {
        message: output,
        line,
        location,
    }
}

fn location(error: &anyhow::Error, source: &Source) -> Option<SourceLocation> {
    let span = if let Some(error) = error.downcast_ref::<Error>() {
        if let Some(span) = error.span {
            Range::from(span)
        } else {
            return None;
        }
    } else if let Some(error) = error.downcast_ref::<PestError>() {
        pest::as_range(error)
    } else {
        return None;
    };

    let start = source.get_offset_line(span.start)?;
    let end = source.get_offset_line(span.end)?;

    Some(SourceLocation {
        start: (start.1, start.2),
        end: (end.1, end.2),
    })
}

fn error_message_and_output(
    error: anyhow::Error,
    source_id: &str,
    source: Source,
    color: bool,
) -> (String, String) {
    let config = Config::default().with_color(color);

    if let Some(error) = error.downcast_ref::<Error>() {
        let message = error.reason.message();

        if let Some(span) = error.span {
            let span = Range::from(span);

            let mut report = Report::build(ReportKind::Error, source_id, span.start)
                .with_config(config)
                .with_message("")
                .with_label(Label::new((source_id, span)).with_message(&message));

            if let Some(help) = &error.help {
                report.set_help(help);
            }

            let mut out = Vec::new();
            report
                .finish()
                .write((source_id, source), &mut out)
                .unwrap();

            let output = String::from_utf8(out).unwrap();
            return (message, output);
        } else {
            let mut out = format!("Error: {message}");

            if let Some(help) = &error.help {
                out = format!("{out}\n  help: {help}");
            }

            return (message, out);
        }
    }

    if let Some(error) = error.downcast_ref::<PestError>() {
        let span = pest::as_range(error);
        let mut out = Vec::new();

        let message = pest::as_message(error);
        Report::build(ReportKind::Error, source_id, span.start)
            .with_config(config)
            .with_message("during parsing")
            .with_label(Label::new((source_id, span)).with_message(&message))
            .finish()
            .write((source_id, source), &mut out)
            .unwrap();

        return (message, String::from_utf8(out).unwrap());
    }

    // default to basic Display
    let mut message = String::new();
    write!(&mut message, "{:#?}", error).unwrap();
    (message.clone(), message)
}

impl Reason {
    fn message(&self) -> String {
        match self {
            Reason::Simple(text) => text.clone(),
            Reason::Expected {
                who,
                expected,
                found,
            } => {
                let who = who.clone().map(|x| format!("{x} ")).unwrap_or_default();
                format!("{who}expected {expected}, but found {found}")
            }
            Reason::Unexpected { found } => format!("unexpected {found}"),
            Reason::NotFound { name, namespace } => format!("{namespace} `{name}` not found"),
        }
    }
}

mod pest {
    use pest::error::{ErrorVariant, InputLocation};
    use std::ops::Range;

    use crate::parser::{PestError, PestRule};

    pub fn as_range(error: &PestError) -> Range<usize> {
        match error.location {
            InputLocation::Pos(r) => r..r + 1,
            InputLocation::Span(r) => r.0..r.1,
        }
    }

    pub fn as_message(error: &PestError) -> String {
        match error.variant {
            ErrorVariant::ParsingError {
                ref positives,
                ref negatives,
            } => parsing_error_message(positives, negatives),
            ErrorVariant::CustomError { ref message } => message.clone(),
        }
    }

    fn parsing_error_message(positives: &[PestRule], negatives: &[PestRule]) -> String {
        match (negatives.is_empty(), positives.is_empty()) {
            (false, false) => format!(
                "unexpected {}; expected {}",
                enumerate(negatives),
                enumerate(positives)
            ),
            (false, true) => format!("unexpected {}", enumerate(negatives)),
            (true, false) => format!("expected {}", enumerate(positives)),
            (true, true) => "unknown parsing error".to_owned(),
        }
    }

    fn enumerate(rules: &[PestRule]) -> String {
        match rules.len() {
            1 => format!("{:?}", rules[0]),
            2 => format!("{:?} or {:?}", rules[0], rules[1]),
            l => {
                let separated = rules
                    .iter()
                    .take(l - 1)
                    .map(|x| format!("{:?}", x))
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("{}, or {:?}", separated, rules[l - 1])
            }
        }
    }
}

impl From<Span> for Range<usize> {
    fn from(a: Span) -> Self {
        a.start..a.end
    }
}

impl Add<Span> for Span {
    type Output = Span;

    fn add(self, rhs: Span) -> Span {
        Span {
            start: self.start.min(rhs.start),
            end: self.end.max(rhs.end),
        }
    }
}

pub trait WithErrorInfo {
    fn with_help<S: Into<String>>(self, help: S) -> Self;

    fn with_span(self, span: Option<Span>) -> Self;
}

impl<T> WithErrorInfo for Result<T, Error> {
    fn with_help<S: Into<String>>(self, help: S) -> Self {
        self.map_err(|e| e.with_help(help))
    }

    fn with_span(self, span: Option<Span>) -> Self {
        self.map_err(|e| e.with_span(span))
    }
}

impl Debug for Span {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "span-chars-{}-{}", self.start, self.end)
    }
}