alpha2-diagnose 0.10.0

Format-neutral document diagnostics for alpha2: a document tree, a JSON reader that recovers, a schema walker, advice and fixes.
Documentation
//! The answer for one document: its verdict and its diagnostics, ordered, grouped and capped.

use serde::{Deserialize, Serialize};

use crate::diagnostic::{Collector, Diagnostic, Fix, Severity};
use crate::render;

/// What a caller asks of a diagnosis, on every surface.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(default, deny_unknown_fields)]
pub struct Options {
    /// Apply every certain fix and answer for the fixed document, with it in `fixed`.
    pub fix: bool,
    /// Add the plain-text rendering as `text`.
    pub text: bool,
    /// Add to each diagnostic the text of the value it is about, at most 400 bytes.
    pub excerpt: bool,
    /// The most diagnostics answered; the rest are counted in `omitted`. Default 50.
    pub limit: usize,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            fix: false,
            text: false,
            excerpt: false,
            limit: DEFAULT_LIMIT,
        }
    }
}

/// The most diagnostics a report answers unless asked otherwise.
pub const DEFAULT_LIMIT: usize = 50;

/// The most bytes of an excerpt.
pub const MAX_EXCERPT_BYTES: usize = 400;

/// The most other places a grouped diagnostic lists.
pub const MAX_ALSO: usize = 3;

/// The answer for one document.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Report {
    /// The document kind: `project`, `spec`, `template`, ...
    pub document: String,
    /// The engine's verdict; false whenever the reader had to recover.
    pub valid: bool,
    /// The problems, by place in the text, errors first at one place.
    pub diagnostics: Vec<Diagnostic>,
    /// How many diagnostics are not answered (past the limit or the collector's capacity).
    pub omitted: usize,
    /// The plain-text rendering, when asked for.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// The document with every certain fix applied, when asked for; the report is then of it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fixed: Option<String>,
    /// The fixes applied to make `fixed`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub applied: Vec<Fix>,
}

/// Where the JSON Schema of a [`Report`] is published.
pub const REPORT_SCHEMA_ID: &str = "https://alpha2.sh/schema/diagnostics.v1.json";

/// The JSON Schema (draft 2020-12) of a [`Report`] as every surface answers it.
#[cfg(feature = "schema")]
#[must_use]
pub fn report_json_schema() -> schemars::Schema {
    let mut schema = schemars::generate::SchemaSettings::draft2020_12()
        .for_serialize()
        .into_generator()
        .into_root_schema_for::<Report>();
    schema.insert("$id".to_owned(), REPORT_SCHEMA_ID.into());
    schema.insert("title".to_owned(), "alpha2 diagnostics report".into());
    schema
}

/// Counts by severity, grouped diagnostics counted by their places.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Counts {
    /// Errors.
    pub errors: usize,
    /// Warnings.
    pub warnings: usize,
    /// Hints.
    pub hints: usize,
}

impl Report {
    /// Orders, groups, caps and renders what was collected. `source` is the text the
    /// document was read from, for excerpts.
    #[must_use]
    pub fn assemble(
        document: &str,
        valid: bool,
        collected: Collector,
        source: Option<&str>,
        options: &Options,
    ) -> Self {
        let (mut diagnostics, dropped) = collected.into_parts();
        order(&mut diagnostics);
        let mut diagnostics = group(diagnostics);
        let omitted = dropped + diagnostics.len().saturating_sub(options.limit);
        diagnostics.truncate(options.limit);
        if options.excerpt
            && let Some(source) = source
        {
            for diagnostic in &mut diagnostics {
                diagnostic.excerpt = diagnostic.span.and_then(|span| excerpt(source, span));
            }
        }
        let mut report = Self {
            document: document.to_owned(),
            valid,
            diagnostics,
            omitted,
            text: None,
            fixed: None,
            applied: Vec::new(),
        };
        if options.text {
            report.text = Some(render::text(&report));
        }
        report
    }

    /// Counts by severity.
    #[must_use]
    pub fn counts(&self) -> Counts {
        let mut counts = Counts::default();
        for diagnostic in &self.diagnostics {
            let slot = match diagnostic.severity {
                Severity::Error => &mut counts.errors,
                Severity::Warning => &mut counts.warnings,
                Severity::Hint => &mut counts.hints,
            };
            *slot += diagnostic.count;
        }
        counts
    }

    /// Whether any diagnostic is an error.
    #[must_use]
    pub fn has_errors(&self) -> bool {
        self.diagnostics.iter().any(Diagnostic::is_error)
    }
}

/// Sorts by place in the text, errors before warnings at one place; diagnostics without a
/// place keep their order after those with one.
pub fn order(diagnostics: &mut [Diagnostic]) {
    diagnostics.sort_by_key(|diagnostic| {
        (
            diagnostic.span.map_or(usize::MAX, |span| span.offset),
            diagnostic.severity,
        )
    });
}

/// Merges diagnostics with one code, one message once indexes are removed and one path once
/// indexes are starred; the first keeps the others as `count` and `also`.
#[must_use]
pub fn group(diagnostics: Vec<Diagnostic>) -> Vec<Diagnostic> {
    let mut groups: Vec<Diagnostic> = Vec::with_capacity(diagnostics.len());
    let mut keys: std::collections::HashMap<(String, String, String), usize> =
        std::collections::HashMap::new();
    for diagnostic in diagnostics {
        let key = (
            diagnostic.code.clone(),
            without_indexes(&diagnostic.message),
            diagnostic.path.starred(),
        );
        if let Some(&index) = keys.get(&key) {
            let first = &mut groups[index];
            first.count += diagnostic.count;
            for path in std::iter::once(diagnostic.path).chain(diagnostic.also) {
                if first.also.len() < MAX_ALSO {
                    first.also.push(path);
                }
            }
        } else {
            keys.insert(key, groups.len());
            groups.push(diagnostic);
        }
    }
    groups
}

fn without_indexes(message: &str) -> String {
    let mut out = String::with_capacity(message.len());
    let mut chars = message.chars().peekable();
    while let Some(char) = chars.next() {
        out.push(char);
        if char == '[' && chars.peek().is_some_and(char::is_ascii_digit) {
            while chars.peek().is_some_and(char::is_ascii_digit) {
                chars.next();
            }
            out.push('*');
        }
    }
    out
}

/// The text of `span`, cut at a character boundary to [`MAX_EXCERPT_BYTES`].
#[must_use]
pub fn excerpt(source: &str, span: crate::tree::Span) -> Option<String> {
    let text = source.get(span.offset..span.end())?;
    if text.len() <= MAX_EXCERPT_BYTES {
        return Some(text.to_owned());
    }
    let mut end = MAX_EXCERPT_BYTES;
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    Some(text[..end].to_owned())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::codes::{SHAPE_MISSING_FIELD, SHAPE_UNKNOWN_FIELD};
    use crate::path::Path;
    use crate::tree::Span;

    fn span(offset: usize) -> Span {
        Span {
            offset,
            length: 1,
            line: 1,
            column: u32::try_from(offset + 1).unwrap(),
        }
    }

    #[test]
    fn orders_by_place_then_severity() {
        let root = Path::root("doc");
        let mut collected = Collector::default();
        collected.push(Diagnostic::new(&SHAPE_UNKNOWN_FIELD, root.key("b"), "b").at(Some(span(9))));
        collected.push(Diagnostic::new(
            &SHAPE_UNKNOWN_FIELD,
            root.key("none"),
            "none",
        ));
        collected.push(Diagnostic::new(&SHAPE_UNKNOWN_FIELD, root.key("a"), "a").at(Some(span(2))));
        let report = Report::assemble("doc", false, collected, None, &Options::default());
        let paths: Vec<String> = report
            .diagnostics
            .iter()
            .map(|diagnostic| diagnostic.path.to_string())
            .collect();
        assert_eq!(paths, ["doc.a", "doc.b", "doc.none"]);
    }

    #[test]
    fn groups_one_problem_over_a_list_and_caps() {
        let root = Path::root("doc");
        let mut collected = Collector::new(6);
        for index in 0..8 {
            collected.push(
                Diagnostic::new(
                    &SHAPE_MISSING_FIELD,
                    root.key("items").index(index),
                    format!("items[{index}] lacks id"),
                )
                .at(Some(span(index * 10))),
            );
        }
        let options = Options {
            limit: 1,
            ..Options::default()
        };
        let report = Report::assemble("doc", false, collected, None, &options);
        assert_eq!(report.diagnostics.len(), 1);
        assert_eq!(report.diagnostics[0].count, 6);
        assert_eq!(report.diagnostics[0].also.len(), MAX_ALSO);
        assert_eq!(report.omitted, 2);
        assert_eq!(report.counts().errors, 6);
    }

    #[test]
    fn excerpt_cuts_at_a_character_boundary() {
        let source = "\u{e9}".repeat(300);
        let span = Span {
            offset: 0,
            length: source.len(),
            line: 1,
            column: 1,
        };
        let cut = excerpt(&source, span).unwrap();
        assert_eq!(cut.len(), MAX_EXCERPT_BYTES);
    }
}