use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
spelling_at_lowering,
};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::lang::Flm;
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::latex::construct::{
ARG_SLOT, BEGIN_SLOT, DEFINITION, END_SLOT, 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, spelling_identity};
use crate::stdlib::features::refs::{
self, SAFE_LABELS, SafeLabels, VALUE_SAFE_LABELS, ValueSafeLabels, stage_spelling,
target_spelling,
};
use super::FEATURE;
use super::diagnostics::EmptyTerm;
use super::elements::{
DEFTERM, SHOWN_ARG, TERM, TERM_ARG, computed_labels, decide_term, written_term,
};
use super::lead_in::{LeadIn, TERM_POINTER, lead_in_instance};
pub const DEFINITION_LATEX_RULE: &str = "flm.defterm.lower.latex-recomposed";
pub const TERM_LATEX_RULE: &str = "flm.term.lower.latex-recomposed";
pub const POINTER_LATEX_RULE: &str = "flm.defterm.term-pointer.lower.latex-recomposed";
pub const ENVIRONMENT: &str = "defterm";
const IGNORE_SPACES_COMMAND: &str = "ignorespaces";
pub const TERM_PARAMETER: &str = "#1";
pub const TERM_COMMAND: &str = "flmTerm";
pub const TERM_IN_DEFTERM_COMMAND: &str = "flmTermInDefterm";
pub const PIECE_NAME: &str = "defterm";
pub const PIECE: &str = "flm.latex.def.defterm";
pub fn definition_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
PIECE_NAME,
"\
% Defined terms. A term definition is written as the environment defterm,
% whose one argument is the term. This file defines the environment further
% below, in the part headed \"definitions written from the configuration of
% FLM features\"; the environment's opening text is the lead-in that the
% document was recomposed with. The body of a term definition opens with
% \\phantomsection, so that a link to the term definition leads to it, and
% with \\flmLabelsWithDisplayText, so that a reference to one of its labels
% prints the term.
% \\flmTerm{<label>}{<shown>}: <shown>, a link to the definition of a term,
% <label> being a label of that definition, as \\flmHyperref takes it.
% \\flmTermInDefterm{<shown>}: <shown> written inside the definition of its
% own term: the term being defined, set apart, with no link.
% Redefine either command to set term links another way.
\\ProvideDocumentCommand\\flmTerm{m m}{\\flmHyperref{#1}{#2}}
\\ProvideDocumentCommand\\flmTermInDefterm{m}{\\emph{#1}}
% What a term link contributes to a PDF bookmark: its text alone. The code
% below runs when the document begins (\\AtBeginDocument) and does nothing
% where hyperref is not loaded.
\\AtBeginDocument{\\ifdefined\\pdfstringdefDisableCommands
\\pdfstringdefDisableCommands{%
\\def\\flmTerm#1#2{#2}%
\\def\\flmTermInDefterm#1{#1}%
}\\fi}
",
"`\\flmTerm{label}{shown}` and `\\flmTermInDefterm{shown}`: the LaTeX hooks of a term \
link; and the package and definition pieces that a term definition requires",
)
.requires([
preamble::HYPERREF,
packages::HYPERREF,
preamble::LABELS,
preamble::LABEL_DISPLAY_TEXT,
preamble::ZREF_CLEVER_TYPE,
])
}
#[derive(Debug)]
pub struct DefinitionLatexRule {
lead_in: Arc<LeadIn>,
}
impl Lower for DefinitionLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let term = node.argument_content_nodes_named(TERM_ARG).ok().flatten();
if term.is_none_or(|content| spelling_identity(content.iter()).is_empty()) {
lw.error(EmptyTerm { what: String::from("defterm") }, node.span().clone());
}
lw.require(&Name::from(PIECE));
let definition = environment_definition(&self.lead_in, &node, cx, lw)?;
let mut labels = Vec::new();
for label in computed_labels(&node) {
labels.push(refs::stage_label(cx, lw, &label.to_string(), Some(&label))?);
}
for written in refs::label_uses(&node) {
labels.push(refs::stage_label(cx, lw, &written.text, written.label.as_ref())?);
}
let hooks = lw.option::<LatexRecomposedRenderOptions>()?.label_hooks;
let labels = refs::stage_label_group(cx, lw, labels, true)?;
let phantom = lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(preamble::PHANTOMSECTION_COMMAND, []),
Vec::new(),
)?;
let mut body = vec![phantom];
if hooks {
let shown = lower_arg_named_or_nothing(cx, lw, &node, TERM_ARG)?;
body.push(refs::stage_labels_with_display_text(cx, lw, shown, labels)?);
} else {
body.extend(labels);
}
body.push(lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(IGNORE_SPACES_COMMAND, []),
Vec::new(),
)?);
body.extend(lw.lower_body(cx, &node)?);
let term = lower_arg_named_or_nothing(cx, lw, &node, TERM_ARG)?;
let environment = lw.pres_slots_with(
cx,
&ElementName::from(ENVIRONMENT_CONSTRUCT),
LatexEnvironmentPayload::new(ENVIRONMENT, [LatexArgShape::Mandatory]),
vec![(String::from(ARG_SLOT), term), (String::from(BODY_SLOT), body)],
)?;
Ok(Lowering::Emit(vec![definition, environment]))
}
}
fn environment_definition(
lead_in: &LeadIn,
node: &NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<BuildId, LowerError> {
let begin = match lead_in_instance(lead_in, node, lw)? {
Some(instance) => lw.splice(cx, &instance)?,
None => Vec::new(),
};
let payload = LatexDefinitionPayload::new(LatexDefinitionKind::Environment, ENVIRONMENT, 1)
.of_feature(FEATURE);
lw.pres_slots_with(
cx,
&ElementName::from(DEFINITION),
payload,
vec![(String::from(BEGIN_SLOT), begin), (String::from(END_SLOT), Vec::new())],
)
}
fn definition_latex_rule(lead_in: Arc<LeadIn>) -> LoweringRule {
LoweringRule::new(
DEFINITION_LATEX_RULE,
DEFTERM,
LoweringDecl::new()
.reads_opt(SAFE_LABELS)
.option::<LatexRecomposedRenderOptions>()
.produces(DEFINITION)
.produces(ENVIRONMENT_CONSTRUCT)
.produces(MACRO)
.produces(RAW),
Arc::new(DefinitionLatexRule { lead_in }),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"a term definition lowers to the environment `defterm` around its term, its body \
opening with `\\phantomsection` and `\\flmLabelsWithDisplayText` over its labels; the \
style file defines the environment from the lead-in template",
)
}
#[derive(Debug, Default, Clone, Copy)]
pub struct TermLatexRule;
impl Lower for TermLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let shown = lower_arg_named_or_nothing(cx, lw, &node, SHOWN_ARG)?;
let Some(decision) = decide_term(&node) else {
if let Some(written) = written_term(&node) {
spelling_at_lowering(written.iter())?;
}
lw.error(EmptyTerm { what: String::from("\\term") }, node.span().clone());
return Ok(Lowering::Emit(vec![term_hook(cx, lw, Vec::new(), shown)?]));
};
if decision.in_own_definition {
lw.require(&Name::from(PIECE));
let hook = lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(TERM_IN_DEFTERM_COMMAND, [LatexArgShape::Mandatory]),
vec![(String::from(ARG_SLOT), shown)],
)?;
return Ok(Lowering::Emit(vec![hook]));
}
let target = decision.target;
let spelling = target_spelling(lw, &target.to_string(), Some(&target))?;
let key = stage_spelling(cx, lw, &spelling)?;
Ok(Lowering::Emit(vec![term_hook(cx, lw, key, shown)?]))
}
}
fn term_hook(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
key: Vec<BuildId>,
shown: Vec<BuildId>,
) -> Result<BuildId, LowerError> {
lw.require(&Name::from(PIECE));
lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(TERM_COMMAND, [LatexArgShape::Mandatory, LatexArgShape::Mandatory]),
vec![(String::from(ARG_SLOT), key), (String::from(ARG_SLOT), shown)],
)
}
fn term_latex_rule() -> LoweringRule {
LoweringRule::new(
TERM_LATEX_RULE,
TERM,
LoweringDecl::new()
.reads_opt(SAFE_LABELS)
.reads_opt(VALUE_SAFE_LABELS)
.produces(MACRO)
.produces(RAW),
Arc::new(TermLatexRule),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"a term link lowers to `\\flmTerm` around its target's safe label and its text, or, \
inside the definition of its own term, to `\\flmTermInDefterm` around its text",
)
}
#[derive(Debug, Default, Clone, Copy)]
pub struct PointerLatexRule;
impl Lower for PointerLatexRule {
fn lower(
&self,
_node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let parameter = lw.pres_with(
cx,
&ElementName::from(RAW),
LatexRawPayload::new(TERM_PARAMETER),
Vec::new(),
)?;
Ok(Lowering::Emit(vec![parameter]))
}
}
pub(super) fn register(b: &mut FeatureBuilder<'_>, lead_in: Arc<LeadIn>) -> 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 term definition's rule stages for \
the environment's LaTeX definition",
)?;
b.peer_element::<LatexEnvironmentPayload>(
ENVIRONMENT_CONSTRUCT,
"the LaTeX family's environment construct, which the term definition's rule stages",
)?;
b.peer_element::<LatexMacroPayload>(
MACRO,
"the LaTeX family's macro-call construct, which the rules stage for the hooks and labels",
)?;
b.peer_element::<LatexRawPayload>(
RAW,
"the LaTeX family's raw node construct, in which the term pointer writes the \
environment's parameter, and a term link 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 term definition's and the term \
link's 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 term link's rule reads for the safe \
label of the target of a term link inside a synthesized value",
)?;
b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece()))?;
let on_latex = || DefaultMark::OnBackends(vec![BACKEND.into()]);
b.lowering_rule(definition_latex_rule(lead_in))?;
b.lowering_rule(term_latex_rule())?;
b.lowering_rule(
LoweringRule::new(
POINTER_LATEX_RULE,
TERM_POINTER,
LoweringDecl::new().produces(RAW),
Arc::new(PointerLatexRule),
on_latex(),
)
.docs(
"a term pointer lowers to the environment's parameter `#1`: it occurs only in the \
lead-in written as the begin code of the environment's LaTeX definition",
),
)?;
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_requests_what_a_definition_uses() {
let piece = definition_piece();
assert_eq!(piece.id, piece_id(PIECE_NAME));
assert_eq!(piece.id.as_str(), PIECE);
assert!(piece.requires.contains(&Name::from(packages::HYPERREF)));
assert!(piece.requires.contains(&Name::from(preamble::LABEL_DISPLAY_TEXT)));
assert!(piece.requires.contains(&Name::from(preamble::ZREF_CLEVER_TYPE)));
assert!(piece.requires.contains(&Name::from(preamble::HYPERREF)));
for hook in [TERM_COMMAND, TERM_IN_DEFTERM_COMMAND] {
assert!(piece.content.contains(&format!("\\ProvideDocumentCommand\\{hook}")));
}
}
}