use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::lang::Flm;
use crate::model::element::element_value;
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::latex::construct::{
ARG_SLOT, DEFINITION, ENVIRONMENT as ENVIRONMENT_CONSTRUCT, MACRO, RAW,
};
use crate::stdlib::backends::latex::{
LatexArgShape, LatexDefinitionKind, LatexDefinitionPayload, LatexEnvironmentPayload,
LatexMacroPayload, LatexPreambleDef, LatexRawPayload, packages, preamble,
};
use crate::stdlib::backends::latex_recomposed::{BACKEND, LatexRecomposedRenderOptions};
use crate::stdlib::backends::lowering::lower_arg_named_or_nothing;
use crate::stdlib::backends::pres::BODY_SLOT;
use crate::stdlib::features::refs::{
self, SAFE_LABELS, SafeLabels, VALUE_SAFE_LABELS, ValueSafeLabels, ZCREF_COMMAND,
stage_spelling, target_spelling,
};
use super::FEATURE;
use super::elements::{THEOREM, TITLE_ARG, TheoremElement, TitleReading, has_noproofref, title_reading};
use super::heading::{Headings, NAME_ELEMENT, RELATION, TITLE_POINTER};
pub const THEOREM_LATEX_RULE: &str = "flm.theorems.theorem.lower.latex-recomposed";
pub const NAME_LATEX_RULE: &str = "flm.theorems.name.lower.latex-recomposed";
pub const TITLE_POINTER_LATEX_RULE: &str = "flm.theorems.title-pointer.lower.latex-recomposed";
pub const RELATION_LATEX_RULE: &str = "flm.theorems.relation.lower.latex-recomposed";
pub const NOPROOFREF_COMMAND: &str = "noproofref";
pub const PROOF_TITLE_COMMAND: &str = "flmProofTitle";
pub const PIECE_NAME: &str = "theorems";
pub const PIECE: &str = "flm.latex.def.theorems";
pub const AUTHORED_PIECE_NAME: &str = "theorems.authored";
pub const AUTHORED_PIECE: &str = "flm.latex.def.theorems.authored";
pub const RESOLVED_PIECE_NAME: &str = "theorems.resolved";
pub const RESOLVED_PIECE: &str = "flm.latex.def.theorems.resolved";
pub const PHFTHM_SHARED_COUNTER: &str = "phfthmcounter";
pub const SHARED_LATEX_COUNTER: &str = "flmtheorem";
pub fn definition_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
PIECE_NAME,
"\
% Theorems. \\noproofref, written after a statement's labels, says that no proof
% of the statement is coming; defined here as nothing where no package (phfthm)
% defined it first.
\\ProvideDocumentCommand\\noproofref{}{}
% The kinds of a class are set in the theorem style of the class's name. The
% shipped class definitionlike is set in amsthm's definition style (upright);
% declare a theorem style of that name before loading this file to change it.
\\ifcsname th@definitionlike\\endcsname\\else\\newtheoremstyle{definitionlike}{}{}{\\normalfont}{}{\\bfseries}{.}{5pt plus 1pt minus 1pt}{}\\fi
",
"`\\noproofref`: a statement with no proof coming, defined as nothing where no package \
defined it; the theorem style of the shipped class `definitionlike`",
)
}
pub fn authored_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
AUTHORED_PIECE_NAME,
"\
% \\flmProofTitle{<title>}: what a proof's heading sets for a title the document
% wrote, which is written as its argument inside the proof environment's
% optional argument. phfthm reads that argument as the thing the proof proves
% and words the heading itself (Proof of <title>), so by default the title
% alone. Redefine \\flmProofTitle to set a proof's title differently.
\\ProvideDocumentCommand\\flmProofTitle{m}{#1}
",
"`\\flmProofTitle`, the LaTeX hook of a proof's title, setting the title alone, which \
`phfthm` words as the thing the proof proves",
)
.requires([packages::PHFTHM])
}
pub fn resolved_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
RESOLVED_PIECE_NAME,
"\
% \\flmProofTitle{<title>}: what a proof's heading sets for a title -- one the
% document wrote, or the statement the proof refers back to -- which is written
% as its argument inside the proof environment's optional argument, the whole
% heading amsthm sets. By default Proof (<title>), \\proofname being the word
% amsthm defines. Redefine \\flmProofTitle to set a proof's title differently;
% \\renewcommand\\flmProofTitle[1]{#1} sets the title alone.
\\ProvideDocumentCommand\\flmProofTitle{m}{\\proofname\\space (#1)}
",
"`\\flmProofTitle`, the LaTeX hook of a proof's title, setting `Proof (<title>)` as the \
whole heading `amsthm` sets",
)
.requires([packages::AMSTHM])
}
fn reference_hook(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
key: Vec<BuildId>,
) -> Result<BuildId, LowerError> {
let command = if lw.option::<LatexRecomposedRenderOptions>()?.label_hooks {
lw.require(&Name::from(preamble::REFS));
preamble::REF_COMMAND
} else {
lw.require(&Name::from(packages::ZREF_CLEVER));
ZCREF_COMMAND
};
lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(command, [LatexArgShape::Mandatory]),
vec![(String::from(ARG_SLOT), key)],
)
}
fn proof_title(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
title: Vec<BuildId>,
) -> Result<BuildId, LowerError> {
command(cx, lw, PROOF_TITLE_COMMAND, vec![LatexArgShape::Mandatory], vec![title])
}
#[derive(Debug)]
pub struct TheoremLatexRule {
headings: Arc<Headings>,
}
impl TheoremLatexRule {
fn title(
&self,
node: &NodeRef<'_, Flm>,
value: &TheoremElement,
resolved: bool,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Option<Vec<BuildId>>, LowerError> {
match title_reading(node).unwrap_or(TitleReading::Absent) {
TitleReading::Absent => Ok(None),
TitleReading::Title | TitleReading::Malformed => {
let title = lower_arg_named_or_nothing(cx, lw, node, TITLE_ARG)?;
if value.class.relation_ref {
Ok(Some(vec![proof_title(cx, lw, title)?]))
} else {
Ok(Some(title))
}
}
TitleReading::Unknown => Err(LowerError::PlaceholderCharacters),
TitleReading::Relation { text, label, shown } if !resolved => {
let stars = if shown { "*" } else { "**" };
let mut title = vec![raw(cx, lw, stars)?];
let spelling = target_spelling(lw, &text, Some(&label))?;
title.extend(stage_spelling(cx, lw, &spelling)?);
Ok(Some(title))
}
TitleReading::Relation { text, label, shown } => {
if !shown {
return Ok(None);
}
let spelling = target_spelling(lw, &text, Some(&label))?;
let key = stage_spelling(cx, lw, &spelling)?;
let reference = reference_hook(cx, lw, key)?;
Ok(Some(vec![proof_title(cx, lw, vec![reference])?]))
}
}
}
}
impl Lower for TheoremLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let value = element_value::<TheoremElement>(&node)
.ok_or_else(|| LowerError::structure("a theorem without its element's data"))?;
let resolved = lw.option::<LatexRecomposedRenderOptions>()?.resolved_proof_refs;
lw.require(&Name::from(PIECE));
lw.require(&Name::from(if resolved { RESOLVED_PIECE } else { AUTHORED_PIECE }));
let declarations = self.declarations(value, resolved, cx, lw)?;
let mut shapes = Vec::new();
let mut slots = Vec::new();
if let Some(title) = self.title(&node, value, resolved, cx, lw)? {
shapes.push(LatexArgShape::Optional);
slots.push((String::from(ARG_SLOT), title));
}
let mut labels = Vec::new();
for written in refs::label_uses(&node) {
labels.push(refs::stage_label(cx, lw, &written.text, written.label.as_ref())?);
}
let mut body = refs::stage_label_group(cx, lw, labels, false)?;
if has_noproofref(&node) {
body.push(lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(NOPROOFREF_COMMAND, []),
Vec::new(),
)?);
}
body.extend(lw.lower_body(cx, &node)?);
slots.push((String::from(BODY_SLOT), body));
let environment = lw.pres_slots_with(
cx,
&ElementName::from(ENVIRONMENT_CONSTRUCT),
LatexEnvironmentPayload::new(value.name.as_str(), shapes),
slots,
)?;
let mut staged = declarations;
staged.push(environment);
Ok(Lowering::Emit(staged))
}
}
const PLAIN_STYLE_PARAMETERS: &str = "{}{}{\\itshape}{}{\\bfseries}{.}{5pt plus 1pt minus 1pt}{}";
fn raw(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, text: &str) -> Result<BuildId, LowerError> {
lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
}
fn command(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
name: &str,
shapes: Vec<LatexArgShape>,
slots: Vec<Vec<BuildId>>,
) -> Result<BuildId, LowerError> {
lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(name, shapes),
slots.into_iter().map(|slot| (String::from(ARG_SLOT), slot)).collect(),
)
}
fn declaration(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
guard: &str,
body: Vec<BuildId>,
) -> Result<BuildId, LowerError> {
let payload =
LatexDefinitionPayload::new(LatexDefinitionKind::Declaration, guard, 0).of_feature(FEATURE);
lw.pres_slots_with(
cx,
&ElementName::from(DEFINITION),
payload,
vec![(String::from(BODY_SLOT), body)],
)
}
impl TheoremLatexRule {
fn declarations(
&self,
value: &TheoremElement,
resolved: bool,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Vec<BuildId>, LowerError> {
let mut staged = Vec::new();
let shared = value.counter.is_some() && value.class.shared_counter;
if resolved && shared {
let body = vec![raw(cx, lw, &format!("\\newcounter{{{SHARED_LATEX_COUNTER}}}"))?];
staged.push(declaration(cx, lw, &format!("c@{SHARED_LATEX_COUNTER}"), body)?);
}
staged.extend(self.kind_declarations(value, resolved, cx, lw)?);
Ok(staged)
}
fn kind_declarations(
&self,
value: &TheoremElement,
resolved: bool,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Vec<BuildId>, LowerError> {
let mut staged = Vec::new();
if value.counter.is_some() {
let class = value.class_name.as_str();
let body = vec![raw(
cx,
lw,
&format!("\\newtheoremstyle{{{class}}}{PLAIN_STYLE_PARAMETERS}"),
)?];
staged.push(declaration(cx, lw, &format!("th@{class}"), body)?);
}
staged.push(self.declaration(value, resolved, cx, lw)?);
Ok(staged)
}
fn declaration(
&self,
value: &TheoremElement,
resolved: bool,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<BuildId, LowerError> {
let env = value.name.as_str();
let word = self.headings.word(&value.name)?;
let word = lw.splice(cx, &word)?;
let (mandatory, optional) = (LatexArgShape::Mandatory, LatexArgShape::Optional);
let mut body = match (value.counter.is_some(), resolved) {
(true, false) => {
let mut keys = format!("thmstyle={}", value.class_name);
if value.class.shared_counter {
keys.push_str(&format!(",counter={PHFTHM_SHARED_COUNTER}"));
}
if !value.kind.expects_proof {
keys.push_str(",proofref=false");
}
let keys = vec![raw(cx, lw, &keys)?];
let name = vec![raw(cx, lw, env)?];
let mut body =
vec![command(cx, lw, "phfMakeTheorem", vec![optional, mandatory, mandatory], vec![keys, name, word])?];
if value.class.shared_counter {
let word = self.headings.word(&value.name)?;
let word = lw.splice(cx, &word)?;
body.push(raw(
cx,
lw,
&format!("\\expandafter\\providecommand\\csname phfthm@{env}autorefname\\endcsname{{"),
)?);
body.extend(word);
body.push(raw(cx, lw, "}")?);
}
body
}
(false, false) => {
let mut name = vec![raw(cx, lw, "defaultproofname={")?];
name.extend(word);
name.push(raw(cx, lw, "}")?);
let env = vec![raw(cx, lw, env)?];
vec![command(cx, lw, "phfMakeProofEnv", vec![optional, mandatory], vec![name, env])?]
}
(true, true) => {
let style = vec![raw(cx, lw, value.class_name.as_str())?];
let style = command(cx, lw, "theoremstyle", vec![mandatory], vec![style])?;
let name = vec![raw(cx, lw, env)?];
let theorem = if value.class.shared_counter {
let counter = vec![raw(cx, lw, SHARED_LATEX_COUNTER)?];
command(cx, lw, "newtheorem", vec![mandatory, optional, mandatory], vec![name, counter, word])?
} else {
command(cx, lw, "newtheorem", vec![mandatory, mandatory], vec![name, word])?
};
vec![
raw(cx, lw, "\\edef\\flm@thm@style{\\the\\thm@style}")?,
style,
theorem,
raw(cx, lw, "\\thm@style\\expandafter{\\flm@thm@style}")?,
]
}
(false, true) => {
let mut body = vec![raw(cx, lw, &format!("\\newenvironment{{{env}}}[1][{{"))?];
body.extend(word);
body.push(raw(cx, lw, "}]{\\begin{proof}[{#1}]}{\\end{proof}}")?);
body
}
};
if value.counter.is_some() {
body.extend(self.reference_type(value, resolved, cx, lw)?);
}
declaration(cx, lw, env, body)
}
fn reference_type(
&self,
value: &TheoremElement,
resolved: bool,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Vec<BuildId>, LowerError> {
let env = value.name.as_str();
let counters = match (value.class.shared_counter, resolved) {
(true, false) => vec![env.to_string(), format!("phfthm@{env}")],
(false, true) => vec![env.to_string()],
(false, false) => vec![format!("phfthm@{env}")],
(true, true) => vec![SHARED_LATEX_COUNTER.to_string()],
};
let mapping: Vec<String> = counters.iter().map(|counter| format!("{counter}={env}")).collect();
let mapping = mapping.join(",");
let words = self.headings.reference_words(&value.name)?;
let mut body = refs::stage_reference_type_setup(cx, lw, env, &words)?;
body.push(raw(
cx,
lw,
&format!("\\AddToHook{{env/{env}/begin}}{{\\zcsetup{{countertype={{{mapping}}}}}}}"),
)?);
Ok(body)
}
}
#[derive(Debug, Default, Clone, Copy)]
struct HeadingNodeLatexRule;
impl Lower for HeadingNodeLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
Ok(Lowering::Emit(lw.lower_body(cx, &node)?))
}
}
fn heading_node_latex_rules() -> [LoweringRule; 3] {
[(NAME_LATEX_RULE, NAME_ELEMENT), (TITLE_POINTER_LATEX_RULE, TITLE_POINTER), (RELATION_LATEX_RULE, RELATION)]
.map(|(name, element)| {
LoweringRule::new(
name,
element,
LoweringDecl::new(),
Arc::new(HeadingNodeLatexRule),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"a node of a theorem's heading lowers to its own body; the recomposed LaTeX \
instantiates no heading, because LaTeX writes a theorem's heading, so the node \
never reaches this backend",
)
})
}
fn latex_rule(headings: Arc<Headings>) -> LoweringRule {
LoweringRule::new(
THEOREM_LATEX_RULE,
THEOREM,
LoweringDecl::new()
.reads_opt(SAFE_LABELS)
.reads_opt(VALUE_SAFE_LABELS)
.option::<LatexRecomposedRenderOptions>()
.produces(DEFINITION)
.produces(ENVIRONMENT_CONSTRUCT)
.produces(MACRO)
.produces(RAW),
Arc::new(TheoremLatexRule { headings }),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"a theorem lowers to the environment of its kind's name around its title, its \
labels in the LaTeX hook `\\flmLabels`, `\\noproofref` where written, and its body, \
with the kind's declaration for the style file; a proof's title is written in the \
LaTeX hook `\\flmProofTitle`, and its back-reference as written, or, under the \
render option `resolved_proof_refs`, as a reference in `\\flmProofTitle`",
)
}
pub(super) fn register(b: &mut FeatureBuilder<'_>, headings: Arc<Headings>) -> Result<(), BuildError> {
b.peer_backend(
BACKEND,
"the latex-recomposed backend, on which the feature's LaTeX rules are the default",
)?;
b.peer_element::<LatexDefinitionPayload>(
DEFINITION,
"the LaTeX family's definition construct, which the theorem's rule stages for the \
declarations of the kinds",
)?;
b.peer_element::<LatexEnvironmentPayload>(
ENVIRONMENT_CONSTRUCT,
"the LaTeX family's environment construct, which the theorem's rule stages",
)?;
b.peer_element::<LatexMacroPayload>(
MACRO,
"the LaTeX family's macro-call construct, which the rules stage for the labels, \
`\\noproofref`, and the LaTeX hooks `\\flmProofTitle` (a proof's title) and `\\flmRef` \
(a reference)",
)?;
b.peer_element::<LatexRawPayload>(
RAW,
"the LaTeX family's raw node construct, in which the theorem's rule writes a \
back-reference's stars, the declarations' fixed LaTeX, and a label whose label type \
the references feature marks as raw (written byte for byte)",
)?;
b.peer_table::<SafeLabels>(
SAFE_LABELS.name(),
"the references feature's safe-labels table, which the rules read for the safe label \
written for a label",
)?;
b.peer_table::<ValueSafeLabels>(
VALUE_SAFE_LABELS.name(),
"the references feature's value names, which the rules read for the safe label of a \
back-reference in a proof inside a synthesized value",
)?;
b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece()))?;
b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(authored_piece()))?;
b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(resolved_piece()))?;
b.lowering_rule(latex_rule(headings))?;
for rule in heading_node_latex_rules() {
b.lowering_rule(rule)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stdlib::backends::latex::preamble::piece_id;
#[test]
fn the_piece_is_named_as_its_identifier_says_and_provides_noproofref() {
let piece = definition_piece();
assert_eq!(piece.id, piece_id(PIECE_NAME));
assert_eq!(piece.id.as_str(), PIECE);
assert!(piece.content.contains("\\ProvideDocumentCommand\\noproofref{}{}"));
assert!(!piece.content.contains("flmProofTitle"));
assert!(piece.requires.is_empty());
}
#[test]
fn each_form_s_piece_provides_the_proof_title_hook_with_its_own_default() {
let authored = authored_piece();
assert_eq!(authored.id, piece_id(AUTHORED_PIECE_NAME));
assert_eq!(authored.id.as_str(), AUTHORED_PIECE);
assert!(authored.content.contains("\\ProvideDocumentCommand\\flmProofTitle{m}{#1}\n"));
assert_eq!(authored.requires, [Name::from(packages::PHFTHM)]);
let resolved = resolved_piece();
assert_eq!(resolved.id, piece_id(RESOLVED_PIECE_NAME));
assert_eq!(resolved.id.as_str(), RESOLVED_PIECE);
assert!(
resolved.content.contains("\\ProvideDocumentCommand\\flmProofTitle{m}{\\proofname\\space (#1)}\n")
);
assert_eq!(resolved.requires, [Name::from(packages::AMSTHM)]);
}
}