Skip to main content

flm_core/stdlib/features/citations/
bibliography.rs

1//! The list of cited works: [`build_list`], the only function that builds
2//! one, the two synthesized elements a list is made of with their general
3//! lowering rules, and the bibliography, the piece that places the list of
4//! every cited work after the document's content.
5//!
6//! A piece is a document-level synthesized value that a backend places
7//! before or after the document's content ([`Piece`]). A **list entry** is an
8//! entry of a list of cited works: one node per work, labeled with the work's
9//! number and holding its citation entry. The bibliography's
10//! builder stage ([`BUILD_BIBLIOGRAPHY`]) writes the piece table
11//! [`BIBLIOGRAPHY`]; the feature contributes the piece's declaration to the
12//! `pieces` feature's service slot ([`pieces::SLOT`]), and each backend that
13//! places pieces lowers the list with the rule of its element:
14//! [`BibliographyRule`] by default, and on the recomposed LaTeX a rule that
15//! writes nothing ([`ListNotWritten`](super::latex::ListNotWritten)).
16
17use std::sync::Arc;
18
19use techy::core::node::{BuildId, NodeRef, NodeTree};
20use techy::serialize::SerialValue;
21
22use crate::core::data::store::StageOut;
23use crate::core::data::table::TableHandle;
24use crate::core::lowering::{
25    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
26};
27use crate::core::piece::{Piece, PieceDecl, PiecePlace};
28use crate::core::plan::PlanCx;
29use crate::core::registry::{BuildError, FeatureBuilder, FlmRegistry};
30use crate::core::run::StageCx;
31use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
32use crate::lang::copy::{copy_pieces_into_value, SynthesizedPiece, ValueContent, ValuePiece};
33use crate::lang::mint::{ElementDef, FlmSynthesizedSpec, SyntaxDef};
34use crate::lang::{Flm, PresPayload};
35use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
36use crate::model::element::ElementSpec;
37use crate::model::names::{ElementName, FeatureName, Name};
38use crate::stdlib::backends::lowering::lower_blocks_with_edges;
39use crate::stdlib::backends::pieces;
40use crate::stdlib::backends::pres::{
41    self, BlockPayload, DocRole, DroppedPayload, HeadingPayload, ListPayload, SpanPayload, ITEM_SLOT,
42    LABEL_SLOT, LIST_LABELED, LIST_NUMBERED,
43};
44use crate::stdlib::features::numbering::{format_many, CounterValue, FormatOptions, NumberedValue};
45
46use super::config::{CitationPlacement, MarkForm};
47use super::entries::{CitationEntries, ENTRIES};
48use super::mark::MarkSettings;
49use super::numbers::{stage_failed, CitedWorks, CITATIONS};
50use super::providers::CitationEntry;
51
52/// The name `flm.citations.bibliography`, used for four things: the
53/// synthesized element of a list of cited works, the role of the block that
54/// list lowers to, the piece that places the list of every cited work after
55/// the content, and that piece's table ([`bibliography_table`]).
56pub const BIBLIOGRAPHY: &str = "flm.citations.bibliography";
57
58/// The name of the synthesized element of one entry of a list of cited works,
59/// `flm.citations.bibliography.entry`: a node of it holds the citation
60/// entry's content and carries a [`ListedEntry`] as its payload.
61pub const BIBLIOGRAPHY_ENTRY: &str = "flm.citations.bibliography.entry";
62
63/// The name of the bibliography's builder stage,
64/// `flm.citations.build-bibliography`, which writes the piece table
65/// [`BIBLIOGRAPHY`].
66pub const BUILD_BIBLIOGRAPHY: &str = "flm.citations.build-bibliography";
67
68/// The role of the span that holds an entry's label in a list of cited works
69/// (its number written through the citation counter style),
70/// `flm.citations.entry.number`.
71pub const ENTRY_NUMBER_ROLE: &str = "flm.citations.entry.number";
72
73/// The kind token that a list of cited works carries on its block and on its
74/// list, `citations`; also the name given to the list's heading
75/// ([`HeadingPayload::name`]).
76pub const KIND_CITATIONS: &str = "citations";
77
78/// The name of the general lowering rule of the list element,
79/// `flm.citations.bibliography.lower.default` ([`BibliographyRule`]), the
80/// default on every backend.
81pub const BIBLIOGRAPHY_RULE: &str = "flm.citations.bibliography.lower.default";
82
83/// The name of the general lowering rule of the entry element,
84/// `flm.citations.bibliography.entry.lower.default`. A list entry is lowered
85/// by its list's rule; this rule fails with a structure error when a list
86/// entry is lowered on its own.
87pub const BIBLIOGRAPHY_ENTRY_RULE: &str = "flm.citations.bibliography.entry.lower.default";
88
89/// Returns the handle of the bibliography's piece table, [`BIBLIOGRAPHY`]: the
90/// builder stage writes it, and a backend that places pieces reads it.
91pub fn bibliography_table() -> TableHandle<Piece> {
92    TableHandle::new(BIBLIOGRAPHY)
93}
94
95/// One cited work of a list, as [`build_list`] takes it: its citation key,
96/// number and identifier, and its citation entry, or `None` for a work with
97/// no citation entry.
98#[derive(Debug, Clone, Copy)]
99pub struct ListedWork<'w> {
100    /// The citation key.
101    pub key: &'w str,
102    /// The work's number, which the label of its entry in the list shows.
103    pub number: usize,
104    /// The work's identifier, which its entry in the list carries.
105    pub identifier: &'w str,
106    /// The work's citation entry; `None` for a citation key with no citation
107    /// entry.
108    pub entry: Option<&'w CitationEntry>,
109}
110
111/// The payload of a node of the entry element ([`BIBLIOGRAPHY_ENTRY`]): the
112/// work's citation key, number and identifier, and whether its citation entry
113/// is missing (the node then holds nothing).
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct ListedEntry {
116    /// The citation key.
117    pub key: String,
118    /// The number that the label of the list entry shows.
119    pub number: usize,
120    /// The identifier that the list entry carries.
121    pub identifier: String,
122    /// Whether the citation key has no citation entry.
123    pub missing: bool,
124}
125
126impl PresPayload for ListedEntry {
127    fn project(&self) -> SerialValue {
128        let mut entries = vec![
129            ("key".to_string(), SerialValue::Str(self.key.clone())),
130            ("number".to_string(), SerialValue::Int(self.number as i64)),
131            ("id".to_string(), SerialValue::Str(self.identifier.clone())),
132        ];
133        if self.missing {
134            entries.push(("missing".to_string(), SerialValue::Bool(true)));
135        }
136        SerialValue::Map(entries)
137    }
138}
139
140impl ListedEntry {
141    /// Returns the payload of the entry node `node`, or `None` for a node that
142    /// carries none.
143    pub fn of<'n>(node: &'n NodeRef<'_, Flm>) -> Option<&'n ListedEntry> {
144        node.ext().payload.as_deref()?.downcast_ref::<ListedEntry>()
145    }
146}
147
148/// Builds the list of `works`, in the order given, and returns it as a
149/// synthesized value's tree. The tree holds one node of the list element
150/// [`BIBLIOGRAPHY`], whose children are one node of the entry element
151/// [`BIBLIOGRAPHY_ENTRY`] per work. Each entry node carries its
152/// [`ListedEntry`] and holds a copy of its citation entry's content as the
153/// synthesized value's own content ([`ValueContent::Own`]), or nothing for a
154/// work with no citation entry. The new nodes take `anchor`'s span and
155/// parsing state.
156///
157/// This is the only function that builds a list of cited works. The
158/// bibliography's builder stage calls it over every cited work of the
159/// document; a caller that lists the works of one part of a document calls it
160/// over that part's works, numbered with
161/// [`number_works`](super::number_works). Wherever the list is placed, the
162/// rule of its element lowers it and writes each number through the citation
163/// counter style ([`BibliographyRule`]).
164///
165/// Call it on a worker thread (a thread with a large enough stack; see
166/// [`on_worker_thread`](crate::lang::guard::on_worker_thread)), as
167/// [`copy_pieces_into_value`](crate::lang::copy::copy_pieces_into_value)
168/// requires.
169///
170/// # Errors
171///
172/// A text that says what went wrong: an element the registry does not hold
173/// (the `citations` feature is not registered), content nesting too deeply,
174/// or the copy failing.
175pub fn build_list(
176    works: &[ListedWork<'_>],
177    registry: &FlmRegistry,
178    anchor: &NodeRef<'_, Flm>,
179) -> Result<Arc<NodeTree<Flm>>, String> {
180    let spec = |name: &str| match registry.element_value(name) {
181        Ok(Some(element)) => Ok(Arc::new(FlmSynthesizedSpec::new(Arc::clone(element)))),
182        Ok(None) => Err(format!("missing element ‘{name}’ in the registry")),
183        Err(error) => Err(error.to_string()),
184    };
185    let (list_spec, entry_spec) = (spec(BIBLIOGRAPHY)?, spec(BIBLIOGRAPHY_ENTRY)?);
186    let contents: Vec<Vec<NodeRef<'_, Flm>>> = works
187        .iter()
188        .map(|work| work.entry.map_or_else(Vec::new, |entry| entry.content.root().children().iter().collect()))
189        .collect();
190    let entries: Vec<SynthesizedPiece<'_, '_>> = works
191        .iter()
192        .zip(&contents)
193        .map(|(work, content)| SynthesizedPiece {
194            spec: Arc::clone(&entry_spec),
195            slot: pres::BODY_SLOT,
196            span: anchor.span().clone(),
197            state: Arc::clone(anchor.parsing_state()),
198            body: content.iter().copied().map(ValuePiece::Node).collect(),
199            payload: Some(Arc::new(ListedEntry {
200                key: work.key.to_string(),
201                number: work.number,
202                identifier: work.identifier.to_string(),
203                missing: work.entry.is_none(),
204            })),
205        })
206        .collect();
207    let list = SynthesizedPiece {
208        spec: list_spec,
209        slot: pres::BODY_SLOT,
210        span: anchor.span().clone(),
211        state: Arc::clone(anchor.parsing_state()),
212        body: entries.iter().map(ValuePiece::Synthesized).collect(),
213        payload: None,
214    };
215    copy_pieces_into_value(&[ValuePiece::Synthesized(&list)], anchor, ValueContent::Own, registry.lang().guard())
216        .map_err(|error| error.to_string())
217}
218
219/// The bibliography's builder stage, [`BUILD_BIBLIOGRAPHY`]: a compute stage
220/// of document scope. It reads the cited works ([`CITATIONS`]) and their
221/// citation entries ([`ENTRIES`]) and writes the piece table
222/// [`BIBLIOGRAPHY`]: the list of every cited work in the order of the numbers
223/// ([`build_list`]), whose nodes take the span and parsing state of the root
224/// of the run's first tree. Where the document cites nothing, or under the
225/// in-place placement, it writes a piece with no content, which no backend
226/// places.
227#[derive(Debug)]
228pub(super) struct BuildBibliography {
229    pub(super) placement: CitationPlacement,
230}
231
232impl BuildBibliography {
233    /// Returns the list's synthesized value, or `None` for nothing to place;
234    /// a failure is reported into `out`.
235    fn build(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) -> Option<Arc<NodeTree<Flm>>> {
236        if self.placement == CitationPlacement::InPlace {
237            return None;
238        }
239        let (citations, entries): (&CitedWorks, Option<&CitationEntries>) =
240            match (cx.get(CITATIONS), cx.get(ENTRIES)) {
241                (Ok(Some(citations)), Ok(entries)) => (citations, entries),
242                (Err(error), _) | (_, Err(error)) => {
243                    stage_failed(out, BUILD_BIBLIOGRAPHY, error);
244                    return None;
245                }
246                (Ok(None), _) => return None,
247            };
248        if citations.is_empty() {
249            return None;
250        }
251        let works: Vec<ListedWork<'_>> = citations
252            .works()
253            .map(|(key, work)| ListedWork {
254                key,
255                number: work.number,
256                identifier: &work.identifier,
257                entry: entries.and_then(|entries| entries.entry(key)),
258            })
259            .collect();
260        // The table of cited works holds no place for a key, so the list's nodes
261        // take the span and parsing state of the root of the run's first tree.
262        let (_, tree) = cx.trees().next()?;
263        match build_list(&works, cx.registry(), &tree.root()) {
264            Ok(value) => Some(value),
265            Err(detail) => {
266                stage_failed(out, BUILD_BIBLIOGRAPHY, detail);
267                None
268            }
269        }
270    }
271}
272
273impl Stage for BuildBibliography {
274    fn decl(&self) -> StageDecl {
275        StageDecl::new(BUILD_BIBLIOGRAPHY, Effect::Compute, Scope::Document)
276            .writes(bibliography_table())
277            .docs(
278                "Builds the list of the cited works, in the order of their numbers, each with its \
279                 citation entry, into the piece `flm.citations.bibliography`.",
280            )
281    }
282
283    fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
284        Needs::new().reads(CITATIONS).reads(ENTRIES)
285    }
286
287    fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
288        let content = self.build(cx, out);
289        match out.table(&bibliography_table()) {
290            Ok(table) => *table = Piece { content },
291            Err(error) => stage_failed(out, BUILD_BIBLIOGRAPHY, error),
292        }
293    }
294}
295
296/// The body of the general rule of the list element [`BIBLIOGRAPHY`],
297/// [`BIBLIOGRAPHY_RULE`], the default on every backend except the recomposed
298/// LaTeX. It stages (builds into the lowered tree; see
299/// [`Lowerer`])
300///
301/// ```text
302/// flm.pres.block { role: flm.citations.bibliography, kinds: [citations],
303///                  doc_role: Bibliography }
304///   ├ flm.pres.block-heading { name: citations, level: <heading_level>, in_toc: false }
305///   │   └ the configured title (`References`), at the configured level (2)
306///   └ flm.pres.list { kinds: [numbered, citations, labeled],
307///                     entry_anchors: [<each work's identifier>] }
308///       per list entry:  label ⇒ flm.pres.span { role: flm.citations.entry.number }
309///                                  holding the number written through the citation counter style
310///                        item  ⇒ the citation entry's content, as one paragraph
311/// ```
312///
313/// The heading is staged where the configuration gives the list a title
314/// ([`heading_title`](super::CitationsConfig::heading_title)); where the
315/// configuration sets no title, the block holds the list alone.
316///
317/// The block carries the document role [`DocRole::Bibliography`] (written
318/// `role="doc-bibliography"` on the HTML page); the list entries carry none,
319/// because the role `doc-biblioentry` is deprecated in the Digital Publishing
320/// ARIA module.
321///
322/// A list entry's label is the work's number written through the citation
323/// counter style: with the citation counter style's delimiters under the
324/// bracketed form (`[1]`), and bare under the superscript form (`1`). The item of a work with no citation
325/// entry is a dropped mark (`flm.pres.dropped`, condition
326/// `flm.citations.no-entry`; see
327/// [recovery](crate::stdlib::backends::lowering::error)) in a paragraph of
328/// its own; the check stage has reported the citation key. A child of the
329/// list that is not a list entry is not written.
330#[derive(Debug)]
331pub struct BibliographyRule {
332    settings: Arc<MarkSettings>,
333}
334
335impl BibliographyRule {
336    /// Stages the label of the work numbered `number`.
337    fn label(&self, cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, number: usize) -> Result<BuildId, LowerError> {
338        let style = self.settings.style()?;
339        let value = CounterValue::new(number as i64);
340        let numbered = [NumberedValue::new(&value)];
341        let options = match self.settings.config().mark {
342            MarkForm::Bracketed => FormatOptions::new().without_word(),
343            MarkForm::Superscript => FormatOptions::new().without_word().without_delimiters(),
344        };
345        let segments = format_many(style, &numbered, &options)
346            .map_err(|error| LowerError::structure(error.to_string()))?;
347        let mut body = Vec::new();
348        for segment in &segments {
349            body.extend(lw.splice(cx, segment.content())?);
350        }
351        let payload = SpanPayload { role: Some(Name::from(ENTRY_NUMBER_ROLE)), ..SpanPayload::default() };
352        lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)
353    }
354}
355
356impl Lower for BibliographyRule {
357    fn lower(
358        &self,
359        node: NodeRef<'_, Flm>,
360        cx: &mut LowerCx<'_>,
361        lw: &mut dyn Lowerer,
362    ) -> Result<Lowering, LowerError> {
363        let entries: Vec<NodeRef<'_, Flm>> = node
364            .children()
365            .iter()
366            .filter(|child| child.ext().element.name.as_str() == BIBLIOGRAPHY_ENTRY)
367            .collect();
368        let mut slots: Vec<(String, Vec<BuildId>)> = Vec::with_capacity(2 * entries.len());
369        let mut entry_anchors = Vec::with_capacity(entries.len());
370        for entry in &entries {
371            let Some(listed) = ListedEntry::of(entry) else { continue };
372            let label = self.label(cx, lw, listed.number)?;
373            let item = if listed.missing {
374                let dropped = DroppedPayload {
375                    condition: Name::from("flm.citations.no-entry"),
376                    detail: "bibliography entry".to_string(),
377                };
378                let mark = lw.pres_with(cx, &ElementName::from(pres::DROPPED), dropped, Vec::new())?;
379                lower_blocks_with_edges(cx, lw, &[], Vec::new(), vec![mark])?
380            } else {
381                let content: Vec<NodeRef<'_, Flm>> = entry.children().iter().collect();
382                lower_blocks_with_edges(cx, lw, &content, Vec::new(), Vec::new())?
383            };
384            slots.push((LABEL_SLOT.to_string(), vec![label]));
385            slots.push((ITEM_SLOT.to_string(), item));
386            entry_anchors.push(Some(listed.identifier.clone()));
387        }
388        let list = ListPayload {
389            kinds: vec![Name::from(LIST_NUMBERED), Name::from(KIND_CITATIONS), Name::from(LIST_LABELED)],
390            anchor: None,
391            entry_anchors,
392            entry_levels: Vec::new(),
393        };
394        let list = lw.pres_slots_with(cx, &ElementName::from(pres::LIST), list, slots)?;
395        let mut body = Vec::with_capacity(2);
396        if let Some(title) = self.settings.heading_title()? {
397            let title = lw.splice(cx, title)?;
398            let level = self.settings.config().heading_level;
399            let heading =
400                HeadingPayload { name: Name::from(KIND_CITATIONS), level, in_toc: false, anchor: None, number: None };
401            body.push(lw.pres_with(cx, &ElementName::from(pres::BLOCK_HEADING), heading, title)?);
402        }
403        body.push(list);
404        let block = BlockPayload {
405            role: Some(Name::from(BIBLIOGRAPHY)),
406            kinds: vec![Name::from(KIND_CITATIONS)],
407            anchor: None,
408            doc_role: Some(DocRole::Bibliography),
409        };
410        Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::BLOCK), block, body)?]))
411    }
412}
413
414/// The body of the general rule of the entry element, which runs only when a
415/// list entry is lowered outside its list (no builder of this feature produces
416/// such a tree): it fails with a structure error, because the list's rule
417/// lowers the content of its entries itself.
418#[derive(Debug, Default)]
419struct EntryOutsideList;
420
421impl Lower for EntryOutsideList {
422    fn lower(
423        &self,
424        _node: NodeRef<'_, Flm>,
425        _cx: &mut LowerCx<'_>,
426        _lw: &mut dyn Lowerer,
427    ) -> Result<Lowering, LowerError> {
428        Err(LowerError::structure("an entry of a list of cited works must be inside its list"))
429    }
430}
431
432/// Declares the list of cited works and the bibliography for the feature that
433/// `b` registers: the two synthesized elements and their general rules, the
434/// piece table, its builder stage, and the piece's declaration, contributed
435/// as a peer contribution to the `pieces` feature's service slot
436/// ([`pieces::SLOT`]). Without the `pieces` feature, the list is built and no
437/// backend places it.
438pub(super) fn declare(
439    b: &mut FeatureBuilder<'_>,
440    owner: &FeatureName,
441    settings: &Arc<MarkSettings>,
442) -> Result<(), BuildError> {
443    let block = || Arc::new(FixedBlockRole(BlockRole::Block)) as Arc<dyn BlockRoleAspect>;
444    b.element(
445        ElementDef::new(
446            owner.clone(),
447            Vec::<&str>::new(),
448            SyntaxDef::Synthesized,
449            Arc::new(ElementSpec::new(BIBLIOGRAPHY).docs("A list of cited works.").with(block())),
450        )
451        .docs("A list of cited works. An author never writes it: a stage builds it."),
452    )?;
453    b.element(
454        ElementDef::new(
455            owner.clone(),
456            Vec::<&str>::new(),
457            SyntaxDef::Synthesized,
458            Arc::new(ElementSpec::new(BIBLIOGRAPHY_ENTRY).docs("One entry of a list of cited works.").with(block())),
459        )
460        .docs("One entry of a list of cited works. An author never writes it: a stage builds it."),
461    )?;
462    b.element_type_text(BIBLIOGRAPHY, "The list of the works a document cites, one entry per work.")?;
463    b.element_type_text(
464        BIBLIOGRAPHY_ENTRY,
465        "One entry of the list of cited works: the mark of one work and its reference.",
466    )?;
467    b.lowering_rule(
468        LoweringRule::new(
469            BIBLIOGRAPHY_RULE,
470            BIBLIOGRAPHY,
471            LoweringDecl::new()
472                .produces(pres::BLOCK)
473                .produces(pres::BLOCK_HEADING)
474                .produces(pres::LIST)
475                .produces(pres::SPAN)
476                .produces(pres::PAR)
477                .produces(pres::DROPPED),
478            Arc::new(BibliographyRule { settings: Arc::clone(settings) }),
479            DefaultMark::Everywhere,
480        )
481        .docs(
482            "a list of cited works lowers to a `flm.pres.block` holding the title as a \
483             `flm.pres.block-heading` and a labeled `flm.pres.list` with one entry per work, its \
484             number as the label",
485        ),
486    )?;
487    b.lowering_rule(
488        LoweringRule::new(
489            BIBLIOGRAPHY_ENTRY_RULE,
490            BIBLIOGRAPHY_ENTRY,
491            LoweringDecl::new(),
492            Arc::new(EntryOutsideList),
493            DefaultMark::Everywhere,
494        )
495        .docs("an entry of a list of cited works is lowered by its list's rule; lowered on its own, it fails"),
496    )?;
497    b.table_named::<Piece>(
498        BIBLIOGRAPHY,
499        "The list of the cited works of the document, as a synthesized value, or nothing to place.",
500    )?;
501    b.stage(Arc::new(BuildBibliography { placement: settings.config().placement }))?;
502    // The pieces feature owns the slot, and may be absent: the list is then
503    // placed by no backend.
504    b.peer_slot(
505        pieces::SLOT,
506        Arc::new(PieceDecl::new(
507            BIBLIOGRAPHY,
508            PiecePlace::AfterContent,
509            "the list of the cited works, placed after the document's content",
510        )),
511    )?;
512    Ok(())
513}