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
//! A tree back to JSON text, and where each value went in it.

use std::fmt::Write as _;

use crate::path::{Path, Segment};
use crate::tree::{Node, NumberKind, Value};

/// A string as a JSON string literal, ASCII only.
#[must_use]
pub fn quote(text: &str) -> String {
    let mut out = String::with_capacity(text.len() + 2);
    push_quoted(&mut out, text, true);
    out
}

fn push_quoted(out: &mut String, text: &str, ascii: bool) {
    out.push('"');
    for char in text.chars() {
        match char {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\u{8}' => out.push_str("\\b"),
            '\u{c}' => out.push_str("\\f"),
            char if u32::from(char) < 0x20 || (ascii && !char.is_ascii()) => {
                let mut units = [0; 2];
                for unit in char.encode_utf16(&mut units) {
                    let _ = write!(out, "\\u{unit:04x}");
                }
            }
            char => out.push(char),
        }
    }
    out.push('"');
}

/// The tree as compact ASCII JSON on one line, numbers by their spelling (a number JSON cannot
/// write as `null`) and repeated keys kept, with the [`Placement`] that maps the text back.
#[must_use]
pub fn json<'a>(tree: &'a Node, root: &Path) -> (String, Placement<'a>) {
    let mut out = String::new();
    write_compact(&mut out, tree, &mut |_, _, _| {});
    (
        out,
        Placement {
            tree,
            root: root.clone(),
        },
    )
}

/// The tree as indented JSON for a person or a model to read; non-ASCII characters kept.
#[must_use]
pub fn json_pretty(tree: &Node) -> String {
    let mut out = String::new();
    write_pretty(&mut out, tree, 0);
    out.push('\n');
    out
}

fn push_number(out: &mut String, node: &Node) {
    if let Value::Number(number) = &node.value {
        if number.kind() == NumberKind::NotFinite {
            out.push_str("null");
        } else {
            out.push_str(number.text());
        }
    }
}

type Visit<'v> = dyn FnMut(Event<'_>, usize, &Node) + 'v;

#[derive(Clone, Copy)]
enum Event<'k> {
    Enter(Option<SegmentRef<'k>>),
    Leave,
}

#[derive(Clone, Copy)]
enum SegmentRef<'k> {
    Key(&'k str),
    Index(usize),
}

fn write_compact(out: &mut String, node: &Node, visit: &mut Visit<'_>) {
    write_compact_at(out, node, None, visit);
}

fn write_compact_at<'k>(
    out: &mut String,
    node: &'k Node,
    segment: Option<SegmentRef<'k>>,
    visit: &mut Visit<'_>,
) {
    visit(Event::Enter(segment), out.len(), node);
    match &node.value {
        Value::Null => out.push_str("null"),
        Value::Bool(value) => out.push_str(if *value { "true" } else { "false" }),
        Value::Number(_) => push_number(out, node),
        Value::Text(text) => push_quoted(out, text, true),
        Value::List(items) => {
            out.push('[');
            for (index, item) in items.iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                write_compact_at(out, item, Some(SegmentRef::Index(index)), visit);
            }
            out.push(']');
        }
        Value::Map(entries) => {
            out.push('{');
            for (index, entry) in entries.iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                visit(
                    Event::Enter(Some(SegmentRef::Key(&entry.key))),
                    out.len(),
                    &entry.value,
                );
                push_quoted(out, &entry.key, true);
                out.push(':');
                write_compact_at(out, &entry.value, None, visit);
                visit(Event::Leave, out.len(), &entry.value);
            }
            out.push('}');
        }
    }
    visit(Event::Leave, out.len(), node);
}

fn write_pretty(out: &mut String, node: &Node, indent: usize) {
    match &node.value {
        Value::List(items) if !items.is_empty() => {
            out.push('[');
            for (index, item) in items.iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                newline(out, indent + 1);
                write_pretty(out, item, indent + 1);
            }
            newline(out, indent);
            out.push(']');
        }
        Value::Map(entries) if !entries.is_empty() => {
            out.push('{');
            for (index, entry) in entries.iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                newline(out, indent + 1);
                push_quoted(out, &entry.key, false);
                out.push_str(": ");
                write_pretty(out, &entry.value, indent + 1);
            }
            newline(out, indent);
            out.push('}');
        }
        Value::List(_) => out.push_str("[]"),
        Value::Map(_) => out.push_str("{}"),
        Value::Text(text) => push_quoted(out, text, false),
        _ => write_compact(out, node, &mut |_, _, _| {}),
    }
}

fn newline(out: &mut String, indent: usize) {
    out.push('\n');
    for _ in 0..indent {
        out.push_str("  ");
    }
}

/// Maps places in the text [`json`] wrote back to paths in the tree, and paths to places.
/// Each query writes the tree again without keeping it, so it costs one pass and no memory.
#[derive(Clone, Debug)]
pub struct Placement<'a> {
    tree: &'a Node,
    root: Path,
}

impl Placement<'_> {
    /// The deepest value whose text holds byte `offset`; an object's key belongs to its entry.
    #[must_use]
    pub fn path_at(&self, offset: usize) -> Path {
        let mut stack: Vec<Option<Segment>> = Vec::new();
        let mut best: Option<Path> = None;
        let mut sink = String::new();
        let mut done = false;
        write_compact(&mut sink, self.tree, &mut |event, at, _| {
            if done {
                return;
            }
            match event {
                Event::Enter(segment) => {
                    if at > offset {
                        done = true;
                        return;
                    }
                    stack.push(segment.map(|segment| match segment {
                        SegmentRef::Key(key) => Segment::Key(key.to_owned()),
                        SegmentRef::Index(index) => Segment::Index(index),
                    }));
                    best = Some(self.root.join(stack.iter().flatten().cloned()));
                }
                Event::Leave => {
                    if at > offset {
                        done = true;
                        return;
                    }
                    stack.pop();
                    best = Some(self.root.join(stack.iter().flatten().cloned()));
                }
            }
        });
        best.unwrap_or_else(|| self.root.clone())
    }

    /// The place of a `serde_json` error position (line and column, both from 1) in the
    /// written text, which is one line.
    #[must_use]
    pub fn path_at_line_column(&self, line: usize, column: usize) -> Path {
        if line > 1 {
            return self.root.clone();
        }
        self.path_at(column.saturating_sub(1))
    }

    /// Where the value at `path` was written: its byte offset and length.
    #[must_use]
    pub fn offset_of(&self, path: &Path) -> Option<(usize, usize)> {
        let wanted = path.segments();
        let mut stack: Vec<Option<Segment>> = Vec::new();
        let mut start = None;
        let mut found = None;
        let mut sink = String::new();
        write_compact(&mut sink, self.tree, &mut |event, at, _| {
            if found.is_some() {
                return;
            }
            match event {
                Event::Enter(segment) => {
                    stack.push(segment.map(|segment| match segment {
                        SegmentRef::Key(key) => Segment::Key(key.to_owned()),
                        SegmentRef::Index(index) => Segment::Index(index),
                    }));
                    if !matches!(segment, Some(SegmentRef::Key(_)))
                        && stack.iter().flatten().eq(wanted.iter())
                    {
                        start = Some((at, stack.len()));
                    }
                }
                Event::Leave => {
                    if let Some((begin, depth)) = start
                        && depth == stack.len()
                    {
                        found = Some((begin, at - begin));
                    }
                    stack.pop();
                }
            }
        });
        found
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::read;

    fn tree(text: &str) -> Node {
        let read = read::json(text, &Path::root("doc"));
        assert!(read.diagnostics.is_empty(), "{:?}", read.diagnostics);
        read.tree.unwrap()
    }

    #[test]
    fn writes_compact_ascii_with_spelling_and_repeats() {
        let node = tree("{ \"a\": 1920.0, \"a\": [1, \"\\u00e9\\n\"], \"b\": {} }");
        let (text, _) = json(&node, &Path::root("doc"));
        assert_eq!(text, "{\"a\":1920.0,\"a\":[1,\"\\u00e9\\n\"],\"b\":{}}");
    }

    #[test]
    fn placement_maps_offsets_to_paths() {
        let node = tree(r#"{"a":{"b":[10,20]},"c":true}"#);
        let root = Path::root("doc");
        let (text, placement) = json(&node, &root);
        let at = |needle: &str| placement.path_at(text.find(needle).unwrap()).to_string();
        assert_eq!(at("20"), "doc.a.b[1]");
        assert_eq!(at("10"), "doc.a.b[0]");
        assert_eq!(at("\"b\""), "doc.a.b");
        assert_eq!(at("true"), "doc.c");
        assert_eq!(placement.path_at(0).to_string(), "doc");
        assert_eq!(placement.path_at(text.len() - 1).to_string(), "doc");
        assert_eq!(
            placement
                .path_at_line_column(1, text.find("20").unwrap() + 2)
                .to_string(),
            "doc.a.b[1]"
        );
        let (offset, length) = placement
            .offset_of(&Path::parse("doc.a.b").unwrap())
            .unwrap();
        assert_eq!(&text[offset..offset + length], "[10,20]");
        assert_eq!(placement.offset_of(&Path::parse("doc.x").unwrap()), None);
    }

    #[test]
    fn pretty_reads_back_to_the_same_tree() {
        let node = tree("{\"a\":[1,{\"b\":null}],\"c\":\"\\u00e9\",\"d\":[],\"e\":{}}");
        let pretty = json_pretty(&node);
        assert!(pretty.contains("\n  \"a\": [\n    1,"));
        assert!(tree(&pretty).same_document(&node));
    }
}