Skip to main content

flm_core/math_passthrough/
latex.rs

1//! The recomposition rules of the [`math-passthrough`](super) feature for the
2//! `latex-recomposed` backend: inline and displayed mathematics, and
3//! display-math environments rebuilt line by line, each formula written as it
4//! was written.
5//!
6//! The `latex-recomposed` backend writes the document back as LaTeX source. Its
7//! rules stage (build into the lowered tree; see
8//! [`Lowerer`]) construct elements, presentation
9//! elements that mirror one construct of LaTeX each ([backends, lowering and
10//! outputs](crate::guide::concepts_overview#backends-lowering-and-outputs)): a
11//! macro call, an environment, a raw node (`flm.pres.latex.raw`, text written
12//! byte for byte), or a definition for the style file. The rendering guide
13//! describes the result under [mathematics in the recomposed
14//! LaTeX](crate::guide::rendering#mathematics-in-the-recomposed-latex).
15//!
16//! # Mathematics is written from its nodes
17//!
18//! Every formula of the recomposed LaTeX (`\(…\)`, `\[…\]`, and each equation line
19//! of a display-math environment) is written by the mathematics writer of the
20//! `userdefs` feature
21//! ([`write_math_run`](crate::stdlib::features::userdefs::kept::write_math_run)):
22//! the source byte for byte, except where a user definition is used. A use of a
23//! user definition that can be written back as a LaTeX definition is written as a
24//! call, and its definition is written to the style file, as for a use in text; a
25//! use of any other user definition is written as its expansion. Nothing inside a
26//! formula is lowered
27//! through the rules except a text command, which is lowered like document text
28//! ([`TEXT_LATEX_RULE`](crate::stdlib::features::math::latex::TEXT_LATEX_RULE)),
29//! and a source comment, which is staged as a comment node
30//! for the emitter.
31//!
32//! # Inline and displayed mathematics
33//!
34//! [`MATH_LATEX_RULE`] (`flm.math.lower.passthrough-latex-recomposed`) is the rule of
35//! `flm.math` on this backend: the group's content written by the mathematics
36//! writer, between the opening and closing parts of the `math` feature's LaTeX
37//! library ([`group_opening`], [`group_closing`]): `\[`…`\]` for displayed
38//! mathematics and `\(`…`\)` for inline mathematics, whichever delimiters the
39//! author used (the formula of an `\ensuremath{…}` written in text:
40//! `\ensuremath{`…`}`).
41//!
42//! # Display-math environments
43//!
44//! A display-math environment is rebuilt line by line, because its body holds
45//! data that the recomposed LaTeX writes differently from the source: the labels
46//! of each line, which the author may write anywhere on the line and which are
47//! written together at the line's end (see *What is written for a line's labels*
48//! below), and the tag of a line, whose content is document text that the rules
49//! lower and the emitter escapes; the rule writes every tag as `\tag*{…}` and
50//! adds the parentheses of an unstarred `\tag` itself.
51//!
52//! [`ENVIRONMENT_LATEX_RULE`] (`flm.math.environment.lower.passthrough-latex-recomposed`)
53//! reads the body as equation lines ([`line_frames`]) and stages, between the
54//! opening and closing parts of the `math` feature's LaTeX library
55//! ([`environment_opening`], [`environment_closing`]), the lines as the
56//! library's line writer ([`stage_lines`]) writes them: for each line in order
57//! its content (item 1 below), the library's closing part of a line
58//! ([`line_closing`](crate::stdlib::features::math::latex::line_closing):
59//! items 2 to 5), and the run of whitespace of item 6:
60//!
61//! 1. The line's content, written by the mathematics writer: raw nodes under the
62//!    library's newline rule (below), the constructs of the user definitions
63//!    used on the line, and every source comment as its comment node, which the
64//!    emitter writes as it writes a comment in text (ending the comment's line
65//!    itself), or leaves out under the backend's render option
66//!    [`drop_comments`](LatexRecomposedRenderOptions::drop_comments).
67//! 2. `\tag*{…}` when the line has a tag: a macro construct whose argument holds
68//!    the tag's content lowered through the ordinary rules, between a `(` and a
69//!    `)` when the tag is not starred. The content is document text, so the
70//!    emitter escapes it.
71//! 3. The line's labels, in order, as one group in `\flmLabels`, a [LaTeX
72//!    hook](crate::stdlib::backends::latex::preamble) (a macro that the style
73//!    file defines with a plain default and that a user redefines in the
74//!    document's preamble; see *What is written for a line's labels*).
75//! 4. `\nonumber` when the line is marked with it, as a macro construct with no
76//!    argument.
77//! 5. The line's `\\`, with its spacing argument as written, as a raw node, when
78//!    another line follows. A final `\\` followed only by whitespace and comments
79//!    is not written back: `amsmath` would set an empty line for it.
80//! 6. The run of whitespace that ended the line's content (a newline and the
81//!    indentation after it), when the newline rule took it off, as a raw node.
82//!
83//! **The newline rule** is the `math` library's
84//! ([`normalize_line_newlines`](crate::stdlib::features::math::latex::normalize_line_newlines);
85//! the library's module documentation, *The newline rule*, states it in full).
86//! Inside a line's content, every run of spaces, tabs and newlines that holds a
87//! newline is written as one newline followed by the indentation after the run's
88//! last newline, so that a label taken off a line of its own, or a dropped
89//! comment, leaves no blank line; the run that ends the content is written after
90//! the line's closing part (item 6), and a run that comes right after a line's
91//! end (that run of the previous line, or a comment) is dropped. When the content
92//! of a line ends with a comment, the line's tag, labels, `\nonumber` and `\\` are
93//! written after the comment's newline, on the next line: a comment never hides
94//! the commands of its line.
95//!
96//! Every environment except `equation` is defined by the LaTeX package `amsmath`,
97//! which the rule then requests (records a package request for; see
98//! [`packages`](crate::stdlib::backends::latex::packages)). A body reported as malformed (an empty line, reported by the
99//! feature's check stage, or a label or tag on a line without a number,
100//! reported by the `math` feature when the body is parsed) is written back as
101//! the author wrote it; those Errors are the only report.
102//!
103//! Two options of the `math` feature ([`MathRecomposeOptions`], set per render
104//! request) change the result:
105//!
106//! - [`surround_display_math`](MathRecomposeOptions::surround_display_math) is
107//!   a pair of LaTeX texts written, byte for byte, before and after every
108//!   displayed formula, environments and `\[…\]` groups alike (both empty by
109//!   default).
110//! - [`emit_flm_math_environment_macro`](MathRecomposeOptions::emit_flm_math_environment_macro)
111//!   writes the environment as `\flmMathEnvironment{<name>}{<arguments>}{<body>}`
112//!   instead, a LaTeX hook defined over `\begin`…`\end` by the definition piece
113//!   [`MATH_ENVIRONMENT`](crate::stdlib::backends::latex::preamble::MATH_ENVIRONMENT),
114//!   which the rule then requires. The hook is a LaTeX hook like `\flmLabels`
115//!   (item 3 above); a definition piece is the unit of LaTeX definitions that
116//!   defines it
117//!   ([`LatexPreambleDef`](crate::stdlib::backends::latex::LatexPreambleDef)).
118//!   The six environments take no arguments, so `<arguments>` is empty.
119//!
120//! # What is written for a line's labels
121//!
122//! A label written on an equation line is data of that line, and
123//! [`ENVIRONMENT_LATEX_RULE`] writes it. Every label of the recomposed LaTeX is
124//! written inside the LaTeX hook `\flmLabels{…}`, in mathematics as after a
125//! heading: each label through [`stage_label`](crate::stdlib::features::refs::stage_label), and the line's labels together
126//! through [`stage_label_group`](crate::stdlib::features::refs::stage_label_group), as in `\flmLabels{\label{ref1}\label{ref2}}`.
127//! The group makes every label after the first on a line refer to that line's
128//! number, which `amsmath` alone does not do. The render option
129//! [`label_hooks`](LatexRecomposedRenderOptions::label_hooks) turns the group off
130//! here as it does everywhere.
131//!
132//! What is written inside each `\label` depends on the safe-labels table of the
133//! references feature ([`SAFE_LABELS`]), which the rule reads optionally, under a
134//! peer declaration ([`PeerName`](crate::core::registry::PeerName)):
135//!
136//! - **With the references feature**, the table holds a safe label for the label
137//!   (the key under which the recomposed LaTeX writes it,
138//!   [`SafeLabels`]), and [`stage_label`](crate::stdlib::features::refs::stage_label) writes it.
139//! - **Without it**, the table is absent, and [`stage_label`](crate::stdlib::features::refs::stage_label) writes the label as
140//!   the document wrote it, byte for byte and **unescaped**; what LaTeX makes of
141//!   a character it treats specially is the caller's concern. The choice between
142//!   the two cases is made by
143//!   [`label_spelling`](crate::stdlib::features::refs::label_spelling).
144//!
145//! When the table is absent, the render option
146//! [`drop_math_labels_without_refs`](LatexRecomposedRenderOptions::drop_math_labels_without_refs)
147//! is also read: when it is set, nothing is written for the line's labels, no
148//! `\label` and no group. With the references feature registered, the option is
149//! not read and changes nothing. A `\tag` and a `\nonumber` are not labels and are
150//! written in both cases.
151//!
152//! No rule here numbers a line: the recomposed LaTeX leaves the numbering to
153//! LaTeX, so the numbers of the compiled document follow its document class and
154//! not FLM's counters.
155//!
156//! # Peer declarations
157//!
158//! The feature owns neither the backend nor the construct elements nor the
159//! safe-labels table, and reads the options of the `math` feature. [`register`] declares them as peer declarations, so that a
160//! registry without the LaTeX features still builds; the rules are then set aside
161//! (excluded from rule selection; see
162//! [`PeerName`](crate::core::registry::PeerName)). The safe-labels table is read
163//! optionally, so that a registry with the backend and without the references
164//! feature still renders.
165
166
167use std::sync::Arc;
168
169use techy::core::node::NodeRef;
170
171use crate::core::lowering::{
172    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
173};
174use crate::core::registry::{BuildError, FeatureBuilder};
175use crate::lang::Flm;
176use crate::lang::structural::MATH;
177use crate::model::names::RuleName;
178use crate::stdlib::backends::latex::construct::{DEFINITION, MACRO, RAW};
179use crate::stdlib::backends::latex::{LatexDefinitionPayload, LatexMacroPayload, LatexRawPayload};
180use crate::stdlib::backends::latex_recomposed::{BACKEND, LatexRecomposedRenderOptions};
181use crate::stdlib::features::math::frame::line_frames;
182use crate::stdlib::features::math::latex::{
183    environment_closing, environment_opening, group_closing, group_opening, stage_lines,
184};
185use crate::stdlib::features::math::{ENVIRONMENT, MathRecomposeOptions};
186use crate::stdlib::features::refs::{SAFE_LABELS, SafeLabels};
187use crate::stdlib::features::userdefs::kept::stage_math_run;
188
189use super::recomposed_unchecked;
190
191/// The name of the recomposition rule of the display-math environments
192/// (`flm.math.environment`) of passthrough mathematics,
193/// `flm.math.environment.lower.passthrough-latex-recomposed`, whose body is
194/// [`EnvironmentLatexRule`]. The default on the `latex-recomposed` backend
195/// only.
196pub const ENVIRONMENT_LATEX_RULE: &str =
197    "flm.math.environment.lower.passthrough-latex-recomposed";
198
199/// The name of the recomposition rule of inline and displayed mathematics
200/// (`flm.math`) of passthrough mathematics,
201/// `flm.math.lower.passthrough-latex-recomposed`, whose body is
202/// [`MathLatexRule`]. The default on the `latex-recomposed` backend only.
203pub const MATH_LATEX_RULE: &str = "flm.math.lower.passthrough-latex-recomposed";
204
205/// The body of [`MATH_LATEX_RULE`]: the group's opening part
206/// ([`group_opening`]), the group's content written by the mathematics writer
207/// ([`stage_math_run`]), and the group's closing part ([`group_closing`]). See
208/// the module documentation, *Inline and displayed mathematics*.
209#[derive(Debug, Default, Clone, Copy)]
210pub struct MathLatexRule;
211
212impl Lower for MathLatexRule {
213    fn lower(
214        &self,
215        node: NodeRef<'_, Flm>,
216        cx: &mut LowerCx<'_>,
217        lw: &mut dyn Lowerer,
218    ) -> Result<Lowering, LowerError> {
219        let content: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
220        let mut nodes = group_opening(cx, lw, &node)?;
221        nodes.extend(stage_math_run(cx, lw, &content)?);
222        nodes.extend(group_closing(cx, lw, &node)?);
223        Ok(Lowering::Emit(nodes))
224    }
225}
226
227/// The rule [`MATH_LATEX_RULE`], ready to be registered: [`math_rule_named`]
228/// under that name.
229pub fn math_rule() -> LoweringRule {
230    math_rule_named(MATH_LATEX_RULE)
231}
232
233/// The library's rule of `flm.math` for the `latex-recomposed` backend,
234/// under the rule name `name`, ready to be registered by any feature: its
235/// body is [`MathLatexRule`], it targets `flm.math`, reads two option types
236/// (the `math` feature's [`MathRecomposeOptions`] and the backend's
237/// [`LatexRecomposedRenderOptions`]), produces the raw construct and the
238/// definition construct (for a user definition used inside mathematics), is
239/// the default on the `latex-recomposed` backend only, declares its output
240/// unchecked there (see the [module documentation](super), *Output that
241/// nothing checks*), and carries the library's description. [`math_rule`] is
242/// this rule under [`MATH_LATEX_RULE`].
243///
244/// A feature that registers the rule declares beside it, as [`register`]
245/// does, a peer declaration ([`PeerName`](crate::core::registry::PeerName))
246/// of the backend ([`FeatureBuilder::peer_backend`]) and of the two
247/// construct elements ([`FeatureBuilder::peer_element`]: [`RAW`], of payload
248/// type [`LatexRawPayload`], and [`DEFINITION`], of payload type
249/// [`LatexDefinitionPayload`]). The feature that registers the rule is its
250/// owner: a plan that keeps its unchecked output names that feature in the
251/// [`PlanWarning::UncheckedOutput`](crate::core::plan::PlanWarning::UncheckedOutput),
252/// with the texts the library declares.
253pub fn math_rule_named(name: impl Into<RuleName>) -> LoweringRule {
254    LoweringRule::new(
255        name,
256        MATH,
257        recomposed_unchecked(
258            LoweringDecl::new()
259                .option::<MathRecomposeOptions>()
260                .option::<LatexRecomposedRenderOptions>()
261                .produces(RAW)
262                .produces(DEFINITION),
263        ),
264        Arc::new(MathLatexRule),
265        DefaultMark::OnBackends(vec![BACKEND.into()]),
266    )
267    .docs(
268        "inline or displayed mathematics lowers to its delimiters around its content written \
269         from its nodes: byte for byte, except that a use of a user definition is written as \
270         a call, with the definition for the style file, or as its expansion",
271    )
272}
273
274/// The body of [`ENVIRONMENT_LATEX_RULE`]: the environment rebuilt line by
275/// line (see the module documentation, *Display-math environments*), between
276/// the environment's opening part ([`environment_opening`]) and its closing
277/// part ([`environment_closing`]).
278///
279/// The rule returns a [`LowerError`] when the node carries no
280/// [`MathEnvironment`](crate::stdlib::features::math::MathEnvironment), when a
281/// table or an option cannot be read, or when a node could not be staged.
282#[derive(Debug, Default, Clone, Copy)]
283pub struct EnvironmentLatexRule;
284
285impl Lower for EnvironmentLatexRule {
286    fn lower(
287        &self,
288        node: NodeRef<'_, Flm>,
289        cx: &mut LowerCx<'_>,
290        lw: &mut dyn Lowerer,
291    ) -> Result<Lowering, LowerError> {
292        let mut nodes = environment_opening(cx, lw, &node)?;
293        // LaTeX numbers the lines and finds their anchors itself: the frames
294        // are read without the two tables.
295        let frames = line_frames(None, None, lw.addr(), &node)
296            .map_err(|error| LowerError::structure(error.to_string()))?;
297        nodes.extend(stage_lines(cx, lw, &frames)?);
298        nodes.extend(environment_closing(cx, lw, &node)?);
299        Ok(Lowering::Emit(nodes))
300    }
301}
302
303/// The rule [`ENVIRONMENT_LATEX_RULE`], ready to be registered:
304/// [`environment_rule_named`] under that name.
305pub fn environment_rule() -> LoweringRule {
306    environment_rule_named(ENVIRONMENT_LATEX_RULE)
307}
308
309/// The library's rule of `flm.math.environment` for the `latex-recomposed`
310/// backend, under the rule name `name`, ready to be registered by any
311/// feature: its body is [`EnvironmentLatexRule`], it targets
312/// `flm.math.environment`, reads the safe-labels table optionally and two
313/// option types (the `math` feature's [`MathRecomposeOptions`] and the
314/// backend's [`LatexRecomposedRenderOptions`]), produces the macro, raw and
315/// definition constructs (the last for a user definition used on a line), is
316/// the default on the `latex-recomposed` backend only, declares its output
317/// unchecked there (see the [module documentation](super), *Output that
318/// nothing checks*), and carries the library's description.
319/// [`environment_rule`] is this rule under [`ENVIRONMENT_LATEX_RULE`].
320///
321/// A line's labels are written from the line's own data; the module
322/// documentation, *What is written for a line's labels*, says what the table
323/// and the backend's options change.
324///
325/// A feature that registers the rule declares beside it, as [`register`]
326/// does, a peer declaration ([`PeerName`](crate::core::registry::PeerName))
327/// of the backend ([`FeatureBuilder::peer_backend`]), of the three construct
328/// elements ([`FeatureBuilder::peer_element`]: [`MACRO`], [`RAW`] and
329/// [`DEFINITION`], of payload types [`LatexMacroPayload`],
330/// [`LatexRawPayload`] and [`LatexDefinitionPayload`]) and of the safe-labels
331/// table ([`FeatureBuilder::peer_table`]: [`SAFE_LABELS`], of value type
332/// [`SafeLabels`]). The feature that registers the rule is its owner: a plan
333/// that keeps its unchecked output names that feature in the
334/// [`PlanWarning::UncheckedOutput`](crate::core::plan::PlanWarning::UncheckedOutput),
335/// with the texts the library declares.
336pub fn environment_rule_named(name: impl Into<RuleName>) -> LoweringRule {
337    LoweringRule::new(
338        name,
339        ENVIRONMENT,
340        recomposed_unchecked(
341            LoweringDecl::new()
342                .reads_opt(SAFE_LABELS)
343                .option::<MathRecomposeOptions>()
344                .option::<LatexRecomposedRenderOptions>()
345                .produces(MACRO)
346                .produces(RAW)
347                .produces(DEFINITION),
348        ),
349        Arc::new(EnvironmentLatexRule),
350        DefaultMark::OnBackends(vec![BACKEND.into()]),
351    )
352    .docs(
353        "a display-math environment lowers to the LaTeX environment of the same name over \
354         its equation lines rebuilt one by one, each line's labels written as one group in \
355         `\\flmLabels` at the end of the line: as their safe labels when the safe-labels \
356         table is present, as the document wrote them when it is absent, and not at all \
357         when it is absent and the render options ask for none",
358    )
359}
360
361
362/// Registers what the `math-passthrough` feature contributes to the
363/// `latex-recomposed` backend: a peer declaration
364/// ([`PeerName`](crate::core::registry::PeerName)) of the backend, of the three
365/// construct elements the rules stage (each with its payload type) and of the
366/// safe-labels table (with its value type), then [`math_rule`] and
367/// [`environment_rule`].
368///
369/// In a registry without the LaTeX features the peer declarations resolve to
370/// nothing and the rules are set aside (excluded from rule selection); the
371/// registry still builds. The safe-labels table is read optionally, so that a
372/// registry with the backend and without the references feature still
373/// renders: a line's labels are then written as the document wrote them,
374/// inside `\flmLabels` as always (see the module documentation, *What is
375/// written for a line's labels*).
376///
377/// # Errors
378///
379/// Returns the [`BuildError`] the feature builder raises, for instance for a
380/// rule already registered under the same name.
381pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
382    b.peer_backend(
383        BACKEND,
384        "the latex-recomposed backend, on which the recomposition rules of passthrough \
385         mathematics are the default",
386    )?;
387    b.peer_element::<LatexMacroPayload>(
388        MACRO,
389        "the LaTeX family's macro construct, which the recomposition rules of mathematics \
390         stage",
391    )?;
392    b.peer_element::<LatexRawPayload>(
393        RAW,
394        "the LaTeX family's raw construct, which the recomposition rules of mathematics \
395         stage",
396    )?;
397    b.peer_element::<LatexDefinitionPayload>(
398        DEFINITION,
399        "the LaTeX family's definition construct, which the recomposition rules of \
400         mathematics stage for a user definition used inside a formula",
401    )?;
402    b.peer_table::<SafeLabels>(
403        SAFE_LABELS.name(),
404        "the references feature's safe-labels table, which the recomposition rule of the \
405         display-math environments reads for the safe label of each label of an equation \
406         line",
407    )?;
408    b.lowering_rule(math_rule())?;
409    b.lowering_rule(environment_rule())
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415    use crate::model::names::ElementName;
416
417    #[test]
418    fn the_rule_is_the_default_on_the_recomposed_backend_only() {
419        let rule = environment_rule();
420        assert_eq!(rule.name, ENVIRONMENT_LATEX_RULE);
421        assert_eq!(rule.element, ENVIRONMENT);
422        assert!(rule.default.is_specific_to(&BACKEND.into()));
423        assert_eq!(rule.decl.options.len(), 2);
424        assert!(rule.decl.reads.is_empty());
425        assert_eq!(
426            rule.decl.reads_opt.len(),
427            1,
428            "a line's labels are written as their safe keys where the table is there"
429        );
430        assert_eq!(rule.decl.produces.len(), 3);
431        let math = math_rule();
432        assert_eq!(math.name, MATH_LATEX_RULE);
433        assert_eq!(math.element, MATH);
434        assert!(math.default.is_specific_to(&BACKEND.into()));
435        assert_eq!(math.decl.produces, [ElementName::from(RAW), ElementName::from(DEFINITION)]);
436        assert!(
437            math.decl.options.contains(&crate::model::options::OptionRef::of::<MathRecomposeOptions>()),
438            "a displayed group is surrounded as an environment is, so the rule reads the math options"
439        );
440    }
441
442}