Skip to main content

flm_core/stdlib/backends/latex_recomposed/
rules.rs

1//! The two structural lowering rules ([`LoweringRule`]) of the
2//! `latex-recomposed` backend, for the paragraph break and the paragraph:
3//! the only lowering rules that the
4//! backend's feature registers itself ([`rules`]).
5//!
6//! Both rules write a blank line, which LaTeX reads as a paragraph break, and
7//! both require the raw tree:
8//!
9//! | element | rule | writes |
10//! |---|---|---|
11//! | `flm.parbreak` | [`PARBREAK_RULE`] ([`ParbreakRule`]) | one blank line, however many blank lines the author wrote at that place |
12//! | `flm.paragraph` | [`PARAGRAPH_RULE`] ([`ParagraphRule`]) | the paragraph's content, lowered, then one blank line |
13//!
14//! # The raw tree
15//!
16//! The recomposed LaTeX keeps the document as the author typed it, so it is
17//! written from the *raw* tree: the [frozen
18//! tree](crate::guide::concepts_overview#frozen-trees-and-computed-data) that
19//! the [block-structure pass](crate::lang::rewrites::blocks) has not
20//! processed, in which no paragraphs were built, no typographic
21//! substitution was made, the text is as parsed, and the paragraph-break
22//! markers (`flm.parbreak`) are still in place. A backend states the tree
23//! state it needs through the requirements of its lowering rules, not through
24//! a setting: both rules here require the capability `flm.blocks.raw`
25//! ([`RAW`]), which the [`blocks`](crate::stdlib::features::blocks) feature
26//! provides through a stage that does nothing and only marks this tree
27//! state. The lowering stage of a backend requires
28//! every capability that the backend's selected rules require
29//! ([`rules_needs`](crate::stdlib::backends::lowering::rules_needs)), so
30//! every plan for this backend keeps its trees raw, regardless of what the
31//! document holds.
32//!
33//! The paragraph rule never applies on the raw tree, where no paragraph group
34//! exists. It is registered because `flm.paragraph` is a structural element
35//! present in every registry, and building a plan for a backend fails
36//! ([`PlanError::Incomplete`](crate::core::plan::PlanError::Incomplete)) when
37//! some element that a document may contain has neither a native emission
38//! nor a rule on that backend. Both rules stage (build into the lowered
39//! tree; see [`Lowerer`]) a `flm.pres.latex.raw` node holding the blank line
40//! ([`LatexRawPayload`]): a blank line is LaTeX syntax that no other construct
41//! element expresses.
42//!
43//! Both rules are marked as the default on this backend only
44//! ([`DefaultMark::OnBackends`]), so that they do not affect the `text`
45//! backend, which writes `flm.parbreak` natively and lowers `flm.paragraph`
46//! through the general rule of the `lowering` feature
47//! ([`PARAGRAPH_RULE`](crate::stdlib::backends::lowering::PARAGRAPH_RULE)).
48//!
49//! # Where the other recomposition rules are registered
50//!
51//! Each standard feature registers the lowering rule that writes its own
52//! elements back as LaTeX (its *recomposition rule*), in a `latex` module of
53//! its own, beside the feature's general rule. Such a rule refers to things
54//! the feature does not register: this backend, in its default mark; the
55//! LaTeX construct elements, in what it produces; and for some features a
56//! table another feature owns, such as the references feature's table of
57//! safe labels. The feature makes a peer declaration ([`PeerName`](crate::core::registry::PeerName)) of each:
58//! a forward declaration that the registry build resolves once every feature
59//! has registered. When a peer declaration resolves to nothing, the rule is
60//! set aside (excluded from rule selection) and the build records one Note.
61//! A host that registers the `textstyles` feature without the `latex`
62//! feature and this backend therefore still builds its registry; a host that
63//! registers this backend gets every feature's recomposition rule selected
64//! like any other rule. This backend's feature declares no content feature as
65//! a dependency: a registry that holds it needs only the `latex`, `lowering`
66//! and `check` features.
67
68use std::sync::Arc;
69
70use techy::core::node::NodeRef;
71
72use crate::core::lowering::{
73    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
74};
75use crate::lang::structural::{PARAGRAPH, PARBREAK};
76use crate::lang::Flm;
77use crate::model::names::ElementName;
78use crate::stdlib::backends::latex::LatexRawPayload;
79use crate::stdlib::backends::latex::construct::RAW as LATEX_RAW;
80use crate::stdlib::features::blocks::RAW;
81
82use super::feature::BACKEND;
83
84/// The registered name of the paragraph-break rule ([`ParbreakRule`]),
85/// `flm.parbreak.lower.latex-recomposed`.
86pub const PARBREAK_RULE: &str = "flm.parbreak.lower.latex-recomposed";
87
88/// The registered name of the paragraph rule ([`ParagraphRule`]),
89/// `flm.paragraph.lower.latex-recomposed`.
90pub const PARAGRAPH_RULE: &str = "flm.paragraph.lower.latex-recomposed";
91
92/// The text of the `flm.pres.latex.raw` node that both rules stage: two
93/// newlines, which LaTeX reads as one paragraph break.
94pub const BLANK_LINE: &str = "\n\n";
95
96/// Stages a `flm.pres.latex.raw` node holding one blank line ([`BLANK_LINE`])
97/// and returns its identifier in the tree being built.
98fn blank_line(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer) -> Result<techy::core::node::BuildId, LowerError> {
99    lw.pres_with(cx, &ElementName::from(LATEX_RAW), LatexRawPayload::new(BLANK_LINE), Vec::new())
100}
101
102/// The lowering rule registered as [`PARBREAK_RULE`]: it lowers a
103/// paragraph-break marker (`flm.parbreak`) to one blank line.
104///
105/// The author may have written several blank lines at that place; LaTeX reads
106/// any number of them as one paragraph break, and the recomposed LaTeX writes
107/// one.
108#[derive(Debug, Default, Clone, Copy)]
109pub struct ParbreakRule;
110
111impl Lower for ParbreakRule {
112    fn lower(
113        &self,
114        _node: NodeRef<'_, Flm>,
115        cx: &mut LowerCx<'_>,
116        lw: &mut dyn Lowerer,
117    ) -> Result<Lowering, LowerError> {
118        Ok(Lowering::Emit(vec![blank_line(cx, lw)?]))
119    }
120}
121
122/// The lowering rule registered as [`PARAGRAPH_RULE`]: it lowers a paragraph
123/// group (`flm.paragraph`) to its content, lowered, followed by one blank
124/// line.
125///
126/// The rule never applies on the raw tree that this backend requires; it
127/// exists so that the plan's completeness check
128/// ([`PlanError::Incomplete`](crate::core::plan::PlanError::Incomplete)) finds
129/// a rule for `flm.paragraph` (see the module documentation).
130#[derive(Debug, Default, Clone, Copy)]
131pub struct ParagraphRule;
132
133impl Lower for ParagraphRule {
134    fn lower(
135        &self,
136        node: NodeRef<'_, Flm>,
137        cx: &mut LowerCx<'_>,
138        lw: &mut dyn Lowerer,
139    ) -> Result<Lowering, LowerError> {
140        let mut nodes = lw.lower_children(cx, &node)?;
141        nodes.push(blank_line(cx, lw)?);
142        Ok(Lowering::Emit(nodes))
143    }
144}
145
146/// The two structural lowering rules of this backend, [`PARBREAK_RULE`] then
147/// [`PARAGRAPH_RULE`], ready to be registered; the [`LatexRecomposed`] feature
148/// registers them.
149///
150/// Each rule requires the capability [`RAW`] (`flm.blocks.raw`), produces
151/// `flm.pres.latex.raw` nodes, and is marked as the default on the
152/// `latex-recomposed` backend only ([`DefaultMark::OnBackends`]).
153///
154/// [`LatexRecomposed`]: super::LatexRecomposed
155///
156/// # Examples
157///
158/// ```
159/// use flm_core::stdlib::backends::latex_recomposed::rules::{PARBREAK_RULE, rules};
160///
161/// let names: Vec<String> = rules().iter().map(|rule| rule.name.to_string()).collect();
162/// assert_eq!(names[0], PARBREAK_RULE);
163/// assert!(rules().iter().all(|rule| rule.decl.requires[0].as_str() == "flm.blocks.raw"));
164/// ```
165pub fn rules() -> Vec<LoweringRule> {
166    let on_this_backend = || DefaultMark::OnBackends(vec![BACKEND.into()]);
167    vec![
168        LoweringRule::new(
169            PARBREAK_RULE,
170            PARBREAK,
171            LoweringDecl::new().requires(RAW).produces(LATEX_RAW),
172            Arc::new(ParbreakRule),
173            on_this_backend(),
174        )
175        .docs("a paragraph-break marker lowers to a raw blank line; requires the raw tree"),
176        LoweringRule::new(
177            PARAGRAPH_RULE,
178            PARAGRAPH,
179            LoweringDecl::new().requires(RAW).produces(LATEX_RAW),
180            Arc::new(ParagraphRule),
181            on_this_backend(),
182        )
183        .docs(
184            "a paragraph group lowers to its lowered content followed by a raw blank line; \
185             requires the raw tree, in which no paragraph group occurs",
186        ),
187    ]
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn both_rules_require_the_raw_tree_and_default_on_this_backend_only() {
196        for rule in rules() {
197            assert_eq!(rule.decl.requires, [crate::model::names::CapName::from(RAW)]);
198            assert_eq!(rule.decl.produces, [ElementName::from(LATEX_RAW)]);
199            assert!(rule.default.is_specific_to(&BACKEND.into()));
200            assert!(!rule.default.is_specific_to(&"text".into()));
201        }
202        assert_eq!(rules()[0].element, PARBREAK);
203        assert_eq!(rules()[1].element, PARAGRAPH);
204    }
205}