Skip to main content

alpha2_diagnose/
report.rs

1//! The answer for one document: its verdict and its diagnostics, ordered, grouped and capped.
2
3use serde::{Deserialize, Serialize};
4
5use crate::diagnostic::{Collector, Diagnostic, Fix, Severity};
6use crate::render;
7
8/// What a caller asks of a diagnosis, on every surface.
9#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
10#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
11#[serde(default, deny_unknown_fields)]
12pub struct Options {
13    /// Apply every certain fix and answer for the fixed document, with it in `fixed`.
14    pub fix: bool,
15    /// Add the plain-text rendering as `text`.
16    pub text: bool,
17    /// Add to each diagnostic the text of the value it is about, at most 400 bytes.
18    pub excerpt: bool,
19    /// The most diagnostics answered; the rest are counted in `omitted`. Default 50.
20    pub limit: usize,
21}
22
23impl Default for Options {
24    fn default() -> Self {
25        Self {
26            fix: false,
27            text: false,
28            excerpt: false,
29            limit: DEFAULT_LIMIT,
30        }
31    }
32}
33
34/// The most diagnostics a report answers unless asked otherwise.
35pub const DEFAULT_LIMIT: usize = 50;
36
37/// The most bytes of an excerpt.
38pub const MAX_EXCERPT_BYTES: usize = 400;
39
40/// The most other places a grouped diagnostic lists.
41pub const MAX_ALSO: usize = 3;
42
43/// The answer for one document.
44#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
45#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
46pub struct Report {
47    /// The document kind: `project`, `spec`, `template`, ...
48    pub document: String,
49    /// The engine's verdict; false whenever the reader had to recover.
50    pub valid: bool,
51    /// The problems, by place in the text, errors first at one place.
52    pub diagnostics: Vec<Diagnostic>,
53    /// How many diagnostics are not answered (past the limit or the collector's capacity).
54    pub omitted: usize,
55    /// The plain-text rendering, when asked for.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub text: Option<String>,
58    /// The document with every certain fix applied, when asked for; the report is then of it.
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub fixed: Option<String>,
61    /// The fixes applied to make `fixed`.
62    #[serde(default, skip_serializing_if = "Vec::is_empty")]
63    pub applied: Vec<Fix>,
64}
65
66/// Where the JSON Schema of a [`Report`] is published.
67pub const REPORT_SCHEMA_ID: &str = "https://alpha2.sh/schema/diagnostics.v1.json";
68
69/// The JSON Schema (draft 2020-12) of a [`Report`] as every surface answers it.
70#[cfg(feature = "schema")]
71#[must_use]
72pub fn report_json_schema() -> schemars::Schema {
73    let mut schema = schemars::generate::SchemaSettings::draft2020_12()
74        .for_serialize()
75        .into_generator()
76        .into_root_schema_for::<Report>();
77    schema.insert("$id".to_owned(), REPORT_SCHEMA_ID.into());
78    schema.insert("title".to_owned(), "alpha2 diagnostics report".into());
79    schema
80}
81
82/// Counts by severity, grouped diagnostics counted by their places.
83#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
84pub struct Counts {
85    /// Errors.
86    pub errors: usize,
87    /// Warnings.
88    pub warnings: usize,
89    /// Hints.
90    pub hints: usize,
91}
92
93impl Report {
94    /// Orders, groups, caps and renders what was collected. `source` is the text the
95    /// document was read from, for excerpts.
96    #[must_use]
97    pub fn assemble(
98        document: &str,
99        valid: bool,
100        collected: Collector,
101        source: Option<&str>,
102        options: &Options,
103    ) -> Self {
104        let (mut diagnostics, dropped) = collected.into_parts();
105        order(&mut diagnostics);
106        let mut diagnostics = group(diagnostics);
107        let omitted = dropped + diagnostics.len().saturating_sub(options.limit);
108        diagnostics.truncate(options.limit);
109        if options.excerpt
110            && let Some(source) = source
111        {
112            for diagnostic in &mut diagnostics {
113                diagnostic.excerpt = diagnostic.span.and_then(|span| excerpt(source, span));
114            }
115        }
116        let mut report = Self {
117            document: document.to_owned(),
118            valid,
119            diagnostics,
120            omitted,
121            text: None,
122            fixed: None,
123            applied: Vec::new(),
124        };
125        if options.text {
126            report.text = Some(render::text(&report));
127        }
128        report
129    }
130
131    /// Counts by severity.
132    #[must_use]
133    pub fn counts(&self) -> Counts {
134        let mut counts = Counts::default();
135        for diagnostic in &self.diagnostics {
136            let slot = match diagnostic.severity {
137                Severity::Error => &mut counts.errors,
138                Severity::Warning => &mut counts.warnings,
139                Severity::Hint => &mut counts.hints,
140            };
141            *slot += diagnostic.count;
142        }
143        counts
144    }
145
146    /// Whether any diagnostic is an error.
147    #[must_use]
148    pub fn has_errors(&self) -> bool {
149        self.diagnostics.iter().any(Diagnostic::is_error)
150    }
151}
152
153/// Sorts by place in the text, errors before warnings at one place; diagnostics without a
154/// place keep their order after those with one.
155pub fn order(diagnostics: &mut [Diagnostic]) {
156    diagnostics.sort_by_key(|diagnostic| {
157        (
158            diagnostic.span.map_or(usize::MAX, |span| span.offset),
159            diagnostic.severity,
160        )
161    });
162}
163
164/// Merges diagnostics with one code, one message once indexes are removed and one path once
165/// indexes are starred; the first keeps the others as `count` and `also`.
166#[must_use]
167pub fn group(diagnostics: Vec<Diagnostic>) -> Vec<Diagnostic> {
168    let mut groups: Vec<Diagnostic> = Vec::with_capacity(diagnostics.len());
169    let mut keys: std::collections::HashMap<(String, String, String), usize> =
170        std::collections::HashMap::new();
171    for diagnostic in diagnostics {
172        let key = (
173            diagnostic.code.clone(),
174            without_indexes(&diagnostic.message),
175            diagnostic.path.starred(),
176        );
177        if let Some(&index) = keys.get(&key) {
178            let first = &mut groups[index];
179            first.count += diagnostic.count;
180            for path in std::iter::once(diagnostic.path).chain(diagnostic.also) {
181                if first.also.len() < MAX_ALSO {
182                    first.also.push(path);
183                }
184            }
185        } else {
186            keys.insert(key, groups.len());
187            groups.push(diagnostic);
188        }
189    }
190    groups
191}
192
193fn without_indexes(message: &str) -> String {
194    let mut out = String::with_capacity(message.len());
195    let mut chars = message.chars().peekable();
196    while let Some(char) = chars.next() {
197        out.push(char);
198        if char == '[' && chars.peek().is_some_and(char::is_ascii_digit) {
199            while chars.peek().is_some_and(char::is_ascii_digit) {
200                chars.next();
201            }
202            out.push('*');
203        }
204    }
205    out
206}
207
208/// The text of `span`, cut at a character boundary to [`MAX_EXCERPT_BYTES`].
209#[must_use]
210pub fn excerpt(source: &str, span: crate::tree::Span) -> Option<String> {
211    let text = source.get(span.offset..span.end())?;
212    if text.len() <= MAX_EXCERPT_BYTES {
213        return Some(text.to_owned());
214    }
215    let mut end = MAX_EXCERPT_BYTES;
216    while !text.is_char_boundary(end) {
217        end -= 1;
218    }
219    Some(text[..end].to_owned())
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225    use crate::codes::{SHAPE_MISSING_FIELD, SHAPE_UNKNOWN_FIELD};
226    use crate::path::Path;
227    use crate::tree::Span;
228
229    fn span(offset: usize) -> Span {
230        Span {
231            offset,
232            length: 1,
233            line: 1,
234            column: u32::try_from(offset + 1).unwrap(),
235        }
236    }
237
238    #[test]
239    fn orders_by_place_then_severity() {
240        let root = Path::root("doc");
241        let mut collected = Collector::default();
242        collected.push(Diagnostic::new(&SHAPE_UNKNOWN_FIELD, root.key("b"), "b").at(Some(span(9))));
243        collected.push(Diagnostic::new(
244            &SHAPE_UNKNOWN_FIELD,
245            root.key("none"),
246            "none",
247        ));
248        collected.push(Diagnostic::new(&SHAPE_UNKNOWN_FIELD, root.key("a"), "a").at(Some(span(2))));
249        let report = Report::assemble("doc", false, collected, None, &Options::default());
250        let paths: Vec<String> = report
251            .diagnostics
252            .iter()
253            .map(|diagnostic| diagnostic.path.to_string())
254            .collect();
255        assert_eq!(paths, ["doc.a", "doc.b", "doc.none"]);
256    }
257
258    #[test]
259    fn groups_one_problem_over_a_list_and_caps() {
260        let root = Path::root("doc");
261        let mut collected = Collector::new(6);
262        for index in 0..8 {
263            collected.push(
264                Diagnostic::new(
265                    &SHAPE_MISSING_FIELD,
266                    root.key("items").index(index),
267                    format!("items[{index}] lacks id"),
268                )
269                .at(Some(span(index * 10))),
270            );
271        }
272        let options = Options {
273            limit: 1,
274            ..Options::default()
275        };
276        let report = Report::assemble("doc", false, collected, None, &options);
277        assert_eq!(report.diagnostics.len(), 1);
278        assert_eq!(report.diagnostics[0].count, 6);
279        assert_eq!(report.diagnostics[0].also.len(), MAX_ALSO);
280        assert_eq!(report.omitted, 2);
281        assert_eq!(report.counts().errors, 6);
282    }
283
284    #[test]
285    fn excerpt_cuts_at_a_character_boundary() {
286        let source = "\u{e9}".repeat(300);
287        let span = Span {
288            offset: 0,
289            length: source.len(),
290            line: 1,
291            column: 1,
292        };
293        let cut = excerpt(&source, span).unwrap();
294        assert_eq!(cut.len(), MAX_EXCERPT_BYTES);
295    }
296}