Skip to main content

flm_core/math_passthrough/
source.rs

1//! The source walk of the [`math-passthrough`](super) feature and the bodies
2//! of its rules that stage `flm.pres.math-passthrough`: the rule of the math
3//! groups (`\(…\)`, `\[…\]`), the rule of the display-math environments, and
4//! the rule of an opaque command lowered on its own.
5//!
6//! Each rule stages (builds into the lowered tree; see [`Lowerer`]) one
7//! [`flm.pres.math-passthrough`](crate::stdlib::backends::pres::MATH_PASSTHROUGH)
8//! node whose body is the source the author wrote, in order and unchanged,
9//! except that every text command becomes content: a `flm.pres.math-text` node
10//! holding the command's argument lowered as inline content, and that
11//! `\ensuremath{…}` inside a formula is written as its argument's content, the
12//! command left out ([`ensuremath`](crate::stdlib::features::math::ensuremath)).
13//! A backend that writes `flm.pres.math-passthrough` natively (the three
14//! standard backends do) needs no rule of its own; on the `latex-recomposed`
15//! backend the feature's rules of [`super::latex`] are chosen instead.
16//!
17//! The rule of the display-math environments reads the line anchors and the
18//! line numbers through the library of the
19//! [`math`](crate::stdlib::features::math) feature
20//! ([`line_frames`], [`stage_tag_content`]), which owns the equation lines,
21//! their reference points and their numbering, and writes each line's content
22//! under that library's newline rule (the module documentation of
23//! [`latex`](crate::stdlib::features::math::latex), *The newline rule*), so
24//! that a `\label`, `\tag` or `\nonumber` taken off a line of its own leaves
25//! no blank line in the formula's source: the run of whitespace that ends a
26//! line's content is written after the line's tag and its `\\`.
27
28use techy::core::node::{BuildId, NodeRef};
29use techy::latexlike::{InvocationSyntaxData, MathGroupForm};
30
31use crate::core::lowering::{Lower, LowerCx, LowerError, Lowerer, Lowering};
32use crate::lang::Flm;
33use crate::lang::mint::is_math_text_command;
34use crate::model::element::{element_of, element_value};
35use crate::model::names::{ElementName, Name};
36use crate::stdlib::backends::lowering::{copy_subtree_verbatim, lower_run};
37use crate::stdlib::backends::pres::{
38    self, MathDisplay, MathPassthroughPayload, MathTextPayload, recompose_source,
39};
40use crate::stdlib::features::math::MathEnvironment;
41use crate::stdlib::features::math::ensuremath::ENSUREMATH;
42use crate::stdlib::features::math::frame::{formula_display, line_frames, stage_tag_content};
43use crate::stdlib::features::math::html::FORMULA_ROLE;
44use crate::stdlib::features::math::latex::NewlineRule;
45use crate::stdlib::features::numbering::COUNTERS;
46use crate::stdlib::features::refs::ANCHORS;
47
48/// The payload of a formula's `flm.pres.math-passthrough` node: `display`,
49/// `env`, and the role of a formula's outermost element, which marks the
50/// formula in an HTML page ([`FORMULA_ROLE`]).
51fn formula_payload(display: MathDisplay, env: Option<String>) -> MathPassthroughPayload {
52    MathPassthroughPayload { display, env, role: Some(Name::from(FORMULA_ROLE)) }
53}
54
55/// The display form of a node, taken from the nearest math group that
56/// contains it: display inside a display group, inline inside any other math
57/// group and when no math group contains the node.
58fn enclosing_display(node: &NodeRef<'_, Flm>) -> MathDisplay {
59    let mut ancestor = node.parent();
60    while let Some(up) = ancestor {
61        if let Some(form) = up.math_form() {
62            return match form {
63                MathGroupForm::Display => MathDisplay::Display,
64                _ => MathDisplay::Inline,
65            };
66        }
67        ancestor = up.parent();
68    }
69    MathDisplay::Inline
70}
71
72/// The body of [`OPAQUE_RULE`](super::OPAQUE_RULE): it stages a
73/// [`flm.pres.math-passthrough`](crate::stdlib::backends::pres::MATH_PASSTHROUGH) node
74/// over a copy of the opaque node, displayed when the nearest math group that
75/// contains the node is displayed and inline otherwise.
76///
77/// The rule runs only when an opaque node is lowered on its own; see the
78/// [feature's module documentation](super), *The rules*. It
79/// returns a [`LowerError`] when the copy or the node could not be staged.
80#[derive(Debug, Default)]
81pub struct OpaqueRule;
82
83impl Lower for OpaqueRule {
84    fn lower(
85        &self,
86        node: NodeRef<'_, Flm>,
87        cx: &mut LowerCx<'_>,
88        lw: &mut dyn Lowerer,
89    ) -> Result<Lowering, LowerError> {
90        let display = enclosing_display(&node);
91        let body = vec![copy_subtree_verbatim(cx, node)?];
92        let payload = formula_payload(display, None);
93        let math = lw.pres_with(cx, &ElementName::from(pres::MATH_PASSTHROUGH), payload, body)?;
94        Ok(Lowering::Emit(vec![math]))
95    }
96}
97
98/// Stages a run of a formula's nodes for the body of a
99/// `flm.pres.math-passthrough` node: every text command, at any depth, is lowered
100/// through the rules and becomes a `flm.pres.math-text` node, and everything
101/// else is written back as its source.
102///
103/// The walk goes through the whole formula, since a text command may be
104/// written at any depth: a group is written as its delimiters around the walk
105/// of its children, an environment as `\begin{…}` and `\end{…}` around the
106/// walk of its arguments and body, `\ensuremath{…}` as the walk of its
107/// argument's content alone, any other command with arguments as the call as
108/// written followed by the walk of each argument, and any other node as a
109/// copy. [`MathRule`] uses it; [`EnvironmentRule`] walks each node of a line
110/// that holds a text command or `\ensuremath{…}` the same way.
111///
112/// # Errors
113///
114/// Returns [`LowerError`] when a copy or a text node could not be staged, or
115/// when a text command could not be lowered.
116pub(crate) fn stage_source(
117    cx: &mut LowerCx<'_>,
118    lw: &mut dyn Lowerer,
119    nodes: &[NodeRef<'_, Flm>],
120) -> Result<Vec<BuildId>, LowerError> {
121    let mut body = Vec::with_capacity(nodes.len());
122    for node in nodes {
123        stage_node(cx, lw, *node, &mut body)?;
124    }
125    Ok(body)
126}
127
128/// Stages one node of a formula and appends what it staged to `body` (see
129/// [`stage_source`] for the cases).
130// This walk carries no depth limit of its own, and needs none, because the
131// parse that made the tree stops first. A parse holds far more on the stack per
132// level of nesting than this walk does, and the parser's stack guard refuses a
133// formula long before the depth this walk would need to run out of the worker
134// thread's stack: measured, a formula of nested braces is refused at about two
135// thousand levels, and a formula at that depth walks through here without
136// trouble. Keep the margin in mind if the parser's stack budget is raised or if
137// this function grows much larger frames.
138fn stage_node(
139    cx: &mut LowerCx<'_>,
140    lw: &mut dyn Lowerer,
141    node: NodeRef<'_, Flm>,
142    body: &mut Vec<BuildId>,
143) -> Result<(), LowerError> {
144    if is_math_text_command(&node) {
145        body.extend(lower_run(cx, lw, std::slice::from_ref(&node))?);
146        return Ok(());
147    }
148    if let Some((open, close)) = node.group_delimiters() {
149        body.push(lw.text(cx, open)?);
150        body.extend(stage_source(cx, lw, &children_of(&node))?);
151        body.push(lw.text(cx, close)?);
152        return Ok(());
153    }
154    if node.is_list() {
155        body.extend(stage_source(cx, lw, &children_of(&node))?);
156        return Ok(());
157    }
158    if let Some(inner) = node.body() {
159        // An environment inside the formula. The name it was written with is
160        // written back around the walk of its arguments and its body.
161        let name = node.name().unwrap_or_default();
162        body.push(lw.text(cx, &format!("\\begin{{{name}}}"))?);
163        stage_arguments(cx, lw, &node, body)?;
164        let inner: Vec<NodeRef<'_, Flm>> = inner.iter().collect();
165        body.extend(stage_source(cx, lw, &inner)?);
166        body.push(lw.text(cx, &format!("\\end{{{name}}}"))?);
167        return Ok(());
168    }
169    if element_of(&node).name == ENSUREMATH {
170        // Inside a formula, `\ensuremath{X}` stands for `X`: the argument's
171        // content is written in place of the command.
172        let content: Vec<NodeRef<'_, Flm>> =
173            node.argument_content_nodes(0).map(|slice| slice.iter().collect()).unwrap_or_default();
174        body.extend(stage_source(cx, lw, &content)?);
175        return Ok(());
176    }
177    if node.callable().is_some_and(|callable| !callable.arguments.is_empty()) {
178        body.push(lw.text(cx, &macro_call(&node))?);
179        return stage_arguments(cx, lw, &node, body);
180    }
181    body.push(copy_subtree_verbatim(cx, node)?);
182    Ok(())
183}
184
185/// The children of a node, collected into a list so that the walk can borrow
186/// the [`Lowerer`] mutably while it goes through them.
187fn children_of<'t>(node: &NodeRef<'t, Flm>) -> Vec<NodeRef<'t, Flm>> {
188    node.children().iter().collect()
189}
190
191/// The beginning of a macro call as written: the escape character, the name,
192/// and the whitespace after the name, which belongs to the call and not to
193/// the argument that follows it.
194fn macro_call(node: &NodeRef<'_, Flm>) -> String {
195    let name = node.name().unwrap_or_default();
196    match node.invocation_syntax() {
197        Some(InvocationSyntaxData::Macro { escape_char, post_space }) => {
198            format!("{escape_char}{name}{}", post_space.resolve(node.span().source()))
199        }
200        _ => format!("\\{name}"),
201    }
202}
203
204/// Walks the arguments of `node` in the order they were written and appends
205/// what it stages to `body`. The delimiters of an argument are nodes of the
206/// argument, so the walk writes them back with it.
207fn stage_arguments(
208    cx: &mut LowerCx<'_>,
209    lw: &mut dyn Lowerer,
210    node: &NodeRef<'_, Flm>,
211    body: &mut Vec<BuildId>,
212) -> Result<(), LowerError> {
213    let count = node.callable().map_or(0, |callable| callable.arguments.len());
214    for index in 0..count {
215        if let Some(region) = node.argument_nodes(index) {
216            let nodes: Vec<NodeRef<'_, Flm>> = region.iter().collect();
217            body.extend(stage_source(cx, lw, &nodes)?);
218        }
219    }
220    Ok(())
221}
222
223/// Stages one equation line's tag: the text `\tag*{`, a
224/// [`flm.pres.math-text`](crate::stdlib::backends::pres::MATH_TEXT) node
225/// holding `content`, and `}`; nothing when `content` is empty.
226///
227/// The same function writes an author's tag and a line's number: `content` is
228/// the lowered content of the author's `\tag`, with the parentheses of the
229/// unstarred form already added, or the number the document gave the line.
230/// The form `\tag*` writes its content as given, so nothing is added to it.
231/// The content node is marked
232/// [`at_tag`](crate::stdlib::backends::pres::MathTextPayload::at_tag), so that
233/// each backend can write it as a tag's content requires.
234///
235/// # Errors
236///
237/// Returns [`LowerError`] when a node could not be staged, or when the calling
238/// rule does not declare that it produces `flm.pres.math-text`.
239fn stage_tag(
240    cx: &mut LowerCx<'_>,
241    lw: &mut dyn Lowerer,
242    content: Vec<BuildId>,
243) -> Result<Vec<BuildId>, LowerError> {
244    if content.is_empty() {
245        return Ok(Vec::new());
246    }
247    let payload = MathTextPayload { command: None, anchor: None, at_tag: true };
248    let text = lw.pres_with(cx, &ElementName::from(pres::MATH_TEXT), payload, content)?;
249    Ok(vec![lw.text(cx, "\\tag*{")?, text, lw.text(cx, "}")?])
250}
251
252/// Whether the walk ([`stage_node`]) must write `node` itself rather than
253/// copy its source: a text command or `\ensuremath{…}`, or a node that holds
254/// one.
255fn needs_walk(node: &NodeRef<'_, Flm>) -> bool {
256    let walked =
257        |node: &NodeRef<'_, Flm>| is_math_text_command(node) || element_of(node).name == ENSUREMATH;
258    walked(node) || node.descendants().any(|descendant| walked(&descendant))
259}
260
261/// One part of an equation line's content, as [`stage_line_content`] writes
262/// it.
263enum LinePart<'t> {
264    /// The source of a run of nodes that need no walk, written as text under
265    /// the newline rule.
266    Text(String),
267    /// A source comment, copied.
268    Comment(NodeRef<'t, Flm>),
269    /// A node written by the walk.
270    Walked(NodeRef<'t, Flm>),
271}
272
273/// Stages the content of one equation line and appends what it staged to
274/// `body`, under the `math` library's newline rule (`rule`, carried across
275/// the environment's lines): each run of nodes that need no walk as the text
276/// of its source, each source comment as a copy, and every other node by the
277/// walk ([`stage_node`]). Returns the run of whitespace the rule took off the
278/// content's end, to be written after the line's tag and its `\\`.
279fn stage_line_content(
280    cx: &mut LowerCx<'_>,
281    lw: &mut dyn Lowerer,
282    content: &[NodeRef<'_, Flm>],
283    rule: &mut NewlineRule,
284    body: &mut Vec<BuildId>,
285) -> Result<String, LowerError> {
286    let mut parts = Vec::new();
287    let mut run: Vec<NodeRef<'_, Flm>> = Vec::new();
288    for node in content {
289        if node.is_comment() || needs_walk(node) {
290            if !run.is_empty() {
291                parts.push(LinePart::Text(recompose_source(&run)));
292                run.clear();
293            }
294            parts.push(if node.is_comment() { LinePart::Comment(*node) } else { LinePart::Walked(*node) });
295        } else {
296            run.push(*node);
297        }
298    }
299    if !run.is_empty() {
300        parts.push(LinePart::Text(recompose_source(&run)));
301    }
302    let count = parts.len();
303    let mut trailing = String::new();
304    for (index, part) in parts.into_iter().enumerate() {
305        match part {
306            LinePart::Text(text) => {
307                let line = rule.text(&text, index + 1 == count);
308                if !line.text.is_empty() {
309                    body.push(lw.text(cx, &line.text)?);
310                }
311                trailing = line.trailing;
312            }
313            LinePart::Comment(node) => {
314                rule.written(&recompose_source(&[node]));
315                body.push(copy_subtree_verbatim(cx, node)?);
316            }
317            LinePart::Walked(node) => {
318                stage_node(cx, lw, node, body)?;
319                rule.piece(false);
320            }
321        }
322    }
323    Ok(trailing)
324}
325
326/// The body of [`ENVIRONMENT_RULE`](super::ENVIRONMENT_RULE): it stages a displayed
327/// [`flm.pres.math-passthrough`](crate::stdlib::backends::pres::MATH_PASSTHROUGH)
328/// node that carries the environment's name, over the environment's equation
329/// lines: for each line, an empty `flm.pres.math-text` node carrying the
330/// line's anchor, the line's source, the line's tag or number, its `\\` when
331/// another line follows, and the run of whitespace that ended the line's
332/// source. A line's `\label` and `\nonumber` are not written: they are data
333/// of the line, which the `math` feature has already read.
334///
335/// The line's source is written under the `math` library's newline rule (see
336/// the module documentation): the source of the nodes that hold no text
337/// command is written as text, so that the rule applies to it.
338///
339/// The rule reads the anchors table and the counter table when they are
340/// present; without them the lines carry no anchor and no number. It returns
341/// a [`LowerError`] when the node carries no [`MathEnvironment`] (a node that a
342/// parse produced for one of the six environments always carries one), when a
343/// table cannot be read, or when a node could not be staged.
344#[derive(Debug, Default, Clone, Copy)]
345pub struct EnvironmentRule;
346
347impl Lower for EnvironmentRule {
348    fn lower(
349        &self,
350        node: NodeRef<'_, Flm>,
351        cx: &mut LowerCx<'_>,
352        lw: &mut dyn Lowerer,
353    ) -> Result<Lowering, LowerError> {
354        let value = element_value::<MathEnvironment>(&node)
355            .ok_or_else(|| LowerError::structure("a math environment without its value"))?;
356        // The frames are computed before anything is staged, because reading
357        // a table borrows the façade the staging needs.
358        let frames = line_frames(lw.get(ANCHORS)?, lw.get(COUNTERS)?, lw.addr(), &node)
359            .map_err(|error| LowerError::structure(error.to_string()))?;
360        let mut body = Vec::new();
361        let mut rule = NewlineRule::default();
362        for frame in &frames {
363            if let Some(anchor) = frame.anchor.clone() {
364                let payload =
365                    MathTextPayload { command: None, anchor: Some(anchor), at_tag: false };
366                body.push(lw.pres_with(
367                    cx,
368                    &ElementName::from(pres::MATH_TEXT),
369                    payload,
370                    Vec::new(),
371                )?);
372            }
373            let trailing = stage_line_content(cx, lw, &frame.line.content, &mut rule, &mut body)?;
374            let content = stage_tag_content(cx, lw, frame)?;
375            let tag = stage_tag(cx, lw, content)?;
376            let closed = !tag.is_empty() || frame.line.linebreak.is_some();
377            body.extend(tag);
378            if let Some(brk) = &frame.line.linebreak {
379                body.push(copy_subtree_verbatim(cx, brk.node)?);
380            }
381            rule.line_end(closed, &trailing);
382            if !trailing.is_empty() {
383                body.push(lw.text(cx, &trailing)?);
384            }
385        }
386        let payload = formula_payload(MathDisplay::Display, Some(value.name.to_string()));
387        let math = lw.pres_with(cx, &ElementName::from(pres::MATH_PASSTHROUGH), payload, body)?;
388        Ok(Lowering::Emit(vec![math]))
389    }
390}
391
392/// The body of [`MATH_RULE`](super::MATH_RULE): it stages a `flm.pres.math-passthrough` node
393/// over the math group's nodes, displayed for `\[…\]` and inline for `\(…\)`.
394/// Every text command inside the group, at any depth, becomes a
395/// `flm.pres.math-text` node (see the module documentation).
396///
397/// The rule returns a [`LowerError`] when a node could not be staged or a text
398/// command could not be lowered.
399#[derive(Debug, Default, Clone, Copy)]
400pub struct MathRule;
401
402impl Lower for MathRule {
403    fn lower(
404        &self,
405        node: NodeRef<'_, Flm>,
406        cx: &mut LowerCx<'_>,
407        lw: &mut dyn Lowerer,
408    ) -> Result<Lowering, LowerError> {
409        let display =
410            if formula_display(&node) { MathDisplay::Display } else { MathDisplay::Inline };
411        let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
412        let body = stage_source(cx, lw, &children)?;
413        let payload = formula_payload(display, None);
414        let math = lw.pres_with(cx, &ElementName::from(pres::MATH_PASSTHROUGH), payload, body)?;
415        Ok(Lowering::Emit(vec![math]))
416    }
417}