use std::{
collections::{BTreeMap, HashSet},
ops::Range,
};
use super::{At, Capture, Checker, Paired, Spot, anchors, blocks::unit_of, rules_named};
use crate::{
grammar::{
self, Block, Captured, DerivationSource, KeyDerivation, KeyText, RuleCommon, Section,
Shape, Squashed,
},
markdown::{self, BlockKind, Unit},
text,
};
type Scope = (Range<usize>, Option<(usize, String)>);
type Pairing = (Paired, usize);
struct Pairer<'a> {
section: usize,
with: &'a [String],
heading: bool,
noun: &'static str,
rule_id: Option<&'a str>,
common: &'a RuleCommon,
demands: bool,
}
fn unit_pairers<'a>(
blocks: Option<&'a [Block]>,
section: usize,
demands: bool,
c: &Checker<'_>,
out: &mut Vec<Pairer<'a>>,
) {
for b in blocks
.unwrap_or(&[])
.iter()
.filter(|b| b.common.only.admits(&c.possible))
{
let demands = demands && b.common.only.admits(c.states);
unit_pairers(b.blocks.as_deref(), section, demands, c, out);
for u in b.units() {
let lines = u.lines.iter().flatten().map(|l| (l, "line"));
for (rule, noun) in std::iter::once((u, unit_of(b.kind))).chain(lines) {
if let Some(with) = &rule.for_each_key_of {
out.push(Pairer {
section,
with,
heading: false,
noun,
rule_id: rule.rule_id.as_deref(),
common: &rule.common,
demands,
});
}
}
unit_pairers(u.blocks.as_deref(), section, demands, c, out);
}
}
}
pub(super) fn check(c: &mut Checker<'_>) {
let mut captures = std::mem::take(&mut c.out.captures);
let firsts = anchors::identities(&captures);
let ids = anchors::anchor_ids(&captures, &firsts);
for (cap, id) in captures.iter_mut().zip(ids) {
cap.anchor = id;
}
uniqueness(c, &captures, &firsts);
pairings(c, &captures);
derivations(c, &captures);
c.out.captures = captures;
}
fn scopes(c: &Checker<'_>, section: usize) -> Vec<Scope> {
if c.sections[section].parent.is_none() {
return vec![(0..usize::MAX, None)];
}
match c.parent_of[section] {
None => Vec::new(),
Some(pj) => c
.occurrences
.iter()
.filter(|o| o.section == pj)
.map(|o| {
let heading = format!("{} {}", "#".repeat(usize::from(o.level)), o.text);
(c.span(o), Some((o.line, heading)))
})
.collect(),
}
}
fn uniqueness(c: &mut Checker<'_>, captures: &[Capture], firsts: &[usize]) {
let sections = c.sections.clone();
let at_capture = |cap: &Capture| At::capture(cap, §ions);
let group_of = |cap: &Capture| -> Option<Pairing> {
let paired = cap.pairs.clone()?;
let scope = scopes(c, cap.section?)
.iter()
.position(|(span, _)| span.contains(&cap.line))
.unwrap_or(usize::MAX);
Some((paired, scope))
};
let mut groups: BTreeMap<Option<Pairing>, Vec<usize>> = BTreeMap::new();
for (i, cap) in captures.iter().enumerate() {
groups.entry(group_of(cap)).or_default().push(i);
}
for (pairing, group) in &groups {
let criterion = if pairing.is_some() {
"TLMD_29"
} else {
"TLMD_148"
};
let mut by_key: BTreeMap<(&str, usize), Vec<&Capture>> = BTreeMap::new();
for &i in group {
let first = firsts[i];
by_key
.entry((captures[first].key.as_str(), first))
.or_default()
.push(&captures[i]);
}
for all in by_key.values() {
let caps: Vec<&Capture> = all.iter().filter(|cap| !cap.repeats).copied().collect();
if caps.len() > 1 {
let at = at_capture(all[0]);
let again: Vec<&[&Capture]> = caps
.windows(2)
.filter(|w| {
!c.repeats.iter().any(|(first, body)| {
body.contains(&w[1].line) && first.contains(&w[0].line)
})
})
.collect();
for w in again {
let (cap, first) = (w[1], caps[0].line);
c.located(at.clone(), |c| {
c.error(
Some(cap.line),
criterion,
format!(
"key {} is captured more than once; it was first captured at line {first}",
text::code(&cap.key)
),
);
});
}
}
}
}
slugs(c, captures, firsts);
}
fn slugs(c: &mut Checker<'_>, captures: &[Capture], firsts: &[usize]) {
let sections = c.sections.clone();
let at_capture = |cap: &Capture| At::capture(cap, §ions);
let headings = &c.doc.body.headings;
let mut first: BTreeMap<String, usize> = BTreeMap::new();
for (i, cap) in captures
.iter()
.enumerate()
.filter(|(_, cap)| cap.pairs.is_none() || cap.heading_slug.is_some())
{
let s = cap.anchor.clone();
let own = |line: usize| {
captures.iter().zip(firsts).any(|(other, &f)| {
f == firsts[i] && other.heading_slug.is_some() && other.line == line
})
};
if let Some(line) = headings
.iter()
.find(|h| h.slug == s && h.line != cap.line && !own(h.line))
.map(|h| h.line)
{
c.located(at_capture(cap), |c| {
c.error(
Some(cap.line),
"TLMD_101",
format!(
"key {} has the slug `{s}` of the heading at line {line}; keys and headings share one namespace",
text::code(&cap.key)
),
);
});
}
match first.get(&s) {
Some(&j) if firsts[j] != firsts[i] => {
let other = &captures[j];
c.located(at_capture(cap), |c| {
c.error(
Some(cap.line),
"TLMD_101",
format!(
"key {} has the slug `{s}` of key {} at line {}; each key needs a slug of its own",
text::code(&cap.key),
text::code(&other.key),
other.line
),
);
});
}
Some(_) => {}
None => {
first.insert(s, i);
}
}
}
}
fn pairings(c: &mut Checker<'_>, captures: &[Capture]) {
let declared = c.sections.clone();
let mut pairers = Vec::new();
for (j, section) in declared.iter().enumerate() {
let demands = section.common.only.admits(c.states);
if let Some(with) = §ion.for_each_key_of {
pairers.push(Pairer {
section: j,
with,
heading: true,
noun: "section",
rule_id: section.rule_id.as_deref(),
common: §ion.common,
demands,
});
}
unit_pairers(section.blocks.as_deref(), j, demands, c, &mut pairers);
}
for p in &pairers {
let section = declared[p.section];
let at = At {
rule_id: p.rule_id.map(str::to_string).or(section.rule_id.clone()),
line: Some(p.common.line),
..At::section(section)
};
c.located(at, |c| pairing(c, captures, p, section));
}
}
fn pairing(c: &mut Checker<'_>, captures: &[Capture], p: &Pairer<'_>, section: &Section) {
for (span, host) in scopes(c, p.section) {
let under = host.as_ref().map_or_else(String::new, |(_, h)| {
format!(" under {h}", h = text::code(h))
});
let mut wanted: Vec<(Vec<KeyText>, &str, usize)> = Vec::new();
for cap in captures.iter().filter(|cap| {
cap.rule_id.as_ref().is_some_and(|r| p.with.contains(r))
&& cap
.pairs
.as_ref()
.is_none_or(|q| !q.with.iter().any(|w| p.with.contains(w)))
&& span.contains(&cap.line)
}) {
match wanted.iter_mut().find(|(_, k, _)| *k == cap.key) {
Some((texts, ..)) => texts.push(cap.text()),
None => wanted.push((vec![cap.text()], &cap.key, cap.line)),
}
}
let names = |texts: &[KeyText], got: &KeyText| texts.iter().any(|k| k.same(got));
let have: Vec<(KeyText, &str, usize)> = captures
.iter()
.filter(|cap| {
cap.pairs
.as_ref()
.is_some_and(|q| q.with == p.with && q.by == p.common.line)
&& span.contains(&cap.line)
})
.map(|cap| (cap.text(), cap.key.as_str(), cap.line))
.collect();
let named: Vec<Option<usize>> = have
.iter()
.map(|(got, ..)| wanted.iter().position(|(texts, ..)| names(texts, got)))
.collect();
for (w, (_, key, at)) in wanted.iter().enumerate().filter(|_| p.demands) {
if !named.contains(&Some(w)) {
let message = if p.heading {
format!(
"no {} section for key {}{under}",
text::code(§ion.label()),
text::code(key)
)
} else {
format!(
"no {} names key {} of {}{under}",
p.noun,
text::code(key),
rules_named(p.with)
)
};
c.emit(p.common, Some(*at), "TLMD_95", message);
}
}
for ((_, key, line), w) in have.iter().zip(&named) {
if w.is_none() {
let message = if p.heading {
format!(
"section names key {}, which is not a key of {}{under}",
text::code(key),
rules_named(p.with)
)
} else {
format!(
"key {} is not a key of {}{under}",
text::code(key),
rules_named(p.with)
)
};
c.emit(p.common, Some(*line), "TLMD_96", message);
}
}
}
}
fn derivations(c: &mut Checker<'_>, captures: &[Capture]) {
let sections = c.sections.clone();
let mut rows = HashSet::new();
rows_in(&c.doc.body.blocks, &mut rows);
for cap in captures {
let Some(derivation) = &cap.derives else {
continue;
};
let key = cap.text();
let values = match &derivation.source {
DerivationSource::Rule(_) => Vec::new(),
DerivationSource::From(k) => c.front_value(k).into_iter().collect(),
};
let parents: Vec<KeyText> = match &derivation.source {
DerivationSource::Rule(r) => parents(captures, r, derivation),
DerivationSource::From(_) => values
.iter()
.map(|v| KeyText::new(&read_as(cap, &rows, v), v, key.verbatim))
.collect(),
};
if key.parent_in(derivation, &parents).is_some() {
continue;
}
let prefix = cap.key.rsplit_once(&derivation.separator).map(|(p, _)| p);
let message = match prefix {
Some(p) => match &derivation.source {
DerivationSource::Rule(r) => format!(
"key {} derives from {}, which is not a key of set `{r}`",
text::code(&cap.key),
text::code(p)
),
DerivationSource::From(k) => match values.first() {
Some(v) => format!(
"key {} derives from {}, which is not {v}, the value of the frontmatter `{k}`",
text::code(&cap.key),
text::code(p),
v = text::code(v)
),
None if c.doc.frontmatter.and_then(|f| f.get(k)).is_some() => continue,
None => format!(
"key {} derives from {}, and the frontmatter `{k}` that it derives from is absent",
text::code(&cap.key),
text::code(p)
),
},
},
None => format!(
"key {} has no {} separator to derive from",
text::code(&cap.key),
text::code(&derivation.separator)
),
};
c.located(At::capture(cap, §ions), |c| {
c.error(Some(cap.line), "TL_33", message);
});
}
}
fn read_as(cap: &Capture, rows: &HashSet<usize>, value: &str) -> String {
let read = match cap.spot {
Spot::Heading(_) => grammar::read(value),
_ if rows.contains(&cap.line) => grammar::row_reading(value).text,
Spot::Before(_) => value.to_string(),
Spot::Inline(..) => grammar::read(value),
};
grammar::squash(&read)
}
fn rows_in(blocks: &[markdown::Block], out: &mut HashSet<usize>) {
for b in blocks {
if b.kind == BlockKind::Table {
out.extend(b.units.iter().map(|u| u.line));
}
for u in &b.units {
rows_in(&u.nested, out);
}
}
}
fn parents(captures: &[Capture], rule: &str, derivation: &KeyDerivation) -> Vec<KeyText> {
captures
.iter()
.filter(|cap| {
cap.rule_id.as_deref() == Some(rule)
&& cap
.derives
.as_ref()
.is_none_or(|d| d.source != derivation.source)
})
.map(Capture::text)
.collect()
}
pub(super) fn key_at(shape: &Shape, name: &str, text: &str) -> Option<Range<usize>> {
Some(shape.captures(text)?.name(name)?.range())
}
pub(super) fn capture(
c: &Checker<'_>,
unit: &Unit,
squashed: &Squashed,
(got, at): (Captured, Option<Range<usize>>),
rule: &grammar::Unit,
block: &grammar::Block,
section: Option<usize>,
) -> Capture {
let reading = unit.reading.or_written(&unit.text);
Capture {
spot: spot(c, (unit, block.kind), squashed.original(got.start)),
written: grammar::written_key(&unit.text, &reading, squashed, at, &got.key),
key: got.key,
line: unit.line,
heading_slug: None,
anchor: String::new(),
scope: rule.unique.clone(),
rule_id: rule
.files_under(&[block.rule_id.as_deref(), c.group_rule.as_deref()])
.map(str::to_string),
rule_name: rule
.named_by(&[block.rule_id.as_deref(), c.group_rule.as_deref()])
.map(str::to_string),
section,
pairs: rule.for_each_key_of.clone().map(|with| Paired {
with,
by: rule.common.line,
}),
repeats: rule.key_repeats,
derives: rule.key_derives_from.clone(),
}
}
pub(super) fn spot(c: &Checker<'_>, (unit, kind): (&Unit, BlockKind), offset: usize) -> Spot {
if let Some(line) = c.lines_block {
return Spot::Before(line);
}
let reading = unit.reading.or_written(&unit.text);
let mut offset = reading.span_of(&unit.text, offset, offset).start;
if matches!(kind, BlockKind::BulletList | BlockKind::NumberedList) {
offset = offset.max(grammar::task_box(&unit.text));
}
let before = &unit.text.as_bytes()[..offset.min(unit.text.len())];
if before.iter().rev().take_while(|&&b| b == b'\\').count() % 2 == 1 {
offset -= 1;
}
match unit
.position(offset)
.filter(|_| !unit.in_joint(offset))
.or_else(|| unit.position_after(offset))
{
Some((line, col)) => Spot::Inline(line, c.doc.body.span_around(line, col).unwrap_or(col)),
None => Spot::Before(unit.line),
}
}