Skip to main content

flm_core/stdlib/features/floats/
lower.rs

1//! The general lowering rule of a float, [`FLOAT_RULE`], the default on every
2//! backend: it lowers a float to a block holding the float's content and,
3//! where the float is numbered or has a caption, the line under the content
4//! (`Figure 1: A photo`).
5//!
6//! A lowering rule ([`LoweringRule`]) is a named registry entity written for
7//! one element, which stages the element's presentation for one backend: to
8//! stage a node is to build it into the tree that the rule is producing
9//! ([`Lowerer`]). The plain-text output uses this rule; the `html` backend
10//! uses a rule that lowers a float in the same way and requires the feature's
11//! stylesheet ([`html`](super::html)); the `latex-recomposed` backend has a
12//! rule of its own ([`latex`](super::latex)). [`float_decl`] gives what every
13//! rule lowering a float declares, and [`float_number`] writes a float's
14//! number.
15
16use std::sync::Arc;
17
18use techy::core::node::{BuildId, NodeRef};
19
20use crate::core::lowering::{
21    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
22};
23use crate::lang::Flm;
24use crate::model::names::{ElementName, Name};
25use crate::stdlib::backends::lowering::{lower_paragraph, lower_run};
26use crate::stdlib::backends::pres::{self, BlockPayload, SpanPayload};
27use crate::stdlib::features::numbering::{COUNTERS, FormatOptions, NumberSegment};
28use crate::stdlib::features::refs::ANCHORS;
29
30use super::body::{FloatFields, is_float_field, is_paragraph, read_float};
31use super::content::Handlers;
32use super::elements::float_point;
33use super::html::STYLE;
34use super::{
35    CAPTION_ROLE, CAPTION_TEXT_ARG, CHECK_HANDLERS, CONTENT_ROLE, FLOAT, FLOAT_ROLE, NUMBERED_KIND,
36    NUMBER_ROLE, UNNUMBERED_KIND,
37};
38
39/// The name of the float's general rule, `flm.floats.float.lower.default`,
40/// whose body is [`FloatRule`].
41pub const FLOAT_RULE: &str = "flm.floats.float.lower.default";
42
43/// The body of [`FLOAT_RULE`].
44///
45/// A role and its kind tokens are feature-owned names on a presentation
46/// payload that say what a container is, so that a stylesheet or a host's
47/// lowering rule can select on them
48/// ([`pres::payload`](crate::stdlib::backends::pres::payload)). A float
49/// lowers to one `flm.pres.block` of role [`FLOAT_ROLE`] (`flm.floats.float`),
50/// whose kind tokens are the float type's name and [`NUMBERED_KIND`] or [`UNNUMBERED_KIND`], which carries the
51/// anchor of the float's reference point where the references feature
52/// computed one, and which holds, in this order regardless of the order in
53/// the source:
54///
55/// - a `flm.pres.block` of role [`CONTENT_ROLE`]
56///   (`flm.floats.float.content`): the float's content, lowered; a paragraph
57///   that holds `\caption`, `\label` or `\nonumber` beside other content is
58///   lowered without those commands;
59/// - where the float is numbered or has a caption, a `flm.pres.block` of role
60///   [`CAPTION_ROLE`] (`flm.floats.float.caption`), with the same kind tokens
61///   as the float's block, holding one paragraph, **the line under the
62///   content**. For a numbered float, the paragraph holds a `flm.pres.span` of
63///   role [`NUMBER_ROLE`] with the type's caption name, a no-break space and
64///   the number, followed, where the float has a caption, by `: ` and the
65///   caption's full content (`Figure 1: A photo`). For an unnumbered float, it
66///   holds the caption alone.
67///
68/// The float is **numbered** where its type's numbering policy numbers it,
69/// given its `\label` and `\nonumber`, and the counter table holds its
70/// number ([`float_number`]): the number is written from the table when the
71/// float is lowered, in the type's counter style without its words. A float
72/// that the run could not number, because the numbering feature is not
73/// registered, is unnumbered; [`read_float`] reports it.
74///
75/// [`read_float`], which every rule lowering a float calls, reports every
76/// problem of the float's body.
77///
78/// At every float the rule requires the feature's style identifier
79/// [`STYLE`] (`flm.floats.style`), which each backend resolves as it
80/// resolves requirements: the stylesheet on the `html` backend, the
81/// definition pieces delivering it on the `latex-rendered` backend, nothing
82/// on the `text` backend.
83#[derive(Debug)]
84pub struct FloatRule {
85    handlers: Arc<Handlers>,
86}
87
88impl FloatRule {
89    /// Returns the rule's body, which tests a float's content against the
90    /// content handlers `handlers`.
91    pub(super) fn new(handlers: Arc<Handlers>) -> FloatRule {
92        FloatRule { handlers }
93    }
94}
95
96/// Returns the number of the float whose reference point is `point`, written
97/// from the counter table ([`COUNTERS`]) in the type's counter style, without
98/// the words before it and without delimiters. Returns `None` where the table
99/// holds no number for the point, and where the numbering feature is not
100/// registered. The calling rule must declare a read of the counter table
101/// ([`float_decl`] declares an optional one).
102///
103/// # Errors
104///
105/// [`LowerError`] when the table cannot be read, and when the number cannot
106/// be written from its record, which does not happen in a correct run, since
107/// the numbering stage refuses a record that its counter style cannot
108/// write.
109pub fn float_number(
110    lw: &dyn Lowerer,
111    point: crate::model::aspects::PointId,
112) -> Result<Option<Vec<NumberSegment>>, LowerError> {
113    let Some(counters) = lw.get(COUNTERS)? else { return Ok(None) };
114    let options = FormatOptions::new().without_word().without_delimiters();
115    match counters.format(point, &options) {
116        None => Ok(None),
117        Some(written) => written.map(Some).map_err(|error| LowerError::structure(error.to_string())),
118    }
119}
120
121/// Lowers `content`, the float's content nodes, in order: a paragraph that
122/// holds one of the float's three commands as a paragraph of the rest of its
123/// content, and every other node through the rules.
124fn lower_content(
125    cx: &mut LowerCx<'_>,
126    lw: &mut dyn Lowerer,
127    content: &[NodeRef<'_, Flm>],
128) -> Result<Vec<BuildId>, LowerError> {
129    let mut out = Vec::new();
130    for node in content {
131        if is_paragraph(node) && node.children().iter().any(|child| is_float_field(&child)) {
132            let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
133            let mut run = Vec::new();
134            for piece in children.split(is_float_field) {
135                run.extend(lower_run(cx, lw, piece)?);
136            }
137            out.push(lower_paragraph(cx, lw, None, run, Vec::new())?);
138        } else {
139            out.extend(lower_run(cx, lw, std::slice::from_ref(node))?);
140        }
141    }
142    Ok(out)
143}
144
145/// Stages a `flm.pres.block` of role `role`, with the kind tokens `kinds` and
146/// the anchor `anchor`, holding `body`.
147fn block(
148    cx: &mut LowerCx<'_>,
149    lw: &mut dyn Lowerer,
150    role: &str,
151    kinds: &[Name],
152    anchor: Option<String>,
153    body: Vec<BuildId>,
154) -> Result<BuildId, LowerError> {
155    let payload = BlockPayload { role: Some(Name::from(role)), kinds: kinds.to_vec(), anchor, doc_role: None };
156    lw.pres_with(cx, &ElementName::from(pres::BLOCK), payload, body)
157}
158
159/// Stages the paragraph of the line under the content: the number's span and
160/// the caption, or either alone. Returns `None` where the float has neither.
161fn line(
162    cx: &mut LowerCx<'_>,
163    lw: &mut dyn Lowerer,
164    fields: &FloatFields<'_>,
165    number: Option<&[NumberSegment]>,
166) -> Result<Option<BuildId>, LowerError> {
167    let mut run = Vec::new();
168    if let Some(segments) = number {
169        let mut body = vec![lw.text(cx, &format!("{}\u{a0}", fields.float_type.caption_name))?];
170        for segment in segments {
171            body.extend(lw.splice(cx, segment.content())?);
172        }
173        let payload = SpanPayload { role: Some(Name::from(NUMBER_ROLE)), ..SpanPayload::default() };
174        run.push(lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)?);
175    }
176    if let Some(caption) = &fields.caption {
177        if number.is_some() {
178            run.push(lw.text(cx, ": ")?);
179        }
180        run.extend(lw.lower_arg_named(cx, &caption.node, CAPTION_TEXT_ARG)?);
181    } else if number.is_none() {
182        return Ok(None);
183    }
184    Ok(Some(lower_paragraph(cx, lw, None, run, Vec::new())?))
185}
186
187impl Lower for FloatRule {
188    fn lower(
189        &self,
190        node: NodeRef<'_, Flm>,
191        cx: &mut LowerCx<'_>,
192        lw: &mut dyn Lowerer,
193    ) -> Result<Lowering, LowerError> {
194        lw.require(&Name::from(STYLE));
195        let reading = read_float(&node, &self.handlers, lw)?;
196        let fields = &reading.fields;
197        let point = float_point(lw.addr());
198        // The anchors table is absent in a registry holding no references
199        // feature: the float is written with no anchor.
200        let anchor = lw.get(ANCHORS)?.and_then(|anchors| anchors.id(point)).map(String::from);
201        let number = if fields.numbered { float_number(lw, point)? } else { None };
202        let numbered = if number.is_some() { NUMBERED_KIND } else { UNNUMBERED_KIND };
203        let kinds = [Name::from(fields.float_type.name.as_str()), Name::from(numbered)];
204        let content = lower_content(cx, lw, &fields.body.content)?;
205        let mut children = vec![block(cx, lw, CONTENT_ROLE, &[], None, content)?];
206        if let Some(line) = line(cx, lw, fields, number.as_deref())? {
207            children.push(block(cx, lw, CAPTION_ROLE, &kinds, None, vec![line])?);
208        }
209        let float = block(cx, lw, FLOAT_ROLE, &kinds, anchor, children)?;
210        Ok(Lowering::Emit(vec![float]))
211    }
212}
213
214/// Returns what a rule that lowers a float declares: optional reads of the
215/// anchors table ([`ANCHORS`]) and of the counter table ([`COUNTERS`]), which
216/// [`read_float`] needs, the requirement of the stage
217/// [`CHECK_HANDLERS`](super::CHECK_HANDLERS), and the production of blocks,
218/// paragraphs and spans. The general rule and the `html` backend's rule
219/// declare exactly this.
220pub fn float_decl() -> LoweringDecl {
221    LoweringDecl::new()
222        .reads_opt(ANCHORS)
223        .reads_opt(COUNTERS)
224        .requires(CHECK_HANDLERS)
225        .produces(pres::BLOCK)
226        .produces(pres::PAR)
227        .produces(pres::SPAN)
228}
229
230/// Returns the float's general rule, [`FLOAT_RULE`], the default on every
231/// backend, which tests a float's content against the content handlers
232/// `handlers`.
233pub(super) fn float_rule(handlers: Arc<Handlers>) -> LoweringRule {
234    LoweringRule::new(
235        FLOAT_RULE,
236        FLOAT,
237        float_decl(),
238        Arc::new(FloatRule::new(handlers)),
239        DefaultMark::Everywhere,
240    )
241    .docs(
242        "a float lowers to a `flm.pres.block` of role `flm.floats.float`, whose kind tokens are \
243         the float type's name and `numbered` or `unnumbered` and which carries the float's \
244         anchor; it holds a block of role `flm.floats.float.content` with the float's content \
245         and, where the float is numbered or has a caption, a block of role \
246         `flm.floats.float.caption` with the line under the content",
247    )
248}