tvm_ffi/
error.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
use crate::derive::{Object, ObjectRef};
use crate::object::{self, Object, ObjectArc, ObjectRefCore};
use std::ffi::c_void;
use tvm_ffi_sys::TVMFFIBacktraceUpdateMode::kTVMFFIBacktraceUpdateModeAppend;
use tvm_ffi_sys::{
    TVMFFIByteArray, TVMFFIErrorCell, TVMFFIErrorCreateWithCauseAndExtraContext,
    TVMFFIErrorMoveFromRaised, TVMFFIErrorSetRaised, TVMFFIObjectHandle, TVMFFITypeIndex,
};

/// Error kind, wraps in a struct to be explicit
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorKind<'a>(&'a str);

impl<'a> ErrorKind<'a> {
    pub fn as_str(&self) -> &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("ValueError");
pub const TYPE_ERROR: ErrorKind = ErrorKind("TypeError");
pub const RUNTIME_ERROR: ErrorKind = ErrorKind("RuntimeError");
pub const ATTRIBUTE_ERROR: ErrorKind = ErrorKind("AttributeError");
pub const KEY_ERROR: ErrorKind = ErrorKind("KeyError");
pub const INDEX_ERROR: ErrorKind = ErrorKind("IndexError");
pub const INTERNAL_ERROR: ErrorKind = ErrorKind("InternalError");
pub const OVERFLOW_ERROR: ErrorKind = ErrorKind("OverflowError");
pub const ZERO_DIVISION_ERROR: ErrorKind = ErrorKind("ZeroDivisionError");

/// error object
#[repr(C)]
#[derive(Object)]
#[type_key = "ffi.Error"]
#[type_index(TVMFFITypeIndex::kTVMFFIError)]
pub struct ErrorObj {
    object: Object,
    cell: TVMFFIErrorCell,
}

/// Error reference class
#[derive(Clone, ObjectRef)]
pub struct Error {
    data: ObjectArc<ErrorObj>,
}

/// Default result that uses Error as the error type
pub type Result<T, E = Error> = std::result::Result<T, E>;

impl Error {
    pub fn new(kind: ErrorKind<'_>, message: &str, traceback: &str) -> Self {
        Self::new_with_cause_and_extra_context(kind, message, traceback, None, None)
    }

    /// Create an error retaining its cause and any application-specific context.
    pub fn new_with_cause_and_extra_context(
        kind: ErrorKind<'_>,
        message: &str,
        traceback: &str,
        cause_chain: Option<&Error>,
        extra_context: Option<&object::ObjectRef>,
    ) -> Self {
        unsafe {
            let kind_data = TVMFFIByteArray::from_str(kind.as_str());
            let message_data = TVMFFIByteArray::from_str(message);
            let traceback_data = TVMFFIByteArray::from_str(traceback);
            let mut error_handle: TVMFFIObjectHandle = std::ptr::null_mut();
            let ret = TVMFFIErrorCreateWithCauseAndExtraContext(
                &kind_data,
                &message_data,
                &traceback_data,
                cause_chain.map_or(std::ptr::null_mut(), |cause| {
                    ObjectArc::as_raw(&cause.data) as TVMFFIObjectHandle
                }),
                extra_context.map_or(std::ptr::null_mut(), |context| {
                    ObjectArc::as_raw(object::ObjectRef::data(context)) as TVMFFIObjectHandle
                }),
                &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 }
        }
    }

    /// Create a new error by moving from raised error
    ///
    /// # Returns
    /// The error from the raised error
    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 }
        }
    }

    /// Set the error as raised
    ///
    /// # Arguments
    /// * `error` - The error to set as raised
    pub fn set_raised(error: &Self) {
        unsafe {
            TVMFFIErrorSetRaised(ObjectArc::as_raw(&error.data) as TVMFFIObjectHandle);
        }
    }

    /// Get the kind of the error
    ///
    /// # Returns
    /// The kind of the error
    pub fn kind(&self) -> ErrorKind<'_> {
        ErrorKind(&self.data.cell.kind.as_str())
    }

    /// Get the message of the error
    ///
    /// # Returns
    /// The message of the error
    pub fn message(&self) -> &str {
        self.data.cell.message.as_str()
    }

    /// Get the backtrace of the error
    ///
    /// # Returns
    /// The backtrace of the error
    pub fn backtrace(&self) -> &str {
        self.data.cell.backtrace.as_str()
    }

    /// Return the cause, if one was attached to this error.
    pub fn cause_chain(&self) -> Option<Error> {
        let handle = self.data.cell.cause_chain;
        if handle.is_null() {
            return None;
        }
        // The cell owns the handle; acquire a reference for the returned wrapper.
        unsafe {
            object::unsafe_::inc_ref(handle.cast());
            Some(Self {
                data: ObjectArc::from_raw(handle.cast()),
            })
        }
    }

    /// Return the application-specific context, if present.
    pub fn extra_context(&self) -> Option<object::ObjectRef> {
        let handle = self.data.cell.extra_context;
        if handle.is_null() {
            return None;
        }
        unsafe {
            object::unsafe_::inc_ref(handle.cast());
            Some(object::ObjectRef::from_data(ObjectArc::from_raw(
                handle.cast(),
            )))
        }
    }

    /// Get the traceback of the error in the order of most recent call last
    ///
    /// # Returns
    /// The traceback of the error
    pub fn traceback_most_recent_call_last(&self) -> String {
        let backtrace = self.backtrace();
        let backtrace_lines = backtrace.split('\n');
        let mut traceback = String::new();
        for line in backtrace_lines.rev() {
            traceback.push_str(line);
            traceback.push('\n');
        }
        traceback
    }

    /// Append the backtrace to the error
    ///
    /// # Arguments
    /// * `this` - The error to append the backtrace to
    /// * `backtrace` - The backtrace to append
    ///
    /// # Returns
    /// The error with the appended backtrace
    pub fn with_appended_backtrace(this: Self, backtrace: &str) -> Self {
        if ObjectArc::strong_count(&this.data) == 1 {
            // this is the only reference to the error
            // we can safely mutate the error
            unsafe {
                let backtrace_data = TVMFFIByteArray::from_str(backtrace);
                (this.data.cell.update_backtrace)(
                    ObjectArc::as_raw(&this.data) as *mut ErrorObj as *mut c_void,
                    &backtrace_data,
                    kTVMFFIBacktraceUpdateModeAppend as i32,
                );
                this
            }
        } else {
            // we need to create a new error because there is more than one unique reference
            // to the error
            let mut new_backtrace = String::new();
            new_backtrace.push_str(this.backtrace());
            new_backtrace.push_str(backtrace);
            Self::new_with_cause_and_extra_context(
                this.kind(),
                this.message(),
                &new_backtrace,
                this.cause_chain().as_ref(),
                this.extra_context().as_ref(),
            )
        }
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Traceback (most recent call last):\n{}{}: {}",
            self.traceback_most_recent_call_last(),
            self.kind().as_str(),
            self.message()
        )
    }
}

impl std::fmt::Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(self, f)
    }
}

impl std::error::Error for Error {}