Skip to main content

flm_core/stdlib/features/cells/
lower.rs

1//! The general lowering rules of the tables of cells.
2//!
3//! [`CellsRule`] (the rule [`RULE`]) is the rule of the `cells` environment
4//! on every backend except `latex-recomposed`. It reads the table through
5//! [`read_grid`], reports every problem found, and stages (builds into the
6//! lowered tree; see [`Lowerer`]) one dropped mark (`flm.pres.dropped`) per
7//! thing left out, then one
8//! [`flm.pres.cells`](crate::stdlib::backends::pres::CELLS) node. The
9//! node's payload is the table's model
10//! ([`CellsPayload`](crate::stdlib::backends::pres::CellsPayload)), and its
11//! `cell` content slots hold the cells' content: a `\cell`'s blocks, or a
12//! `\celldata` entry's inline content as one paragraph with the whitespace
13//! at its edges trimmed ([`stage_trimmed`]), so that a cell holds blocks on
14//! every backend. An empty table stages nothing but its dropped marks. On
15//! the backend it runs on, the rule requires (records a requirement for) what
16//! each cell style used in the table declares for that backend
17//! ([`CellStyle::requires`](super::CellStyle::requires)): style definitions
18//! on HTML, definition pieces or package requests on the recomposed LaTeX.
19//!
20//! What each backend makes of the `flm.pres.cells` node:
21//!
22//! - **HTML**: a `<table>` written as the
23//!   [HTML contract](crate::stdlib::backends::html::CONVENTIONS) states for
24//!   `flm.pres.cells`, a cell's facts as attributes, with the feature's
25//!   style definition ([`html`](super::html));
26//! - **Text**: a table of the layout engine, its columns aligned, the rows
27//!   of column headers followed by a horizontal line; row headers, edge
28//!   lines and custom styles are not shown;
29//! - **`latex-recomposed`**: this rule is not used; the recomposition rule
30//!   ([`latex`](super::latex)) writes one call of the LaTeX hook
31//!   `\flmCellsTable`.
32//!
33//! [`OutsideRule`] is the rule of a `\cell`, `\celldata`, `\\`, `&`,
34//! `\rownames` or `\colnames` that the lowering reaches on its own, outside
35//! the table's reader, on every backend. It reports the command
36//! ([`OutsideTable`]); it shows the content of a command that has content
37//! where the command is written, and places a dropped mark where a command
38//! without content was.
39
40use std::sync::Arc;
41
42use techy::core::node::{BuildId, NodeRef};
43use techy::error::Diagnostic;
44
45use crate::core::lowering::{
46    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
47};
48use crate::lang::Flm;
49use crate::model::element::element_of;
50use crate::model::names::{ElementName, Name};
51use crate::stdlib::backends::lowering::{lower_paragraph, stage_trimmed};
52use crate::stdlib::backends::pres::{self, CELL_SLOT, DroppedPayload};
53
54use super::diagnostics::OutsideTable;
55use super::reader::{CellContent, read_grid};
56use super::styles::Styles;
57use super::{CELL, COLNAMES, COLUMN, CONTENT_ARG, DATA, DATA_ARG, ENVIRONMENT, MERGE, ROW, ROWNAMES};
58
59/// The name of the general rule of the `cells` environment,
60/// `flm.cells.cells.lower.default` ([`CellsRule`]).
61pub const RULE: &str = "flm.cells.cells.lower.default";
62
63/// The lowering rule [`RULE`] of the `cells` environment, the default on
64/// every backend except `latex-recomposed`: it stages the table's dropped
65/// marks, then one `flm.pres.cells` node. See the
66/// [module documentation](self).
67#[derive(Debug)]
68pub struct CellsRule {
69    styles: Arc<Styles>,
70}
71
72impl CellsRule {
73    /// The rule, reading style tokens against the cell style declarations
74    /// `styles`.
75    pub fn new(styles: Arc<Styles>) -> CellsRule {
76        CellsRule { styles }
77    }
78}
79
80impl Lower for CellsRule {
81    fn lower(
82        &self,
83        node: NodeRef<'_, Flm>,
84        cx: &mut LowerCx<'_>,
85        lw: &mut dyn Lowerer,
86    ) -> Result<Lowering, LowerError> {
87        let grid = read_grid(&node, &self.styles)?;
88        // Every report is made, by each render that lowers the table.
89        let mut staged = Vec::new();
90        for problem in grid.problems {
91            lw.diagnose(problem.diagnostic);
92            if let Some(mark) = problem.dropped {
93                staged.push(lw.pres_with(cx, &ElementName::from(pres::DROPPED), mark, Vec::new())?);
94            }
95        }
96        if grid.payload.cells.is_empty() {
97            return Ok(Lowering::Emit(staged));
98        }
99        let backend = lw.backend().clone();
100        for name in &grid.styles {
101            if let Some(style) = self.styles.get(name.as_str()) {
102                for id in style.requirements_on(backend.as_str()) {
103                    lw.require(id);
104                }
105            }
106        }
107        let mut slots: Vec<(String, Vec<BuildId>)> = Vec::with_capacity(grid.contents.len());
108        for content in grid.contents {
109            let blocks = match content {
110                CellContent::Blocks(slice) => lw.lower_nodes(cx, slice)?,
111                CellContent::Inline(slice) => {
112                    let nodes: Vec<NodeRef<'_, Flm>> = slice.iter().collect();
113                    let run = stage_trimmed(cx, lw, &nodes, |_| false)?;
114                    vec![lower_paragraph(cx, lw, None, run, Vec::new())?]
115                }
116            };
117            slots.push((CELL_SLOT.to_string(), blocks));
118        }
119        staged.push(lw.pres_slots_with(cx, &ElementName::from(pres::CELLS), grid.payload, slots)?);
120        Ok(Lowering::Emit(staged))
121    }
122}
123
124/// The lowering rule of a command of the tables of cells that is lowered on
125/// its own, outside the reader of its table ([`OUTSIDE_RULES`]), the default
126/// on every backend. It reports the command as [`OutsideTable`]. It shows a
127/// `\cell`'s content as blocks, and a `\celldata`'s data as inline content,
128/// where the command is written. It leaves out a `\\`, an `&`, a
129/// `\rownames` or a `\colnames`, and a `\cell` or a `\celldata` missing
130/// its content argument, and places a dropped mark (`flm.pres.dropped`)
131/// where the command was. The rule also covers `\merge`, since every element
132/// needs a rule, but no document reaches it there: the placement and mapping
133/// arguments in which `\merge` can be written are read by the table's
134/// reader and never lowered.
135#[derive(Debug, Default)]
136pub struct OutsideRule;
137
138/// The commands [`OutsideRule`] covers, each with its element, the name of
139/// its rule, the message saying where the command must be written (the
140/// detail of [`OutsideTable`]), and how the command is written.
141pub const OUTSIDE_RULES: [(&str, &str, &str, &str); 7] = [
142    (
143        CELL,
144        "flm.cells.cell.lower.default",
145        "‘\\cell’ must be written directly in the body of a ‘cells’ environment, or as an entry of ‘\\celldata’",
146        "\\cell",
147    ),
148    (
149        DATA,
150        "flm.cells.data.lower.default",
151        "‘\\celldata’ must be written directly in the body of a ‘cells’ environment",
152        "\\celldata",
153    ),
154    (
155        ROW,
156        "flm.cells.row.lower.default",
157        "‘\\\\’ in a table of cells must be written directly in its body or in the data of ‘\\celldata’",
158        "\\\\",
159    ),
160    (
161        COLUMN,
162        "flm.cells.column.lower.default",
163        "‘&’ must be written directly in the data of ‘\\celldata’, between two entries",
164        "&",
165    ),
166    (
167        MERGE,
168        "flm.cells.merge.lower.default",
169        "‘\\merge’ must be written in the placement of ‘\\cell’ or the mapping of ‘\\celldata’",
170        "\\merge",
171    ),
172    (
173        ROWNAMES,
174        "flm.cells.rownames.lower.default",
175        "‘\\rownames’ must be written directly in the body of a ‘cells’ environment",
176        "\\rownames",
177    ),
178    (
179        COLNAMES,
180        "flm.cells.colnames.lower.default",
181        "‘\\colnames’ must be written directly in the body of a ‘cells’ environment",
182        "\\colnames",
183    ),
184];
185
186impl Lower for OutsideRule {
187    fn lower(
188        &self,
189        node: NodeRef<'_, Flm>,
190        cx: &mut LowerCx<'_>,
191        lw: &mut dyn Lowerer,
192    ) -> Result<Lowering, LowerError> {
193        let element = element_of(&node).name.clone();
194        let Some(&(_, _, detail, spelling)) =
195            OUTSIDE_RULES.iter().find(|(name, ..)| *name == element.as_str())
196        else {
197            return Err(LowerError::structure("a command of the tables of cells without its rule"));
198        };
199        lw.diagnose(Diagnostic::error(OutsideTable { detail: detail.to_string() }, node.span().clone()));
200        let content = match element.as_str() {
201            CELL => Some(CONTENT_ARG),
202            DATA => Some(DATA_ARG),
203            _ => None,
204        };
205        let shown =
206            content.filter(|argument| matches!(node.argument_content_nodes_named(argument), Ok(Some(_))));
207        if let Some(argument) = shown {
208            return Ok(Lowering::Emit(lw.lower_arg_named(cx, &node, argument)?));
209        }
210        let mark = DroppedPayload {
211            condition: Name::from("flm.cells.outside-table"),
212            detail: format!("{spelling} out of place"),
213        };
214        Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::DROPPED), mark, Vec::new())?]))
215    }
216}
217
218/// The general rules of the feature: the rule of the environment, reading
219/// style tokens against `styles`, and one [`OutsideRule`] per command it
220/// covers.
221pub(super) fn rules(styles: Arc<Styles>) -> Vec<LoweringRule> {
222    let mut rules = vec![
223        LoweringRule::new(
224            RULE,
225            ENVIRONMENT,
226            LoweringDecl::new().produces(pres::CELLS).produces(pres::PAR).produces(pres::DROPPED),
227            Arc::new(CellsRule::new(styles)),
228            DefaultMark::Everywhere,
229        )
230        .docs(
231            "a table of cells lowers to `flm.pres.cells`, its payload the table's model and its \
232             `cell` content slots the cells' content, after one dropped mark \
233             (`flm.pres.dropped`) per thing left out",
234        ),
235    ];
236    for (element, rule, _, _) in OUTSIDE_RULES {
237        rules.push(
238            LoweringRule::new(
239                rule,
240                element,
241                LoweringDecl::new().produces(pres::DROPPED),
242                Arc::new(OutsideRule),
243                DefaultMark::Everywhere,
244            )
245            .docs(
246                "a command of the tables of cells lowered outside its table is reported; its \
247                 content is shown where the command is written, or a dropped mark is placed there",
248            ),
249        );
250    }
251    rules
252}