use std::collections::HashMap;
use super::states_of;
use crate::{
Compiled, Finding, Locator, MarkerCheck, Model, RepoPath,
grammar::{CitationRule, CitedFrom},
markdown::slug,
model::{KeyEntry, KeyIndex, Query},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Citation {
pub slug: Option<String>,
pub source: RepoPath,
pub source_type: String,
pub rel: Option<String>,
pub line: usize,
}
impl Citation {
pub fn counts_for(&self, from: &CitedFrom) -> bool {
match (from, &self.rel) {
(CitedFrom::Types(types), None) => types.contains(&self.source_type),
(CitedFrom::Marker(rel), Some(r)) => r == rel,
_ => false,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Citations {
by_target: HashMap<RepoPath, Vec<Citation>>,
added: Vec<(RepoPath, Citation)>,
}
impl Citations {
pub fn add(&mut self, target: RepoPath, citation: Citation) {
self.added.push((target.clone(), citation.clone()));
self.by_target.entry(target).or_default().push(citation);
}
pub fn len(&self) -> usize {
self.added.len()
}
pub fn is_empty(&self) -> bool {
self.added.is_empty()
}
pub fn since(&self, mark: usize) -> Vec<(RepoPath, Citation)> {
self.added[mark..].to_vec()
}
pub fn of<'a>(
&'a self,
target: &'a RepoPath,
slug: Option<&'a str>,
from: &'a CitedFrom,
) -> impl Iterator<Item = &'a Citation> + 'a {
self.by_target
.get(target)
.into_iter()
.flatten()
.filter(move |c| &c.source != target)
.filter(move |c| c.counts_for(from))
.filter(move |c| slug.is_none_or(|s| c.slug.as_deref() == Some(s)))
}
pub fn markers_of<'a>(&'a self, target: &'a RepoPath) -> impl Iterator<Item = &'a Citation> {
self.by_target
.get(target)
.into_iter()
.flatten()
.filter(|c| c.rel.is_some())
}
}
pub fn check_document(
model: &Model,
compiled: &Compiled,
keys: &KeyIndex,
citations: &Citations,
k: usize,
doc: &crate::Document,
) -> Vec<Finding> {
let mut findings = Vec::new();
let Some((r, schema)) = compiled.for_doc(model, k, doc) else {
return findings;
};
if schema.cited_by.is_empty() && schema.markers.is_none() {
return findings;
}
model.note(Query::Citations(doc.path.clone()));
let schema_id = model.schema(r).id();
if let Some(allowed) = &schema.markers {
findings.extend(refused_markers(model, citations, doc, allowed, &schema_id));
}
let states = states_of(doc.frontmatter.as_ref(), schema);
let markers_off = model.marker_check == MarkerCheck::Off;
for rule in schema
.cited_by
.iter()
.filter(|r| r.common.only.admits(&states))
.filter(|r| !(markers_off && matches!(r.from, CitedFrom::Marker(_))))
{
let from = from_phrase(rule);
let locator = match &rule.keys {
None => format!("cited-by {}", locator_of(rule)),
Some(id) => format!("cited-by {} of `{id}`", locator_of(rule)),
};
let locator = Locator::schema(schema_id.clone()).at(locator);
let cited = |slug: Option<&str>| citations.of(&doc.path, slug, &rule.from).next().is_some();
let uncited = |line: Option<usize>, message: String| {
Finding::new(
doc.path.clone(),
line,
rule.common.severity,
"SOKF_SCHEMA_17",
message,
)
.at(&locator)
};
match &rule.keys {
None => {
if !cited(None) {
findings.push(uncited(None, format!("no {from} cites this document")));
}
}
Some(id) => {
let mut owned: Vec<&KeyEntry> = keys
.of_document(&doc.path)
.filter(|e| e.rule_id.as_deref() == Some(id.as_str()))
.collect();
owned.sort_by_key(|e| (e.line, e.key.clone()));
owned.dedup_by_key(|e| slug(&e.key));
for e in owned {
let by_heading = e.heading_slug.as_deref().is_some_and(|h| cited(Some(h)));
if !cited(Some(&slug(&e.key))) && !by_heading {
findings.push(uncited(
Some(e.line),
format!("no {from} cites key `{}`", e.key),
));
}
}
}
}
}
findings
}
fn refused_markers(
model: &Model,
citations: &Citations,
doc: &crate::Document,
allowed: &[String],
schema_id: &str,
) -> Vec<Finding> {
let severity = model.marker_check.severity();
let held = if allowed.is_empty() {
"no marker".to_string()
} else {
let rels: Vec<String> = allowed.iter().map(|r| format!("`sokf-{r}:`")).collect();
format!("only {}", rels.join(", "))
};
let name = doc.id().unwrap_or(doc.path.as_str());
citations
.markers_of(&doc.path)
.filter(|c| c.rel.as_ref().is_some_and(|r| !allowed.contains(r)))
.map(|c| {
let rel = c.rel.as_deref().unwrap_or_default();
Finding::new(
c.source.clone(),
Some(c.line),
severity,
"SOKF_SCHEMA_49",
format!("`sokf-{rel}:` cites `{name}`, whose schema admits {held}"),
)
.at(&Locator::schema(schema_id).at("markers"))
})
.collect()
}
fn locator_of(rule: &CitationRule) -> String {
match &rule.from {
CitedFrom::Types(types) => format!("`{}`", types.join("`, `")),
CitedFrom::Marker(rel) => format!("marker `{rel}`"),
}
}
pub(super) fn or_list(types: &[String]) -> String {
types
.iter()
.map(|t| format!("`{t}`"))
.collect::<Vec<_>>()
.join(" or ")
}
fn from_phrase(rule: &CitationRule) -> String {
match &rule.from {
CitedFrom::Types(types) => format!("{} document", or_list(types)),
CitedFrom::Marker(rel) => format!("`sokf-{rel}:` marker"),
}
}