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
//! Applying fixes: text edits to the text, path edits to the tree.

use crate::diagnostic::{Applicability, Diagnostic, Edit, Fix};
use crate::path::{Path, Segment};
use crate::tree::{Entry, Node, Value};

/// Two edits that change one place.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Overlap {
    /// Byte offset where the edits meet.
    pub offset: usize,
}

/// `text` with the text edits applied; other edits are ignored.
///
/// # Errors
/// [`Overlap`] when two edits change overlapping bytes, or an edit lies outside the text or
/// splits a character.
pub fn apply_text<'e>(
    text: &str,
    edits: impl IntoIterator<Item = &'e Edit>,
) -> Result<String, Overlap> {
    let mut spans: Vec<(usize, usize, &str)> = edits
        .into_iter()
        .filter_map(|edit| match edit {
            Edit::Text {
                offset,
                length,
                replacement,
            } => Some((*offset, *length, replacement.as_str())),
            _ => None,
        })
        .collect();
    spans.sort_by_key(|&(offset, length, _)| (offset, length));
    for pair in spans.windows(2) {
        let (offset, length, _) = pair[0];
        if offset + length > pair[1].0 || (length == 0 && pair[1].1 == 0 && offset == pair[1].0) {
            return Err(Overlap { offset: pair[1].0 });
        }
    }
    let mut out = String::with_capacity(text.len());
    let mut at = 0;
    for (offset, length, replacement) in spans {
        let end = offset + length;
        if end > text.len() || !text.is_char_boundary(offset) || !text.is_char_boundary(end) {
            return Err(Overlap { offset });
        }
        out.push_str(&text[at..offset]);
        out.push_str(replacement);
        at = end;
    }
    out.push_str(&text[at..]);
    Ok(out)
}

/// The certain fixes of `diagnostics`, in order.
pub fn certain(diagnostics: &[Diagnostic]) -> impl Iterator<Item = &Fix> {
    diagnostics
        .iter()
        .flat_map(|diagnostic| &diagnostic.fixes)
        .filter(|fix| fix.applicability == Applicability::Certain)
}

/// What [`apply`] did.
#[derive(Clone, Debug)]
pub struct Applied {
    /// The tree with the fixes applied.
    pub tree: Node,
    /// The fixes applied.
    pub applied: Vec<Fix>,
    /// The certain fixes not applied: two on one place, or one whose place is gone.
    pub skipped: Vec<Fix>,
}

fn paths(fix: &Fix) -> impl Iterator<Item = &Path> {
    fix.edits.iter().flat_map(|edit| match edit {
        Edit::Move { from, to } => vec![from, to],
        other => other.path().into_iter().collect(),
    })
}

fn overlaps(a: &Fix, b: &Fix) -> bool {
    paths(a).any(|left| paths(b).any(|right| left.starts_with(right) || right.starts_with(left)))
}

fn order_key(fix: &Fix) -> Vec<std::cmp::Reverse<SortSegment>> {
    paths(fix)
        .next()
        .map(|path| {
            path.segments()
                .iter()
                .map(|segment| {
                    std::cmp::Reverse(match segment {
                        Segment::Key(key) => SortSegment::Key(key.clone()),
                        Segment::Index(index) => SortSegment::Index(*index),
                    })
                })
                .collect()
        })
        .unwrap_or_default()
}

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
enum SortSegment {
    Index(usize),
    Key(String),
}

/// Applies the certain path fixes to a copy of `tree`; two fixes on one place are both skipped.
/// Text edits are the reader's and already in the tree it read.
#[must_use]
pub fn apply(tree: &Node, fixes: &[Fix]) -> Applied {
    let certain: Vec<&Fix> = fixes
        .iter()
        .filter(|fix| fix.applicability == Applicability::Certain)
        .collect();
    let mut skipped = Vec::new();
    let mut chosen: Vec<&Fix> = Vec::new();
    for (index, fix) in certain.iter().enumerate() {
        let path_edits = fix.edits.iter().any(|edit| edit.path().is_some());
        let clash = certain
            .iter()
            .enumerate()
            .any(|(other, candidate)| other != index && path_edits && overlaps(fix, candidate));
        if clash {
            skipped.push((*fix).clone());
        } else {
            chosen.push(fix);
        }
    }
    chosen.sort_by(|a, b| {
        let (a, b) = (order_key(a), order_key(b));
        b.len().cmp(&a.len()).then_with(|| a.cmp(&b))
    });
    let mut tree = tree.clone();
    let mut applied = Vec::new();
    for fix in chosen {
        let mut trial = tree.clone();
        if fix.edits.iter().all(|edit| apply_edit(&mut trial, edit)) {
            tree = trial;
            applied.push(fix.clone());
        } else {
            skipped.push(fix.clone());
        }
    }
    Applied {
        tree,
        applied,
        skipped,
    }
}

fn parent_and_last<'t>(tree: &'t mut Node, path: &Path) -> Option<(&'t mut Node, Segment)> {
    let mut parent = path.clone();
    let last = parent.pop()?;
    Some((tree.at_mut(&parent)?, last))
}

fn take(tree: &mut Node, path: &Path) -> Option<Node> {
    let (parent, last) = parent_and_last(tree, path)?;
    match (&mut parent.value, last) {
        (Value::Map(entries), Segment::Key(key)) => {
            let index = entries.iter().rposition(|entry| entry.key == key)?;
            Some(entries.remove(index).value)
        }
        (Value::List(items), Segment::Index(index)) if index < items.len() => {
            Some(items.remove(index))
        }
        _ => None,
    }
}

fn put(tree: &mut Node, path: &Path, value: Node) -> bool {
    let Some((parent, last)) = parent_and_last(tree, path) else {
        return false;
    };
    match (&mut parent.value, last) {
        (Value::Map(entries), Segment::Key(key)) => {
            if entries.iter().any(|entry| entry.key == key) {
                return false;
            }
            entries.push(Entry {
                key,
                key_span: None,
                value,
            });
            true
        }
        (Value::List(items), Segment::Index(index)) if index <= items.len() => {
            items.insert(index, value);
            true
        }
        _ => false,
    }
}

fn apply_edit(tree: &mut Node, edit: &Edit) -> bool {
    match edit {
        Edit::Text { .. } => true,
        Edit::Replace { path, value } => tree.at_mut(path).is_some_and(|node| {
            *node = value.clone();
            true
        }),
        Edit::RenameKey { path, to } => {
            let Some((parent, Segment::Key(key))) = parent_and_last(tree, path) else {
                return false;
            };
            let Value::Map(entries) = &mut parent.value else {
                return false;
            };
            if entries.iter().any(|entry| entry.key == *to) {
                return false;
            }
            let Some(entry) = entries.iter_mut().rev().find(|entry| entry.key == key) else {
                return false;
            };
            entry.key.clone_from(to);
            entry.key_span = None;
            true
        }
        Edit::Remove { path } => take(tree, path).is_some(),
        Edit::Insert { path, value } => put(tree, path, value.clone()),
        Edit::Move { from, to } => take(tree, from).is_some_and(|value| put(tree, to, value)),
    }
}

/// The text edits that make `fixes` in `source`, keeping its layout, when every edit is a
/// rename or a replacement of a value read from it; `None` otherwise.
#[must_use]
pub fn as_text_edits(tree: &Node, fixes: &[Fix]) -> Option<Vec<Edit>> {
    let mut edits = Vec::new();
    for fix in fixes {
        for edit in &fix.edits {
            match edit {
                Edit::Text { .. } => edits.push(edit.clone()),
                Edit::Replace { path, value } => {
                    let span = tree.at(path)?.span?;
                    edits.push(Edit::Text {
                        offset: span.offset,
                        length: span.length,
                        replacement: crate::write::json(value, path).0,
                    });
                }
                Edit::RenameKey { path, to } => {
                    let parent = tree.at(&path.parent()?)?;
                    let span = parent.entry(path.last_key()?)?.key_span?;
                    edits.push(Edit::Text {
                        offset: span.offset,
                        length: span.length,
                        replacement: crate::write::quote(to),
                    });
                }
                _ => return None,
            }
        }
    }
    Some(edits)
}