Skip to main content

flm_core/stdlib/features/xnotes/
lower.rs

1//! The general lowering rules of the xnote and of a list entry, and the
2//! public staging helpers that every rule writing an xnote calls.
3//!
4//! A lowering rule ([`Lower`]) stages (builds into the lowered tree, through
5//! the [`Lowerer`]) the presentation of one element for the backend being
6//! rendered; its default mark says on which backends it is chosen. The
7//! general rules of this module are marked default on every backend:
8//!
9//! - [`XnoteRule`] ([`XNOTE_RULE`](super::XNOTE_RULE)) writes an xnote where
10//!   it is written. For a listed xnote kind it writes the xnote's **mark**, a
11//!   superscript span linked to the xnote; for an in-place kind it writes the
12//!   xnote **in place**: one span holding the mark and the content where the
13//!   content is inline, one block holding the content's paragraphs where the
14//!   content holds blocks.
15//! - [`EntryRule`] ([`ENTRY_RULE`](super::ENTRY_RULE)) is the rule of an entry
16//!   of a list of xnotes lowered outside its list: it writes nothing and
17//!   reports it.
18//!
19//! The shapes are staged by public helpers, [`stage_mark`],
20//! [`stage_in_place`], [`stage_mark_text`] and [`append_to_last_paragraph`].
21//! The feature's own rules call them, and so does the rule of another
22//! feature's element that carries xnotes, so that every xnote is written in
23//! the same way; each helper states what it stages. The
24//! [module documentation of the feature](super) describes xnotes, xnote kinds
25//! and marks.
26
27use std::sync::Arc;
28
29use techy::core::node::{BuildId, NodeRef};
30
31use crate::core::lowering::{Lower, LowerCx, LowerError, Lowerer, Lowering, NodeRegion};
32use crate::core::run::MissingEntry;
33use crate::lang::rewrites::blocks::{argument_holds_blocks, slot_holds_blocks, stands_in_blocks};
34use crate::lang::text::{is_blank, plain_text};
35use crate::lang::{Flm, FlmGroupType};
36use crate::model::aspects::{BlockRole, PointId, block_role_of};
37use crate::model::element::element_value;
38use crate::model::names::{CapName, ElementName, Name};
39use crate::stdlib::backends::lowering::{lower_blocks_with_edges, lower_run};
40use crate::stdlib::backends::pres::{
41    self, BlockPayload, DocRole, LinkPayload, SpanPayload, SpanStyle,
42};
43use crate::stdlib::features::numbering::{self, COUNTERS, FormatOptions};
44use crate::stdlib::features::refs::{ANCHORS, CAPITAL_VARIANT};
45
46use super::config::{XnoteKind, XnotePlacement};
47use super::diagnostics::{BadLabelArgument, Empty, EntryOutsideList};
48use super::stages::{XNOTES, XnoteRecord};
49use super::{
50    contents_of_kind, labels_of, mark_style_name, XnoteElement, INPLACE_ROLE, KIND_XNOTES, LINK_KIND, MARK_ROLE,
51    STYLE,
52};
53
54/// How the brackets around an in-place xnote are written: the only
55/// difference between an in-place xnote written by the HTML rule and one
56/// written by the general rule.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum Brackets {
59    /// `[` and `]` are staged as text around the in-place xnote, before its
60    /// mark and after its content. Used by the general rule (the plain-text
61    /// output) and by any rule that writes the brackets as text.
62    Text,
63    /// No bracket is staged, and the output draws its own: the HTML page's
64    /// stylesheet draws them, so that a page's own stylesheet can replace
65    /// them.
66    Drawn,
67}
68
69/// The record that the table of xnotes holds for the `nth` xnote of the xnote
70/// kind `kind` that `node` carries, counting from 0, found among that kind's
71/// records by the node's address
72/// ([`Xnotes::records_at`](super::Xnotes::records_at)); `None` where the table
73/// holds no record for it.
74///
75/// # Errors
76///
77/// [`LowerError`] when `node` is not a node of the tree being lowered, when
78/// the calling rule did not declare that it reads [`XNOTES`], and when the
79/// table records the node's xnotes of another kind only: the caller passed
80/// the wrong kind.
81pub(super) fn find(
82    lw: &dyn Lowerer,
83    node: &NodeRef<'_, Flm>,
84    kind: &XnoteKind,
85    nth: usize,
86) -> Result<Option<XnoteRecord>, LowerError> {
87    let addr = lw.addr_of(node)?;
88    let Some(xnotes) = lw.get(XNOTES)? else {
89        return Ok(None);
90    };
91    let mut of_kind = xnotes.records_at(kind.name.as_str(), addr).peekable();
92    if of_kind.peek().is_some() {
93        return Ok(of_kind.nth(nth).cloned());
94    }
95    if let Some((other, _)) = xnotes.record_at(addr) {
96        return Err(LowerError::structure(format!(
97            "the xnote is recorded of the kind `{other}`, and was written as one of the kind `{}`",
98            kind.name
99        )));
100    }
101    Ok(None)
102}
103
104/// The content of one xnote of a node, as the node's
105/// [`XnoteSource`](super::XnoteSource) aspect returns it.
106pub(super) enum Content<'t> {
107    /// A region of the node, and its content nodes: `None` for an argument a
108    /// parse recovery left absent, or a region the node does not have.
109    Region(NodeRegion, Option<Vec<NodeRef<'t, Flm>>>),
110    /// The node's aspect returns no xnote at that position.
111    Nothing,
112}
113
114impl<'t> Content<'t> {
115    /// The content of the `nth` xnote of the xnote kind `kind` that `node`
116    /// carries, counting from 0: the `nth` of that kind that the node's
117    /// [`XnoteSource`](super::XnoteSource) aspect returns, under the pairing
118    /// that aspect states.
119    pub(super) fn of(node: &NodeRef<'t, Flm>, kind: &XnoteKind, nth: usize) -> Content<'t> {
120        let Some(region) = contents_of_kind(node, kind.name.as_str()).get(nth).copied() else {
121            return Content::Nothing;
122        };
123        let nodes = if region.is_absent(node) { None } else { region.content_nodes(node) };
124        Content::Region(region, nodes)
125    }
126
127    /// The content nodes: none for no content, and for an argument a parse
128    /// recovery left absent.
129    pub(super) fn nodes(&self) -> &[NodeRef<'t, Flm>] {
130        match self {
131            Content::Region(_, Some(nodes)) => nodes,
132            Content::Region(_, None) | Content::Nothing => &[],
133        }
134    }
135
136    /// Whether the content holds nothing but whitespace (`~` and `\ `
137    /// included) and comments. An argument a parse recovery left absent is
138    /// not empty: the parse has reported it.
139    fn is_empty(&self) -> bool {
140        match self {
141            Content::Region(_, None) => false,
142            Content::Region(_, Some(nodes)) => !nodes.iter().any(is_content),
143            Content::Nothing => true,
144        }
145    }
146
147    /// Whether the block-structure pass laid the content out as blocks: for an
148    /// argument as [`argument_holds_blocks`] says, for a slot as
149    /// [`slot_holds_blocks`] says.
150    pub(super) fn holds_blocks(&self, node: &NodeRef<'_, Flm>) -> bool {
151        match self {
152            Content::Region(NodeRegion::Argument(index), _) => argument_holds_blocks(node, *index),
153            Content::Region(NodeRegion::Slot(index), _) => slot_holds_blocks(node, *index),
154            Content::Nothing => false,
155        }
156    }
157}
158
159/// Whether `node` is content: anything but a comment and a blank node
160/// ([`is_blank`]: whitespace-only text, and a node that is whitespace, such as
161/// `~` and `\ `), so `\footnote{~}` is as empty as `\footnote{ }`.
162fn is_content(node: &NodeRef<'_, Flm>) -> bool {
163    !(node.is_comment() || is_blank(node))
164}
165
166/// Whether `node` is a paragraph that the block-structure pass built.
167fn is_paragraph(node: &NodeRef<'_, Flm>) -> bool {
168    node.group_type() == Some(FlmGroupType::Paragraph)
169}
170
171/// Stages (builds into the lowered tree, through `lw`; see [`Lowerer`]) the
172/// mark of one xnote that the node `node` carries, of the xnote kind `kind`: the shape a listed kind writes where the xnote was written.
173/// It also reports the problems of the xnote: [`Empty`](super::Empty) and
174/// `flm.run.missing-entry`, in the cases listed below.
175///
176/// It writes the mark alone, never the content: the content is shown, and
177/// lowered once, where the kind's list shows it.
178///
179/// **What the caller passes.** `node` is the node being lowered: a node
180/// carrying xnotes, whose element implements
181/// [`XnoteSource`](super::XnoteSource) and returns its reference points with
182/// [`ref_points`](super::ref_points), so that the table [`XNOTES`] records
183/// it. `kind` is the kind of the xnote written, the one the caller declared
184/// through [`contribute_kind`](super::contribute_kind). `nth` is the xnote's
185/// position among the node's xnotes of that kind, counting from 0: the record
186/// and the content of that xnote are the ones paired as
187/// [`XnoteSource`](super::XnoteSource) states. An element carrying one xnote
188/// of the kind passes `0`; an element carrying several calls the helper once
189/// for each, with `0`, `1`, …, and places the marks where it writes them,
190/// side by side in that order or apart.
191///
192/// **What the calling rule must declare.** It must declare that it reads
193/// [`XNOTES`] and that it produces `flm.pres.span` and `flm.pres.link`. It may
194/// declare optional reads of the numbering feature's counter table
195/// [`COUNTERS`] and of the references feature's anchors table [`ANCHORS`]:
196/// without the first, the mark has no number; without the second, it has no
197/// anchor and no link.
198///
199/// **What it stages.** For an xnote that the table records, it stages one
200/// `flm.pres.span { style: Superscript, role: flm.xnotes.xnote.mark, anchor:
201/// <the mark's anchor> }` holding a
202/// `flm.pres.link { href: "#<the xnote's anchor>", kind: xnote, doc_role:
203/// NoteRef, label: "<Word> <n>" }`, which holds the mark text
204/// ([`stage_mark_text`]). The link's label is its accessible name, the name
205/// that assistive technology reads in place of the link's text: the kind's
206/// singular word (its capital variant, where one is declared) with its
207/// non-breaking space made a space, then the xnote's number as a reference
208/// writes it without the word (`Footnote 1`); the word alone where there is
209/// no number. The word is read as plain text: `~` and the non-breaking space
210/// become spaces, and any other markup in it appears as written. The span is
211/// staged regardless of the mark text, so that the mark's anchor exists for
212/// the link back to it; an empty mark text gives an empty span. Where the
213/// xnote has no anchor (in a registry without the references feature, or for
214/// a numbered xnote with no number and no label), there is no link, and the
215/// span holds the mark text alone.
216///
217/// **Other cases.** An xnote written inside another xnote's content is an
218/// xnote like any other: its mark is written where it is written, which is
219/// where the other xnote's content is shown. A node for which the table holds
220/// no record is written as nothing and reported as the Error
221/// `flm.run.missing-entry`: a node of the document that the collect stage did
222/// not reach, or an xnote in content that the run builds itself, apart from
223/// the document's trees (for instance a list's own label template, whose
224/// xnote is not one the document wrote at that place). A position `nth`
225/// beyond the node's recorded xnotes of the kind is likewise written as
226/// nothing and reported as `flm.run.missing-entry`. Content shown again (a
227/// heading's title that a reference shows) holds no xnote, only the node that
228/// represents it ([`MarkOf`](super::MarkOf)), which
229/// [`MarkOfRule`](super::MarkOfRule) writes as the mark.
230///
231/// An xnote with no content is still written, and is reported as the Warning
232/// [`Empty`](super::Empty).
233///
234/// # Errors
235///
236/// [`LowerError`] when `node` is not a node of the tree being lowered, when
237/// the calling rule did not declare what it reads or produces, when `kind` is
238/// not the kind the table records for `node`, and from the staging of the
239/// nodes.
240pub fn stage_mark(
241    cx: &mut LowerCx<'_>,
242    lw: &mut dyn Lowerer,
243    node: &NodeRef<'_, Flm>,
244    kind: &XnoteKind,
245    nth: usize,
246) -> Result<Vec<BuildId>, LowerError> {
247    let Some(record) = find(lw, node, kind, nth)? else {
248        report_missing(lw, node);
249        return Ok(Vec::new());
250    };
251    report_empty(lw, node, kind, nth)?;
252    let mark = Mark { anchored: true, linked: true };
253    Ok(vec![write_mark(cx, lw, kind, &record, mark)?])
254}
255
256/// Stages (builds into the lowered tree, through `lw`; see [`Lowerer`]) one
257/// xnote that the node `node` carries, of the xnote kind `kind`, in place: the shape an in-place kind writes where the xnote was written. It
258/// also reports the problems of the xnote: [`Empty`](super::Empty) and
259/// `flm.run.missing-entry`, in the cases that [`stage_mark`] lists.
260///
261/// **What the caller passes** is what [`stage_mark`] states, `nth` included:
262/// an element carrying several xnotes of an in-place kind calls the helper
263/// once for each, and each xnote is written in place with its own mark and
264/// content. A position beyond the node's recorded xnotes of the kind is
265/// written as nothing and reported as `flm.run.missing-entry`. `brackets`
266/// says how the brackets around the xnote are written: as text
267/// ([`Brackets::Text`], the general rule) or not at all
268/// ([`Brackets::Drawn`], the HTML page, whose stylesheet draws them); nothing
269/// else differs.
270///
271/// **What the calling rule must declare.** It must declare that it reads
272/// [`XNOTES`] and that it produces `flm.pres.span`, `flm.pres.block` and
273/// `flm.pres.par`; it may declare optional reads of [`COUNTERS`] and
274/// [`ANCHORS`], as for [`stage_mark`].
275///
276/// **What it stages.** For an xnote that the table records and whose content
277/// is inline, it stages
278///
279/// ```text
280/// flm.pres.span { role: flm.xnotes.xnote.inplace, kinds: [xnotes, <kind>],
281///                 anchor: <the xnote's anchor>, doc_role: Footnote }
282///   ├ "["
283///   ├ flm.pres.span { style: Superscript, role: flm.xnotes.xnote.mark,
284///   │                 anchor: <the mark's anchor> }  [ the mark text ]
285///   ├ the content, lowered through the rules
286///   └ "]"
287/// ```
288///
289/// The mark span holds no link, since the xnote is right beside it. Where the
290/// xnote is a block (its content holds paragraphs, and its element's block
291/// role makes it a block of its own), it stages instead a `flm.pres.block` of
292/// the same role, kinds, anchor and document role, whose children are the
293/// content's paragraphs and blocks lowered as they are, with `[` and the mark
294/// span at the head of the first paragraph and `]` at the end of the last
295/// ([`append_to_last_paragraph`]). A block that the block-structure pass kept
296/// where it was written in an inline region (a heading's title, `\text{…}`,
297/// the argument of `\textbf{…}`) is written in the inline shape, its
298/// paragraphs' runs joined by a space: the block-structure pass has reported
299/// it (`flm.blocks.block-in-inline`), and nothing more is reported.
300///
301/// An xnote inside another xnote's content is written in the same shapes,
302/// where that content is shown; the other cases are the ones [`stage_mark`]
303/// states.
304///
305/// # Errors
306///
307/// As [`stage_mark`], and from the lowering of the content.
308pub fn stage_in_place(
309    cx: &mut LowerCx<'_>,
310    lw: &mut dyn Lowerer,
311    node: &NodeRef<'_, Flm>,
312    kind: &XnoteKind,
313    nth: usize,
314    brackets: Brackets,
315) -> Result<Vec<BuildId>, LowerError> {
316    let Some(record) = find(lw, node, kind, nth)? else {
317        report_missing(lw, node);
318        return Ok(Vec::new());
319    };
320    report_empty(lw, node, kind, nth)?;
321    in_place(cx, lw, node, kind, nth, &record, brackets)
322}
323
324/// Stages (builds into the lowered tree, through `lw`; see [`Lowerer`]) the
325/// mark text of the xnote of the xnote kind `kind` whose own
326/// reference point is `point`: what a mark shows, in the running text and
327/// beside the xnote's entry in a list alike.
328///
329/// For a numbered kind, the mark text is the xnote's own number (never the
330/// parts of the counters it is numbered within), written in the kind's mark
331/// style ([`mark_style_name`](super::mark_style_name), `#{arabic}` by
332/// default; a declared counter style that a host replaces through the
333/// numbering feature's configuration), without word and delimiters: `1`. It
334/// is empty where the counter table is absent (a registry without the
335/// numbering feature, which the collect stage reports) or holds no number for
336/// the point (which the numbering feature reports). For an unnumbered kind,
337/// the mark text is the content of the kind's [`mark`](XnoteKind::mark)
338/// template, which holds no number placeholder: FLM text compiled when the
339/// registry was built, with the compiler of a numbered kind's mark, and read
340/// from the table of xnotes ([`Xnotes::fixed_mark`](super::Xnotes::fixed_mark)).
341/// `\dag` writes what the macro `\dag` writes, `~*` a non-breaking space and
342/// `*`, and the empty template nothing.
343///
344/// The calling rule must declare that it reads [`XNOTES`], and may declare an
345/// optional read of the numbering feature's counter table [`COUNTERS`].
346///
347/// # Errors
348///
349/// [`LowerError`] when the calling rule did not declare its reads of
350/// [`XNOTES`] and [`COUNTERS`], when the counter table holds no mark style
351/// for a numbered kind, when the number cannot be written in the mark style,
352/// and from the staging of the content.
353pub fn stage_mark_text(
354    cx: &mut LowerCx<'_>,
355    lw: &mut dyn Lowerer,
356    kind: &XnoteKind,
357    point: PointId,
358) -> Result<Vec<BuildId>, LowerError> {
359    if !kind.numbered {
360        // The fixed mark is compiled once, when the registry is built; a
361        // lowering rule cannot reach the registry, so the compiled content
362        // travels in the table of xnotes.
363        let Some(xnotes) = lw.get(XNOTES)? else { return Ok(Vec::new()) };
364        let trees = xnotes.fixed_mark(kind.name.as_str()).to_vec();
365        let mut staged = Vec::new();
366        for tree in &trees {
367            staged.extend(lw.splice(cx, tree)?);
368        }
369        return Ok(staged);
370    }
371    let segments = {
372        let Some(counters) = lw.get(COUNTERS)? else { return Ok(Vec::new()) };
373        let Some(record) = counters.record(point) else { return Ok(Vec::new()) };
374        let name = mark_style_name(kind.name.as_str());
375        let style = counters.style(&name).ok_or_else(|| {
376            LowerError::structure(format!("the counter table carries no mark style `{name}`"))
377        })?;
378        // The own number alone: no parent, so no part of a counter the kind
379        // is numbered within: the mark only has to find the note on the page,
380        // and the reference is what shows the full number.
381        let options = FormatOptions::new().without_word().without_delimiters();
382        numbering::format(&record.value, style, None, &options)
383            .map_err(|error| LowerError::structure(error.to_string()))?
384    };
385    let mut staged = Vec::new();
386    for segment in &segments {
387        staged.extend(lw.splice(cx, segment.content())?);
388    }
389    Ok(staged)
390}
391
392/// Lowers `content`, a run of sibling nodes holding paragraphs and blocks or
393/// holding inline content, as blocks, with `appended` at the end of the last
394/// paragraph's inline run, and returns the blocks.
395///
396/// This is how something is added after the last words of content that may
397/// hold paragraphs: the closing bracket of an in-place xnote, or the link
398/// back from an entry of a list of xnotes to its mark. `appended` holds nodes
399/// that the caller staged and placed nowhere else.
400///
401/// - Inline content (no paragraph and no block among the nodes) becomes one
402///   `flm.pres.par` holding the content lowered through the rules, then
403///   `appended`.
404/// - Content holding blocks is lowered block by block: each paragraph becomes
405///   a `flm.pres.par` of its inline run lowered through the rules, with
406///   `appended` at the end of the last one; every other block is lowered by
407///   its rule. Content whose last block is not a paragraph (a list, for
408///   example) gets one more `flm.pres.par`, holding `appended` alone.
409/// - Empty content with nothing appended gives nothing.
410///
411/// The function is the lowering feature's
412/// [`lower_blocks_with_edges`](crate::stdlib::backends::lowering::lower_blocks_with_edges)
413/// with nothing at the head. The calling rule stages every paragraph through
414/// [`lower_paragraph`](crate::stdlib::backends::lowering::lower_paragraph),
415/// the only function that stages a paragraph, so a rule that replaces the
416/// paragraph rule is not consulted for these paragraphs. The calling rule
417/// must declare that it produces `flm.pres.par`.
418pub fn append_to_last_paragraph(
419    cx: &mut LowerCx<'_>,
420    lw: &mut dyn Lowerer,
421    content: &[NodeRef<'_, Flm>],
422    appended: Vec<BuildId>,
423) -> Result<Vec<BuildId>, LowerError> {
424    lower_blocks_with_edges(cx, lw, content, Vec::new(), appended)
425}
426
427/// Reports `flm.run.missing-entry` at `node`, a node for which the table of
428/// xnotes holds no record, with the table, the stage that writes it and the
429/// node's element.
430pub(super) fn report_missing(lw: &mut dyn Lowerer, node: &NodeRef<'_, Flm>) {
431    let table = CapName::from(XNOTES.name());
432    let producer = lw.producer_of(&table).map(|stage| stage.to_string()).unwrap_or_else(|| "nobody".to_string());
433    let element = node.ext().element.name.to_string();
434    lw.error(MissingEntry { table: table.to_string(), producer, element }, node.span().clone());
435}
436
437/// Reports [`Empty`] for the `nth` xnote of the xnote kind `kind` that `node`
438/// carries, when its content holds nothing.
439pub(super) fn report_empty(
440    lw: &mut dyn Lowerer,
441    node: &NodeRef<'_, Flm>,
442    kind: &XnoteKind,
443    nth: usize,
444) -> Result<(), LowerError> {
445    if Content::of(node, kind, nth).is_empty() {
446        lw.warning(Empty { kind: kind.name.to_string() }, node.span().clone());
447    }
448    Ok(())
449}
450
451/// The anchors of the mark and of the xnote of `record`, from the anchors
452/// table where the plan computes it.
453///
454/// # Errors
455///
456/// [`LowerError`] when the calling rule did not declare its read of
457/// [`ANCHORS`].
458pub(super) fn identifiers(
459    lw: &dyn Lowerer,
460    record: &XnoteRecord,
461) -> Result<(Option<String>, Option<String>), LowerError> {
462    let Some(anchors) = lw.get(ANCHORS)? else { return Ok((None, None)) };
463    let id = |point| anchors.lookup(point).flatten().map(String::from);
464    Ok((id(record.mark), id(record.point)))
465}
466
467/// The accessible name of the link from the mark of the xnote whose point is
468/// `point` to the xnote: the kind's singular word (its capital variant, where
469/// one is declared) with its non-breaking spaces made spaces, then the
470/// xnote's number as a reference writes it without the word (`Footnote 1`);
471/// the word alone where there is no number.
472// The number a reference shows, not the mark's: the name identifies the
473// xnote as a reference does, whatever style the mark is written in.
474fn link_label(lw: &dyn Lowerer, kind: &XnoteKind, point: PointId) -> Result<String, LowerError> {
475    let words = kind.words.variants.get(CAPITAL_VARIANT).unwrap_or(&kind.words.base);
476    accessible_name(lw, kind, &words.one, point)
477}
478
479/// The accessible name of the xnote of the xnote kind `kind` whose point is
480/// `point`, spelled with `word`: `word` with its non-breaking spaces made
481/// spaces, then the xnote's number as a reference writes it without the word
482/// (`Footnote 1`); the word alone where there is no number; the number alone
483/// where the word is empty. Every link to or from an xnote takes its
484/// accessible name from this function.
485///
486/// # Errors
487///
488/// [`LowerError`] when the calling rule did not declare its read of
489/// [`COUNTERS`], and when the number cannot be written.
490pub(super) fn accessible_name(
491    lw: &dyn Lowerer,
492    kind: &XnoteKind,
493    word: &str,
494    point: PointId,
495) -> Result<String, LowerError> {
496    let word = word.replace(['~', '\u{a0}'], " ");
497    let word = word.trim();
498    let number = if kind.numbered {
499        match lw.get(COUNTERS)? {
500            None => None,
501            Some(counters) => counters
502                .format(point, &FormatOptions::new().without_word().without_delimiters())
503                .transpose()
504                .map_err(|error| LowerError::structure(error.to_string()))?
505                .map(|segments| segments.iter().map(|segment| plain_text(segment.content())).collect::<String>()),
506        }
507    } else {
508        None
509    };
510    Ok(match number.as_deref().map(str::trim) {
511        Some(number) if !number.is_empty() && !word.is_empty() => format!("{word} {number}"),
512        Some(number) if !number.is_empty() => number.to_string(),
513        _ => word.to_string(),
514    })
515}
516
517/// How a mark is written, beyond its text: whether its span carries the
518/// mark's anchor, and whether its text is a link to the xnote.
519///
520/// The mark written where the xnote is written carries the anchor, which the
521/// entry of a listed xnote links back to; a mark written in content shown
522/// again carries none, so that the anchor stays where the xnote is written
523/// and the page's anchors stay unique. A listed xnote's mark links to the
524/// xnote, and so does a mark in content shown again; the mark of an in-place
525/// xnote written where the xnote is written does not, because its content is
526/// written right beside it.
527#[derive(Debug, Clone, Copy)]
528pub(super) struct Mark {
529    /// Whether the span carries the mark's anchor.
530    pub(super) anchored: bool,
531    /// Whether the mark text is a link to the xnote.
532    pub(super) linked: bool,
533}
534
535/// Stages the mark of the xnote of the xnote kind `kind` whose record is
536/// `record`, shaped as `mark` says: one
537/// `flm.pres.span { style: Superscript, role: flm.xnotes.xnote.mark }`,
538/// carrying the mark's anchor where `mark` is anchored and the plan computes
539/// one, and holding the mark text ([`stage_mark_text`]), inside a
540/// `flm.pres.link` to the xnote, with the document role `NoteRef` and the
541/// accessible name that [`stage_mark`] documents, where `mark` is linked and
542/// the xnote has an anchor. Every mark of an xnote in the running text is
543/// staged by this function.
544///
545/// # Errors
546///
547/// [`LowerError`] when the calling rule did not declare what it reads or
548/// produces, and from the staging of the mark text.
549pub(super) fn write_mark(
550    cx: &mut LowerCx<'_>,
551    lw: &mut dyn Lowerer,
552    kind: &XnoteKind,
553    record: &XnoteRecord,
554    mark: Mark,
555) -> Result<BuildId, LowerError> {
556    let (mark_anchor, xnote_anchor) = identifiers(lw, record)?;
557    let text = stage_mark_text(cx, lw, kind, record.point)?;
558    let body = match xnote_anchor.filter(|_| mark.linked) {
559        Some(anchor) => {
560            let link = LinkPayload {
561                href: format!("#{anchor}"),
562                kind: Name::from(LINK_KIND),
563                doc_role: Some(DocRole::NoteRef),
564                label: Some(link_label(lw, kind, record.point)?),
565                shows_target: false,
566            };
567            vec![lw.pres_with(cx, &ElementName::from(pres::LINK), link, text)?]
568        }
569        None => text,
570    };
571    let payload = SpanPayload {
572        style: Some(SpanStyle::Superscript),
573        role: Some(Name::from(MARK_ROLE)),
574        anchor: mark_anchor.filter(|_| mark.anchored),
575        ..SpanPayload::default()
576    };
577    lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)
578}
579
580/// Stages the `nth` xnote of the xnote kind `kind` that `node` carries,
581/// recorded as `record`, in place, in the shape that [`stage_in_place`]
582/// documents, with its brackets as `brackets` says.
583fn in_place(
584    cx: &mut LowerCx<'_>,
585    lw: &mut dyn Lowerer,
586    node: &NodeRef<'_, Flm>,
587    kind: &XnoteKind,
588    nth: usize,
589    record: &XnoteRecord,
590    brackets: Brackets,
591) -> Result<Vec<BuildId>, LowerError> {
592    let content = Content::of(node, kind, nth);
593    let kinds = vec![Name::from(KIND_XNOTES), kind.name.clone()];
594    let (_, anchor) = identifiers(lw, record)?;
595    let mut leading = Vec::new();
596    if brackets == Brackets::Text {
597        leading.push(lw.text(cx, "[")?);
598    }
599    leading.push(write_mark(cx, lw, kind, record, Mark { anchored: true, linked: false })?);
600    let trailing = match brackets {
601        Brackets::Text => vec![lw.text(cx, "]")?],
602        Brackets::Drawn => Vec::new(),
603    };
604    // The block the language layer made the xnote, where it stands among
605    // blocks; the inline shape wherever else it stands.
606    if matches!(block_role_of(node), BlockRole::Block) && stands_in_blocks(node, lw.layout()) {
607        let children = lower_blocks_with_edges(cx, lw, content.nodes(), leading, trailing)?;
608        let payload = BlockPayload {
609            role: Some(Name::from(INPLACE_ROLE)),
610            kinds,
611            anchor,
612            doc_role: Some(DocRole::Footnote),
613        };
614        return Ok(vec![lw.pres_with(cx, &ElementName::from(pres::BLOCK), payload, children)?]);
615    }
616    let run = if content.holds_blocks(node) {
617        lower_joined(cx, lw, content.nodes())?
618    } else {
619        lower_run(cx, lw, content.nodes())?
620    };
621    let payload = SpanPayload {
622        role: Some(Name::from(INPLACE_ROLE)),
623        kinds,
624        anchor,
625        doc_role: Some(DocRole::Footnote),
626        ..SpanPayload::default()
627    };
628    let body = [leading, run, trailing].concat();
629    Ok(vec![lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)?])
630}
631
632/// Lowers `content`, a run of paragraphs and blocks, as inline content: each
633/// paragraph's inline run, a space between two of them; every other node as
634/// the rules lower it.
635// The block-structure pass has already reported the block it kept where no
636// block can stand, and that report is the whole report; a block that is not a
637// paragraph has no inline form and is lowered as it stands, not dropped.
638fn lower_joined(
639    cx: &mut LowerCx<'_>,
640    lw: &mut dyn Lowerer,
641    content: &[NodeRef<'_, Flm>],
642) -> Result<Vec<BuildId>, LowerError> {
643    let mut out = Vec::new();
644    let mut after_block = false;
645    for node in content {
646        if node.is_comment() {
647            out.extend(lower_run(cx, lw, std::slice::from_ref(node))?);
648            continue;
649        }
650        if after_block {
651            out.push(lw.text(cx, " ")?);
652        }
653        if is_paragraph(node) {
654            out.extend(lw.lower_children(cx, node)?);
655        } else {
656            out.extend(lower_run(cx, lw, std::slice::from_ref(node))?);
657        }
658        after_block = true;
659    }
660    Ok(out)
661}
662
663/// Reports the first thing other than a `\label` that the optional argument
664/// of the xnote `node` holds, as [`BadLabelArgument`], at the xnote, wherever
665/// the xnote is lowered.
666pub(super) fn report_labels(lw: &mut dyn Lowerer, node: &NodeRef<'_, Flm>, kind: &XnoteKind) {
667    if let Some(first) = labels_of(node).1.into_iter().next() {
668        lw.error(BadLabelArgument { kind: kind.name.to_string(), found: first.found }, node.span().clone());
669    }
670}
671
672/// Lowers the xnote `node` of the element [`XNOTE`](super::XNOTE): reports
673/// the refused content of its optional argument, then stages its mark
674/// ([`stage_mark`]) for a listed xnote kind or the xnote in place
675/// ([`stage_in_place`]) for an in-place one, with its brackets as `brackets`
676/// says. The general rule and the HTML rule of the element call it, so that
677/// what they write differs in the brackets alone, and so does the element's
678/// rule on the `latex-rendered` backend
679/// ([`XnoteRenderedRule`](super::latex_rendered::XnoteRenderedRule)) for a
680/// listed xnote kind.
681///
682/// It first requires the feature's style identifier [`STYLE`]
683/// (`flm.xnotes.style`), which each backend resolves as it resolves
684/// requirements: the stylesheet on the `html` backend, the definition pieces
685/// delivering it on the `latex-rendered` backend, nothing on the `text`
686/// backend.
687pub(super) fn lower_xnote(
688    node: &NodeRef<'_, Flm>,
689    cx: &mut LowerCx<'_>,
690    lw: &mut dyn Lowerer,
691    brackets: Brackets,
692) -> Result<Lowering, LowerError> {
693    lw.require(&Name::from(STYLE));
694    let value = element_value::<XnoteElement>(node)
695        .ok_or_else(|| LowerError::structure("an xnote without its element's data"))?;
696    let kind = Arc::clone(&value.kind);
697    report_labels(lw, node, &kind);
698    // The element carries one xnote, the first of its kind.
699    let staged = match kind.placement {
700        XnotePlacement::List => stage_mark(cx, lw, node, &kind, 0)?,
701        XnotePlacement::InPlace => stage_in_place(cx, lw, node, &kind, 0, brackets)?,
702    };
703    Ok(Lowering::Emit(staged))
704}
705
706/// The general lowering rule of the element [`XNOTE`](super::XNOTE),
707/// [`XNOTE_RULE`](super::XNOTE_RULE), marked default on every backend.
708///
709/// It reports the refused content of the xnote's optional argument
710/// ([`BadLabelArgument`]), then writes the xnote's mark, as [`stage_mark`]
711/// stages it, for a listed xnote kind, and the xnote in place, as
712/// [`stage_in_place`] stages it with the brackets written as text, for an
713/// in-place kind. The plain-text backend uses this rule; the `html` backend
714/// uses [`XnoteHtmlRule`](super::html::XnoteHtmlRule), the
715/// `latex-recomposed` backend [`XnoteLatexRule`](super::latex::XnoteLatexRule)
716/// and the `latex-rendered` backend
717/// [`XnoteRenderedRule`](super::latex_rendered::XnoteRenderedRule).
718#[derive(Debug, Default)]
719pub struct XnoteRule;
720
721impl Lower for XnoteRule {
722    fn lower(
723        &self,
724        node: NodeRef<'_, Flm>,
725        cx: &mut LowerCx<'_>,
726        lw: &mut dyn Lowerer,
727    ) -> Result<Lowering, LowerError> {
728        lower_xnote(&node, cx, lw, Brackets::Text)
729    }
730}
731
732/// The lowering rule of the element [`ENTRY`](super::ENTRY),
733/// [`ENTRY_RULE`](super::ENTRY_RULE), marked default on every backend.
734///
735/// The rule of a list lowers the content of its entries itself and never
736/// lowers an entry, so an entry that reaches a lowering of its own was not
737/// written by its list: this rule writes nothing for it and reports it as
738/// [`EntryOutsideList`](super::EntryOutsideList).
739#[derive(Debug, Default)]
740pub struct EntryRule;
741
742impl Lower for EntryRule {
743    fn lower(
744        &self,
745        node: NodeRef<'_, Flm>,
746        _cx: &mut LowerCx<'_>,
747        lw: &mut dyn Lowerer,
748    ) -> Result<Lowering, LowerError> {
749        lw.error(EntryOutsideList, node.span().clone());
750        Ok(Lowering::Emit(Vec::new()))
751    }
752}