tvm_ffi/error.rs
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19//! [`Error`], the error that crosses the FFI boundary, and its [`ErrorKind`]s.
20
21use crate::derive::{Object, ObjectRef};
22use crate::object::{self, Object, ObjectArc, ObjectRefCore};
23use crate::type_traits::AnyCompatible;
24use std::ffi::c_void;
25use tvm_ffi_sys::TVMFFIBacktraceUpdateMode::{
26 kTVMFFIBacktraceUpdateModeAppend, kTVMFFIBacktraceUpdateModeReplace,
27};
28use tvm_ffi_sys::{
29 TVMFFIAny, TVMFFIByteArray, TVMFFIErrorCell, TVMFFIErrorCreateWithCauseAndExtraContext,
30 TVMFFIErrorMoveFromRaised, TVMFFIErrorSetRaised, TVMFFIObjectHandle, TVMFFITypeIndex,
31};
32
33/// The object behind an [`Error`]: its kind, message, backtrace, cause and context.
34#[repr(C)]
35#[derive(Object)]
36#[object(type_key = "ffi.Error", unsafe type_index = TVMFFITypeIndex::kTVMFFIError)]
37pub struct ErrorObj {
38 object: Object,
39 cell: TVMFFIErrorCell,
40}
41
42/// An error that crosses the FFI boundary, with a kind, a message and a
43/// backtrace.
44///
45/// An `Error` raised in another language arrives in Rust as an `Err`, and one
46/// returned from a Rust [`Function`](crate::Function) is raised in the caller's
47/// language. Create one with [`bail!`](crate::bail) or
48/// [`ensure!`](crate::ensure), which also record the source location.
49///
50/// # Examples
51///
52/// ```
53/// use tvm_ffi::{bail, Result, VALUE_ERROR};
54///
55/// fn parse_digit(c: char) -> Result<u32> {
56/// match c.to_digit(10) {
57/// Some(digit) => Ok(digit),
58/// None => bail!(VALUE_ERROR, "not a digit: {:?}", c),
59/// }
60/// }
61///
62/// let error = parse_digit('x').unwrap_err();
63/// assert_eq!(error.kind(), VALUE_ERROR);
64/// assert_eq!(error.message(), "not a digit: 'x'");
65/// ```
66///
67/// An `Error` is `Send + Sync`, so a `Result` can cross threads.
68#[repr(C)]
69#[derive(Clone, ObjectRef)]
70#[object_ref(skip_deref, skip_debug, skip_display)]
71pub struct Error {
72 data: ObjectArc<ErrorObj>,
73}
74
75// SAFETY: a shared Error is never mutated: updates copy unless this handle is unique.
76unsafe impl Send for Error {}
77unsafe impl Sync for Error {}
78
79/// A `Result` whose error type defaults to [`Error`].
80pub type Result<T, E = Error> = std::result::Result<T, E>;
81
82/// The kind of an [`Error`], such as `ValueError`, matching the exception
83/// type that Python raises.
84///
85/// Use the constants such as [`VALUE_ERROR`] and [`TYPE_ERROR`], or
86/// [`ErrorKind::new("MyError")`](ErrorKind::new) for a custom kind.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
88pub struct ErrorKind<'a>(&'a str);
89
90impl<'a> ErrorKind<'a> {
91 /// The kind named `name`, which Python raises as that exception type.
92 ///
93 /// ```
94 /// use tvm_ffi::{Error, ErrorKind};
95 /// const MY_ERROR: ErrorKind = ErrorKind::new("MyError");
96 /// let error = Error::new(MY_ERROR, "bad input");
97 /// assert_eq!(error.kind().as_str(), "MyError");
98 /// ```
99 pub const fn new(name: &'a str) -> Self {
100 Self(name)
101 }
102
103 /// Get the name of the kind.
104 ///
105 /// # Returns
106 ///
107 /// The name, such as `"ValueError"`.
108 pub fn as_str(&self) -> &'a str {
109 self.0
110 }
111}
112
113impl<'a> std::fmt::Display for ErrorKind<'a> {
114 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115 write!(f, "{}", self.0)
116 }
117}
118
119/// `ValueError`: an argument has the right type but a bad value.
120pub const VALUE_ERROR: ErrorKind = ErrorKind::new("ValueError");
121/// `TypeError`: a value has the wrong type.
122pub const TYPE_ERROR: ErrorKind = ErrorKind::new("TypeError");
123/// `RuntimeError`: an operation failed for another reason.
124pub const RUNTIME_ERROR: ErrorKind = ErrorKind::new("RuntimeError");
125/// `AttributeError`: a field, method or attribute does not exist.
126pub const ATTRIBUTE_ERROR: ErrorKind = ErrorKind::new("AttributeError");
127/// `KeyError`: a map has no such key.
128pub const KEY_ERROR: ErrorKind = ErrorKind::new("KeyError");
129/// `IndexError`: an index is out of range.
130pub const INDEX_ERROR: ErrorKind = ErrorKind::new("IndexError");
131/// `InternalError`: a bug, such as a broken invariant or a caught panic.
132pub const INTERNAL_ERROR: ErrorKind = ErrorKind::new("InternalError");
133/// `OverflowError`: a result does not fit its type.
134pub const OVERFLOW_ERROR: ErrorKind = ErrorKind::new("OverflowError");
135/// `ZeroDivisionError`: a division or remainder by zero.
136pub const ZERO_DIVISION_ERROR: ErrorKind = ErrorKind::new("ZeroDivisionError");
137
138impl Error {
139 /// The `InternalError` for a panic caught at an FFI boundary, where unwinding
140 /// into the caller would abort the process. The message is the panic's, when it
141 /// is a string.
142 ///
143 /// ```
144 /// use tvm_ffi::{Error, INTERNAL_ERROR};
145 /// let payload = std::panic::catch_unwind(|| panic!("bad state")).unwrap_err();
146 /// let error = Error::from_panic(payload);
147 /// assert_eq!(error.kind(), INTERNAL_ERROR);
148 /// assert_eq!(error.message(), "panicked: bad state");
149 /// ```
150 pub fn from_panic(payload: Box<dyn std::any::Any + Send>) -> Self {
151 let message = payload
152 .downcast_ref::<&str>()
153 .copied()
154 .or_else(|| {
155 payload
156 .downcast_ref::<std::string::String>()
157 .map(|s| s.as_str())
158 })
159 .unwrap_or("unknown payload");
160 Self::new(INTERNAL_ERROR, &format!("panicked: {message}"))
161 }
162
163 /// The `TypeError` for a reference that [`downcast`](crate::ObjectRefCore::downcast)
164 /// handed back because it is not a `B`, naming both types.
165 ///
166 /// ```
167 /// use tvm_ffi::{object::ObjectRef, Array, Error, ObjectRefCore, TYPE_ERROR};
168 /// let object: ObjectRef = Array::from_vec(vec![1_i64]).into();
169 /// let error = object.downcast::<Array<f64>>().map_err(Error::downcast_failed::<Array<f64>>);
170 /// assert_eq!(error.unwrap_err().kind(), TYPE_ERROR);
171 /// ```
172 pub fn downcast_failed<B: AnyCompatible>(source: impl object::ObjectRefCore) -> Self {
173 let mut cell = TVMFFIAny::new();
174 // SAFETY: `source` stays alive while its borrowed cell is inspected.
175 unsafe { AnyCompatible::copy_to_any_view(&source, &mut cell) };
176 let message = format!(
177 "Cannot convert from type `{}` to `{}`",
178 B::get_mismatch_type_info(&cell),
179 B::type_str()
180 );
181 Self::new(TYPE_ERROR, &message)
182 }
183
184 /// Create an error with an empty backtrace.
185 ///
186 /// Prefer [`format_err!`](crate::format_err) or [`bail!`](crate::bail),
187 /// which also record the source location. Add the other parts with
188 /// [`with_backtrace`](Self::with_backtrace),
189 /// [`with_cause`](Self::with_cause) and
190 /// [`with_extra_context`](Self::with_extra_context).
191 ///
192 /// # Arguments
193 ///
194 /// * `kind` - The kind of the error, such as [`VALUE_ERROR`].
195 /// * `message` - The message of the error.
196 ///
197 /// # Returns
198 ///
199 /// The error.
200 pub fn new(kind: ErrorKind<'_>, message: &str) -> Self {
201 Self::create(kind, message, "", None, std::ptr::null_mut())
202 }
203
204 /// Set `cause` as the error that caused this one, the
205 /// [`cause_chain`](Self::cause_chain). The error is updated in place when
206 /// it is not shared, and copied otherwise.
207 ///
208 /// ```
209 /// use tvm_ffi::{Error, RUNTIME_ERROR, VALUE_ERROR};
210 /// let cause = Error::new(VALUE_ERROR, "bad input");
211 /// let error = Error::new(RUNTIME_ERROR, "load failed").with_cause(&cause);
212 /// assert_eq!(error.cause_chain().unwrap().message(), "bad input");
213 /// ```
214 #[inline]
215 pub fn with_cause(mut self, cause: &Error) -> Self {
216 *self.cause_chain_mut() = Some(cause.clone());
217 self
218 }
219
220 /// Set `context` as the [`extra_context`](Self::extra_context), an object
221 /// of application-specific context; `Send + Sync`, since the error is.
222 /// The error is updated in place when it is not shared, and copied
223 /// otherwise.
224 #[inline]
225 pub fn with_extra_context<T: ObjectRefCore + Send + Sync>(mut self, context: &T) -> Self {
226 *self.extra_context_mut() = Some(object::into_root_object_ref(context.clone()));
227 self
228 }
229
230 /// Create an error from its parts, with `extra_context` a borrowed object
231 /// handle or null.
232 fn create(
233 kind: ErrorKind<'_>,
234 message: &str,
235 backtrace: &str,
236 cause_chain: Option<&Error>,
237 extra_context: TVMFFIObjectHandle,
238 ) -> Self {
239 unsafe {
240 let kind_data = TVMFFIByteArray::from_str(kind.as_str());
241 let message_data = TVMFFIByteArray::from_str(message);
242 let backtrace_data = TVMFFIByteArray::from_str(backtrace);
243 let mut error_handle: TVMFFIObjectHandle = std::ptr::null_mut();
244 let ret = TVMFFIErrorCreateWithCauseAndExtraContext(
245 &kind_data,
246 &message_data,
247 &backtrace_data,
248 cause_chain.map_or(std::ptr::null_mut(), |cause| {
249 ObjectArc::as_ptr(&cause.data) as TVMFFIObjectHandle
250 }),
251 extra_context,
252 &mut error_handle,
253 );
254 assert_eq!(ret, 0, "Failed to create error object");
255 let error_obj = ObjectArc::from_raw(error_handle as *const ErrorObj);
256 Self { data: error_obj }
257 }
258 }
259
260 /// Create a new error by moving from the error that the last failed FFI call
261 /// raised on this thread, as set by [`Error::set_raised`]. An associated
262 /// function rather than a constructor from a value: it takes the thread's
263 /// state.
264 ///
265 /// # Returns
266 ///
267 /// The raised error.
268 ///
269 /// # Panics
270 ///
271 /// Panics if no error was raised.
272 pub fn from_raised() -> Self {
273 unsafe {
274 let mut error_handle: TVMFFIObjectHandle = std::ptr::null_mut();
275 TVMFFIErrorMoveFromRaised(&mut error_handle as *mut TVMFFIObjectHandle);
276 assert!(
277 !error_handle.is_null(),
278 "Calling Error::from_raised but no error was raised"
279 );
280 let error_obj = ObjectArc::from_raw(error_handle as *const ErrorObj);
281 Self { data: error_obj }
282 }
283 }
284
285 /// Set `error` as the raised error of the calling thread, for the caller of
286 /// an `extern "C"` function, which then returns `-1`, to take with
287 /// [`Error::from_raised`]. An associated function rather than a method: it
288 /// changes the thread's state, not `error`.
289 ///
290 /// # Arguments
291 ///
292 /// * `error` - The error to set as raised.
293 pub fn set_raised(error: &Self) {
294 unsafe {
295 TVMFFIErrorSetRaised(ObjectArc::as_ptr(&error.data) as TVMFFIObjectHandle);
296 }
297 }
298
299 /// Get the kind of the error.
300 ///
301 /// # Returns
302 ///
303 /// The kind of the error, such as [`VALUE_ERROR`].
304 pub fn kind(&self) -> ErrorKind<'_> {
305 // SAFETY: the error cell holds UTF-8 text that lives as long as the error.
306 ErrorKind(unsafe { self.data.cell.kind.as_str() })
307 }
308
309 /// Get the message of the error.
310 ///
311 /// # Returns
312 ///
313 /// The message of the error.
314 pub fn message(&self) -> &str {
315 // SAFETY: the error cell holds UTF-8 text that lives as long as the error.
316 unsafe { self.data.cell.message.as_str() }
317 }
318
319 /// Get the backtrace of the error.
320 ///
321 /// It may be rewritten when the error is re-raised through another
322 /// language: copy it to keep it across FFI calls.
323 ///
324 /// # Returns
325 ///
326 /// The backtrace, most recent call first.
327 pub fn backtrace(&self) -> &str {
328 // SAFETY: the error cell holds UTF-8 text that lives as long as the error.
329 unsafe { self.data.cell.backtrace.as_str() }
330 }
331
332 /// The error that caused this one, the next link of the cause chain; the
333 /// same error that `std::error::Error::source` returns.
334 pub fn cause_chain(&self) -> Option<&Error> {
335 let handle = &self.data.cell.cause_chain;
336 if handle.is_null() {
337 return None;
338 }
339 // SAFETY: the cell owns a non-null handle to an error object, and an
340 // `Error` is exactly that one object pointer.
341 Some(unsafe { &*(handle as *const _ as *const Error) })
342 }
343
344 /// The application-specific context object, if present.
345 ///
346 /// The context is shared with every thread the error reaches, so it must be
347 /// safe to share; a context set by another language is the setter's
348 /// responsibility.
349 pub fn extra_context(&self) -> Option<&object::ObjectRef> {
350 let handle = &self.data.cell.extra_context;
351 if handle.is_null() {
352 return None;
353 }
354 // SAFETY: the cell owns a non-null object handle, and an `ObjectRef`
355 // is exactly that one object pointer.
356 Some(unsafe { &*(handle as *const _ as *const object::ObjectRef) })
357 }
358
359 /// The `cause_chain` slot, to update in place.
360 fn cause_chain_mut(&mut self) -> &mut Option<Error> {
361 let error = self.make_mut();
362 // SAFETY: this handle is the only reference, and the slot owns a nullable
363 // error handle, which is exactly an `Option<Error>`.
364 unsafe { &mut *std::ptr::addr_of_mut!((*error).cell.cause_chain).cast::<Option<Error>>() }
365 }
366
367 /// The `extra_context` slot, to update in place.
368 pub(crate) fn extra_context_mut(&mut self) -> &mut Option<object::ObjectRef> {
369 let error = self.make_mut();
370 // SAFETY: this handle is the only reference, and the slot owns a nullable
371 // object handle, which is exactly an `Option<ObjectRef>`.
372 unsafe {
373 &mut *std::ptr::addr_of_mut!((*error).cell.extra_context)
374 .cast::<Option<object::ObjectRef>>()
375 }
376 }
377
378 /// Get the traceback of the error in the order of most recent call last, as
379 /// Python prints it.
380 ///
381 /// # Returns
382 ///
383 /// The traceback of the error.
384 pub fn traceback_most_recent_call_last(&self) -> String {
385 let backtrace = self.backtrace();
386 let mut traceback = String::new();
387 for line in backtrace.split('\n').rev().filter(|line| !line.is_empty()) {
388 traceback.push_str(line);
389 traceback.push('\n');
390 }
391 traceback
392 }
393
394 /// Replace the backtrace, most recent call first. The error is updated in
395 /// place when it is not shared, and copied otherwise.
396 #[inline]
397 pub fn with_backtrace(mut self, backtrace: &str) -> Self {
398 let error = self.make_mut();
399 // SAFETY: `make_mut` made this handle the only reference to `error`.
400 unsafe {
401 let backtrace_data = TVMFFIByteArray::from_str(backtrace);
402 ((*error).cell.update_backtrace)(
403 error.cast::<c_void>(),
404 &backtrace_data,
405 kTVMFFIBacktraceUpdateModeReplace as i32,
406 );
407 }
408 self
409 }
410
411 /// Append the backtrace to the error.
412 ///
413 /// [`attach_context!`](crate::attach_context) appends the current source
414 /// location this way. The error is updated in place when it is not shared, and
415 /// copied otherwise.
416 ///
417 /// # Arguments
418 ///
419 /// * `backtrace` - The backtrace to append.
420 ///
421 /// # Returns
422 ///
423 /// The error with the appended backtrace.
424 pub fn with_appended_backtrace(mut self, backtrace: &str) -> Self {
425 let error = self.make_mut();
426 // SAFETY: `make_mut` made this handle the only reference to `error`.
427 unsafe {
428 let backtrace_data = TVMFFIByteArray::from_str(backtrace);
429 ((*error).cell.update_backtrace)(
430 error.cast::<c_void>(),
431 &backtrace_data,
432 kTVMFFIBacktraceUpdateModeAppend as i32,
433 );
434 }
435 self
436 }
437
438 /// Make this handle the only reference to its error, copying a shared one, as
439 /// `Arc::make_mut`.
440 fn make_mut(&mut self) -> *mut ErrorObj {
441 if !ObjectArc::is_unique(&self.data) {
442 *self = Self::create(
443 self.kind(),
444 self.message(),
445 self.backtrace(),
446 self.cause_chain(),
447 self.data.cell.extra_context,
448 );
449 }
450 ObjectArc::as_mut_ptr(&mut self.data)
451 }
452}
453
454/// Formats the kind and the message, such as `ValueError: bad x`, as C++
455/// `what()`; [`Debug`](std::fmt::Debug) adds the traceback.
456impl std::fmt::Display for Error {
457 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
458 write!(f, "{}: {}", self.kind().as_str(), self.message())
459 }
460}
461
462/// Formats the traceback, most recent call last, then the kind and the
463/// message, as Python prints an exception; `unwrap` and `expect` print it.
464impl std::fmt::Debug for Error {
465 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
466 if self.backtrace().is_empty() {
467 return std::fmt::Display::fmt(self, f);
468 }
469 write!(
470 f,
471 "Traceback (most recent call last):\n{}{self}",
472 self.traceback_most_recent_call_last(),
473 )
474 }
475}
476
477impl std::error::Error for Error {
478 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
479 self.cause_chain().map(|cause| cause as _)
480 }
481}