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
use alloc::{borrow::Cow, boxed::Box, sync::Arc, vec::Vec};
use core::{fmt, ops::Range};

pub use miette::{
    self, Diagnostic, IntoDiagnostic, LabeledSpan, NamedSource, Report, Result, Severity,
    SourceCode, WrapErr,
};
pub use tracing;
pub use vm_core::debuginfo::*;

// LABEL
// ================================================================================================

/// Represents a diagnostic label.
///
/// A label is a source span and optional diagnostic text that should be laid out next to the
/// source snippet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Label {
    span: miette::SourceSpan,
    label: Option<Cow<'static, str>>,
}

impl Label {
    /// Construct a label for the given range of bytes, expressible as any type which can be
    /// converted to a [`Range<usize>`], e.g. [miette::SourceSpan].
    pub fn at<R>(range: R) -> Self
    where
        Range<usize>: From<R>,
    {
        let range = Range::<usize>::from(range);
        Self { span: range.into(), label: None }
    }

    /// Construct a label which points to a specific offset in the source file.
    pub fn point<L>(at: usize, label: L) -> Self
    where
        Cow<'static, str>: From<L>,
    {
        Self {
            span: miette::SourceSpan::from(at),
            label: Some(Cow::from(label)),
        }
    }

    /// Construct a label from the given source range and diagnostic text.
    pub fn new<R, L>(range: R, label: L) -> Self
    where
        Range<usize>: From<R>,
        Cow<'static, str>: From<L>,
    {
        let range = Range::<usize>::from(range);
        Self {
            span: range.into(),
            label: Some(Cow::from(label)),
        }
    }

    /// Returns the diagnostic text, the actual "label", for this label.
    pub fn label(&self) -> Option<&str> {
        self.label.as_deref()
    }
}

impl From<Label> for miette::SourceSpan {
    #[inline(always)]
    fn from(label: Label) -> Self {
        label.span
    }
}

impl From<Label> for LabeledSpan {
    #[inline]
    fn from(label: Label) -> LabeledSpan {
        if let Some(message) = label.label {
            LabeledSpan::at(label.span, message)
        } else {
            LabeledSpan::underline(label.span)
        }
    }
}

// RELATED LABEL
// ================================================================================================

/// This type is used to associate a more complex label or set of labels with some other error. In
/// particular, it is used to reference related bits of source code distinct from that of the
/// original error.
///
/// A related label can have a distinct severity, its own message, and its own sub-labels, and may
/// reference code in a completely different source file that the original error.
#[derive(Debug)]
pub struct RelatedLabel {
    /// The severity for this related label
    pub severity: Severity,
    /// The message for this label
    pub message: Cow<'static, str>,
    /// The sub-labels for this label
    pub labels: Vec<Label>,
    /// The source file to use when rendering source spans of this label as snippets.
    pub file: Option<Arc<SourceFile>>,
}

impl fmt::Display for RelatedLabel {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.message.as_ref())
    }
}

#[cfg(feature = "std")]
impl std::error::Error for RelatedLabel {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

#[cfg(not(feature = "std"))]
impl miette::StdError for RelatedLabel {
    fn source(&self) -> Option<&(dyn miette::StdError + 'static)> {
        None
    }
}

impl RelatedLabel {
    pub fn new<S>(severity: Severity, message: S) -> Self
    where
        Cow<'static, str>: From<S>,
    {
        Self {
            severity,
            message: Cow::from(message),
            labels: vec![],
            file: None,
        }
    }

    pub fn error<S>(message: S) -> Self
    where
        Cow<'static, str>: From<S>,
    {
        Self::new(Severity::Error, message)
    }

    #[allow(unused)]
    pub fn warning<S>(message: S) -> Self
    where
        Cow<'static, str>: From<S>,
    {
        Self::new(Severity::Warning, message)
    }

    #[allow(unused)]
    pub fn advice<S>(message: S) -> Self
    where
        Cow<'static, str>: From<S>,
    {
        Self::new(Severity::Advice, message)
    }

    pub fn with_source_file(mut self, file: Option<Arc<SourceFile>>) -> Self {
        self.file = file;
        self
    }

    pub fn with_labeled_span<S>(self, span: SourceSpan, message: S) -> Self
    where
        Cow<'static, str>: From<S>,
    {
        let range = span.into_range();
        self.with_label(Label::new((range.start as usize)..(range.end as usize), message))
    }

    pub fn with_label(mut self, label: Label) -> Self {
        self.labels.push(label);
        self
    }

    #[allow(unused)]
    pub fn with_labels<I>(mut self, labels: I) -> Self
    where
        I: IntoIterator<Item = Label>,
    {
        self.labels.extend(labels);
        self
    }
}

impl Diagnostic for RelatedLabel {
    fn code<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        None
    }
    fn severity(&self) -> Option<Severity> {
        Some(self.severity)
    }
    fn help<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        None
    }
    fn url<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        None
    }
    fn source_code(&self) -> Option<&dyn SourceCode> {
        self.file.as_ref().map(|f| f as &dyn SourceCode)
    }
    fn labels(&self) -> Option<Box<dyn Iterator<Item = LabeledSpan> + '_>> {
        if self.labels.is_empty() {
            None
        } else {
            Some(Box::new(self.labels.iter().cloned().map(|l| l.into())))
        }
    }
    fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn Diagnostic> + 'a>> {
        None
    }
    fn diagnostic_source(&self) -> Option<&dyn Diagnostic> {
        None
    }
}

// RELATED ERROR
// ================================================================================================

/// This type allows rolling up a diagnostic into a parent error
///
/// This is necessary as [Report] cannot be used as the source error when deriving [Diagnostic].
#[derive(Debug)]
pub struct RelatedError(Report);

impl RelatedError {
    pub fn into_report(self) -> Report {
        self.0
    }

    #[inline(always)]
    pub fn as_diagnostic(&self) -> &dyn Diagnostic {
        self.0.as_ref()
    }
}

impl Diagnostic for RelatedError {
    fn code<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        self.as_diagnostic().code()
    }
    fn severity(&self) -> Option<Severity> {
        self.as_diagnostic().severity()
    }
    fn help<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        self.as_diagnostic().help()
    }
    fn url<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        self.as_diagnostic().url()
    }
    fn source_code(&self) -> Option<&dyn SourceCode> {
        self.as_diagnostic().source_code()
    }
    fn labels(&self) -> Option<Box<dyn Iterator<Item = LabeledSpan> + '_>> {
        self.as_diagnostic().labels()
    }
    fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn Diagnostic> + 'a>> {
        self.as_diagnostic().related()
    }
    fn diagnostic_source(&self) -> Option<&dyn Diagnostic> {
        self.as_diagnostic().diagnostic_source()
    }
}

impl fmt::Display for RelatedError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for RelatedError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        AsRef::<dyn std::error::Error>::as_ref(&self.0).source()
    }
}

#[cfg(not(feature = "std"))]
impl miette::StdError for RelatedError {
    fn source(&self) -> Option<&(dyn miette::StdError + 'static)> {
        AsRef::<dyn miette::StdError>::as_ref(&self.0).source()
    }
}

impl From<Report> for RelatedError {
    fn from(report: Report) -> Self {
        Self(report)
    }
}

impl RelatedError {
    pub const fn new(report: Report) -> Self {
        Self(report)
    }

    pub fn wrap<E>(error: E) -> Self
    where
        E: Diagnostic + Send + Sync + 'static,
    {
        Self(Report::new_boxed(Box::new(error)))
    }
}

// REPORTING
// ================================================================================================

/// Rendering and error reporting implementation details.
pub mod reporting {
    use core::fmt;

    pub use miette::{
        set_hook, DebugReportHandler, JSONReportHandler, NarratableReportHandler, ReportHandler,
    };
    #[cfg(feature = "std")]
    pub use miette::{set_panic_hook, GraphicalReportHandler, GraphicalTheme};

    pub type ReportHandlerOpts = miette::MietteHandlerOpts;

    #[cfg(feature = "std")]
    pub type DefaultReportHandler = miette::GraphicalReportHandler;

    #[cfg(not(feature = "std"))]
    pub type DefaultReportHandler = miette::DebugReportHandler;

    /// A type that can be used to render a [super::Diagnostic] via [core::fmt::Display]
    pub struct PrintDiagnostic<D, R = DefaultReportHandler> {
        handler: R,
        diag: D,
    }

    impl<D: AsRef<dyn super::Diagnostic>> PrintDiagnostic<D> {
        pub fn new(diag: D) -> Self {
            Self { handler: Default::default(), diag }
        }
        #[cfg(feature = "std")]
        pub fn new_without_color(diag: D) -> Self {
            Self {
                handler: DefaultReportHandler::new_themed(GraphicalTheme::none()),
                diag,
            }
        }
        #[cfg(not(feature = "std"))]
        pub fn new_without_color(diag: D) -> Self {
            Self::new(diag)
        }
    }

    impl<D: AsRef<dyn super::Diagnostic>> PrintDiagnostic<D, NarratableReportHandler> {
        pub fn narrated(diag: D) -> Self {
            Self {
                handler: NarratableReportHandler::default(),
                diag,
            }
        }
    }

    impl<D: AsRef<dyn super::Diagnostic>> PrintDiagnostic<D, JSONReportHandler> {
        pub fn json(diag: D) -> Self {
            Self { handler: JSONReportHandler, diag }
        }
    }

    impl<D: AsRef<dyn super::Diagnostic>> fmt::Display for PrintDiagnostic<D> {
        fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
            self.handler.render_report(f, self.diag.as_ref())
        }
    }

    impl<D: AsRef<dyn super::Diagnostic>> fmt::Display for PrintDiagnostic<D, NarratableReportHandler> {
        fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
            self.handler.render_report(f, self.diag.as_ref())
        }
    }

    impl<D: AsRef<dyn super::Diagnostic>> fmt::Display for PrintDiagnostic<D, JSONReportHandler> {
        fn fmt(&self, f: &mut fmt::Formatter) -> core::fmt::Result {
            self.handler.render_report(f, self.diag.as_ref())
        }
    }
}