silcrow 0.2.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
use super::*;

/// The marker lines of a corpus file, 1-based: each comment line naming `pin` or a `§` marker
/// other than an end, or the first line when there is none.
fn corpus_markers(text: &str) -> Vec<usize> {
    let found: Vec<usize> = text
        .lines()
        .enumerate()
        .filter(|(_, line)| {
            let t = line.trim_start();
            let comment = ["//", "#", "<!--", "/*", "{/*", "--"]
                .iter()
                .any(|c| t.starts_with(c));
            comment && (t.contains("pin") || (t.contains("§ ") && !t.contains("§ end")))
        })
        .map(|(i, _)| i + 1)
        .collect();
    if found.is_empty() {
        vec![1]
    } else {
        found
    }
}

/// The shape of the span at each of `lines`, `None` where the file does not parse clean or the
/// line holds no span.
fn corpus_shapes(path: &str, text: &str, lines: &[usize]) -> Vec<Option<String>> {
    let path = std::path::Path::new(path);
    let Some(lang) = lang_for_path(path) else {
        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
        return lines
            .iter()
            .map(|&line| Some(crate::fallback::mint(ext, text, line, usize::MAX, &[])))
            .collect();
    };
    let tree = parse(lang, text).filter(|tree| !tree.root_node().has_error());
    lines
        .iter()
        .map(|&line| {
            let tree = tree.as_ref()?;
            let extent = span_range(lang, text, tree, line)?;
            Some(pin_shape(lang, text, tree, extent, &[], &|_| None))
        })
        .collect()
}

/// Measures, on pairs of a file and its formatted copy listed in `SX_FMT_PAIRS`, the shape of
/// every span and the import line texts of the file before and after, and writes one row per
/// span and one per file to `SX_FMT_REPORT`. Ignored: the formatters run outside the suite.
#[test]
#[ignore]
fn formatter_corpus() {
    let pairs = std::fs::read_to_string(std::env::var("SX_FMT_PAIRS").unwrap()).unwrap();
    let mut rows = String::new();
    for pair in pairs.lines() {
        let (before, after) = pair.split_once('\t').unwrap();
        let a = std::fs::read_to_string(before).unwrap();
        let b = std::fs::read_to_string(after).unwrap();
        let (ma, mb) = (corpus_markers(&a), corpus_markers(&b));
        if ma.len() != mb.len() {
            rows.push_str(&format!(
                "{before}\t{after}\t-\t-\tMARKERS\t{}\t{}\n",
                ma.len(),
                mb.len()
            ));
            continue;
        }
        let clean = |lang: &LangSpec, text: &str| {
            parse(lang, text).is_some_and(|t| !t.root_node().has_error())
        };
        let lang = lang_for_path(std::path::Path::new(before));
        if let Some(lang) = lang.filter(|lang| clean(lang, &a) && clean(lang, &b)) {
            let texts = |text: &str| {
                let mut lines = crate::follow::import_texts(lang, text);
                lines.sort();
                lines
            };
            let (ia, ib) = (texts(&a), texts(&b));
            if !ia.is_empty() {
                let status = if ia == ib { "SAME" } else { "MOVED" };
                rows.push_str(&format!(
                    "{before}\t{after}\timports\timports\t{status}\t{:?}\t{:?}\n",
                    ia.join("\n"),
                    ib.join("\n")
                ));
            }
        }
        let (shapes_a, shapes_b) = (
            corpus_shapes(before, &a, &ma),
            corpus_shapes(after, &b, &mb),
        );
        for (((la, lb), sa), sb) in ma.into_iter().zip(mb).zip(shapes_a).zip(shapes_b) {
            let status = match (&sa, &sb) {
                (None, _) => "SKIP",
                (Some(_), None) => "AFTERFAIL",
                (Some(x), Some(y)) if x == y => "SAME",
                _ => "MOVED",
            };
            rows.push_str(&format!(
                "{before}\t{after}\t{la}\t{lb}\t{status}\t{:?}\t{:?}\n",
                sa.unwrap_or_default(),
                sb.unwrap_or_default()
            ));
        }
    }
    std::fs::write(std::env::var("SX_FMT_REPORT").unwrap(), rows).unwrap();
}