use crate::derive::{Object, ObjectRef};
use crate::object::{self, Object, ObjectArc, ObjectRefCore};
use crate::type_traits::AnyCompatible;
use std::ffi::c_void;
use tvm_ffi_sys::TVMFFIBacktraceUpdateMode::{
kTVMFFIBacktraceUpdateModeAppend, kTVMFFIBacktraceUpdateModeReplace,
};
use tvm_ffi_sys::{
TVMFFIAny, TVMFFIByteArray, TVMFFIErrorCell, TVMFFIErrorCreateWithCauseAndExtraContext,
TVMFFIErrorMoveFromRaised, TVMFFIErrorSetRaised, TVMFFIObjectHandle, TVMFFITypeIndex,
};
#[repr(C)]
#[derive(Object)]
#[object(type_key = "ffi.Error", unsafe type_index = TVMFFITypeIndex::kTVMFFIError)]
pub struct ErrorObj {
object: Object,
cell: TVMFFIErrorCell,
}
#[repr(C)]
#[derive(Clone, ObjectRef)]
#[object_ref(skip_deref, skip_debug, skip_display)]
pub struct Error {
data: ObjectArc<ErrorObj>,
}
unsafe impl Send for Error {}
unsafe impl Sync for Error {}
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ErrorKind<'a>(&'a str);
impl<'a> ErrorKind<'a> {
pub const fn new(name: &'a str) -> Self {
Self(name)
}
pub fn as_str(&self) -> &'a str {
self.0
}
}
impl<'a> std::fmt::Display for ErrorKind<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
pub const VALUE_ERROR: ErrorKind = ErrorKind::new("ValueError");
pub const TYPE_ERROR: ErrorKind = ErrorKind::new("TypeError");
pub const RUNTIME_ERROR: ErrorKind = ErrorKind::new("RuntimeError");
pub const ATTRIBUTE_ERROR: ErrorKind = ErrorKind::new("AttributeError");
pub const KEY_ERROR: ErrorKind = ErrorKind::new("KeyError");
pub const INDEX_ERROR: ErrorKind = ErrorKind::new("IndexError");
pub const INTERNAL_ERROR: ErrorKind = ErrorKind::new("InternalError");
pub const OVERFLOW_ERROR: ErrorKind = ErrorKind::new("OverflowError");
pub const ZERO_DIVISION_ERROR: ErrorKind = ErrorKind::new("ZeroDivisionError");
impl Error {
pub fn from_panic(payload: Box<dyn std::any::Any + Send>) -> Self {
let message = payload
.downcast_ref::<&str>()
.copied()
.or_else(|| {
payload
.downcast_ref::<std::string::String>()
.map(|s| s.as_str())
})
.unwrap_or("unknown payload");
Self::new(INTERNAL_ERROR, &format!("panicked: {message}"))
}
pub fn downcast_failed<B: AnyCompatible>(source: impl object::ObjectRefCore) -> Self {
let mut cell = TVMFFIAny::new();
unsafe { AnyCompatible::copy_to_any_view(&source, &mut cell) };
let message = format!(
"Cannot convert from type `{}` to `{}`",
B::get_mismatch_type_info(&cell),
B::type_str()
);
Self::new(TYPE_ERROR, &message)
}
pub fn new(kind: ErrorKind<'_>, message: &str) -> Self {
Self::create(kind, message, "", None, std::ptr::null_mut())
}
#[inline]
pub fn with_cause(mut self, cause: &Error) -> Self {
*self.cause_chain_mut() = Some(cause.clone());
self
}
#[inline]
pub fn with_extra_context<T: ObjectRefCore + Send + Sync>(mut self, context: &T) -> Self {
*self.extra_context_mut() = Some(object::into_root_object_ref(context.clone()));
self
}
fn create(
kind: ErrorKind<'_>,
message: &str,
backtrace: &str,
cause_chain: Option<&Error>,
extra_context: TVMFFIObjectHandle,
) -> Self {
unsafe {
let kind_data = TVMFFIByteArray::from_str(kind.as_str());
let message_data = TVMFFIByteArray::from_str(message);
let backtrace_data = TVMFFIByteArray::from_str(backtrace);
let mut error_handle: TVMFFIObjectHandle = std::ptr::null_mut();
let ret = TVMFFIErrorCreateWithCauseAndExtraContext(
&kind_data,
&message_data,
&backtrace_data,
cause_chain.map_or(std::ptr::null_mut(), |cause| {
ObjectArc::as_ptr(&cause.data) as TVMFFIObjectHandle
}),
extra_context,
&mut error_handle,
);
assert_eq!(ret, 0, "Failed to create error object");
let error_obj = ObjectArc::from_raw(error_handle as *const ErrorObj);
Self { data: error_obj }
}
}
pub fn from_raised() -> Self {
unsafe {
let mut error_handle: TVMFFIObjectHandle = std::ptr::null_mut();
TVMFFIErrorMoveFromRaised(&mut error_handle as *mut TVMFFIObjectHandle);
assert!(
!error_handle.is_null(),
"Calling Error::from_raised but no error was raised"
);
let error_obj = ObjectArc::from_raw(error_handle as *const ErrorObj);
Self { data: error_obj }
}
}
pub fn set_raised(error: &Self) {
unsafe {
TVMFFIErrorSetRaised(ObjectArc::as_ptr(&error.data) as TVMFFIObjectHandle);
}
}
pub fn kind(&self) -> ErrorKind<'_> {
ErrorKind(unsafe { self.data.cell.kind.as_str() })
}
pub fn message(&self) -> &str {
unsafe { self.data.cell.message.as_str() }
}
pub fn backtrace(&self) -> &str {
unsafe { self.data.cell.backtrace.as_str() }
}
pub fn cause_chain(&self) -> Option<&Error> {
let handle = &self.data.cell.cause_chain;
if handle.is_null() {
return None;
}
Some(unsafe { &*(handle as *const _ as *const Error) })
}
pub fn extra_context(&self) -> Option<&object::ObjectRef> {
let handle = &self.data.cell.extra_context;
if handle.is_null() {
return None;
}
Some(unsafe { &*(handle as *const _ as *const object::ObjectRef) })
}
fn cause_chain_mut(&mut self) -> &mut Option<Error> {
let error = self.make_mut();
unsafe { &mut *std::ptr::addr_of_mut!((*error).cell.cause_chain).cast::<Option<Error>>() }
}
pub(crate) fn extra_context_mut(&mut self) -> &mut Option<object::ObjectRef> {
let error = self.make_mut();
unsafe {
&mut *std::ptr::addr_of_mut!((*error).cell.extra_context)
.cast::<Option<object::ObjectRef>>()
}
}
pub fn traceback_most_recent_call_last(&self) -> String {
let backtrace = self.backtrace();
let mut traceback = String::new();
for line in backtrace.split('\n').rev().filter(|line| !line.is_empty()) {
traceback.push_str(line);
traceback.push('\n');
}
traceback
}
#[inline]
pub fn with_backtrace(mut self, backtrace: &str) -> Self {
let error = self.make_mut();
unsafe {
let backtrace_data = TVMFFIByteArray::from_str(backtrace);
((*error).cell.update_backtrace)(
error.cast::<c_void>(),
&backtrace_data,
kTVMFFIBacktraceUpdateModeReplace as i32,
);
}
self
}
pub fn with_appended_backtrace(mut self, backtrace: &str) -> Self {
let error = self.make_mut();
unsafe {
let backtrace_data = TVMFFIByteArray::from_str(backtrace);
((*error).cell.update_backtrace)(
error.cast::<c_void>(),
&backtrace_data,
kTVMFFIBacktraceUpdateModeAppend as i32,
);
}
self
}
fn make_mut(&mut self) -> *mut ErrorObj {
if !ObjectArc::is_unique(&self.data) {
*self = Self::create(
self.kind(),
self.message(),
self.backtrace(),
self.cause_chain(),
self.data.cell.extra_context,
);
}
ObjectArc::as_mut_ptr(&mut self.data)
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.kind().as_str(), self.message())
}
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.backtrace().is_empty() {
return std::fmt::Display::fmt(self, f);
}
write!(
f,
"Traceback (most recent call last):\n{}{self}",
self.traceback_most_recent_call_last(),
)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.cause_chain().map(|cause| cause as _)
}
}