use std::{borrow::Cow, ops::Range};
use super::{
At, Host, NullHost,
derived::{derived, derived_unit},
label,
};
use crate::{
Finding, Locator, RepoPath,
grammar::{
Block, FmFormat, Format, FormatMatch, FormatRegistry, FormatSource, FrontmatterConstraint,
Label, Schema, Section, Shape, Squashed, Text, Unit, Words, captured, carries_labels, read,
read_row, refused_masked, row_code_spans, row_reading, squash,
},
markdown::{self, BlockKind, Reading, is_slug, is_url},
text,
};
type Problem = Option<String>;
struct Examples<'a> {
schema: &'a Schema,
path: &'a RepoPath,
out: Vec<Finding>,
failed: Failed,
locator: Locator,
at: At,
labels: Words,
}
pub fn check(schema: &Schema, path: &RepoPath, id: &str) -> Vec<Finding> {
check_examples(schema, &NullHost, path, id).0
}
#[derive(Debug, Default)]
pub(super) struct Failed {
pub texts: Vec<String>,
pub rules: Vec<usize>,
}
pub(super) fn check_examples(
schema: &Schema,
host: &dyn Host,
path: &RepoPath,
id: &str,
) -> (Vec<Finding>, Failed) {
let mut e = Examples {
schema,
path,
out: Vec::new(),
failed: Failed::default(),
locator: Locator::schema(id),
at: At::default(),
labels: label::words_of(schema, host),
};
for (key, constraint) in &schema.core.frontmatter {
if let Some(text) = &constraint.example {
e.at = At {
named: Some(format!("key `{key}`")),
..At::default()
};
e.said_of(
text,
constraint.common.line,
"TL_64",
frontmatter(key, constraint),
);
}
}
for section in &schema.sections {
e.at = At {
region: Some(format!("section \"{}\"", section.label())),
rule_id: section.rule_id.clone(),
..At::default()
};
if let Some(text) = §ion.heading.example {
e.said_of(text, section.common.line, "TL_64", heading(section));
if let (Some(kd), Some(_)) = (§ion.heading.key_derives_from, §ion.heading.key) {
let problem = derived(schema, kd, section.example_key(), markdown::reading);
e.said_of(text, section.common.line, "TL_127", problem);
}
}
e.blocks(section.blocks.as_deref());
}
if let Some(preamble) = &schema.preamble {
e.at = At {
region: Some("preamble".to_string()),
..At::default()
};
e.blocks(preamble.blocks.as_deref());
}
e.at = At::default();
let bound = schema.bound_formats();
for (name, (format, source)) in &schema.core.formats.entries {
let reads: Vec<Reads> = [
(bound.prose.contains(name), Reads::Prose),
(bound.rows.contains(name), Reads::Row),
(bound.lines.contains(name), Reads::Lines),
]
.into_iter()
.filter_map(|(bound, reads)| bound.then_some(reads))
.collect();
let own = matches!(source, FormatSource::Schema(_));
let layer = if own {
String::new()
} else {
format!(" ({})", source.label())
};
for (criterion, message, text, line) in format_failures(name, format, &layer, &reads) {
let at = if own { line } else { schema.core.line };
if let Some(text) = text.filter(|t| !t.is_empty()) {
e.failed.texts.push(text);
}
if !matches!(source, FormatSource::File(_) | FormatSource::Pack(_)) {
e.out
.push(Finding::error(path.clone(), Some(at), criterion, message));
}
}
}
(e.out, e.failed)
}
pub fn check_formats(
registry: &FormatRegistry,
source: &FormatSource,
path: &RepoPath,
) -> Vec<Finding> {
registry
.entries
.iter()
.filter(|(_, (_, s))| s == source)
.flat_map(|(name, (format, _))| {
format_failures(name, format, "", &[]).into_iter().map(
|(criterion, message, _, line)| {
Finding::error(path.clone(), Some(line), criterion, message)
},
)
})
.chain(super::spelling::check_formats(registry, source, path))
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Reads {
Prose,
Row,
Lines,
}
impl Reads {
fn reading(self, text: &str) -> Reading {
match self {
Reads::Prose => markdown::reading(text),
Reads::Row => row_reading(text),
Reads::Lines => Reading::written(text),
}
}
fn format(self, format: &Format) -> Cow<'_, Format> {
match self {
Reads::Prose => Cow::Owned(format.read_with(&read)),
Reads::Row => Cow::Owned(format.read_with(&read_row)),
Reads::Lines => Cow::Borrowed(format),
}
}
fn code_spans(self, text: &str) -> Vec<Range<usize>> {
match self {
Reads::Row => row_code_spans(text),
Reads::Prose => markdown::code_spans_in(text),
Reads::Lines => Vec::new(),
}
}
}
type FormatFailure = (&'static str, String, Option<String>, usize);
fn format_failures(
name: &str,
format: &Format,
layer: &str,
reads: &[Reads],
) -> Vec<FormatFailure> {
let failures = |r: Reads| format_examples(name, &r.format(format), layer, r);
if reads.is_empty() {
let failed = failures(Reads::Prose);
return if failed.is_empty() || failures(Reads::Lines).is_empty() {
Vec::new()
} else {
failed
};
}
let mut failed: Vec<FormatFailure> = Vec::new();
for &r in reads {
for f in failures(r) {
if !failed.iter().any(|g| g.1 == f.1) {
failed.push(f);
}
}
}
failed
}
fn format_examples(name: &str, format: &Format, layer: &str, reads: Reads) -> Vec<FormatFailure> {
let read_line = |text: &str| written(text, &reads.reading(text));
let mut out = Vec::new();
let line_of = |variant: Option<&str>| {
variant
.and_then(|v| format.raw.get("variants")?.get(v))
.map_or(format.raw.line, |node| node.line)
};
let examples: Vec<(Option<(&str, &Shape)>, &str)> = match &format.example {
Some(example) => vec![(None, example.as_str())],
None => format
.variants
.iter()
.map(|(vi, v)| (Some((vi.as_str(), &v.shape)), v.example.as_str()))
.collect(),
};
for (own, line) in examples {
let quoted = read_line(line);
let text = quoted.squashed.text.clone();
let code = reads.code_spans(&text);
let masked = markdown::mask_code(&text, &code);
let checked = quoted.quoting(|q| format.check_quoting(&text, &masked, "line", q));
let problem = match (own, checked) {
(Some((vi, shape)), _) if !shape.matches(&text, |_| None) => Some(format!(
"the example {} of variant `{vi}` of format `{name}`{layer} does not match its own variant: it {}", text::code(line),
quoted.quoting(|q| shape.failure_quoting(&text, q))
)),
(_, FormatMatch::Fail(reason) | FormatMatch::Refused(reason)) => {
let reason = without_example(&reason);
Some(format!("the example {} of format `{name}`{layer} {reason}", text::code(line)))
}
(_, FormatMatch::Ok(None)) => format.key.as_ref().map(|key| {
format!(
"the example {} of format `{name}`{layer} carries no key: the format captures `{key}`", text::code(line)
)
}),
(_, FormatMatch::Ok(Some(_))) => None,
};
if let Some(message) = problem {
let failed = squash(line);
out.push((
"TL_65",
message,
Some(failed),
line_of(own.map(|(vi, _)| vi)),
));
}
}
for (i, (vi, variant)) in format.variants.iter().enumerate() {
let text = read_line(&variant.example).squashed.text;
if !variant.shape.matches(&text, |_| None) {
continue;
}
for (j, (vj, other)) in format.variants.iter().enumerate() {
if i != j && other.shape.matches(&text, |_| None) {
out.push((
"TL_43",
format!(
"the example of variant `{vi}` of format `{name}`{layer} also matches variant `{vj}`: each variant's example matches its own variant only"
),
None,
line_of(Some(vi)),
));
}
}
}
out
}
impl Examples<'_> {
fn said_of(&mut self, text: &str, line: usize, criterion: &'static str, problem: Problem) {
let text = squash(text);
if problem.is_some() {
self.failed.rules.push(line);
if !text.is_empty() {
self.failed.texts.push(text);
}
}
self.say(line, criterion, problem);
}
fn say(&mut self, line: usize, criterion: &'static str, problem: Problem) {
if let Some(reason) = problem {
let locator = self.at.locate(&self.locator);
self.out.push(
Finding::error(self.path.clone(), Some(line), criterion, reason).at(&locator),
);
}
}
fn inside(&mut self, pos: Option<usize>, rule_id: Option<&String>, f: impl FnOnce(&mut Self)) {
let mut at = self.at.clone();
at.blocks.extend(pos);
if pos.is_some() || rule_id.is_some() {
at.rule_id = rule_id.cloned();
}
let held = std::mem::replace(&mut self.at, at);
f(self);
self.at = held;
}
fn blocks(&mut self, rules: Option<&[Block]>) {
for block in rules.unwrap_or(&[]) {
self.inside(Some(block.pos), block.rule_id.as_ref(), |e| e.block(block));
}
}
fn block(&mut self, block: &Block) {
let lines = matches!(block.kind, BlockKind::Code | BlockKind::Html);
let consumers = consumers(block);
for (i, text) in block.examples.iter().enumerate() {
for rule in &consumers {
let problem = item(i, &block.examples, self.unit(block, rule, text, lines));
self.said_of(text, block.common.line, "TL_64", problem);
let problem = item(
i,
&block.examples,
derived_unit(self.schema, &self.labels, block, rule, text),
);
self.said_of(text, block.common.line, "TL_127", problem);
}
if block.units().next().is_none() {
let (bare, found) = self.label_of(block, None, text);
let problem = self.label_problem(block, None, text, &bare, found.as_ref());
self.said_of(
text,
block.common.line,
"TL_64",
item(i, &block.examples, problem),
);
}
}
for rule in block.units() {
self.units(block, rule, lines);
}
if let Some(rules) = &block.rules {
self.grammar(block, rules);
}
self.blocks(block.blocks.as_deref());
}
fn units(&mut self, block: &Block, rule: &Unit, lines: bool) {
for (i, text) in rule.examples.iter().enumerate() {
let problem = item(i, &rule.examples, self.unit(block, rule, text, lines));
self.inside(None, rule.rule_id.as_ref(), |e| {
e.said_of(text, rule.common.line, "TL_64", problem);
});
}
let examples = examples_of(self.schema, rule);
for (i, text) in examples.iter().enumerate() {
let problem = item(
i,
&examples,
derived_unit(self.schema, &self.labels, block, rule, text),
);
self.inside(None, rule.rule_id.as_ref(), |e| {
e.said_of(text, rule.common.line, "TL_127", problem);
});
}
for line in rule.lines.iter().flatten() {
self.units(block, line, lines);
}
if let Some(lines) = &rule.lines {
self.grammar(block, lines);
}
self.blocks(rule.blocks.as_deref());
}
fn grammar(&mut self, block: &Block, rules: &[Unit]) {
for (i, rule) in rules.iter().enumerate() {
if !rule.is_production() {
continue;
}
let examples = examples_of(self.schema, rule);
for (n, text) in examples.iter().enumerate() {
if let Some(earlier) = rules[..i].iter().position(|r| {
r.is_production() && has_shape(self.schema, &self.labels, block, r, text)
}) {
let problem = Some(format!(
"the example {} is taken by the rule at line {} first, so this rule takes nothing: order the rules from the narrowest",
text::code(text),
rules[earlier].common.line
));
self.inside(None, rule.rule_id.as_ref(), |e| {
e.say(rule.common.line, "TLMD_58", item(n, &examples, problem));
});
}
}
}
}
}
fn item(i: usize, examples: &[String], problem: Problem) -> Problem {
let reason = problem?;
if examples.len() > 1 {
Some(format!("item {} of `example`: {reason}", i + 1))
} else {
Some(reason)
}
}
fn examples_of(schema: &Schema, rule: &Unit) -> Vec<String> {
if !rule.examples.is_empty() {
return rule.examples.clone();
}
rule.format
.as_ref()
.and_then(|n| schema.formats_of(rule).get(n))
.map(|f| vec![f.first_example().to_string()])
.unwrap_or_default()
}
fn has_shape(schema: &Schema, words: &Words, block: &Block, rule: &Unit, text: &str) -> bool {
let (bare, _) = schema.unlabelled(words, block, Some(rule), &rule.read_text(text));
rule.fits(schema.formats_of(rule), &bare, |_| None)
}
impl Examples<'_> {
fn label_of(
&self,
block: &Block,
rule: Option<&Unit>,
text: &str,
) -> (String, Option<crate::grammar::Found>) {
self.schema.unlabelled(&self.labels, block, rule, text)
}
fn label_problem(
&self,
block: &Block,
rule: Option<&Unit>,
text: &str,
bare: &str,
found: Option<&crate::grammar::Found>,
) -> Problem {
if self.labels.is_empty() || !carries_labels(block.kind) {
return None;
}
let listed = self.labels.listed();
match (block.label_of(rule), found) {
(Some(Label::Required), None) => Some(format!(
"the example {} carries no label, and its rule requires one: {listed}",
text::code(text)
)),
(None, Some(f)) => Some(format!(
"the example {} carries the label `[{}]`, and its rule declares no `label`",
text::code(bare),
f.words
)),
(Some(_), Some(f)) if !self.labels.accepts(&f.words) => Some(format!(
"the label `[{}]` of the example {} is none of the labels of the schema: {listed}",
f.words,
text::code(bare)
)),
_ => None,
}
}
fn unit(&self, block: &Block, rule: &Unit, text: &str, lines: bool) -> Problem {
if lines {
return unit(self.schema, rule, text, &squash(text), None, lines);
}
let (bare, found) = self.label_of(block, Some(rule), &rule.read_text(text));
let shown = if found.is_some() { bare.as_str() } else { text };
let quote = found
.is_none()
.then(|| written(text, &rule.reading_of(text)));
unit(self.schema, rule, shown, &bare, quote.as_ref(), lines)
.or_else(|| self.label_problem(block, Some(rule), text, &bare, found.as_ref()))
}
}
fn unit(
schema: &Schema,
rule: &Unit,
text: &str,
bare: &str,
quote: Option<&label::Read>,
lines: bool,
) -> Problem {
let squashed = bare.to_string();
if let Some(select) = &rule.select
&& !select.is_match(&squashed)
{
return Some(format!(
"the example {} does not match `select-pattern` {}, so this rule would not govern it",
text::code(text),
text::code(select.as_str())
));
}
if let Some(shape) = rule.matcher()
&& !matches!(shape, Shape::Text(Text::From(_)))
&& !shape.matches(&squashed, |_| None)
{
let written = rule.shape.as_ref().filter(|s| matches!(s, Shape::Text(_)));
let failure = match (written, quote) {
(Some(text), _) => text.failure(&squashed),
(None, Some(q)) => q.quoting(|q| shape.failure_quoting(&squashed, q)),
(None, None) => shape.failure(&squashed),
};
return Some(format!("the example {} {failure}", text::code(text)));
}
let format = rule.format_in(schema.formats_of(rule));
let code = if lines || !rule.bans_in(schema.formats_of(rule)) {
Vec::new()
} else if rule.reads_row {
row_code_spans(&squashed)
} else {
markdown::code_spans_in(&squashed)
};
let masked = markdown::mask_code(&squashed, &code);
if let Some(reason) =
refused_masked(&squashed, &masked, &rule.prohibited_patterns, "line", None)
{
return Some(format!(
"the example {} is refused: {reason}",
text::code(text)
));
}
if let Some(name) = &rule.format {
match format.map(|f| (f, f.check_masked(&squashed, &masked, "line"))) {
Some((f, FormatMatch::Fail(reason) | FormatMatch::Refused(reason))) => {
let reason = if f.examples().contains(&text) {
without_example(&reason)
} else {
&reason
};
return Some(format!("the example {} {reason}", text::code(text)));
}
Some((f, FormatMatch::Ok(None))) if f.key.is_some() && !rule.key_optional => {
return Some(format!(
"the example {} carries no key: the format `{name}` captures `{}`",
text::code(text),
f.key.clone().unwrap_or_default()
));
}
_ => {}
}
}
if let Some(k) = &rule.key
&& !rule.key_optional
&& let Some(shape) = rule.matcher()
&& captured(shape, k, &squashed).is_none()
{
return Some(format!(
"the example {} captures no `key` `{k}`",
text::code(text)
));
}
None
}
fn without_example(reason: &str) -> &str {
reason
.rsplit_once("; a line of this kind reads ")
.or_else(|| reason.rsplit_once(" A line of this kind reads "))
.map_or(reason, |(why, _)| why)
}
fn consumers(block: &Block) -> Vec<&Unit> {
block
.units()
.filter(|r| {
!matches!(r.shape, Some(Shape::Text(_))) && r.examples.is_empty() && r.format.is_none()
})
.collect()
}
fn written(text: &str, reading: &Reading) -> label::Read {
label::Read {
squashed: Squashed::mapped(&reading.text, &reading.map),
label: None,
shown: Squashed::new(text),
}
}
fn heading(section: &Section) -> Problem {
let text = section.heading.example.as_ref()?;
let shape = §ion.heading.read;
let quote = written(text, &markdown::reading(text));
let read = quote.squashed.text.as_str();
if matches!(shape, Shape::Text(_)) || shape.matches(read, |_| None) {
return None;
}
let failure = quote.quoting(|q| shape.failure_quoting(read, q));
Some(format!("the example {} {failure}", text::code(text)))
}
fn frontmatter(key: &str, constraint: &FrontmatterConstraint) -> Problem {
let text = constraint.example.as_ref()?;
let said = |reason: String| Some(format!("the example of `{key}` {reason}"));
if let Some(c) = &constraint.const_
&& c != text
{
return said(format!("is not the `const` {c}", c = text::code(c)));
}
if let Some(shape) = &constraint.shape
&& constraint.id_template.is_none()
&& !shape.matches(&squash(text), |_| None)
{
return said(shape.failure(&squash(text)));
}
if let Some(values) = &constraint.enum_
&& !values.contains(text)
{
return said(format!("is not one of {}", text::code_list(values, ", ")));
}
match constraint.format {
Some(FmFormat::Slug) if !is_slug(text) => return said("is not a slug".into()),
Some(FmFormat::Url) if !is_url(text) => return said("is not a URL".into()),
_ => {}
}
if let Some(template) = &constraint.id_template
&& !template.matches(text)
{
return said("does not match the id template".into());
}
None
}