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
321/// A trait to add context to a result.
322pub trait WithContext<T>: Sized {
323    /// Add a context to the result.
324    fn context(self, loc: &'static str) -> Result<T>;
325
326    /// Add a context to the result with additional arguments.
327    fn with_context<F>(self, loc: &'static str, f: F) -> Result<T>
328    where
329        F: FnOnce() -> Option<Box<[(&'static str, String)]>>;
330}
331
332impl<T, E: ErrKindExt> WithContext<T> for Result<T, E> {
333    fn context(self, loc: &'static str) -> Result<T> {
334        self.map_err(|e| Error::new(loc, e.to_error_kind(), None))
335    }
336
337    fn with_context<F>(self, loc: &'static str, f: F) -> Result<T>
338    where
339        F: FnOnce() -> Option<Box<[(&'static str, String)]>>,
340    {
341        self.map_err(|e| Error::new(loc, e.to_error_kind(), f()))
342    }
343}
344
345impl<T> WithContext<T> for Option<T> {
346    fn context(self, loc: &'static str) -> Result<T> {
347        self.ok_or_else(|| Error::new(loc, ErrKind::None, None))
348    }
349
350    fn with_context<F>(self, loc: &'static str, f: F) -> Result<T>
351    where
352        F: FnOnce() -> Option<Box<[(&'static str, String)]>>,
353    {
354        self.ok_or_else(|| Error::new(loc, ErrKind::None, f()))
355    }
356}
357
358/// A trait to add context to a result without a specific error type.
359pub trait WithContextUntyped<T>: Sized {
360    /// Add a context to the result.
361    fn context_ut(self, loc: &'static str) -> Result<T>;
362
363    /// Add a context to the result with additional arguments.
364    fn with_context_ut<F>(self, loc: &'static str, f: F) -> Result<T>
365    where
366        F: FnOnce() -> Option<Box<[(&'static str, String)]>>;
367}
368
369impl<T, E: std::fmt::Display> WithContextUntyped<T> for Result<T, E> {
370    fn context_ut(self, loc: &'static str) -> Result<T> {
371        self.map_err(|e| Error::new(loc, ErrKind::Msg(ecow::eco_format!("{e}")), None))
372    }
373
374    fn with_context_ut<F>(self, loc: &'static str, f: F) -> Result<T>
375    where
376        F: FnOnce() -> Option<Box<[(&'static str, String)]>>,
377    {
378        self.map_err(|e| Error::new(loc, ErrKind::Msg(ecow::eco_format!("{e}")), f()))
379    }
380}
381
382/// The error prelude.
383pub mod prelude {
384    #![allow(missing_docs)]
385
386    use super::ErrKindExt;
387    use crate::Error;
388
389    pub use super::{IgnoreLogging, WithContext, WithContextUntyped};
390    pub use crate::{bail, Result};
391
392    pub fn map_string_err<T: ToString>(loc: &'static str) -> impl Fn(T) -> Error {
393        move |e| Error::new(loc, e.to_string().to_error_kind(), None)
394    }
395
396    pub fn map_into_err<S: ErrKindExt, T: Into<S>>(loc: &'static str) -> impl Fn(T) -> Error {
397        move |e| Error::new(loc, e.into().to_error_kind(), None)
398    }
399
400    pub fn map_err<T: ErrKindExt>(loc: &'static str) -> impl Fn(T) -> Error {
401        move |e| Error::new(loc, e.to_error_kind(), None)
402    }
403
404    pub fn wrap_err(loc: &'static str) -> impl Fn(Error) -> Error {
405        move |e| Error::new(loc, crate::ErrKind::Inner(e), None)
406    }
407
408    pub fn map_string_err_with_args<
409        T: ToString,
410        Args: IntoIterator<Item = (&'static str, String)>,
411    >(
412        loc: &'static str,
413        args: Args,
414    ) -> impl FnOnce(T) -> Error {
415        move |e| {
416            Error::new(
417                loc,
418                e.to_string().to_error_kind(),
419                Some(args.into_iter().collect::<Vec<_>>().into_boxed_slice()),
420            )
421        }
422    }
423
424    pub fn map_into_err_with_args<
425        S: ErrKindExt,
426        T: Into<S>,
427        Args: IntoIterator<Item = (&'static str, String)>,
428    >(
429        loc: &'static str,
430        args: Args,
431    ) -> impl FnOnce(T) -> Error {
432        move |e| {
433            Error::new(
434                loc,
435                e.into().to_error_kind(),
436                Some(args.into_iter().collect::<Vec<_>>().into_boxed_slice()),
437            )
438        }
439    }
440
441    pub fn map_err_with_args<T: ErrKindExt, Args: IntoIterator<Item = (&'static str, String)>>(
442        loc: &'static str,
443        args: Args,
444    ) -> impl FnOnce(T) -> Error {
445        move |e| {
446            Error::new(
447                loc,
448                e.to_error_kind(),
449                Some(args.into_iter().collect::<Vec<_>>().into_boxed_slice()),
450            )
451        }
452    }
453
454    pub fn wrap_err_with_args<Args: IntoIterator<Item = (&'static str, String)>>(
455        loc: &'static str,
456        args: Args,
457    ) -> impl FnOnce(Error) -> Error {
458        move |e| {
459            Error::new(
460                loc,
461                crate::ErrKind::Inner(e),
462                Some(args.into_iter().collect::<Vec<_>>().into_boxed_slice()),
463            )
464        }
465    }
466
467    pub fn _error_once(loc: &'static str, args: Box<[(&'static str, String)]>) -> Error {
468        Error::new(loc, crate::ErrKind::None, Some(args))
469    }
470
471    pub fn _msg(loc: &'static str, msg: EcoString) -> Error {
472        Error::new(loc, crate::ErrKind::Msg(msg), None)
473    }
474
475    pub use ecow::eco_format as _eco_format;
476
477    #[macro_export]
478    macro_rules! bail {
479        ($($arg:tt)+) => {{
480            let args = $crate::error::prelude::_eco_format!($($arg)+);
481            return Err($crate::error::prelude::_msg(concat!(file!(), ":", line!(), ":", column!()), args))
482        }};
483    }
484
485    #[macro_export]
486    macro_rules! error_once {
487        ($loc:expr, $($arg_key:ident: $arg:expr),+ $(,)?) => {
488            $crate::error::prelude::_error_once($loc, Box::new([$((stringify!($arg_key), $arg.to_string())),+]))
489        };
490        ($loc:expr $(,)?) => {
491            $crate::error::prelude::_error_once($loc, Box::new([]))
492        };
493    }
494
495    #[macro_export]
496    macro_rules! error_once_map {
497        ($loc:expr, $($arg_key:ident: $arg:expr),+ $(,)?) => {
498            $crate::error::prelude::map_err_with_args($loc, [$((stringify!($arg_key), $arg.to_string())),+])
499        };
500        ($loc:expr $(,)?) => {
501            $crate::error::prelude::map_err($loc)
502        };
503    }
504
505    #[macro_export]
506    macro_rules! error_once_map_string {
507        ($loc:expr, $($arg_key:ident: $arg:expr),+ $(,)?) => {
508            $crate::error::prelude::map_string_err_with_args($loc, [$((stringify!($arg_key), $arg.to_string())),+])
509        };
510        ($loc:expr $(,)?) => {
511            $crate::error::prelude::map_string_err($loc)
512        };
513    }
514
515    use ecow::EcoString;
516    pub use error_once;
517    pub use error_once_map;
518    pub use error_once_map_string;
519}
520
521#[test]
522fn test_send() {
523    fn is_send<T: Send>() {}
524    is_send::<Error>();
525}