flm_core/stdlib/features/math/ensuremath.rs
1//! `\ensuremath{…}`: mathematics wherever it is written.
2//!
3//! LaTeX's `\ensuremath{X}` typesets `X` as mathematics: in text it is an
4//! inline formula, and inside a formula it is `X` itself. The `math` feature
5//! declares the command in both parsing modes, with one element type,
6//! [`ENSUREMATH`] (`flm.math.ensuremath`), and one default rule on every
7//! backend, [`RULE`].
8//!
9//! # In text: an inline formula
10//!
11//! In text mode, `\ensuremath{X}` is read as the inline formula `\(X\)`. Its
12//! one argument must be written in braces, and the braces delimit a **math
13//! group**: a node of the structural element
14//! [`flm.math`](crate::lang::structural::MATH), inline
15//! ([`MathGroupForm::Inline`]), whose content `X` is parsed in math mode, as
16//! the content of `\(…\)` is. The group is the argument's content
17//! ([`argument_content_nodes`](techy::core::node::NodeRef::argument_content_nodes)
18//! answers it alone); the `\ensuremath` node around it holds nothing else.
19//!
20//! A feature that processes mathematics therefore meets this formula as it
21//! meets `\(X\)`: the same element, the same form (not displayed, so no
22//! number), the same content, with its text commands. Its rule for `flm.math`
23//! lowers the group, reached through [`RULE`], which lowers the argument; its
24//! stages find the group among the tree's descendants. The one difference is
25//! the delimiters written in the source: the group's delimiters are `{` and
26//! `}` (what [`group_delimiters`](techy::core::node::NodeRef::group_delimiters)
27//! answers), so an output that writes a formula's delimiters takes them from
28//! the group's form, as every output of the standard backends does, not from
29//! the source.
30//!
31//! The recomposed LaTeX writes this formula as written, `\ensuremath{X}`:
32//! [`group_opening`](super::latex::group_opening) and
33//! [`group_closing`](super::latex::group_closing), which a processing
34//! feature's rule for `flm.math` calls on that backend, write `\ensuremath{`
35//! and `}` for it in place of `\(` and `\)`. The command keeps the formula
36//! valid LaTeX where it ends up inside another formula: a kept user
37//! definition whose template writes `\ensuremath`, used inside a formula, or
38//! an argument that a template places in mathematics.
39//!
40//! Without braces (`\ensuremath x`) the argument is missing, an Error.
41//!
42//! # In mathematics: the argument in its place
43//!
44//! In math mode, `\ensuremath{X}` stands for `X` as if `X` were written in its
45//! place. The command takes one mandatory argument, read in math mode like the
46//! formula around it. [`RULE`] lowers the argument's content, so a formula
47//! lowered node by node writes `X`. A writer that writes a formula's TeX from
48//! its nodes for a renderer writes the argument's content and leaves out the
49//! command: the source walk of
50//! [`math-passthrough`](crate::math_passthrough), whose TeX reaches the HTML
51//! page's MathJax, does, and so does the `math-mathjax` extension. The
52//! recomposed LaTeX writes a formula as the author wrote it, so it keeps the
53//! command, which LaTeX defines, as it does in text.
54//!
55//! # The element and its rule
56//!
57//! The two declarations share the element type [`ENSUREMATH`]; the parsing
58//! mode of the node tells them apart. [`RULE`]
59//! (`flm.math.ensuremath.lower.default`) is the default rule on every backend:
60//! it lowers the argument's content through the rules, the inline formula in
61//! text mode, `X` in math mode.
62
63// The command is this feature's, the owner of math mode, so that no formula
64// renderer needs to know it: in text it is a math group whose delimiters are the
65// command's braces, which every feature processing mathematics meets as an
66// inline formula, and inside a formula a writer of the formula's TeX writes the
67// argument in its place.
68
69use std::sync::Arc;
70
71use techy::core::constructs::{
72 scan_argument_noise, stage_pre_space, ArgumentParser, ChildStateSpec, ConstructParserResult,
73 GroupArgumentParser, ParseContext, ParsedArgumentNodes,
74};
75use techy::core::node::{ContentNodes, NodeRef};
76use techy::core::specs::ArgumentSpec;
77use techy::core::token::{GroupRule, TokenEdge, TokenKind};
78use techy::latexlike::{MathGroupForm, Mode};
79
80use crate::core::lowering::{
81 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
82};
83use crate::core::registry::{BuildError, FeatureBuilder};
84use crate::lang::mint::{ArgDef, ArgStdKind, DefinitionShape, ElementDef, FlmArgumentParser, SyntaxDef};
85use crate::lang::{Flm, FlmGroupType};
86use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
87use crate::model::element::ElementSpec;
88use crate::model::names::FeatureName;
89use crate::stdlib::backends::lowering::lower_arg_or_nothing;
90
91/// The command's name, `ensuremath`, written without the leading backslash.
92pub const COMMAND: &str = "ensuremath";
93
94/// The name of the element type of `\ensuremath`, `flm.math.ensuremath`, in
95/// both parsing modes.
96pub const ENSUREMATH: &str = "flm.math.ensuremath";
97
98/// The name of the default lowering rule of [`ENSUREMATH`] on every backend,
99/// `flm.math.ensuremath.lower.default`, whose body is [`EnsureMathRule`].
100pub const RULE: &str = "flm.math.ensuremath.lower.default";
101
102/// The name of the command's only argument, `formula` in text mode and in
103/// math mode alike.
104pub const FORMULA_ARG: &str = "formula";
105
106/// The argument parser of `\ensuremath` in text mode: a `{…}` group read as an
107/// inline math group.
108///
109/// The group opens at a `{` of the content class and closes at its matching
110/// `}`. It is staged as a group of the class
111/// [`FlmGroupType::Math`] ([`MathGroupForm::Inline`]), so its content is
112/// parsed in math mode, and the group itself is the argument's content. When
113/// no `{` follows the command (after whitespace and comments), the argument is
114/// missing and reported as a mandatory argument is.
115#[derive(Debug)]
116struct FormulaArgument {
117 /// The rule of the math group: `{` and `}`, the inline math class.
118 rule: Arc<GroupRule<Flm>>,
119 /// The parser that reports a missing argument when no `{` follows.
120 missing: GroupArgumentParser<Flm>,
121}
122
123impl FormulaArgument {
124 fn new() -> FormulaArgument {
125 FormulaArgument {
126 rule: Arc::new(GroupRule {
127 group_type: FlmGroupType::Math(MathGroupForm::Inline),
128 open: String::from("{"),
129 close: String::from("}"),
130 }),
131 missing: GroupArgumentParser::new(FlmGroupType::Content).with_expression_fallback(false),
132 }
133 }
134}
135
136impl ArgumentParser<Flm> for FormulaArgument {
137 fn parse_argument(
138 &self,
139 cx: &mut ParseContext<'_, '_, Flm>,
140 spec: &ArgumentSpec<Flm>,
141 ) -> ConstructParserResult<Flm, Option<ParsedArgumentNodes<Flm>>> {
142 let noise = scan_argument_noise(cx)?;
143 let open = noise.next.clone().filter(|token| {
144 matches!(cx.tokens.token_kind(token), TokenKind::GroupOpen { rule, .. }
145 if rule.group_type == FlmGroupType::Content && rule.open == self.rule.open)
146 });
147 let Some(open) = open else {
148 // No brace group: the standard parser of a braced argument reads
149 // the same position and reports the missing argument.
150 noise.rewind(cx);
151 return self.missing.parse_argument(cx, spec);
152 };
153 let mut nodes = noise.nodes;
154 stage_pre_space(cx, &mut nodes, &open)?;
155 cx.tokens.move_to(&open, TokenEdge::EndPastPostSpace);
156 let base = Arc::clone(&cx.state);
157 let (group, _) =
158 cx.parse_group(base, &open, Arc::clone(&self.rule), ChildStateSpec::inherit(), None)?;
159 let index = u32::try_from(nodes.len()).unwrap_or(u32::MAX);
160 nodes.push(group);
161 Ok(Some(ParsedArgumentNodes::new(
162 nodes,
163 ContentNodes::InRegion(index..index.saturating_add(1)),
164 (),
165 )))
166 }
167
168 /// Returns `false`: the argument is mandatory.
169 fn can_match_empty(&self) -> bool {
170 false
171 }
172}
173
174impl FlmArgumentParser for FormulaArgument {
175 fn identity(&self) -> Vec<u8> {
176 b"flm.math.ensuremath.formula".to_vec()
177 }
178
179 /// No user definition can declare an argument read by this parser.
180 fn definition_shape(&self) -> DefinitionShape {
181 DefinitionShape::NoShape { token: "formula" }
182 }
183
184 fn description(&self) -> String {
185 String::from("a `{…}` group read as an inline formula")
186 }
187}
188
189/// The element value of `\ensuremath` in the parsing mode `mode`, inline (the
190/// default block role).
191fn element(mode: Mode) -> Arc<ElementSpec> {
192 let docs = match mode {
193 Mode::Text => "`\\ensuremath{…}` in text: an inline formula, as `\\(…\\)`.",
194 _ => "`\\ensuremath{…}` inside mathematics: its argument, as if written in its place.",
195 };
196 Arc::new(
197 ElementSpec::new(ENSUREMATH)
198 .docs(docs)
199 .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT))),
200 )
201}
202
203/// The declaration of `\ensuremath` in text mode: a macro whose one argument
204/// is an inline formula ([`FormulaArgument`]).
205fn text_def(owner: &FeatureName) -> ElementDef {
206 ElementDef::new(
207 owner.clone(),
208 [COMMAND],
209 SyntaxDef::Macro {
210 args: vec![ArgDef::named(
211 FORMULA_ARG,
212 Arc::new(FormulaArgument::new()) as Arc<dyn FlmArgumentParser>,
213 )
214 .docs("The formula, in braces: its content is mathematics.")],
215 },
216 element(Mode::Text),
217 )
218 .modes([Mode::Text])
219 .docs(
220 "Writes an inline formula, as `\\(…\\)` does. The braces are required; their \
221 content is read in math mode.",
222 )
223}
224
225/// The declaration of `\ensuremath` in math mode: a macro with one mandatory
226/// argument, read in math mode.
227fn math_def(owner: &FeatureName) -> ElementDef {
228 ElementDef::new(
229 owner.clone(),
230 [COMMAND],
231 SyntaxDef::Macro {
232 args: vec![ArgDef::named(FORMULA_ARG, ArgStdKind::Mandatory)
233 .docs("The mathematics, as if written in place of the command.")],
234 },
235 element(Mode::Math),
236 )
237 .modes([Mode::Math])
238 .docs("Inside mathematics, writes its argument as if it were written in place of the command.")
239}
240
241/// The body of [`RULE`]: it lowers the argument's content through the rules,
242/// the inline formula in text mode and the mathematics in math mode, and
243/// stages nothing of its own.
244///
245/// When the argument is missing (a parse recovery left it absent and the
246/// parse reported it), the rule produces nothing. It returns a [`LowerError`]
247/// when the argument's content could not be lowered.
248#[derive(Debug, Default, Clone, Copy)]
249pub struct EnsureMathRule;
250
251impl Lower for EnsureMathRule {
252 fn lower(
253 &self,
254 node: NodeRef<'_, Flm>,
255 cx: &mut LowerCx<'_>,
256 lw: &mut dyn Lowerer,
257 ) -> Result<Lowering, LowerError> {
258 Ok(Lowering::Emit(lower_arg_or_nothing(cx, lw, &node, 0)?))
259 }
260}
261
262/// Registers `\ensuremath` in both parsing modes and its default lowering
263/// rule, as part of the `math` feature.
264///
265/// # Errors
266///
267/// Returns the [`BuildError`] the feature builder raises, for instance for a
268/// rule already registered under the same name.
269pub(super) fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
270 let owner: FeatureName = b.feature().clone();
271 b.element(text_def(&owner))?;
272 b.element(math_def(&owner))?;
273 b.element_type_text(
274 ENSUREMATH,
275 "Mathematics that holds whether `\\ensuremath` is written in text or inside a formula: \
276 in text, an inline formula; inside mathematics, the mathematics it holds.",
277 )?;
278 b.lowering_rule(
279 LoweringRule::new(
280 RULE,
281 ENSUREMATH,
282 LoweringDecl::new(),
283 Arc::new(EnsureMathRule),
284 DefaultMark::Everywhere,
285 )
286 .docs(
287 "`\\ensuremath` lowers to its argument lowered through the rules: in text an inline \
288 formula, inside mathematics the mathematics it holds",
289 ),
290 )?;
291 Ok(())
292}
293
294#[cfg(test)]
295mod tests {
296 use super::*;
297
298 #[test]
299 fn the_command_is_declared_once_per_mode_with_one_argument() {
300 let owner = FeatureName::from("math");
301 let text = text_def(&owner);
302 assert_eq!(text.modes, vec![Mode::Text]);
303 let math = math_def(&owner);
304 assert_eq!(math.modes, vec![Mode::Math]);
305 for def in [text, math] {
306 let SyntaxDef::Macro { args } = &def.syntax else { panic!("a macro") };
307 assert_eq!(args.len(), 1);
308 assert_eq!(args[0].name.as_deref(), Some(FORMULA_ARG));
309 assert_eq!(args[0].mode, None, "the mode comes from the group or the formula");
310 }
311 }
312
313 #[test]
314 fn both_declarations_carry_the_one_element_type() {
315 assert_eq!(element(Mode::Text).name, ENSUREMATH);
316 assert_eq!(element(Mode::Math).name, ENSUREMATH);
317 }
318}