1#[derive(Debug, Clone, PartialEq)]
4pub enum Error {
5 NotImplemented(String),
7 Invalid(String),
9 Io(String),
11 Cancelled,
13 Coded(&'static str, Box<Error>),
15}
16
17pub mod code {
20 pub const FILE_NOT_FOUND: &str = "file.not_found";
22 pub const IS_FOLDER: &str = "file.is_folder";
24 pub const GLASS_NOT_FOUND: &str = "glass.not_found";
26 pub const STATE_NOT_FOUND: &str = "project.state_not_found";
28 pub const BLOCK_NOT_FOUND: &str = "project.block_not_found";
30 pub const LENS_NOT_FOUND: &str = "catalog.lens_not_found";
32 pub const BAD_ARGUMENT: &str = "argument.invalid";
34 pub const PUPIL_VIGNETTED: &str = "system.pupil_vignetted";
36 pub const ALL_VIGNETTED: &str = "system.all_vignetted";
38
39 pub const ALL: [&str; 9] = [
41 FILE_NOT_FOUND,
42 IS_FOLDER,
43 GLASS_NOT_FOUND,
44 STATE_NOT_FOUND,
45 BLOCK_NOT_FOUND,
46 LENS_NOT_FOUND,
47 BAD_ARGUMENT,
48 PUPIL_VIGNETTED,
49 ALL_VIGNETTED,
50 ];
51}
52
53const PREFIXES: [(&str, &str); 3] = [
55 ("not supported: ", "未対応: "),
56 ("invalid: ", "不正: "),
57 ("I/O: ", "入出力: "),
58];
59
60impl std::fmt::Display for Error {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 let ja = crate::i18n::is_ja();
64 let pre = |i: usize| if ja { PREFIXES[i].1 } else { PREFIXES[i].0 };
65 match self {
66 Error::NotImplemented(s) => write!(f, "{}{}", pre(0), crate::i18n::tr(s)),
67 Error::Invalid(s) => write!(f, "{}{}", pre(1), crate::i18n::tr(s)),
68 Error::Io(s) => write!(f, "{}{}", pre(2), crate::i18n::tr(s)),
69 Error::Cancelled => f.write_str(&crate::i18n::tr("cancelled")),
70 Error::Coded(_, e) => e.fmt(f),
71 }
72 }
73}
74
75pub fn parse_display(s: &str) -> Option<Error> {
77 let kinds: [fn(String) -> Error; 3] = [Error::NotImplemented, Error::Invalid, Error::Io];
78 PREFIXES.iter().zip(kinds).find_map(|((en, ja), k)| {
79 s.strip_prefix(en)
80 .or_else(|| s.strip_prefix(ja))
81 .map(|m| k(m.to_string()))
82 })
83}
84
85pub fn strip_invalid(s: &str) -> &str {
87 s.strip_prefix(PREFIXES[1].0)
88 .or_else(|| s.strip_prefix(PREFIXES[1].1))
89 .unwrap_or(s)
90}
91
92impl std::error::Error for Error {}
93
94impl Error {
95 pub fn kind(&self) -> &'static str {
97 match self {
98 Error::NotImplemented(_) => "not_implemented",
99 Error::Invalid(_) => "invalid",
100 Error::Io(_) => "io",
101 Error::Cancelled => "cancelled",
102 Error::Coded(_, e) => e.kind(),
103 }
104 }
105
106 pub fn code(&self) -> &'static str {
108 match self {
109 Error::Coded(c, _) => c,
110 e => e.kind(),
111 }
112 }
113
114 pub fn with_code(self, c: &'static str) -> Error {
116 Error::Coded(c, Box::new(self.base_owned()))
117 }
118
119 pub fn base(&self) -> &Error {
121 match self {
122 Error::Coded(_, e) => e.base(),
123 e => e,
124 }
125 }
126
127 fn base_owned(self) -> Error {
128 match self {
129 Error::Coded(_, e) => e.base_owned(),
130 e => e,
131 }
132 }
133
134 pub fn message(&self) -> Option<&str> {
136 match self.base() {
137 Error::NotImplemented(s) | Error::Invalid(s) | Error::Io(s) => Some(s),
138 _ => None,
139 }
140 }
141
142 pub fn map_message(self, f: impl FnOnce(&str) -> String) -> Error {
145 match self {
146 Error::NotImplemented(s) => Error::NotImplemented(f(&s)),
147 Error::Invalid(s) => Error::Invalid(f(&s)),
148 Error::Io(s) => Error::Io(f(&s)),
149 Error::Cancelled => Error::Cancelled,
150 Error::Coded(c, e) => Error::Coded(c, Box::new(e.map_message(f))),
151 }
152 }
153
154 pub fn at(self, ctx: impl std::fmt::Display) -> Error {
156 match self {
157 Error::NotImplemented(s) => Error::NotImplemented(format!("{ctx}: {s}")),
158 Error::Invalid(s) => Error::Invalid(format!("{ctx}: {s}")),
159 Error::Io(s) => Error::Io(format!("{ctx}: {s}")),
160 Error::Cancelled => Error::Cancelled,
161 Error::Coded(c, e) => Error::Coded(c, Box::new(e.at(ctx))),
162 }
163 }
164}
165
166impl From<std::io::Error> for Error {
168 fn from(e: std::io::Error) -> Self {
169 let c = match e.kind() {
170 std::io::ErrorKind::NotFound => Some(code::FILE_NOT_FOUND),
171 std::io::ErrorKind::IsADirectory => Some(code::IS_FOLDER),
172 _ => None,
173 };
174 let x = Error::Io(e.to_string());
175 match c {
176 Some(c) => x.with_code(c),
177 None => x,
178 }
179 }
180}
181
182impl Error {
183 pub fn io_at<C: std::fmt::Display>(ctx: C) -> impl FnOnce(std::io::Error) -> Error {
185 move |e| Error::from(e).at(ctx)
186 }
187}
188
189impl From<String> for Error {
191 fn from(s: String) -> Self {
192 parse_display(&s).unwrap_or(Error::Invalid(s))
193 }
194}
195
196impl From<&str> for Error {
197 fn from(s: &str) -> Self {
198 Error::from(s.to_string())
199 }
200}
201
202impl From<Error> for String {
206 fn from(e: Error) -> Self {
207 match e {
208 Error::Invalid(s) => s,
209 Error::NotImplemented(s) => format!("{}{s}", PREFIXES[0].0),
210 Error::Io(s) => format!("{}{s}", PREFIXES[2].0),
211 Error::Cancelled => "cancelled".into(),
212 Error::Coded(_, e) => String::from(*e),
213 }
214 }
215}
216
217pub type Result<T> = std::result::Result<T, Error>;
218
219#[macro_export]
220macro_rules! notimpl {
221 ($($a:tt)*) => { return Err($crate::error::Error::NotImplemented(format!($($a)*))) };
222}
223#[macro_export]
224macro_rules! invalid {
225 (code = $c:expr; $($a:tt)*) => {
226 return Err($crate::error::Error::Invalid(format!($($a)*)).with_code($c))
227 };
228 ($($a:tt)*) => { return Err($crate::error::Error::Invalid(format!($($a)*))) };
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234
235 #[test]
236 fn prefixes_round_trip() {
237 for e in [
238 Error::Invalid("x".into()),
239 Error::Io("y".into()),
240 Error::NotImplemented("z".into()),
241 ] {
242 assert_eq!(parse_display(&e.to_string()), Some(e));
243 }
244 assert_eq!(strip_invalid("不正: a"), "a");
245 assert_eq!(strip_invalid("invalid: a"), "a");
246 assert_eq!(parse_display("a"), None);
247 }
248
249 #[test]
250 fn io_errors_keep_the_kind() {
251 let nf = std::io::Error::from(std::io::ErrorKind::NotFound);
252 let e = Error::io_at("a.zmx")(nf);
253 assert_eq!((e.kind(), e.code()), ("io", code::FILE_NOT_FOUND));
254 assert!(
255 e.message().unwrap_or_default().starts_with("a.zmx: "),
256 "{e}"
257 );
258 let e = Error::from(std::io::Error::other("x"));
259 assert_eq!((e.kind(), e.code()), ("io", "io"));
260 }
261
262 #[test]
263 fn codes_keep_kind_and_text() {
264 let e = Error::Invalid("x".into()).with_code(code::GLASS_NOT_FOUND);
265 assert_eq!((e.kind(), e.code()), ("invalid", "glass.not_found"));
266 assert_eq!(e.to_string(), Error::Invalid("x".into()).to_string());
267 let e = e.at("surface 3");
268 assert_eq!(e.code(), "glass.not_found");
269 assert_eq!(e.message(), Some("surface 3: x"));
270 assert_eq!(Error::Io("y".into()).code(), "io");
271 assert_eq!(
272 Error::Cancelled.with_code(code::BAD_ARGUMENT).base(),
273 &Error::Cancelled
274 );
275 assert_eq!(
276 Error::from("invalid: z".to_string()),
277 Error::Invalid("z".into())
278 );
279 }
280}