use super::{Checker, Host, LabelFacts, LabelRepair, short};
use crate::{
grammar::{
Block as Rule, Found, Label, Schema, Squashed, Unit as UnitRule, Words, carries_labels,
is_words, squash, without,
},
markdown::Unit,
};
pub(crate) fn words_of(schema: &Schema, host: &dyn Host) -> Words {
let language = schema.core.language.as_deref();
Words::new(
schema
.labels
.iter()
.map(|key| {
let words = host
.label_words(&LabelFacts::new(key, language))
.map(|w| squash(&w))
.filter(|w| is_words(w))
.unwrap_or_else(|| key.clone());
(key.clone(), words)
})
.collect(),
)
}
pub(crate) struct Read {
pub squashed: Squashed,
pub label: Option<(Found, usize)>,
}
impl Checker<'_> {
fn reads_labels(&self, block: &Rule) -> bool {
!self.labels.is_empty() && carries_labels(block.kind)
}
pub(crate) fn read(&self, unit: &Unit, block: &Rule, rule: Option<&UnitRule>) -> Read {
let squashed = Squashed::new(&unit.text);
if !self.reads_labels(block) {
return Read {
squashed,
label: None,
};
}
let link = |words: &str| self.links.contains(&squash(words).to_lowercase());
match self
.schema
.label_in(&self.labels, block, rule, &squashed.text)
.filter(|found| !link(&found.words))
{
Some(found) => Read {
squashed: without(&squashed, &found.at),
label: Some((found.clone(), squashed.original(found.at.start))),
},
None => Read {
squashed,
label: None,
},
}
}
pub(crate) fn check_label(
&mut self,
unit: &Unit,
block: &Rule,
rule: Option<&UnitRule>,
read: &Read,
shaped: bool,
) -> bool {
if !self.reads_labels(block) {
return false;
}
let common = rule.map_or(&block.common, |r| &r.common);
match (block.label_of(rule), &read.label) {
(Some(Label::Required), None) if shaped => {
let listed = self.labels.listed();
self.emit(
common,
Some(unit.line),
"TLMD_249",
format!(
"`{}` carries no label; its rule requires one: {listed}",
short(&read.squashed.text)
),
);
true
}
(None, Some((found, _))) => {
self.emit(
common,
Some(unit.line),
"TLMD_250",
format!(
"`{}` carries the label `[{}]`, and its rule declares no `label`",
short(&read.squashed.text),
found.words
),
);
true
}
(Some(_), Some((found, start))) if !self.labels.accepts(&found.words) => {
let listed = self.labels.listed();
self.emit(
common,
Some(unit.line),
"TLMD_251",
format!(
"the label `[{}]` is none of the labels of the schema: {listed}",
found.words
),
);
if let Some(new) = self.labels.words(&found.words).map(str::to_string)
&& let Some((line, col)) = unit.position(*start)
{
self.out.label_repairs.push(LabelRepair {
line,
col,
old: format!("[{}]", found.words),
new: format!("[{new}]"),
});
return false;
}
true
}
_ => false,
}
}
pub(crate) fn label_kept(&self, read: &Read) -> String {
let Some((found, _)) = &read.label else {
return String::new();
};
let words = match self.labels.words(&found.words) {
Some(w) if !self.labels.accepts(&found.words) => w,
_ => found.words.as_str(),
};
format!("[{words}] ")
}
}