Skip to main content

flm_core/core/
piece.rs

1//! Pieces: document-level synthesized values that a backend places before or
2//! after the document's content. This module holds the declaration of a piece
3//! ([`PieceDecl`], [`PiecePlace`]) and the type of its content ([`Piece`]).
4//!
5//! A piece is a document-level synthesized value that a backend places before
6//! or after the document's content (the title, the list of footnotes, the
7//! bibliography), built once by its builder stage into a table named for the
8//! piece and rendered by each backend with its own rules
9//! ([pieces](crate::guide::concepts_overview#pieces)). A synthesized value is
10//! a small tree that a stage builds while a run is under way, held outside the
11//! document's trees ([synthesized
12//! values](crate::guide::concepts_overview#synthesized-values)).
13//!
14//! Three things distinguish a piece from the document's content: the author
15//! does not write it where it appears; a stage *builds* it from what the
16//! document contains, once, over the whole document; and the backend *places*
17//! it at the place its declaration gives (before the content or after it),
18//! not at a position in a tree.
19//!
20//! A piece has three parts. A feature that offers a piece writes the first two
21//! with the items of this module; the backends supply the third.
22//!
23//! 1. **Its content** is a [`Piece`]: a small tree built from document
24//!    elements (the elements the feature declares, text, references,
25//!    mathematics), held in a table named for the piece. The content is a
26//!    synthesized value: a consumer brings it up to date before reading it as
27//!    document content ([value
28//!    catch-up](crate::guide::concepts_overview#value-catch-up)). The stage
29//!    that writes the table is the piece's **builder**. Because the content is
30//!    a table, another stage that writes the same table replaces the builder
31//!    when a plan request prefers that stage.
32//! 2. **Its declaration** is a [`PieceDecl`]: the piece's name, the table
33//!    holding its content, where it is placed, and whether a render places it
34//!    by default. The feature contributes it to the service slot `flm.pieces`
35//!    that the `pieces` feature owns
36//!    ([`stdlib::backends::pieces::SLOT`](crate::stdlib::backends::pieces::SLOT)).
37//! 3. **Its rendering** belongs to each backend: a per-backend stage lowers
38//!    the content with the lowering rules the plan selected for that backend,
39//!    and the backend writes the result into its output, as an [output
40//!    region](crate::core::region) of its own on HTML and on the recomposed
41//!    LaTeX, inside the printed text on the text backend. That machinery is in
42//!    [`crate::stdlib::backends::pieces`].
43//!
44//! Because the content is built from document elements, and never a string or
45//! a tree of one backend's own elements, one builder serves every backend, and
46//! a stage that replaces the builder changes the piece on every output at
47//! once.
48//!
49//! A piece in this sense is unrelated to a table piece, the part of one table
50//! that one stage invocation produced ([`Table::absorb`], [`PieceClass`]).
51//!
52//! This module depends on no backend and no feature: it holds only the values
53//! a feature declares a piece with.
54
55use std::sync::Arc;
56
57use techy::core::node::NodeTree;
58use techy::serialize::SerialValue;
59
60use crate::core::data::table::{PieceClass, ProjectCx, Table, TableHandle};
61use crate::lang::Flm;
62use crate::model::names::Name;
63
64/// Where a backend places a piece: before or after the document's content.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub enum PiecePlace {
67    /// Before the document's first tree.
68    BeforeContent,
69    /// After the document's last tree.
70    AfterContent,
71}
72
73impl PiecePlace {
74    /// Returns the place's name as a serialized table or a message writes
75    /// it: `before-content` or `after-content`.
76    pub fn as_str(self) -> &'static str {
77        match self {
78            PiecePlace::BeforeContent => "before-content",
79            PiecePlace::AfterContent => "after-content",
80        }
81    }
82}
83
84/// The declaration of one piece: its name, the table that holds its content,
85/// where a backend places it, and whether a render places it by default.
86///
87/// A feature that offers a piece does three things:
88///
89/// - it contributes this declaration to the service slot
90///   [`flm.pieces`](crate::stdlib::backends::pieces::SLOT) as a peer
91///   contribution
92///   ([`FeatureBuilder::peer_slot`](crate::core::registry::FeatureBuilder::peer_slot)),
93///   so that the feature also builds in a registry without the `pieces`
94///   feature;
95/// - it declares the table [`PieceDecl::table`], of value type [`Piece`]
96///   ([`FeatureBuilder::table`](crate::core::registry::FeatureBuilder::table));
97/// - it registers the builder stage that writes that table.
98///
99/// When two pieces have the same place, a backend places them in the order of
100/// their contributions to the slot. Which pieces a render places is decided
101/// by [`selected_pieces`](crate::stdlib::backends::pieces::selected_pieces).
102///
103/// # Examples
104///
105/// ```
106/// use flm_core::core::piece::{PieceDecl, PiecePlace};
107///
108/// let decl = PieceDecl::new("my.notes", PiecePlace::AfterContent, "the notes");
109/// assert_eq!(decl.table.name().as_str(), "my.notes");
110/// assert!(decl.default_on);
111/// assert!(!decl.default_on(false).default_on);
112/// ```
113#[derive(Debug, Clone)]
114pub struct PieceDecl {
115    /// The piece's name: a dotted name the contributing feature owns, such as
116    /// `mypkg.notes`. The render options
117    /// ([`PiecesRenderOptions`](crate::stdlib::backends::pieces::PiecesRenderOptions))
118    /// refer to the piece by this name.
119    pub name: Name,
120    /// The table holding the piece's content, whose value type is always
121    /// [`Piece`]. [`PieceDecl::new`] gives it the piece's name; the builder
122    /// stage declares it as a table it writes
123    /// ([`StageDecl::writes`](crate::core::stage::StageDecl::writes)).
124    pub table: TableHandle<Piece>,
125    /// Where a backend places the piece.
126    pub place: PiecePlace,
127    /// Whether every render places the piece unless the render options leave
128    /// it out. A piece declared `false` is placed only when the render options
129    /// include it.
130    pub default_on: bool,
131    /// A description of the piece, written by the feature that offers it.
132    pub docs: String,
133}
134
135impl PieceDecl {
136    /// Returns the declaration of the piece `name`, placed at `place` and
137    /// placed by default, whose content is held in the table of the same name
138    /// as the piece, with the description `docs`.
139    pub fn new(name: impl Into<Name>, place: PiecePlace, docs: impl Into<String>) -> PieceDecl {
140        let name = name.into();
141        let table = TableHandle::new(name.clone());
142        PieceDecl { name, table, place, default_on: true, docs: crate::kept_docs(docs) }
143    }
144
145    /// Sets whether every render places the piece unless the render options
146    /// leave it out (see [`default_on`](PieceDecl#structfield.default_on)),
147    /// and returns the declaration.
148    pub fn default_on(mut self, on: bool) -> PieceDecl {
149        self.default_on = on;
150        self
151    }
152}
153
154/// The content of one piece: a synthesized value built from document
155/// elements, or nothing to place.
156///
157/// This is the value type of every table that holds a piece's content, so
158/// that a backend's pieces stage (the stage that lowers the pieces for that
159/// backend, [`PiecesStage`](crate::stdlib::backends::pieces::PiecesStage))
160/// reads any piece by its name alone. A content of `None` places nothing and
161/// reports nothing: a list of notes in a document without notes is not an
162/// error.
163///
164/// The content is a [synthesized
165/// value](crate::guide::concepts_overview#synthesized-values), which a backend
166/// brings up to date before lowering it
167/// ([`StageCx::resolve_value`](crate::core::run::StageCx::resolve_value)). A
168/// synthesized value must not state a fact about the document as a whole: a
169/// labeled reference point inside it is refused when it is brought up to date,
170/// the backend's pieces stage reports `flm.pieces.lowering-failed`
171/// ([`PieceLoweringFailed`](crate::stdlib::backends::pieces::PieceLoweringFailed)),
172/// and the piece is left out of that backend's output.
173///
174/// The piece's builder stage (the stage that builds its content) writes the
175/// table once; a second value combined into the table replaces the first
176/// ([`Table::absorb`]). The serialized form of the table
177/// ([`Table::project`]) is a map whose key `content` holds the tree
178/// ([`ProjectCx::tree`]), or an empty map when the piece holds nothing.
179#[derive(Debug, Clone, Default)]
180pub struct Piece {
181    /// The piece's content, or `None` when there is nothing to place.
182    pub content: Option<Arc<NodeTree<Flm>>>,
183}
184
185impl Piece {
186    /// Returns a piece holding `content`.
187    pub fn new(content: Arc<NodeTree<Flm>>) -> Piece {
188        Piece { content: Some(content) }
189    }
190}
191
192impl Table for Piece {
193    fn absorb(&mut self, piece: Piece) {
194        *self = piece;
195    }
196
197    /// `{content: <the content's tree>}` when the piece holds content
198    /// ([`ProjectCx::tree`]), an empty map otherwise.
199    fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
200        match &self.content {
201            Some(content) => SerialValue::Map(vec![(String::from("content"), cx.tree(content))]),
202            None => SerialValue::Map(Vec::new()),
203        }
204    }
205
206    fn piece_class(&self) -> PieceClass {
207        if self.content.is_some() { PieceClass::DocumentFact } else { PieceClass::Empty }
208    }
209}