Skip to main content

astrs_cli/
diagnostic.rs

1//! [`CliDiagnostic`]: the one flat, orderable diagnostic shape
2//! `astrs validate` renders, unifying four different upstream types
3//! (an I/O failure, [`astrs_manifest::ManifestError`],
4//! [`astrs_manifest::ValidationError`], [`astrs_manifest::expand::ExpandError`]
5//! and [`astrs_graph::Diagnostic`]) that otherwise share no common trait
6//! beyond `Display` — blueprint §17's "human diagnostics (path, severity,
7//! colored)" and `--json` need one list to print, not five differently
8//! shaped error types each rendered by hand.
9//!
10//! Every failure mode `astrs validate` can encounter — the file not
11//! existing, the YAML not parsing, a structural violation, a module that
12//! fails to expand, a type mismatch, an unconsumed output — becomes one
13//! [`CliDiagnostic`] rather than aborting the command outright. This is
14//! deliberate: a diagnostic tool's job is to tell the user everything
15//! that's wrong in one pass, not to stop at the first problem (the same
16//! reasoning [`astrs_manifest::ValidationErrors`] itself documents).
17
18use std::fmt;
19
20pub use astrs_graph::Severity;
21
22/// Which stage of the `validate` pipeline produced a [`CliDiagnostic`].
23#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
24#[serde(rename_all = "snake_case")]
25pub enum Source {
26    /// The manifest file could not be read from disk.
27    Io,
28    /// The manifest did not parse as YAML.
29    Parse,
30    /// [`astrs_manifest::Manifest::validate`] reported a structural
31    /// violation.
32    Structural,
33    /// [`astrs_manifest::expand::expand`] failed.
34    Expand,
35    /// [`astrs_graph::DataflowGraph::diagnostics`] (or its construction
36    /// pass) reported an observation.
37    Graph,
38    /// `--prove` was requested but formal verification is not enabled in
39    /// this build.
40    Prove,
41}
42
43impl fmt::Display for Source {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        f.write_str(match self {
46            Self::Io => "io",
47            Self::Parse => "parse",
48            Self::Structural => "structural",
49            Self::Expand => "expand",
50            Self::Graph => "graph",
51            Self::Prove => "prove",
52        })
53    }
54}
55
56/// One unified validation observation.
57#[derive(Debug, Clone, serde::Serialize)]
58pub struct CliDiagnostic {
59    /// How serious this observation is.
60    pub severity: Severity,
61    /// Which stage produced it.
62    pub source: Source,
63    /// A document path (`nodes[3].inputs.frames`) when the underlying
64    /// observation is anchored to one, e.g. every
65    /// [`Source::Structural`] entry. `None` for whole-file observations
66    /// ([`Source::Io`], [`Source::Parse`] without a known location,
67    /// [`Source::Prove`]) and for [`Source::Graph`] entries (that crate's
68    /// [`astrs_graph::Diagnostic`] identifies nodes/edges structurally
69    /// rather than via a document path; see its own `Display`, folded
70    /// into [`Self::message`] instead).
71    #[serde(skip_serializing_if = "Option::is_none")]
72    pub path: Option<String>,
73    /// A human-readable rendering of the observation.
74    pub message: String,
75}
76
77impl CliDiagnostic {
78    /// The manifest file could not be read.
79    #[must_use]
80    pub fn io(message: impl Into<String>) -> Self {
81        Self {
82            severity: Severity::Error,
83            source: Source::Io,
84            path: None,
85            message: message.into(),
86        }
87    }
88
89    /// The manifest did not parse as YAML.
90    #[must_use]
91    pub fn parse(err: &astrs_manifest::ManifestError) -> Self {
92        let path = match (err.line(), err.column()) {
93            (Some(line), Some(column)) => Some(format!("line {line}, column {column}")),
94            _ => None,
95        };
96        Self {
97            severity: Severity::Error,
98            source: Source::Parse,
99            path,
100            message: err.to_string(),
101        }
102    }
103
104    /// One structural violation from [`astrs_manifest::Manifest::validate`].
105    #[must_use]
106    pub fn structural(err: &astrs_manifest::ValidationError) -> Self {
107        Self {
108            severity: Severity::Error,
109            source: Source::Structural,
110            path: Some(err.path.clone()),
111            message: err.kind.to_string(),
112        }
113    }
114
115    /// Module expansion failed.
116    #[must_use]
117    pub fn expand(err: &astrs_manifest::expand::ExpandError) -> Self {
118        Self {
119            severity: Severity::Error,
120            source: Source::Expand,
121            path: None,
122            message: err.to_string(),
123        }
124    }
125
126    /// [`astrs_graph::DataflowGraph::from_manifest`] rejected the
127    /// manifest outright.
128    ///
129    /// Reachable in practice only when the manifest skipped
130    /// [`astrs_manifest::Manifest::validate`] — see that function's own
131    /// docs — which `validate`'s pipeline never does; kept as a
132    /// diagnostic rather than an assumed-unreachable panic so a future
133    /// regression in that pipeline degrades to a reported error instead
134    /// of a crash.
135    #[must_use]
136    pub fn graph_build_error(err: &astrs_graph::GraphBuildError) -> Self {
137        Self {
138            severity: Severity::Error,
139            source: Source::Graph,
140            path: None,
141            message: err.to_string(),
142        }
143    }
144
145    /// One observation from [`astrs_graph::DataflowGraph::diagnostics`] (or
146    /// its construction pass).
147    #[must_use]
148    pub fn graph(diag: &astrs_graph::Diagnostic) -> Self {
149        Self {
150            severity: diag.severity,
151            source: Source::Graph,
152            path: None,
153            message: diag.to_string(),
154        }
155    }
156
157    /// `--prove` was requested on a build without the `verify` feature.
158    ///
159    /// A warning rather than an error: the obligations were still encoded
160    /// and printed, and the command reports the missing solver through
161    /// [`crate::error::CliError::ProofUnavailable`]'s exit code rather
162    /// than by inflating the diagnostic scale.
163    #[must_use]
164    pub fn prove_unavailable() -> Self {
165        Self {
166            severity: Severity::Warning,
167            source: Source::Prove,
168            path: None,
169            message: "--prove encoded every obligation but this build has no solver; \
170                      rebuild with `--features verify` to discharge them"
171                .to_string(),
172        }
173    }
174
175    /// One refuted obligation.
176    #[must_use]
177    pub fn prove_violation(heading: &str, headline: &str) -> Self {
178        Self {
179            severity: Severity::Error,
180            source: Source::Prove,
181            path: None,
182            message: format!("{heading}: {headline}"),
183        }
184    }
185
186    /// Some obligation left a hole in the proof, so the run rules out what
187    /// it lists and no more.
188    ///
189    /// `missing_declaration` counts only *gaps* — obligations that needed a
190    /// fact nobody supplied. An obligation with nothing to prove (no
191    /// declared budget, no typed edge) is vacuously satisfied and is
192    /// deliberately not counted here, even though the proof report lists it
193    /// under "not attempted".
194    #[must_use]
195    pub fn prove_incomplete(missing_declaration: usize, inconclusive: usize) -> Self {
196        Self {
197            severity: Severity::Warning,
198            source: Source::Prove,
199            path: None,
200            message: format!(
201                "{missing_declaration} obligation(s) lack a declaration to decide them and \
202                 {inconclusive} were left undecided; this proof rules out what it lists, and no more"
203            ),
204        }
205    }
206
207    /// The proof run could not be set up at all.
208    #[must_use]
209    pub fn prove_error(message: impl Into<String>) -> Self {
210        Self {
211            severity: Severity::Error,
212            source: Source::Prove,
213            path: None,
214            message: message.into(),
215        }
216    }
217}
218
219/// The worst [`Severity`] across `diagnostics`, or `None` for an empty
220/// list.
221#[must_use]
222pub fn max_severity(diagnostics: &[CliDiagnostic]) -> Option<Severity> {
223    diagnostics.iter().map(|d| d.severity).max()
224}
225
226/// `astrs validate`'s exit code convention (blueprint §17): `0` clean,
227/// `1` warnings only, `2` any error (including a file that never parsed).
228#[must_use]
229pub fn exit_code_for(diagnostics: &[CliDiagnostic]) -> i32 {
230    match max_severity(diagnostics) {
231        None | Some(Severity::Info) => 0,
232        Some(Severity::Warning) => 1,
233        Some(Severity::Error) => 2,
234    }
235}
236
237const RED: &str = "\x1b[31m";
238const YELLOW: &str = "\x1b[33m";
239const CYAN: &str = "\x1b[36m";
240const BOLD: &str = "\x1b[1m";
241const RESET: &str = "\x1b[0m";
242
243fn severity_color(severity: Severity) -> &'static str {
244    match severity {
245        Severity::Error => RED,
246        Severity::Warning => YELLOW,
247        Severity::Info => CYAN,
248    }
249}
250
251/// Render one diagnostic as a single human-readable line: `[severity]
252/// (source) path: message`, with the severity tag and source both
253/// wrapped in plain ANSI SGR codes when `use_color` is set (no `path`
254/// segment when the diagnostic has none).
255#[must_use]
256pub fn render_line(diagnostic: &CliDiagnostic, use_color: bool) -> String {
257    let severity_str = diagnostic.severity.to_string();
258    let tag = if use_color {
259        format!(
260            "{BOLD}{}[{severity_str}]{RESET}",
261            severity_color(diagnostic.severity)
262        )
263    } else {
264        format!("[{severity_str}]")
265    };
266    let mut line = format!("{tag} ({}) ", diagnostic.source);
267    if let Some(path) = &diagnostic.path {
268        line.push_str(path);
269        line.push_str(": ");
270    }
271    line.push_str(&diagnostic.message);
272    line
273}
274
275/// Render every diagnostic, one per line, in list order.
276#[must_use]
277pub fn render_human(diagnostics: &[CliDiagnostic], use_color: bool) -> String {
278    diagnostics
279        .iter()
280        .map(|d| render_line(d, use_color))
281        .collect::<Vec<_>>()
282        .join("\n")
283}
284
285#[cfg(test)]
286mod tests {
287    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
288    use super::*;
289
290    #[test]
291    fn max_severity_is_none_for_an_empty_list() {
292        assert_eq!(max_severity(&[]), None);
293        assert_eq!(exit_code_for(&[]), 0);
294    }
295
296    #[test]
297    fn exit_code_reflects_the_worst_severity() {
298        let info = vec![CliDiagnostic {
299            severity: Severity::Info,
300            source: Source::Graph,
301            path: None,
302            message: "m".to_string(),
303        }];
304        assert_eq!(exit_code_for(&info), 0);
305
306        let warning = vec![CliDiagnostic {
307            severity: Severity::Warning,
308            source: Source::Graph,
309            path: None,
310            message: "m".to_string(),
311        }];
312        assert_eq!(exit_code_for(&warning), 1);
313
314        let error = vec![CliDiagnostic {
315            severity: Severity::Error,
316            source: Source::Io,
317            path: None,
318            message: "m".to_string(),
319        }];
320        assert_eq!(exit_code_for(&error), 2);
321    }
322
323    #[test]
324    fn exit_code_takes_the_worst_across_a_mixed_list() {
325        let mixed = vec![
326            CliDiagnostic {
327                severity: Severity::Info,
328                source: Source::Graph,
329                path: None,
330                message: "info".to_string(),
331            },
332            CliDiagnostic {
333                severity: Severity::Warning,
334                source: Source::Graph,
335                path: None,
336                message: "warning".to_string(),
337            },
338        ];
339        assert_eq!(exit_code_for(&mixed), 1);
340    }
341
342    #[test]
343    fn render_line_without_color_has_no_escape_codes() {
344        let d = CliDiagnostic::io("cannot read file");
345        let line = render_line(&d, false);
346        assert!(!line.contains('\x1b'));
347        assert!(line.contains("[error]"));
348        assert!(line.contains("(io)"));
349        assert!(line.contains("cannot read file"));
350    }
351
352    #[test]
353    fn render_line_with_color_wraps_the_severity_tag() {
354        let d = CliDiagnostic::io("cannot read file");
355        let line = render_line(&d, true);
356        assert!(line.contains('\x1b'));
357        assert!(line.contains(RESET));
358    }
359
360    #[test]
361    fn render_line_includes_path_when_present() {
362        let d = CliDiagnostic {
363            severity: Severity::Error,
364            source: Source::Structural,
365            path: Some("nodes[2].id".to_string()),
366            message: "bad".to_string(),
367        };
368        let line = render_line(&d, false);
369        assert!(line.contains("nodes[2].id: bad"));
370    }
371
372    #[test]
373    fn structural_diagnostic_carries_the_validation_error_path() {
374        let err = astrs_manifest::ValidationError {
375            path: "nodes[0].id".to_string(),
376            kind: astrs_manifest::ValidationErrorKind::InvalidIdCharset {
377                id: "bad id".to_string(),
378            },
379        };
380        let d = CliDiagnostic::structural(&err);
381        assert_eq!(d.path.as_deref(), Some("nodes[0].id"));
382        assert_eq!(d.severity, Severity::Error);
383    }
384
385    #[test]
386    fn parse_diagnostic_captures_line_and_column_when_available() {
387        let err = astrs_manifest::Manifest::from_yaml_str("nodes: [").unwrap_err();
388        let d = CliDiagnostic::parse(&err);
389        assert!(d.path.is_some(), "path was: {:?}", d.path);
390    }
391
392    #[test]
393    fn graph_diagnostic_preserves_its_severity() {
394        let diag = astrs_graph::Diagnostic::new(
395            Severity::Warning,
396            astrs_graph::DiagnosticKind::UnconsumedOutput {
397                node: astrs_graph::NodeId::new("camera"),
398                output: astrs_graph::PortName::new("frames"),
399            },
400        );
401        let d = CliDiagnostic::graph(&diag);
402        assert_eq!(d.severity, Severity::Warning);
403        assert!(d.message.contains("camera"));
404    }
405
406    #[test]
407    fn prove_unavailable_points_at_the_rebuild() {
408        let d = CliDiagnostic::prove_unavailable();
409        assert_eq!(d.severity, Severity::Warning);
410        assert_eq!(d.source, Source::Prove);
411        assert!(d.message.contains("--features verify"), "{}", d.message);
412    }
413
414    #[test]
415    fn prove_violation_is_an_error_naming_both_halves() {
416        let d = CliDiagnostic::prove_violation("deadlock freedom", "`a` can never fire");
417        assert_eq!(d.severity, Severity::Error);
418        assert_eq!(d.source, Source::Prove);
419        assert!(d.message.contains("deadlock freedom"));
420        assert!(d.message.contains("can never fire"));
421    }
422
423    #[test]
424    fn prove_incomplete_is_a_warning_counting_both_gaps() {
425        let d = CliDiagnostic::prove_incomplete(2, 1);
426        assert_eq!(d.severity, Severity::Warning);
427        assert!(d.message.contains('2') && d.message.contains('1'));
428    }
429
430    #[test]
431    fn prove_error_is_an_error() {
432        let d = CliDiagnostic::prove_error("profile is inconsistent");
433        assert_eq!(d.severity, Severity::Error);
434        assert_eq!(d.source, Source::Prove);
435    }
436
437    #[test]
438    fn json_serialization_omits_absent_path() {
439        let d = CliDiagnostic::io("nope");
440        let json = serde_json::to_string(&d).unwrap();
441        assert!(!json.contains("\"path\""));
442        assert!(json.contains("\"severity\":\"error\""));
443    }
444
445    #[test]
446    fn json_serialization_includes_present_path() {
447        let d = CliDiagnostic {
448            severity: Severity::Error,
449            source: Source::Structural,
450            path: Some("nodes[0]".to_string()),
451            message: "m".to_string(),
452        };
453        let json = serde_json::to_string(&d).unwrap();
454        assert!(json.contains("\"path\":\"nodes[0]\""));
455    }
456}