use std::{borrow::Cow, ops::Range};
use super::{
Checker, Subject,
bound::{self, check_text},
claim::{at_unit, check_blocks},
keys,
label::Read,
quoted,
rules::{check_lines, check_rules, reach, reads},
};
use crate::{
grammar::{
self, Block as Rule, FormatMatch, Lang, RuleCommon, Shape, Squashed, Unit as UnitRule,
captured, refused_quoting,
},
markdown::{self, Block, BlockDetail, BlockKind, Unit, host_ref},
text,
};
pub(super) fn unit_noun(c: &Checker<'_>, kind: BlockKind) -> &'static str {
if c.lines_block.is_some() {
return "line";
}
unit_of(kind)
}
pub(crate) fn unit_of(kind: BlockKind) -> &'static str {
match kind {
BlockKind::Prose | BlockKind::Blockquote => "paragraph",
BlockKind::BulletList | BlockKind::NumberedList => "item",
BlockKind::Table => "row",
BlockKind::Image => "image",
BlockKind::References => "definition",
BlockKind::Code | BlockKind::Html => "line",
BlockKind::Group => "repetition",
_ => "unit",
}
}
pub(super) fn noun(kind: BlockKind) -> &'static str {
match kind {
BlockKind::Prose | BlockKind::Blockquote => "paragraphs",
BlockKind::BulletList | BlockKind::NumberedList => "items",
BlockKind::Table => "rows",
BlockKind::Image => "images",
BlockKind::References => "definitions",
BlockKind::Group => "repetitions",
_ => "units",
}
}
#[expect(
clippy::too_many_lines,
reason = "one pass of the check, a split of which is a refactor of its own"
)]
pub(super) fn check_plain(c: &mut Checker<'_>, block: &Block, rule: &Rule, section: Option<usize>) {
c.gate(&rule.common, block.line);
let mark = c.bound.len();
let headed = block.units.is_empty()
&& matches!(&block.detail, BlockDetail::Quote { headings } if !headings.is_empty());
if let Some(seq) = &rule.sequence {
match_units(c, seq, &block.units, rule, section, block.line);
} else if !matches!(rule.kind, BlockKind::Region | BlockKind::ThematicBreak) && !headed {
check_count(c, rule, block.units.len(), block.line);
}
if let Some(each) = &rule.each {
for unit in &block.units {
check_unit(
c,
unit,
each,
rule,
section,
rule.sequence.is_none().then_some(each),
);
}
}
if let Some(rules) = &rule.rules {
check_rules(c, block, rules, rule, section);
}
if rule.each.is_none() && rule.sequence.is_none() && rule.rules.is_none() {
for unit in &block.units {
let read = c.read(unit, rule, None);
if c.check_label(unit, rule, None, &read, true) {
c.broke(unit);
}
no_nested(c, unit, &rule.common);
}
}
if matches!(rule.kind, BlockKind::Code | BlockKind::Html) {
for unit_rule in rule.units() {
check_lines(c, block, unit_rule, rule, section);
}
}
match (&block.detail, rule.kind) {
(BlockDetail::Code { lang, .. }, BlockKind::Code) => {
if lang.is_empty() {
c.emit(
&rule.common,
Some(block.line),
"TLMD_43",
"the code block has no tag",
);
} else if let Some(Lang::Tags(tags)) = &rule.lang
&& !tags.iter().any(|t| t == lang || t == "any")
{
c.emit(
&rule.common,
Some(block.line),
"TLMD_43",
format!(
"the code block is tagged {}; expected {}",
text::code(lang),
text::code_list(tags, " or ")
),
);
}
}
(BlockDetail::Quote { headings }, BlockKind::Blockquote) => {
for h in headings {
c.emit(
&rule.common,
Some(h.line),
"TLMD_172",
format!(
"heading {} is inside a blockquote; a heading of the document stands outside every quote",
text::code(&format!("{} {}", "#".repeat(usize::from(h.level)), h.text))
),
);
}
}
(BlockDetail::Table { columns, readings }, BlockKind::Table) => {
if let Some(expected) = &rule.columns {
let read = rule
.columns_read
.clone()
.unwrap_or_else(|| expected.iter().map(|c| grammar::read(c)).collect());
let cells: Vec<String> = if readings.len() == columns.len() {
readings.clone()
} else {
columns.iter().map(|c| grammar::read(c)).collect()
};
let ok = if rule.columns_open {
cells.starts_with(&read)
} else {
cells == read
};
if !ok {
c.emit(
&rule.common,
Some(block.line),
"TLMD_44",
format!(
"the table header is {}; expected {}",
text::code(&columns.join(" | ")),
text::code(&expected.join(" | "))
),
);
}
}
}
(BlockDetail::Region { target }, BlockKind::Region) => {
let what = rule
.source_pattern
.as_ref()
.and_then(|p| match c.host.region(target) {
Subject::Document => {
let dialect = c.host.dialect();
let marker = dialect.region.map(|r| dialect.spell(r)).unwrap_or_default();
Some(names_a_document(
&text::code(&format!("{marker} {target}")),
p.as_str(),
))
}
Subject::Text(subject) if p.is_match(&subject) => None,
Subject::Text(subject) if &subject == target => Some(format!(
"the include target {target} does not match {}",
text::code(p.as_str()),
target = text::code(target)
)),
Subject::Text(subject) => Some(format!(
"the include target {target}, read as {subject}, does not match {}",
text::code(p.as_str()),
target = text::code(target),
subject = text::code(&subject)
)),
Subject::Unknown => None,
});
if let Some(what) = what {
c.emit(
&rule.common,
Some(block.line),
"TLMD_163",
format!("{what}{}", reads("target", rule.example())),
);
}
}
(_, BlockKind::Image) => {
if let Some(p) = &rule.source_pattern {
for unit in &block.units {
let scheme = c.host.dialect().scheme;
let mismatch = |path: &str| {
format!(
"the image {path} does not match {}",
text::code(p.as_str()),
path = text::code(path)
)
};
let what = match host_ref(&unit.text, scheme) {
Some(r) => match c.host.image(&r) {
Subject::Unknown => continue,
Subject::Document => names_a_document(
&format!(
"the image {}",
text::code(&format!("{}:{r}", scheme.unwrap_or_default()))
),
p.as_str(),
),
Subject::Text(path) if p.is_match(&path) => continue,
Subject::Text(path) => mismatch(&path),
},
None if p.is_match(&unit.text) => continue,
None => mismatch(&unit.text),
};
c.emit(
&rule.common,
Some(unit.line),
"TLMD_163",
format!("{what}{}", reads("target", rule.example())),
);
}
}
}
_ => {}
}
if !rule.inline_html && !block.html_lines.is_empty() {
bound::inline_html(c, block, rule, mark);
}
}
fn counted(kind: BlockKind) -> (&'static str, &'static str) {
match kind {
BlockKind::Code => ("fence", "fences"),
BlockKind::Html => ("unit", "units"),
_ => (unit_of(kind), noun(kind)),
}
}
pub(super) fn check_count(c: &mut Checker<'_>, rule: &Rule, n: usize, line: usize) {
let (one, many) = counted(rule.kind);
if n < rule.min {
c.emit(
&rule.common,
Some(line),
"TLMD_146",
format!(
"the {} block needs at least {}; it has {n}",
rule.kind.name_in(&c.host.dialect()),
text::count(rule.min, one, many)
),
);
}
if let Some(limit) = &rule.max
&& let Some(max) = limit.hard()
&& n > max
{
c.emit(
&rule.common,
Some(line),
"TLMD_160",
text::at_limit(
format!(
"the {} block allows at most {}; it has {n}",
rule.kind.name_in(&c.host.dialect()),
text::count(max, one, many)
),
&limit.when_at_limit,
),
);
}
}
fn satisfies(c: &Checker<'_>, unit: &Unit, rule: &UnitRule, block: &Rule) -> bool {
let read = c.read(unit, block, Some(rule));
let squashed = &read.squashed;
let text = squashed.text.as_str();
if let Some(shape) = rule.matcher()
&& !shape.matches(text, |k| c.front_reading(k, rule))
{
return false;
}
if let Some(name) = &rule.format
&& let Some(f) = c.schema.formats_of(rule).get(name)
&& !(if f.prohibited.is_empty() {
f.conforms(text)
} else {
f.conforms_masked(text, &ban_text(c, unit, squashed, rule))
})
{
return false;
}
if let Some(k) = &rule.key
&& !rule.key_optional
&& rule.matcher().and_then(|s| captured(s, k, text)).is_none()
{
return false;
}
true
}
fn ban_text<'a>(
c: &Checker<'_>,
unit: &Unit,
squashed: &'a Squashed,
rule: &UnitRule,
) -> Cow<'a, str> {
if !rule.bans_in(c.schema.formats_of(rule)) {
return Cow::Borrowed(&squashed.text);
}
markdown::mask_code(&squashed.text, &code_of(c, unit, squashed))
}
fn code_of(c: &Checker<'_>, unit: &Unit, squashed: &Squashed) -> Vec<Range<usize>> {
let code = c.doc.body.code_in(unit);
let mut out: Vec<Range<usize>> = Vec::new();
if code.is_empty() {
return out;
}
let mut k = 0;
for i in 0..squashed.text.len() {
let at = squashed.original(i);
while code.get(k).is_some_and(|r| r.end <= at) {
k += 1;
}
if code.get(k).is_none_or(|r| r.start > at) {
continue;
}
match out.last_mut() {
Some(r) if r.end == i => r.end = i + 1,
_ => out.push(i..i + 1),
}
}
out
}
pub(super) fn has_shape(c: &Checker<'_>, text: &str, rule: &UnitRule) -> bool {
rule.matcher()
.is_none_or(|s| s.matches(text, |k| c.front_reading(k, rule)))
&& rule
.format_in(c.schema.formats_of(rule))
.is_none_or(|f| f.shape_for(text).is_some())
}
pub(super) fn shape_failure_of(rule: &UnitRule, read: &Read) -> Option<String> {
let text = read.squashed.text.as_str();
match (&rule.shape, rule.matcher()) {
(Some(written @ Shape::Text(_)), _) => Some(written.failure(text)),
(_, Some(shape)) => Some(read.quoting(|q| shape.failure_quoting(text, q))),
_ => None,
}
}
fn match_units(
c: &mut Checker<'_>,
seq: &[UnitRule],
units: &[Unit],
block: &Rule,
section: Option<usize>,
at: usize,
) {
let mut ui = 0;
for (pi, rule) in seq.iter().enumerate() {
let mut count = 0;
while let Some(unit) = units.get(ui) {
let take = satisfies(c, unit, rule, block)
|| (count == 0
&& !rule.optional
&& (reach(c, rule, &c.read(unit, block, Some(rule)).squashed.text) > 0
|| !seq[pi + 1..].iter().any(|later| {
(later.shape.is_some() || later.format.is_some())
&& satisfies(c, unit, later, block)
})));
if !take {
break;
}
check_unit(c, unit, rule, block, section, Some(rule));
ui += 1;
count += 1;
if !rule.repeat {
break;
}
}
if count == 0 && !rule.optional {
let line = units.get(ui).map_or(at, |u| u.line);
c.located(at_unit(&c.at, rule), |c| {
c.emit(
&rule.common,
Some(line),
"TLMD_147",
format!("position {} of the sequence is missing", pi + 1),
);
});
}
}
for unit in &units[ui.min(units.len())..] {
c.emit(
&block.common,
Some(unit.line),
"TLMD_161",
format!("{} is beyond the sequence", quoted(&unit.text)),
);
c.broke(unit);
}
}
fn line_at(unit: &Unit, squashed: &Squashed, offset: usize) -> usize {
unit.position(squashed.original(offset))
.map_or(unit.line, |(line, _)| line)
}
pub(super) fn check_unit(
c: &mut Checker<'_>,
unit: &Unit,
rule: &UnitRule,
block: &Rule,
section: Option<usize>,
judge: Option<&UnitRule>,
) {
if unit.text.is_empty() && unit.nested.first().is_some_and(|b| b.line == unit.line) {
check_nested(c, unit, rule, section);
return;
}
c.located(at_unit(&c.at, rule), |c| {
check_own(c, unit, rule, block, section, judge);
});
check_nested(c, unit, rule, section);
}
#[expect(
clippy::too_many_lines,
reason = "one pass of the check, a split of which is a refactor of its own"
)]
fn check_own(
c: &mut Checker<'_>,
unit: &Unit,
rule: &UnitRule,
block: &Rule,
section: Option<usize>,
judge: Option<&UnitRule>,
) {
let judges_label = judge.is_some_and(|j| std::ptr::eq(j, rule));
let read = c.read(unit, block, Some(judge.unwrap_or(rule)));
let squashed = &read.squashed;
let text = squashed.text.as_str();
let reported = c.out.findings.len();
let masked = ban_text(c, unit, squashed, rule);
if c.records_accepted && accepts(c, unit_noun(c, block.kind), text, rule) {
c.accept(rule, unit.line, unit.end_line.max(unit.line));
}
let mark = c.bound.len();
check_text(c, unit, rule, block, &read);
let bound = bound::bound_since(c, mark, unit);
let schema = c.schema;
let format = rule.format_in(schema.formats_of(rule));
let shown = read.shown.text.as_str();
let example = rule
.example()
.map(str::to_string)
.or_else(|| format.map(|f| f.first_example().to_string()));
if let Some(shape @ (Shape::Template(_) | Shape::Pattern(_))) = rule.matcher()
&& !shape.matches(text, |_| None)
{
let line = match shape {
Shape::Template(t) => line_at(unit, squashed, t.failure(text).offset),
_ => unit.line,
};
c.emit(
&rule.common,
Some(line),
"TL_74",
format!(
"{} {}{}",
quoted(shown),
shape_failure_of(rule, &read).unwrap_or_default(),
reads(unit_noun(c, block.kind), rule.example())
),
);
}
let mut format_matched = rule.format.is_none();
if let Some(name) = &rule.format {
let checked = format
.map(|f| read.quoting(|q| f.check_quoting(text, &masked, unit_noun(c, block.kind), q)));
format_matched = matches!(checked, Some(FormatMatch::Ok(_)));
match checked {
Some(FormatMatch::Ok(None))
if format.is_some_and(|f| f.key.is_some()) && !rule.key_optional =>
{
c.emit(
&rule.common,
Some(unit.line),
"TL_44",
format!(
"{} carries no key: the format `{name}` captures `{}`",
quoted(shown),
format.and_then(|f| f.key.clone()).unwrap_or_default()
),
);
}
Some(FormatMatch::Fail(msg)) => {
c.emit(
&rule.common,
Some(unit.line),
"TL_74",
format!("{} {msg}", quoted(shown)),
);
}
Some(FormatMatch::Refused(msg)) => {
c.emit(&rule.common, Some(unit.line), "TL_75", msg);
}
Some(FormatMatch::Ok(Some(got))) => {
let at = format
.and_then(|f| keys::key_at(f.shape_for(text)?.0, f.key.as_deref()?, text));
let cap = keys::capture(c, unit, squashed, (got, at), rule, block, section);
c.out.captures.push(cap);
}
_ => {}
}
}
if let Some(k) = &rule.key {
let shape = match (rule.matcher(), &rule.format) {
(Some(shape), _) => Some(shape),
(None, Some(_)) => format
.and_then(|f| f.shape_for(text))
.map(|(shape, _)| shape),
(None, None) => None,
};
let got = shape.and_then(|shape| captured(shape, k, text));
match got {
Some(got) => {
let at = shape.and_then(|shape| keys::key_at(shape, k, text));
let cap = keys::capture(c, unit, squashed, (got, at), rule, block, section);
c.out.captures.push(cap);
}
None if !rule.key_optional
&& rule.matcher().is_none_or(|s| s.matches(text, |_| None))
&& format_matched =>
{
c.emit(
&rule.common,
Some(unit.line),
"TL_44",
format!(
"{} carries no key: `{k}` captures nothing{}",
quoted(shown),
reads(unit_noun(c, block.kind), rule.example())
),
);
}
None => {}
}
}
if let Some(reason) = read.quoting(|q| {
refused_quoting(
text,
&masked,
&rule.prohibited_patterns,
unit_noun(c, block.kind),
example.as_deref(),
q,
)
}) {
c.emit(&rule.common, Some(unit.line), "TL_75", reason);
bound::moves(c, bound);
}
let broke = c.out.findings.len() > reported;
let by_label = judges_label && {
let shaped = has_shape(c, text, rule);
c.check_label(unit, block, Some(rule), &read, shaped)
};
if broke || by_label {
c.broke(unit);
}
}
fn accepts(c: &Checker<'_>, noun: &str, text: &str, rule: &UnitRule) -> bool {
matches!(noun, "paragraph" | "item" | "row") && has_shape(c, text, rule)
}
fn check_nested(c: &mut Checker<'_>, unit: &Unit, rule: &UnitRule, section: Option<usize>) {
match &rule.blocks {
Some(nested) => {
let inner: Vec<&Block> = unit.nested.iter().collect();
check_blocks(c, Some(nested), &inner, true, section, unit.line);
}
None => c.located(at_unit(&c.at, rule), |c| no_nested(c, unit, &rule.common)),
}
}
fn no_nested(c: &mut Checker<'_>, unit: &Unit, common: &RuleCommon) {
if let Some(first) = unit.nested.first() {
let message = if unit.text.is_empty() && first.line == unit.line {
format!(
"the item's text reads as {} block",
first.kind.spoken_in(&c.host.dialect())
)
} else {
"the item carries content beyond its text".to_string()
};
c.emit(common, Some(first.line), "TLMD_162", message);
c.broke_beyond_text(unit);
for inner in &unit.nested {
c.broke_block(inner);
}
}
}
fn names_a_document(shown: &str, pattern: &str) -> String {
format!(
"{shown} names a document; this rule takes what matches {}, a file or an asset by its path",
text::code(pattern)
)
}