flm_core/stdlib/features/headings/title.rs
1//! The heading title template: what is written before the title of a numbered
2//! heading, such as `1.2. ` in `1.2. Notation`. Each heading kind has one, its
3//! [`title_number_format`](super::HeadingDecl::title_number_format); it is written in
4//! the template language, compiled once when the registry is built, and instantiated
5//! at every numbered heading.
6//!
7//! # The template
8//!
9//! The template states how a heading's number joins its title: the number and the
10//! text around it, `#{number}. ` by default, which writes `1. ` before
11//! `Introduction`. It may hold a word (`Chapter~#{number}: `) or show the number in
12//! another form (`#[bare]{number} `). It is written in the template language, FLM text
13//! with placeholders (see [the template language shared by
14//! features](crate::guide::concepts_overview#the-template-language-shared-by-features)),
15//! and its only placeholder name is [`NUMBER_PLACEHOLDER`], `number`:
16//!
17//! - `#{number}` is the heading's number as the kind's counter style writes it,
18//! without the word ([`WORD`](super::numbers::WORD), `§`) and the delimiters a
19//! reference writes: `1.2` for a subsection, the numbers of its parent counters
20//! joined as the counter style joins them.
21//! - `#[bare]{number}` is the kind's own number without the numbers of the counters
22//! it is numbered within: `2` where `#{number}` writes `1.2`.
23//! - `#[Roman]{number}` is the kind's own number in another number format (any number
24//! format name, [`NumberFormat`](crate::stdlib::features::numbering::NumberFormat)),
25//! with the numbers of the parent counters written as usual: `1.II`. The two keys can be combined: `#[Roman,bare]{number}`.
26//!
27//! Everything else in the template is FLM content, and markup may enclose the
28//! placeholder. A template without any placeholder is allowed: the heading then shows
29//! its text and nothing of its number, and still counts.
30//!
31//! The template carries structure, not styling: how the number looks is decided by a
32//! program's lowering rule or by a stylesheet, through the role [`NUMBER_ROLE`] the
33//! number carries.
34//!
35//! # How the template is compiled and written
36//!
37//! A late-initialization build hook
38//! ([`LateInit`]) compiles every kind's template once
39//! the language is built. A template that does not parse, that uses a placeholder
40//! other than `number`, or that gives `number` a key it does not take, fails the
41//! registry build with an error that gives the heading kind.
42//!
43//! At each heading the document numbered, the lowering rule of the heading
44//! ([`HeadingRule`](super::HeadingRule)) instantiates the kind's template. Each
45//! `#{number}` is replaced by a node of the element [`NUMBER_ELEMENT`] holding the
46//! number, and that node lowers to a
47//! [`flm.pres.span`](crate::stdlib::backends::pres::SPAN) of role [`NUMBER_ROLE`]
48//! around the number alone ([`NumberRule`]); the rest of the template is ordinary
49//! heading content before the title. The element is *synthesized*: it has no source
50//! form, so no document can write it.
51
52use std::collections::BTreeMap;
53use std::fmt;
54use std::sync::{Arc, OnceLock};
55
56use techy::core::node::{
57 BodySlotExt, BuildId, ChildRegion, ContentNodes, NodeKind, NodeRef, NodeTree, ParsedSlot,
58 ParsedSlots, SlotRole,
59};
60use techy::core::Lang;
61use techy::latexlike::BodyMarker;
62use techy::source::SourceSpan;
63use techy::transform::{Restage, RestageContext, RestageVisitor};
64
65use crate::core::lowering::{Lower, LowerCx, LowerError, Lowerer, Lowering};
66use crate::core::registry::{LateInit, LateInitError};
67use crate::lang::guard::{self, GuardPolicy};
68use crate::lang::mint::FlmSynthesizedSpec;
69use crate::lang::rewrites::userdefs::template::{
70 CompiledTemplate, PlaceholderVocabulary, TemplateLanguage,
71};
72use crate::lang::{BuiltLang, Flm, FlmDiagnostics};
73use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
74use crate::model::element::ElementSpec;
75use crate::model::names::{ElementName, Name};
76use crate::stdlib::backends::pres::{self, SpanPayload};
77use crate::stdlib::features::numbering::{
78 compile_text, instantiate_template, occurrences_of, parse_keys, AncestorKeys, Binding,
79 Bindings, NumberSegment, StyleError,
80};
81
82use super::numbers::NUMBER_ROLE;
83
84/// The only placeholder name of a heading title template, `number`: `#{number}`
85/// is the heading's number.
86pub const NUMBER_PLACEHOLDER: &str = "number";
87
88/// The heading title template every heading kind has by default, `#{number}. `:
89/// the number, a period and a space before the title, as in `1. Introduction`.
90pub const DEFAULT_TITLE_NUMBER_FORMAT: &str = "#{number}. ";
91
92/// The element of the node that holds a heading's number inside the
93/// instantiated heading title template, `flm.heading.number`.
94///
95/// The element is synthesized (it has no source form, so no document can write
96/// it). Its lowering rule, [`NUMBER_RULE`], lowers it to a span of role
97/// [`NUMBER_ROLE`] around the number.
98pub const NUMBER_ELEMENT: &str = "flm.heading.number";
99
100/// The name of the default lowering rule of [`NUMBER_ELEMENT`],
101/// `flm.heading.number.lower.default` ([`NumberRule`]). On the `latex-recomposed`
102/// backend the element has its own rule
103/// ([`NUMBER_LATEX_RULE`](super::latex::NUMBER_LATEX_RULE)).
104pub const NUMBER_RULE: &str = "flm.heading.number.lower.default";
105
106/// The name of the body slot the number node holds the number in.
107const BODY_SLOT: &str = "body";
108
109/// One `#{number}` of a compiled template: the text of its bracket as written
110/// (`written`), which matches the placeholder to its binding when the template is
111/// instantiated, and the keys read from that text (`keys`).
112struct Occurrence {
113 written: String,
114 keys: AncestorKeys,
115}
116
117/// One kind's heading title template, compiled.
118struct CompiledTitle {
119 template: CompiledTemplate,
120 /// Every distinct bracket text the template gives `#{number}`, in the
121 /// order first written.
122 occurrences: Vec<Occurrence>,
123}
124
125/// What the headings feature shares between its registration, its
126/// late-initialization build hook and its lowering rule: each kind's heading
127/// title template as declared, the element of the number node, and the compiled
128/// templates once the hook has run.
129pub(super) struct Titles {
130 declared: Vec<(Name, String)>,
131 spec: Arc<FlmSynthesizedSpec>,
132 compiled: OnceLock<BTreeMap<Name, CompiledTitle>>,
133}
134
135impl fmt::Debug for Titles {
136 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137 f.debug_struct("Titles").field("declared", &self.declared).finish_non_exhaustive()
138 }
139}
140
141impl Titles {
142 /// Returns the shared state for `declared` (each kind's name and heading
143 /// title template), with the number node carrying `element`.
144 pub(super) fn new(declared: Vec<(Name, String)>, element: Arc<ElementSpec>) -> Titles {
145 Titles {
146 declared,
147 spec: Arc::new(FlmSynthesizedSpec::new(element)),
148 compiled: OnceLock::new(),
149 }
150 }
151}
152
153/// Returns the element value of [`NUMBER_ELEMENT`].
154pub(super) fn number_element() -> Arc<ElementSpec> {
155 Arc::new(
156 ElementSpec::new(NUMBER_ELEMENT)
157 .docs(
158 "The number of a numbered heading, where the kind's heading title template \
159 writes `#{number}`. No document can write it.",
160 )
161 .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT))),
162 )
163}
164
165// --- compiling -------------------------------------------------------------------------------
166
167/// Compiles `text`, the heading title template of the kind `kind`.
168///
169/// # Errors
170///
171/// A sentence that gives the kind and what is wrong: a text that is not valid
172/// FLM, a placeholder other than `number`, or a key `#[…]{number}` does not take.
173fn compile_title(
174 kind: &Name,
175 text: &str,
176 lang: &BuiltLang,
177 language: &TemplateLanguage,
178) -> Result<CompiledTitle, String> {
179 let refused = |detail: String| {
180 format!("the heading title template `{text}` of the heading kind `{kind}` is not valid: {detail}")
181 };
182 let vocabulary = PlaceholderVocabulary::new(0).extra(NUMBER_PLACEHOLDER, true);
183 let what = format!("the heading kind `{kind}`");
184 let template = compile_text(text, &what, &vocabulary, lang, language)
185 .map_err(|error| refused(describe(&error)))?;
186 let mut occurrences: Vec<Occurrence> = Vec::new();
187 for (_, written) in occurrences_of(&template) {
188 let keys = parse_keys(&written).map_err(|key| {
189 refused(format!(
190 "`#[…]{{{NUMBER_PLACEHOLDER}}}` takes the key `bare` and number format names, \
191 not `{key}`"
192 ))
193 })?;
194 if !occurrences.iter().any(|occurrence| occurrence.written == written) {
195 occurrences.push(Occurrence { written, keys });
196 }
197 }
198 Ok(CompiledTitle { template, occurrences })
199}
200
201/// Returns what `error` reports, as a sentence: the diagnostics of a template
202/// that did not compile, one after the other.
203fn describe(error: &StyleError) -> String {
204 match error {
205 StyleError::Template { diagnostics, .. } | StyleError::Parse { diagnostics, .. } => {
206 diagnostics.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")
207 }
208 other => other.to_string(),
209 }
210}
211
212/// The late-initialization build hook of the headings feature: it compiles every
213/// kind's heading title template once the language is built.
214///
215/// A template that does not compile fails the registry build with an error that
216/// gives the kind: the template is configuration, so a mistake in it is reported
217/// once rather than at every numbered heading. Every kind's template is compiled,
218/// whether the kind is numbered or not.
219pub(super) struct CompileTitles {
220 pub(super) titles: Arc<Titles>,
221}
222
223impl LateInit for CompileTitles {
224 fn late_init(&self, lang: &BuiltLang, _diags: &mut FlmDiagnostics) -> Result<(), LateInitError> {
225 let language = TemplateLanguage::new(lang).map_err(|errors| {
226 LateInitError::new(format!(
227 "the template language of the headings feature: {}",
228 errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")
229 ))
230 })?;
231 let mut compiled = BTreeMap::new();
232 for (kind, text) in &self.titles.declared {
233 let title = compile_title(kind, text, lang, &language).map_err(LateInitError::new)?;
234 compiled.insert(kind.clone(), title);
235 }
236 // The hook runs once per registration of the feature, and a registry
237 // holds the feature once, so the cell is empty here.
238 let _ = self.titles.compiled.set(compiled);
239 Ok(())
240 }
241}
242
243// --- writing ---------------------------------------------------------------------------------
244
245/// Returns what is written before the title of a heading of kind `kind`: the
246/// kind's heading title template with each `#{number}` replaced by what `number`
247/// writes for the keys of that placeholder, as a synthesized value ready to be
248/// spliced ([`Lowerer::splice`](crate::core::lowering::Lowerer::splice)). `None`
249/// when `number` has no number for the heading.
250///
251/// # Errors
252///
253/// [`LowerError`] when the template was not compiled (the build hook did not
254/// run), when the number could not be written, or when the content could not be
255/// built.
256pub(super) fn title_number(
257 titles: &Titles,
258 kind: &Name,
259 mut number: impl FnMut(AncestorKeys) -> Option<Result<Vec<NumberSegment>, String>>,
260) -> Result<Option<Arc<NodeTree<Flm>>>, LowerError> {
261 let title = titles.compiled.get().and_then(|compiled| compiled.get(kind)).ok_or_else(|| {
262 LowerError::other(format!(
263 "the heading title template of the heading kind `{kind}` was not compiled"
264 ))
265 })?;
266 let mut entries = Vec::with_capacity(title.occurrences.len());
267 for occurrence in &title.occurrences {
268 let Some(segments) = number(occurrence.keys) else { return Ok(None) };
269 let segments = segments.map_err(LowerError::other)?;
270 entries.push(Binding {
271 name: NUMBER_PLACEHOLDER.to_string(),
272 keys: occurrence.written.clone(),
273 content: number_node(&titles.spec, title.template.tree(), &segments)?,
274 });
275 }
276 let site = title.template.tree().root().span().clone();
277 instantiate_template(&site, &title.template, &Bindings::new(entries))
278 .map(Some)
279 .map_err(|error| LowerError::other(error.to_string()))
280}
281
282/// Returns a value tree holding one node of [`NUMBER_ELEMENT`] whose body is the
283/// content of `segments`, with a source span at the start of `anchor`, the
284/// compiled template the node is substituted into.
285fn number_node(
286 spec: &Arc<FlmSynthesizedSpec>,
287 anchor: &Arc<NodeTree<Flm>>,
288 segments: &[NumberSegment],
289) -> Result<Arc<NodeTree<Flm>>, LowerError> {
290 let mut visitor = NumberNode { spec, segments };
291 guard::restager(&mut visitor, GuardPolicy::StackBudget)
292 .restage(anchor)
293 .map(Arc::new)
294 .map_err(|error| LowerError::other(error.to_string()))
295}
296
297/// The visitor [`number_node`] runs: called once, at the anchor tree's root,
298/// it emits a list node holding the number node over a copy of every
299/// segment's nodes.
300struct NumberNode<'a> {
301 spec: &'a Arc<FlmSynthesizedSpec>,
302 segments: &'a [NumberSegment],
303}
304
305/// A visitor that carries every node over unchanged.
306struct Verbatim;
307
308impl RestageVisitor<Flm, (), ()> for Verbatim {
309 type Error = String;
310
311 fn restage(
312 &mut self,
313 _node: NodeRef<'_, Flm>,
314 _cx: &mut RestageContext<'_, Flm, (), ()>,
315 ) -> Result<Restage<()>, String> {
316 Ok(Restage::Descend(()))
317 }
318}
319
320impl RestageVisitor<Flm, (), ()> for NumberNode<'_> {
321 type Error = String;
322
323 fn restage(
324 &mut self,
325 root: NodeRef<'_, Flm>,
326 cx: &mut RestageContext<'_, Flm, (), ()>,
327 ) -> Result<Restage<()>, String> {
328 let mut children: Vec<BuildId> = Vec::new();
329 for segment in self.segments {
330 for node in segment.content().root().children().iter() {
331 children.extend(
332 cx.restage_subtree(node, &mut Verbatim).map_err(|error| error.to_string())?,
333 );
334 }
335 }
336 let span = SourceSpan::new(root.span().source(), root.span().start()..root.span().start());
337 let state = Arc::clone(root.parsing_state());
338 let count = children.len() as u32;
339 let mut data = self.spec.callable_data();
340 data.slots = ParsedSlots::new(vec![ParsedSlot::new(
341 ChildRegion::new(0..count, ContentNodes::InRegion(0..count)),
342 BODY_SLOT,
343 SlotRole::Content,
344 BodyMarker::make_body(),
345 )]);
346 let kind = NodeKind::callable(data);
347 let ext = Flm::make_node_ext(&kind, &span, &state, cx.builder().staged_children(&children))
348 .map_err(|error| error.to_string())?;
349 let number = cx
350 .builder()
351 .add(kind, span.clone(), Arc::clone(&state), children, ext, ())
352 .map_err(|error| error.to_string())?;
353 let kind = NodeKind::list();
354 let ext = Flm::make_node_ext(&kind, &span, &state, cx.builder().staged_children(&[number]))
355 .map_err(|error| error.to_string())?;
356 let list = cx
357 .builder()
358 .add(kind, span, state, vec![number], ext, ())
359 .map_err(|error| error.to_string())?;
360 Ok(Restage::Emit(vec![list]))
361 }
362}
363
364// --- lowering the number node ------------------------------------------------------------------
365
366/// The implementation of the lowering rule [`NUMBER_RULE`]: a node of
367/// [`NUMBER_ELEMENT`] lowers to a
368/// [`flm.pres.span`](crate::stdlib::backends::pres::SPAN) of role
369/// [`NUMBER_ROLE`] around its body, the number, lowered through the lowering
370/// rules.
371#[derive(Debug, Default, Clone, Copy)]
372pub struct NumberRule;
373
374impl Lower for NumberRule {
375 fn lower(
376 &self,
377 node: NodeRef<'_, Flm>,
378 cx: &mut LowerCx<'_>,
379 lw: &mut dyn Lowerer,
380 ) -> Result<Lowering, LowerError> {
381 let body = lw.lower_body(cx, &node)?;
382 let payload = SpanPayload {
383 style: None,
384 role: Some(Name::from(NUMBER_ROLE)),
385 kinds: Vec::new(),
386 anchor: None,
387 doc_role: None,
388 };
389 let span = lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)?;
390 Ok(Lowering::Emit(vec![span]))
391 }
392}