Skip to main content

mq_lang/module/
error.rs

1use thiserror::Error;
2
3use crate::Token;
4use crate::error::syntax::SyntaxError;
5use std::borrow::Cow;
6
7/// Errors that can occur while loading or resolving mq modules.
8#[derive(Debug, PartialEq, Error)]
9#[non_exhaustive]
10pub enum ModuleError {
11    /// The module was already loaded.
12    #[error("Module `{0}` is already loaded")]
13    AlreadyLoaded(Cow<'static, str>),
14    /// The module could not be found.
15    #[error("Module `{0}` not found")]
16    NotFound(Cow<'static, str>),
17    /// Reading the module failed.
18    #[error("IO error: {0}")]
19    IOError(Cow<'static, str>),
20    /// The module has a syntax error.
21    #[error(transparent)]
22    SyntaxError(#[from] SyntaxError),
23    /// The module imports itself, directly or through other modules.
24    #[error("Circular module dependency: {chain}")]
25    CircularDependency {
26        /// The modules in the cycle, e.g. `a -> b -> a`.
27        chain: Cow<'static, str>,
28        /// The directive that closes the cycle.
29        token: Token,
30    },
31    /// The module declaration is malformed.
32    #[error("Invalid module, expected IDENT or BINDING")]
33    InvalidModule,
34    /// HTTP imports are only permitted at the top level; modules may not fetch remote dependencies.
35    #[cfg(feature = "http-import")]
36    #[error(
37        "HTTP import of `{0}` is not allowed inside an imported module; HTTP imports are only permitted at the top level"
38    )]
39    HttpImportNotAllowed(Cow<'static, str>),
40}
41
42impl ModuleError {
43    /// Returns the token the error points at, if any.
44    #[cold]
45    pub fn token(&self) -> Option<&Token> {
46        match self {
47            ModuleError::AlreadyLoaded(_) => None,
48            ModuleError::NotFound(_) => None,
49            ModuleError::IOError(_) => None,
50            ModuleError::SyntaxError(err) => err.token(),
51            ModuleError::InvalidModule => None,
52            ModuleError::CircularDependency { token, .. } => Some(token),
53            #[cfg(feature = "http-import")]
54            ModuleError::HttpImportNotAllowed(_) => None,
55        }
56    }
57}