use tramlines_md::{
check::{Counts, LimitFacts, LimitSubject, RuleName},
markdown::BlockKind,
};
use super::front::guidance_comment;
use crate::{
Model,
config::{Texts, fill_template, placeholders},
grammar::{Compiled, Limit, LimitKind, SokfSchema, squash},
model::Manifest,
};
#[derive(Debug, Clone)]
pub struct Words<'a> {
texts: &'a Texts,
language: String,
}
impl<'a> Words<'a> {
pub fn new(texts: &'a Texts, language: impl Into<String>) -> Self {
Words {
texts,
language: language.into(),
}
}
pub fn description(&self) -> Option<String> {
let rule = squash(self.texts.words(&self.language, "description")?);
(!rule.is_empty()).then_some(rule)
}
pub fn label(&self, key: &str) -> Option<String> {
self.texts.label(&self.language, key)
}
pub fn attribution(&self, key: &str) -> Option<String> {
self.texts.attribution(&self.language, key)
}
pub fn limit_lead(&self, facts: &LimitFacts<'_>) -> Option<String> {
let name = match facts.subject {
LimitSubject::Rule {
name: Some(RuleName::Format(n) | RuleName::RuleId(n)),
..
} => Some(n),
_ => None,
};
self.lead(facts.kind, facts.count, unit_of(&facts.subject), name)
}
pub fn link_lead(&self, limit: &Limit, rel: &str) -> Option<String> {
self.lead(limit.kind, limit.count, "link", Some(rel))
}
fn lead(
&self,
kind: LimitKind,
count: usize,
unit: &str,
name: Option<&str>,
) -> Option<String> {
let lang = self.language.as_str();
let template = match (kind, count) {
(LimitKind::Hard, 0) => "limit.ban",
(LimitKind::Hard, _) => "limit.hard",
(LimitKind::Soft, _) => "limit.soft",
};
let template = self.texts.words(lang, template)?;
let shown = count.to_string();
if !placeholders(template).contains(&"unit") {
return Some(fill_template(template, &[("count", &shown)]));
}
let noun = || {
let (one, other) = self.texts.forms(lang, unit)?;
Some(if count == 1 { one } else { other })
};
let unit = match name {
Some(name) => {
let rule_unit = self.texts.words(lang, "rule-unit")?;
let noun = if placeholders(rule_unit).contains(&"unit") {
noun()?
} else {
""
};
fill_template(rule_unit, &[("name", name), ("unit", noun)])
}
None => noun()?.to_string(),
};
Some(fill_template(
template,
&[("count", &shown), ("unit", &unit)],
))
}
}
fn unit_of(subject: &LimitSubject<'_>) -> &'static str {
let block = match subject {
LimitSubject::Key(_) => return "value",
LimitSubject::Rule {
counts: Counts::Lines,
..
} => return "line",
LimitSubject::Rule { block, .. } | LimitSubject::Block(block) => *block,
};
match block {
BlockKind::Prose | BlockKind::Blockquote => "paragraph",
BlockKind::BulletList | BlockKind::NumberedList => "item",
BlockKind::Table => "row",
BlockKind::Code => "fence",
BlockKind::Image => "image",
BlockKind::References => "definition",
BlockKind::Group => "repetition",
_ => "unit",
}
}
pub fn language(
model: &Model,
compiled: &Compiled,
schema: &SokfSchema,
type_name: &str,
knowledge: Option<usize>,
fallback: Option<usize>,
) -> String {
let home = knowledge
.filter(|_| type_name != "Schema")
.and_then(|k| compiled.for_type(model, k, type_name))
.map(|(r, _)| r.knowledge)
.or(fallback);
let manifest = home.and_then(|k| model.knowledges[k].manifest.as_ref());
language_of(schema, manifest)
}
fn language_of(schema: &SokfSchema, manifest: Option<&Manifest>) -> String {
let given = |l: &Option<String>| l.clone().filter(|l| !l.is_empty());
given(&schema.core.core.language)
.or_else(|| manifest.and_then(|m| given(&m.primary_language)))
.unwrap_or_else(|| "en".to_string())
}
pub fn with_description(document: &str, rule: &str) -> String {
let lines: Vec<&str> = document.split_inclusive('\n').collect();
if lines.first().map(|l| l.trim_end()) != Some("---") {
return document.to_string();
}
let Some(end) = lines.iter().skip(1).position(|l| l.trim_end() == "---") else {
return document.to_string();
};
let Some(at) = lines[1..=end]
.iter()
.position(|l| l.starts_with("description:"))
.map(|i| i + 1)
else {
return document.to_string();
};
let own = guidance_comment("");
let mut out: Vec<String> = lines.iter().map(|l| (*l).to_string()).collect();
match out[at - 1].strip_prefix(&own) {
Some(rest) => out[at - 1] = format!("{} {rest}", guidance_comment(rule)),
None => out.insert(at, format!("{}\n", guidance_comment(rule))),
}
out.concat()
}
#[cfg(test)]
mod tests {
use super::*;
fn facts(kind: LimitKind, count: usize, subject: LimitSubject<'_>) -> LimitFacts<'_> {
LimitFacts::new(kind, count, subject, None)
}
#[test]
fn a_limit_is_worded_with_its_count_and_its_unit() {
let texts = Texts::english();
let words = Words::new(&texts, "en");
let lead = |f: LimitFacts<'_>| words.limit_lead(&f);
assert_eq!(
lead(facts(
LimitKind::Hard,
9,
LimitSubject::Block(BlockKind::BulletList)
))
.as_deref(),
Some(
"At most 9 items. Never leave out or merge content to stay within the count. When at the limit:"
)
);
assert_eq!(
lead(facts(
LimitKind::Soft,
1,
LimitSubject::Block(BlockKind::Prose)
))
.as_deref(),
Some(
"Usually up to 1 paragraph. Never leave out or merge content to stay within the count. When at the limit:"
)
);
let rule = |counts, name| LimitSubject::Rule {
block: BlockKind::Code,
counts,
name,
};
assert_eq!(
lead(facts(
LimitKind::Hard,
9,
rule(Counts::Lines, Some(RuleName::Format("node")))
))
.as_deref(),
Some(
"At most 9 `node` lines. Never leave out or merge content to stay within the count. When at the limit:"
)
);
assert_eq!(
lead(facts(
LimitKind::Hard,
0,
rule(Counts::Lines, Some(RuleName::RuleId("todo")))
))
.as_deref(),
Some("No `todo` lines. Instead:")
);
let list = LimitSubject::Rule {
block: BlockKind::NumberedList,
counts: Counts::Units,
name: None,
};
assert_eq!(
lead(facts(LimitKind::Hard, 1, list)).as_deref(),
Some(
"At most 1 item. Never leave out or merge content to stay within the count. When at the limit:"
)
);
assert_eq!(
lead(facts(LimitKind::Soft, 3, LimitSubject::Key("tags"))).as_deref(),
Some(
"Usually up to 3 values. Never leave out or merge content to stay within the count. When at the limit:"
)
);
assert_eq!(
lead(facts(
LimitKind::Hard,
1,
LimitSubject::Block(BlockKind::Code)
))
.as_deref(),
Some(
"At most 1 fence. Never leave out or merge content to stay within the count. When at the limit:"
)
);
assert_eq!(
lead(facts(
LimitKind::Hard,
2,
LimitSubject::Block(BlockKind::Group)
))
.as_deref(),
Some(
"At most 2 repetitions. Never leave out or merge content to stay within the count. When at the limit:"
)
);
}
#[test]
fn each_unit_is_a_unit_of_the_texts() {
let kinds = [
BlockKind::Prose,
BlockKind::BulletList,
BlockKind::NumberedList,
BlockKind::Table,
BlockKind::Code,
BlockKind::Blockquote,
BlockKind::Image,
BlockKind::Region,
BlockKind::Html,
BlockKind::ThematicBreak,
BlockKind::References,
BlockKind::Group,
BlockKind::Heading,
];
let mut subjects = vec![LimitSubject::Key("tags")];
for block in kinds {
subjects.push(LimitSubject::Block(block));
for counts in [Counts::Units, Counts::Lines] {
subjects.push(LimitSubject::Rule {
block,
counts,
name: None,
});
}
}
for subject in subjects {
assert!(
crate::config::UNITS.contains(&unit_of(&subject)),
"{subject:?}"
);
}
}
#[test]
fn a_language_without_the_words_gives_none() {
let texts = Texts::english();
let f = facts(LimitKind::Hard, 3, LimitSubject::Block(BlockKind::Table));
assert_eq!(Words::new(&texts, "de").limit_lead(&f), None);
assert_eq!(Words::new(&texts, "de").description(), None);
assert_eq!(
Words::new(&texts, "en-GB").limit_lead(&f).as_deref(),
Some(
"At most 3 rows. Never leave out or merge content to stay within the count. When at the limit:"
)
);
}
#[test]
fn a_template_without_its_unit_needs_no_forms() {
let texts = Texts::default().with(
"de: { limit: { ban: 'Keine. Stattdessen:', hard: 'Höchstens {count}.', \
soft: 'Meist {count} {unit}.' }, rule-unit: '`{name}`' }\n",
);
let words = Words::new(&texts, "de");
let table = LimitSubject::Block(BlockKind::Table);
let lead = |kind, count, subject| words.limit_lead(&facts(kind, count, subject));
assert_eq!(
lead(LimitKind::Hard, 0, table).as_deref(),
Some("Keine. Stattdessen:")
);
assert_eq!(
lead(LimitKind::Hard, 4, table).as_deref(),
Some("Höchstens 4.")
);
let tasks = LimitSubject::Rule {
block: BlockKind::BulletList,
counts: Counts::Units,
name: Some(RuleName::RuleId("tasks")),
};
assert_eq!(
lead(LimitKind::Soft, 9, tasks).as_deref(),
Some("Meist 9 `tasks`.")
);
assert_eq!(lead(LimitKind::Soft, 9, table), None);
let part_of = Limit {
kind: LimitKind::Hard,
count: 0,
when_at_limit: String::new(),
};
assert_eq!(
words.link_lead(&part_of, "part-of").as_deref(),
Some("Keine. Stattdessen:")
);
}
#[test]
fn the_rule_for_a_description_opens_the_line_before_the_key() {
let own =
"---\ntype: Note\n# sokf:guidance The note says why.\ndescription: Why.\n---\n\nBody\n";
assert_eq!(
with_description(own, "The rule."),
"---\ntype: Note\n# sokf:guidance The rule. The note says why.\ndescription: Why.\n---\n\nBody\n"
);
let bare = "---\ntype: Note\ndescription: Why.\n---\n";
assert_eq!(
with_description(bare, "The rule."),
"---\ntype: Note\n# sokf:guidance The rule.\ndescription: Why.\n---\n"
);
for text in [
"---\ntype: Note\n---\n\ndescription: x\n",
"# Title\n",
"---\ntype: Note\n",
] {
assert_eq!(with_description(text, "The rule."), text);
}
}
}