-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathreport.rs
254 lines (216 loc) · 6.73 KB
/
report.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
//! Error reporting data structures and miette integration.
use core::fmt;
/// Implemented by errors which can be converted into a [`Report`].
pub trait Enrich<'s>: Sized + private::Sealed {
/// The value which caused the error.
type Subject;
/// Enrich the error with its subject.
fn enrich(self, subject: impl Into<Self::Subject>) -> Enriched<'s, Self> {
Enriched::new(self, subject)
}
/// The docs.rs URL for this error
fn url() -> &'static str;
/// Returns the label for the given [`Subject`] if applicable.
fn labels(&self, subject: &Self::Subject) -> Option<Box<dyn Iterator<Item = Label>>>;
}
/// A label for a span within a json pointer or malformed string.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Label {
text: String,
offset: usize,
len: usize,
}
impl Label {
/// Creates a new instance of a [`Label`] from its parts
pub fn new(text: String, offset: usize, len: usize) -> Self {
Self { text, offset, len }
}
}
#[cfg(feature = "miette")]
impl From<Label> for miette::LabeledSpan {
fn from(value: Label) -> Self {
miette::LabeledSpan::new(Some(value.text), value.offset, value.len)
}
}
/// An error wrapper which includes the [`String`] which failed to parse or the
/// [`PointerBuf`] being used.
#[derive(Clone, PartialEq, Eq)]
pub struct Enriched<'s, S: Enrich<'s>> {
source: S,
subject: S::Subject,
}
impl<'s, S: Enrich<'s>> Enriched<'s, S> {
/// Create a new `Report` with the given subject and error.
fn new(source: S, subject: impl Into<S::Subject>) -> Self {
Self {
source,
subject: subject.into(),
}
}
/// Returns labels associated with spans where the error occurs.
pub fn labels(&self) -> Option<Box<dyn Iterator<Item = Label>>> {
self.source.labels(&self.subject)
}
/// The value which caused the error.
pub fn subject(&self) -> &S::Subject {
&self.subject
}
/// The error which occurred.
pub fn original(&self) -> &S {
&self.source
}
/// The docs.rs URL for the error of this [`Report`].
pub fn url() -> &'static str {
S::url()
}
}
impl<'s, S> core::ops::Deref for Enriched<'s, S>
where
S: Enrich<'s>,
{
type Target = S;
fn deref(&self) -> &Self::Target {
&self.source
}
}
impl<'s, S> fmt::Display for Enriched<'s, S>
where
S: Enrich<'s> + fmt::Display,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
fmt::Display::fmt(&self.source, f)
}
}
impl<'s, S> fmt::Debug for Enriched<'s, S>
where
S: Enrich<'s> + fmt::Debug,
S::Subject: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Enriched")
.field("source", &self.source)
.field("subject", &self.subject)
.finish()
}
}
#[cfg(feature = "std")]
impl<'s, S> std::error::Error for Enriched<'s, S>
where
S: Enrich<'s> + fmt::Debug + std::error::Error + 'static,
S::Subject: fmt::Debug,
{
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
Some(&self.source)
}
}
#[cfg(feature = "miette")]
impl<'s, S> miette::Diagnostic for Enriched<'s, S>
where
S: Enrich<'s> + fmt::Debug + std::error::Error + 'static,
S::Subject: fmt::Debug + miette::SourceCode,
{
fn url<'a>(&'a self) -> Option<Box<dyn core::fmt::Display + 'a>> {
Some(Box::new(Self::url()))
}
fn source_code(&self) -> Option<&dyn miette::SourceCode> {
Some(&self.subject)
}
fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
Some(Box::new(self.labels()?.map(Into::into)))
}
}
macro_rules! impl_diagnostic_url {
(enum $type:ident) => {
$crate::report::impl_diagnostic_url!("enum", "", $type)
};
(struct $type:ident) => {
$crate::report::impl_diagnostic_url!("struct", "", $type)
};
(enum $mod:ident::$type:ident) => {
$crate::report::impl_diagnostic_url!("enum", concat!("/", stringify!($mod)), $type)
};
(struct $mod:ident::$type:ident) => {
$crate::report::impl_diagnostic_url!("struct", concat!("/", stringify!($mod)), $type)
};
($kind:literal, $mod:expr, $type:ident) => {
concat!(
"https://docs.rs/jsonptr/",
env!("CARGO_PKG_VERSION"),
"/jsonptr",
$mod,
"/",
$kind,
".",
stringify!($type),
".html",
)
};
}
pub(crate) use impl_diagnostic_url;
mod private {
pub trait Sealed {}
impl Sealed for crate::pointer::ParseError {}
impl Sealed for crate::assign::Error {}
}
pub trait Diagnose<'s, T> {
type Error: Enrich<'s>;
#[allow(clippy::missing_errors_doc)]
fn diagnose(
self,
subject: impl Into<<Self::Error as Enrich<'s>>::Subject>,
) -> Result<T, Enriched<'s, Self::Error>>;
#[allow(clippy::missing_errors_doc)]
fn diagnose_with<F, S>(self, f: F) -> Result<T, Enriched<'s, Self::Error>>
where
F: FnOnce() -> S,
S: Into<<Self::Error as Enrich<'s>>::Subject>;
}
impl<'s, T, E> Diagnose<'s, T> for Result<T, E>
where
E: Enrich<'s>,
{
type Error = E;
fn diagnose(
self,
subject: impl Into<<Self::Error as Enrich<'s>>::Subject>,
) -> Result<T, Enriched<'s, Self::Error>> {
self.map_err(|error| error.enrich(subject.into()))
}
fn diagnose_with<F, S>(self, f: F) -> Result<T, Enriched<'s, Self::Error>>
where
F: FnOnce() -> S,
S: Into<<Self::Error as Enrich<'s>>::Subject>,
{
self.diagnose(f())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Pointer, PointerBuf};
#[test]
#[cfg(all(
feature = "assign",
feature = "miette",
feature = "serde",
feature = "json"
))]
fn assign_error() {
let mut v = serde_json::json!({"foo": {"bar": ["0"]}});
let ptr = PointerBuf::parse("/foo/bar/invalid/cannot/reach").unwrap();
let report = ptr.assign(&mut v, "qux").diagnose(ptr).unwrap_err();
println!("{:?}", miette::Report::from(report));
let ptr = PointerBuf::parse("/foo/bar/3/cannot/reach").unwrap();
let report = ptr.assign(&mut v, "qux").diagnose(ptr).unwrap_err();
println!("{:?}", miette::Report::from(report));
}
#[test]
fn parse_error() {
let invalid = "/foo/bar/invalid~3~encoding/cannot/reach";
let report = Pointer::parse(invalid).diagnose(invalid).unwrap_err();
println!("{:?}", miette::Report::from(report));
let report = PointerBuf::parse("/foo/bar/invalid~3~encoding/cannot/reach").unwrap_err();
let report = miette::Report::from(report);
println!("{report:?}");
}
}