use std::collections::BTreeMap;
use std::sync::{Arc, OnceLock};
use techy::core::node::{BuildId, NodeRef, NodeTree};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::core::registry::{BuildError, FeatureBuilder, Finalizer, LateInit, LateInitError};
use crate::lang::rewrites::userdefs::template::{PlaceholderVocabulary, TemplateLanguage};
use crate::lang::{BuiltLang, Flm, FlmDiagnostics};
use crate::model::element::element_value;
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::latex::construct::{ARG_SLOT, DEFINITION, ENVIRONMENT, 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_run, lower_written_pieces};
use crate::stdlib::backends::pres::BODY_SLOT;
use crate::stdlib::features::numbering::{COUNTERS, compile_text, instantiate_fixed};
use crate::stdlib::features::refs::{self, ANCHORS, SAFE_LABELS, SafeLabels};
use super::body::{Caption, is_float_field, read_float};
use super::config::FloatType;
use super::content::Handlers;
use super::elements::FloatElement;
use super::{CAPTION_FIELD, CAPTION_TEXT_ARG, CHECK_HANDLERS, FEATURE, FLOAT, TYPES_SLOT};
pub const LATEX_RULE: &str = "flm.floats.float.lower.latex-recomposed";
pub const PIECE_NAME: &str = "floats";
pub const PIECE: &str = "flm.latex.def.floats";
pub const ENVIRONMENT_NAME: &str = "flmFloat";
pub const SET_USE_CONFIG_PREFIX: &str = "flmFloatSetUseConfig";
pub const PLACEMENT_ARGS_PREFIX: &str = "flmFloatPlacementArgs";
pub const REFERENCE_TYPE_GUARD_PREFIX: &str = "flm@float@reftype@";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FloatCase {
NumCap,
NumOnly,
CapOnly,
Bare,
}
impl FloatCase {
pub const ALL: [FloatCase; 4] =
[FloatCase::NumCap, FloatCase::NumOnly, FloatCase::CapOnly, FloatCase::Bare];
pub fn of(numbered: bool, captioned: bool) -> FloatCase {
match (numbered, captioned) {
(true, true) => FloatCase::NumCap,
(true, false) => FloatCase::NumOnly,
(false, true) => FloatCase::CapOnly,
(false, false) => FloatCase::Bare,
}
}
pub fn as_str(self) -> &'static str {
match self {
FloatCase::NumCap => "NumCap",
FloatCase::NumOnly => "NumOnly",
FloatCase::CapOnly => "CapOnly",
FloatCase::Bare => "Bare",
}
}
pub fn is_numbered(self) -> bool {
matches!(self, FloatCase::NumCap | FloatCase::NumOnly)
}
}
pub fn definition_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
PIECE_NAME,
"\
% Floats: a float of FLM's figure, table or a configured float type is
% written as \\begin{flmFloat}{<type>}{<case>} <content> \\caption{<caption>}
% <labels> \\end{flmFloat}, <case> being NumCap (numbered, with a caption),
% NumOnly (numbered, no caption: an empty \\caption{} shows the number),
% CapOnly (a caption, no number) or Bare (neither).
% \\flmFloatSetUseConfig<case>{<type>}{<placement>}: how a float of the case is
% set. By default a numbered float is set in the environment <type> at
% <placement>, and an unnumbered one where it is written, in a center
% environment in which \\caption works as in the float <type>; a CapOnly
% float's caption is set with no number (\\caption* of the caption package).
% \\flmFloatPlacementArgs<case>: the placement of a float of the case, [tbph]
% for the numbered cases and [h] for the others.
% The content is centered. Redefine these commands to set floats differently.
\\providecommand\\flmFloatPlacementArgsNumCap{[tbph]}
\\providecommand\\flmFloatPlacementArgsNumOnly{[tbph]}
\\providecommand\\flmFloatPlacementArgsCapOnly{[h]}
\\providecommand\\flmFloatPlacementArgsBare{[h]}
\\def\\flm@float@infloat#1#2{\\edef\\flm@float@begin{\\noexpand\\begin{#1}#2}\\def\\flm@float@end{\\end{#1}}}
\\def\\flm@float@incenter#1{\\def\\flm@float@begin{\\begin{center}\\def\\@captype{#1}}\\def\\flm@float@end{\\end{center}}}
\\def\\flm@float@starcaption{\\let\\flm@float@caption\\caption\\def\\caption{\\flm@float@caption*}}
\\ProvideDocumentCommand\\flmFloatSetUseConfigNumCap{m m}{\\flm@float@infloat{#1}{#2}}
\\ProvideDocumentCommand\\flmFloatSetUseConfigNumOnly{m m}{\\flm@float@infloat{#1}{#2}}
\\ProvideDocumentCommand\\flmFloatSetUseConfigCapOnly{m m}{\\flm@float@incenter{#1}\\flm@float@starcaption}
\\ProvideDocumentCommand\\flmFloatSetUseConfigBare{m m}{\\flm@float@incenter{#1}}
\\ProvideDocumentEnvironment{flmFloat}{m m}{%
\\edef\\flm@float@placement{\\csname flmFloatPlacementArgs#2\\endcsname}%
\\csname flmFloatSetUseConfig#2\\endcsname{#1}{\\flm@float@placement}%
\\flm@float@begin\\centering}{\\flm@float@end}
",
"`\\begin{flmFloat}{type}{case}`: the LaTeX hook environment of a float, with \
`\\flmFloatSetUseConfig<case>` and `\\flmFloatPlacementArgs<case>` for each of its four \
cases",
)
.requires([packages::CAPTION])
}
struct ReferenceWords {
keys: Vec<(&'static str, Arc<NodeTree<Flm>>)>,
}
#[derive(Default)]
pub(super) struct TypeWords {
by_type: OnceLock<BTreeMap<Name, ReferenceWords>>,
}
impl std::fmt::Debug for TypeWords {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let names: Vec<&Name> = self.by_type.get().map(|by| by.keys().collect()).unwrap_or_default();
f.debug_struct("TypeWords").field("by_type", &names).finish()
}
}
fn compile_word(
name: &Name,
text: &str,
lang: &BuiltLang,
language: &TemplateLanguage,
) -> Result<Arc<NodeTree<Flm>>, LateInitError> {
let what = format!("the words of the float type `{name}`");
let refused = |detail: String| {
LateInitError::new(format!(
"the word `{text}` of the float type `{name}` is not valid FLM text: {detail}"
))
};
let template = compile_text(text, &what, &PlaceholderVocabulary::new(0), lang, language)
.map_err(|error| refused(error.to_string()))?;
instantiate_fixed(&template).map_err(refused)
}
fn reference_words(
float_type: &FloatType,
lang: &BuiltLang,
language: &TemplateLanguage,
) -> Result<ReferenceWords, LateInitError> {
let mut keys = Vec::new();
for (key, text) in refs::reference_type_words(&float_type.words) {
keys.push((key, compile_word(&float_type.name, text, lang, language)?));
}
Ok(ReferenceWords { keys })
}
struct CollectTypes {
words: Arc<TypeWords>,
}
impl Finalizer for CollectTypes {
fn finalize(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
let types: Vec<FloatType> = match b.services() {
Some(services) => services.services_named::<FloatType>(TYPES_SLOT).cloned().collect(),
None => {
return Err(BuildError::Feature {
feature: b.feature().clone(),
detail: String::from("the types slot must be assembled before the finalizer runs"),
});
}
};
b.late_init(Arc::new(CompileWords { words: Arc::clone(&self.words), types }))
}
}
struct CompileWords {
words: Arc<TypeWords>,
types: Vec<FloatType>,
}
impl LateInit for CompileWords {
fn late_init(&self, lang: &BuiltLang, _diags: &mut FlmDiagnostics) -> Result<(), LateInitError> {
let language = TemplateLanguage::new(lang).map_err(|errors| {
LateInitError::new(format!(
"the template language of the floats feature: {}",
errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")
))
})?;
let mut by_type = BTreeMap::new();
for float_type in &self.types {
by_type.insert(float_type.name.clone(), reference_words(float_type, lang, &language)?);
}
let _ = self.words.by_type.set(by_type);
Ok(())
}
}
#[derive(Debug)]
pub struct FloatLatexRule {
handlers: Arc<Handlers>,
words: Arc<TypeWords>,
}
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 shown(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
caption: &Caption<'_>,
) -> Result<Vec<BuildId>, LowerError> {
let Some(alt) = &caption.alt else {
return lw.lower_arg_named(cx, &caption.node, CAPTION_TEXT_ARG);
};
lower_written_pieces(cx, lw, alt)
}
impl FloatLatexRule {
fn reference_type(
&self,
float_type: &FloatType,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<BuildId, LowerError> {
let name = float_type.name.as_str();
let words = self
.words
.by_type
.get()
.and_then(|by| by.get(&float_type.name))
.ok_or_else(|| LowerError::other(format!("the words of the float type `{name}` were not compiled")))?;
let mut body = refs::stage_reference_type_setup(cx, lw, name, &words.keys)?;
let guard = format!("{REFERENCE_TYPE_GUARD_PREFIX}{name}");
body.push(raw(cx, lw, &format!("\\def\\{guard}{{}}"))?);
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 Lower for FloatLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let reading = read_float(&node, &self.handlers, lw)?;
let fields = &reading.fields;
let float_type = &element_value::<FloatElement>(&node)
.ok_or_else(|| LowerError::structure("a float without its value"))?
.float_type;
let case = FloatCase::of(fields.numbered, fields.caption.is_some());
lw.require(&Name::from(PIECE));
let declaration = self.reference_type(float_type, cx, lw)?;
let body: Vec<NodeRef<'_, Flm>> = node.body().map(|body| body.iter().collect()).unwrap_or_default();
let mut content = Vec::new();
for run in body.split(is_float_field) {
content.extend(lower_run(cx, lw, run)?);
}
let caption = match &fields.caption {
Some(caption) => Some(lw.lower_arg_named(cx, &caption.node, CAPTION_TEXT_ARG)?),
None if case.is_numbered() => Some(Vec::new()),
None => None,
};
if let Some(text) = caption {
content.push(command(cx, lw, CAPTION_FIELD, vec![LatexArgShape::Mandatory], vec![text])?);
}
let mut labels = Vec::new();
for written in refs::label_uses_in(fields.body.labels.iter().copied()) {
labels.push(refs::stage_label(cx, lw, &written.text, written.label.as_ref())?);
}
match (&fields.caption, case) {
(Some(caption), FloatCase::CapOnly) if !labels.is_empty() => {
lw.require(&Name::from(packages::HYPERREF));
content.push(command(cx, lw, preamble::PHANTOMSECTION_COMMAND, Vec::new(), Vec::new())?);
let hooks = lw.option::<LatexRecomposedRenderOptions>()?.label_hooks;
let group = refs::stage_label_group(cx, lw, labels, false)?;
if hooks {
let shown = shown(cx, lw, caption)?;
content.push(refs::stage_labels_with_display_text(cx, lw, shown, group)?);
} else {
content.extend(group);
}
}
_ => content.extend(refs::stage_label_group(cx, lw, labels, false)?),
}
let type_arg = vec![raw(cx, lw, float_type.name.as_str())?];
let case_arg = vec![raw(cx, lw, case.as_str())?];
let environment = lw.pres_slots_with(
cx,
&ElementName::from(ENVIRONMENT),
LatexEnvironmentPayload::new(ENVIRONMENT_NAME, [LatexArgShape::Mandatory, LatexArgShape::Mandatory]),
vec![
(String::from(ARG_SLOT), type_arg),
(String::from(ARG_SLOT), case_arg),
(String::from(BODY_SLOT), content),
],
)?;
Ok(Lowering::Emit(vec![declaration, environment]))
}
}
fn latex_rule(handlers: Arc<Handlers>, words: Arc<TypeWords>) -> LoweringRule {
LoweringRule::new(
LATEX_RULE,
FLOAT,
LoweringDecl::new()
.reads_opt(ANCHORS)
.reads_opt(COUNTERS)
.reads_opt(SAFE_LABELS)
.requires(CHECK_HANDLERS)
.option::<LatexRecomposedRenderOptions>()
.produces(DEFINITION)
.produces(ENVIRONMENT)
.produces(MACRO)
.produces(RAW),
Arc::new(FloatLatexRule { handlers, words }),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"a float lowers to the LaTeX hook environment `flmFloat` over its type and case, \
around its content, `\\caption{…}` and its labels, after the declaration of its type's \
reference type",
)
}
pub(super) fn register(b: &mut FeatureBuilder<'_>, handlers: Arc<Handlers>) -> Result<(), BuildError> {
b.peer_backend(
BACKEND,
"the latex-recomposed backend, on which the recomposition rule is the default",
)?;
b.peer_element::<LatexDefinitionPayload>(
DEFINITION,
"the LaTeX family's definition construct, which the recomposition rule stages for the \
declaration of a float type's reference type",
)?;
b.peer_element::<LatexEnvironmentPayload>(
ENVIRONMENT,
"the LaTeX family's environment construct, which the recomposition rule stages for the \
float",
)?;
b.peer_element::<LatexMacroPayload>(
MACRO,
"the LaTeX family's macro-call construct, which the recomposition rule stages for the \
caption and the labels",
)?;
b.peer_element::<LatexRawPayload>(
RAW,
"the LaTeX family's raw node construct, in which the environment's arguments, the \
reference type's keys and a label are written",
)?;
b.peer_table::<SafeLabels>(
SAFE_LABELS.name(),
"the references feature's safe-labels table, which the recomposition rule reads for the \
safe label of each label",
)?;
b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece()))?;
let words = Arc::new(TypeWords::default());
b.finalizer(Arc::new(CollectTypes { words: Arc::clone(&words) }))?;
b.lowering_rule(latex_rule(handlers, words))
}
#[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_the_caption_package() {
let piece = definition_piece();
assert_eq!(piece.id, piece_id(PIECE_NAME));
assert_eq!(piece.id.as_str(), PIECE);
assert_eq!(piece.requires, [Name::from(packages::CAPTION)]);
}
#[test]
fn the_piece_defines_the_environment_and_the_two_commands_of_each_case() {
let piece = definition_piece();
for case in FloatCase::ALL {
for prefix in [SET_USE_CONFIG_PREFIX, PLACEMENT_ARGS_PREFIX] {
let name = format!("\\{prefix}{}{{", case.as_str());
assert!(piece.content.contains(&name), "{name}");
}
}
assert!(piece.content.contains("\\ProvideDocumentEnvironment{flmFloat}{m m}"));
assert!(piece.content.contains("\\providecommand\\flmFloatPlacementArgsNumCap{[tbph]}"));
assert!(piece.content.contains("\\providecommand\\flmFloatPlacementArgsCapOnly{[h]}"));
assert!(piece.content.contains("\\flm@float@caption*"));
assert!(piece.content.contains("\\centering"));
}
#[test]
fn the_case_follows_the_number_and_the_caption() {
assert_eq!(FloatCase::of(true, true).as_str(), "NumCap");
assert_eq!(FloatCase::of(true, false).as_str(), "NumOnly");
assert_eq!(FloatCase::of(false, true).as_str(), "CapOnly");
assert_eq!(FloatCase::of(false, false).as_str(), "Bare");
assert!(FloatCase::NumOnly.is_numbered() && !FloatCase::CapOnly.is_numbered());
}
}