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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use anstream::adapter::strip_str;
pub use anyhow::Result;

use ariadne::{Cache, Config, Label, Report, ReportKind, Source};
use serde::Serialize;

use std::error::Error as StdError;
use std::fmt::{self, Debug, Display, Formatter};
use std::ops::Range;
use std::path::PathBuf;
use std::{collections::HashMap, io::stderr};

use crate::SourceTree;

pub use crate::ir::Span;

#[derive(Debug, Clone)]
pub struct Error {
    /// Message kind. Currently only Error is implemented.
    pub kind: MessageKind,
    pub span: Option<Span>,
    pub reason: Reason,
    pub hints: Vec<String>,
    pub code: Option<&'static str>,
}

#[derive(Debug, Clone)]
pub struct Errors(pub Vec<Error>);

/// Location within the source file.
/// Tuples contain:
/// - line number (0-based),
/// - column number within that line (0-based),
#[derive(Debug, Clone, Serialize)]
pub struct SourceLocation {
    pub start: (usize, usize),

    pub end: (usize, usize),
}

/// Compile message kind. Currently only Error is implemented.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub enum MessageKind {
    Error,
    Warning,
    Lint,
}

#[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 {
            kind: MessageKind::Error,
            span: None,
            reason,
            hints: Vec::new(),
            code: None,
        }
    }

    pub fn new_simple<S: ToString>(reason: S) -> Self {
        Error::new(Reason::Simple(reason.to_string()))
    }

    pub fn with_code(mut self, code: &'static str) -> Self {
        self.code = Some(code);
        self
    }
}

impl WithErrorInfo for crate::Error {
    fn with_hints<S: Into<String>, I: IntoIterator<Item = S>>(mut self, hints: I) -> Self {
        self.hints = hints.into_iter().map(|x| x.into()).collect();
        self
    }

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

    fn push_hint<S: Into<String>>(mut self, hint: S) -> Self {
        self.hints.push(hint.into());
        self
    }
}

#[derive(Clone, Serialize)]
pub struct ErrorMessage {
    /// Message kind. Currently only Error is implemented.
    pub kind: MessageKind,
    /// Machine-readable identifier of the error
    pub code: Option<String>,
    /// Plain text of the error
    pub reason: String,
    /// A list of suggestions of how to fix the error
    pub hints: Vec<String>,
    /// Character offset of error origin within a source file
    pub span: Option<Span>,
    /// Annotated code, containing cause and hints.
    pub display: Option<String>,
    /// Line and column number of error origin within a source file
    pub location: Option<SourceLocation>,
}

impl Display for ErrorMessage {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        // https://github.com/zesterer/ariadne/issues/52
        if let Some(display) = &self.display {
            let message_without_trailing_spaces = display
                .split('\n')
                .map(str::trim_end)
                .collect::<Vec<_>>()
                .join("\n");
            f.write_str(&message_without_trailing_spaces)?;
        } else {
            let code = (self.code.as_ref())
                .map(|c| format!("[{c}] "))
                .unwrap_or_default();

            writeln!(f, "{}Error: {}", code, &self.reason)?;
            for hint in &self.hints {
                // TODO: consider alternative formatting for hints.
                writeln!(f, "↳ Hint: {}", hint)?;
            }
        }
        Ok(())
    }
}

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

// Needed for anyhow
impl StdError for Error {}

// Needed for anyhow
impl StdError for Errors {}

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

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

#[derive(Debug, Clone, Serialize)]
pub struct ErrorMessages {
    pub inner: Vec<ErrorMessage>,
}
impl StdError for ErrorMessages {}

impl From<ErrorMessage> for ErrorMessages {
    fn from(e: ErrorMessage) -> Self {
        ErrorMessages { inner: vec![e] }
    }
}

impl Display for ErrorMessages {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        for e in &self.inner {
            Display::fmt(&e, f)?;
        }
        Ok(())
    }
}

pub fn downcast(error: anyhow::Error) -> ErrorMessages {
    let mut code = None;
    let mut span = None;
    let mut hints = Vec::new();

    let error = match error.downcast::<ErrorMessages>() {
        Ok(messages) => return messages,
        Err(error) => error,
    };

    let error = match error.downcast::<Errors>() {
        Ok(messages) => {
            return ErrorMessages {
                inner: messages
                    .0
                    .into_iter()
                    .flat_map(|e| downcast(e.into()).inner)
                    .collect(),
            }
        }
        Err(error) => error,
    };

    let reason = match error.downcast::<Error>() {
        Ok(error) => {
            code = error.code.map(|x| x.to_string());
            span = error.span;
            hints.extend(error.hints);

            error.reason.to_string()
        }
        Err(error) => {
            // default to basic Display
            format!("{:#?}", error)
        }
    };

    ErrorMessage {
        code,
        kind: MessageKind::Error,
        reason,
        hints,
        span,
        display: None,
        location: None,
    }
    .into()
}

impl From<anyhow::Error> for ErrorMessages {
    fn from(e: anyhow::Error) -> Self {
        downcast(e)
    }
}

impl ErrorMessages {
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).unwrap()
    }

    /// Computes message location and builds the pretty display.
    pub fn composed(mut self, sources: &SourceTree) -> Self {
        let mut cache = FileTreeCache::new(sources);

        for e in &mut self.inner {
            let Some(span) = e.span else {
                continue;
            };
            let Some(source_path) = sources.source_ids.get(&span.source_id) else {
                continue;
            };

            let Ok(source) = cache.fetch(source_path) else {
                continue
            };
            e.location = e.compose_location(source);

            e.display = e.compose_display(source_path.clone(), &mut cache);
        }
        self
    }
}

impl ErrorMessage {
    fn compose_display(&self, source_path: PathBuf, cache: &mut FileTreeCache) -> Option<String> {
        // We always pass color to ariadne as true, and then (currently) strip later.
        let config = Config::default().with_color(true);

        let span = Range::from(self.span?);

        let mut report = Report::build(ReportKind::Error, source_path.clone(), span.start)
            .with_config(config)
            .with_label(Label::new((source_path, span)).with_message(&self.reason));

        if let Some(code) = &self.code {
            report = report.with_code(code);
        }

        // I don't know how to set multiple hints...
        if !self.hints.is_empty() {
            report.set_help(&self.hints[0]);
        }
        if self.hints.len() > 1 {
            report.set_note(&self.hints[1]);
        }
        if self.hints.len() > 2 {
            report.set_message(&self.hints[2]);
        }

        let mut out = Vec::new();
        report.finish().write(cache, &mut out).ok()?;

        // Strip colors, for external libraries which don't yet strip
        // themselves, and for insta snapshot tests. This will respond to
        // environment variables such as `CLI_COLOR`. Eventually we can remove
        // this, always pass colors back, and the consuming library can strip
        // (including insta https://github.com/mitsuhiko/insta/issues/378).
        String::from_utf8(out).ok().map(|x| {
            if !should_use_color() {
                strip_str(&x).to_string()
            } else {
                x
            }
        })
    }

    fn compose_location(&self, source: &Source) -> Option<SourceLocation> {
        let span = self.span?;

        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 should_use_color() -> bool {
    match anstream::AutoStream::choice(&stderr()) {
        anstream::ColorChoice::Auto => true,
        anstream::ColorChoice::Always => true,
        anstream::ColorChoice::AlwaysAnsi => true,
        anstream::ColorChoice::Never => false,
    }
}

struct FileTreeCache<'a> {
    file_tree: &'a SourceTree,
    cache: HashMap<PathBuf, Source>,
}
impl<'a> FileTreeCache<'a> {
    fn new(file_tree: &'a SourceTree) -> Self {
        FileTreeCache {
            file_tree,
            cache: HashMap::new(),
        }
    }
}

impl<'a> Cache<PathBuf> for FileTreeCache<'a> {
    fn fetch(&mut self, id: &PathBuf) -> Result<&Source, Box<dyn fmt::Debug + '_>> {
        let file_contents = match self.file_tree.sources.get(id) {
            Some(v) => v,
            None => return Err(Box::new(format!("Unknown file `{id:?}`"))),
        };

        Ok(self
            .cache
            .entry(id.clone())
            .or_insert_with(|| Source::from(file_contents)))
    }

    fn display<'b>(&self, id: &'b PathBuf) -> Option<Box<dyn fmt::Display + 'b>> {
        match id.as_os_str().to_str() {
            Some(s) => Some(Box::new(s)),
            None => None,
        }
    }
}

impl Display for Reason {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Reason::Simple(text) => f.write_str(text),
            Reason::Expected {
                who,
                expected,
                found,
            } => {
                if let Some(who) = who {
                    write!(f, "{who} ")?;
                }
                write!(f, "expected {expected}, but found {found}")
            }
            Reason::Unexpected { found } => write!(f, "unexpected {found}"),
            Reason::NotFound { name, namespace } => write!(f, "{namespace} `{name}` not found"),
        }
    }
}

pub trait WithErrorInfo: Sized {
    fn push_hint<S: Into<String>>(self, hint: S) -> Self;

    fn with_hints<S: Into<String>, I: IntoIterator<Item = S>>(self, hints: I) -> Self;

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

impl WithErrorInfo for anyhow::Error {
    fn push_hint<S: Into<String>>(self, hint: S) -> Self {
        self.downcast_ref::<crate::Error>()
            .map(|e| e.clone().push_hint(hint).into())
            .unwrap_or(self)
    }

    fn with_hints<S: Into<String>, I: IntoIterator<Item = S>>(self, hints: I) -> Self {
        self.downcast_ref::<crate::Error>()
            .map(|e| e.clone().with_hints(hints).into())
            .unwrap_or(self)
    }

    // Add a span of an expression onto the error. We need this implementation
    // because we often pass `anyhow::Error`, and still want to try adding a
    // span. So we need to try downcasting it to our error type first, and that
    // fails, we return the original error.
    fn with_span(self, span: Option<Span>) -> Self {
        self.downcast_ref::<crate::Error>()
            .map(|e| e.clone().with_span(span).into())
            .unwrap_or(self)
    }
}

impl<T, E: WithErrorInfo> WithErrorInfo for Result<T, E> {
    fn with_hints<S: Into<String>, I: IntoIterator<Item = S>>(self, hints: I) -> Self {
        self.map_err(|e| e.with_hints(hints))
    }

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

    fn push_hint<S: Into<String>>(self, hint: S) -> Self {
        self.map_err(|e| e.push_hint(hint))
    }
}