tinymist_std/
error.rs

1//! Error handling utilities for the `tinymist` crate.
2
3use core::fmt;
4
5use ecow::EcoString;
6use serde::{Deserialize, Serialize};
7#[cfg(feature = "typst")]
8use typst::diag::SourceDiagnostic;
9
10use lsp_types::Range as LspRange;
11
12/// The severity of a diagnostic message, following the LSP specification.
13#[derive(serde_repr::Serialize_repr, serde_repr::Deserialize_repr, Debug, Clone)]
14#[repr(u8)]
15pub enum DiagSeverity {
16    /// An error message.
17    Error = 1,
18    /// A warning message.
19    Warning = 2,
20    /// An information message.
21    Information = 3,
22    /// A hint message.
23    Hint = 4,
24}
25
26impl fmt::Display for DiagSeverity {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            DiagSeverity::Error => write!(f, "error"),
30            DiagSeverity::Warning => write!(f, "warning"),
31            DiagSeverity::Information => write!(f, "information"),
32            DiagSeverity::Hint => write!(f, "hint"),
33        }
34    }
35}
36
37/// <https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnostic>
38/// The `owner` and `source` fields are not included in the struct, but they
39/// could be added to `ErrorImpl::arguments`.
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct DiagMessage {
42    /// The typst package specifier.
43    pub package: String,
44    /// The file path relative to the root of the workspace or the package.
45    pub path: String,
46    /// The diagnostic message.
47    pub message: EcoString,
48    /// The severity of the diagnostic message.
49    pub severity: DiagSeverity,
50    /// The char range in the file. The position encoding must be negotiated.
51    pub range: Option<LspRange>,
52}
53
54impl DiagMessage {}
55
56/// ALl kind of errors that can occur in the `tinymist` crate.
57#[derive(Debug, Clone)]
58#[non_exhaustive]
59pub enum ErrKind {
60    /// No message.
61    None,
62    /// A string message.
63    Msg(EcoString),
64    /// A source diagnostic message.
65    #[cfg(feature = "typst")]
66    RawDiag(ecow::EcoVec<SourceDiagnostic>),
67    /// A source diagnostic message.
68    Diag(Box<DiagMessage>),
69    /// An inner error.
70    Inner(Error),
71}
72
73/// A trait to convert an error kind into an error kind.
74pub trait ErrKindExt {
75    /// Convert the error kind into an error kind.
76    fn to_error_kind(self) -> ErrKind;
77}
78
79impl ErrKindExt for ErrKind {
80    fn to_error_kind(self) -> Self {
81        self
82    }
83}
84
85impl ErrKindExt for std::io::Error {
86    fn to_error_kind(self) -> ErrKind {
87        ErrKind::Msg(self.to_string().into())
88    }
89}
90
91impl ErrKindExt for std::str::Utf8Error {
92    fn to_error_kind(self) -> ErrKind {
93        ErrKind::Msg(self.to_string().into())
94    }
95}
96
97impl ErrKindExt for String {
98    fn to_error_kind(self) -> ErrKind {
99        ErrKind::Msg(self.into())
100    }
101}
102
103impl ErrKindExt for &str {
104    fn to_error_kind(self) -> ErrKind {
105        ErrKind::Msg(self.into())
106    }
107}
108
109impl ErrKindExt for &String {
110    fn to_error_kind(self) -> ErrKind {
111        ErrKind::Msg(self.into())
112    }
113}
114
115impl ErrKindExt for EcoString {
116    fn to_error_kind(self) -> ErrKind {
117        ErrKind::Msg(self)
118    }
119}
120
121impl ErrKindExt for &dyn std::fmt::Display {
122    fn to_error_kind(self) -> ErrKind {
123        ErrKind::Msg(self.to_string().into())
124    }
125}
126
127impl ErrKindExt for serde_json::Error {
128    fn to_error_kind(self) -> ErrKind {
129        ErrKind::Msg(self.to_string().into())
130    }
131}
132
133impl ErrKindExt for anyhow::Error {
134    fn to_error_kind(self) -> ErrKind {
135        ErrKind::Msg(self.to_string().into())
136    }
137}
138
139impl ErrKindExt for Error {
140    fn to_error_kind(self) -> ErrKind {
141        ErrKind::Msg(self.to_string().into())
142    }
143}
144
145/// The internal error implementation.
146#[derive(Debug, Clone)]
147pub struct ErrorImpl {
148    /// A static error identifier.
149    loc: &'static str,
150    /// The kind of error.
151    kind: ErrKind,
152    /// Additional extractable arguments for the error.
153    args: Option<Box<[(&'static str, String)]>>,
154}
155
156/// This type represents all possible errors that can occur in typst.ts
157#[derive(Clone)]
158pub struct Error {
159    /// This `Box` allows us to keep the size of `Error` as small as possible. A
160    /// larger `Error` type was substantially slower due to all the functions
161    /// that pass around `Result<T, Error>`.
162    err: Box<ErrorImpl>,
163}
164
165impl Error {
166    /// Creates a new error.
167    pub fn new(
168        loc: &'static str,
169        kind: ErrKind,
170        args: Option<Box<[(&'static str, String)]>>,
171    ) -> Self {
172        Self {
173            err: Box::new(ErrorImpl { loc, kind, args }),
174        }
175    }
176
177    /// Returns the location of the error.
178    pub fn loc(&self) -> &'static str {
179        self.err.loc
180    }
181
182    /// Returns the kind of the error.
183    pub fn kind(&self) -> &ErrKind {
184        &self.err.kind
185    }
186
187    /// Returns the arguments of the error.
188    pub fn arguments(&self) -> &[(&'static str, String)] {
189        self.err.args.as_deref().unwrap_or_default()
190    }
191
192    /// Returns the diagnostics attach to the error.
193    #[cfg(feature = "typst")]
194    pub fn diagnostics(&self) -> Option<&[SourceDiagnostic]> {
195        match &self.err.kind {
196            ErrKind::RawDiag(diag) => Some(diag),
197            _ => None,
198        }
199    }
200}
201
202impl fmt::Debug for Error {
203    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204        <Self as fmt::Display>::fmt(self, f)
205    }
206}
207
208macro_rules! write_with_args {
209    ($f:expr, $args:expr, $fmt:expr  $(, $arg:expr)*) => {
210        if let Some(args) = $args.as_ref() {
211            write!($f, "{}, with {:?}", format_args!($fmt $(, $arg)*), args)
212        } else {
213            write!($f, $fmt $(, $arg)*)
214        }
215    };
216}
217
218impl fmt::Display for Error {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        let err = &self.err;
221
222        if err.loc.is_empty() {
223            match &err.kind {
224                ErrKind::Msg(msg) => {
225                    if msg.is_empty() {
226                        write_with_args!(f, err.args, "{}", err.loc)
227                    } else {
228                        write_with_args!(f, err.args, "{}: {msg}", err.loc)
229                    }
230                }
231                #[cfg(feature = "typst")]
232                ErrKind::RawDiag(diag) => {
233                    write_with_args!(f, err.args, "{diag:?}")
234                }
235                ErrKind::Diag(diag) => {
236                    write_with_args!(f, err.args, "{}", diag.message)
237                }
238                ErrKind::Inner(e) => write_with_args!(f, err.args, "{e}"),
239                ErrKind::None => write_with_args!(f, err.args, "unknown error"),
240            }
241        } else {
242            match &err.kind {
243                ErrKind::Msg(msg) => {
244                    if msg.is_empty() {
245                        write_with_args!(f, err.args, "{}", err.loc)
246                    } else {
247                        write_with_args!(f, err.args, "{}: {msg}", err.loc)
248                    }
249                }
250                #[cfg(feature = "typst")]
251                ErrKind::RawDiag(diag) => {
252                    write_with_args!(f, err.args, "{}: {diag:?}", err.loc)
253                }
254                ErrKind::Diag(diag) => {
255                    write_with_args!(f, err.args, "{}: {}", err.loc, diag.message)
256                }
257                ErrKind::Inner(e) => write_with_args!(f, err.args, "{}: {}", err.loc, e),
258                ErrKind::None => write_with_args!(f, err.args, "{}", err.loc),
259            }
260        }
261    }
262}
263
264impl From<anyhow::Error> for Error {
265    fn from(e: anyhow::Error) -> Self {
266        Error::new("", e.to_string().to_error_kind(), None)
267    }
268}
269
270#[cfg(feature = "typst")]
271impl From<ecow::EcoVec<SourceDiagnostic>> for Error {
272    fn from(e: ecow::EcoVec<SourceDiagnostic>) -> Self {
273        Error::new("", ErrKind::RawDiag(e), None)
274    }
275}
276
277impl std::error::Error for Error {}
278
279#[cfg(feature = "web")]
280impl ErrKindExt for wasm_bindgen::JsValue {
281    fn to_error_kind(self) -> ErrKind {
282        ErrKind::Msg(ecow::eco_format!("{self:?}"))
283    }
284}
285
286#[cfg(feature = "web")]
287impl From<Error> for wasm_bindgen::JsValue {
288    fn from(e: Error) -> Self {
289        js_sys::Error::new(&e.to_string()).into()
290    }
291}
292
293#[cfg(feature = "web")]
294impl From<&Error> for wasm_bindgen::JsValue {
295    fn from(e: &Error) -> Self {
296        js_sys::Error::new(&e.to_string()).into()
297    }
298}
299
300/// The result type used in the `tinymist` crate.
301pub type Result<T, Err = Error> = std::result::Result<T, Err>;
302
303/// A trait to add context to a result.
304pub trait IgnoreLogging<T>: Sized {
305    /// Log an error message and return `None`.
306    fn log_error(self, msg: &str) -> Option<T>;
307    /// Log an error message and return `None`.
308    fn log_error_with(self, f: impl FnOnce() -> String) -> Option<T>;
309}
310
311impl<T, E: std::fmt::Display> IgnoreLogging<T> for Result<T, E> {
312    fn log_error(self, msg: &str) -> Option<T> {
313        self.inspect_err(|e| log::error!("{msg}: {e}")).ok()
314    }
315
316    fn log_error_with(self, f: impl FnOnce() -> String) -> Option<T> {
317        self.inspect_err(|e| log::error!("{}: {e}", f())).ok()
318    }
319}
320
321impl<T> IgnoreLogging<T> for Option<T> {
322    fn log_error(self, msg: &str) -> Option<T> {
323        self.or_else(|| {
324            log::error!("{msg}");
325            None
326        })
327    }
328
329    fn log_error_with(self, f: impl FnOnce() -> String) -> Option<T> {
330        self.or_else(|| {
331            log::error!("{}", f());
332            None
333        })
334    }
335}
336
337/// A trait to add context to a result.
338pub trait WithContext<T>: Sized {
339    /// Add a context to the result.
340    fn context(self, loc: &'static str) -> Result<T>;
341
342    /// Add a context to the result with additional arguments.
343    fn with_context<F>(self, loc: &'static str, f: F) -> Result<T>
344    where
345        F: FnOnce() -> Option<Box<[(&'static str, String)]>>;
346}
347
348impl<T, E: ErrKindExt> WithContext<T> for Result<T, E> {
349    fn context(self, loc: &'static str) -> Result<T> {
350        self.map_err(|e| Error::new(loc, e.to_error_kind(), None))
351    }
352
353    fn with_context<F>(self, loc: &'static str, f: F) -> Result<T>
354    where
355        F: FnOnce() -> Option<Box<[(&'static str, String)]>>,
356    {
357        self.map_err(|e| Error::new(loc, e.to_error_kind(), f()))
358    }
359}
360
361impl<T> WithContext<T> for Option<T> {
362    fn context(self, loc: &'static str) -> Result<T> {
363        self.ok_or_else(|| Error::new(loc, ErrKind::None, None))
364    }
365
366    fn with_context<F>(self, loc: &'static str, f: F) -> Result<T>
367    where
368        F: FnOnce() -> Option<Box<[(&'static str, String)]>>,
369    {
370        self.ok_or_else(|| Error::new(loc, ErrKind::None, f()))
371    }
372}
373
374/// A trait to add context to a result without a specific error type.
375pub trait WithContextUntyped<T>: Sized {
376    /// Add a context to the result.
377    fn context_ut(self, loc: &'static str) -> Result<T>;
378
379    /// Add a context to the result with additional arguments.
380    fn with_context_ut<F>(self, loc: &'static str, f: F) -> Result<T>
381    where
382        F: FnOnce() -> Option<Box<[(&'static str, String)]>>;
383}
384
385impl<T, E: std::fmt::Display> WithContextUntyped<T> for Result<T, E> {
386    fn context_ut(self, loc: &'static str) -> Result<T> {
387        self.map_err(|e| Error::new(loc, ErrKind::Msg(ecow::eco_format!("{e}")), None))
388    }
389
390    fn with_context_ut<F>(self, loc: &'static str, f: F) -> Result<T>
391    where
392        F: FnOnce() -> Option<Box<[(&'static str, String)]>>,
393    {
394        self.map_err(|e| Error::new(loc, ErrKind::Msg(ecow::eco_format!("{e}")), f()))
395    }
396}
397
398/// The error prelude.
399pub mod prelude {
400    #![allow(missing_docs)]
401
402    use super::ErrKindExt;
403    use crate::Error;
404
405    pub use super::{IgnoreLogging, WithContext, WithContextUntyped};
406    pub use crate::{bail, Result};
407
408    pub fn map_string_err<T: ToString>(loc: &'static str) -> impl Fn(T) -> Error {
409        move |e| Error::new(loc, e.to_string().to_error_kind(), None)
410    }
411
412    pub fn map_into_err<S: ErrKindExt, T: Into<S>>(loc: &'static str) -> impl Fn(T) -> Error {
413        move |e| Error::new(loc, e.into().to_error_kind(), None)
414    }
415
416    pub fn map_err<T: ErrKindExt>(loc: &'static str) -> impl Fn(T) -> Error {
417        move |e| Error::new(loc, e.to_error_kind(), None)
418    }
419
420    pub fn wrap_err(loc: &'static str) -> impl Fn(Error) -> Error {
421        move |e| Error::new(loc, crate::ErrKind::Inner(e), None)
422    }
423
424    pub fn map_string_err_with_args<
425        T: ToString,
426        Args: IntoIterator<Item = (&'static str, String)>,
427    >(
428        loc: &'static str,
429        args: Args,
430    ) -> impl FnOnce(T) -> Error {
431        move |e| {
432            Error::new(
433                loc,
434                e.to_string().to_error_kind(),
435                Some(args.into_iter().collect::<Vec<_>>().into_boxed_slice()),
436            )
437        }
438    }
439
440    pub fn map_into_err_with_args<
441        S: ErrKindExt,
442        T: Into<S>,
443        Args: IntoIterator<Item = (&'static str, String)>,
444    >(
445        loc: &'static str,
446        args: Args,
447    ) -> impl FnOnce(T) -> Error {
448        move |e| {
449            Error::new(
450                loc,
451                e.into().to_error_kind(),
452                Some(args.into_iter().collect::<Vec<_>>().into_boxed_slice()),
453            )
454        }
455    }
456
457    pub fn map_err_with_args<T: ErrKindExt, Args: IntoIterator<Item = (&'static str, String)>>(
458        loc: &'static str,
459        args: Args,
460    ) -> impl FnOnce(T) -> Error {
461        move |e| {
462            Error::new(
463                loc,
464                e.to_error_kind(),
465                Some(args.into_iter().collect::<Vec<_>>().into_boxed_slice()),
466            )
467        }
468    }
469
470    pub fn wrap_err_with_args<Args: IntoIterator<Item = (&'static str, String)>>(
471        loc: &'static str,
472        args: Args,
473    ) -> impl FnOnce(Error) -> Error {
474        move |e| {
475            Error::new(
476                loc,
477                crate::ErrKind::Inner(e),
478                Some(args.into_iter().collect::<Vec<_>>().into_boxed_slice()),
479            )
480        }
481    }
482
483    pub fn _error_once(loc: &'static str, args: Box<[(&'static str, String)]>) -> Error {
484        Error::new(loc, crate::ErrKind::None, Some(args))
485    }
486
487    pub fn _msg(loc: &'static str, msg: EcoString) -> Error {
488        Error::new(loc, crate::ErrKind::Msg(msg), None)
489    }
490
491    pub use ecow::eco_format as _eco_format;
492
493    #[macro_export]
494    macro_rules! bail {
495        ($($arg:tt)+) => {{
496            let args = $crate::error::prelude::_eco_format!($($arg)+);
497            return Err($crate::error::prelude::_msg(concat!(file!(), ":", line!(), ":", column!()), args))
498        }};
499    }
500
501    #[macro_export]
502    macro_rules! error_once {
503        ($loc:expr, $($arg_key:ident: $arg:expr),+ $(,)?) => {
504            $crate::error::prelude::_error_once($loc, Box::new([$((stringify!($arg_key), $arg.to_string())),+]))
505        };
506        ($loc:expr $(,)?) => {
507            $crate::error::prelude::_error_once($loc, Box::new([]))
508        };
509    }
510
511    #[macro_export]
512    macro_rules! error_once_map {
513        ($loc:expr, $($arg_key:ident: $arg:expr),+ $(,)?) => {
514            $crate::error::prelude::map_err_with_args($loc, [$((stringify!($arg_key), $arg.to_string())),+])
515        };
516        ($loc:expr $(,)?) => {
517            $crate::error::prelude::map_err($loc)
518        };
519    }
520
521    #[macro_export]
522    macro_rules! error_once_map_string {
523        ($loc:expr, $($arg_key:ident: $arg:expr),+ $(,)?) => {
524            $crate::error::prelude::map_string_err_with_args($loc, [$((stringify!($arg_key), $arg.to_string())),+])
525        };
526        ($loc:expr $(,)?) => {
527            $crate::error::prelude::map_string_err($loc)
528        };
529    }
530
531    use ecow::EcoString;
532    pub use error_once;
533    pub use error_once_map;
534    pub use error_once_map_string;
535}
536
537#[test]
538fn test_send() {
539    fn is_send<T: Send>() {}
540    is_send::<Error>();
541}