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
284
285
286
mod collector;
mod diagnostic_set;
mod failure_policy;
mod limits;
#[cfg(test)]
mod tests;
use alloc::{boxed::Box, string::String, sync::Arc, vec, vec::Vec};
use core::slice;
pub use self::{
collector::{DiagnosticCollector, MergeSummary},
diagnostic_set::{DiagnosticEntry, DiagnosticInstanceId, DiagnosticSet, SeverityCounts},
failure_policy::{DefaultFailurePolicy, FailurePolicy, WarningsAsErrors},
limits::DiagnosticLimits,
};
use self::{diagnostic_set::DiagnosticMetadataSnapshot, limits::LimitReachedDiagnostic};
use crate::{
Diagnostic, DiagnosticCodeRef, DiagnosticDescriptor, DiagnosticMetadata, DiagnosticTag,
OwnedDiagnostic, Report, Severity, SourceProvider,
};
/// An [Outcome] represents the output of a computation and the set of diagnostics that were
/// produced during that computation. Diagnostics may or may not indicate failure, so this type
/// does not treat an outcome as either/or - a successful outcome may still produce diagnostics,
/// which is the primary distinction between this type and [`core::result::Result<T, E>`].
#[derive(Debug)]
pub struct Outcome<T, E = ()> {
pub result: Result<T, E>,
pub diagnostics: DiagnosticSet,
}
impl<T, E> Outcome<T, E> {
/// Returns true if this outcome represents success according to the default failure policy
#[inline]
pub fn is_ok(&self) -> bool {
self.is_ok_with_policy(&DefaultFailurePolicy)
}
/// Returns true if this outcome represents success according to `policy`
pub fn is_ok_with_policy<P>(&self, policy: &P) -> bool
where
P: ?Sized + FailurePolicy,
{
self.result.is_ok() && !self.diagnostics.assess(policy)
}
/// Returns true if this outcome represents failure according to the default failure policy
#[inline]
pub fn is_err(&self) -> bool {
self.is_err_with_policy(&DefaultFailurePolicy)
}
/// Returns true if this outcome represents failure according to `policy`
#[inline]
pub fn is_err_with_policy<P>(&self, policy: &P) -> bool
where
P: ?Sized + FailurePolicy,
{
self.result.is_err() || self.diagnostics.assess(policy)
}
/// Transform the value associated with this outcome, preserving the diagnostics
pub fn map<U>(self, mapper: impl FnOnce(T) -> U) -> Outcome<U, E> {
Outcome {
result: self.result.map(mapper),
diagnostics: self.diagnostics,
}
}
/// Transform the error value associated with this outcome, preserving the diagnostics
pub fn map_err<U>(self, mapper: impl FnOnce(E) -> U) -> Outcome<T, U> {
Outcome {
result: self.result.map_err(mapper),
diagnostics: self.diagnostics,
}
}
/// Transform the value with a fallible associated with this outcome, preserving the diagnostics
pub fn and_then<U>(
self,
mapper: impl FnOnce(T, &mut DiagnosticCollector) -> Result<U, E>,
) -> Outcome<U, E> {
let mut collector = DiagnosticCollector::default();
collector.merge(self.diagnostics);
let result = self.result.and_then(|value| mapper(value, &mut collector));
Outcome {
result,
diagnostics: collector.finish(),
}
}
}
impl<T, E> Outcome<T, E>
where
Report: From<E>,
{
/// Unwrap a successful outcome/value of type `T`, or panic.
#[track_caller]
pub fn unwrap(self) -> T {
self.into_result().unwrap()
}
/// Expect this outcome to have successfully produced a value of `T`, or panic with `message`
///
/// Returns the `T` that was produced, and discards the diagnostics.
#[track_caller]
pub fn expect(self, message: &str) -> T {
self.into_result().expect(message)
}
/// Expect this outcome to have failed to produce a value of `T`, or panic with `message`
///
/// Returns the diagnostics associated with this outcome
#[track_caller]
pub fn expect_err(self, message: &str) -> DiagnosticSet {
if self.is_ok() {
panic!("{message}");
}
match self.result {
Ok(_) => self.diagnostics,
Err(err) => {
let mut collector = DiagnosticCollector::default();
collector.add_report(Report::from(err));
collector.merge(self.diagnostics);
collector.finish()
}
}
}
/// Convert this outcome into a `Result<T, Report>` using the default failure policy
///
/// If the inner `Result` of this outcome is an error, it will be converted to a `Report` as
/// the primary diagnostic
pub fn into_result(self) -> Result<T, Report> {
self.into_result_with_policy(&DefaultFailurePolicy)
}
/// Convert this outcome into a `Result<T, Report>` using the provided failure policy
pub fn into_result_with_policy<P>(self, policy: &P) -> Result<T, Report>
where
P: ?Sized + FailurePolicy,
{
if self.is_ok_with_policy(policy) {
self.result.map_err(Report::from)
} else {
match self.result {
Ok(_) => Err(self.diagnostics.into_report(policy)),
Err(err) => {
let mut collector = DiagnosticCollector::default();
collector.add_report(Report::from(err));
collector.merge(self.diagnostics);
let diagnostics = collector.finish();
Err(diagnostics.into_report(policy))
}
}
}
}
/// Converts this outcome into the std application's rich termination path.
#[cfg(feature = "std")]
pub fn into_exit(self) -> crate::ExitWithOutcome<T> {
let Self {
result,
diagnostics,
} = self;
let outcome = match result {
Ok(value) => Outcome {
result: Ok(value),
diagnostics,
},
Err(err) => {
let mut collector = DiagnosticCollector::default();
collector.add_report(Report::from(err));
collector.merge(diagnostics);
Outcome {
result: Err(()),
diagnostics: collector.finish(),
}
}
};
crate::ExitWithOutcome::new(outcome)
}
}
impl<T> Outcome<T, ()> {
pub fn from_report(report: Report) -> Self {
let mut collector = DiagnosticCollector::default();
collector.add_report(report);
Self {
result: Err(()),
diagnostics: collector.finish(),
}
}
/// Unwrap a successful outcome/value of type `T`, or panic.
#[track_caller]
pub fn unwrap(self) -> T {
self.into_result().unwrap()
}
/// Expect this outcome to have successfully produced a value of `T`, or panic with `message`
///
/// Returns the `T` that was produced, and discards the diagnostics.
#[track_caller]
pub fn expect(self, message: &str) -> T {
self.into_result().expect(message)
}
/// Expect this outcome to have failed to produce a value of `T`, or panic with `message`
///
/// Returns the diagnostics associated with this outcome
#[track_caller]
pub fn expect_err(self, message: &str) -> DiagnosticSet {
if self.is_ok() {
panic!("{message}");
}
self.diagnostics
}
/// Convert this outcome into a `Result<T, Report>` using the default failure policy
///
/// If the inner `Result` of this outcome is an error, it will be converted to a `Report` as
/// the primary diagnostic
pub fn into_result(self) -> Result<T, Report> {
self.into_result_with_policy(&DefaultFailurePolicy)
}
/// Convert this outcome into a `Result<T, Report>` using the provided failure policy
pub fn into_result_with_policy<P>(self, policy: &P) -> Result<T, Report>
where
P: ?Sized + FailurePolicy,
{
if self.is_ok_with_policy(policy) {
self.result.map_err(|_| Report::msg("operation failed with no diagnostics"))
} else {
Err(self.diagnostics.into_report(policy))
}
}
/// Converts this outcome into the std application's rich termination path.
#[cfg(feature = "std")]
pub fn into_exit(self) -> crate::ExitWithOutcome<T> {
crate::ExitWithOutcome::new(self)
}
}
impl<T, E> From<Result<T, E>> for Outcome<T, E> {
fn from(result: Result<T, E>) -> Self {
Self {
result,
diagnostics: DiagnosticSet::default(),
}
}
}
impl<T> From<T> for Outcome<T> {
fn from(value: T) -> Self {
Self {
result: Ok(value),
diagnostics: DiagnosticSet::default(),
}
}
}
/// Represents a type-erased diagnostic sink for use in libraries.
///
/// This abstracts over how diagnostics are collected and reported by the parent application.
pub trait DiagnosticSink {
/// Push `diagnostic` to the sink
///
/// Returns a `PushResult` that indicates whether the diagnostic was successfully recorded, or
/// if it was rejected due to limits or configuration.
fn push(&mut self, diagnostic: OwnedDiagnostic) -> PushResult;
}
/// Result of pushing one user diagnostic into a sink.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PushResult {
/// The diagnostic was accepted successfully
Accepted,
/// The diagnostic was dropped due to a limit on diagnostics that match its characteristics
DroppedByLimit,
/// The diagnostic was dropped because the receiver was closed after a limit was reached
ClosedAfterLimit,
}