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
#![deny(missing_docs)]
pub struct Location {
pub file: Option<String>,
pub line: usize,
pub col: usize,
}
impl Location {
pub fn new(file: Option<String>, line: usize, col: usize) -> Self {
Location { file, line, col }
}
}
impl std::fmt::Display for Location {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(file) = &self.file {
write!(formatter, "{}:{}:{}", file, self.line, self.col)
} else {
write!(formatter, "{}:{}", self.line, self.col)
}
}
}
impl std::fmt::Debug for Location {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "{}", &self)
}
}
#[derive(Debug)]
pub enum Error {
Configuration(String),
Parse(Option<Location>, String),
Internal(Option<Location>, String),
TestFailure(Option<Location>, String),
}
impl std::error::Error for Error {}
impl Error {
pub fn configuration(err: impl std::fmt::Display) -> Self {
Error::Configuration(err.to_string())
}
pub fn parse(location: Option<Location>, err: impl std::fmt::Display) -> Self {
Error::Parse(location, err.to_string())
}
pub fn internal(location: Option<Location>, err: impl Into<String>) -> Self {
Error::Internal(location, err.into())
}
pub fn test_failure(location: Option<Location>, err: impl Into<String>) -> Self {
Error::TestFailure(location, err.into())
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (prefix, loc, err) = match &self {
Error::Configuration(err) => ("Configuration error", &None, err.to_string()),
Error::Parse(loc, err) => ("Parse error", loc, err.to_string()),
Error::Internal(loc, err) => ("Internal error", loc, err.to_string()),
Error::TestFailure(loc, err) => ("Test failure", loc, err.to_string()),
};
match loc {
Some(loc) => write!(f, "{}: {}: {}", prefix, loc, err),
None => write!(f, "{}: {}", prefix, err),
}
}
}
#[macro_export]
macro_rules! test_error {
($err:expr) => {
Error::test_failure(
Some(Location::new(Some(file!().to_string()), line!() as usize, column!() as usize)),
$err,
)
};
}