Skip to main content

rune/workspace/
error.rs

1use core::fmt;
2
3use std::path::Path;
4
5use crate::alloc::{self, Box, String};
6use crate::ast::{Span, Spanned};
7use crate::compile::HasSpan;
8use crate::source;
9use crate::workspace::glob;
10use crate::SourceId;
11
12/// An error raised when interacting with workspaces.
13#[derive(Debug)]
14pub struct WorkspaceError {
15    span: Span,
16    kind: rust_alloc::boxed::Box<WorkspaceErrorKind>,
17}
18
19impl WorkspaceError {
20    /// Construct a new workspace error with the given span and kind.
21    #[inline]
22    pub(crate) fn new<S, K>(spanned: S, kind: K) -> Self
23    where
24        S: Spanned,
25        WorkspaceErrorKind: From<K>,
26    {
27        Self {
28            span: spanned.span(),
29            kind: rust_alloc::boxed::Box::new(WorkspaceErrorKind::from(kind)),
30        }
31    }
32
33    /// Construct a custom message as an error.
34    #[inline]
35    pub fn msg<S, M>(spanned: S, message: M) -> Self
36    where
37        S: Spanned,
38        M: fmt::Display + fmt::Debug + Send + Sync + 'static,
39    {
40        Self::new(
41            spanned,
42            WorkspaceErrorKind::Custom {
43                error: anyhow::Error::msg(message),
44            },
45        )
46    }
47}
48
49impl Spanned for WorkspaceError {
50    #[inline]
51    fn span(&self) -> Span {
52        self.span
53    }
54}
55
56impl core::error::Error for WorkspaceError {
57    #[inline]
58    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
59        self.kind.source()
60    }
61}
62
63impl fmt::Display for WorkspaceError {
64    #[inline]
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        fmt::Display::fmt(&self.kind, f)
67    }
68}
69
70impl WorkspaceError {
71    #[inline]
72    pub(crate) fn missing_field(span: Span, field: &'static str) -> Self {
73        Self::new(span, WorkspaceErrorKind::MissingField { field })
74    }
75
76    #[inline]
77    pub(crate) fn expected_array(span: Span) -> Self {
78        Self::new(span, WorkspaceErrorKind::ExpectedArray)
79    }
80}
81
82impl<S, E> From<HasSpan<S, E>> for WorkspaceError
83where
84    S: Spanned,
85    WorkspaceErrorKind: From<E>,
86{
87    #[inline]
88    fn from(spanned: HasSpan<S, E>) -> Self {
89        Self::new(spanned.span(), spanned.into_inner())
90    }
91}
92
93/// A workspace error.
94#[derive(Debug)]
95#[allow(missing_docs)]
96#[non_exhaustive]
97pub(crate) enum WorkspaceErrorKind {
98    Custom {
99        error: anyhow::Error,
100    },
101    GlobError {
102        path: Box<Path>,
103        error: glob::GlobError,
104    },
105    Source {
106        path: Box<Path>,
107        error: source::FromPathError,
108    },
109    Toml {
110        error: toml::de::Error,
111    },
112    Key {
113        error: serde_hashkey::Error,
114    },
115    MissingSourceId {
116        source_id: SourceId,
117    },
118    MissingField {
119        field: &'static str,
120    },
121    ExpectedArray,
122    MissingManifestPath,
123    ExpectedTable,
124    UnsupportedKey {
125        key: String,
126    },
127    AllocError {
128        error: alloc::Error,
129    },
130    UnsupportedDependency {
131        name: String,
132    },
133    DependenciesWithoutPackage,
134    MissingDependency {
135        name: String,
136        path: Box<Path>,
137    },
138    DependencyCycle {
139        name: String,
140    },
141    ReadDeclarations {
142        path: Box<Path>,
143        error: std::io::Error,
144    },
145}
146
147impl core::error::Error for WorkspaceErrorKind {
148    #[inline]
149    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
150        match self {
151            WorkspaceErrorKind::GlobError { error, .. } => Some(error),
152            WorkspaceErrorKind::Source { error, .. } => Some(error),
153            WorkspaceErrorKind::Toml { error, .. } => Some(error),
154            WorkspaceErrorKind::Key { error, .. } => Some(error),
155            WorkspaceErrorKind::ReadDeclarations { error, .. } => Some(error),
156            _ => None,
157        }
158    }
159}
160
161impl fmt::Display for WorkspaceErrorKind {
162    #[inline]
163    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
164        match self {
165            WorkspaceErrorKind::Custom { error } => error.fmt(f),
166            WorkspaceErrorKind::GlobError { path, error } => write!(
167                f,
168                "Failed to glob at `{path}`: {error}",
169                path = path.display()
170            ),
171            WorkspaceErrorKind::Source { path, error } => write!(
172                f,
173                "Failed to load source at `{path}`: {error}",
174                path = path.display()
175            ),
176            WorkspaceErrorKind::Toml { error } => {
177                write!(f, "Failed to deserialize manifest: {error}",)
178            }
179            WorkspaceErrorKind::Key { error } => {
180                write!(f, "Failed to deserialize: {error}")
181            }
182            WorkspaceErrorKind::MissingSourceId { source_id } => {
183                write!(f, "Missing source id `{source_id}`",)
184            }
185            WorkspaceErrorKind::MissingField { field } => {
186                write!(f, "Missing required field `{field}`",)
187            }
188            WorkspaceErrorKind::ExpectedArray => write!(f, "Expected array"),
189            WorkspaceErrorKind::MissingManifestPath => write!(
190                f,
191                "Element `[workspace]` can only be used in manifests with a valid path"
192            ),
193            WorkspaceErrorKind::ExpectedTable => write!(f, "Expected table"),
194            WorkspaceErrorKind::UnsupportedKey { key } => write!(f, "Key `{key}` not supported",),
195            WorkspaceErrorKind::AllocError { error } => error.fmt(f),
196            WorkspaceErrorKind::UnsupportedDependency { name } => write!(
197                f,
198                "Dependency `{name}` is not supported, only path dependencies like `{name} = {{ path = \"..\" }}` are"
199            ),
200            WorkspaceErrorKind::DependenciesWithoutPackage => write!(
201                f,
202                "Element `[dependencies]` can only be used in a manifest with a `[package]`"
203            ),
204            WorkspaceErrorKind::MissingDependency { name, path } => write!(
205                f,
206                "Dependency `{name}` has no manifest at `{path}`",
207                path = path.display()
208            ),
209            WorkspaceErrorKind::DependencyCycle { name } => write!(
210                f,
211                "Dependency `{name}` depends on a package which depends on it"
212            ),
213            WorkspaceErrorKind::ReadDeclarations { path, error } => write!(
214                f,
215                "Failed to look for declaration sources in `{path}`: {error}",
216                path = path.display()
217            ),
218        }
219    }
220}
221
222impl From<anyhow::Error> for WorkspaceErrorKind {
223    #[inline]
224    fn from(error: anyhow::Error) -> Self {
225        WorkspaceErrorKind::Custom { error }
226    }
227}
228
229impl From<toml::de::Error> for WorkspaceErrorKind {
230    #[inline]
231    fn from(error: toml::de::Error) -> Self {
232        WorkspaceErrorKind::Toml { error }
233    }
234}
235
236impl From<serde_hashkey::Error> for WorkspaceErrorKind {
237    #[inline]
238    fn from(error: serde_hashkey::Error) -> Self {
239        WorkspaceErrorKind::Key { error }
240    }
241}
242
243impl From<alloc::Error> for WorkspaceError {
244    #[inline]
245    fn from(error: alloc::Error) -> Self {
246        WorkspaceError::new(Span::empty(), error)
247    }
248}
249
250impl From<alloc::Error> for WorkspaceErrorKind {
251    #[inline]
252    fn from(error: alloc::Error) -> Self {
253        WorkspaceErrorKind::AllocError { error }
254    }
255}