use std::{
borrow::Cow,
collections::{HashMap, HashSet},
};
use super::{At, Checker, Repair, blocks, label::Read, quoted};
use crate::{
Finding, Severity,
grammar::{Block as Rule, Shape, Text, Unit as UnitRule, squash, task_box},
markdown::{self, Block, BlockKind, Unit},
text,
};
fn expected_text(c: &Checker<'_>, text: &Text) -> Option<String> {
c.text_of(text).map(|s| squash(&s))
}
fn repair_prefix(c: &Checker<'_>, unit: &Unit) -> Option<String> {
let raw = c.doc.text.lines().nth(unit.line.checked_sub(1)?)?;
let clean = c.doc.body.clean_line(unit.line, raw);
let line: &str = &clean;
if unit.text.is_empty() {
return Some(format!("{} ", line.trim_end()));
}
(0..=line.len())
.filter(|&i| line.is_char_boundary(i))
.find(|&i| {
let rest = line[i..].trim_end();
!rest.is_empty()
&& !rest.starts_with(char::is_whitespace)
&& unit.text.starts_with(rest)
})
.map(|i| line[..i].to_string())
}
pub(super) fn check_text(
c: &mut Checker<'_>,
unit: &Unit,
rule: &UnitRule,
block: &Rule,
read: &Read,
) {
let Some(Shape::Text(text)) = &rule.shape else {
return;
};
let Some(expected) = expected_text(c, text) else {
let Text::From(key) = text else {
return;
};
if !c.unbound_is_own_fault(key) {
return;
}
c.emit(
&rule.common,
Some(unit.line),
"TLMD_168",
format!(
"{} is bound to the frontmatter `{key}`, which is absent",
quoted(&unit.text)
),
);
return;
};
let reading = c.text_of(text).map(|t| squash(&rule.read_text(&t)));
if reading.as_deref() == Some(read.squashed.text.as_str()) {
if let Text::From(key) = text {
record(c, unit, block, key, expected);
}
return;
}
if let Text::From(key) = text
&& c.value_missing(key)
{
return;
}
let prefix = repair_prefix(c, unit);
let at = match block.kind {
BlockKind::BulletList | BlockKind::NumberedList => task_box(&expected),
_ => 0,
};
let label = match block.label_of(Some(rule)) {
Some(_) => c.label_kept(read),
None => String::new(),
};
let full = format!("{}{label}{}", &expected[..at], &expected[at..]);
let written = match c.lines_block {
Some(_) => Ok(Cow::Borrowed(full.as_str())),
None => markdown::unit_written(prefix.as_deref().unwrap_or_default(), &full),
};
let (criterion, message) = match (text, &written) {
(Text::From(key), Err(why)) => {
let line = c.doc.frontmatter.and_then(|f| f.get(key)).map(|v| v.line);
let at = At {
named: Some(format!("key `{key}`")),
..At::default()
};
let said = why.said(
&format!("the frontmatter `{key}`"),
&expected,
blocks::unit_of(block.kind),
);
let subject = format!("the frontmatter `{key}` ");
let reported = c.out.findings.iter().any(|f| {
f.criterion == "TLMD_276" && f.line == line && f.message.starts_with(&subject)
});
if !reported {
c.located(at, |c| c.emit(&rule.common, line, "TLMD_276", said));
}
return;
}
(Text::Literal(_), _) => (
"TL_74",
format!("{} must read {}", quoted(&unit.text), text::code(&expected)),
),
(Text::From(key), Ok(_)) => (
"TLMD_165",
format!(
"{} must equal the frontmatter `{key}`: {}",
quoted(&unit.text),
text::code(&expected)
),
),
};
c.emit(&rule.common, Some(unit.line), criterion, message);
if c.has_other_shape(unit, rule, block) {
return;
}
let written = sure_text(c, unit, block.kind, prefix.as_deref(), written.ok(), &full);
if let (Some(prefix), Some(text)) = (prefix, written) {
if let Some(finding) = c.out.findings.last().cloned() {
c.settles(&finding);
}
c.out.repairs.push(Repair {
line: unit.line,
end_line: unit.end_line.max(unit.line),
prefix,
text,
});
}
}
fn read_back(
c: &Checker<'_>,
unit: &Unit,
prefix: &str,
text: &str,
full: &str,
below: bool,
) -> Option<String> {
let last = unit.line.checked_sub(1)?;
let lines: Vec<&str> = c.doc.text.lines().take(last).collect();
if lines.last().is_none_or(|l| l.trim().is_empty()) {
return Some(text.to_string());
}
let indent = |l: &str| l.len() - l.trim_start().len();
let defined = |i: usize| c.doc.body.ref_defs.iter().any(|d| d.2 == i + 1);
let mut first = None;
for i in (c.doc.body_line.max(1) - 1..last).rev().take(REACH) {
if lines[i].trim().is_empty() {
break;
}
let found = if below {
opens_item(lines[i]) || indent(lines[i]) < prefix.len()
} else {
defined(i)
};
if found {
first = Some(i);
break;
}
}
if !below && first.is_none_or(|f| !markdown::all_definitions(&lines[f..last])) {
return Some(text.to_string());
}
let first = first?;
let base = &lines[first][..indent(lines[first])];
let unindent = |l: &'_ str| -> String {
l.strip_prefix(base)
.unwrap_or_else(|| l.trim_start())
.to_string()
};
let above = lines[first..last]
.iter()
.map(|l| unindent(l))
.collect::<Vec<_>>()
.join("\n");
let original = prefix;
let prefix = unindent(prefix);
let prefix = prefix.as_str();
let at = last - first + 1;
let reads = |written: &str| {
let parse = |line: &str| {
let body = format!("{above}\n{prefix}{line}\n");
markdown::parse(
&body,
1,
&markdown::Segments::default(),
&markdown::Dialect::default(),
)
};
let (before, after) = (parse(&unit.text), parse(written));
before.ref_defs == after.ref_defs
&& unit_at(&after.blocks, at).is_some_and(|u| u.text == written.trim())
};
let alone =
|e: &String| markdown::unit_written(original, e).is_ok_and(|w| w.as_ref() == e.as_str());
std::iter::once(text.to_string())
.chain(markdown::escapes(full).filter(alone))
.find(|t| reads(t))
}
#[derive(Debug, Clone)]
pub(super) struct Bound {
first: usize,
last: usize,
key: String,
value: String,
noun: &'static str,
rule: usize,
claimed: bool,
moved: Vec<Tag>,
}
type Tag = (&'static str, Option<usize>, String);
type TagOf<'f> = (&'f str, Option<usize>, &'f str);
fn tag_of(f: &Finding) -> TagOf<'_> {
(f.criterion.as_str(), f.line, f.message.as_str())
}
fn record(c: &mut Checker<'_>, unit: &Unit, block: &Rule, key: &str, value: String) {
let prose = matches!(
block.kind,
BlockKind::Prose | BlockKind::Blockquote | BlockKind::BulletList | BlockKind::NumberedList
);
if prose && c.lines_block.is_none() {
c.bound.push(Bound {
first: unit.line,
last: unit.end_line.max(unit.line),
key: key.to_string(),
value,
noun: blocks::unit_of(block.kind),
rule: std::ptr::from_ref(block) as usize,
claimed: true,
moved: Vec::new(),
});
}
}
pub(super) fn released(mut records: Vec<Bound>) -> Vec<Bound> {
release(&mut records);
records
}
pub(super) fn release(records: &mut [Bound]) {
for b in records {
b.claimed = false;
}
}
pub(super) fn claimed_tags(records: &[Bound]) -> HashSet<TagOf<'_>> {
records
.iter()
.filter(|b| b.claimed)
.flat_map(|b| {
b.moved
.iter()
.map(|(crit, line, message)| (*crit, *line, message.as_str()))
})
.collect()
}
pub(super) fn moves(c: &mut Checker<'_>, at: Option<usize>) {
let Some(f) = c.out.findings.last() else {
return;
};
let tag = (crit(&f.criterion), f.line, f.message.clone());
if let Some(b) = at.and_then(|i| c.bound.get_mut(i)) {
b.moved.push(tag);
}
}
fn crit(criterion: &str) -> &'static str {
if criterion == "TLMD_45" {
"TLMD_45"
} else {
"TL_75"
}
}
pub(super) fn bound_since(c: &Checker<'_>, mark: usize, unit: &Unit) -> Option<usize> {
(mark..c.bound.len()).find(|&i| c.bound[i].first == unit.line)
}
fn holding(ranges: &[(usize, usize, usize)], line: usize) -> Option<usize> {
let after = ranges.partition_point(|&(first, _, _)| first <= line);
after
.checked_sub(1)
.filter(|&i| line <= ranges[i].1)
.map(|i| ranges[i].2)
}
pub(super) fn inline_html(c: &mut Checker<'_>, block: &Block, rule: &Rule, mark: usize) {
let me = std::ptr::from_ref(rule) as usize;
let mut values: Vec<(usize, usize, usize)> = (mark..c.bound.len())
.filter(|&i| c.bound[i].rule == me)
.map(|i| (c.bound[i].first, c.bound[i].last, i))
.collect();
values.sort_unstable();
let mut nested: Vec<(usize, usize, usize)> = if rule.units().any(|u| u.blocks.is_some()) {
block
.units
.iter()
.flat_map(|u| &u.nested)
.map(|b| (b.line, b.end_line.max(b.line), 0))
.collect()
} else {
Vec::new()
};
nested.sort_unstable();
let mut seen = HashSet::new();
let mut own = false;
let mut lines: Vec<(usize, Option<usize>)> = Vec::new();
for (n, &line) in block.html_lines.iter().enumerate() {
let at = holding(&values, line);
let first_of_its_kind = match at {
Some(i) => seen.insert(i),
None => !own && holding(&nested, line).is_none(),
};
if n == 0 || first_of_its_kind {
own |= at.is_none();
lines.push((line, at));
}
}
for (line, at) in lines {
c.emit(
&rule.common,
Some(line),
"TLMD_45",
"inline HTML is not accepted here",
);
moves(c, at);
}
}
pub(super) fn report_values(c: &mut Checker<'_>) {
let bound = std::mem::take(&mut c.bound);
let mut owners: HashMap<TagOf<'_>, usize> = HashMap::new();
for (i, b) in bound.iter().enumerate() {
for (crit, line, message) in &b.moved {
owners.entry((*crit, *line, message.as_str())).or_insert(i);
}
}
let mut faults: Vec<(&Bound, String, bool)> = Vec::new();
let findings = std::mem::take(&mut c.out.findings);
for f in findings {
match owners.get(&tag_of(&f)) {
Some(&i) => {
let why = f
.message
.rsplit_once(" (schema ")
.map_or(f.message.as_str(), |(why, _)| why)
.to_string();
fault(&mut faults, &bound[i], why, f.severity == Severity::Error);
}
None => c.out.findings.push(f),
}
}
for (b, why, error) in faults {
let line = c
.doc
.frontmatter
.and_then(|f| f.get(&b.key))
.map(|v| v.line);
let at = At {
named: Some(format!("key `{}`", b.key)),
..At::default()
};
let message = format!(
"the frontmatter `{}` holds {}, which the {} bound to it can't hold: {why}",
b.key,
text::code(&b.value),
b.noun
);
c.located(at, |c| c.error(line, "TLMD_312", message));
if !error && let Some(f) = c.out.findings.last_mut() {
f.severity = Severity::Warning;
}
}
}
fn fault<'b>(faults: &mut Vec<(&'b Bound, String, bool)>, b: &'b Bound, why: String, error: bool) {
match faults.iter_mut().find(|(o, _, _)| o.key == b.key) {
Some(f) => f.2 |= error,
None => faults.push((b, why, error)),
}
}
fn sure_text(
c: &Checker<'_>,
unit: &Unit,
kind: BlockKind,
prefix: Option<&str>,
written: Option<Cow<'_, str>>,
full: &str,
) -> Option<String> {
let list = matches!(kind, BlockKind::BulletList | BlockKind::NumberedList);
let below = list && prefix.is_some_and(|p| p.trim().is_empty());
let prefix_or_none = prefix.unwrap_or_default();
match written {
Some(text) if list && text.trim().is_empty() => emptied(c, unit, prefix_or_none),
Some(text) if list && !below => Some(text.into_owned()),
Some(text) if c.lines_block.is_none() => {
read_back(c, unit, prefix_or_none, &text, full, below)
}
other => other.map(Cow::into_owned),
}
}
fn emptied(c: &Checker<'_>, unit: &Unit, prefix: &str) -> Option<String> {
let lines: Vec<&str> = c.doc.text.lines().collect();
let line = |n: usize| n.checked_sub(1).and_then(|i| lines.get(i)).copied();
let blank = |n: usize| line(n).is_none_or(|l| l.trim().is_empty());
let end = unit.end_line.max(unit.line);
let indent = |l: &str| l.len() - l.trim_start().len();
if blank(end + 1)
&& line(end + 2).is_some_and(|l| !l.trim().is_empty() && indent(l) >= prefix.len())
{
return None;
}
if !first_of_list(&c.doc.body.blocks, unit.line) || blank(unit.line - 1) {
return Some(String::new());
}
let above = line(unit.line - 1)?;
let base = &above[..indent(above)];
let marker = prefix.strip_prefix(base).unwrap_or(prefix);
let probe = format!("{}\n{}\n", &above[base.len()..], marker.trim_end());
let read = markdown::parse(
&probe,
1,
&markdown::Segments::default(),
&markdown::Dialect::default(),
);
unit_at(&read.blocks, 2)
.is_some_and(|u| u.text.is_empty())
.then(String::new)
}
fn first_of_list(blocks: &[markdown::Block], line: usize) -> bool {
blocks.iter().any(|b| {
let list = matches!(b.kind, BlockKind::BulletList | BlockKind::NumberedList);
(list && b.units.first().is_some_and(|u| u.line == line))
|| b.units.iter().any(|u| first_of_list(&u.nested, line))
})
}
const REACH: usize = 32;
fn opens_item(line: &str) -> bool {
let t = line.trim_start();
let digits = t.len() - t.trim_start_matches(|c: char| c.is_ascii_digit()).len();
let rest = match digits {
0 => t.strip_prefix(['-', '*', '+']),
1..=9 => t[digits..].strip_prefix(['.', ')']),
_ => None,
};
rest.is_some_and(|r| r.is_empty() || r.starts_with([' ', '\t']))
}
fn unit_at(blocks: &[markdown::Block], line: usize) -> Option<&Unit> {
blocks.iter().flat_map(|b| &b.units).find_map(|u| {
if u.line == line {
Some(u)
} else {
unit_at(&u.nested, line)
}
})
}