Skip to main content

litsea_binding_core/
error.rs

1//! Shared, FFI-independent error type for the language bindings.
2//!
3//! Every binding needs to turn a [`LitseaError`] into its host language's
4//! exception type. Doing that per binding would duplicate the mapping five
5//! times, so this module reduces the error to a stable [`ErrorKind`]
6//! category plus a message. Each binding then writes a single conversion
7//! from [`CoreError`] into its native exception (for example, an
8//! [`ErrorKind::InvalidArgument`] becomes a Python `ValueError` rather than
9//! a bare `RuntimeError`).
10
11use std::fmt;
12
13use litsea::LitseaError;
14
15/// Category of a binding-facing error.
16///
17/// The set is deliberately independent of the `remote_model` feature so
18/// that a binding's exception hierarchy does not change shape when the
19/// feature is toggled.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum ErrorKind {
22    /// The caller supplied an invalid argument, such as an unknown language
23    /// name or an unsupported URI scheme.
24    InvalidArgument,
25    /// A model could not be obtained or is not the kind the operation needs
26    /// (including a failed download and a legacy joint POS model).
27    Model,
28    /// An input/output operation failed.
29    Io,
30    /// Model or training data could not be parsed.
31    Parse,
32    /// The operation is not supported in this build or environment.
33    Unsupported,
34    /// POS tagging was requested from a segmenter built on a
35    /// segmentation-only model.
36    PosUnavailable,
37    /// A runtime failure that does not fit a more specific category.
38    Runtime,
39}
40
41impl ErrorKind {
42    /// Returns a stable, lowercase identifier for the kind.
43    ///
44    /// Bindings expose this to their host language (as an exception
45    /// attribute or an error `code`), so the strings must not change once
46    /// released.
47    ///
48    /// # Returns
49    /// The identifier, for example `"invalid_argument"`.
50    #[must_use]
51    pub fn as_str(self) -> &'static str {
52        match self {
53            ErrorKind::InvalidArgument => "invalid_argument",
54            ErrorKind::Model => "model",
55            ErrorKind::Io => "io",
56            ErrorKind::Parse => "parse",
57            ErrorKind::Unsupported => "unsupported",
58            ErrorKind::PosUnavailable => "pos_unavailable",
59            ErrorKind::Runtime => "runtime",
60        }
61    }
62}
63
64impl fmt::Display for ErrorKind {
65    /// Writes the identifier returned by [`ErrorKind::as_str`].
66    ///
67    /// # Arguments
68    /// * `f` - The formatter to write to.
69    ///
70    /// # Returns
71    /// `Ok(())` on success, or a [`fmt::Error`] if writing fails.
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.write_str(self.as_str())
74    }
75}
76
77/// An FFI-independent error shared by all Litsea language bindings.
78///
79/// Carries a [`ErrorKind`] category plus a human-readable message. It is
80/// `Clone` (unlike [`LitseaError`], which wraps [`std::io::Error`]) because
81/// bindings frequently need to store or re-raise an error after the
82/// original has been consumed.
83#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
84#[error("{message}")]
85pub struct CoreError {
86    /// The error category.
87    kind: ErrorKind,
88    /// The human-readable message.
89    message: String,
90}
91
92impl CoreError {
93    /// Creates an error with the given kind and message.
94    ///
95    /// # Arguments
96    /// * `kind` - The error category.
97    /// * `message` - The human-readable message.
98    ///
99    /// # Returns
100    /// The new [`CoreError`].
101    pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
102        Self {
103            kind,
104            message: message.into(),
105        }
106    }
107
108    /// Creates an [`ErrorKind::InvalidArgument`] error.
109    ///
110    /// # Arguments
111    /// * `message` - The human-readable message.
112    ///
113    /// # Returns
114    /// The new [`CoreError`].
115    pub fn invalid_argument(message: impl Into<String>) -> Self {
116        Self::new(ErrorKind::InvalidArgument, message)
117    }
118
119    /// Creates an [`ErrorKind::Model`] error.
120    ///
121    /// # Arguments
122    /// * `message` - The human-readable message.
123    ///
124    /// # Returns
125    /// The new [`CoreError`].
126    pub fn model(message: impl Into<String>) -> Self {
127        Self::new(ErrorKind::Model, message)
128    }
129
130    /// Creates an [`ErrorKind::Runtime`] error.
131    ///
132    /// # Arguments
133    /// * `message` - The human-readable message.
134    ///
135    /// # Returns
136    /// The new [`CoreError`].
137    pub fn runtime(message: impl Into<String>) -> Self {
138        Self::new(ErrorKind::Runtime, message)
139    }
140
141    /// Returns the error category.
142    ///
143    /// # Returns
144    /// The [`ErrorKind`] this error was created with.
145    #[must_use]
146    pub fn kind(&self) -> ErrorKind {
147        self.kind
148    }
149
150    /// Returns the human-readable message.
151    ///
152    /// # Returns
153    /// The message, without the kind prefix.
154    #[must_use]
155    pub fn message(&self) -> &str {
156        &self.message
157    }
158}
159
160impl From<LitseaError> for CoreError {
161    /// Maps a [`LitseaError`] onto a [`CoreError`].
162    ///
163    /// [`LitseaError::PosLearnerNotSet`] is rewritten: its message names the
164    /// Rust constructor `with_two_stage_learner()`, which means nothing to a
165    /// Python or Ruby caller, so the binding-facing message points at the
166    /// model file instead.
167    ///
168    /// # Arguments
169    /// * `error` - The error to convert.
170    ///
171    /// # Returns
172    /// The equivalent [`CoreError`].
173    fn from(error: LitseaError) -> Self {
174        let kind = match error {
175            LitseaError::Io(_) => ErrorKind::Io,
176            LitseaError::InvalidData(_) => ErrorKind::Parse,
177            LitseaError::InvalidInput(_) => ErrorKind::InvalidArgument,
178            LitseaError::Unsupported(_) => ErrorKind::Unsupported,
179            LitseaError::PosLearnerNotSet => {
180                return Self::new(
181                    ErrorKind::PosUnavailable,
182                    "this segmenter was built from a segmentation-only model; \
183                     load a two-stage POS model (for example japanese_pos.model) to tag parts of speech",
184                );
185            }
186            // `LitseaError::Download` only exists when the `remote_model`
187            // feature is enabled on the `litsea` crate.
188            #[cfg(feature = "remote_model")]
189            LitseaError::Download(_) => ErrorKind::Model,
190            // `LitseaError` is `#[non_exhaustive]`, and `litsea/remote_model`
191            // may also be enabled by another crate in the graph without this
192            // crate's feature.
193            _ => ErrorKind::Runtime,
194        };
195
196        Self::new(kind, error.to_string())
197    }
198}
199
200/// Result alias for the binding core.
201pub type CoreResult<T> = Result<T, CoreError>;
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    #[test]
208    fn test_error_kind_identifiers_are_stable() {
209        assert_eq!(ErrorKind::InvalidArgument.as_str(), "invalid_argument");
210        assert_eq!(ErrorKind::Model.as_str(), "model");
211        assert_eq!(ErrorKind::Io.as_str(), "io");
212        assert_eq!(ErrorKind::Parse.as_str(), "parse");
213        assert_eq!(ErrorKind::Unsupported.as_str(), "unsupported");
214        assert_eq!(ErrorKind::PosUnavailable.as_str(), "pos_unavailable");
215        assert_eq!(ErrorKind::Runtime.as_str(), "runtime");
216        assert_eq!(ErrorKind::Io.to_string(), "io");
217    }
218
219    #[test]
220    fn test_from_litsea_error_maps_kinds() {
221        let io = CoreError::from(LitseaError::Io(std::io::Error::other("boom")));
222        assert_eq!(io.kind(), ErrorKind::Io);
223        assert_eq!(io.message(), "boom");
224
225        let data = CoreError::from(LitseaError::InvalidData("bad line".to_string()));
226        assert_eq!(data.kind(), ErrorKind::Parse);
227        assert_eq!(data.message(), "invalid data: bad line");
228
229        let input = CoreError::from(LitseaError::InvalidInput("bad scheme".to_string()));
230        assert_eq!(input.kind(), ErrorKind::InvalidArgument);
231
232        let unsupported = CoreError::from(LitseaError::Unsupported("nope"));
233        assert_eq!(unsupported.kind(), ErrorKind::Unsupported);
234    }
235
236    #[test]
237    fn test_pos_learner_not_set_is_rewritten() {
238        let error = CoreError::from(LitseaError::PosLearnerNotSet);
239        assert_eq!(error.kind(), ErrorKind::PosUnavailable);
240        assert!(
241            error.message().contains("two-stage POS model"),
242            "message should point at the model file, got: {}",
243            error.message()
244        );
245        assert!(
246            !error.message().contains("with_two_stage_learner"),
247            "the Rust constructor name must not leak into bindings, got: {}",
248            error.message()
249        );
250    }
251
252    #[test]
253    fn test_constructors() {
254        assert_eq!(CoreError::invalid_argument("x").kind(), ErrorKind::InvalidArgument);
255        assert_eq!(CoreError::model("x").kind(), ErrorKind::Model);
256        assert_eq!(CoreError::runtime("x").kind(), ErrorKind::Runtime);
257        assert_eq!(CoreError::model("boom").to_string(), "boom");
258    }
259}