Skip to main content

runic_diagnostics/
application.rs

1use alloc::boxed::Box;
2use std::process::{ExitCode, Termination};
3
4use crate::{
5    DefaultFailurePolicy, Emitter, FailurePolicy, Outcome, SourceProvider, StderrEmitter,
6    TerminalPolicy,
7    terminal::{EMISSION_FALLBACK, PREPARATION_FALLBACK, write_stderr_fallback},
8};
9
10/// A rich application result that emits every diagnostic before returning.
11pub struct ExitWithOutcome<T = ()> {
12    outcome: Outcome<T>,
13    sources: Option<Box<dyn SourceProvider>>,
14    policy: Box<dyn FailurePolicy>,
15    terminal_policy: TerminalPolicy,
16}
17
18impl<T> ExitWithOutcome<T> {
19    pub(crate) fn new(outcome: Outcome<T>) -> Self {
20        Self {
21            outcome,
22            sources: None,
23            policy: Box::new(DefaultFailurePolicy),
24            terminal_policy: TerminalPolicy::default(),
25        }
26    }
27
28    /// Overrides the retained session source providers used by default.
29    pub fn with_sources<P>(mut self, sources: P) -> Self
30    where
31        P: SourceProvider + 'static,
32    {
33        self.sources = Some(Box::new(sources));
34        self
35    }
36
37    /// Replaces the default error-only failure policy.
38    pub fn with_policy<P>(mut self, policy: P) -> Self
39    where
40        P: FailurePolicy + 'static,
41    {
42        self.policy = Box::new(policy);
43        self
44    }
45
46    /// Selects how stderr terminal capabilities are resolved.
47    pub fn with_terminal_policy(mut self, terminal_policy: TerminalPolicy) -> Self {
48        self.terminal_policy = terminal_policy;
49        self
50    }
51
52    pub const fn outcome(&self) -> &Outcome<T> {
53        &self.outcome
54    }
55
56    pub fn into_outcome(self) -> Outcome<T> {
57        self.outcome
58    }
59}
60
61impl<T> From<Outcome<T>> for ExitWithOutcome<T> {
62    fn from(outcome: Outcome<T>) -> Self {
63        Self::new(outcome)
64    }
65}
66
67impl<T> Termination for ExitWithOutcome<T> {
68    fn report(self) -> ExitCode {
69        let Self {
70            outcome,
71            sources,
72            policy,
73            terminal_policy,
74        } = self;
75        let mut emitter = StderrEmitter::new(terminal_policy);
76        report_with(
77            outcome,
78            sources.as_deref(),
79            policy.as_ref(),
80            |prepared| emitter.emit_set(prepared).map(|_| ()),
81            write_stderr_fallback,
82        )
83    }
84}
85
86fn report_with<T, E>(
87    outcome: Outcome<T>,
88    sources: Option<&dyn SourceProvider>,
89    policy: &dyn FailurePolicy,
90    mut emit: impl FnMut(&crate::PreparedSet<'_>) -> Result<(), E>,
91    mut fallback: impl FnMut(&[u8]),
92) -> ExitCode {
93    let policy_failed = outcome.is_err_with_policy(policy);
94    let prepared = match sources {
95        Some(sources) => outcome.diagnostics.prepare(sources),
96        None => outcome.diagnostics.prepare_attached(),
97    };
98    let prepared = match prepared {
99        Ok(prepared) => prepared,
100        Err(_) => {
101            fallback(PREPARATION_FALLBACK);
102            return ExitCode::FAILURE;
103        }
104    };
105    if emit(&prepared).is_err() {
106        fallback(EMISSION_FALLBACK);
107        return ExitCode::FAILURE;
108    }
109    if policy_failed {
110        ExitCode::FAILURE
111    } else {
112        ExitCode::SUCCESS
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use alloc::vec::Vec;
119    use core::fmt;
120
121    use super::*;
122    use crate::{Diagnostic, DiagnosticCollector, Severity, source::EmptySourceProvider};
123
124    #[derive(Debug)]
125    struct Simple(Severity);
126
127    impl Diagnostic for Simple {
128        fn severity(&self) -> Severity {
129            self.0
130        }
131
132        fn message(&self, out: &mut dyn fmt::Write) -> fmt::Result {
133            out.write_str("simple")
134        }
135    }
136
137    #[derive(Debug)]
138    struct Unpreparable;
139
140    impl Diagnostic for Unpreparable {
141        fn message(&self, _out: &mut dyn fmt::Write) -> fmt::Result {
142            Err(fmt::Error)
143        }
144    }
145
146    fn outcome(diagnostic: impl Diagnostic + Send + Sync + 'static) -> Outcome<()> {
147        let mut collector = DiagnosticCollector::new();
148        collector.add(diagnostic);
149        Outcome {
150            result: Ok(()),
151            diagnostics: collector.finish(),
152        }
153    }
154
155    #[test]
156    fn infrastructure_failures_override_policy_success_with_static_fallbacks() {
157        let sources = EmptySourceProvider;
158        let mut fallback = Vec::new();
159        let status = report_with(
160            outcome(Simple(Severity::Warning)),
161            Some(&sources),
162            &DefaultFailurePolicy,
163            |_| Err::<(), ()>(()),
164            |message| fallback.extend_from_slice(message),
165        );
166        assert_eq!(status, ExitCode::FAILURE);
167        assert_eq!(fallback, EMISSION_FALLBACK);
168
169        fallback.clear();
170        let status = report_with(
171            outcome(Unpreparable),
172            Some(&sources),
173            &DefaultFailurePolicy,
174            |_| Ok::<(), ()>(()),
175            |message| fallback.extend_from_slice(message),
176        );
177        assert_eq!(status, ExitCode::FAILURE);
178        assert_eq!(fallback, PREPARATION_FALLBACK);
179    }
180
181    #[test]
182    fn policy_status_is_used_only_after_successful_infrastructure() {
183        let sources = EmptySourceProvider;
184        let mut emitted = 0;
185        let mut fallback_called = false;
186        let status = report_with(
187            outcome(Simple(Severity::Error)),
188            Some(&sources),
189            &DefaultFailurePolicy,
190            |prepared| {
191                emitted = prepared.len();
192                Ok::<(), ()>(())
193            },
194            |_| fallback_called = true,
195        );
196        assert_eq!(status, ExitCode::FAILURE);
197        assert_eq!(emitted, 1);
198        assert!(!fallback_called);
199    }
200
201    #[derive(Debug)]
202    struct Located(crate::SourceSpan);
203
204    impl Diagnostic for Located {
205        fn message(&self, out: &mut dyn fmt::Write) -> fmt::Result {
206            out.write_str("located diagnostic")
207        }
208
209        fn visit(&self, visitor: &mut dyn crate::VisitDiagnostic) {
210            visitor.label(crate::Label {
211                span: self.0,
212                style: crate::LabelStyle::Primary,
213                message: None,
214            });
215        }
216    }
217
218    #[test]
219    fn retained_sources_are_used_unless_explicitly_overridden() {
220        use crate::{SourceMap, SourceNamespace, SourceSpan, TextRange};
221
222        let namespace = SourceNamespace::new_unchecked(1);
223        for explicit_override in [false, true] {
224            let mut retained = SourceMap::new(namespace);
225            let id = retained.insert("retained.runic", "retained source", None).unwrap();
226            let mut outcome =
227                outcome(Located(SourceSpan::session(id, TextRange::new(0, 8).unwrap())));
228            outcome.diagnostics =
229                outcome.diagnostics.attach_session_sources(alloc::sync::Arc::new(retained));
230            let mut exit = ExitWithOutcome::from(outcome);
231            if explicit_override {
232                let mut sources = SourceMap::new(namespace);
233                assert_eq!(sources.insert("override.runic", "override source", None).unwrap(), id);
234                exit = exit.with_sources(sources);
235            }
236            let mut rendered = alloc::string::String::new();
237            let status = report_with(
238                exit.outcome,
239                exit.sources.as_deref(),
240                exit.policy.as_ref(),
241                |prepared| {
242                    rendered = alloc::format!("{prepared}");
243                    Ok::<(), ()>(())
244                },
245                |_| panic!("diagnostic preparation and emission should succeed"),
246            );
247            assert_eq!(status, ExitCode::FAILURE);
248            let expected = if explicit_override {
249                "override"
250            } else {
251                "retained"
252            };
253            assert!(rendered.contains(&alloc::format!("{expected}.runic")), "{rendered}");
254            assert!(rendered.contains(&alloc::format!("{expected} source")), "{rendered}");
255            let unexpected = if explicit_override {
256                "retained"
257            } else {
258                "override"
259            };
260            assert!(!rendered.contains(&alloc::format!("{unexpected}.runic")), "{rendered}");
261        }
262    }
263
264    #[test]
265    fn failed_result_without_diagnostics_returns_failure() {
266        let status = report_with(
267            Outcome::<()> {
268                result: Err(()),
269                diagnostics: Default::default(),
270            },
271            None,
272            &DefaultFailurePolicy,
273            |_| Ok::<(), ()>(()),
274            |_| panic!("empty diagnostics should prepare and emit successfully"),
275        );
276        assert_eq!(status, ExitCode::FAILURE);
277    }
278
279    #[test]
280    fn warning_status_respects_the_failure_policy() {
281        for (policy, expected) in [
282            (&DefaultFailurePolicy as &dyn FailurePolicy, ExitCode::SUCCESS),
283            (&crate::WarningsAsErrors as &dyn FailurePolicy, ExitCode::FAILURE),
284        ] {
285            let mut emitted = 0;
286            let status = report_with(
287                outcome(Simple(Severity::Warning)),
288                None,
289                policy,
290                |prepared| {
291                    emitted = prepared.len();
292                    Ok::<(), ()>(())
293                },
294                |_| panic!("warning should prepare and emit successfully"),
295            );
296            assert_eq!(emitted, 1);
297            assert_eq!(status, expected);
298        }
299    }
300}