flm_core/model/aspects.rs
1//! The aspects that the standard features implement and read: block roles,
2//! reference points, reference sites, headings, content outside the
3//! surrounding text, what replaces a node in a copy of content, and whether a
4//! node is whitespace.
5//!
6//! An aspect is a piece of behavior attached to an element when a feature
7//! registers the element and read back through a trait object; it is evaluated per
8//! occurrence of the element and reads no options (see [elements and
9//! aspects](crate::guide::concepts_overview#elements-and-aspects)). An element
10//! holds its aspects in its [`AspectMap`](crate::model::element::AspectMap).
11//! A stage or a backend asks an element what it does by looking up an aspect
12//! ("is this a block?", "which reference points does this node carry?"), never
13//! by matching the element's name against a fixed list. A stage written today
14//! therefore works on an element that a feature written later declares.
15//!
16//! An aspect method has access to the element's own data, which its
17//! implementation holds, and receives the node it is asked about; [`InCopy`]
18//! also receives the purpose of the copy. No aspect method receives option
19//! values or anything else about the document as a whole or about the run. Two
20//! rules follow, and hold for every aspect of this module:
21//!
22//! - **An aspect is evaluated per occurrence.** The node is a parameter of every
23//! method, because the same element may give a different result at each
24//! place it occurs: one heading element declares a different reference point
25//! at every heading.
26//! - **An aspect reads no [options](crate::model::options).** A fact that
27//! varies from document to document is an option of the stage that uses the
28//! aspect's result, not of the aspect. A fact fixed by a feature's
29//! configuration is held by the element's data or by the aspect's
30//! implementation, both built when the registry is built.
31//!
32//! # The aspects defined here
33//!
34//! - [`BlockRoleAspect`] — whether an occurrence is a block, inline content, a
35//! displayed item or a block decorator ([`BlockRole`]); read with
36//! [`block_role_of`].
37//! - [`Referenceable`] — the [reference points](RefPoint) an occurrence
38//! carries: the places in the document that a reference can point at, each
39//! declaring which [label types](AcceptedRefTypes) may be written for it.
40//! - [`Referencing`] — the [reference sites](RefSite) an occurrence carries:
41//! the places that point at a reference point.
42//! - [`Sectioning`] — the heading level of an occurrence, whether it is
43//! listed in the table of contents, and what an entry of the table of
44//! contents shows for it.
45//! - [`ApartFromText`] — the content of an occurrence that is not part of the
46//! text around it, such as the words of a footnote written in a heading's
47//! title; read with [`apart_from_text_of`].
48//! - [`InCopy`] — what replaces an occurrence in a copy of content shown a
49//! second time, away from where it is written ([`CopiedAs`]): the occurrence
50//! as written, nothing, or a new node of the element's own; read with
51//! [`copied_as`].
52//! - [`Whitespace`] — that every occurrence is whitespace, such as the
53//! non-breaking space `~`: a marker with no method and no data, which the
54//! block-structure pass, the trimming of paragraphs at lowering and the
55//! features' tests for blank content read; read with [`is_whitespace_of`].
56//!
57//! The functions [`block_role_of`], [`apart_from_text_of`], [`copied_as`] and
58//! [`is_whitespace_of`] supply the result for an element that does not declare
59//! the aspect, so a caller reads those aspects through them rather than
60//! through the aspect map.
61//!
62//! This module holds the aspects that many features implement, and the
63//! aspects that state what an element is ([`Whitespace`]). An aspect that only
64//! one rewrite pass reads and that describes what that pass does with a node
65//! is declared beside that pass instead
66//! ([`Expand`](crate::lang::rewrites::userdefs::Expand),
67//! [`BlockStructure`](crate::lang::rewrites::blocks::BlockStructure)), since it
68//! has no meaning apart from that pass.
69//!
70//! # Content an aspect returns
71//!
72//! An aspect that returns document content returns a [`ContentRef`]: a
73//! reference to an argument or the body *of the node the aspect was asked
74//! about*, or to one node of that node's tree, rather than a copy of a tree.
75//! A reference into the node's own tree always designates content of that tree
76//! and is cheap to carry, whereas a copy would have to be stored and kept up to
77//! date.
78//!
79//! The exception is content that no node of the tree holds by itself: a label
80//! that a feature's configuration supplies, such as the bullet beside the items
81//! of a list, or a part of a run of characters, such as the value `Custom` of
82//! `tag=Custom`, which shares its node with the key. The aspect then builds
83//! that content as a small tree of its own and returns it
84//! ([`ContentRef::Synthesized`]).
85//!
86//! Labels and anchor identifiers are owned [`String`]s rather than shared
87//! names: a stage computes them per node while it scans the document and uses
88//! them as keys of the tables it writes, so every consumer needs plain
89//! comparable data.
90
91use std::fmt;
92use std::hash::{Hash, Hasher};
93use std::sync::Arc;
94
95use techy::core::node::{NodeId, NodeRef, NodeTree};
96
97use crate::model::addr::NodeAddr;
98use crate::model::names::{Name, RefKind};
99use crate::lang::copy::ValueContent;
100use crate::lang::mint::FlmSynthesizedSpec;
101use crate::lang::text::collapse_whitespace;
102use crate::lang::{Flm, FlmSpan, PresPayload};
103
104// --- block roles --------------------------------------------------------------------
105
106/// How an inline element treats the whitespace immediately before and after
107/// it: the data of [`BlockRole::Inline`].
108///
109/// Setting either field removes the whitespace on that side entirely, so that
110/// an element such as a citation mark can control its own spacing. The
111/// whitespace removed is every piece of whitespace between the element and the
112/// nearest content on that side, the nodes that are whitespace
113/// ([`Whitespace`], such as `~` and `\ `) included: before an element that
114/// absorbs the whitespace before it, `word~`, `word ~ ` and `word~~` all leave
115/// `word` alone. Source comments between the whitespace and the element do not
116/// prevent the removal, and are kept: in `word %% note` followed on the next
117/// line by the element, the space after `word` is removed too. Ordinary inline
118/// content keeps the spaces around it: [`InlineSpacing::CONTENT`].
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Deserialize)]
120#[derive(schemars::JsonSchema)]
121#[serde(deny_unknown_fields)]
122pub struct InlineSpacing {
123 /// Remove the whitespace immediately before the element.
124 pub absorb_before: bool,
125 /// Remove the whitespace immediately after the element.
126 pub absorb_after: bool,
127}
128
129impl InlineSpacing {
130 /// Ordinary inline content: the spaces on both sides are kept.
131 pub const CONTENT: InlineSpacing = InlineSpacing { absorb_before: false, absorb_after: false };
132}
133
134/// Where a block decorator is placed within its block: the data of
135/// [`BlockRole::BlockDecorator`].
136///
137/// A block decorator is an element attached to the block it occurs in, such as
138/// a run-in heading or the mark that closes a proof. The block-structure pass
139/// ([`crate::lang::rewrites::blocks`]) places it accordingly.
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Deserialize)]
141#[derive(schemars::JsonSchema)]
142#[serde(rename_all = "kebab-case")]
143pub enum Placement {
144 /// First in its block: a new block begins at the element, and the inline
145 /// content that follows it belongs to that block, as for a run-in heading.
146 Leads,
147 /// Last in its block: the block ends after the element, as for the mark
148 /// that closes a proof.
149 Trails,
150 /// Anywhere in its block; the element begins or ends no block.
151 Free,
152}
153
154/// The role of an occurrence in the block and paragraph structure: a block,
155/// inline content, a displayed item, or a block decorator.
156///
157/// The block-structure rewrite pass ([`crate::lang::rewrites::blocks`]) reads
158/// it to cut content into blocks: the pass begins a new block at each `Block`
159/// node and at each paragraph break, keeps `Inline` and `Displayed` nodes
160/// inside the surrounding block, and attaches a `BlockDecorator` to the block
161/// it occurs in. The pass removes the whitespace on both sides of a
162/// `Displayed` node, as it does beside an `Inline` node whose
163/// [`InlineSpacing`] absorbs the whitespace on both sides. When the pass trims
164/// the whitespace at the edges of a block, it looks past a decorator, so a
165/// decorator at an edge does not keep the whitespace beside it.
166///
167/// An element that declares no [`BlockRoleAspect`] has [`BlockRole::DEFAULT`];
168/// read an occurrence's role with [`block_role_of`].
169#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Deserialize)]
170#[derive(schemars::JsonSchema)]
171#[serde(rename_all = "kebab-case")]
172pub enum BlockRole {
173 /// A block of its own, between paragraphs.
174 Block,
175 /// Inline content inside a block, with the whitespace beside it treated as
176 /// the [`InlineSpacing`] says.
177 Inline(InlineSpacing),
178 /// A displayed item: a node that stands in inline content (a paragraph,
179 /// or any content region laid out inline) and is set on lines of its own,
180 /// with the whitespace beside it removed, such as a display equation. A
181 /// displayed item continues the paragraph it stands in, and may hold
182 /// anything: its own lowering rule lays its content out.
183 Displayed,
184 /// Attached to the block it occurs in, at the [`Placement`] given.
185 BlockDecorator(Placement),
186}
187
188impl BlockRole {
189 /// The role of an element that declares no [`BlockRoleAspect`]: ordinary
190 /// inline content, which keeps the whitespace around it.
191 pub const DEFAULT: BlockRole = BlockRole::Inline(InlineSpacing::CONTENT);
192}
193
194/// The aspect that gives the [`BlockRole`] of an occurrence.
195///
196/// The method receives the node, so an element that is a block in some places
197/// and inline content in others decides from the node: from its own content,
198/// from where it is placed, or from how it is written. A section command of a
199/// quotation (such as `\lines` or `\attributed`) is a block directly in the
200/// quotation's body and inline content elsewhere; an image is a block as a
201/// direct child of a float's body and inline content elsewhere; a mathematics
202/// group is a displayed item when written `\[…\]` or `$$…$$` and inline
203/// content when written `\(…\)` or `$…$`
204/// ([`StructuralElementSpecs::math`](crate::lang::structural::StructuralElementSpecs::math)).
205/// [`BlockRole`] therefore has no "either" variant: an element whose role
206/// depends on its content, its position or how it is written computes the
207/// role in this method.
208///
209/// Most elements have one fixed role and declare [`FixedBlockRole`]. Read the
210/// role of a node with [`block_role_of`], which supplies
211/// [`BlockRole::DEFAULT`] for an element that does not declare this aspect.
212pub trait BlockRoleAspect: Send + Sync {
213 /// The block role of this occurrence.
214 fn block_role(&self, node: &NodeRef<'_, Flm>) -> BlockRole;
215}
216
217/// A [`BlockRoleAspect`] that gives the same role for every occurrence.
218///
219/// Most elements declare this one: `FixedBlockRole(BlockRole::Block)` for a
220/// heading, `FixedBlockRole(BlockRole::DEFAULT)` for an emphasis command.
221///
222/// # Examples
223///
224/// ```
225/// use flm_core::model::aspects::{BlockRole, FixedBlockRole, InlineSpacing};
226///
227/// let heading = FixedBlockRole(BlockRole::Block);
228/// let emphasis = FixedBlockRole(BlockRole::DEFAULT);
229/// assert_eq!(heading.0, BlockRole::Block);
230/// assert_eq!(emphasis.0, BlockRole::Inline(InlineSpacing::CONTENT));
231/// ```
232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233pub struct FixedBlockRole(pub BlockRole);
234
235impl BlockRoleAspect for FixedBlockRole {
236 fn block_role(&self, _node: &NodeRef<'_, Flm>) -> BlockRole {
237 self.0
238 }
239}
240
241/// The block role of the node `node`: the role its element's
242/// [`BlockRoleAspect`] gives, or [`BlockRole::DEFAULT`] when its element does
243/// not declare that aspect.
244///
245/// Use this function to read a node's role. Reading the aspect map directly
246/// would leave every caller to supply the default for the many elements, such
247/// as plain text or an emphasis command, that do not declare the aspect.
248pub fn block_role_of(node: &NodeRef<'_, Flm>) -> BlockRole {
249 match node.ext().element.aspect::<dyn BlockRoleAspect>() {
250 Some(aspect) => aspect.block_role(node),
251 None => BlockRole::DEFAULT,
252 }
253}
254
255/// The aspect of an element each of whose nodes is whitespace, such as the
256/// non-breaking space `~` and the space `\ `; read with [`is_whitespace_of`].
257///
258/// Such a node is whitespace to the layout of paragraphs, and to the readers
259/// listed below, which ignore whitespace. The block-structure pass
260/// ([`crate::lang::rewrites::blocks`]) treats such a node as it treats text
261/// that is only whitespace, wherever it removes whitespace:
262///
263/// - beside an inline element that absorbs the whitespace on that side
264/// ([`InlineSpacing`]), the node is removed with the rest of the whitespace
265/// between the element and the nearest content;
266/// - on both sides of a displayed item ([`BlockRole::Displayed`]), the node
267/// is removed with the rest of the whitespace between the item and the
268/// nearest content;
269/// - at the start and at the end of a paragraph, the node is removed with the
270/// rest of the whitespace there;
271/// - the node is not paragraph content: a stretch holding only whitespace,
272/// such nodes and comments starts no paragraph, and between blocks it is
273/// removed;
274/// - a straight quote right after the node opens, as it does after a space
275/// (in `a~"x"`, the quote before `x` opens).
276///
277/// Everywhere else the pass keeps the node where it is written, as a node of
278/// its own: it is never merged into the text beside it and never collapsed
279/// with the whitespace around it (`a~~b` keeps its two nodes, `a~ b` the node
280/// and the space). A node that stays is lowered by its element's own lowering
281/// rule.
282///
283/// The other readers of the aspect treat such a node as they treat text that
284/// is only whitespace, and each makes the blank test of the first item below:
285///
286/// - the lowering helpers' blank test
287/// ([`is_blank`](crate::stdlib::backends::lowering::is_blank)), through
288/// which the helper that trims a paragraph a rule writes over content it
289/// cuts out itself
290/// ([`stage_trimmed`](crate::stdlib::backends::lowering::stage_trimmed):
291/// a quotation's passage, attribution and lines, a `\celldata` entry)
292/// removes the node at that paragraph's edges, and the quotation's and the
293/// `\celldata` reader's tests find a section or an entry holding only such
294/// nodes empty;
295/// - the readers of a list's body and of a float's body
296/// ([`list_items`](crate::stdlib::features::lists::list_items),
297/// [`float_body`](crate::stdlib::features::floats::float_body)), and the
298/// recomposed LaTeX of a list and of a quotation, which leaves the node out
299/// where it writes the layout itself;
300/// - an xnote's test for empty content
301/// ([`Empty`](crate::stdlib::features::xnotes::Empty): `\footnote{~}` is
302/// reported empty) and the reader of an xnote's labels argument
303/// ([`labels_of`](crate::stdlib::features::xnotes::labels_of));
304/// - the readers of a list's, an item's and a caption's bracket
305/// ([`list_options`](crate::stdlib::features::lists::list_options),
306/// [`item_options`](crate::stdlib::features::lists::item_options),
307/// [`read_caption`](crate::stdlib::features::floats::read_caption)): a
308/// bracket holding only whitespace is as if it were not written;
309/// - the trimming of a key-value entry's value
310/// ([`key_value_pieces`](crate::lang::copy::key_value_pieces): `tag=~x~`
311/// gives `x`);
312/// - the value tests of a user definition's template, which read the one
313/// placeholder of their test argument, whitespace aside
314/// ([`userdefs`](crate::lang::rewrites::userdefs));
315/// - the test for a star of a theorem's title that is not one run of
316/// characters
317/// ([`title_reading`](crate::stdlib::features::theorems::title_reading)),
318/// and its copy in the title's reader: `[~*\emph{x}]` begins with a star,
319/// as `[ *\emph{x}]` does.
320///
321/// A reader of text taken as typed or with its markup keeps such a node as
322/// part of the text, even where it removes the whitespace at the text's ends:
323/// a citation key, a term (`\term{~}` is not empty) and a theorem's
324/// back-reference (`[~*lem:a]` is malformed, while `[ *lem:a]` refers to
325/// `lem:a`). A label holds no such node: it is read from a characters-only
326/// group ([`crate::lang::chars_group`]), in which `~` and the backslash of
327/// `\ ` are ordinary characters.
328///
329/// The no-break space U+00A0 typed directly in the text is no such node: it is
330/// a character of the text, and the pass and every reader above count it as
331/// content, as they count every character other than the space, the tab, the
332/// carriage return and the line feed ([the whitespace of FLM
333/// text](crate::lang::text#whitespace)). The one exception is the key of a
334/// `key=value` entry, whose ends techy's key-value reader trims of every
335/// Unicode whitespace character, U+00A0 included.
336///
337/// The aspect has no method: its presence is the whole statement, the same
338/// for every node of the element. It is meant for an inline element, of the
339/// block role [`BlockRole::Inline`]. Attach it by its trait-object type, with
340/// its implementation [`IsWhitespace`]:
341/// `.with::<dyn Whitespace>(Arc::new(IsWhitespace))` on an
342/// [`ElementSpec`](crate::model::element::ElementSpec).
343pub trait Whitespace: Send + Sync {}
344
345/// The implementation of [`Whitespace`]. It carries no data: the presence of
346/// the aspect is the whole statement.
347#[derive(Debug, Clone, Copy, Default)]
348pub struct IsWhitespace;
349
350impl Whitespace for IsWhitespace {}
351
352/// Whether the node `node` is whitespace: whether its element carries the
353/// [`Whitespace`] aspect. `false` for an element that does not declare that
354/// aspect.
355pub fn is_whitespace_of(node: &NodeRef<'_, Flm>) -> bool {
356 node.ext().element.has_aspect::<dyn Whitespace>()
357}
358
359// --- content references ---------------------------------------------------------------
360
361/// Document content that an aspect returns: a reference to content *of the
362/// node the aspect was asked about* (one of its arguments, its body, or one
363/// node of the same tree) or, for content that no node holds by itself, a
364/// small tree the aspect built.
365///
366/// An aspect refers to content wherever it can, for the reason given in the
367/// [module documentation](self#content-an-aspect-returns). A consumer reads a
368/// reference on the node that the aspect was asked about, with
369/// [`ContentRef::nodes`]; a [`ContentRef::Synthesized`] tree is read as it is.
370///
371/// # Comparing two references
372///
373/// Two references are equal when they designate the same content. Two
374/// synthesized trees are equal only when they are the *same* tree, shared
375/// through one pointer (as the lists feature shares the one bullet tree it
376/// builds per configured bullet with every item), and never because two trees
377/// built separately hold the same text: a tree holds spans, sources and
378/// parsing states that cannot be compared, and nothing in the library compares
379/// content by its text. The hash of a [`ContentRef::Synthesized`] covers the
380/// variant alone, so that it depends on no memory address and is the same on
381/// every run.
382#[derive(Debug, Clone)]
383pub enum ContentRef {
384 /// The content of the argument at this position, counted from zero in the
385 /// order the arguments are written at the call.
386 Argument(usize),
387 /// The content of the argument with this name.
388 ArgumentNamed(String),
389 /// The node's body: the content of an environment, or of a command that
390 /// takes a body.
391 Body,
392 /// One node of the same tree, by its identifier: the node itself, one of
393 /// its descendants, or any other node of that tree.
394 Node(NodeId),
395 /// Content that no node of the tree holds by itself, built by the aspect as
396 /// a small tree of its own: the bullet that a list's configuration places
397 /// beside its items, or the value `Custom` of `tag=Custom`, which shares a
398 /// run of characters with its key.
399 ///
400 /// The tree has the shape of a synthesized value built by copying
401 /// ([`crate::lang::copy`]): its root is a list node that holds the content
402 /// and adds nothing of its own (no delimiters, no text), so the content is
403 /// read as written inside it. A consumer uses the tree like a synthesized
404 /// value copied out of the document (the references feature shows it
405 /// where a reference to the point shows content); the tree is not part of
406 /// the document's own trees.
407 ///
408 /// An aspect that returns the same content for many points builds it once
409 /// and shares it: the lists feature builds one tree per configured bullet
410 /// when the registry is built. See [comparing two
411 /// references](ContentRef#comparing-two-references) for how two such trees
412 /// compare.
413 Synthesized(Arc<NodeTree<Flm>>),
414}
415
416impl PartialEq for ContentRef {
417 fn eq(&self, other: &ContentRef) -> bool {
418 match (self, other) {
419 (ContentRef::Argument(a), ContentRef::Argument(b)) => a == b,
420 (ContentRef::ArgumentNamed(a), ContentRef::ArgumentNamed(b)) => a == b,
421 (ContentRef::Body, ContentRef::Body) => true,
422 (ContentRef::Node(a), ContentRef::Node(b)) => a == b,
423 // The same tree, never two trees holding the same text.
424 (ContentRef::Synthesized(a), ContentRef::Synthesized(b)) => Arc::ptr_eq(a, b),
425 _ => false,
426 }
427 }
428}
429
430impl Eq for ContentRef {}
431
432impl Hash for ContentRef {
433 fn hash<H: Hasher>(&self, state: &mut H) {
434 std::mem::discriminant(self).hash(state);
435 match self {
436 ContentRef::Argument(index) => index.hash(state),
437 ContentRef::ArgumentNamed(name) => name.hash(state),
438 ContentRef::Body => {}
439 ContentRef::Node(id) => id.hash(state),
440 // The variant alone: equal trees are one pointer, and hashing the
441 // pointer would make a hash differ from run to run.
442 ContentRef::Synthesized(_) => {}
443 }
444 }
445}
446
447impl ContentRef {
448 /// The nodes this reference designates, read on `node`, the node whose
449 /// aspect returned the reference: the content of an argument, the body, or
450 /// one node of the tree; for [`ContentRef::Synthesized`], the children of
451 /// the root of the tree it carries.
452 ///
453 /// Returns `None` when the reference does not apply to `node`: an argument
454 /// that is absent or does not exist, no body, or no node with that
455 /// identifier in the tree.
456 pub fn nodes<'t>(&'t self, node: &NodeRef<'t, Flm>) -> Option<Vec<NodeRef<'t, Flm>>> {
457 match self {
458 ContentRef::Argument(index) => Some(node.argument_content_nodes(*index)?.iter().collect()),
459 ContentRef::ArgumentNamed(name) => {
460 Some(node.argument_content_nodes_named(name).ok()??.iter().collect())
461 }
462 ContentRef::Body => Some(node.body()?.iter().collect()),
463 ContentRef::Node(id) => Some(vec![node.tree().get(*id)?]),
464 ContentRef::Synthesized(tree) => Some(tree.root().children().iter().collect()),
465 }
466 }
467}
468
469// --- content apart from the text around it ----------------------------------------------
470
471/// The aspect that gives the content of an occurrence that is not part of the
472/// text of the content around it.
473///
474/// The **text** of a run of content is its words, read out of the tree
475/// ([`plain_text_of`](crate::lang::text::plain_text_of)); for example, a
476/// heading without a label gets an identifier encoded from the text of its
477/// title. Some content is written inside a run without being part of its
478/// words: a footnote written in a heading's title is shown at the foot of the
479/// page, and its words are not the title's; the label that a `\ref` refers to
480/// is not a word of the text. An element that holds such content returns it
481/// from this aspect, as [content references](ContentRef) on the node, and
482/// every reading of the text of an enclosing run leaves that content out,
483/// with everything inside it. The rest of the element, such as its other
484/// arguments, is read as usual. A [`ContentRef::Synthesized`] designates no
485/// content of the tree, and the reading ignores it.
486///
487/// An element that does not declare this aspect has no such content. Read the
488/// result with [`apart_from_text_of`], which returns an empty list for an
489/// element that does not declare the aspect.
490pub trait ApartFromText: Send + Sync {
491 /// The content of this occurrence that is not part of the text around it,
492 /// as references on `node`.
493 fn apart_from_text(&self, node: &NodeRef<'_, Flm>) -> Vec<ContentRef>;
494}
495
496/// The content of the node `node` that is not part of the text around it: the
497/// result of its element's [`ApartFromText`] aspect, or an empty list when its
498/// element does not declare that aspect.
499pub fn apart_from_text_of(node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
500 match node.ext().element.aspect::<dyn ApartFromText>() {
501 Some(aspect) => aspect.apart_from_text(node),
502 None => Vec::new(),
503 }
504}
505
506// --- what stands for a node in a copy ----------------------------------------------------
507
508/// What replaces a node in a copy of content shown a second time: the result
509/// of the element's [`InCopy`] aspect, read with [`copied_as`].
510///
511/// A copy shown again is content of the document copied into a synthesized
512/// value ([`crate::lang::copy`]) to be shown a second time, away from where it
513/// is written, such as a heading's title that a reference prints
514/// ([`ValueContent::Shown`]). The copy operation reads this for every node it
515/// copies, at every depth, and stages (builds into the copy) what it says in
516/// the node's place.
517#[derive(Debug, Clone)]
518pub enum CopiedAs {
519 /// The node itself, copied as written with its span and source; its
520 /// children are copied as their own elements say. This is the result for
521 /// an element that does not declare the [`InCopy`] aspect.
522 Verbatim,
523 /// Nothing: the copy holds nothing in the node's place, and nothing of the
524 /// node's descendants.
525 Nothing,
526 /// One new node in the node's place, described by the [`StandIn`]; the
527 /// node's descendants are not copied.
528 StandIn(StandIn),
529}
530
531/// A new node that a copy stages in place of a node of the document
532/// ([`CopiedAs::StandIn`]): a node of a [synthesized
533/// element](crate::lang::mint::SyntaxDef::Synthesized) (an element that no
534/// document writes), carrying data of its own and holding no children.
535///
536/// The copy stages it with the span and the parsing state of the node it
537/// replaces, as it does for every copied node, so that a diagnostic about it
538/// points where the document wrote that node. The feature whose aspect returns
539/// the stand-in owns its element and its payload: the feature declares the
540/// element, with a lowering rule on every backend, and puts in the payload
541/// what that rule needs to know about the node it replaces. For example, the
542/// stand-in of an xnote (a note set apart from the running text, such as a
543/// footnote; see [`xnotes`](crate::stdlib::features::xnotes)) identifies the
544/// xnote, and its lowering rules write the xnote's mark.
545#[derive(Clone)]
546pub struct StandIn {
547 /// The specification of the new node, which carries its synthesized
548 /// element.
549 pub spec: Arc<FlmSynthesizedSpec>,
550 /// The node's own data, attached to its node extension
551 /// ([`FlmNodeExt::payload`](crate::lang::FlmNodeExt::payload)), or `None`
552 /// for a node without data.
553 pub payload: Option<Arc<dyn PresPayload>>,
554}
555
556impl fmt::Debug for StandIn {
557 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
558 f.debug_struct("StandIn")
559 .field("element", &self.spec.element().name)
560 .field("payload", &self.payload)
561 .finish()
562 }
563}
564
565/// The aspect that says what replaces an occurrence in a copy of content
566/// shown a second time ([`CopiedAs`]): the node as written, nothing, or a new
567/// node of the element's own.
568///
569/// Content of the document is copied into a synthesized value
570/// ([`crate::lang::copy`]) to be shown a second time, away from where it is
571/// written: a heading's title that a reference prints, the caption of an
572/// unnumbered float, a defined term, the tag of a list item. Most content is
573/// shown again as it was written, and an element that does not declare this
574/// aspect is copied as written. An element that must not be repeated returns
575/// something else. For example, an xnote shown again would be a second note
576/// with the same number and the same labels, so the xnotes feature returns a
577/// new node of its own in the xnote's place, which its lowering rules write as
578/// the xnote's mark.
579///
580/// The copy operation reads the aspect when the copy is made, once per node
581/// and per copy, for every node it copies at every depth: the children of a
582/// node that gives [`CopiedAs::Verbatim`] are read in turn, and the copy does
583/// not descend into a node that gives anything else. Like every aspect, it is
584/// evaluated per occurrence, from the element's data and the node.
585///
586/// Only a copy shown again ([`ValueContent::Shown`]) reads the aspect. A copy
587/// that the synthesized value holds as its own content ([`ValueContent::Own`])
588/// is copied as written regardless of the aspect: a use site of a user
589/// definition copied to be expanded *is* the document's content at that
590/// place, and content copied to be read must be what was written.
591///
592/// The library has no built-in stand-in element: the element, its payload and
593/// its lowering rules belong to the feature that returns the stand-in. Read the
594/// result with [`copied_as`], which gives [`CopiedAs::Verbatim`] for an
595/// element that does not declare the aspect and for every copy of
596/// [`ValueContent::Own`] content.
597pub trait InCopy: Send + Sync {
598 /// What replaces this occurrence in a copy made for `purpose`.
599 ///
600 /// Only a copy shown again reads the aspect, so `purpose` is currently
601 /// always [`ValueContent::Shown`]; it is passed so that an element can
602 /// distinguish a purpose added later.
603 fn in_copy(&self, node: &NodeRef<'_, Flm>, purpose: ValueContent) -> CopiedAs;
604}
605
606/// What replaces the node `node` in a copy made for `purpose`: for a copy
607/// shown again ([`ValueContent::Shown`]), the result of its element's
608/// [`InCopy`] aspect; [`CopiedAs::Verbatim`] for a copy of
609/// [`ValueContent::Own`] content and for an element that does not declare the
610/// aspect.
611pub fn copied_as(node: &NodeRef<'_, Flm>, purpose: ValueContent) -> CopiedAs {
612 if purpose == ValueContent::Own {
613 return CopiedAs::Verbatim;
614 }
615 match node.ext().element.aspect::<dyn InCopy>() {
616 Some(aspect) => aspect.in_copy(node, purpose),
617 None => CopiedAs::Verbatim,
618 }
619}
620
621// --- reference points ---------------------------------------------------------------
622
623/// A label, as written in `\label{type:label}`: the label type before the
624/// first colon, and the label proper after it.
625///
626/// A label is the text an author writes as `\label{type:label}` after a
627/// construct, which the construct reads as a field and attaches to its
628/// reference point (see [reference points, labels and
629/// anchors](crate::guide::concepts_overview#reference-points-labels-and-anchors)).
630/// The reference point carries its labels in [`RefPoint::labels`], and a
631/// reference site gives the label it points at in [`RefSite::target`]. The
632/// label type is part of the label and does not depend on the [reference
633/// kind](RefPoint::kind) of the point, so one point may carry labels of several
634/// types, among those the point [accepts](AcceptedRefTypes), and each label is
635/// looked up as a whole.
636#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
637pub struct Label {
638 /// The label type (`sec` in `sec:intro`).
639 pub ref_type: String,
640 /// The label proper (`intro` in `sec:intro`).
641 pub ref_label: String,
642}
643
644impl Label {
645 /// A label made of the label type `ref_type` and the label proper
646 /// `ref_label`, taken as given (no trimming, no check).
647 pub fn new(ref_type: impl Into<String>, ref_label: impl Into<String>) -> Label {
648 Label { ref_type: ref_type.into(), ref_label: ref_label.into() }
649 }
650
651 /// Reads a label from its written form `type:label`: the text before the
652 /// first colon is the label type, everything after it (further colons
653 /// included) is the label proper. In each part, every run of whitespace
654 /// (the space, the tab, the carriage return and the line feed: [the
655 /// whitespace of FLM text](crate::lang::text#whitespace)) is made one space
656 /// and the whitespace at both ends is removed, as in a citation key
657 /// ([`spelling_identity`](crate::stdlib::backends::pres::spelling_identity));
658 /// every other character counts as written, quotes, dashes and the no-break
659 /// space U+00A0 included. A label written with a doubled space, or broken
660 /// over two lines, is therefore the label written with one space.
661 ///
662 /// The standard features read every label a document writes with this
663 /// function (a `\label`, the target of a `\ref`, a `\hyperref` or an
664 /// `\eqref`, a proof's back-reference), so that a label and a reference to
665 /// it agree.
666 ///
667 /// Returns `None` when the text holds no colon, or when either part is
668 /// empty after the whitespace is removed. A caller that reads a label from
669 /// a document reports that case with a diagnostic at the label's span (see
670 /// [`MalformedLabel`]).
671 ///
672 /// # Examples
673 ///
674 /// ```
675 /// use flm_core::model::aspects::Label;
676 ///
677 /// let label = Label::parse("sec:intro").unwrap();
678 /// assert_eq!(label.ref_type, "sec");
679 /// assert_eq!(label.ref_label, "intro");
680 /// assert_eq!(label.to_string(), "sec:intro");
681 /// assert_eq!(Label::parse(" sec : a \n b "), Some(Label::new("sec", "a b")));
682 /// assert!(Label::parse("no-colon-here").is_none());
683 /// ```
684 pub fn parse(text: &str) -> Option<Label> {
685 let (ref_type, ref_label) = text.split_once(':')?;
686 let (ref_type, ref_label) = (collapse_whitespace(ref_type), collapse_whitespace(ref_label));
687 if ref_type.is_empty() || ref_label.is_empty() {
688 return None;
689 }
690 Some(Label::new(ref_type, ref_label))
691 }
692}
693
694impl fmt::Display for Label {
695 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
696 write!(f, "{}:{}", self.ref_type, self.ref_label)
697 }
698}
699
700/// How the anchor of a reference point is formed: the identifier a link in the
701/// output points at.
702///
703/// The element declares the policy for each point; the refs feature computes
704/// the identifier from it in its anchors stage, in document order, and records
705/// it in the table [`ANCHORS`](crate::stdlib::features::refs::ANCHORS), so that the same document always
706/// gives the same identifiers. A point whose identifier would be one an earlier
707/// point already has is reported and gets no anchor, except under
708/// [`AnchorPolicy::Slug`], where the later point gets a number appended
709/// instead.
710#[derive(Debug, Clone, PartialEq, Eq, Hash)]
711pub enum AnchorPolicy {
712 /// This identifier, used as given.
713 Explicit(String),
714 /// Encoded from the point's first remaining label: the first of its labels
715 /// that no earlier point carries and whose type the point accepts
716 /// ([`AcceptedRefTypes`]). A point with no such label gets no anchor.
717 FromFirstLabel,
718 /// Encoded from the given content, such as a heading's title, after a
719 /// prefix and a double hyphen, as in `sec--The_Title`. An identifier
720 /// encoded from the title rather than from a number does not change when
721 /// text is inserted before the point, so a link from outside the document
722 /// keeps working. Where several points encode to the same identifier, the
723 /// later ones get `-2`, `-3`, … appended in document order
724 /// (`sec--The_Title-2`).
725 ///
726 /// The element gives the prefix, so that an identifier encoded from the
727 /// title and one encoded from a label can begin alike: a heading gives
728 /// `sec`, the label type it accepts, and both `\label{sec:intro}` and an
729 /// unlabeled title give an identifier beginning with `sec`.
730 Slug {
731 /// The text written before the double hyphen.
732 prefix: String,
733 /// The content the identifier is encoded from.
734 content: ContentRef,
735 },
736 /// The prefix, a hyphen, and the number the document gave the point: the
737 /// values of the counters it is numbered within, outermost first, then its
738 /// own number, each written in decimal and joined by hyphens, as in
739 /// `theorem-2-3`.
740 ///
741 /// The element gives the prefix, as under [`AnchorPolicy::Slug`] and
742 /// [`AnchorPolicy::Auto`]. The numbers are written in decimal regardless of
743 /// how the counter style shows them, so that the identifier does not change
744 /// when the counter style does;
745 /// [`value_anchor`](crate::stdlib::features::refs::value_anchor) writes
746 /// them.
747 ///
748 /// **A point that the document did not number** (because a counter it
749 /// depends on has no value yet, or because no numbering feature is
750 /// registered) falls back to what [`AnchorPolicy::FromFirstLabel`] gives:
751 /// the point's first remaining label if it has one, and no identifier
752 /// otherwise. The identifier of a point under this policy therefore
753 /// depends on the numbering.
754 FromValue {
755 /// The text written before the number.
756 prefix: String,
757 },
758 /// The point's first remaining label if it has one; otherwise the prefix,
759 /// a double hyphen, the point's position among the points of its reference
760 /// kind, and four lowercase letters, as in `eq--8kqzt`.
761 ///
762 /// A point with a remaining label gets the identifier
763 /// [`AnchorPolicy::FromFirstLabel`] would give, never one from its
764 /// position, so that its identifier does not change when a point is
765 /// inserted before it. A point without a label gets an identifier from its
766 /// position, so that every point has an identifier that a link from
767 /// outside the document can use.
768 ///
769 /// The element gives the prefix, as under [`AnchorPolicy::Slug`]: a
770 /// display-math environment gives `eq`, the label type its lines accept,
771 /// so that the identifiers of a labeled line (`eq-euler`) and of an
772 /// unlabeled one begin alike.
773 ///
774 /// **The four letters** are computed from the prefix and the position
775 /// alone, so the same position gives the same identifier in every document
776 /// and on every run. The position alone already makes the identifier
777 /// unique; the letters keep it from reading as a number of the document.
778 /// Written as `eq--8`, the identifier would suggest equation (8), which it
779 /// is not as soon as an unnumbered equation comes before it.
780 /// [`auto_anchor`](crate::stdlib::features::refs::auto_anchor) computes
781 /// the identifier and documents how the letters are derived.
782 Auto {
783 /// The text written before the double hyphen.
784 prefix: String,
785 },
786}
787
788/// What a reference point is numbered by: the counter it counts in, the
789/// counter style its number is shown in, the scoped instances it counts
790/// under, the levels of the counter it advances, and optionally a number
791/// template of its own.
792///
793/// A counter is a dotted name under which things are counted in document
794/// order ([`CounterDecl`](crate::stdlib::features::numbering::CounterDecl)),
795/// and a counter style says how a counter value is shown
796/// ([`CounterStyleDecl`](crate::stdlib::features::numbering::CounterStyleDecl)). A
797/// point that is to carry a number gives a number source in
798/// [`RefPoint::number`], and the numbering feature
799/// ([`numbering`](crate::stdlib::features::numbering)) numbers every point
800/// that gives one; no setting of the numbering feature turns numbering off for
801/// a point. A point that is not to
802/// carry a number gives none: a line of an `equation*` environment, a heading
803/// written with a star, a heading of a kind that the headings configuration
804/// does not number. The element decides from the node and from its feature's
805/// configuration, fixed when the registry was built, since an aspect reads no
806/// option; the same document is therefore numbered the same way on every
807/// output.
808///
809/// The counter and the counter style are given by name. A point that gives a
810/// counter or a counter style that no feature declares is reported by the
811/// numbering stage, not here.
812///
813/// # Scoped instances
814///
815/// A point may count in a **scoped instance** of its counter rather than in
816/// the counter's single sequence through the document. A scoped instance is an
817/// independent sequence of the counter's values attached to a node, usually
818/// the environment the point is written in, and it covers exactly that node's
819/// content: two sibling environments are two instances, and each starts again
820/// from the counter's initial value. The point lists the instances it counts
821/// under in [`instances`](NumberSource::instances), outermost first, the last
822/// being its own. An instance inside another is numbered within the current
823/// value of the enclosing instance, so the item of a nested list reads `2.(b)`
824/// or `(b)` depending on what the counter writes for its enclosing levels. The
825/// [numbering guide](crate::guide::numbering) describes the whole mechanism.
826#[derive(Debug, Clone, PartialEq, Eq, Hash)]
827pub struct NumberSource {
828 /// The name of the counter the point counts in, such as
829 /// `flm.headings.section` or `flm.math.equation`. The feature that
830 /// declares the counter owns its name; points of several reference kinds,
831 /// from any feature, may count in one counter.
832 pub counter: Name,
833 /// The scoped instances of the counter that the point counts under,
834 /// outermost first: nodes of the tree of the node the aspect was asked
835 /// about, which contain the point's node and each hold one sequence of the
836 /// counter's values. The last is the point's own instance; each one
837 /// encloses the next. Empty for a point that counts in the counter's single
838 /// sequence through the document, as nearly every point does.
839 ///
840 /// Each instance must be a node that contains the point's node (never the
841 /// node that carries the point itself) and must enclose the next instance;
842 /// otherwise the point is not numbered and the numbering stage reports the
843 /// Error `flm.numbering.instance-not-enclosing`. An instance is given by
844 /// its node's identifier, as in [`ContentRef::Node`], because an aspect is
845 /// given a node of one tree and not the tree's place in the document; the
846 /// numbering stage records the instance as the full [`NodeAddr`] of that
847 /// node.
848 pub instances: Vec<NodeId>,
849 /// The name of the counter style the point's number is shown in, which
850 /// gives the number format, the word before the number and the
851 /// delimiters.
852 pub style: Name,
853 /// Which levels of the counter this point advances, in the order it
854 /// advances them.
855 ///
856 /// A counter value is a number with optional sub-numbers: level 0 is the
857 /// number, level 1 the first sub-number, and advancing a level resets the
858 /// deeper levels to zero. Most points advance `[0]` and show `(3)`, then
859 /// `(4)`. A group of sub-numbered lines is written by advancing two levels
860 /// at once on the first line and the deeper level alone on the rest: the
861 /// first line advances `[0, 1]` and shows `(3a)`, the lines after it
862 /// advance `[1]` and show `(3b)`, `(3c)`, and the next equation advances
863 /// `[0]` and shows `(4)`.
864 pub advance: Vec<u32>,
865 /// A number template of the point's own, or `None` to use the number
866 /// format of the counter style ([`style`](NumberSource::style)) as
867 /// declared.
868 ///
869 /// The text is a number template
870 /// ([`NumberTemplate`](crate::stdlib::features::numbering::NumberTemplate)):
871 /// every `#{name}` is the number in the format `name` (`#{arabic}`,
872 /// `#{alph}`, `#{roman}`, …), every other character is written as given,
873 /// and markup may surround the number: `(#{alph})`, `#{Roman}.`. The text
874 /// is the author's input, like the text of a `\tag`; for example, a list's
875 /// reference template written `ref=(#{alph})`, or `label=(#{alph})` alone.
876 /// The aspect passes it on as written, without compiling it, since an
877 /// aspect has no language to compile it with. The numbering stage compiles
878 /// each distinct text once per run and per counter style, and records the
879 /// point in the counter style [`style`](NumberSource::style) with its
880 /// number format replaced by this template, so that the point's number and
881 /// every reference to it use the template: `(b)`, `Item~(b)`. A template
882 /// that does not compile is reported as the Error
883 /// `flm.numbering.bad-number-format`, and the point is numbered with the
884 /// counter style as declared.
885 pub number_format: Option<String>,
886}
887
888/// The label types a reference point accepts.
889///
890/// A label is written `type:label`, and the part before the colon, the [label
891/// type](Label::ref_type), says what sort of thing is labeled: `sec:intro`
892/// labels a section, `eq:euler` an equation. A reference point declares which
893/// label types may be written for it, so that a label of the wrong type is
894/// reported instead of becoming a working link.
895///
896/// [`AcceptedRefTypes::Any`] accepts every label type. It suits a construct
897/// whose label types are not fixed in advance, and it is the default.
898///
899/// The labels of a document are checked against this declaration when they
900/// are collected: a written label whose type the point does not accept
901/// defines nothing (no reference resolves to it), and the label check
902/// ([`CHECK_LABELS`](crate::stdlib::features::refs::CHECK_LABELS)) reports it
903/// as `flm.refs.label-type-not-accepted`.
904#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
905pub enum AcceptedRefTypes {
906 /// Every label type is accepted.
907 #[default]
908 Any,
909 /// Only these label types, in the order the point declares them. An empty
910 /// list accepts no label.
911 These(Vec<String>),
912}
913
914impl AcceptedRefTypes {
915 /// A point that accepts every label type.
916 pub fn any() -> AcceptedRefTypes {
917 AcceptedRefTypes::Any
918 }
919
920 /// A point that accepts these label types and no others.
921 ///
922 /// # Examples
923 ///
924 /// ```
925 /// use flm_core::model::aspects::AcceptedRefTypes;
926 ///
927 /// let accepted = AcceptedRefTypes::these(["sec", "topic"]);
928 /// assert!(accepted.accepts("sec"));
929 /// assert!(!accepted.accepts("eq"));
930 /// assert!(AcceptedRefTypes::any().accepts("eq"));
931 /// ```
932 pub fn these(types: impl IntoIterator<Item = impl Into<String>>) -> AcceptedRefTypes {
933 AcceptedRefTypes::These(types.into_iter().map(Into::into).collect())
934 }
935
936 /// Returns `true` when a label of the type `ref_type` may be written for
937 /// the point.
938 pub fn accepts(&self, ref_type: &str) -> bool {
939 match self {
940 AcceptedRefTypes::Any => true,
941 AcceptedRefTypes::These(types) => types.iter().any(|one| one == ref_type),
942 }
943 }
944
945 /// The accepted label types, or `None` when every type is accepted. A
946 /// report about a refused label lists these types.
947 pub fn listed(&self) -> Option<&[String]> {
948 match self {
949 AcceptedRefTypes::Any => None,
950 AcceptedRefTypes::These(types) => Some(types),
951 }
952 }
953}
954
955/// A text written as a label for a reference point that is not of the form
956/// `type:label`, such as `\label{intro}`, with no colon.
957///
958/// Such a text defines no label: no reference resolves to it, and a point
959/// whose labels are all of this kind is as unlabeled as one with no `\label`
960/// at all. The construct that read the text records it on the point it
961/// declares ([`RefPoint::malformed`]), and the refs feature
962/// ([`crate::stdlib::features::refs`]) reports it once, as
963/// `flm.refs.bad-label`, at the span of the field it was written in.
964#[derive(Debug, Clone, PartialEq, Eq)]
965pub struct MalformedLabel {
966 /// The text as written, trimmed.
967 pub text: String,
968 /// The span of the field it was written in.
969 pub span: FlmSpan,
970 /// The position of this text among the point's labels, counted from zero
971 /// over the labels ([`RefPoint::labels`], the computed ones first) and
972 /// these texts together, in the order the document wrote them.
973 ///
974 /// The labels and these texts are kept apart because almost every reader
975 /// wants the labels alone. This position lets a reader that needs the
976 /// written order restore it, as the recomposed LaTeX output does when it
977 /// gives each label a key of its own.
978 pub position: usize,
979}
980
981/// A reference point: one place in a document that can be referred to,
982/// numbered, or given an anchor, such as a heading, an equation line, a
983/// theorem or a footnote.
984///
985/// An element declares the reference points of each occurrence through the
986/// [`Referenceable`] aspect, and the `refpoints` feature records them for every
987/// tree ([`REFPOINTS`](crate::stdlib::features::refpoints::REFPOINTS)). A node
988/// carries zero or more points: a display-math environment has one point per
989/// equation line, a heading has one, and an element that nothing can point at
990/// does not declare the aspect. A point is identified by a [`PointId`]. See
991/// [reference points, labels and
992/// anchors](crate::guide::concepts_overview#reference-points-labels-and-anchors).
993///
994/// # What a reference to the point shows
995///
996/// A point gives the two things it may show, and a reference shows the first
997/// of these that exists: the point's **number**, shown in the counter style of
998/// its [number source](RefPoint::number), when the numbering gave it one in
999/// this document; otherwise its [content](RefPoint::content), such as a
1000/// heading's title; otherwise the label the reference was written with, as
1001/// written.
1002///
1003/// A point gives both because a point with a number source may still get no
1004/// number in a run (no numbering feature registered, a counter that no feature
1005/// declares, an enclosing counter with no value) and must then have something
1006/// else to show. The point's element decides whether the point has a number
1007/// source, from its feature's configuration fixed when the registry was
1008/// built, and every point that has one is numbered where possible. What a
1009/// reference shows is therefore decided by the target; the reference site
1010/// decides only how it is presented ([`RefDisplayOptions`]).
1011#[derive(Debug, Clone, PartialEq, Eq)]
1012pub struct RefPoint {
1013 /// The reference kind: what sort of thing the point is, such as
1014 /// `section`, `equation` or `theorem`. The set of kinds is open: a feature
1015 /// uses the kinds it needs.
1016 pub kind: RefKind,
1017 /// The labels of this point: first the [`computed`](Self::computed)
1018 /// ones, which the element computed, then the labels written for the point
1019 /// in the document, in the order they were written.
1020 pub labels: Vec<Label>,
1021 /// The number of the point's computed labels: the first `computed`
1022 /// [labels](Self::labels) were computed by the element, not written by the
1023 /// author, and the accepted label types ([`accepts`](Self::accepts)) do not
1024 /// apply to them. `0` for a point whose labels are all written, which is
1025 /// every point except one whose element derives labels from the document,
1026 /// as a term definition (the `defterm` environment) does from its term.
1027 pub computed: usize,
1028 /// The texts written as labels for this point that are not of the form
1029 /// `type:label`, in the order they were written, each with its
1030 /// [position](MalformedLabel::position) among the point's labels. They
1031 /// define nothing; the refs feature reports each one.
1032 pub malformed: Vec<MalformedLabel>,
1033 /// How the point's anchor, the identifier a link points at, is formed.
1034 pub anchor: AnchorPolicy,
1035 /// What the point is numbered by, or `None` for a point that carries no
1036 /// number. See [`NumberSource`] and [what a reference to the point
1037 /// shows](Self#what-a-reference-to-the-point-shows).
1038 pub number: Option<NumberSource>,
1039 /// The content a reference shows when the point has no number, such as a
1040 /// heading's title, the text of an explicit tag or the bullet beside a
1041 /// list's item: a reference into the frozen tree, or a tree the aspect
1042 /// built when no node holds the content by itself
1043 /// ([`ContentRef::Synthesized`]). `None` for a point with no content to
1044 /// show.
1045 pub content: Option<ContentRef>,
1046 /// The label types that may be written for this point. A written label of
1047 /// another type defines nothing and is reported; see [`AcceptedRefTypes`].
1048 /// The check applies to what the author wrote only: the first
1049 /// [`computed`](Self::computed) labels are not checked.
1050 pub accepts: AcceptedRefTypes,
1051}
1052
1053/// The identifier of one reference point: the address of the node that
1054/// carries it and the point's index among that node's points.
1055///
1056/// A node's element returns the node's points in document order
1057/// ([`Referenceable::points`]), and the index is the point's position in that
1058/// list, counted from zero. The pair identifies the point within the whole
1059/// document; every table about reference points uses it as its key.
1060#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1061pub struct PointId {
1062 /// The node carrying the point.
1063 pub addr: NodeAddr,
1064 /// The point's index among the node's points, counted from zero in
1065 /// document order.
1066 pub index: u32,
1067}
1068
1069/// The aspect that declares the [reference points](RefPoint) a node carries:
1070/// the places in it that a reference can point at.
1071///
1072/// The `refpoints` feature reads this aspect on every node whose element
1073/// declares it, and the refs feature ([`crate::stdlib::features::refs`])
1074/// collects the labels written for each point and computes the anchors. Any
1075/// element may declare the aspect, so a construct that a third-party feature
1076/// declares is referred to exactly like a standard heading.
1077///
1078/// See [`Referencing`] for the places that point at a reference point.
1079pub trait Referenceable: Send + Sync {
1080 /// The reference points of this occurrence, in document order.
1081 ///
1082 /// Each point declares the label types it accepts
1083 /// ([`RefPoint::accepts`]); a construct with no fixed set of label types
1084 /// declares [`AcceptedRefTypes::Any`].
1085 fn points(&self, node: &NodeRef<'_, Flm>) -> Vec<RefPoint>;
1086}
1087
1088// --- reference sites ------------------------------------------------------------------
1089
1090/// How one reference site presents the reference point it points at.
1091///
1092/// A prefix is the word a reference writes before the target's number or
1093/// title, such as `Section` or `Eq.`; these options say which form of the
1094/// prefix to use and whether to show it. Each site records them through
1095/// [`Referencing`], as the document wrote them in the brackets of
1096/// `\ref[…]{…}`, so that an output that leaves the formatting of references
1097/// to another program (such as the recomposed LaTeX) can write them back
1098/// unchanged.
1099///
1100/// The lowering rule that shows a reference reads them; the standard rule
1101/// translates them into the terms of the counter style when it writes a
1102/// target's number
1103/// ([`lower_reference`](crate::stdlib::features::refs::lower_reference)).
1104#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1105pub struct RefDisplayOptions {
1106 /// The name of the prefix form asked for at this site, or `None` to leave
1107 /// the choice to the target.
1108 pub variant: Option<String>,
1109 /// Whether the prefix is shown before the target's number or title.
1110 pub with_prefix: bool,
1111}
1112
1113impl Default for RefDisplayOptions {
1114 fn default() -> RefDisplayOptions {
1115 RefDisplayOptions { variant: None, with_prefix: true }
1116 }
1117}
1118
1119/// A reference site: one place in a document that points at a [reference
1120/// point](RefPoint), such as a `\ref`, a `\hyperref`, a proof's
1121/// back-reference to its theorem, or a link to a defined term.
1122///
1123/// An element declares the reference sites of each occurrence through the
1124/// [`Referencing`] aspect, and the refs feature
1125/// ([`crate::stdlib::features::refs`]) resolves them. A node carries zero or
1126/// more sites. See [reference points, labels and
1127/// anchors](crate::guide::concepts_overview#reference-points-labels-and-anchors).
1128#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1129pub struct RefSite {
1130 /// The label this site points at. The refs feature looks it up among the
1131 /// labels collected from every reference point of the document.
1132 pub target: Label,
1133 /// How the resolved target is presented here.
1134 pub display: RefDisplayOptions,
1135 /// Whether the site is shown in the output. A site that is not shown still
1136 /// records the connection between the two places, from which a list of
1137 /// what points at a target is built: a proof written `[**thm:a]` refers to
1138 /// the theorem without showing a reference in its heading. The element
1139 /// that declares the site reads this field where it writes the site (a
1140 /// theorem's heading shows a proof's back-reference only when the site is
1141 /// shown); the refs feature resolves every site in the same way.
1142 pub shown: bool,
1143}
1144
1145/// The aspect that declares the [reference sites](RefSite) a node carries:
1146/// the places in it that point at a reference point. The reference points
1147/// themselves are declared by [`Referenceable`].
1148///
1149/// The refs feature ([`crate::stdlib::features::refs`]) resolves the sites of
1150/// every element that declares this aspect, so any construct can refer, not
1151/// only the reference command: a proof referring to its theorem, an equation
1152/// reference (`\eqref`), a link to a defined term. None of them has to look up labels or anchors, or
1153/// format the reference, by itself.
1154pub trait Referencing: Send + Sync {
1155 /// The reference sites of this occurrence, in document order.
1156 fn sites(&self, node: &NodeRef<'_, Flm>) -> Vec<RefSite>;
1157}
1158
1159// --- sectioning -----------------------------------------------------------------------
1160
1161/// The aspect that declares that an occurrence is a heading: its heading level,
1162/// whether it is listed in the table of contents, and what an entry of the
1163/// table of contents shows for it.
1164///
1165/// Every method takes the node, because whether a heading is listed in the
1166/// table of contents is a fact about the occurrence: the standard headings
1167/// feature ([`headings`](crate::stdlib::features::headings)) reads it from the
1168/// key `toc=false` written at the call, so two headings of the same kind may
1169/// differ. So is what an entry shows: the feature reads the alternative title
1170/// from the key `alt=` written at the call.
1171pub trait Sectioning: Send + Sync {
1172 /// The heading level of this occurrence: the smaller the number, the
1173 /// outer the heading. Every `u32`, `0` included, is a valid level; the
1174 /// standard heading kinds use 1 (`\section`) to 5 (`\subparagraph`).
1175 fn level(&self, node: &NodeRef<'_, Flm>) -> u32;
1176
1177 /// Whether this occurrence is listed in the table of contents. The default
1178 /// implementation returns `true`.
1179 fn in_toc(&self, node: &NodeRef<'_, Flm>) -> bool {
1180 let _ = node;
1181 true
1182 }
1183
1184 /// The content a table of contents shows for this occurrence, or `None`
1185 /// when it shows nothing but the occurrence's number. The default returns `None`.
1186 ///
1187 /// The standard headings return the alternative title written with the
1188 /// key `alt=`, copied into a synthesized value of its own
1189 /// ([`ContentRef::Synthesized`]), and the heading's title argument
1190 /// otherwise. A table of contents asks every heading through this method
1191 /// alone, so a heading kind of an extension decides what its entries show;
1192 /// the standard table of contents is the
1193 /// [`toc`](crate::stdlib::features::toc) feature.
1194 fn toc_title(&self, node: &NodeRef<'_, Flm>) -> Option<ContentRef> {
1195 let _ = node;
1196 None
1197 }
1198}
1199
1200#[cfg(test)]
1201mod tests {
1202 use super::*;
1203
1204 #[test]
1205 fn label_parses_at_the_first_colon() {
1206 let label = Label::parse("sec:a:b").unwrap();
1207 assert_eq!(label.ref_type, "sec");
1208 assert_eq!(label.ref_label, "a:b");
1209 assert_eq!(label.to_string(), "sec:a:b");
1210 }
1211
1212 #[test]
1213 fn label_requires_both_parts() {
1214 assert!(Label::parse("nocolon").is_none());
1215 assert!(Label::parse(":x").is_none());
1216 assert!(Label::parse("sec: ").is_none());
1217 }
1218
1219 #[test]
1220 fn the_default_display_options_show_the_prefix() {
1221 assert!(RefDisplayOptions::default().with_prefix);
1222 }
1223
1224 #[test]
1225 fn the_default_block_role_is_inline_content() {
1226 assert_eq!(BlockRole::DEFAULT, BlockRole::Inline(InlineSpacing::CONTENT));
1227 }
1228
1229 /// `\\gone{…}` answers nothing in a copy shown again, `\\held{…}` a
1230 /// stand-in, and every other node declares no [`InCopy`].
1231 mod in_copy {
1232 use super::*;
1233 use crate::lang::mint::{ArgDef, ElementDef, SyntaxDef};
1234 use crate::lang::{FlmSource, LangInputs, ParseOptions, build_language, parse_fragment};
1235 use crate::model::doc::FragmentLayout;
1236 use crate::model::element::ElementSpec;
1237
1238 struct Answers(fn() -> CopiedAs);
1239
1240 impl InCopy for Answers {
1241 fn in_copy(&self, _node: &NodeRef<'_, Flm>, _purpose: ValueContent) -> CopiedAs {
1242 (self.0)()
1243 }
1244 }
1245
1246 fn stand_in() -> CopiedAs {
1247 let spec = FlmSynthesizedSpec::new(Arc::new(ElementSpec::new("t.stand-in")));
1248 CopiedAs::StandIn(StandIn { spec: Arc::new(spec), payload: None })
1249 }
1250
1251 fn answers(purpose: ValueContent) -> Vec<(String, &'static str)> {
1252 let mut inputs = LangInputs::new();
1253 for (name, answer) in [("gone", (|| CopiedAs::Nothing) as fn() -> CopiedAs), ("held", stand_in)] {
1254 inputs.elements.push(ElementDef::new(
1255 "t",
1256 [name],
1257 SyntaxDef::Macro { args: vec![ArgDef::mandatory("text")] },
1258 Arc::new(
1259 ElementSpec::new(format!("t.{name}"))
1260 .with::<dyn InCopy>(Arc::new(Answers(answer)) as Arc<dyn InCopy>),
1261 ),
1262 ));
1263 }
1264 let lang = build_language(inputs);
1265 let source = Arc::new(FlmSource::new("a\\gone{b}\\held{c}"));
1266 let fragment = parse_fragment(&lang, source, FragmentLayout::Inline, &ParseOptions::default())
1267 .expect("a parse");
1268 fragment
1269 .tree()
1270 .root()
1271 .children()
1272 .iter()
1273 .map(|node| {
1274 let answer = match copied_as(&node, purpose) {
1275 CopiedAs::Verbatim => "verbatim",
1276 CopiedAs::Nothing => "nothing",
1277 CopiedAs::StandIn(stand_in) => {
1278 assert_eq!(stand_in.spec.element().name.as_str(), "t.stand-in");
1279 "stand-in"
1280 }
1281 };
1282 (node.ext().element.name.to_string(), answer)
1283 })
1284 .collect()
1285 }
1286
1287 #[test]
1288 fn a_copy_shown_again_takes_each_element_s_answer_and_verbatim_by_default() {
1289 let answers = answers(ValueContent::Shown);
1290 let kinds: Vec<&str> = answers.iter().map(|(_, answer)| *answer).collect();
1291 assert_eq!(kinds, ["verbatim", "nothing", "stand-in"]);
1292 assert_eq!(answers[1].0, "t.gone");
1293 }
1294
1295 #[test]
1296 fn a_copy_of_the_value_s_own_is_verbatim_whatever_the_element_answers() {
1297 let answers = answers(ValueContent::Own);
1298 assert!(answers.iter().all(|(_, answer)| *answer == "verbatim"));
1299 assert_eq!(answers.len(), 3);
1300 }
1301 }
1302}