flm_core/stdlib/features/xnotes/mark_of.rs
1//! An xnote in content shown again: the element [`MARK_OF`] of the node that
2//! represents the xnote in the copy, its payload [`MarkOf`], and its general
3//! lowering rule [`MarkOfRule`].
4//!
5//! Content of the document that holds an xnote is shown a second time, away
6//! from where it is written, when a reference prints a heading's title, an
7//! unnumbered float's caption or a defined term, or a list item's tag. The
8//! xnote there is not a second xnote: its number, its labels and its place in
9//! its kind's list are the ones it has where it was written. So when such
10//! content is copied to be shown again, the xnote's element returns, through
11//! its [`InCopy`] aspect, which the copy consults, a new node that represents
12//! the xnote: a node of the element [`MARK_OF`], with no children,
13//! carrying a [`MarkOf`] payload that identifies the node carrying the
14//! xnote. Nothing of the xnote itself is copied: no labels, no content. A
15//! node carrying several xnotes becomes one node of the copy that represents
16//! all of them, written as their marks side by side, in the node's order.
17//! Another feature's element that carries xnotes returns the same node,
18//! through [`copied_as`]. A copy made for content that a [synthesized
19//! value](crate::guide::concepts_overview#synthesized-values) holds as its
20//! own ([`ValueContent::Own`]: the use site of a user definition copied to be
21//! expanded in place, content copied only to be read) holds the xnote as
22//! written.
23//!
24//! The general rule writes that node as the xnote's mark: the superscript mark
25//! text in the kind's mark style, inside a link to the xnote that carries the
26//! accessible name (`Footnote 1`), as the xnote's own mark is written where
27//! the xnote is written ([`stage_mark`](super::stage_mark)), with one
28//! difference: it carries **no anchor**. The mark's anchor is the one where
29//! the xnote is written, which the xnote's entry in its list links back to,
30//! and a page holds each anchor once. The mark of an in-place xnote kind is
31//! written in the same way, as a link to the xnote where it was written.
32//! Content shown again is usually inside a link of its own (a reference is a
33//! link to its target), so the mark's link is then inside another link; a
34//! backend writes that as it writes any link inside a link (the HTML page
35//! writes the inner one as its text). Nothing is added to any list, and
36//! nothing is reported: the xnote reports its problems where it was written.
37//!
38//! On the recomposed LaTeX the node writes nothing
39//! ([`MarkOfLatexRule`](super::latex::MarkOfLatexRule)), because no rule of
40//! the standard features lowers content shown again on that backend.
41
42use std::sync::{Arc, OnceLock};
43
44use techy::core::node::NodeRef;
45use techy::serialize::SerialValue;
46
47use crate::core::lowering::{
48 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
49};
50use crate::lang::copy::ValueContent;
51use crate::lang::mint::FlmSynthesizedSpec;
52use crate::lang::{Flm, FlmSpan, PresPayload};
53use crate::model::aspects::{CopiedAs, InCopy, StandIn};
54use crate::model::element::ElementSpec;
55use crate::stdlib::backends::pres;
56use crate::stdlib::features::numbering::COUNTERS;
57use crate::stdlib::features::refs;
58
59use super::config::XnoteKind;
60use super::lower::{report_missing, write_mark, Mark};
61use super::stages::{XnoteRecord, XNOTES};
62use super::{XnoteElement, MARK_OF, MARK_OF_RULE};
63
64/// The payload of a node of the element [`MARK_OF`]: the xnotes that the
65/// node represents in content shown again, which are every xnote of the given
66/// xnote kinds that the original node (the node the copy was made from)
67/// carries.
68///
69/// The payload identifies the xnotes by their kinds and by the source span of
70/// their node (the source and the range where it was written), which the copy
71/// keeps for every node it copies: the rule finds the xnotes' records among
72/// the kinds' records written at that span
73/// ([`Xnotes::records_written_at`](super::Xnotes::records_written_at)). A node
74/// of a copy has no address among the document's, so the span is what
75/// identifies the original node.
76#[derive(Debug, Clone)]
77pub struct MarkOf {
78 /// The xnote kinds of the xnotes that the node represents: the kinds of
79 /// the xnotes its original node carries, each once.
80 pub kinds: Vec<Arc<XnoteKind>>,
81 /// The source span of the xnotes' node, where it was written.
82 pub original: FlmSpan,
83}
84
85impl PresPayload for MarkOf {
86 /// `{kinds: [<each kind's name>], original: "@<start>-<end>"}`: the kinds,
87 /// and the byte range where the xnotes' node was written.
88 fn project(&self) -> SerialValue {
89 SerialValue::Map(vec![
90 (
91 String::from("kinds"),
92 SerialValue::List(
93 self.kinds.iter().map(|kind| SerialValue::Str(kind.name.to_string())).collect(),
94 ),
95 ),
96 (
97 String::from("original"),
98 SerialValue::Str(format!("@{}-{}", self.original.start(), self.original.end())),
99 ),
100 ])
101 }
102}
103
104impl MarkOf {
105 /// The payload of the node `node`, or `None` for a node that carries no
106 /// payload or a payload of another type.
107 pub fn of<'n>(node: &'n NodeRef<'_, Flm>) -> Option<&'n MarkOf> {
108 node.ext().payload.as_deref()?.downcast_ref::<MarkOf>()
109 }
110}
111
112/// What the element of `node`, a node carrying xnotes of the xnote kinds
113/// `kinds`, returns from its [`InCopy`] aspect, for a copy made for
114/// `purpose`: in content copied to be shown again ([`ValueContent::Shown`]),
115/// one node of the element [`MARK_OF`] that represents every xnote of those
116/// kinds the node carries ([`MarkOf`]), written as their marks; in a copy of
117/// content that a synthesized value holds as its own ([`ValueContent::Own`]),
118/// the node copied as written.
119///
120/// The element of `\footnote` passes its one xnote kind; another feature's
121/// element carrying xnotes passes the kinds of its xnotes, each once, so that
122/// its xnotes are shown in a copy as those of `\footnote` are. The element
123/// [`MARK_OF`] belongs to the `xnotes` feature: in a registry without that
124/// feature, no rule writes the node. Its element specification is a single
125/// one, shared by every registry, because an element's [`InCopy`] aspect has
126/// no access to a registry to take it from; the specification holds nothing a
127/// registry configures, and would have to become each registry's own if it
128/// came to depend on a configuration.
129pub fn copied_as(node: &NodeRef<'_, Flm>, purpose: ValueContent, kinds: Vec<Arc<XnoteKind>>) -> CopiedAs {
130 match purpose {
131 ValueContent::Own => CopiedAs::Verbatim,
132 ValueContent::Shown => {
133 let payload = MarkOf { kinds, original: node.span().clone() };
134 CopiedAs::StandIn(StandIn { spec: Arc::clone(mark_of_spec()), payload: Some(Arc::new(payload)) })
135 }
136 }
137}
138
139/// In content copied to be shown again, an xnote becomes one node of the
140/// element [`MARK_OF`] that identifies it ([`MarkOf`]), written as its mark;
141/// in a copy of content that a synthesized value holds as its own
142/// ([`ValueContent::Own`]), it is copied as written ([`copied_as`]).
143impl InCopy for XnoteElement {
144 fn in_copy(&self, node: &NodeRef<'_, Flm>, purpose: ValueContent) -> CopiedAs {
145 copied_as(node, purpose, vec![Arc::clone(&self.kind)])
146 }
147}
148
149/// The specification of the nodes that represent xnotes in content shown
150/// again, and its element, the one that the feature registers as
151/// [`MARK_OF`]: inline content, keeping the whitespace around it as the copy
152/// holds it. It is the same for every registry, since it holds nothing a
153/// registry configures.
154pub(super) fn mark_of_spec() -> &'static Arc<FlmSynthesizedSpec> {
155 static SPEC: OnceLock<Arc<FlmSynthesizedSpec>> = OnceLock::new();
156 SPEC.get_or_init(|| {
157 let element = ElementSpec::new(MARK_OF)
158 .docs("The mark of an xnote, written in its place in content shown again.");
159 Arc::new(FlmSynthesizedSpec::new(Arc::new(element)))
160 })
161}
162
163/// The general rule of the element [`MARK_OF`], [`MARK_OF_RULE`], marked
164/// default on every backend; the recomposed LaTeX uses a rule of its own that
165/// writes nothing.
166pub(super) fn mark_of_rule() -> LoweringRule {
167 LoweringRule::new(
168 MARK_OF_RULE,
169 MARK_OF,
170 LoweringDecl::new()
171 .reads(XNOTES)
172 .reads_opt(COUNTERS)
173 .reads_opt(refs::ANCHORS)
174 .produces(pres::SPAN)
175 .produces(pres::LINK),
176 Arc::new(MarkOfRule),
177 DefaultMark::Everywhere,
178 )
179 .docs(
180 "an xnote in content shown again lowers to the xnote's mark, a superscript \
181 `flm.pres.span` holding the mark text inside a `flm.pres.link` to the xnote, with no \
182 anchor",
183 )
184}
185
186/// The general lowering rule of the element [`MARK_OF`], [`MARK_OF_RULE`]:
187/// the marks of the xnotes that the node represents ([`MarkOf`]).
188///
189/// Each mark is one `flm.pres.span { style: Superscript, role:
190/// flm.xnotes.xnote.mark }` holding the mark text
191/// ([`stage_mark_text`](super::stage_mark_text)) inside a `flm.pres.link` to
192/// the xnote, as the xnote's own mark is written where the xnote is written
193/// ([`stage_mark`](super::stage_mark)) but with no anchor, regardless of the
194/// kind's placement: the mark's anchor is the one where the xnote is written.
195///
196/// The rule finds the xnotes among their kinds' records by the span where
197/// their node was written: every record of those kinds written there, each
198/// written as its mark, side by side, in the order of the node's points (the
199/// order in which the node's element returns its xnotes). Where the table of
200/// xnotes holds none, the rule writes nothing and reports
201/// `flm.run.missing-entry`, as the xnote's own rule does. It reports nothing
202/// else: the problems of an xnote (an empty content, a refused optional
203/// argument) are reported where it was written.
204#[derive(Debug, Default, Clone, Copy)]
205pub struct MarkOfRule;
206
207impl Lower for MarkOfRule {
208 fn lower(
209 &self,
210 node: NodeRef<'_, Flm>,
211 cx: &mut LowerCx<'_>,
212 lw: &mut dyn Lowerer,
213 ) -> Result<Lowering, LowerError> {
214 let mark_of =
215 MarkOf::of(&node).ok_or_else(|| LowerError::structure("a mark of an xnote without its payload"))?;
216 let mut found: Vec<(Arc<XnoteKind>, XnoteRecord)> = match lw.get(XNOTES)? {
217 None => Vec::new(),
218 Some(xnotes) => mark_of
219 .kinds
220 .iter()
221 .flat_map(|kind| {
222 xnotes
223 .records_written_at(kind.name.as_str(), &mark_of.original)
224 .map(|record| (Arc::clone(kind), record.clone()))
225 })
226 .collect(),
227 };
228 if found.is_empty() {
229 report_missing(lw, &node);
230 return Ok(Lowering::Emit(Vec::new()));
231 }
232 // Every xnote of the kinds written at the span, in the node's order: a
233 // copy asks a node once, so the node's one stand-in stands for all its
234 // xnotes.
235 found.sort_by_key(|(_, record)| record.point);
236 let mut marks = Vec::with_capacity(found.len());
237 for (kind, record) in &found {
238 // No identifier, which is the mark's where the xnote stands.
239 marks.push(write_mark(cx, lw, kind, record, Mark { anchored: false, linked: true })?);
240 }
241 Ok(Lowering::Emit(marks))
242 }
243}