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
//! One diagnosis from text to report, for a pack that brings the document kind's schema,
//! advisors and judge.

use crate::advise::{self, Advisor};
use crate::diagnostic::{Collector, Diagnostic, Edit, Fix};
use crate::fix;
use crate::path::Path;
use crate::read;
use crate::report::{Options, Report};
use crate::schema::Schema;
use crate::shape::{self, CheckOptions, Finding};
use crate::tree::Node;
use crate::write::{self, Placement};

/// What a document kind brings to a diagnosis.
pub trait Pack {
    /// The document kind and root name of its paths: `project`, `spec`, `template`.
    fn document(&self) -> &str;

    /// The schema the tree is walked against.
    fn schema(&self) -> Option<&Schema>;

    /// Advisors run before the generic ones.
    fn advisors(&self) -> Vec<&dyn Advisor> {
        Vec::new()
    }

    /// A refusal before the text is read, such as a size limit; the report holds it alone.
    fn refuse(&self, text: &str) -> Option<Diagnostic> {
        let _ = text;
        None
    }

    /// A refusal after the text is read, such as a version this build does not read; the walk
    /// and the judge are then skipped.
    fn refuse_tree(&self, tree: &Node, root: &Path) -> Option<Diagnostic> {
        let _ = (tree, root);
        None
    }

    /// Runs the engine's own parser and checks on the written tree, adds what the engine says
    /// and the walk did not, and answers the engine's verdict.
    fn judge(&self, judged: &Judged<'_>, out: &mut Vec<Finding>) -> bool;
}

/// What a judge is handed.
pub struct Judged<'a> {
    /// The document as read and recovered.
    pub tree: &'a Node,
    /// The tree written as compact JSON, for the engine's parser.
    pub written: &'a str,
    /// Maps places in `written` back to paths.
    pub placement: &'a Placement<'a>,
    /// What the reader and the walker found.
    pub found: &'a [Finding],
    /// Containers the reader closed early.
    pub incomplete: &'a [Path],
    /// The root of the document's paths.
    pub root: &'a Path,
}

impl Judged<'_> {
    /// Whether an engine refusal at `path` is already told: an error found at, inside or
    /// around it, or a container cut short around it.
    #[must_use]
    pub fn covered(&self, path: &Path) -> bool {
        self.found.iter().any(|finding| {
            finding.diagnostic.is_error()
                && (finding.diagnostic.path.starts_with(path)
                    || path.starts_with(&finding.diagnostic.path))
        }) || self.incomplete.iter().any(|cut| path.starts_with(cut))
    }
}

struct Pass {
    diagnostics: Vec<Diagnostic>,
    tree: Option<Node>,
    valid: bool,
}

fn analyze(pack: &dyn Pack, text: &str) -> Pass {
    let root = Path::root(pack.document());
    if let Some(refusal) = pack.refuse(text) {
        return Pass {
            diagnostics: vec![refusal],
            tree: None,
            valid: false,
        };
    }
    let read = read::json(text, &root);
    let mut findings: Vec<Finding> = read.diagnostics.into_iter().map(Finding::bare).collect();
    let Some(tree) = read.tree else {
        return Pass {
            diagnostics: findings
                .into_iter()
                .map(|finding| finding.diagnostic)
                .collect(),
            tree: None,
            valid: false,
        };
    };
    let recovered = !findings.is_empty();
    if let Some(refusal) = pack.refuse_tree(&tree, &root) {
        findings.push(Finding::bare(refusal));
        return Pass {
            diagnostics: findings
                .into_iter()
                .map(|finding| finding.diagnostic)
                .collect(),
            tree: Some(tree),
            valid: false,
        };
    }
    let schema = pack.schema();
    if let Some(schema) = schema {
        let options = CheckOptions {
            incomplete: &read.incomplete,
            ..CheckOptions::default()
        };
        findings.extend(shape::check(schema, &tree, &root, &options));
    }
    let (written, placement) = write::json(&tree, &root);
    let mut judged_findings = Vec::new();
    let accepted = pack.judge(
        &Judged {
            tree: &tree,
            written: &written,
            placement: &placement,
            found: &findings,
            incomplete: &read.incomplete,
            root: &root,
        },
        &mut judged_findings,
    );
    findings.extend(judged_findings);
    let advisors = pack.advisors();
    let diagnostics = advise::run(findings, schema, &tree, &advisors);
    Pass {
        diagnostics,
        tree: Some(tree),
        valid: accepted && !recovered,
    }
}

/// Diagnoses `text` as the pack's document kind.
#[must_use]
pub fn diagnose(pack: &dyn Pack, text: &str, options: &Options) -> Report {
    if !options.fix {
        let pass = analyze(pack, text);
        return assemble(pack, pass, text, options);
    }
    let mut current = text.to_owned();
    let mut applied: Vec<Fix> = Vec::new();
    let mut pass = analyze(pack, &current);
    for _ in 0..MAX_FIX_ROUNDS {
        let Some((next, done)) = fix_round(&current, &pass) else {
            break;
        };
        applied.extend(done);
        current = next;
        pass = analyze(pack, &current);
    }
    let mut report = assemble(pack, pass, &current, options);
    report.fixed = Some(current);
    report.applied = applied;
    if options.text {
        report.text = Some(crate::render::text(&report));
    }
    report
}

const MAX_FIX_ROUNDS: usize = 4;

fn fix_round(current: &str, pass: &Pass) -> Option<(String, Vec<Fix>)> {
    let certain: Vec<Fix> = fix::certain(&pass.diagnostics).cloned().collect();
    if certain.is_empty() {
        return None;
    }
    let (text_fixes, path_fixes): (Vec<Fix>, Vec<Fix>) = certain.into_iter().partition(|fix| {
        fix.edits
            .iter()
            .all(|edit| matches!(edit, Edit::Text { .. }))
    });
    let tree = pass.tree.as_ref();
    let chosen = tree.map_or_else(Vec::new, |tree| fix::apply(tree, &path_fixes).applied);
    if let Some(path_edits) = tree.and_then(|tree| fix::as_text_edits(tree, &chosen)) {
        let edits: Vec<&Edit> = text_fixes
            .iter()
            .flat_map(|fix| &fix.edits)
            .chain(&path_edits)
            .collect();
        if let Ok(next) = fix::apply_text(current, edits) {
            let done: Vec<Fix> = text_fixes.into_iter().chain(chosen).collect();
            return (next != current && !done.is_empty()).then_some((next, done));
        }
    }
    if !text_fixes.is_empty() {
        let mut next = current.to_owned();
        let mut done = Vec::new();
        let mut taken: Vec<&Edit> = Vec::new();
        for fix in &text_fixes {
            let trial: Vec<&Edit> = taken.iter().copied().chain(&fix.edits).collect();
            if let Ok(text) = fix::apply_text(current, trial.iter().copied()) {
                next = text;
                taken = trial;
                done.push(fix.clone());
            }
        }
        return (!done.is_empty()).then_some((next, done));
    }
    let tree = tree?;
    let result = fix::apply(tree, &path_fixes);
    if result.applied.is_empty() {
        return None;
    }
    Some((write::json_pretty(&result.tree), result.applied))
}

fn assemble(pack: &dyn Pack, pass: Pass, text: &str, options: &Options) -> Report {
    let mut collected = Collector::default();
    collected.extend(pass.diagnostics);
    Report::assemble(pack.document(), pass.valid, collected, Some(text), options)
}