Skip to main content

lensbench_core/
error.rs

1//! エラー型。対応していない機能は黙って無視せず `NotImplemented` で止める。
2
3#[derive(Debug, Clone, PartialEq)]
4pub enum Error {
5    /// 対応していない機能を含む
6    NotImplemented(String),
7    /// 値や構成が不正
8    Invalid(String),
9    /// ファイルの読込
10    Io(String),
11    /// 計算を途中でやめた([`crate::par::CancelToken::cancel`]、GUI で系が変わったとき)
12    Cancelled,
13    /// 機械で見分ける符号([`code`] の定数)を付けた誤り([`Error::with_code`]。種類・文は中の誤りのもの)
14    Coded(&'static str, Box<Error>),
15}
16
17/// 誤りの符号([`Error::code`])。serve の `error.data.code`・Python の例外の `code`・試験の判定に使う。
18/// 符号の付いていない誤りの符号は種類の名前([`Error::kind`])
19pub mod code {
20    /// ファイルが無い(種類 io)
21    pub const FILE_NOT_FOUND: &str = "file.not_found";
22    /// ファイルでなくフォルダ(種類 io)
23    pub const IS_FOLDER: &str = "file.is_folder";
24    /// ガラスがカタログに無い・ガラスカタログが見つからない(種類 invalid)
25    pub const GLASS_NOT_FOUND: &str = "glass.not_found";
26    /// プロジェクトに無い状態の名前(種類 invalid)
27    pub const STATE_NOT_FOUND: &str = "project.state_not_found";
28    /// プロジェクトに無いブロックの id(種類 invalid)
29    pub const BLOCK_NOT_FOUND: &str = "project.block_not_found";
30    /// レンズカタログに無い品(種類 invalid)
31    pub const LENS_NOT_FOUND: &str = "catalog.lens_not_found";
32    /// 引数の組み合わせ・値の誤り(読み方の構成・状態・経路の指定など。種類 invalid)
33    pub const BAD_ARGUMENT: &str = "argument.invalid";
34    /// 瞳の光線が像面に届かず(けられ・止まり)、瞳の大きさを決められない系の状態(MTF など。種類 invalid)
35    pub const PUPIL_VIGNETTED: &str = "system.pupil_vignetted";
36    /// 視野の光線が全部けられ(止まり)、像面に届く光線が無い(MTF・PSF・波面など。種類 invalid)
37    pub const ALL_VIGNETTED: &str = "system.all_vignetted";
38
39    /// 符号の一覧(docs・試験で使う)
40    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
53/// 種類の前置き(英語と、日本語の表示のとき)
54const PREFIXES: [(&str, &str); 3] = [
55    ("not supported: ", "未対応: "),
56    ("invalid: ", "不正: "),
57    ("I/O: ", "入出力: "),
58];
59
60/// 表示の文([`crate::i18n`]: 英語の元の文、日本語の表示なら表で訳す)
61impl 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
75/// 誤りを文字列にしたもの s から種類の前置き(英語・日本語)を外し、種類の誤りに戻す(前置きが無ければ None)
76pub 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
85/// 誤りを文字列にしたもの s から「不正: 」(英語は「invalid: 」)の前置きを外す(無ければそのまま)
86pub 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    /// 種類の名前(serve の誤りの `data.kind`・Python の例外のクラスに使う): `not_implemented`・`invalid`・`io`・`cancelled`
96    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    /// 機械で見分ける符号([`code`] の定数。符号を付けていなければ種類の名前 [`Error::kind`])
107    pub fn code(&self) -> &'static str {
108        match self {
109            Error::Coded(c, _) => c,
110            e => e.kind(),
111        }
112    }
113
114    /// 符号 c を付ける(種類・文は変えない。付いていれば付け替える)
115    pub fn with_code(self, c: &'static str) -> Error {
116        Error::Coded(c, Box::new(self.base_owned()))
117    }
118
119    /// 符号を外した誤り(種類で `match` するとき)
120    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    /// 符号のない文の誤り([`Error::Invalid`]・[`Error::Io`]・[`Error::NotImplemented`])の文(中断は None)
135    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    /// 文を f で書き換える(種類・符号は変えない。中断はそのまま)。訳の表の文をソースに残すとき
143    /// (`e.map_message(|e| format!("operation {k}: {e}"))`)
144    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    /// 文を前に足す(種類は変えない)。例: `e.at(sys.surf_label(j))` で「面 87(STANDARD, 膜 THORB): …」
155    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
166/// 入出力の誤り(種類 io。ファイルが無い・フォルダのときは符号 [`code::FILE_NOT_FOUND`]・[`code::IS_FOLDER`] も)
167impl 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    /// 入出力の誤りに文脈(ファイルの名前など)を付けて種類 io のまま上げる: `map_err(Error::io_at(p.display()))`
184    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
189/// 文字列の誤り(種類の前置きがあればその種類、無ければ [`Error::Invalid`])。`Result<_, String>` を返す関数を `?` で呼べる
190impl 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
202/// 誤りを文字列にする(`Result<_, String>` を返す関数の中で `?` で呼べる。種類・符号は消えるので、新しいコードは
203/// [`Error`] のまま返す)。文字列の誤りは表示する所で訳す約束なので、ここでは訳さない(英語の元の文)。
204/// 不正([`Error::Invalid`])は前置きなしの文、ほかは英語の種類の前置きつき([`From<String>`] で種類に戻る)
205impl 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}