rune/diagnostics/
fatal.rs

1use core::fmt;
2
3use ::rust_alloc::boxed::Box;
4
5#[cfg(feature = "emit")]
6use crate::ast::{Span, Spanned};
7use crate::compile::{self, LinkerError};
8use crate::SourceId;
9
10/// Fatal diagnostic emitted during compilation. Fatal diagnostics indicates an
11/// unrecoverable issue.
12#[derive(Debug)]
13pub struct FatalDiagnostic {
14    /// The source id of the error.
15    pub(crate) source_id: SourceId,
16    /// The kind of the load error.
17    pub(crate) kind: Box<FatalDiagnosticKind>,
18}
19
20impl FatalDiagnostic {
21    /// The source id where the error originates from.
22    pub fn source_id(&self) -> SourceId {
23        self.source_id
24    }
25
26    /// The kind of the load error.
27    pub fn kind(&self) -> &FatalDiagnosticKind {
28        &self.kind
29    }
30
31    /// The kind of the load error.
32    #[cfg(test)]
33    pub(crate) fn into_kind(self) -> FatalDiagnosticKind {
34        *self.kind
35    }
36
37    #[cfg(feature = "emit")]
38    pub(crate) fn span(&self) -> Option<Span> {
39        match &*self.kind {
40            FatalDiagnosticKind::CompileError(error) => Some(error.span()),
41            FatalDiagnosticKind::LinkError(..) => None,
42            FatalDiagnosticKind::Internal(..) => None,
43        }
44    }
45}
46
47impl fmt::Display for FatalDiagnostic {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        self.kind.fmt(f)
50    }
51}
52
53impl core::error::Error for FatalDiagnostic {
54    #[inline]
55    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
56        match &*self.kind {
57            FatalDiagnosticKind::CompileError(error) => Some(error),
58            FatalDiagnosticKind::LinkError(error) => Some(error),
59            _ => None,
60        }
61    }
62}
63
64/// The kind of a [FatalDiagnostic].
65#[derive(Debug)]
66#[allow(missing_docs)]
67#[non_exhaustive]
68pub enum FatalDiagnosticKind {
69    CompileError(compile::Error),
70    LinkError(LinkerError),
71    /// An internal error.
72    Internal(&'static str),
73}
74
75impl fmt::Display for FatalDiagnosticKind {
76    #[inline]
77    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78        match self {
79            FatalDiagnosticKind::CompileError(error) => error.fmt(f),
80            FatalDiagnosticKind::LinkError(error) => error.fmt(f),
81            FatalDiagnosticKind::Internal(message) => message.fmt(f),
82        }
83    }
84}
85
86impl From<compile::Error> for FatalDiagnosticKind {
87    #[inline]
88    fn from(error: compile::Error) -> Self {
89        FatalDiagnosticKind::CompileError(error)
90    }
91}
92
93impl From<LinkerError> for FatalDiagnosticKind {
94    #[inline]
95    fn from(error: LinkerError) -> Self {
96        FatalDiagnosticKind::LinkError(error)
97    }
98}