Skip to main content

runic_diagnostics/
collection.rs

1mod collector;
2mod diagnostic_set;
3mod failure_policy;
4mod limits;
5#[cfg(test)]
6mod tests;
7
8use alloc::{boxed::Box, string::String, sync::Arc, vec, vec::Vec};
9use core::slice;
10
11pub use self::{
12    collector::{DiagnosticCollector, MergeSummary},
13    diagnostic_set::{DiagnosticEntry, DiagnosticInstanceId, DiagnosticSet, SeverityCounts},
14    failure_policy::{DefaultFailurePolicy, FailurePolicy, WarningsAsErrors},
15    limits::DiagnosticLimits,
16};
17use self::{diagnostic_set::DiagnosticMetadataSnapshot, limits::LimitReachedDiagnostic};
18use crate::{
19    Diagnostic, DiagnosticCodeRef, DiagnosticDescriptor, DiagnosticMetadata, DiagnosticTag,
20    OwnedDiagnostic, Report, Severity, SourceProvider,
21};
22
23/// An [Outcome] represents the output of a computation and the set of diagnostics that were
24/// produced during that computation. Diagnostics may or may not indicate failure, so this type
25/// does not treat an outcome as either/or - a successful outcome may still produce diagnostics,
26/// which is the primary distinction between this type and [`core::result::Result<T, E>`].
27#[derive(Debug)]
28pub struct Outcome<T, E = ()> {
29    pub result: Result<T, E>,
30    pub diagnostics: DiagnosticSet,
31}
32
33impl<T, E> Outcome<T, E> {
34    /// Returns true if this outcome represents success according to the default failure policy
35    #[inline]
36    pub fn is_ok(&self) -> bool {
37        self.is_ok_with_policy(&DefaultFailurePolicy)
38    }
39
40    /// Returns true if this outcome represents success according to `policy`
41    pub fn is_ok_with_policy<P>(&self, policy: &P) -> bool
42    where
43        P: ?Sized + FailurePolicy,
44    {
45        self.result.is_ok() && !self.diagnostics.assess(policy)
46    }
47
48    /// Returns true if this outcome represents failure according to the default failure policy
49    #[inline]
50    pub fn is_err(&self) -> bool {
51        self.is_err_with_policy(&DefaultFailurePolicy)
52    }
53
54    /// Returns true if this outcome represents failure according to `policy`
55    #[inline]
56    pub fn is_err_with_policy<P>(&self, policy: &P) -> bool
57    where
58        P: ?Sized + FailurePolicy,
59    {
60        self.result.is_err() || self.diagnostics.assess(policy)
61    }
62
63    /// Transform the value associated with this outcome, preserving the diagnostics
64    pub fn map<U>(self, mapper: impl FnOnce(T) -> U) -> Outcome<U, E> {
65        Outcome {
66            result: self.result.map(mapper),
67            diagnostics: self.diagnostics,
68        }
69    }
70
71    /// Transform the error value associated with this outcome, preserving the diagnostics
72    pub fn map_err<U>(self, mapper: impl FnOnce(E) -> U) -> Outcome<T, U> {
73        Outcome {
74            result: self.result.map_err(mapper),
75            diagnostics: self.diagnostics,
76        }
77    }
78
79    /// Transform the value with a fallible associated with this outcome, preserving the diagnostics
80    pub fn and_then<U>(
81        self,
82        mapper: impl FnOnce(T, &mut DiagnosticCollector) -> Result<U, E>,
83    ) -> Outcome<U, E> {
84        let mut collector = DiagnosticCollector::default();
85        collector.merge(self.diagnostics);
86        let result = self.result.and_then(|value| mapper(value, &mut collector));
87        Outcome {
88            result,
89            diagnostics: collector.finish(),
90        }
91    }
92}
93
94impl<T, E> Outcome<T, E>
95where
96    Report: From<E>,
97{
98    /// Unwrap a successful outcome/value of type `T`, or panic.
99    #[track_caller]
100    pub fn unwrap(self) -> T {
101        self.into_result().unwrap()
102    }
103
104    /// Expect this outcome to have successfully produced a value of `T`, or panic with `message`
105    ///
106    /// Returns the `T` that was produced, and discards the diagnostics.
107    #[track_caller]
108    pub fn expect(self, message: &str) -> T {
109        self.into_result().expect(message)
110    }
111
112    /// Expect this outcome to have failed to produce a value of `T`, or panic with `message`
113    ///
114    /// Returns the diagnostics associated with this outcome
115    #[track_caller]
116    pub fn expect_err(self, message: &str) -> DiagnosticSet {
117        if self.is_ok() {
118            panic!("{message}");
119        }
120        match self.result {
121            Ok(_) => self.diagnostics,
122            Err(err) => {
123                let mut collector = DiagnosticCollector::default();
124                collector.add_report(Report::from(err));
125                collector.merge(self.diagnostics);
126                collector.finish()
127            }
128        }
129    }
130
131    /// Convert this outcome into a `Result<T, Report>` using the default failure policy
132    ///
133    /// If the inner `Result` of this outcome is an error, it will be converted to a `Report` as
134    /// the primary diagnostic
135    pub fn into_result(self) -> Result<T, Report> {
136        self.into_result_with_policy(&DefaultFailurePolicy)
137    }
138
139    /// Convert this outcome into a `Result<T, Report>` using the provided failure policy
140    pub fn into_result_with_policy<P>(self, policy: &P) -> Result<T, Report>
141    where
142        P: ?Sized + FailurePolicy,
143    {
144        if self.is_ok_with_policy(policy) {
145            self.result.map_err(Report::from)
146        } else {
147            match self.result {
148                Ok(_) => Err(self.diagnostics.into_report(policy)),
149                Err(err) => {
150                    let mut collector = DiagnosticCollector::default();
151                    collector.add_report(Report::from(err));
152                    collector.merge(self.diagnostics);
153                    let diagnostics = collector.finish();
154                    Err(diagnostics.into_report(policy))
155                }
156            }
157        }
158    }
159
160    /// Converts this outcome into the std application's rich termination path.
161    #[cfg(feature = "std")]
162    pub fn into_exit(self) -> crate::ExitWithOutcome<T> {
163        let Self {
164            result,
165            diagnostics,
166        } = self;
167        let outcome = match result {
168            Ok(value) => Outcome {
169                result: Ok(value),
170                diagnostics,
171            },
172            Err(err) => {
173                let mut collector = DiagnosticCollector::default();
174                collector.add_report(Report::from(err));
175                collector.merge(diagnostics);
176                Outcome {
177                    result: Err(()),
178                    diagnostics: collector.finish(),
179                }
180            }
181        };
182        crate::ExitWithOutcome::new(outcome)
183    }
184}
185
186impl<T> Outcome<T, ()> {
187    pub fn from_report(report: Report) -> Self {
188        let mut collector = DiagnosticCollector::default();
189        collector.add_report(report);
190        Self {
191            result: Err(()),
192            diagnostics: collector.finish(),
193        }
194    }
195
196    /// Unwrap a successful outcome/value of type `T`, or panic.
197    #[track_caller]
198    pub fn unwrap(self) -> T {
199        self.into_result().unwrap()
200    }
201
202    /// Expect this outcome to have successfully produced a value of `T`, or panic with `message`
203    ///
204    /// Returns the `T` that was produced, and discards the diagnostics.
205    #[track_caller]
206    pub fn expect(self, message: &str) -> T {
207        self.into_result().expect(message)
208    }
209
210    /// Expect this outcome to have failed to produce a value of `T`, or panic with `message`
211    ///
212    /// Returns the diagnostics associated with this outcome
213    #[track_caller]
214    pub fn expect_err(self, message: &str) -> DiagnosticSet {
215        if self.is_ok() {
216            panic!("{message}");
217        }
218        self.diagnostics
219    }
220
221    /// Convert this outcome into a `Result<T, Report>` using the default failure policy
222    ///
223    /// If the inner `Result` of this outcome is an error, it will be converted to a `Report` as
224    /// the primary diagnostic
225    pub fn into_result(self) -> Result<T, Report> {
226        self.into_result_with_policy(&DefaultFailurePolicy)
227    }
228
229    /// Convert this outcome into a `Result<T, Report>` using the provided failure policy
230    pub fn into_result_with_policy<P>(self, policy: &P) -> Result<T, Report>
231    where
232        P: ?Sized + FailurePolicy,
233    {
234        if self.is_ok_with_policy(policy) {
235            self.result.map_err(|_| Report::msg("operation failed with no diagnostics"))
236        } else {
237            Err(self.diagnostics.into_report(policy))
238        }
239    }
240
241    /// Converts this outcome into the std application's rich termination path.
242    #[cfg(feature = "std")]
243    pub fn into_exit(self) -> crate::ExitWithOutcome<T> {
244        crate::ExitWithOutcome::new(self)
245    }
246}
247
248impl<T, E> From<Result<T, E>> for Outcome<T, E> {
249    fn from(result: Result<T, E>) -> Self {
250        Self {
251            result,
252            diagnostics: DiagnosticSet::default(),
253        }
254    }
255}
256
257impl<T> From<T> for Outcome<T> {
258    fn from(value: T) -> Self {
259        Self {
260            result: Ok(value),
261            diagnostics: DiagnosticSet::default(),
262        }
263    }
264}
265
266/// Represents a type-erased diagnostic sink for use in libraries.
267///
268/// This abstracts over how diagnostics are collected and reported by the parent application.
269pub trait DiagnosticSink {
270    /// Push `diagnostic` to the sink
271    ///
272    /// Returns a `PushResult` that indicates whether the diagnostic was successfully recorded, or
273    /// if it was rejected due to limits or configuration.
274    fn push(&mut self, diagnostic: OwnedDiagnostic) -> PushResult;
275}
276
277/// Result of pushing one user diagnostic into a sink.
278#[derive(Clone, Copy, Debug, Eq, PartialEq)]
279pub enum PushResult {
280    /// The diagnostic was accepted successfully
281    Accepted,
282    /// The diagnostic was dropped due to a limit on diagnostics that match its characteristics
283    DroppedByLimit,
284    /// The diagnostic was dropped because the receiver was closed after a limit was reached
285    ClosedAfterLimit,
286}