Skip to main content

flm_core/stdlib/features/floats/
content.rs

1//! Content handlers: what decides which content a float type accepts.
2//!
3//! A **content handler** ([`FloatContentHandler`]) is a value with a name that
4//! accepts a float's content or refuses it. A float type lists, by name, the
5//! content handlers it accepts ([`FloatType::handlers`](super::FloatType::handlers));
6//! the float's rule tries them in that order, and the first that accepts the
7//! content decides. Content that no handler of the type accepts is reported
8//! ([`ContentRefused`](super::ContentRefused)).
9//!
10//! Content handlers are contributed to the service slot [`CONTENT_SLOT`]
11//! (`flm.floats.content`) by the feature that owns the kind of content a
12//! handler accepts: the `graphics` feature contributes `includegraphics`,
13//! which accepts exactly one image, and the `cells` feature contributes
14//! `cells`, which accepts exactly one table of cells. The `floats` feature
15//! contributes only `any` ([`AnyContent`]), which accepts any content. A
16//! feature contributes its handler as a peer contribution
17//! ([`peer_slot`](crate::core::registry::FeatureBuilder::peer_slot)): the
18//! registry build drops it with one Note when the `floats` feature is not
19//! registered, so the contributing feature builds with or without floats.
20//!
21//! ```
22//! use std::sync::Arc;
23//! use flm_core::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
24//! use flm_core::lang::Flm;
25//! use flm_core::stdlib::features::floats::{CONTENT_SLOT, FloatContentHandler};
26//! use techy::core::node::NodeRef;
27//!
28//! /// Admits exactly one paragraph.
29//! struct OneParagraph;
30//!
31//! impl FloatContentHandler for OneParagraph {
32//!     fn name(&self) -> &str {
33//!         "one-paragraph"
34//!     }
35//!     fn admit(&self, content: &[NodeRef<'_, Flm>]) -> Result<(), String> {
36//!         match content {
37//!             [one] if one.group_type() == Some(flm_core::lang::FlmGroupType::Paragraph) => Ok(()),
38//!             _ => Err("exactly one paragraph".to_string()),
39//!         }
40//!     }
41//! }
42//!
43//! struct Mine;
44//! impl FlmFeature for Mine {
45//!     fn info(&self) -> FeatureInfo { FeatureInfo::new("mine", "Mine") }
46//!     fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
47//!         b.peer_slot::<dyn FloatContentHandler>(CONTENT_SLOT, Arc::new(OneParagraph))
48//!     }
49//! }
50//! ```
51//!
52//! When the registry is built, the feature's build hook reads every
53//! contribution of the slot into a [`Handlers`] value that the feature's
54//! lowering rules share. The stage [`CHECK_HANDLERS`]
55//! (`flm.floats.check-handlers`) reports, once per run, each handler that a
56//! float type used in the document lists and that no registered feature
57//! contributes ([`MissingHandler`]).
58
59use std::collections::{BTreeMap, BTreeSet};
60use std::sync::{Arc, OnceLock};
61
62use techy::core::node::NodeRef;
63use techy::error::Diagnostic;
64
65use crate::core::data::store::StageOut;
66use crate::core::plan::PlanCx;
67use crate::core::registry::{BuildError, FeatureBuilder, Finalizer};
68use crate::core::run::StageCx;
69use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
70use crate::lang::{Flm, FlmOrigin, nowhere};
71use crate::stdlib::features::index::{ELEMENT_INDEX, walk_values_of};
72
73use super::config::FloatType;
74use super::diagnostics::{MissingHandler, StageFailed};
75use super::elements::FloatElement;
76use super::{ANY_HANDLER, CHECK_HANDLERS, CONTENT_SLOT, TYPES_SLOT};
77
78/// A **content handler**: a value that accepts a float's content or refuses
79/// it, contributed to the service slot [`CONTENT_SLOT`] and listed by name by
80/// the float types that accept it. See the [module documentation](self).
81///
82/// The registry build fails when two contributed handlers have the same
83/// name.
84pub trait FloatContentHandler: Send + Sync {
85    /// Returns the handler's name, by which a float type lists it
86    /// ([`FloatType::handlers`](super::FloatType::handlers)): `any`,
87    /// `includegraphics`, `cells`. Unique among the slot's contributions.
88    fn name(&self) -> &str;
89
90    /// Returns `Ok(())` when the handler accepts `content`, the float's
91    /// content nodes in order: the direct children of its body and the
92    /// paragraphs built there, without the commands `\caption`, `\label` and
93    /// `\nonumber`, whitespace and source comments
94    /// ([`float_body`](super::float_body)). A paragraph holding one of those
95    /// commands beside other content is one content node; the float's rule
96    /// leaves the command out when it lowers the paragraph. On the raw tree
97    /// that the recomposed LaTeX reads (the frozen tree that the
98    /// block-structure pass has not processed; [the raw
99    /// tree](mod@crate::stdlib::backends::latex_recomposed::rules#the-raw-tree)),
100    /// where no paragraph is built, the
101    /// content nodes are the body's direct children without the paragraph
102    /// breaks. A handler that counts blocks (one image, one table) therefore
103    /// gives the same result on both trees.
104    ///
105    /// # Errors
106    ///
107    /// The refusal: a description of what the handler accepts, which
108    /// completes the sentence "a ‘figure’ must hold …", for example `exactly
109    /// one image`. The float's rule reports the refusals only where no
110    /// handler of the type accepts the content.
111    fn admit(&self, content: &[NodeRef<'_, Flm>]) -> Result<(), String>;
112}
113
114/// The content handler `any` ([`ANY_HANDLER`]), the only one the `floats`
115/// feature contributes: it accepts any content, including no content.
116#[derive(Debug, Default, Clone, Copy)]
117pub struct AnyContent;
118
119impl FloatContentHandler for AnyContent {
120    fn name(&self) -> &str {
121        ANY_HANDLER
122    }
123
124    fn admit(&self, _content: &[NodeRef<'_, Flm>]) -> Result<(), String> {
125        Ok(())
126    }
127}
128
129/// The content handlers of a registry, by name, as the float's rules read
130/// them.
131///
132/// The feature creates one value when it registers and shares it among its
133/// lowering rules (the general rule and the rules of the `html` and
134/// `latex-recomposed` backends). The feature's build hook (a
135/// [`Finalizer`]) fills it once, when the registry is built, from every
136/// contribution to the service slot [`CONTENT_SLOT`]. A value created with
137/// [`Default`] and never filled holds no handler.
138#[derive(Default)]
139pub struct Handlers {
140    by_name: OnceLock<BTreeMap<String, Arc<dyn FloatContentHandler>>>,
141}
142
143impl std::fmt::Debug for Handlers {
144    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145        let names: Vec<&String> = self.by_name.get().map(|by| by.keys().collect()).unwrap_or_default();
146        f.debug_struct("Handlers").field("by_name", &names).finish()
147    }
148}
149
150/// Which content handler of a float's type accepted the float's content, or
151/// the refusals where none did, as [`Handlers::verdict`] returns it.
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub enum Verdict {
154    /// The handler of this name, the first of the type's handlers to accept
155    /// the content, accepted it.
156    Admitted(String),
157    /// No handler of the type accepted the content. The list holds the
158    /// refusal of each handler that a registered feature contributes, in the
159    /// type's order. A handler that no registered feature contributes has no
160    /// entry, so the list is empty where none of the type's handlers is
161    /// contributed.
162    Refused(Vec<String>),
163}
164
165impl Handlers {
166    /// Returns the handler of the name `name`, where a registered feature
167    /// contributes one.
168    pub fn get(&self, name: &str) -> Option<&Arc<dyn FloatContentHandler>> {
169        self.by_name.get()?.get(name)
170    }
171
172    /// Returns how `content` fares against the handlers `names`, tried in
173    /// order: the first that accepts it decides. A name that no registered
174    /// feature contributes accepts nothing and adds no refusal to the list,
175    /// since the document's author cannot write the content it would
176    /// accept.
177    pub fn verdict(&self, names: &[String], content: &[NodeRef<'_, Flm>]) -> Verdict {
178        let mut refusals = Vec::with_capacity(names.len());
179        for name in names {
180            if let Some(handler) = self.get(name) {
181                match handler.admit(content) {
182                    Ok(()) => return Verdict::Admitted(name.clone()),
183                    Err(refusal) => refusals.push(refusal),
184                }
185            }
186        }
187        Verdict::Refused(refusals)
188    }
189}
190
191/// The feature's build hook: it reads every contribution of the service slot
192/// [`CONTENT_SLOT`] into the feature's [`Handlers`], and fails the registry
193/// build for two handlers of one name and for two float types of one name in
194/// the service slot [`TYPES_SLOT`].
195pub(super) struct CollectHandlers {
196    pub(super) handlers: Arc<Handlers>,
197}
198
199impl Finalizer for CollectHandlers {
200    fn finalize(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
201        let refuse = |b: &FeatureBuilder<'_>, detail: String| BuildError::Feature {
202            feature: b.feature().clone(),
203            detail,
204        };
205        let Some(services) = b.services() else {
206            return Err(refuse(b, "the content slot must be assembled before the finalizer runs".into()));
207        };
208        // A type another feature contributed is checked against the others
209        // here, once the slot holds them all.
210        let mut types = BTreeSet::new();
211        for float_type in services.services_named::<FloatType>(TYPES_SLOT) {
212            if !types.insert(float_type.name.as_str()) {
213                return Err(refuse(
214                    b,
215                    format!("the float type `{}` may not be declared twice", float_type.name),
216                ));
217            }
218        }
219        // The rule keeps the shared values themselves: it has no access to the
220        // registry's services while it runs.
221        let mut by_name: BTreeMap<String, Arc<dyn FloatContentHandler>> = BTreeMap::new();
222        for handler in services.shared_named::<dyn FloatContentHandler>(CONTENT_SLOT) {
223            let name = handler.name().to_string();
224            if by_name.insert(name.clone(), Arc::clone(handler)).is_some() {
225                return Err(refuse(
226                    b,
227                    format!("the float content handler `{name}` may not be contributed twice"),
228                ));
229            }
230        }
231        if self.handlers.by_name.set(by_name).is_err() {
232            return Err(refuse(b, "the feature may be registered at most once in a registry".into()));
233        }
234        Ok(())
235    }
236}
237
238/// The stage [`CHECK_HANDLERS`]
239/// (`flm.floats.check-handlers`): a check that runs once per document and
240/// reports, once per run, each content handler that a float type used in the
241/// document lists and that no registered feature contributes
242/// ([`MissingHandler`], a Note, at the first float of the type). Every rule
243/// that lowers a float requires it, so it runs wherever a float may be
244/// lowered; it is a member of the collection
245/// [`flm.validated`](crate::stdlib::VALIDATED), so the `check` workflow
246/// ([`CHECK_WORKFLOW`](crate::stdlib::CHECK_WORKFLOW)), which validates a
247/// document and writes no output, runs it too. It finds the floats through
248/// the element index ([`ElementIndex`](crate::stdlib::features::index::ElementIndex), table [`ELEMENT_INDEX`]).
249pub(super) struct CheckHandlers;
250
251impl Stage for CheckHandlers {
252    fn decl(&self) -> StageDecl {
253        StageDecl::new(CHECK_HANDLERS, Effect::Check, Scope::Document).provides(CHECK_HANDLERS).docs(
254            "Reports, once per run, each content handler that a float type used in the \
255             document lists and that no registered feature contributes (a Note, at the first \
256             float of the type).",
257        )
258    }
259
260    fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
261        Needs::new().reads(ELEMENT_INDEX)
262    }
263
264    fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
265        let index = match cx.get(ELEMENT_INDEX) {
266            Ok(Some(index)) => index,
267            Ok(None) => return,
268            Err(error) => {
269                out.diags.push(Diagnostic::error(
270                    StageFailed { stage: CHECK_HANDLERS.to_string(), detail: error.to_string() },
271                    nowhere(FlmOrigin::none()),
272                ));
273                return;
274            }
275        };
276        let contributed: BTreeSet<&str> = cx
277            .registry()
278            .services()
279            .services_named::<dyn FloatContentHandler>(CONTENT_SLOT)
280            .map(|handler| handler.name())
281            .collect();
282        let mut seen: BTreeSet<String> = BTreeSet::new();
283        for (_, node, value) in walk_values_of::<FloatElement>(cx, index) {
284            let float_type = &value.float_type;
285            if !seen.insert(float_type.name.to_string()) {
286                continue;
287            }
288            for handler in &float_type.handlers {
289                if !contributed.contains(handler.as_str()) {
290                    out.diags.push(Diagnostic::note(
291                        MissingHandler {
292                            float_type: float_type.name.to_string(),
293                            handler: handler.clone(),
294                        },
295                        node.span().clone(),
296                    ));
297                }
298            }
299        }
300    }
301}
302
303#[cfg(test)]
304mod tests {
305    use super::*;
306
307    #[test]
308    fn the_any_handler_admits_everything() {
309        assert_eq!(AnyContent.name(), "any");
310        assert_eq!(AnyContent.admit(&[]), Ok(()));
311    }
312
313    #[test]
314    fn a_handler_nobody_contributes_admits_nothing() {
315        let handlers = Handlers::default();
316        let _ = handlers.by_name.set(BTreeMap::from([(
317            "any".to_string(),
318            Arc::new(AnyContent) as Arc<dyn FloatContentHandler>,
319        )]));
320        let names = |list: &[&str]| list.iter().map(|name| name.to_string()).collect::<Vec<_>>();
321        assert_eq!(handlers.verdict(&names(&["cells", "any"]), &[]), Verdict::Admitted("any".into()));
322        assert_eq!(handlers.verdict(&names(&["cells"]), &[]), Verdict::Refused(Vec::new()));
323    }
324}