Skip to main content

crcbl_hal/
error.rs

1//! Errors crossing the seam.
2//!
3//! Two enums, split by who has to handle them:
4//!
5//! * [`HalError`] — something went wrong. Callers log it and usually give up;
6//!   stage 2 was explicit that the MVP has no fallback
7//!   paths ("error clearly and exit").
8//! * [`SurfaceError`] — presentation-specific, and *routinely non-fatal*.
9//!   [`SurfaceError::OutOfDate`] happens on every window resize and is part of
10//!   the normal frame loop, not an exceptional condition.
11//!
12//! No variant carries a backend type. Where a backend has detail worth keeping
13//! (a driver message, a shader compiler diagnostic) it goes into a `String`,
14//! because the alternative is either losing it or leaking `ash::vk::Result`
15//! into every caller.
16
17use crate::Features;
18
19/// A backend operation failed.
20#[derive(Debug, thiserror::Error)]
21pub enum HalError {
22    /// No adapter with that index exists.
23    #[error("no adapter with index {0}")]
24    NoSuchAdapter(u32),
25
26    /// The chosen adapter lacks features the caller required.
27    ///
28    /// `missing` is the exact gap, from
29    /// [`DeviceCaps::missing`](crate::DeviceCaps::missing) — so the log line
30    /// says which capability to go look up, not merely that something was
31    /// absent.
32    #[error("adapter lacks required features: {missing:?}")]
33    UnsupportedFeatures {
34        /// Features requested but not present.
35        missing: Features,
36    },
37
38    /// A handle did not resolve: it was destroyed, never created, or belongs to
39    /// a different device.
40    ///
41    /// The generational [`Handle`](crcbl_core::Handle) makes this a clean
42    /// failure rather than an alias to whatever took the slot; see
43    /// `crcbl-core`'s handle module.
44    #[error("invalid or stale {kind} handle {bits:#x}")]
45    InvalidHandle {
46        /// Resource kind, e.g. `"buffer"`.
47        kind: &'static str,
48        /// The handle's packed bits, from
49        /// [`Handle::to_bits`](crcbl_core::Handle::to_bits).
50        bits: u64,
51    },
52
53    /// A handle resolved, but it belongs to a different [`Instance`] or
54    /// [`Device`] than the one it was given to.
55    ///
56    /// Distinct from [`HalError::InvalidHandle`] because the causes and the
57    /// fixes differ: a stale handle means "you kept this too long", a foreign
58    /// one means "you crossed two objects that never met". Both are caller
59    /// bugs; neither may be undefined behaviour.
60    ///
61    /// Handle bits are only unique within the backend that issued them, so two
62    /// instances *will* hand out identical bits. Detecting this is therefore an
63    /// implementation obligation on backends, not a property of the handle —
64    /// see [`crate::device`] for the required mechanism.
65    ///
66    /// [`Instance`]: crate::Instance
67    /// [`Device`]: crate::Device
68    #[error("{kind} handle {bits:#x} belongs to a different instance or device")]
69    ForeignObject {
70        /// Resource kind, e.g. `"surface"`.
71        kind: &'static str,
72        /// The handle's packed bits.
73        bits: u64,
74    },
75
76    /// Device memory exhausted.
77    #[error("out of device memory")]
78    OutOfDeviceMemory,
79
80    /// Host memory exhausted.
81    #[error("out of host memory")]
82    OutOfHostMemory,
83
84    /// The device was lost — driver reset, GPU hang, TDR, or the browser
85    /// reclaiming the context. Everything created from it is dead.
86    #[error("device lost: {0}")]
87    DeviceLost(String),
88
89    /// SPIR-V rejected, or cross-compilation to MSL/DXIL/WGSL failed.
90    #[error("shader compilation failed: {0}")]
91    ShaderCompilation(String),
92
93    /// The pipeline state was rejected by the driver.
94    #[error("pipeline creation failed: {0}")]
95    PipelineCreation(String),
96
97    /// A descriptor field was out of range or self-inconsistent — a caller bug,
98    /// which is why the message is expected to name the field.
99    #[error("invalid descriptor: {0}")]
100    InvalidDescriptor(String),
101
102    /// The operation is real but this backend cannot do it. Distinct from
103    /// [`HalError::UnsupportedFeatures`], which is about a *device*.
104    #[error("unsupported by the {backend} backend: {what}")]
105    Unsupported {
106        /// Backend that refused.
107        backend: crate::BackendKind,
108        /// What was asked for.
109        what: &'static str,
110    },
111
112    /// Anything else the backend wants to report verbatim.
113    #[error("{0}")]
114    Backend(String),
115}
116
117/// A surface or swapchain operation failed.
118///
119/// Split out from [`HalError`] because the frame loop must handle
120/// [`SurfaceError::OutOfDate`] as a normal event: every resize produces one, and
121/// a caller that treats it as fatal has a bug that only appears when someone
122/// drags a window edge.
123#[derive(Debug, thiserror::Error)]
124pub enum SurfaceError {
125    /// The swapchain no longer matches the surface — the window resized, the
126    /// canvas changed size, or the display mode changed. Reconfigure with
127    /// [`Device::reconfigure_swapchain`](crate::Device::reconfigure_swapchain)
128    /// and try again next frame.
129    ///
130    /// This is expected traffic, not an error condition.
131    #[error("swapchain out of date; reconfigure and retry")]
132    OutOfDate,
133
134    /// The surface is gone — the window was destroyed, or the compositor
135    /// dropped the connection. Not recoverable by reconfiguring.
136    #[error("surface lost")]
137    Lost,
138
139    /// Acquire timed out with no image available.
140    ///
141    /// Backends with an implicit acquire (WebGPU's `getCurrentTexture`) never
142    /// produce this.
143    #[error("timed out waiting for a swapchain image")]
144    Timeout,
145
146    /// A general failure underneath.
147    #[error(transparent)]
148    Hal(#[from] HalError),
149}
150
151impl HalError {
152    /// Builds an [`HalError::InvalidHandle`] from a typed handle.
153    ///
154    /// Backends call this in their handle-lookup path so the error carries the
155    /// same bits that appear in `Handle`'s `Debug` output.
156    #[must_use]
157    pub fn invalid_handle<T>(kind: &'static str, handle: crcbl_core::Handle<T>) -> Self {
158        Self::InvalidHandle {
159            kind,
160            bits: handle.to_bits(),
161        }
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use crate::{BackendKind, Buffer};
169    use crcbl_core::{Handle, Pool};
170
171    #[test]
172    fn messages_name_the_specific_problem() {
173        let missing = Features::DESCRIPTOR_INDEXING | Features::BUFFER_DEVICE_ADDRESS;
174        let text = HalError::UnsupportedFeatures { missing }.to_string();
175        assert!(text.contains("DESCRIPTOR_INDEXING"), "{text}");
176        assert!(text.contains("BUFFER_DEVICE_ADDRESS"), "{text}");
177
178        let text = HalError::Unsupported {
179            backend: BackendKind::WebGpu,
180            what: "push constants",
181        }
182        .to_string();
183        assert_eq!(text, "unsupported by the webgpu backend: push constants");
184    }
185
186    #[test]
187    fn invalid_handle_carries_the_handle_bits() {
188        let mut pool: Pool<u8> = Pool::new();
189        let handle: Handle<u8> = pool.insert(0);
190        let typed: Handle<Buffer> = handle.cast();
191        let error = HalError::invalid_handle("buffer", typed);
192        let HalError::InvalidHandle { kind, bits } = error else {
193            panic!("wrong variant");
194        };
195        assert_eq!(kind, "buffer");
196        assert_eq!(bits, typed.to_bits());
197        assert_ne!(bits, 0, "packed handle bits are never zero");
198    }
199
200    #[test]
201    fn out_of_date_is_its_own_variant_and_survives_a_hal_error_wrap() {
202        // The frame loop matches on `OutOfDate` directly; if a `HalError`
203        // conversion ever swallowed it into `Hal(..)`, resize handling would
204        // silently become fatal. (`matches!(SurfaceError::OutOfDate,
205        // SurfaceError::OutOfDate)` used to stand here and could not fail.)
206        let wrapped: SurfaceError = HalError::OutOfHostMemory.into();
207        assert!(matches!(wrapped, SurfaceError::Hal(_)));
208        assert!(
209            !matches!(
210                wrapped,
211                SurfaceError::OutOfDate | SurfaceError::Lost | SurfaceError::Timeout
212            ),
213            "and the conversion must not manufacture a presentation variant \
214             either — a resize is something a backend decides, never something \
215             a generic error becomes"
216        );
217        // `transparent`, so the wrap keeps the inner message rather than
218        // prefixing one a caller would have to strip.
219        assert_eq!(wrapped.to_string(), HalError::OutOfHostMemory.to_string());
220    }
221}