silcrow 0.2.1

Deterministic CLI for a citable, checkable graph of laws in a git tree.
use anyhow::{bail, Context, Result};
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use crate::follow::FollowIndex;
use crate::list::{drafts, live_clauses, mark, sign, Draft};
use crate::marker::MarkerAddr;
use crate::model::Law;
use crate::parse::{self, Scan};
use crate::span::{self, CodeFile};
use crate::workspace::{ProjectRef, Workspace};

/// How a pin reads the code asked about: inside its span, in the code before the span that
/// it hashes, in the YAML keys and entries above its span, in an import line of its file that
/// spells a name it calls, or in a body it follows.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Reads {
    Span,
    Before,
    Above,
    Imports,
    Follows,
}

impl Reads {
    fn word(self) -> &'static str {
        match self {
            Reads::Span => "span",
            Reads::Before => "before",
            Reads::Above => "above",
            Reads::Imports => "imports",
            Reads::Follows => "follows",
        }
    }
}

/// A file of the project, or one 1-based line of it, as its byte range.
#[derive(Debug, PartialEq, Eq)]
struct Target {
    rel: PathBuf,
    bytes: (usize, usize),
}

/// A marker whose pin reads a target: its address, its file and 1-based line, and how.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Hit {
    project: Option<String>,
    id: String,
    letter: Option<String>,
    path: PathBuf,
    line: usize,
    reads: Reads,
}

pub fn run(
    ws: &Workspace,
    project: &ProjectRef,
    cwd: &Path,
    paths: &[String],
    json: bool,
) -> Result<()> {
    // ยง k40z0sght@5at5f
    let root = project.dir.as_path();
    let scan = parse::scan_root(root)?;
    let code = CodeFile::read_all(root)?;
    let targets = paths
        .iter()
        .map(|arg| target(root, cwd, arg, &code))
        .collect::<Result<Vec<_>>>()?;
    let follow = FollowIndex::from_files(&code, &crate::policy::TestPaths::at(root)?);
    let hits = hits(&code, &follow, &targets);
    let others = if hits.iter().any(|hit| hit.project.is_some()) {
        ws.law_scans(&project.key)?.scans
    } else {
        BTreeMap::new()
    };
    let laws = group(&scan, &others, hits)?;
    let drafts = note_drafts(&scan, &others, &laws);
    // ยง v0nc7pmm7@1dhst
    if json {
        println!("{}", serde_json::to_string(&to_json(&laws, &drafts))?);
    } else {
        print!("{}", to_text(&laws, &drafts));
    }
    // ยง end v0nc7pmm7
    Ok(())
}

/// Reads `<file>[:<line>]`, the file relative to `cwd`, as a range of a code file of the project.
fn target(root: &Path, cwd: &Path, arg: &str, code: &[CodeFile]) -> Result<Target> {
    // ยง k40z0sght.b@axak1
    let (path, line) = match arg.rsplit_once(':') {
        Some((path, line)) if !path.is_empty() && line.bytes().all(|b| b.is_ascii_digit()) => {
            let line: usize = line
                .parse()
                .with_context(|| format!("`{arg}`: no line {line}"))?;
            (path, Some(line))
        }
        _ => (arg, None),
    };
    let abs = std::fs::canonicalize(cwd.join(path))
        .with_context(|| format!("`{path}` is no file of this tree"))?;
    let root = std::fs::canonicalize(root)?;
    let Ok(rel) = abs.strip_prefix(&root) else {
        bail!("`{path}` is outside the project {}", root.display());
    };
    let Some(file) = code.iter().find(|file| file.rel == rel) else {
        bail!("`{path}` is no file the code walk reads, so no marker governs it");
    };
    let bytes = match line {
        None => (0, file.text.len()),
        Some(line) => line_bytes(&file.text, line).with_context(|| {
            format!(
                "`{arg}`: {} has {} line(s)",
                rel.display(),
                file.text.lines().count()
            )
        })?,
    };
    Ok(Target {
        rel: rel.to_path_buf(),
        bytes,
    })
}

/// The byte range of 1-based `line`, its newline included.
fn line_bytes(text: &str, line: usize) -> Option<(usize, usize)> {
    let mut start = 0;
    for (idx, piece) in text.split_inclusive('\n').enumerate() {
        if idx + 1 == line {
            return Some((start, start + piece.len()));
        }
        start += piece.len();
    }
    None
}

/// Whether `start..end` without `holes` shares a byte with `range`.
fn meets(start: usize, end: usize, holes: &[(usize, usize)], range: (usize, usize)) -> bool {
    let (mut from, to) = (start.max(range.0), end.min(range.1));
    let mut holes = holes.to_vec();
    holes.sort();
    for (hole_start, hole_end) in holes {
        if hole_start > from {
            break;
        }
        from = from.max(hole_end);
    }
    from < to
}

/// Every marker of the project whose pin reads a target, once per marker by the closest way.
fn hits(code: &[CodeFile], follow: &FollowIndex, targets: &[Target]) -> Vec<Hit> {
    // ยง k40z0sght.a@fsjka
    let at = |rel: &Path, start: usize, end: usize, holes: &[(usize, usize)]| {
        targets
            .iter()
            .any(|t| t.rel == rel && meets(start, end, holes, t.bytes))
    };
    let mut out: BTreeMap<(PathBuf, usize, MarkerAddr), Reads> = BTreeMap::new();
    for file in code {
        let markers = file.span_markers();
        for m in &markers {
            let punch = span::punch_of(&markers, m.line);
            let prefix = file.prefix(m.start, m.end);
            let reads = if at(&file.rel, m.start, m.end, &punch) {
                Some(Reads::Span)
            } else if prefix
                .iter()
                .any(|(start, end, holes)| at(&file.rel, *start, *end, holes))
            {
                Some(Reads::Before)
            } else if file
                .above(m.start, m.end)
                .iter()
                .any(|(start, end, holes)| at(&file.rel, *start, *end, holes))
            {
                Some(Reads::Above)
            } else if follow
                .pin_import_bytes(&file.rel, m.start, m.end, &punch, &prefix)
                .iter()
                .any(|&(start, end)| at(&file.rel, start, end, &[]))
            {
                Some(Reads::Imports)
            } else {
                follow
                    .followed_callees(&file.rel, m.start, m.end, &punch, &prefix)
                    .iter()
                    .any(|c| at(&c.path, c.start, c.end, &[]))
                    .then_some(Reads::Follows)
            };
            if let Some(reads) = reads {
                let mut addr = m.addr.clone();
                addr.digest = None;
                out.insert((file.rel.clone(), m.line, addr), reads);
            }
        }
    }
    let mut hits: Vec<Hit> = out
        .into_iter()
        .map(|((path, line, addr), reads)| Hit {
            project: addr.project,
            id: addr.id,
            letter: addr.letter,
            path,
            line,
            reads,
        })
        .collect();
    hits.sort();
    hits
}

/// A law some pin of the targets carries, with the clauses those pins name and the pins.
struct Governing<'a> {
    project: Option<String>,
    law: &'a Law,
    letters: Vec<String>,
    hits: Vec<Hit>,
}

fn group<'a>(
    own: &'a Scan,
    others: &'a BTreeMap<String, Scan>,
    hits: Vec<Hit>,
) -> Result<Vec<Governing<'a>>> {
    let mut out: Vec<Governing<'a>> = Vec::new();
    for hit in hits {
        let scan = match &hit.project {
            None => own,
            Some(key) => others
                .get(key)
                .with_context(|| format!("no project `{key}` in this workspace"))?,
        };
        let Some(law) = scan
            .laws
            .iter()
            .find(|law| !law.struck && (law.id == hit.id || law.aliases.contains(&hit.id)))
        else {
            bail!(
                "{}:{}: the marker names `{}`, which no active law declares. Run `silcrow check`.",
                hit.path.display(),
                hit.line,
                hit.id
            );
        };
        let entry = match out
            .iter_mut()
            .position(|g| g.project == hit.project && g.law.id == law.id)
        {
            Some(idx) => &mut out[idx],
            None => {
                out.push(Governing {
                    project: hit.project.clone(),
                    law,
                    letters: Vec::new(),
                    hits: Vec::new(),
                });
                out.last_mut().expect("just pushed")
            }
        };
        if let Some(letter) = &hit.letter {
            if !entry.letters.contains(letter) {
                entry.letters.push(letter.clone());
            }
        }
        entry.hits.push(hit);
    }
    Ok(out)
}

/// The drafts of each note that declares a law some pin of the targets carries, in the order
/// the laws are printed, each with the project of its note.
fn note_drafts<'a>(
    own: &'a Scan,
    others: &'a BTreeMap<String, Scan>,
    laws: &[Governing<'a>],
) -> Vec<(Option<String>, Draft<'a>)> {
    // ยง k40z0sght.d@wakp0
    let mut notes: Vec<(&Option<String>, &Path)> = Vec::new();
    for g in laws {
        let note = (&g.project, g.law.loc.path.as_path());
        if !notes.contains(&note) {
            notes.push(note);
        }
    }
    let mut out = Vec::new();
    for (project, note) in notes {
        let scan = match project {
            None => own,
            Some(key) => &others[key],
        };
        let laws = scan.laws.iter().filter(|law| law.loc.path == note);
        out.extend(drafts(laws).into_iter().map(|d| (project.clone(), d)));
    }
    out
}

fn hit_clauses<'a>(g: &Governing<'a>) -> Vec<(&'a str, &'a str, bool)> {
    live_clauses(g.law)
        .into_iter()
        .filter(|(letter, _, _)| g.letters.iter().any(|l| l == letter))
        .collect()
}

fn address_of(hit: &Hit) -> String {
    let mut out = match &hit.project {
        Some(project) => format!("{project}:{}", hit.id),
        None => hit.id.clone(),
    };
    if let Some(letter) = &hit.letter {
        out.push('.');
        out.push_str(letter);
    }
    out
}

fn draft_address(project: &Option<String>, draft: &Draft) -> String {
    match project {
        Some(project) => format!("{project}:{}", draft.address()),
        None => draft.address(),
    }
}

fn to_json(laws: &[Governing<'_>], drafts: &[(Option<String>, Draft<'_>)]) -> Value {
    let laws: Vec<Value> = laws
        .iter()
        .map(|g| {
            let mut law = json!({
                "id": g.law.id,
                "note": g.law.loc.path.display().to_string(),
                "name": g.law.name,
                "draft": g.law.draft,
                "public": g.law.public,
                "clauses": hit_clauses(g).iter().map(|(letter, text, draft)| json!({
                    "letter": letter, "text": text, "draft": draft,
                })).collect::<Vec<_>>(),
                "markers": g.hits.iter().map(|hit| json!({
                    "address": address_of(hit),
                    "path": hit.path.display().to_string(),
                    "line": hit.line,
                    "reads": hit.reads.word(),
                })).collect::<Vec<_>>(),
            });
            if let Some(project) = &g.project {
                law["project"] = json!(project);
            }
            law
        })
        .collect();
    let drafts: Vec<Value> = drafts
        .iter()
        .map(|(project, d)| {
            json!({
                "address": draft_address(project, d),
                "note": d.loc().path.display().to_string(),
                "line": d.loc().line,
                "text": d.clause.map_or(&d.law.name, |c| &c.text),
            })
        })
        .collect();
    json!({ "laws": laws, "drafts": drafts })
}

fn to_text(laws: &[Governing<'_>], drafts: &[(Option<String>, Draft<'_>)]) -> String {
    let mut out = String::new();
    for g in laws {
        let project = g
            .project
            .as_ref()
            .map_or(String::new(), |p| format!("{p}:"));
        out.push_str(&format!(
            "{} {project}{}  {}\n  {}\n",
            sign(g.law),
            g.law.id,
            g.law.loc.path.display(),
            g.law.name
        ));
        for (letter, text, draft) in hit_clauses(g) {
            out.push_str(&format!("  ({letter}){} {text}\n", mark(draft)));
        }
        for hit in &g.hits {
            out.push_str(&format!(
                "    {} {}:{} {}\n",
                hit.reads.word(),
                hit.path.display(),
                hit.line,
                address_of(hit)
            ));
        }
    }
    if !drafts.is_empty() {
        out.push_str("Drafts of these notes, not implemented:\n");
        for (project, d) in drafts {
            let text = d.clause.map_or(&d.law.name, |c| &c.text);
            out.push_str(&format!("  ยง {} {text}\n", draft_address(project, d)));
        }
    }
    out
}