Skip to main content

flm_core/stdlib/features/toc/
rules.rs

1//! The synthesized elements of the table of contents and their general
2//! lowering rules, the default on every backend.
3//!
4//! The three elements are [`PIECE`] (the root), [`LIST`] and [`ENTRY`]. They
5//! are synthesized: no document can write them, and the stage
6//! [`BuildToc`](super::BuildToc) builds them. Each declares the block role
7//! `Block`, so the block-structure pass, which runs over the value before it
8//! is lowered, wraps the title inside an entry in one paragraph, before the
9//! entry's sub-list; the entry's rule writes that paragraph as its content
10//! alone. The rules stage:
11//!
12//! - the root ([`RootRule`]): a `flm.pres.block` of role `flm.toc`, kind
13//!   token `toc` and document role [`DocRole::Toc`], holding its list;
14//! - a list ([`ListRule`]): an unlabeled `flm.pres.list` of kind tokens
15//!   `unnumbered` and `toc`, each entry with an empty label;
16//! - an entry ([`EntryRule`]): the number in a span of role
17//!   [`NUMBER_ROLE`] and a space, where the heading has a number; the
18//!   title; both inside one link to the heading's anchor where it has one;
19//!   then the sub-list, where there is one.
20//!
21//! The rules read the counters and anchors tables where they are computed,
22//! and are registered with peer declarations of those tables and of the
23//! presentation elements they produce, so that the feature builds in a
24//! registry without the `numbering` or `refs` features.
25
26use std::sync::Arc;
27
28use techy::core::node::{BuildId, NodeRef};
29use techy::error::Diagnostic;
30
31use crate::core::lowering::{
32    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
33};
34use crate::core::registry::{BuildError, FeatureBuilder};
35use crate::core::run::MissingEntry;
36use crate::lang::mint::{ElementDef, SyntaxDef};
37use crate::lang::Flm;
38use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
39use crate::model::element::ElementSpec;
40use crate::model::names::{CapName, ElementName, Name};
41use crate::stdlib::backends::pres::{
42    self, BlockPayload, DocRole, LinkPayload, ListPayload, SpanPayload, ITEM_SLOT, LABEL_SLOT,
43    LIST_UNNUMBERED,
44};
45use crate::stdlib::features::numbering::{Counters, FormatOptions, COUNTERS};
46use crate::stdlib::features::refs::{Anchors, ANCHORS};
47
48use super::{TocEntryPayload, ENTRY, KIND_TOC, LIST, NUMBER_ROLE, PIECE, STYLE};
49
50/// The link kind of an entry's link, `toc`.
51pub const LINK_KIND: &str = "toc";
52
53/// Returns the name of the general lowering rule of the element `element`,
54/// `<element>.lower.default`.
55pub fn rule_name(element: &str) -> String {
56    format!("{element}.lower.default")
57}
58
59/// The general lowering rule of the root of the table of contents, the
60/// element [`PIECE`], `flm.toc.lower.default`. It stages
61///
62/// ```text
63/// flm.pres.block { role: flm.toc, kinds: [toc], doc_role: Toc }
64///   └ the root's children, lowered: its list
65/// ```
66///
67/// It requires the feature's style identifier [`STYLE`] (`flm.toc.style`),
68/// which each backend resolves as it resolves requirements: the stylesheet on
69/// the `html` backend, the definition pieces delivering it on the
70/// `latex-rendered` backend, nothing on the `text` backend.
71#[derive(Debug, Default, Clone, Copy)]
72pub struct RootRule;
73
74impl Lower for RootRule {
75    fn lower(
76        &self,
77        node: NodeRef<'_, Flm>,
78        cx: &mut LowerCx<'_>,
79        lw: &mut dyn Lowerer,
80    ) -> Result<Lowering, LowerError> {
81        lw.require(&Name::from(STYLE));
82        let content = lw.lower_children(cx, &node)?;
83        let block = BlockPayload {
84            role: Some(Name::from(PIECE)),
85            kinds: vec![Name::from(KIND_TOC)],
86            anchor: None,
87            doc_role: Some(DocRole::Toc),
88        };
89        Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::BLOCK), block, content)?]))
90    }
91}
92
93/// The general lowering rule of a list of entries, the element [`LIST`],
94/// `flm.toc.list.lower.default`. It stages
95///
96/// ```text
97/// flm.pres.list { kinds: [unnumbered, toc], entry_levels: [<each entry's level>] }
98///   per entry:  label ⇒ nothing
99///               item  ⇒ the entry, lowered
100/// ```
101///
102/// Each entry's level is the level of its heading, from the entry's payload
103/// ([`TocEntryPayload`]); an entry node that carries no payload has no level.
104/// The list carries no `labeled` token, no anchor and no entry anchors; every
105/// entry has its two slots, the label slot empty, as the `itemize` list of the
106/// `lists` feature writes an item without a label. A child that is not an
107/// entry, which the stage never builds, is not written.
108#[derive(Debug, Default, Clone, Copy)]
109pub struct ListRule;
110
111impl Lower for ListRule {
112    fn lower(
113        &self,
114        node: NodeRef<'_, Flm>,
115        cx: &mut LowerCx<'_>,
116        lw: &mut dyn Lowerer,
117    ) -> Result<Lowering, LowerError> {
118        let mut slots: Vec<(String, Vec<BuildId>)> = Vec::new();
119        let mut entry_levels: Vec<Option<u32>> = Vec::new();
120        for one in each_child(&node)? {
121            let Some(entry) = one.first().filter(|child| child.ext().element.name.as_str() == ENTRY) else {
122                continue;
123            };
124            entry_levels.push(TocEntryPayload::of(&entry).map(|payload| payload.level));
125            slots.push((LABEL_SLOT.to_string(), Vec::new()));
126            slots.push((ITEM_SLOT.to_string(), lw.lower_nodes(cx, one)?));
127        }
128        let payload = ListPayload {
129            kinds: vec![Name::from(LIST_UNNUMBERED), Name::from(KIND_TOC)],
130            anchor: None,
131            entry_anchors: Vec::new(),
132            entry_levels,
133        };
134        Ok(Lowering::Emit(vec![lw.pres_slots_with(cx, &ElementName::from(pres::LIST), payload, slots)?]))
135    }
136}
137
138/// Returns each child of `node` as a slice of one node, in order, as
139/// [`Lowerer::lower_nodes`] takes them.
140fn each_child<'t>(node: &NodeRef<'t, Flm>) -> Result<Vec<techy::core::node::NodeSlice<'t, Flm>>, LowerError> {
141    let children = node.children();
142    let start = children.range().start;
143    (0u32..)
144        .zip(children.iter())
145        .map(|(index, _)| {
146            node.tree()
147                .slice(start + index..start + index + 1)
148                .ok_or_else(|| LowerError::structure("a child outside its parent's children"))
149        })
150        .collect()
151}
152
153/// The general lowering rule of one entry, the element [`ENTRY`],
154/// `flm.toc.entry.lower.default`. It reads the entry's payload
155/// ([`TocEntryPayload`]) and stages
156///
157/// ```text
158/// flm.pres.link { href: "#<anchor>", kind: toc, shows_target: true }
159///   ├ flm.pres.span { role: flm.toc.entry.number }  the number
160///   ├ " "
161///   └ the title
162/// the sub-list, lowered, where the entry holds one
163/// ```
164///
165/// - The **number** is the point's number as the counters table writes it,
166///   without the word and the delimiters a reference writes
167///   ([`FormatOptions::without_word`], [`FormatOptions::without_delimiters`]),
168///   and without the heading kind's title template. Where the counters table
169///   holds no number for the point (an unnumbered heading, or no `numbering`
170///   feature), there is no number span and no space.
171/// - The **title** is the entry's content other than its sub-list, each
172///   paragraph the block-structure pass made written as its content alone.
173/// - The **link** stands around the number and the title where the anchors
174///   table gives the point an anchor; otherwise they stand bare. The link has
175///   no document role and no accessible name, and says that its content is
176///   the target's own display. A point the anchors table never saw is the
177///   Error `flm.run.missing-entry` ([`MissingEntry`]), and the entry is
178///   written without a link.
179///
180/// An entry with no point has no number and no link.
181#[derive(Debug, Default, Clone, Copy)]
182pub struct EntryRule;
183
184impl Lower for EntryRule {
185    fn lower(
186        &self,
187        node: NodeRef<'_, Flm>,
188        cx: &mut LowerCx<'_>,
189        lw: &mut dyn Lowerer,
190    ) -> Result<Lowering, LowerError> {
191        let point = TocEntryPayload::of(&node).and_then(|payload| payload.point);
192        // The number's segments and the anchor are read before anything is
193        // staged, since reading a table borrows the façade the staging needs.
194        let segments = match (point, lw.get(COUNTERS)?) {
195            (Some(point), Some(counters)) => number(counters, point)?,
196            _ => Vec::new(),
197        };
198        let anchor = match point {
199            Some(point) => anchor(&node, point, lw)?,
200            None => None,
201        };
202        let mut shown = Vec::new();
203        if !segments.is_empty() {
204            let mut number = Vec::new();
205            for segment in &segments {
206                number.extend(lw.splice(cx, segment.content())?);
207            }
208            let span = SpanPayload { role: Some(Name::from(NUMBER_ROLE)), ..SpanPayload::default() };
209            shown.push(lw.pres_with(cx, &ElementName::from(pres::SPAN), span, number)?);
210            shown.push(lw.text(cx, " ")?);
211        }
212        let paragraph = Arc::clone(&lw.lang().structural().paragraph);
213        let mut lists = Vec::new();
214        for (one, child) in each_child(&node)?.into_iter().zip(node.children().iter()) {
215            let name = &child.ext().element.name;
216            if name.as_str() == LIST {
217                lists.push(one);
218            } else if *name == paragraph.name {
219                shown.extend(lw.lower_children(cx, &child)?);
220            } else {
221                shown.extend(lw.lower_nodes(cx, one)?);
222            }
223        }
224        let mut staged = match anchor {
225            Some(anchor) => {
226                let link = LinkPayload {
227                    href: format!("#{anchor}"),
228                    kind: Name::from(LINK_KIND),
229                    doc_role: None,
230                    label: None,
231                    shows_target: true,
232                };
233                vec![lw.pres_with(cx, &ElementName::from(pres::LINK), link, shown)?]
234            }
235            None => shown,
236        };
237        for one in lists {
238            staged.extend(lw.lower_nodes(cx, one)?);
239        }
240        Ok(Lowering::Emit(staged))
241    }
242}
243
244/// The segments of the number of `point`, bare; empty where the counters
245/// table holds no number for it.
246fn number(counters: &Counters, point: crate::model::aspects::PointId) -> Result<Vec<crate::stdlib::features::numbering::NumberSegment>, LowerError> {
247    let options = FormatOptions::new().without_word().without_delimiters();
248    match counters.format(point, &options) {
249        None => Ok(Vec::new()),
250        Some(result) => result.map_err(|error| LowerError::structure(error.to_string())),
251    }
252}
253
254/// The anchor of `point`, the first reference point of the entry `node`'s
255/// heading: `None` where the plan computes no anchors, or where the anchors
256/// stage gave the point none. A point the anchors stage never saw is
257/// reported as [`MissingEntry`], and has no anchor.
258fn anchor(
259    node: &NodeRef<'_, Flm>,
260    point: crate::model::aspects::PointId,
261    lw: &mut dyn Lowerer,
262) -> Result<Option<String>, LowerError> {
263    let found: Option<Option<String>> = match lw.get(ANCHORS)? {
264        None => return Ok(None),
265        Some(anchors) => anchors.lookup(point).map(|entry| entry.map(String::from)),
266    };
267    match found {
268        Some(anchor) => Ok(anchor),
269        None => {
270            let table = CapName::from(ANCHORS.name());
271            let producer =
272                lw.producer_of(&table).map(|stage| stage.to_string()).unwrap_or_else(|| "nobody".to_string());
273            lw.diagnose(Diagnostic::error(
274                MissingEntry { table: table.to_string(), producer, element: ENTRY.to_string() },
275                node.span().clone(),
276            ));
277            Ok(None)
278        }
279    }
280}
281
282/// What the rules of the three elements read and produce: the counters and
283/// anchors tables, both optionally, and the presentation elements they
284/// stage.
285pub(super) fn decl() -> LoweringDecl {
286    LoweringDecl::new()
287        .reads_opt(COUNTERS)
288        .reads_opt(ANCHORS)
289        .produces(pres::BLOCK)
290        .produces(pres::LIST)
291        .produces(pres::SPAN)
292        .produces(pres::LINK)
293        .produces(pres::PAR)
294}
295
296/// Makes, for the feature that `b` registers, the peer declarations
297/// ([`PeerName`](crate::core::registry::PeerName)) of the tables and the
298/// presentation elements the rules use, as the lists of xnotes declare them,
299/// so that the feature builds in a registry without the features that own
300/// them.
301fn declare_peers(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
302    b.peer_table::<Counters>(COUNTERS.name(), "the numbering feature's counter table: each entry's number")?;
303    b.peer_table::<Anchors>(ANCHORS.name(), "the references feature's anchors table: each entry's link target")?;
304    b.peer_element::<BlockPayload>(pres::BLOCK, "the table of contents")?;
305    b.peer_element::<ListPayload>(pres::LIST, "a list of entries of the table of contents")?;
306    b.peer_element::<SpanPayload>(pres::SPAN, "the number of an entry of the table of contents")?;
307    b.peer_element::<LinkPayload>(pres::LINK, "the link from an entry of the table of contents to its heading")?;
308    b.peer_element::<pres::ParPayload>(pres::PAR, "a paragraph inside an entry's title")
309}
310
311/// Declares, for the feature `b` registers, the three synthesized elements,
312/// their general lowering rules, and the peer declarations the rules need.
313pub(super) fn declare(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
314    let owner = b.feature().clone();
315    let elements = [
316        (
317            PIECE,
318            "The table of contents: one list of entries.",
319            "The table of contents of the document, built from its headings.",
320        ),
321        (
322            LIST,
323            "A list of entries of the table of contents.",
324            "A list of entries of the table of contents: the headings of one level, under one \
325             heading or at the top.",
326        ),
327        (
328            ENTRY,
329            "One entry of the table of contents: the title, then the list of its sub-entries.",
330            "One entry of the table of contents: one heading's title, then the entries of the \
331             headings under it.",
332        ),
333    ];
334    for (name, docs, type_docs) in elements {
335        b.element_type_text(name, type_docs)?;
336        let role = Arc::new(FixedBlockRole(BlockRole::Block)) as Arc<dyn BlockRoleAspect>;
337        b.element(
338            ElementDef::new(
339                owner.clone(),
340                Vec::<&str>::new(),
341                SyntaxDef::Synthesized,
342                Arc::new(ElementSpec::new(name).docs(docs).with(role)),
343            )
344            .docs(format!("{docs} No document can write it: a stage builds it from the headings.")),
345        )?;
346    }
347    declare_peers(b)?;
348    let rules: [(&str, Arc<dyn Lower>, &str); 3] = [
349        (
350            PIECE,
351            Arc::new(RootRule),
352            "the table of contents lowers to a `flm.pres.block` of role `flm.toc` and document role \
353             `toc`, holding its list",
354        ),
355        (
356            LIST,
357            Arc::new(ListRule),
358            "a list of entries lowers to an unlabeled `flm.pres.list` of kinds `unnumbered` and `toc`",
359        ),
360        (
361            ENTRY,
362            Arc::new(EntryRule),
363            "an entry lowers to its number and its title inside a link to its heading, then its \
364             sub-list",
365        ),
366    ];
367    for (element, rule, docs) in rules {
368        b.lowering_rule(
369            LoweringRule::new(rule_name(element), element, decl(), rule, DefaultMark::Everywhere).docs(docs),
370        )?;
371    }
372    Ok(())
373}