use crate::{
grammar::{Block, DerivationSource, KeyDerivation, KeyText, Schema, Unit, Words},
markdown::Reading,
text,
};
type Problem = Option<String>;
pub(super) fn derived_unit(
schema: &Schema,
words: &Words,
block: &Block,
rule: &Unit,
text: &str,
) -> Problem {
let kd = rule.key_derives_from.as_ref()?;
let key = schema.example_key(words, block, rule, text);
derived(schema, kd, key, rule.reader())
}
pub(super) fn derived(
schema: &Schema,
kd: &KeyDerivation,
key: Option<KeyText>,
read: fn(&str) -> Reading,
) -> Problem {
let key = key?;
let sep = &kd.separator;
let parents = schema.parent_examples(kd, read, key.verbatim);
if parents.is_empty() || key.parent_in(kd, &parents).is_some() {
return None;
}
let (of, mut named): (String, Vec<String>) = match &kd.source {
DerivationSource::From(k) => (
format!("the value that the scaffold writes for the frontmatter `{k}`"),
parents.iter().map(|p| text::code(p.written())).collect(),
),
DerivationSource::Rule(r) => (
format!("a key of an example of set `{r}`"),
parents.iter().map(|p| text::code(&p.read)).collect(),
),
};
let mut seen = std::collections::HashSet::new();
named.retain(|n| seen.insert(n.clone()));
Some(format!(
"the key {} of the example does not start with {}, {of}, followed by the separator {}",
text::code(&key.read),
named.join(" or "),
text::code(sep)
))
}