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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
mod aggregate;
mod global;
mod scope;
mod serde;
mod sync_error;
pub use global::{BadBinaryFormat, CannotBeNone, Global};
pub use scope::*;
pub use sync_error::*;
pub use tea_codec_macros::define_scope;
pub use smallvec::{smallvec, SmallVec};
#[cfg(feature = "backtrace")]
use std::backtrace::Backtrace;
use std::{
any::TypeId,
borrow::Cow,
boxed::ThinBox,
fmt::{Debug, Display, Formatter},
marker::PhantomData,
mem::{self, ManuallyDrop},
};
use crate::type_gym::{Equality, NotEqual, TypeMark};
pub struct Error<S = ()> {
data: ThinBox<ErrorData<dyn Descriptee>>,
_p: PhantomData<S>,
}
#[cfg(feature = "backtrace")]
enum ErrorLocation {
Native(Backtrace),
Serialized(Cow<'static, str>),
}
struct ErrorData<T>
where
T: ?Sized,
{
#[cfg(feature = "backtrace")]
location: ErrorLocation,
source: T,
}
auto trait NotWrappedError {}
impl<S> !NotWrappedError for TypeMark<Error<S>> {}
impl<S> NotWrappedError for Error<S> {}
pub trait NotError {}
impl<T> NotError for T where TypeMark<T>: NotWrappedError {}
impl<S> Error<S>
where
S: Scope,
{
fn new<T>(data: T, #[cfg(feature = "backtrace")] location: ErrorLocation) -> Self
where
T: NotError + Send + Sync + 'static,
{
Self {
data: ThinBox::new_unsize(ErrorData {
#[cfg(feature = "backtrace")]
location,
source: Dispatcher::<_, S>::new(data),
}),
_p: PhantomData,
}
}
}
#[cfg(not(feature = "checked"))]
impl<T, S> From<T> for Error<S>
where
T: NotError + Send + Sync + 'static,
S: Scope,
{
default fn from(data: T) -> Self {
Self::new(
data,
#[cfg(feature = "backtrace")]
ErrorLocation::Native(Backtrace::capture()),
)
}
}
#[cfg(feature = "checked")]
impl<T, S> From<T> for Error<S>
where
T: NotError + Send + Sync + 'static,
S: Scope + DescriptableMark<T>,
{
default fn from(data: T) -> Self {
Self::new(
data,
#[cfg(feature = "backtrace")]
ErrorLocation::Native(Backtrace::capture()),
)
}
}
impl<X, Y> From<Error<X>> for Error<Y>
where
Equality<X, Y>: NotEqual,
{
fn from(source: Error<X>) -> Self {
Self {
data: source.data,
_p: PhantomData,
}
}
}
impl<'a, X, Y> From<&'a Error<X>> for &'a Error<Y>
where
Equality<X, Y>: NotEqual,
{
fn from(scope: &'a Error<X>) -> Self {
scope.as_scope()
}
}
impl<S> Error<S> {
pub fn name(&self) -> Cow<str> {
if let Some(name) = self.data.source.name() {
name
} else {
"".into()
}
}
pub fn summary(&self) -> Option<Cow<str>> {
self.data.source.summary()
}
pub fn human(&self) -> Option<String> {
if let Some(detail) = self.data.source.detail() {
let reg = regex::Regex::new(r"___([\s\S]*)___").unwrap();
if let Some(r) = reg.captures(&detail) {
if let Some(mm) = r.get(1) {
return Some(mm.as_str().to_string());
}
}
}
None
}
pub fn detail(&self) -> Option<Cow<str>> {
self.data.source.detail()
}
pub fn inner(&self) -> SmallVec<[&Error; 1]> {
self.data.source.inner().unwrap_or_default()
}
#[cfg(feature = "backtrace")]
pub fn backtrace(&self) -> Cow<str> {
match &self.data.location {
ErrorLocation::Native(location) => Cow::Owned(location.to_string()),
ErrorLocation::Serialized(location) => Cow::Borrowed(location),
}
}
pub fn into_scope<T>(self) -> Error<T> {
Error {
data: self.data,
_p: PhantomData,
}
}
pub fn as_scope<T>(&self) -> &Error<T> {
unsafe { mem::transmute(self) }
}
pub fn back_cast<T>(self) -> Result<T, Self>
where
T: Send + Sync + 'static,
{
if self.data.source.type_id() == Some(TypeId::of::<T>()) {
let mut data = self.data;
unsafe {
let result = (&mut (*(&mut data.source as *mut _ as *mut Dispatcher<T, S>)).data
as *mut T)
.read();
mem::transmute::<_, ThinBox<ErrorData<ManuallyDrop<dyn Descriptee>>>>(data);
Ok(result)
}
} else {
Err(self)
}
}
pub fn back_cast_ref<T>(&self) -> Option<&T>
where
T: Send + Sync + 'static,
{
if self.data.source.type_id() == Some(TypeId::of::<T>()) {
unsafe { Some(&(*(&self.data.source as *const _ as *const Dispatcher<T, S>)).data) }
} else {
None
}
}
pub fn is_name_of<T>(&self) -> bool
where
T: Send + Sync + Default + 'static,
S: Scope,
{
Dispatcher::<T, S>::new(Default::default()).name() == Some(self.name())
}
pub fn name_of<T>() -> Option<String>
where
T: Send + Sync + Default + 'static,
S: Scope,
{
Dispatcher::<T, S>::new(Default::default())
.name()
.map(Into::into)
}
}
impl<S> Display for Error<S> {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
if let Some(value) = self.summary() {
f.write_str(value.as_ref())?;
}
Ok(())
}
}
impl<S> Debug for Error<S> {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
f.write_fmt(format_args!("[{}]", self.name().as_ref()))?;
if let Some(value) = self.summary() {
f.write_str(value.as_ref())?;
}
if let Some(value) = self.detail() {
f.write_fmt(format_args!("\n{value}"))?;
}
let inner = self.inner();
for (index, &inner) in inner.iter().enumerate() {
f.write_fmt(format_args!("\nInner Error {index}: {{{inner:?}}}"))?;
}
#[cfg(feature = "backtrace")]
f.write_fmt(format_args!("\n{}", self.backtrace()))?;
Ok(())
}
}
impl<S> std::error::Error for Error<S> {}
pub trait ResultXExt {
fn assume_error_into_backcast<E>(self) -> Option<E>
where
E: Send + Sync + 'static;
}
impl<T, S> ResultXExt for Result<T, Error<S>> {
fn assume_error_into_backcast<E>(self) -> Option<E>
where
E: Send + Sync + 'static,
{
if let Err(e) = self {
if let Ok(e) = e.back_cast() {
return Some(e);
}
}
None
}
}
impl<S> PartialEq for Error<S> {
fn eq(&self, other: &Self) -> bool {
self.name() == other.name()
&& self.summary() == other.summary()
&& self.detail() == other.detail()
&& self.inner() == other.inner()
}
}
impl<S> Eq for Error<S> {}