Skip to main content

flm_core/stdlib/features/math/
unprocessed.rs

1//! The rule of last resort of the display-math environments: a display-math
2//! environment that no feature processing mathematics lowers is an Error.
3//!
4//! A display-math environment ([`ENVIRONMENT`], `flm.math.environment`) is
5//! lowered by the rules of the feature that processes mathematics (the
6//! module documentation of [`math`](super), *Processing mathematics*). Where
7//! no such feature has a rule for the environment on the backend at hand, in
8//! a registry without a processing feature for instance, [`RULE`] lowers it,
9//! as the `lowering` feature's rule of last resort
10//! ([`MathGroupRule`](crate::stdlib::backends::lowering::MathGroupRule))
11//! lowers a math group: it reports [`MathUnprocessed`]
12//! (`flm.math.unprocessed`, an Error) at the environment, and lowers the
13//! content of the environment's equation lines through the rules as ordinary
14//! content, inside a `flm.pres.span` of role `flm.math` and kind `display`. A
15//! character run is text, an unknown command its `flm.pres.unknown`, a text
16//! command its `flm.pres.math-text`. The `\\`, `\label`, `\tag` and
17//! `\nonumber` of the body are data of the lines ([`lines`](super::lines)) and
18//! are not written.
19//!
20//! The rule is registered on every backend and marked [`DefaultMark::Never`],
21//! so it is chosen on a backend only where it is the sole candidate for the
22//! environment: the rule of a processing feature applies wherever one is
23//! registered for the backend. With it, every backend renders every
24//! display-math environment, so the plan of a standard workflow builds for a
25//! registry that holds the `math` feature and no processing feature.
26
27use std::sync::Arc;
28
29use techy::core::node::NodeRef;
30use techy::error::Diagnostic;
31
32use crate::core::lowering::{
33    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
34};
35use crate::core::registry::{BuildError, FeatureBuilder};
36use crate::lang::Flm;
37use crate::lang::structural::FIELD;
38use crate::lang::structural::MATH;
39use crate::model::element::element_of;
40use crate::model::names::{ElementName, Name};
41use crate::stdlib::backends::lowering::rules::MATH_DISPLAY_KIND;
42use crate::stdlib::backends::lowering::MathUnprocessed;
43use crate::stdlib::backends::pres::{self, SpanPayload};
44
45use super::ENVIRONMENT;
46
47/// The name of the rule of last resort of [`ENVIRONMENT`] on every backend,
48/// `flm.math.environment.lower.default`, whose body is
49/// [`UnprocessedEnvironmentRule`].
50pub const RULE: &str = "flm.math.environment.lower.default";
51
52/// The body of [`RULE`]: it reports [`MathUnprocessed`]
53/// (`flm.math.unprocessed`, an Error) at the environment's span, and stages a
54/// `flm.pres.span` of role `flm.math` and kind `display` over the content of
55/// the environment's equation lines, lowered
56/// through the rules as ordinary content. The fields of the body (`\\`,
57/// `\label`, `\tag`, `\nonumber`) are not lowered. See the module
58/// documentation.
59///
60/// It returns a [`LowerError`] when a node of the content could not be
61/// lowered or a node could not be staged.
62#[derive(Debug, Default, Clone, Copy)]
63pub struct UnprocessedEnvironmentRule;
64
65impl Lower for UnprocessedEnvironmentRule {
66    fn lower(
67        &self,
68        node: NodeRef<'_, Flm>,
69        cx: &mut LowerCx<'_>,
70        lw: &mut dyn Lowerer,
71    ) -> Result<Lowering, LowerError> {
72        lw.diagnose(Diagnostic::error(MathUnprocessed, node.span().clone()));
73        let mut content = Vec::new();
74        if let Some(body) = node.body() {
75            let start = body.range().start;
76            for (index, child) in (0u32..).zip(body.iter()) {
77                if element_of(&child).name == FIELD {
78                    continue;
79                }
80                let one = node
81                    .tree()
82                    .slice(start + index..start + index + 1)
83                    .ok_or_else(|| LowerError::structure("a child outside its parent's body"))?;
84                content.extend(lw.lower_nodes(cx, one)?);
85            }
86        }
87        let payload = SpanPayload {
88            role: Some(Name::from(MATH)),
89            kinds: vec![Name::from(MATH_DISPLAY_KIND)],
90            ..SpanPayload::default()
91        };
92        let span = lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, content)?;
93        Ok(Lowering::Emit(vec![span]))
94    }
95}
96
97/// The rule [`RULE`]: [`UnprocessedEnvironmentRule`] for [`ENVIRONMENT`] on
98/// every backend, never a default.
99fn rule() -> LoweringRule {
100    LoweringRule::new(
101        RULE,
102        ENVIRONMENT,
103        LoweringDecl::new().produces(pres::SPAN),
104        Arc::new(UnprocessedEnvironmentRule),
105        // The rule of last resort: never a default, so that the rule of a
106        // feature that processes mathematics applies wherever one is
107        // registered for the backend.
108        DefaultMark::Never,
109    )
110    .docs(
111        "a display-math environment that no feature processes is an Error, and lowers to a \
112         `flm.pres.span` of role `flm.math` over the content of its equation lines lowered as \
113         ordinary content",
114    )
115}
116
117/// Registers [`RULE`], as part of the `math` feature.
118///
119/// # Errors
120///
121/// Returns the [`BuildError`] the feature builder raises, for instance for a
122/// rule already registered under the same name.
123pub(super) fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
124    b.lowering_rule(rule())?;
125    Ok(())
126}
127