stable_mir/
error.rs

1//! When things go wrong, we need some error handling.
2//! There are a few different types of errors in StableMIR:
3//!
4//! - [CompilerError]: This represents errors that can be raised when invoking the compiler.
5//! - [Error]: Generic error that represents the reason why a request that could not be fulfilled.
6
7use std::fmt::{Debug, Display, Formatter};
8use std::{fmt, io};
9
10macro_rules! error {
11     ($fmt: literal $(,)?) => { Error(format!($fmt)) };
12     ($fmt: literal, $($arg:tt)*) => { Error(format!($fmt, $($arg)*)) };
13}
14
15pub(crate) use error;
16
17/// An error type used to represent an error that has already been reported by the compiler.
18#[derive(Clone, Copy, PartialEq, Eq)]
19pub enum CompilerError<T> {
20    /// Compilation failed, either due to normal errors or ICE.
21    Failed,
22    /// Compilation was interrupted.
23    Interrupted(T),
24    /// Compilation skipped. This happens when users invoke rustc to retrieve information such as
25    /// --version.
26    Skipped,
27}
28
29/// A generic error to represent an API request that cannot be fulfilled.
30#[derive(Clone, Debug, Eq, PartialEq)]
31pub struct Error(pub(crate) String);
32
33impl Error {
34    pub fn new(msg: String) -> Self {
35        Self(msg)
36    }
37}
38
39impl From<&str> for Error {
40    fn from(value: &str) -> Self {
41        Self(value.into())
42    }
43}
44
45impl Display for Error {
46    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
47        Display::fmt(&self.0, f)
48    }
49}
50
51impl<T> Display for CompilerError<T>
52where
53    T: Display,
54{
55    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
56        match self {
57            CompilerError::Failed => write!(f, "Compilation Failed"),
58            CompilerError::Interrupted(reason) => write!(f, "Compilation Interrupted: {reason}"),
59            CompilerError::Skipped => write!(f, "Compilation Skipped"),
60        }
61    }
62}
63
64impl<T> Debug for CompilerError<T>
65where
66    T: Debug,
67{
68    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
69        match self {
70            CompilerError::Failed => write!(f, "Compilation Failed"),
71            CompilerError::Interrupted(reason) => write!(f, "Compilation Interrupted: {reason:?}"),
72            CompilerError::Skipped => write!(f, "Compilation Skipped"),
73        }
74    }
75}
76
77impl std::error::Error for Error {}
78
79impl<T> std::error::Error for CompilerError<T> where T: Display + Debug {}
80
81impl From<io::Error> for Error {
82    fn from(value: io::Error) -> Self {
83        Error(value.to_string())
84    }
85}