Skip to main content

flm_core/stdlib/backends/pieces/
feature.rs

1//! This module defines the `pieces` feature ([`PiecesFeature`]), along with
2//! the functions that select the pieces placed during a render.
3//!
4//! A *piece* is a part of the output that a backend places before or after the
5//! document's content, such as the document's title or the bibliography
6//! ([`Piece`](crate::core::piece::Piece)). The `pieces` feature registers two
7//! things:
8//!
9//! - the service slot [`SLOT`] (`flm.pieces`), to which each feature that
10//!   offers a piece contributes the declaration of the piece ([`PieceDecl`]);
11//! - the settings `include` and `exclude` ([`PiecesRenderOptions`]), with which
12//!   the pieces to be placed during a render are selected.
13//!
14//! The feature registers no stage and no table. Each backend that places
15//! pieces registers its own pieces stage ([`PiecesStage`](super::PiecesStage))
16//! and the table that this stage writes.
17//!
18//! The declarations of the pieces are values contributed to a service slot
19//! ([`crate::core::services`]), and not a kind of definition in the registry.
20//! A declaration is data that the pieces stages read: a name, a table, a place
21//! and a default. The registry has nothing to check or to schedule for it.
22//!
23//! A registry that contains a backend with a pieces stage must also contain the
24//! `pieces` feature. Otherwise, building a plan for this backend fails with an
25//! error that identifies the option type [`PiecesRenderOptions`].
26
27use std::collections::{BTreeMap, BTreeSet};
28use std::sync::Arc;
29
30use crate::core::settings::SettingsDecl;
31use crate::core::piece::PieceDecl;
32use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature, FlmRegistry};
33use crate::core::services::Arity;
34use crate::model::names::{BackendName, Name};
35use crate::model::options::Bind;
36
37/// The name of the `pieces` feature, `pieces`.
38///
39/// The identifiers of the conditions that the pieces stages report begin with
40/// `flm.pieces.` ([`super::error`]).
41pub const FEATURE: &str = "pieces";
42
43/// Returns the settings declaration of the `pieces` feature. The fields of
44/// [`PiecesRenderOptions`] are the settings of the feature, set on the render
45/// request.
46fn settings() -> SettingsDecl {
47    SettingsDecl::new(FEATURE)
48        .options::<PiecesRenderOptions>(
49            Bind::Render,
50            "The pieces placed during a render in addition to those placed by default \
51            (`include`), and the pieces placed by default that are left out of a render \
52            (`exclude`). Set per render request.",
53        )
54}
55
56/// The name of the service slot `flm.pieces`, to which features contribute the
57/// declarations of their pieces.
58///
59/// Each value of this service slot is a [`PieceDecl`]. The service slot keeps
60/// the declarations in the order of their contributions. A backend places two
61/// pieces with the same place in this order.
62///
63/// A feature that offers a piece contributes its declaration with
64/// [`FeatureBuilder::peer_slot`], so that the feature can also be used in a
65/// registry without the `pieces` feature. In such a registry, the declaration
66/// is dropped, and the registry build reports a note.
67pub const SLOT: &str = "flm.pieces";
68
69/// The render option with which the pieces placed during a render are
70/// selected.
71///
72/// A piece is placed during a render if it is listed in `include`, or if it is
73/// placed by default
74/// ([`PieceDecl::default_on`](crate::core::piece::PieceDecl#structfield.default_on))
75/// and is not listed in `exclude`. A piece that is listed in both sets is
76/// therefore placed. The two sets apply to every backend of the render.
77///
78/// The field [`backends`](Self::backends) restricts this selection for each
79/// backend separately:
80///
81/// - On a backend that has an entry in `backends`, only the selected pieces
82///   listed in this entry are placed.
83/// - On a backend without an entry, all selected pieces are placed, unless the
84///   pieces stage of the backend places only the pieces listed for it
85///   ([`PiecesStage::placing_only_named`](super::PiecesStage::placing_only_named)).
86///   In that case, no piece is placed on this backend.
87///
88/// The function [`selected_pieces`] applies these rules.
89///
90/// The option is set on the render request ([`Bind::Render`]). A piece that is
91/// not placed during a render is not built: the stage that builds the content
92/// of the piece is not scheduled in the plan. A name in `include` or `exclude`
93/// that is not the name of a piece defined in any feature is ignored, and
94/// reported as `flm.pieces.unknown-piece`
95/// ([`UnknownPiece`](super::UnknownPiece)).
96///
97/// # Examples
98///
99/// ```
100/// use flm_core::stdlib::backends::pieces::PiecesRenderOptions;
101///
102/// let options = PiecesRenderOptions::default().exclude("mypkg.notes");
103/// assert!(options.exclude.iter().any(|name| name.as_str() == "mypkg.notes"));
104/// assert!(options.include.is_empty());
105/// ```
106#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, serde::Deserialize)]
107#[derive(schemars::JsonSchema)]
108#[serde(default, deny_unknown_fields)]
109pub struct PiecesRenderOptions {
110    /// Pieces to be placed during a render although they are not placed by
111    /// default, such as `flm.toc`.
112    pub include: BTreeSet<Name>,
113    /// Pieces placed by default that are left out of a render.
114    pub exclude: BTreeSet<Name>,
115    /// For each backend that has an entry, the only pieces that the backend
116    /// may place.
117    ///
118    /// A host sets this field from the pieces that its compose template
119    /// accepts
120    /// ([`select_pieces`](crate::stdlib::features::compose::select_pieces)),
121    /// so that a piece for which the template has no place is never built. This
122    /// field cannot be set as a setting.
123    #[serde(skip)]
124    #[schemars(skip)]
125    pub backends: BTreeMap<BackendName, BTreeSet<Name>>,
126}
127
128impl PiecesRenderOptions {
129    /// Adds the piece `name` to the set
130    /// [`include`](PiecesRenderOptions#structfield.include), and returns the
131    /// options.
132    pub fn include(mut self, name: impl Into<Name>) -> PiecesRenderOptions {
133        self.include.insert(name.into());
134        self
135    }
136
137    /// Adds the piece `name` to the set
138    /// [`exclude`](PiecesRenderOptions#structfield.exclude), and returns the
139    /// options.
140    pub fn exclude(mut self, name: impl Into<Name>) -> PiecesRenderOptions {
141        self.exclude.insert(name.into());
142        self
143    }
144}
145
146/// Returns the declarations of all pieces of `registry`, in the order of the
147/// service slot [`SLOT`].
148///
149/// In a registry without the `pieces` feature, no piece is declared, and the
150/// result is empty.
151pub fn declared_pieces(registry: &FlmRegistry) -> impl Iterator<Item = &PieceDecl> + '_ {
152    registry.services().services_named::<PieceDecl>(SLOT)
153}
154
155/// Returns the declarations of the pieces placed on `backend` during a render
156/// with `options`, in the order of the service slot [`SLOT`].
157///
158/// The selection follows the rules described at [`PiecesRenderOptions`]. The
159/// flag `only_named` applies when `backend` has no entry in
160/// [`PiecesRenderOptions::backends`]. In that case, the function returns all
161/// pieces that `include` and `exclude` select if `only_named` is `false`, and
162/// no piece if `only_named` is `true`.
163///
164/// The pieces stage of a backend calls this function with its own flag
165/// ([`PiecesStage::places_only_named`](super::PiecesStage::places_only_named)),
166/// first when the plan is built, then when the stage runs. When the plan is
167/// built, the stages that build the returned pieces are scheduled. When the
168/// stage runs, it lowers the returned pieces.
169///
170/// In a registry without the `pieces` feature, no piece is declared, and the
171/// result is empty.
172pub fn selected_pieces(
173    registry: &FlmRegistry,
174    options: &PiecesRenderOptions,
175    backend: &BackendName,
176    only_named: bool,
177) -> Vec<PieceDecl> {
178    let named = options.backends.get(backend);
179    if named.is_none() && only_named {
180        return Vec::new();
181    }
182    declared_pieces(registry)
183        .filter(|decl| {
184            (decl.default_on && !options.exclude.contains(&decl.name))
185                || options.include.contains(&decl.name)
186        })
187        .filter(|decl| named.is_none_or(|names| names.contains(&decl.name)))
188        .cloned()
189        .collect()
190}
191
192/// Returns the names in `include` and `exclude` of `options` that are not the
193/// names of pieces declared in `registry`, sorted and without duplicates.
194///
195/// The pieces stage of each backend reports each of these names as
196/// `flm.pieces.unknown-piece` ([`UnknownPiece`](super::UnknownPiece)).
197pub fn unknown_pieces(registry: &FlmRegistry, options: &PiecesRenderOptions) -> Vec<Name> {
198    let declared: BTreeSet<&Name> = declared_pieces(registry).map(|decl| &decl.name).collect();
199    let named: BTreeSet<&Name> = options.include.iter().chain(&options.exclude).collect();
200    named.into_iter().filter(|name| !declared.contains(name)).cloned().collect()
201}
202
203/// The `pieces` feature, which registers the service slot [`SLOT`] and the
204/// settings [`PiecesRenderOptions`] (see the [module
205/// documentation](mod@super::feature)).
206///
207/// Use [`feature()`] to obtain the feature as a shared value.
208#[derive(Debug, Default)]
209pub struct PiecesFeature;
210
211impl FlmFeature for PiecesFeature {
212    fn info(&self) -> FeatureInfo {
213        FeatureInfo::new(FEATURE, "Pieces").docs(
214            "The `pieces` feature provides the service slot `flm.pieces`, to which features \
215             contribute the declarations of their pieces. A piece is a part of the output that a \
216             backend places before or after the document's content, such as the title or the \
217             bibliography. The pieces to be rendered are selected with the `include` and \
218             `exclude` settings of this feature.",
219        )
220    }
221
222    fn settings(&self) -> Option<SettingsDecl> {
223        Some(settings())
224    }
225
226    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
227        b.service_slot::<PieceDecl>(
228            SLOT,
229            Arity::OrderedMany,
230            "The declarations of the pieces that the features offer, the parts that a backend \
231             places before or after the document's content. A backend places two pieces with \
232             the same place in the order of their declarations.",
233        )?;
234        Ok(())
235    }
236}
237
238/// Returns the `pieces` feature as a shared value, for instance to list it in
239/// a package entry.
240///
241/// # Examples
242///
243/// ```
244/// use flm_core::stdlib::backends::pieces;
245///
246/// assert_eq!(pieces::feature().info().name.as_str(), pieces::FEATURE);
247/// ```
248pub fn feature() -> Arc<dyn FlmFeature> {
249    Arc::new(PiecesFeature)
250}