use super::{
Checker,
blocks::{check_unit, noun, shape_failure_of, unit_noun},
claim::at_unit,
label::Read,
quoted,
};
use crate::{
grammar::{Block as Rule, RuleCommon, Shape, Unit as UnitRule, squash},
markdown::{Block, BlockDetail, Unit},
text,
};
fn content_lines(block: &Block) -> Vec<(usize, &str)> {
let first = match block.detail {
BlockDetail::Code { fence, .. } if fence > 0 => block.line + 1,
_ => block.line,
};
match block.units.first() {
Some(u) => u
.text
.lines()
.enumerate()
.map(|(i, text)| (first + i, text.trim_start()))
.filter(|(_, text)| !text.trim().is_empty())
.collect(),
None => Vec::new(),
}
}
pub(super) fn check_lines(
c: &mut Checker<'_>,
block: &Block,
unit_rule: &UnitRule,
rule: &Rule,
section: Option<usize>,
) {
let Some(rules) = &unit_rule.lines else {
return;
};
let units: Vec<Unit> = content_lines(block)
.into_iter()
.map(|(line, text)| Unit::leaf(text.to_string(), line, line))
.collect();
let held = c.lines_block.replace(block.line);
let taken = apply_rules(c, &units, rules, rule, section, block.line, "lines");
if !unit_rule.lines_open {
untaken(
c,
&units,
&taken,
rules,
rule,
&unit_rule.common,
("the fence", "line"),
"lines-open",
);
}
c.lines_block = held;
}
fn apply_rules(
c: &mut Checker<'_>,
units: &[Unit],
rules: &[UnitRule],
rule: &Rule,
section: Option<usize>,
at: usize,
noun: &str,
) -> Vec<bool> {
let production: Vec<Option<usize>> = units
.iter()
.map(|u| {
rules
.iter()
.position(|r| r.is_production() && satisfies_shape(c, u, r, rule))
})
.collect();
let judge: Vec<Option<usize>> = units
.iter()
.zip(&production)
.map(|(u, p)| {
p.or_else(|| {
rules.iter().position(|r| {
!r.is_counter()
&& match &r.select {
Some(s) => s.is_match(&c.read(u, rule, Some(r)).squashed.text),
None => !r.has_shape(),
}
})
})
})
.collect();
let mut taken = vec![false; units.len()];
for (ri, guarded) in rules.iter().enumerate() {
let selected: Vec<usize> = (0..units.len())
.filter(|&i| match &guarded.select {
Some(s) => s.is_match(&c.read(&units[i], rule, Some(guarded)).squashed.text),
None if guarded.has_shape() => production[i] == Some(ri),
None => true,
})
.collect();
let what = match (&guarded.select, &guarded.shape, &guarded.format) {
(Some(s), _, _) | (None, Some(Shape::Pattern(s)), _) => {
format!("the {noun} matching {}", text::code(s.as_str()))
}
(None, Some(Shape::Template(t)), _) => {
format!("the {noun} of the template {}", text::code(&t.source))
}
(None, Some(shape @ Shape::Text(_)), _) => {
format!("the {noun} reading {}", text::code(&shape.label()))
}
(None, None, Some(name)) => format!("the {noun} of the format `{name}`"),
(None, None, None) => format!("the block's {noun}"),
};
c.located(at_unit(&c.at, guarded), |c| {
count(c, guarded, &selected, units, at, &what);
});
if guarded.is_counter() {
continue;
}
for i in selected {
taken[i] = true;
check_unit(
c,
&units[i],
guarded,
rule,
section,
judge[i].map(|j| &rules[j]),
);
}
}
taken
}
fn count(
c: &mut Checker<'_>,
guarded: &UnitRule,
selected: &[usize],
units: &[Unit],
at: usize,
what: &str,
) {
let n = selected.len();
if n < guarded.min {
c.emit(
&guarded.common,
Some(at),
"TLMD_93",
format!(
"{what}: at least {} {} needed; there {} {n}",
guarded.min,
text::is_are(guarded.min),
text::is_are(n)
),
);
}
if let Some(limit) = &guarded.max
&& let Some(max) = limit.hard()
&& n > max
{
let line = selected.get(max).map_or(at, |&i| units[i].line);
c.emit(
&guarded.common,
Some(line),
"TLMD_159",
text::at_limit(
format!(
"{what}: at most {max} {} allowed; there {} {n}",
text::is_are(max),
text::is_are(n)
),
&limit.when_at_limit,
),
);
}
}
fn satisfies_shape(c: &Checker<'_>, unit: &Unit, rule: &UnitRule, block: &Rule) -> bool {
let read = c.read(unit, block, Some(rule));
rule.fits(c.schema.formats_of(rule), &read.squashed.text, |k| {
c.front_reading(k, rule)
})
}
#[expect(
clippy::too_many_arguments,
reason = "each is a part of the report of a unit that no rule takes"
)]
fn untaken(
c: &mut Checker<'_>,
units: &[Unit],
taken: &[bool],
rules: &[UnitRule],
block: &Rule,
common: &RuleCommon,
(whose, unit_is): (&str, &str),
open: &str,
) {
for (unit, seen) in units.iter().zip(taken) {
if *seen {
continue;
}
let text = squash(&unit.text);
let best = rules
.iter()
.filter(|r| r.is_production())
.map(|r| (r, c.read(unit, block, Some(r))))
.fold(None::<(&UnitRule, Read, usize)>, |best, (r, read)| {
let n = reach(c, r, &read.squashed.text);
match best {
Some((_, _, m)) if m >= n => best,
_ => Some((r, read, n)),
}
})
.filter(|(_, _, n)| *n > 0)
.map(|(r, read, _)| (r, read));
if let Some((r, read)) = best {
let reason = shape_failure(c, r, &read, unit_is);
c.emit(
&r.common,
Some(unit.line),
"TLMD_57",
format!(
"{} matches no rule of {whose}; the nearest {reason}",
quoted(&read.shown.text)
),
);
} else {
let meant = meant(c, unit, rules, block, unit_is);
c.emit(
common,
Some(unit.line),
if open == "lines-open" {
"TLMD_87"
} else {
"TLMD_53"
},
format!(
"{} matches no rule of {whose}{meant}; declare it or set `{open}`",
quoted(&text)
),
);
}
c.broke(unit);
}
}
fn meant(c: &Checker<'_>, unit: &Unit, rules: &[UnitRule], block: &Rule, unit_is: &str) -> String {
let examples = |r: &UnitRule| -> Vec<String> {
let own: Vec<&str> = r.examples.iter().map(String::as_str).collect();
let list = if own.is_empty() {
r.format_in(c.schema.formats_of(r))
.map(|f| f.examples())
.unwrap_or_default()
} else {
own
};
list.iter()
.map(|e| {
c.schema
.unlabelled(&c.labels, block, Some(r), &r.read_text(e))
.0
})
.collect()
};
let productions: Vec<(&UnitRule, Read, Vec<String>)> = rules
.iter()
.filter(|r| r.is_production())
.map(|r| (r, c.read(unit, block, Some(r)), examples(r)))
.filter(|(_, _, e)| !e.is_empty())
.collect();
let shared = |read: &Read, e: &[String]| {
e.iter()
.map(|e| common_prefix(&read.squashed.text, e))
.max()
.unwrap_or(0)
};
let reach: Vec<usize> = productions.iter().map(|p| shared(&p.1, &p.2)).collect();
let most = reach.iter().copied().max().unwrap_or(0);
let nearest: Vec<&(&UnitRule, Read, Vec<String>)> = productions
.iter()
.zip(&reach)
.filter(|(_, n)| **n == most)
.map(|(p, _)| p)
.collect();
if let [(r, read, _)] = nearest.as_slice()
&& most > 0
{
format!("; the nearest {}", shape_failure(c, r, read, unit_is))
} else {
let shown: Vec<String> = nearest
.iter()
.filter_map(|(r, _, _)| {
r.example().or_else(|| {
r.format_in(c.schema.formats_of(r))
.and_then(|f| f.examples().first().copied())
})
})
.filter(|e| !e.is_empty())
.map(text::code)
.collect();
if shown.is_empty() {
String::new()
} else {
format!(
"; {} {unit_is} of this kind reads {}",
text::article(unit_is),
shown.join(", or reads ")
)
}
}
}
pub(super) fn reads(what: &str, example: Option<&str>) -> String {
example
.filter(|e| !e.is_empty())
.map_or_else(String::new, |e| {
format!(
"; {} {what} of this kind reads {}",
text::article(what),
text::code(e)
)
})
}
fn common_prefix(a: &str, b: &str) -> usize {
a.char_indices()
.zip(b.chars())
.find(|((_, x), y)| x != y)
.map_or_else(|| a.len().min(b.len()), |((i, _), _)| i)
}
pub(super) fn reach(c: &Checker<'_>, rule: &UnitRule, text: &str) -> usize {
rule.reach(c.schema.formats_of(rule), text)
}
fn shape_failure(c: &Checker<'_>, rule: &UnitRule, read: &Read, unit_is: &str) -> String {
let text = read.squashed.text.as_str();
match (&rule.shape, &rule.format) {
(Some(_), _) => format!(
"{}{}",
shape_failure_of(rule, read).unwrap_or_default(),
reads(unit_is, rule.example())
),
(None, Some(name)) => match rule
.format_in(c.schema.formats_of(rule))
.map(|f| read.quoting(|q| f.matching_quoting(text, unit_is, q)))
{
Some(Err(reason)) => reason,
_ => format!("format `{name}`"),
},
(None, None) => String::new(),
}
}
pub(super) fn check_rules(
c: &mut Checker<'_>,
block: &Block,
rules: &[UnitRule],
rule: &Rule,
section: Option<usize>,
) {
let taken = apply_rules(
c,
&block.units,
rules,
rule,
section,
block.line,
noun(rule.kind),
);
if rule.units_open {
for (unit, _) in block.units.iter().zip(&taken).filter(|(_, t)| !**t) {
let read = c.read(unit, rule, None);
if c.check_label(unit, rule, None, &read, true) {
c.broke(unit);
}
}
} else {
untaken(
c,
&block.units,
&taken,
rules,
rule,
&rule.common,
("the block", unit_noun(c, rule.kind)),
"units-open",
);
}
}