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
mod context;
mod linkedlist;
use std::borrow::Cow;
use std::fmt::Display;
pub use context::{Context, Location};
#[derive(Debug, thiserror::Error)]
pub struct Error {
context: Context,
kind: ErrorKind,
}
impl Error {
pub fn new(kind: ErrorKind) -> Error {
Error {
context: Context::new(),
kind,
}
}
pub fn custom(error: impl Into<CustomError>) -> Error {
Error::new(ErrorKind::Custom(error.into()))
}
pub fn kind(&self) -> &ErrorKind {
&self.kind
}
pub fn context(&self) -> &Context {
&self.context
}
pub fn at(self, loc: Location) -> Self {
Error {
context: self.context.at(loc),
kind: self.kind,
}
}
pub fn at_idx(self, idx: usize) -> Self {
Error {
context: self.context.at(Location::idx(idx)),
kind: self.kind,
}
}
pub fn at_field(self, field: impl Into<Cow<'static, str>>) -> Self {
Error {
context: self.context.at(Location::field(field)),
kind: self.kind,
}
}
pub fn at_variant(self, variant: impl Into<Cow<'static, str>>) -> Self {
Error {
context: self.context.at(Location::variant(variant)),
kind: self.kind,
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let path = self.context.path();
let kind = &self.kind;
write!(f, "Error at {path}: {kind}")
}
}
#[derive(Debug, thiserror::Error)]
pub enum ErrorKind {
#[error("Cannot find type with ID {0}")]
TypeNotFound(u32),
#[error("Cannot encode {actual:?} into type with ID {expected}")]
WrongShape {
actual: Kind,
expected: u32,
},
#[error("Cannot encode to type; expected length {expected_len} but got length {actual_len}")]
WrongLength {
actual_len: usize,
expected_len: usize,
},
#[error("Number {value} is out of range for target type {expected}")]
NumberOutOfRange {
value: String,
expected: u32,
},
#[error("Variant {name} does not exist on type with ID {expected}")]
CannotFindVariant {
name: String,
expected: u32,
},
#[error("Field {name} does not exist in our source struct")]
CannotFindField {
name: String,
},
#[error("Custom error: {0}")]
Custom(CustomError),
}
type CustomError = Box<dyn std::error::Error + Send + Sync + 'static>;
#[allow(missing_docs)]
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Kind {
Struct,
Tuple,
Variant,
Array,
BitSequence,
Bool,
Char,
Str,
Number,
}
#[cfg(test)]
mod test {
use super::*;
#[derive(thiserror::Error, Debug)]
enum MyError {
#[error("Foo!")]
Foo,
}
#[test]
fn custom_error() {
Error::custom(MyError::Foo);
}
}