use std::collections::BTreeMap;
use std::hash::{Hash, Hasher};
use crate::model::names::Name;
use crate::stdlib::features::numbering::{NumberTemplate, PluralWords, PrefixWords};
pub const DEFAULT_HEADING: &str = r"#{name}\IfValueT{#{title}}{ (#{title})}";
pub const DEFAULT_CLOSING_MARK: &str = "\u{25a1}";
pub const DEFAULT_LABEL_TYPES: [&str; 9] =
["thm", "prop", "cor", "lem", "rem", "def", "dfn", "x", "topic"];
pub const LOWERCASE_VARIANT: &str = crate::stdlib::features::refs::LOWERCASE_VARIANT;
pub const CAPITAL_VARIANT: &str = crate::stdlib::features::refs::CAPITAL_VARIANT;
pub const ABBREVIATED_VARIANT: &str = crate::stdlib::features::refs::ABBREVIATED_VARIANT;
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct TheoremClass {
pub numbered: bool,
pub shared_counter: bool,
pub heading: String,
pub closing_mark: Option<String>,
pub relation_ref: bool,
}
impl TheoremClass {
pub fn numbered() -> TheoremClass {
TheoremClass {
numbered: true,
shared_counter: true,
heading: DEFAULT_HEADING.to_string(),
closing_mark: None,
relation_ref: false,
}
}
pub fn unnumbered() -> TheoremClass {
TheoremClass { numbered: false, ..TheoremClass::numbered() }
}
pub fn shared_counter(mut self, shared_counter: bool) -> TheoremClass {
self.shared_counter = shared_counter;
self
}
pub fn heading(mut self, heading: impl Into<String>) -> TheoremClass {
self.heading = heading.into();
self
}
pub fn closing_mark(mut self, closing_mark: Option<String>) -> TheoremClass {
self.closing_mark = closing_mark;
self
}
pub fn relation_ref(mut self, relation_ref: bool) -> TheoremClass {
self.relation_ref = relation_ref;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct TheoremKind {
pub class: Name,
pub words: PrefixWords,
pub expects_proof: bool,
}
impl TheoremKind {
pub fn new(class: impl Into<Name>, words: PrefixWords) -> TheoremKind {
TheoremKind { class: class.into(), words, expects_proof: false }
}
pub fn from_word(class: impl Into<Name>, word: &str) -> TheoremKind {
let plural = format!("{word}s");
TheoremKind::new(class, regular(word, &plural))
}
pub fn expects_proof(mut self, expects_proof: bool) -> TheoremKind {
self.expects_proof = expects_proof;
self
}
}
fn capitalized(text: &str) -> String {
let mut chars = text.chars();
match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect(),
None => String::new(),
}
}
fn regular(one: &str, other: &str) -> PrefixWords {
let capital = PluralWords::new(capitalized(one), capitalized(other));
PrefixWords { base: capital.clone(), variants: BTreeMap::new() }
.with_variant(LOWERCASE_VARIANT, PluralWords::new(one, other))
.with_variant(CAPITAL_VARIANT, capital)
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct TheoremsConfig {
pub classes: BTreeMap<Name, TheoremClass>,
pub kinds: BTreeMap<Name, TheoremKind>,
pub number_format: NumberTemplate,
pub label_types: Vec<String>,
}
impl Default for TheoremsConfig {
fn default() -> TheoremsConfig {
TheoremsConfig::new()
}
}
impl TheoremsConfig {
fn with_shipped_classes() -> TheoremsConfig {
TheoremsConfig {
classes: BTreeMap::new(),
kinds: BTreeMap::new(),
number_format: NumberTemplate::formats("#{arabic}"),
label_types: DEFAULT_LABEL_TYPES.iter().map(|ty| ty.to_string()).collect(),
}
.class("theoremlike", TheoremClass::numbered())
.class("definitionlike", TheoremClass::numbered())
.class(
"prooflike",
TheoremClass::unnumbered()
.closing_mark(Some(DEFAULT_CLOSING_MARK.to_string()))
.relation_ref(true),
)
}
fn shipped(
self,
name: &str,
class: &str,
(one, other): (&str, &str),
abbreviated: (&str, &str),
expects_proof: bool,
) -> TheoremsConfig {
let words = regular(one, other)
.with_variant(ABBREVIATED_VARIANT, PluralWords::new(abbreviated.0, abbreviated.1));
let kind = TheoremKind::new(class, words).expects_proof(expects_proof);
self.kind(name, kind)
}
fn statements(self) -> TheoremsConfig {
self.shipped("theorem", "theoremlike", ("theorem", "theorems"), ("Thm.", "Thms."), true)
.shipped(
"proposition",
"theoremlike",
("proposition", "propositions"),
("Prop.", "Props."),
true,
)
.shipped("lemma", "theoremlike", ("lemma", "lemmas"), ("Lem.", "Lems."), true)
.shipped(
"corollary",
"theoremlike",
("corollary", "corollaries"),
("Cor.", "Cors."),
true,
)
}
fn definition(self) -> TheoremsConfig {
self.shipped(
"definition",
"definitionlike",
("definition", "definitions"),
("Def.", "Defs."),
false,
)
}
fn proof(self) -> TheoremsConfig {
self.shipped("proof", "prooflike", ("proof", "proofs"), ("Proof", "Proofs"), false)
}
pub fn new() -> TheoremsConfig {
TheoremsConfig::with_shipped_classes()
.statements()
.shipped(
"conjecture",
"theoremlike",
("conjecture", "conjectures"),
("Conj.", "Conjs."),
false,
)
.definition()
.shipped("remark", "definitionlike", ("remark", "remarks"), ("Rem.", "Rems."), false)
.proof()
}
pub fn simpleset() -> TheoremsConfig {
TheoremsConfig::with_shipped_classes().statements().definition().proof()
}
pub fn richset() -> TheoremsConfig {
let mut config = TheoremsConfig::new();
for (name, plural, abbreviated) in [
("idea", "ideas", ("Idea", "Ideas")),
("question", "questions", ("Qtn.", "Qtns.")),
("claim", "claims", ("Clm.", "Clms.")),
("observation", "observations", ("Obs.", "Obs.")),
("problem", "problems", ("Prob.", "Probs.")),
] {
config = config.shipped(name, "definitionlike", (name, plural), abbreviated, false);
}
config
}
pub fn empty() -> TheoremsConfig {
TheoremsConfig { classes: BTreeMap::new(), kinds: BTreeMap::new(), ..TheoremsConfig::new() }
}
pub fn kind(mut self, name: impl Into<Name>, kind: TheoremKind) -> TheoremsConfig {
self.kinds.insert(name.into(), kind);
self
}
pub fn without_kind(mut self, name: &str) -> TheoremsConfig {
self.kinds.remove(&Name::from(name));
self
}
pub fn class(mut self, name: impl Into<Name>, class: TheoremClass) -> TheoremsConfig {
self.classes.insert(name.into(), class);
self
}
pub fn number_format(mut self, number_format: NumberTemplate) -> TheoremsConfig {
self.number_format = number_format;
self
}
pub fn label_types(
mut self,
label_types: impl IntoIterator<Item = impl Into<String>>,
) -> TheoremsConfig {
self.label_types = label_types.into_iter().map(Into::into).collect();
self
}
pub fn kind_and_class(&self, name: &str) -> Option<(&TheoremKind, &TheoremClass)> {
let kind = self.kinds.get(&Name::from(name))?;
Some((kind, self.classes.get(&kind.class)?))
}
pub fn validate(&self) -> Result<(), String> {
let cannot_name = |text: &str| {
text.is_empty()
|| text.chars().any(|ch| ch.is_whitespace() || matches!(ch, '{' | '}' | '\\' | '%'))
};
for name in self.classes.keys() {
if cannot_name(name.as_str()) {
return Err(format!(
"the theorem class name `{name}` must not be empty or contain whitespace, \
a brace, a backslash or `%`"
));
}
}
for (name, kind) in &self.kinds {
if cannot_name(name.as_str()) {
return Err(format!(
"the theorem kind name `{name}` must not be empty or contain whitespace, a \
brace, a backslash or `%`, since it is the name of an environment"
));
}
if !self.classes.contains_key(&kind.class) {
return Err(format!(
"the theorem kind `{name}` belongs to the class `{}`, which the \
configuration does not declare",
kind.class
));
}
}
for (name, kind) in self.kinds.iter().filter(|(_, kind)| kind.expects_proof) {
let numbered = self.classes.get(&kind.class).is_some_and(|class| class.numbered);
if !numbered {
return Err(format!(
"the theorem kind `{name}` expects a proof, but its class `{}` is unnumbered \
and accepts no label, so no proof can refer back to it",
kind.class
));
}
if self.label_types.is_empty() {
return Err(format!(
"the theorem kind `{name}` expects a proof, but the configuration declares no \
label types, so no proof can refer back to it"
));
}
}
Ok(())
}
pub fn digest_bytes(&self) -> Vec<u8> {
let TheoremsConfig { classes, kinds, number_format, label_types } = self;
let mut out = Vec::new();
push_len(&mut out, classes.len());
for (name, class) in classes {
let TheoremClass { numbered, shared_counter, heading, closing_mark, relation_ref } = class;
push_text(&mut out, name.as_str());
out.push(u8::from(*numbered));
out.push(u8::from(*shared_counter));
push_text(&mut out, heading);
match closing_mark {
Some(mark) => {
out.push(1);
push_text(&mut out, mark);
}
None => out.push(0),
}
out.push(u8::from(*relation_ref));
}
push_len(&mut out, kinds.len());
for (name, kind) in kinds {
let TheoremKind { class, words, expects_proof } = kind;
push_text(&mut out, name.as_str());
push_text(&mut out, class.as_str());
push_plural(&mut out, &words.base);
push_len(&mut out, words.variants.len());
for (variant, plural) in &words.variants {
push_text(&mut out, variant);
push_plural(&mut out, plural);
}
out.push(u8::from(*expects_proof));
}
match number_format {
NumberTemplate::Formats(text) => {
out.push(0);
push_text(&mut out, text);
}
NumberTemplate::Initial(text) => {
out.push(1);
push_text(&mut out, text);
}
}
push_len(&mut out, label_types.len());
for label_type in label_types {
push_text(&mut out, label_type);
}
out
}
}
fn push_len(out: &mut Vec<u8>, len: usize) {
out.extend_from_slice(&(len as u64).to_le_bytes());
}
fn push_text(out: &mut Vec<u8>, text: &str) {
push_len(out, text.len());
out.extend_from_slice(text.as_bytes());
}
fn push_plural(out: &mut Vec<u8>, plural: &PluralWords) {
push_text(out, &plural.one);
push_text(out, &plural.other);
}
impl Hash for TheoremsConfig {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(&self.digest_bytes());
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_word_is_capitalized_by_its_first_letter() {
assert_eq!(capitalized("lemma"), "Lemma");
assert_eq!(capitalized("énoncé"), "Énoncé");
assert_eq!(capitalized(""), "");
}
#[test]
fn the_digest_bytes_change_with_every_field() {
let base = TheoremsConfig::new();
let changed = [
base.clone().without_kind("remark"),
base.clone().kind("remark", TheoremKind::from_word("definitionlike", "note")),
base.clone().kind(
"remark",
TheoremKind::from_word("definitionlike", "remark").expects_proof(true),
),
base.clone().class("prooflike", TheoremClass::unnumbered()),
base.clone().class("theoremlike", TheoremClass::numbered().shared_counter(false)),
base.clone().class("theoremlike", TheoremClass::numbered().heading("#{name}")),
base.clone().class("theoremlike", TheoremClass::numbered().relation_ref(true)),
base.clone().class(
"theoremlike",
TheoremClass::numbered().closing_mark(Some(String::new())),
),
base.clone().number_format(NumberTemplate::formats("#{roman}")),
base.clone().number_format(NumberTemplate::initial("#{arabic}")),
base.clone().label_types(["thm"]),
];
for other in &changed {
assert_ne!(other.digest_bytes(), base.digest_bytes(), "{other:?}");
}
assert_eq!(TheoremsConfig::new().digest_bytes(), base.digest_bytes());
}
}