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
use core::fmt;

use ::rust_alloc::boxed::Box;

#[cfg(feature = "emit")]
use crate::ast::{Span, Spanned};
use crate::compile::{self, LinkerError};
use crate::SourceId;

/// Fatal diagnostic emitted during compilation. Fatal diagnostics indicates an
/// unrecoverable issue.
#[derive(Debug)]
pub struct FatalDiagnostic {
    /// The source id of the error.
    pub(crate) source_id: SourceId,
    /// The kind of the load error.
    pub(crate) kind: Box<FatalDiagnosticKind>,
}

impl FatalDiagnostic {
    /// The source id where the error originates from.
    pub fn source_id(&self) -> SourceId {
        self.source_id
    }

    /// The kind of the load error.
    pub fn kind(&self) -> &FatalDiagnosticKind {
        &self.kind
    }

    /// The kind of the load error.
    #[cfg(test)]
    pub(crate) fn into_kind(self) -> FatalDiagnosticKind {
        *self.kind
    }

    #[cfg(feature = "emit")]
    pub(crate) fn span(&self) -> Option<Span> {
        match &*self.kind {
            FatalDiagnosticKind::CompileError(error) => Some(error.span()),
            FatalDiagnosticKind::LinkError(..) => None,
            FatalDiagnosticKind::Internal(..) => None,
        }
    }
}

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

cfg_std! {
    impl std::error::Error for FatalDiagnostic {
        #[inline]
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            match &*self.kind {
                FatalDiagnosticKind::CompileError(error) => Some(error),
                FatalDiagnosticKind::LinkError(error) => Some(error),
                _ => None,
            }
        }
    }
}

/// The kind of a [FatalDiagnostic].
#[derive(Debug)]
#[allow(missing_docs)]
#[non_exhaustive]
pub enum FatalDiagnosticKind {
    CompileError(compile::Error),
    LinkError(LinkerError),
    /// An internal error.
    Internal(&'static str),
}

impl fmt::Display for FatalDiagnosticKind {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            FatalDiagnosticKind::CompileError(error) => error.fmt(f),
            FatalDiagnosticKind::LinkError(error) => error.fmt(f),
            FatalDiagnosticKind::Internal(message) => message.fmt(f),
        }
    }
}

impl From<compile::Error> for FatalDiagnosticKind {
    #[inline]
    fn from(error: compile::Error) -> Self {
        FatalDiagnosticKind::CompileError(error)
    }
}

impl From<LinkerError> for FatalDiagnosticKind {
    #[inline]
    fn from(error: LinkerError) -> Self {
        FatalDiagnosticKind::LinkError(error)
    }
}