Skip to main content

flm_core/stdlib/backends/lowering/
rules.rs

1//! The default lowering rules of the structural elements, and the helpers
2//! other rules use to stage paragraphs and trimmed inline content.
3//!
4//! The **structural elements** are the elements of the node shapes no
5//! feature declares: text, comments, containers, groups of each class,
6//! paragraphs, paragraph breaks, template placeholders, fields, and the macros and
7//! environments a parse could not attribute to any feature
8//! ([`StructuralElements`](crate::lang::structural::StructuralElements); see
9//! [structural elements](crate::guide::concepts_overview#structural-elements)).
10//! Most structural elements need no rule: `flm.text`, `flm.group`,
11//! `flm.opaque-wrapper`, `flm.comment`, `flm.container` and `flm.parbreak` are
12//! elements a backend writes natively, so nothing lowers them; the `text`
13//! backend of this crate writes all six natively
14//! ([`FLOW_THROUGH`](crate::stdlib::backends::text::FLOW_THROUGH)). An
15//! opaque wrapper has no delimiters, so a backend writes it through its
16//! children, and its text comes out as typed. The
17//! paragraph-break element is among them because it remains after block
18//! structuring inside opaque math content. The six rules of this module cover
19//! the elements that do need a rule, and [`default_rules`] is the list the
20//! `lowering` feature registers:
21//!
22//! | element | lowers to | rule |
23//! |---|---|---|
24//! | `flm.paragraph` | `flm.pres.par` | [`ParagraphRule`] |
25//! | `flm.math` | `flm.pres.span` of role `flm.math`, and an Error | [`MathGroupRule`] |
26//! | `flm.verbatim` | `flm.pres.verbatim` | [`VerbatimRule`] |
27//! | `flm.unknown.macro` | `flm.pres.unknown` | [`UnknownMacroRule`] |
28//! | `flm.unknown.environment` | `flm.pres.unknown` | [`UnknownEnvironmentRule`] |
29//! | `flm.field` | nothing, and an Error | [`FieldRule`] |
30//!
31//! Each is registered as the default rule for its element on every backend
32//! ([`DefaultMark::Everywhere`]), except the rule of `flm.math`, which is never
33//! a default ([`DefaultMark::Never`]): it is chosen only where no feature that
34//! processes mathematics has a rule for `flm.math` on the backend at hand. A backend uses it unless the plan request
35//! prefers another rule by name, the backend writes the element natively, or
36//! another rule is marked as the default on that backend
37//! ([`DefaultMark::OnBackends`]); see the rule selection order at
38//! [`SelectedRules`](crate::core::plan::SelectedRules).
39//!
40//! # What the default rules do and require
41//!
42//! **The paragraph rule requires the capability `flm.blocks.structured`**
43//! ([`BLOCKS_STRUCTURED`]). A paragraph group exists only in a tree the
44//! block-structure rewrite has processed, and a rule states what must have
45//! happened before it runs by requiring a capability. Since this rule is
46//! selected for every backend that does not write `flm.paragraph` natively,
47//! every such plan structures its trees.
48//!
49//! **Verbatim content is copied unchanged.** It is an [opaque
50//! region](crate::guide::concepts_overview#opaque-regions): nothing inside it
51//! is lowered, and the nodes are copied unchanged into the presentation
52//! node's body ([`super::copy_run_verbatim`]). Verbatim content is first read
53//! as characters, as every rule that stages verbatim content reads it
54//! ([`super::stage_verbatim_content`]): content that a template substituted
55//! there and that is not characters is reported as
56//! [`ContentNotCharacters`](super::ContentNotCharacters) at the command or
57//! environment owning the group, and shown as its source text.
58//!
59//! **A math group is an Error until a feature processes mathematics.** The
60//! math groups and the display-math environments are lowered by the rules of
61//! the feature that processes mathematics (for example the feature of the
62//! package [`math_passthrough`](crate::math_passthrough)). Where no
63//! such feature has a rule for `flm.math` on the backend at hand, the rule of
64//! last resort [`MathGroupRule`] reports
65//! [`MathUnprocessed`] (`flm.math.unprocessed`) at the
66//! group and lowers the group's content through the rules as ordinary content,
67//! inside a `flm.pres.span` of role `flm.math` and kind `inline` or `display`.
68//! The `math` feature's own rule of last resort does the same for a
69//! display-math environment
70//! ([`unprocessed`](crate::stdlib::features::math::unprocessed)).
71//!
72//! **A verbatim group's display and kind are inferred.** Its display is
73//! `Block` when the group is the body of a block-role element declared with a
74//! verbatim body and `Inline` otherwise; its verbatim kind is `text`, the kind
75//! that applies no formatting of its own, because a bare group states no
76//! kind. An element that needs another kind, another display or a language
77//! tag builds the payload in its own rule from the group's children, as the
78//! two rules of the `verbatim` feature do.
79//!
80//! **An unattributed macro or environment is lowered as content, not as an
81//! error mark.** `flm.unknown.macro` and `flm.unknown.environment` are the
82//! elements the parse gives a macro or an environment no feature declares.
83//! They lower to `flm.pres.unknown` carrying the kind, the name and the
84//! source text of the invocation, so a backend writes what the author wrote.
85//! The run's diagnostics report the mistake; the output itself says nothing
86//! about it.
87//!
88//! **A field reaching a backend is an error.** A *field* is a macro that a
89//! construct absorbs as data rather than as content, such as the `\label`
90//! written after a heading or the `\tag` on an equation line (see [fields:
91//! data a construct
92//! reads](crate::guide::concepts_overview#fields-data-a-construct-reads)),
93//! and every field node carries the element [`FIELD`]. The construct that
94//! declared a field reads it, and nothing is written for the field itself,
95//! so a field node that reaches the lowering means that construct did not
96//! read its data. [`FieldRule`] writes nothing for it and reports
97//! [`FieldNotRead`] at the node, on every backend. The rule also makes every
98//! plan complete for the element: a document may contain a field, so every
99//! backend needs a lowering for it.
100//!
101//! **A mandatory argument that the parse left absent after a parse error is
102//! not a second mistake.** The node lowers to the content that does exist (an
103//! empty span, a heading with an empty title), and the parse's own diagnostic
104//! remains the only report: no `flm.lowering.rule-failed`, no
105//! `flm.pres.unsupported` stand-in. [`lower_arg_or_nothing`] and
106//! [`lower_arg_named_or_nothing`] behave this way, and a rule lowering a
107//! mandatory argument should call them rather than the strict
108//! [`Lowerer::lower_arg`] and [`Lowerer::lower_arg_named`], which fail on an
109//! absent argument. None of the rules of this module lowers an argument.
110
111use std::sync::Arc;
112
113use techy::core::node::{BuildId, NodeRef};
114use techy::error::Diagnostic;
115use techy::latexlike::{InvocationSyntaxData, MathGroupForm};
116
117use crate::model::aspects::{BlockRole, block_role_of};
118use crate::core::lowering::{
119    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
120};
121use crate::model::names::{ElementName, Name};
122use crate::lang::mint::field_name;
123use crate::lang::structural::{FIELD, MATH, PARAGRAPH, UNKNOWN_ENVIRONMENT, UNKNOWN_MACRO, VERBATIM};
124use crate::lang::text::is_space;
125use crate::lang::{Flm, FlmGroupType};
126use crate::stdlib::backends::pres::{
127    self, ParPayload, SpanPayload, UnknownKind, UnknownPayload, VerbatimDisplay, VerbatimKind,
128    VerbatimPayload,
129};
130
131use super::driver::{lower_run, stage_verbatim_content};
132use super::error::{FieldNotRead, MathUnprocessed};
133
134/// The registered name of the paragraph rule, [`ParagraphRule`].
135pub const PARAGRAPH_RULE: &str = "flm.paragraph.lower.default";
136/// The registered name of the rule of last resort of the math groups,
137/// `flm.math.lower.default` ([`MathGroupRule`]).
138pub const MATH_RULE: &str = "flm.math.lower.default";
139/// The registered name of the verbatim rule, [`VerbatimRule`].
140pub const VERBATIM_RULE: &str = "flm.verbatim.lower.default";
141/// The registered name of the unattributed-macro rule, [`UnknownMacroRule`].
142pub const UNKNOWN_MACRO_RULE: &str = "flm.unknown.macro.lower.default";
143/// The registered name of the unattributed-environment rule,
144/// [`UnknownEnvironmentRule`].
145pub const UNKNOWN_ENVIRONMENT_RULE: &str = "flm.unknown.environment.lower.default";
146/// The registered name of the field rule, [`FieldRule`].
147pub const FIELD_RULE: &str = "flm.field.lower.default";
148
149/// The capability [`ParagraphRule`] requires: the table of trees the
150/// block-structure rewrite writes, declared by the `blocks` feature. Because
151/// the rule requires it, every plan whose backend lowers paragraphs includes
152/// that rewrite.
153pub const BLOCKS_STRUCTURED: &str = "flm.blocks.structured";
154
155/// Lowers the content of the argument at `index` (in invocation order) of
156/// `node`, or produces nothing when the parse left that argument absent after
157/// a parse error.
158///
159/// A rule should use this function for a mandatory argument: the parse has
160/// already reported a missing argument, and lowering reports nothing more
161/// about it (see the module documentation). Use [`Lowerer::lower_arg`]
162/// instead when an absent argument really is a failure of the rule.
163///
164/// # Errors
165///
166/// Returns any error that lowering the argument's content returns: a [`LowerError`]
167/// from a rule that ran inside it, or a staging failure.
168pub fn lower_arg_or_nothing(
169    cx: &mut LowerCx<'_>,
170    lw: &mut dyn Lowerer,
171    node: &NodeRef<'_, Flm>,
172    index: usize,
173) -> Result<Vec<BuildId>, LowerError> {
174    if node.argument_content_nodes(index).is_none() {
175        return Ok(Vec::new());
176    }
177    lw.lower_arg(cx, node, index)
178}
179
180/// [`lower_arg_or_nothing`] for the argument named `name` instead of one at a
181/// position.
182///
183/// # Errors
184///
185/// As [`lower_arg_or_nothing`], and additionally: a `name` the node's element
186/// does not declare is a failure of the rule, returned by
187/// [`Lowerer::lower_arg_named`], not treated as an absent argument.
188pub fn lower_arg_named_or_nothing(
189    cx: &mut LowerCx<'_>,
190    lw: &mut dyn Lowerer,
191    node: &NodeRef<'_, Flm>,
192    name: &str,
193) -> Result<Vec<BuildId>, LowerError> {
194    if let Ok(None) = node.argument_content_nodes_named(name) {
195        return Ok(Vec::new());
196    }
197    lw.lower_arg_named(cx, node, name)
198}
199
200/// Lowers `flm.field` to nothing and reports [`FieldNotRead`]: a field that
201/// reaches a backend on its own is a fault of the construct that absorbed it.
202///
203/// See the module documentation, *A field reaching a backend is an error*.
204///
205/// # Errors
206///
207/// Returns [`LowerError`] for a node of the field element that is not a
208/// macro node, and so has no field name. Every field node is a macro node
209/// named as the field is written, so only a caller that builds another node
210/// of the field element can cause this; nothing in this crate does.
211#[derive(Debug, Default)]
212pub struct FieldRule;
213
214impl Lower for FieldRule {
215    fn lower(
216        &self,
217        node: NodeRef<'_, Flm>,
218        _cx: &mut LowerCx<'_>,
219        lw: &mut dyn Lowerer,
220    ) -> Result<Lowering, LowerError> {
221        let field = field_name(&node)
222            .ok_or_else(|| {
223                LowerError::structure("a field node must be a macro node")
224            })?;
225        let condition =
226            FieldNotRead { backend: lw.backend().to_string(), field: field.to_string() };
227        lw.diagnose(Diagnostic::error(condition, node.span().clone()));
228        Ok(Lowering::Emit(Vec::new()))
229    }
230}
231
232/// Stages one `flm.pres.par` holding `leading`, then the inline content of
233/// the paragraph `node` lowered through the rules, then `trailing`, and
234/// returns it.
235///
236/// Every paragraph of this crate is staged through this function.
237/// [`ParagraphRule`] calls it with nothing at either edge; a rule that
238/// writes a paragraph of the document with something added at its start or
239/// its end (the bracket and the mark of an xnote shown in place, the link
240/// back from an entry of a list of xnotes) calls it with the nodes to add,
241/// which it staged and placed nowhere else. `node` is a paragraph the
242/// block-structure pass built (`flm.paragraph`), or `None` for a paragraph
243/// that holds no content of the document, only `leading` then `trailing`.
244///
245/// The [`Lowerer`] moves any decoration in the paragraph into an attached
246/// slot and leaves a `flm.pres.deco-mark` at its former position. The
247/// paragraph is staged by the calling rule, at that rule's node: a rule that
248/// replaces [`ParagraphRule`] is not used for it.
249///
250/// The calling rule must declare that it produces `flm.pres.par`.
251///
252/// # Errors
253///
254/// [`LowerError`] from the lowering of the paragraph's run, and when the
255/// calling rule did not declare that it produces `flm.pres.par` or the node
256/// could not be staged.
257// A staged node cannot be changed afterwards, so a rule adding nodes at a
258// paragraph's edges cannot let the paragraph rule stage the paragraph and then
259// add to it; one function keeps one way of staging a paragraph.
260pub fn lower_paragraph(
261    cx: &mut LowerCx<'_>,
262    lw: &mut dyn Lowerer,
263    node: Option<&NodeRef<'_, Flm>>,
264    leading: Vec<BuildId>,
265    trailing: Vec<BuildId>,
266) -> Result<BuildId, LowerError> {
267    let mut body = leading;
268    if let Some(node) = node {
269        body.extend(lw.lower_children(cx, node)?);
270    }
271    body.extend(trailing);
272    lw.pres_with(cx, &ElementName::from(pres::PAR), ParPayload::default(), body)
273}
274
275/// Lowers `content` (a run of sibling nodes holding paragraphs and blocks,
276/// or inline content) as blocks, with `leading` at the start of the first
277/// paragraph's inline content and `trailing` at the end of the last one, and
278/// returns the blocks.
279///
280/// A rule uses this function to place something before the first words, or
281/// after the last words, of content that may hold paragraphs: the opening
282/// and the closing bracket of an xnote shown in place, the link back from an
283/// entry of a list of xnotes to its mark, the lead-in of a term definition,
284/// the heading and the closing mark of a theorem.
285/// `leading` and `trailing` hold nodes the caller staged and placed nowhere
286/// else; either may be empty.
287///
288/// - Inline content (no paragraph and no block among the nodes) becomes one
289///   `flm.pres.par` holding `leading`, the content lowered through the rules,
290///   then `trailing`.
291/// - Content holding blocks is lowered block by block: each paragraph becomes
292///   a `flm.pres.par` of its inline content lowered through the rules, with
293///   `leading` at the start of the first one and `trailing` at the end of the
294///   last one; every other block is lowered by the rules. Content whose first
295///   block is not a paragraph (a list, for example) gets one more
296///   `flm.pres.par` before it, holding `leading` alone, and content whose
297///   last block is not a paragraph one more after it, holding `trailing`
298///   alone. Comments at either end are skipped when the first and the last
299///   block are found.
300/// - Empty content with something to place is treated as inline content
301///   too: one `flm.pres.par` holding `leading` then `trailing`, so a theorem
302///   with an empty body shows its heading and its closing mark in one
303///   paragraph. Empty content with nothing to place gives nothing.
304///
305/// Every paragraph is staged through [`lower_paragraph`], by the calling
306/// rule: a rule that replaces the paragraph rule is not used for these
307/// paragraphs. The calling rule must declare that it produces
308/// `flm.pres.par`.
309///
310/// # Errors
311///
312/// [`LowerError`] when `content` is not a run of siblings of the tree being
313/// lowered, and from the lowering of the content and the staging of the
314/// paragraphs.
315pub fn lower_blocks_with_edges(
316    cx: &mut LowerCx<'_>,
317    lw: &mut dyn Lowerer,
318    content: &[NodeRef<'_, Flm>],
319    leading: Vec<BuildId>,
320    trailing: Vec<BuildId>,
321) -> Result<Vec<BuildId>, LowerError> {
322    let is_paragraph = |node: &NodeRef<'_, Flm>| node.group_type() == Some(FlmGroupType::Paragraph);
323    let is_block = |node: &NodeRef<'_, Flm>| {
324        is_paragraph(node) || matches!(block_role_of(node), BlockRole::Block)
325    };
326    if !content.iter().any(is_block) {
327        let run = lower_run(cx, lw, content)?;
328        if run.is_empty() && leading.is_empty() && trailing.is_empty() {
329            return Ok(Vec::new());
330        }
331        return Ok(vec![lower_paragraph(cx, lw, None, [leading, run].concat(), trailing)?]);
332    }
333    // The edge nodes are inline, and a paragraph is the one block holding
334    // inline content, hence one more paragraph where another block stands first
335    // or last.
336    let first = content.iter().position(|node| !node.is_comment());
337    let last = content.iter().rposition(|node| !node.is_comment());
338    let into_first = first.is_some_and(|at| is_paragraph(&content[at]));
339    let into_last = last.is_some_and(|at| is_paragraph(&content[at]));
340    let mut leading = Some(leading);
341    let mut trailing = Some(trailing);
342    let mut out = Vec::new();
343    if !into_first {
344        let leading = leading.take().unwrap_or_default();
345        if !leading.is_empty() {
346            out.push(lower_paragraph(cx, lw, None, leading, Vec::new())?);
347        }
348    }
349    for (at, node) in content.iter().enumerate() {
350        if !is_paragraph(node) {
351            out.extend(lower_run(cx, lw, std::slice::from_ref(node))?);
352            continue;
353        }
354        let head = if into_first && Some(at) == first { leading.take() } else { None };
355        let tail = if into_last && Some(at) == last { trailing.take() } else { None };
356        let (head, tail) = (head.unwrap_or_default(), tail.unwrap_or_default());
357        out.push(lower_paragraph(cx, lw, Some(node), head, tail)?);
358    }
359    let trailing = trailing.take().unwrap_or_default();
360    if !trailing.is_empty() {
361        out.push(lower_paragraph(cx, lw, None, Vec::new(), trailing)?);
362    }
363    Ok(out)
364}
365
366/// Stages `content`, a run of inline content, with the whitespace at both of
367/// its ends trimmed, and returns the staged nodes. The whitespace and the
368/// comments before its first content and after its last are left out, and
369/// the text at either edge is staged without its leading or its trailing
370/// whitespace. Everything between the two edges is lowered through the rules
371/// unchanged. Content holding only whitespace and comments stages nothing.
372///
373/// A rule uses this function to write a paragraph over inline content whose
374/// edges the block-structure pass did not trim, because the rule cuts that
375/// content out of a longer run itself: the `quote` feature's passage,
376/// attribution and lines, and an entry of the `cells` feature's
377/// `\celldata`, each written without the spaces around it. Whitespace here
378/// is what [`is_blank`] counts as blank: the space, the tab, the carriage
379/// return and the line feed, and the nodes that are whitespace, such as `~`
380/// and `\ ` ([`Whitespace`](crate::model::aspects::Whitespace)), the same
381/// whitespace the block-structure pass removes at a paragraph's edges. The
382/// character U+00A0 typed in text is content.
383///
384/// `passed_over` selects further nodes that are not content (commands that
385/// write nothing, which the calling rule reads in place, such as the `\\`
386/// and the `\indent` of a quotation's lines section); they are left out at
387/// the edges as whitespace is. A caller with none passes `|_| false`.
388///
389/// # Errors
390///
391/// [`LowerError`] from the lowering of the content and the staging of the
392/// trimmed text.
393pub fn stage_trimmed(
394    cx: &mut LowerCx<'_>,
395    lw: &mut dyn Lowerer,
396    content: &[NodeRef<'_, Flm>],
397    passed_over: impl Fn(&NodeRef<'_, Flm>) -> bool,
398) -> Result<Vec<BuildId>, LowerError> {
399    stage_trimmed_runs(cx, lw, &[content], passed_over)
400}
401
402/// [`stage_trimmed`] over several runs of siblings read as one run of
403/// content, the edges being those of the whole. The `quote` feature uses it
404/// for the lines of a quotation's lines section, which are cut into runs at
405/// each `\indent`.
406///
407/// # Errors
408///
409/// As [`stage_trimmed`].
410// A trimmed edge is staged as a text node of its own: the block-structuring
411// pass trims a paragraph's edges while it builds the paragraph, over text it
412// is resolving, and nothing of it can be called on a structured tree at
413// lowering, so the edge's trimmed text is staged through the façade.
414pub fn stage_trimmed_runs(
415    cx: &mut LowerCx<'_>,
416    lw: &mut dyn Lowerer,
417    runs: &[&[NodeRef<'_, Flm>]],
418    passed_over: impl Fn(&NodeRef<'_, Flm>) -> bool,
419) -> Result<Vec<BuildId>, LowerError> {
420    let is_content =
421        |node: &NodeRef<'_, Flm>| !(node.is_comment() || is_blank(node) || passed_over(node));
422    let nodes: Vec<(usize, usize)> = runs
423        .iter()
424        .enumerate()
425        .flat_map(|(run, nodes)| (0..nodes.len()).map(move |at| (run, at)))
426        .collect();
427    let node_at = |(run, at): (usize, usize)| runs[run][at];
428    let Some(first) = nodes.iter().position(|&place| is_content(&node_at(place))) else {
429        return Ok(Vec::new());
430    };
431    let last = nodes.iter().rposition(|&place| is_content(&node_at(place))).unwrap_or(first);
432    let mut out = Vec::new();
433    // The nodes from `first` to `last`, each run's share lowered as one run;
434    // the two edge nodes, when they are text, staged trimmed.
435    let mut pending: Option<(usize, usize, usize)> = None;
436    for (index, &(run, at)) in nodes.iter().enumerate().take(last + 1).skip(first) {
437        let node = runs[run][at];
438        let trimmed = (index == first || index == last)
439            .then(|| node.chars())
440            .flatten()
441            .map(|text| {
442                let text = if index == first { text.trim_start_matches(is_space) } else { text };
443                if index == last { text.trim_end_matches(is_space) } else { text }
444            })
445            .filter(|trimmed| Some(*trimmed) != node.chars());
446        match trimmed {
447            Some(text) => {
448                if let Some((run, from, to)) = pending.take() {
449                    out.extend(lower_run(cx, lw, &runs[run][from..to])?);
450                }
451                out.push(lw.text(cx, text)?);
452            }
453            None => {
454                pending = match pending {
455                    Some((pending_run, from, to)) if pending_run == run && to == at => {
456                        Some((run, from, at + 1))
457                    }
458                    Some((pending_run, from, to)) => {
459                        out.extend(lower_run(cx, lw, &runs[pending_run][from..to])?);
460                        Some((run, at, at + 1))
461                    }
462                    None => Some((run, at, at + 1)),
463                };
464            }
465        }
466    }
467    if let Some((run, from, to)) = pending {
468        out.extend(lower_run(cx, lw, &runs[run][from..to])?);
469    }
470    Ok(out)
471}
472
473/// Whether `node` is blank: a node that is whitespace, such as `~` and `\ `
474/// (its element carries the aspect
475/// [`Whitespace`](crate::model::aspects::Whitespace)), or text made of
476/// whitespace alone: the space, the tab, the carriage return and the line
477/// feed. Text holding the character U+00A0 is not blank. [`stage_trimmed`]
478/// leaves blank nodes out at the edges of a run.
479///
480/// This is the one blank test of every reader of FLM content (see [the
481/// whitespace of FLM text](crate::lang::text#whitespace)): the
482/// block-structure pass and the features' readers make the same test.
483pub fn is_blank(node: &NodeRef<'_, Flm>) -> bool {
484    crate::lang::text::is_blank(node)
485}
486
487/// Lowers `flm.paragraph` to a `flm.pres.par` holding the paragraph's
488/// lowered inline content, through [`lower_paragraph`].
489///
490/// The [`Lowerer`] moves any decoration in that content into an attached slot
491/// and leaves a `flm.pres.deco-mark` at its former position.
492#[derive(Debug, Default)]
493pub struct ParagraphRule;
494
495impl Lower for ParagraphRule {
496    fn lower(
497        &self,
498        node: NodeRef<'_, Flm>,
499        cx: &mut LowerCx<'_>,
500        lw: &mut dyn Lowerer,
501    ) -> Result<Lowering, LowerError> {
502        let par = lower_paragraph(cx, lw, Some(&node), Vec::new(), Vec::new())?;
503        Ok(Lowering::Emit(vec![par]))
504    }
505}
506
507/// The rule of last resort of the math groups: it reports
508/// [`MathUnprocessed`] (`flm.math.unprocessed`, an Error) at the group's span,
509/// and lowers the group's content through the rules as ordinary content,
510/// inside a `flm.pres.span` of role `flm.math` ([`MATH`]) and kind `inline`
511/// or `display` (see the module documentation, *A math group is an Error
512/// until a feature processes mathematics*).
513///
514/// It is marked [`DefaultMark::Never`], so it is chosen on a backend only
515/// where it is the sole candidate for `flm.math`: in a registry without a
516/// feature that processes mathematics, or whose processing feature has no
517/// rule for `flm.math` on that backend. The content is lowered as the rules
518/// lower it anywhere: a character run is text, a comment a comment, an
519/// unknown command its `flm.pres.unknown`, a text command its
520/// `flm.pres.math-text`.
521///
522/// # Errors
523///
524/// Returns [`LowerError`] when a child could not be lowered or the span could
525/// not be staged.
526#[derive(Debug, Default)]
527pub struct MathGroupRule;
528
529impl Lower for MathGroupRule {
530    fn lower(
531        &self,
532        node: NodeRef<'_, Flm>,
533        cx: &mut LowerCx<'_>,
534        lw: &mut dyn Lowerer,
535    ) -> Result<Lowering, LowerError> {
536        lw.diagnose(Diagnostic::error(MathUnprocessed, node.span().clone()));
537        let kind = match node.group_type() {
538            Some(FlmGroupType::Math(MathGroupForm::Display)) => MATH_DISPLAY_KIND,
539            _ => MATH_INLINE_KIND,
540        };
541        let content = lw.lower_children(cx, &node)?;
542        let payload = SpanPayload {
543            role: Some(Name::from(MATH)),
544            kinds: vec![Name::from(kind)],
545            ..SpanPayload::default()
546        };
547        let span = lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, content)?;
548        Ok(Lowering::Emit(vec![span]))
549    }
550}
551
552/// The kind of the span [`MathGroupRule`] stages for an inline math group
553/// (`\(…\)`, `$…$`), `inline`.
554pub const MATH_INLINE_KIND: &str = "inline";
555
556/// The kind of the span [`MathGroupRule`] stages for a displayed math group
557/// (`\[…\]`, `$$…$$`), `display`.
558pub const MATH_DISPLAY_KIND: &str = "display";
559
560/// Lowers `flm.verbatim` to `flm.pres.verbatim`, copying the group's content
561/// unchanged once it is read as characters ([`stage_verbatim_content`];
562/// content that is not characters is reported at the command or environment
563/// owning the group, and shown as its source text).
564///
565/// The display is `Block` when the group is the body of a block-role element
566/// declared with a verbatim body, and `Inline` otherwise. The verbatim kind
567/// is always `text`, the kind that applies no formatting of its own, because
568/// a bare verbatim group states no kind (see the module documentation).
569#[derive(Debug, Default)]
570pub struct VerbatimRule;
571
572/// The callable whose argument or body directly holds `node` (a verbatim
573/// group, a quote environment's section command), when there is one. An
574/// opaque wrapper over the argument or the body
575/// ([`FlmGroupType::OpaqueWrapper`]) is looked through.
576pub(crate) fn owning_callable<'t>(node: &NodeRef<'t, Flm>) -> Option<NodeRef<'t, Flm>> {
577    // The body slot's content nodes are the callable's own children; a
578    // transparent container in between (a hook's) is looked through. An
579    // opaque wrapper stands over an argument's nodes, or over the body's
580    // container under a container of its own.
581    let parent_past_list = |node: &NodeRef<'t, Flm>| {
582        let parent = node.parent()?;
583        if parent.is_list() { parent.parent() } else { Some(parent) }
584    };
585    let mut owner = parent_past_list(node)?;
586    if owner.group_type() == Some(FlmGroupType::OpaqueWrapper) {
587        owner = parent_past_list(&owner)?;
588    }
589    owner.is_callable().then_some(owner)
590}
591
592/// Whether the verbatim group is the body of a block-role element: the group
593/// is one of the content nodes of the owning callable's body slot (the body
594/// of an environment declared with a verbatim body), and the callable's block
595/// role is `Block`.
596fn is_block_verbatim(node: &NodeRef<'_, Flm>) -> bool {
597    owning_callable(node).is_some_and(|owner| {
598        block_role_of(&owner) == BlockRole::Block
599            && owner.body().is_some_and(|body| body.iter().any(|child| child.id() == node.id()))
600    })
601}
602
603impl Lower for VerbatimRule {
604    fn lower(
605        &self,
606        node: NodeRef<'_, Flm>,
607        cx: &mut LowerCx<'_>,
608        lw: &mut dyn Lowerer,
609    ) -> Result<Lowering, LowerError> {
610        let display =
611            if is_block_verbatim(&node) { VerbatimDisplay::Block } else { VerbatimDisplay::Inline };
612        let owner = owning_callable(&node).unwrap_or(node);
613        let body = stage_verbatim_content(&owner, node.children(), cx, lw)?;
614        let payload = VerbatimPayload { kind: VerbatimKind::Text, display, lang: None };
615        let verbatim = lw.pres_with(cx, &ElementName::from(pres::VERBATIM), payload, body)?;
616        Ok(Lowering::Emit(vec![verbatim]))
617    }
618}
619
620/// The name of an unattributed callable as written, and the escape character
621/// that introduced it when the node records one (a macro).
622fn spelling_of(node: &NodeRef<'_, Flm>) -> (String, Option<char>) {
623    let name = node.name().unwrap_or_default().to_string();
624    let escape = match node.invocation_syntax() {
625        Some(InvocationSyntaxData::Macro { escape_char, .. }) => Some(*escape_char),
626        _ => None,
627    };
628    (name, escape)
629}
630
631/// Lowers `flm.unknown.macro` (a macro no feature declares) to a childless
632/// `flm.pres.unknown` carrying its source text, `\name`.
633#[derive(Debug, Default)]
634pub struct UnknownMacroRule;
635
636impl Lower for UnknownMacroRule {
637    fn lower(
638        &self,
639        node: NodeRef<'_, Flm>,
640        cx: &mut LowerCx<'_>,
641        lw: &mut dyn Lowerer,
642    ) -> Result<Lowering, LowerError> {
643        let (name, escape) = spelling_of(&node);
644        let payload = UnknownPayload {
645            kind: UnknownKind::Macro,
646            spelling: format!("{}{name}", escape.unwrap_or('\\')),
647            name,
648        };
649        let unknown =
650            lw.pres_with(cx, &ElementName::from(pres::UNKNOWN), payload, Vec::new())?;
651        Ok(Lowering::Emit(vec![unknown]))
652    }
653}
654
655/// Lowers `flm.unknown.environment` (an environment no feature declares) to
656/// a `flm.pres.unknown` holding its lowered body.
657///
658/// The payload's `spelling` is the bare environment name; each backend
659/// writes its own `\begin` and `\end` around the body.
660#[derive(Debug, Default)]
661pub struct UnknownEnvironmentRule;
662
663impl Lower for UnknownEnvironmentRule {
664    fn lower(
665        &self,
666        node: NodeRef<'_, Flm>,
667        cx: &mut LowerCx<'_>,
668        lw: &mut dyn Lowerer,
669    ) -> Result<Lowering, LowerError> {
670        let (name, _) = spelling_of(&node);
671        let body = lw.lower_body(cx, &node)?;
672        let payload = UnknownPayload {
673            kind: UnknownKind::Environment,
674            spelling: name.clone(),
675            name,
676        };
677        let unknown = lw.pres_with(cx, &ElementName::from(pres::UNKNOWN), payload, body)?;
678        Ok(Lowering::Emit(vec![unknown]))
679    }
680}
681
682/// The six default rules of this module, one per structural element that
683/// needs a rule, as values a feature can register; the `lowering` feature
684/// registers them.
685///
686/// # Examples
687///
688/// ```
689/// use flm_core::stdlib::backends::lowering::{PARAGRAPH_RULE, default_rules};
690///
691/// let names: Vec<String> =
692///     default_rules().iter().map(|rule| rule.name.to_string()).collect();
693/// assert_eq!(names.len(), 6);
694/// assert!(names.contains(&PARAGRAPH_RULE.to_string()));
695/// ```
696pub fn default_rules() -> Vec<LoweringRule> {
697    vec![
698        LoweringRule::new(
699            FIELD_RULE,
700            FIELD,
701            LoweringDecl::new(),
702            Arc::new(FieldRule),
703            DefaultMark::Everywhere,
704        )
705        .docs(
706            "a field that reaches a backend on its own is an error: the construct it was \
707             written after did not read its data",
708        ),
709        LoweringRule::new(
710            PARAGRAPH_RULE,
711            PARAGRAPH,
712            LoweringDecl::new().requires(BLOCKS_STRUCTURED).produces(pres::PAR),
713            Arc::new(ParagraphRule),
714            DefaultMark::Everywhere,
715        )
716        .docs("a paragraph group lowers to `flm.pres.par` over its lowered inline run"),
717        LoweringRule::new(
718            MATH_RULE,
719            MATH,
720            LoweringDecl::new().produces(pres::SPAN),
721            Arc::new(MathGroupRule),
722            // The rule of last resort: never a default, so that the rule of a
723            // feature that processes mathematics applies wherever one is
724            // registered for the backend.
725            DefaultMark::Never,
726        )
727        .docs(
728            "a math group that no feature processes is an Error, and lowers to a \
729             `flm.pres.span` of role `flm.math` over its content lowered as ordinary content",
730        ),
731        LoweringRule::new(
732            VERBATIM_RULE,
733            VERBATIM,
734            LoweringDecl::new().produces(pres::VERBATIM),
735            Arc::new(VerbatimRule),
736            DefaultMark::Everywhere,
737        )
738        .docs("a verbatim group lowers to `flm.pres.verbatim` over its content, verbatim"),
739        LoweringRule::new(
740            UNKNOWN_MACRO_RULE,
741            UNKNOWN_MACRO,
742            LoweringDecl::new().produces(pres::UNKNOWN),
743            Arc::new(UnknownMacroRule),
744            DefaultMark::Everywhere,
745        )
746        .docs("an unattributed macro lowers to a childless `flm.pres.unknown` of its spelling"),
747        LoweringRule::new(
748            UNKNOWN_ENVIRONMENT_RULE,
749            UNKNOWN_ENVIRONMENT,
750            LoweringDecl::new().produces(pres::UNKNOWN),
751            Arc::new(UnknownEnvironmentRule),
752            DefaultMark::Everywhere,
753        )
754        .docs("an unattributed environment lowers to `flm.pres.unknown` over its lowered body"),
755    ]
756}