flm_core/stdlib/features/math/eqref.rs
1//! `\eqref{eq:euler}`: a reference to an equation line that shows its number and
2//! nothing else, `(13)` where `\ref{eq:euler}` shows `Eq.~(13)`.
3//!
4//! The command belongs to the [`math`](super) feature because what it refers to,
5//! one line of a display-math environment, belongs to that feature. It takes
6//! **one** label, whose label type (the part before the colon; see [reference
7//! points, labels and
8//! anchors](crate::guide::concepts_overview#reference-points-labels-and-anchors))
9//! must be `eq` ([`TARGET_TYPE`]), the label type that an equation line accepts
10//! ([`LABEL_TYPES`]). A label of any other type is an Error at the command
11//! ([`NotAnEquation`], `flm.math.eqref-not-an-equation`), and the command then
12//! shows the label's text, unlinked, as an unresolved reference does.
13//!
14//! # What the command shows
15//!
16//! An `\eqref` shows what `\ref[noprefix]` shows for the same label: the number
17//! the document gave the line, between the parentheses of the equation counter
18//! style ([`COUNTER_STYLE`](super::COUNTER_STYLE)) and without the prefix words;
19//! for a line with a `\tag`, the tag's content; and when the label refers to no
20//! equation line, or the references feature is not registered, the label as
21//! written, unlinked. The default rule [`RULE`] does not decide this itself: it
22//! calls the references feature's function for reference commands,
23//! [`lower_reference`], so that `\eqref` and `\ref` always show a label the same
24//! way. Unlike a `\ref` with one label, an `\eqref` adds none of the texts that
25//! [`RefsConfig`](crate::stdlib::features::refs::RefsConfig) writes around a
26//! single reference (`one_pre`, `one_post`): it shows the number and nothing
27//! else.
28//!
29//! # Recomposing to LaTeX
30//!
31//! On the `latex-recomposed` backend, [`LATEX_RULE`] writes `\eqref{…}` around
32//! the label's safe label, the key under which the recomposed LaTeX writes every
33//! label ([`SafeLabels`](crate::stdlib::features::refs::SafeLabels)), and
34//! requests the LaTeX package `amsmath`, which defines `\eqref`. The numbering is
35//! LaTeX's there, so the compiled document shows the number LaTeX gave the
36//! equation, not the one FLM computed.
37//!
38//! An `\eqref` whose label no equation line carries is written under the safe
39//! label assigned to that label, as every reference to a missing label is, and
40//! LaTeX reports it as an undefined reference. A label of a type other than `eq`
41//! is the same Error as on every other backend, and the label is written as the
42//! document wrote it, never as the safe label of the construct that carries that label, so
43//! a recomposed `\eqref` never points at a heading.
44//!
45//! The label is read as characters first, as a `\ref`'s is
46//! ([`read_target_at_lowering`]). A label that holds a placeholder of a user
47//! definition's template cannot be read that way; the uses of such a definition
48//! are then expanded instead of written as calls, and the label of an expanded
49//! use is written through [`target_spelling`]. That function also handles a
50//! label that appears only inside a [synthesized
51//! value](crate::guide::concepts_overview#synthesized-values) (a small tree that
52//! a stage builds during a run): it reads the label's name from the references
53//! feature's value names table ([`ValueSafeLabels`], `flm.labels.safe.value`).
54//!
55//! # Without the references feature
56//!
57//! The rules read the tables of the references feature optionally, under peer
58//! declarations ([`PeerName`](crate::core::registry::PeerName)): when that
59//! feature is registered, the stages that write the tables run before the rules;
60//! when it is not, the command shows its label as the document wrote it,
61//! unlinked. A registry with mathematics and without references therefore
62//! renders an `\eqref` instead of refusing the plan.
63//!
64//! Rendering reports nothing about the missing references feature; the registry
65//! build has already reported one Note for each unresolved peer declaration. The
66//! check of the label type reads what the author wrote, before any table is read, so
67//! `\eqref{eq:euler}` in such a registry shows `eq:euler` unlinked and reports
68//! nothing, and only a label of another type is an Error.
69//!
70//! # Map of the module
71//!
72//! - [`EQREF`], [`element`], [`EqrefElement`], [`args`] — the element, its only
73//! element value and its arguments; [`eqref_target`] reads the label of a node.
74//! - [`RULE`], [`EqrefRule`], [`LATEX_RULE`], [`EqrefLatexRule`], [`rules`] — the
75//! two lowering rules and their bodies.
76//! - [`NotAnEquation`] — the condition of a label of the wrong type.
77//! - [`register`] — registers the element, the rules and the peer declarations.
78
79use std::sync::Arc;
80use std::sync::LazyLock;
81
82use techy::core::node::{BuildId, NodeRef};
83use techy::error::{Diagnostic, DiagnosticInfo};
84
85use crate::core::lowering::{
86 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
87};
88use crate::core::registry::{BuildError, FeatureBuilder};
89use crate::lang::Flm;
90use crate::lang::text::{is_space, read_chars};
91use crate::lang::mint::{ArgDef, ArgStdKind, ElementDef, SyntaxDef};
92use crate::model::aspects::{
93 ApartFromText, BlockRole, BlockRoleAspect, ContentRef, FixedBlockRole, Label, RefDisplayOptions,
94 RefSite, Referencing,
95};
96use crate::model::element::{ElementSpec, element_value};
97use crate::model::names::{ElementName, FeatureName, Name};
98use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO, RAW};
99use crate::stdlib::backends::latex::{LatexArgShape, LatexMacroPayload, packages};
100use crate::stdlib::backends::latex_recomposed::BACKEND as LATEX_BACKEND;
101use crate::stdlib::backends::pres;
102use crate::stdlib::features::numbering::COUNTERS;
103use crate::stdlib::features::refs::{
104 LabelSpelling, REF_RESOLUTIONS, RefResolutions, RefTargetText, SAFE_LABELS, TARGET_ARG,
105 TARGET_ARG_ROLE, VALUE_SAFE_LABELS, ValueSafeLabels, lower_reference, read_target_at_lowering,
106 stage_spelling, target_spelling,
107};
108
109use super::LABEL_TYPES;
110
111/// The name of the element of `\eqref`, `flm.math.eqref`. Its element value
112/// carries an [`EqrefElement`], which is also the element's [`Referencing`]
113/// aspect.
114pub const EQREF: &str = "flm.math.eqref";
115
116/// The name of the default lowering rule of [`EQREF`] on every backend,
117/// `flm.math.eqref.lower.default`, whose body is [`EqrefRule`].
118pub const RULE: &str = "flm.math.eqref.lower.default";
119
120/// The name of the recomposition rule of [`EQREF`] for the `latex-recomposed`
121/// backend, `flm.math.eqref.lower.latex-recomposed`, whose body is
122/// [`EqrefLatexRule`].
123pub const LATEX_RULE: &str = "flm.math.eqref.lower.latex-recomposed";
124
125/// The LaTeX command that the recomposed LaTeX writes, `eqref`: the `amsmath`
126/// package's reference to an equation, which prints the number in
127/// parentheses.
128pub const LATEX_COMMAND: &str = "eqref";
129
130/// The label type that the label of an `\eqref` must have, `eq`: the type of
131/// the labels an equation line accepts.
132pub const TARGET_TYPE: &str = LABEL_TYPES[0];
133
134/// The data of the element value of `flm.math.eqref`, and the element's
135/// [`Referencing`] aspect: it declares the reference site
136/// ([`RefSite`]) of an `\eqref` node, a place that refers to a reference
137/// point.
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub struct EqrefElement;
140
141/// The label of an `\eqref` node: its argument read as characters, trimmed of
142/// the whitespace around it, and parsed when the text has the form
143/// `type:label`. `None` when `node` is not an `\eqref`, or when its argument
144/// holds a placeholder of a user definition's template that was not expanded:
145/// such an argument has no characters to read, declares no reference site,
146/// and nothing is reported for it.
147///
148/// The text is **not** split at commas: an `\eqref` takes one label, and a
149/// comma in the text is part of that label.
150pub fn eqref_target(node: &NodeRef<'_, Flm>) -> Option<RefTargetText> {
151 element_value::<EqrefElement>(node)?;
152 let text = match node.argument_content_nodes_named(TARGET_ARG) {
153 Ok(Some(content)) => match read_chars(content.iter()) {
154 Ok(read) if read.has_placeholder() => return None,
155 Ok(read) => read.text().unwrap_or_default().trim_matches(is_space).to_string(),
156 Err(_) => String::new(),
157 },
158 _ => String::new(),
159 };
160 let label = Label::parse(&text);
161 Some(RefTargetText { text, label })
162}
163
164/// Whether `target` is a label that an `\eqref` accepts: one of the form
165/// `type:label` whose type is [`TARGET_TYPE`].
166///
167/// Both the reference site that the element declares and the Error that the
168/// rules report use this function, so the two always agree.
169fn names_an_equation(target: &RefTargetText) -> bool {
170 target.label.as_ref().is_some_and(|label| label.ref_type == TARGET_TYPE)
171}
172
173impl Referencing for EqrefElement {
174 /// The reference site of an `\eqref` whose label has the type `eq`, with
175 /// the display options of `\ref[noprefix]`: no prefix words before the
176 /// number, and no variant.
177 ///
178 /// A label of any other type declares no site: the rules report it as an
179 /// Error at the command, and nothing resolves it.
180 fn sites(&self, node: &NodeRef<'_, Flm>) -> Vec<RefSite> {
181 let Some(target) = eqref_target(node).filter(names_an_equation) else {
182 return Vec::new();
183 };
184 let Some(label) = target.label else { return Vec::new() };
185 vec![RefSite {
186 target: label,
187 display: RefDisplayOptions { variant: None, with_prefix: false },
188 shown: true,
189 }]
190 }
191}
192
193/// The label of an `\eqref`, its argument [`TARGET_ARG`], is not part of the
194/// text around the command, as a `\ref`'s label is not.
195impl ApartFromText for EqrefElement {
196 fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
197 vec![ContentRef::ArgumentNamed(TARGET_ARG.to_string())]
198 }
199}
200
201static EQREF_ELEMENT: LazyLock<Arc<ElementSpec>> = LazyLock::new(|| {
202 Arc::new(
203 ElementSpec::new(EQREF)
204 .docs("A reference to an equation line that shows its number in parentheses.")
205 .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
206 .with::<dyn ApartFromText>(Arc::new(EqrefElement))
207 .with::<dyn Referencing>(Arc::new(EqrefElement))
208 .with_value(Arc::new(EqrefElement)),
209 )
210});
211
212/// The element value of every `\eqref` node. It is one shared value, so that no
213/// second element value named `flm.math.eqref` is ever created.
214pub fn element() -> Arc<ElementSpec> {
215 Arc::clone(&EQREF_ELEMENT)
216}
217
218/// The arguments of `\eqref`: its one label. There are no display options,
219/// because an `\eqref` always shows the number alone.
220pub fn args() -> Vec<ArgDef> {
221 vec![
222 ArgDef::named(TARGET_ARG, ArgStdKind::CharsGroup)
223 .docs("The equation's label, `eq:label`.")
224 .role(TARGET_ARG_ROLE),
225 ]
226}
227
228/// Condition `flm.math.eqref-not-an-equation` (an Error): the label of an
229/// `\eqref` does not have the label type `eq`.
230///
231/// Both rules report it at the command, on every backend. The recovery: the
232/// command shows the label's text, unlinked, as an unresolved reference does,
233/// and the recomposed LaTeX writes the label as the document wrote it.
234#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
235#[diagnostic(
236 id = "flm.math.eqref-not-an-equation",
237 message = "`\\eqref` refers to equations: the label `{label}` must begin with `{expected}:`"
238)]
239pub struct NotAnEquation {
240 /// The label as the document wrote it.
241 pub label: String,
242 /// The label type the label must have, `eq`.
243 pub expected: String,
244}
245
246/// The body of [`RULE`]: it shows the line's number through the references
247/// feature's [`lower_reference`], and reports [`NotAnEquation`] for a label of
248/// another type. See the module documentation, *What the command shows*.
249///
250/// The rule returns a [`LowerError`] when the node is not an `\eqref`, when a
251/// table cannot be read, or when the reference could not be lowered.
252#[derive(Debug, Default, Clone, Copy)]
253pub struct EqrefRule;
254
255impl Lower for EqrefRule {
256 fn lower(
257 &self,
258 node: NodeRef<'_, Flm>,
259 cx: &mut LowerCx<'_>,
260 lw: &mut dyn Lowerer,
261 ) -> Result<Lowering, LowerError> {
262 let mut target = eqref_target(&node)
263 .ok_or_else(|| LowerError::structure("an `\\eqref` without its element's data"))?;
264 // The condition is read from what the author wrote, before any table
265 // is consulted, so that a correct target is never reported because a
266 // registry holds no feature to resolve it.
267 let names_equation = names_an_equation(&target);
268 if !names_equation {
269 let condition = NotAnEquation {
270 label: target.text.clone(),
271 expected: String::from(TARGET_TYPE),
272 };
273 lw.diagnose(Diagnostic::error(condition, node.span().clone()));
274 }
275 // Two ways to have nothing to point at: the element declared no site
276 // for a target of the wrong type, and where no feature resolves
277 // references no target resolves at all. Either way the command is
278 // shown the way a target that is no label at all is shown: its text,
279 // unlinked.
280 if !names_equation || lw.get(REF_RESOLUTIONS)?.is_none() {
281 target.label = None;
282 }
283 let display = RefDisplayOptions { variant: None, with_prefix: false };
284 // `\eqref` shows its one item bare, without the `one_pre` and
285 // `one_post` a one-target `\ref` takes.
286 let items = lower_reference(cx, lw, &node, std::slice::from_ref(&target), &display)?;
287 Ok(Lowering::Emit(items.into_iter().flatten().collect()))
288 }
289}
290
291/// The body of [`LATEX_RULE`]: `\eqref` around the label's safe label, and a
292/// request for the LaTeX package `amsmath`. See the module documentation,
293/// *Recomposing to LaTeX*.
294///
295/// The rule returns a [`LowerError`] when the label holds a placeholder of a
296/// template ([`read_target_at_lowering`]), when a table cannot be read, or when
297/// a node could not be staged.
298#[derive(Debug, Default, Clone, Copy)]
299pub struct EqrefLatexRule;
300
301impl Lower for EqrefLatexRule {
302 fn lower(
303 &self,
304 node: NodeRef<'_, Flm>,
305 cx: &mut LowerCx<'_>,
306 lw: &mut dyn Lowerer,
307 ) -> Result<Lowering, LowerError> {
308 read_target_at_lowering(&node)?;
309 lw.require(&Name::from(packages::AMSMATH));
310 let target = eqref_target(&node).unwrap_or(RefTargetText {
311 text: String::new(),
312 label: None,
313 });
314 let spelling = if names_an_equation(&target) {
315 target_spelling(lw, &target.text, target.label.as_ref())?
316 } else {
317 // The same condition as on every other backend, at the same node,
318 // so that the one backend whose output a LaTeX compiler reads is
319 // not the one where a wrong target passes. The label is written as
320 // the document wrote it, never as the name allocated for whatever
321 // does carry it, so that the reference cannot resolve to a heading.
322 let condition = NotAnEquation {
323 label: target.text.clone(),
324 expected: String::from(TARGET_TYPE),
325 };
326 lw.diagnose(Diagnostic::error(condition, node.span().clone()));
327 LabelSpelling::Raw(target.text.clone())
328 };
329 let key = stage_spelling(cx, lw, &spelling)?;
330 Ok(Lowering::Emit(vec![eqref_command(cx, lw, key)?]))
331 }
332}
333
334/// Stages the macro construct `\eqref` around `key`, the staged label.
335fn eqref_command(
336 cx: &mut LowerCx<'_>,
337 lw: &mut dyn Lowerer,
338 key: Vec<BuildId>,
339) -> Result<BuildId, LowerError> {
340 lw.pres_slots_with(
341 cx,
342 &ElementName::from(MACRO),
343 LatexMacroPayload::new(LATEX_COMMAND, [LatexArgShape::Mandatory]),
344 vec![(String::from(ARG_SLOT), key)],
345 )
346}
347
348/// The two rules of `\eqref`, ready to be registered: [`RULE`], the default on
349/// every backend, and [`LATEX_RULE`], the default on the `latex-recomposed`
350/// backend only.
351///
352/// [`RULE`] reads the resolutions table of the references feature and the
353/// counter table of the numbering feature, both optionally: when the registry
354/// holds the feature that writes a table, the plan runs that stage before the
355/// rule; when it does not, the command shows the label as the document wrote
356/// it. [`LATEX_RULE`] reads the safe labels and the value names of the
357/// references feature in the same way.
358pub fn rules() -> Vec<LoweringRule> {
359 vec![
360 LoweringRule::new(
361 RULE,
362 EQREF,
363 LoweringDecl::new()
364 .reads_opt(REF_RESOLUTIONS)
365 .reads_opt(COUNTERS)
366 .produces(pres::LINK)
367 .produces(pres::SPAN),
368 Arc::new(EqrefRule),
369 DefaultMark::Everywhere,
370 )
371 .docs(
372 "an `\\eqref` lowers to what `\\ref[noprefix]` lowers to for the same label: the \
373 line's number in parentheses, inside a link to the equation line",
374 ),
375 LoweringRule::new(
376 LATEX_RULE,
377 EQREF,
378 LoweringDecl::new()
379 .reads_opt(SAFE_LABELS)
380 .reads_opt(VALUE_SAFE_LABELS)
381 .produces(MACRO)
382 .produces(RAW),
383 Arc::new(EqrefLatexRule),
384 DefaultMark::OnBackends(vec![LATEX_BACKEND.into()]),
385 )
386 .docs("an `\\eqref` lowers to the LaTeX `\\eqref` around its label's safe label"),
387 ]
388}
389
390/// Registers `\eqref`: peer declarations
391/// ([`PeerName`](crate::core::registry::PeerName)) of the references feature's
392/// resolutions table and value names, the element and its element type's
393/// text, and its two rules.
394///
395/// The peer declarations that the recomposition rule also needs (the
396/// `latex-recomposed` backend and the macro and raw constructs) are made by
397/// the feature's [`latex`](super::latex) module, so a registry without the
398/// LaTeX features sets this rule aside (excludes it from rule selection) with
399/// the others.
400///
401/// # Errors
402///
403/// Returns the [`BuildError`] the feature builder raises, for instance for an
404/// element or a rule already registered under the same name.
405pub fn register(b: &mut FeatureBuilder<'_>, owner: &FeatureName) -> Result<(), BuildError> {
406 // The resolutions table belongs to the references feature, and the rule
407 // reads it optionally: where that feature is registered the declaration
408 // resolves and the read is passed on as a required one, so the stage that
409 // writes the table runs before the rule; where it is not, the declaration
410 // goes unresolved with one Note and the rule still runs, showing the
411 // label as the document wrote it. An optional read never sets a rule
412 // aside.
413 b.peer_table::<RefResolutions>(
414 REF_RESOLUTIONS.name(),
415 "the references feature's resolutions table, which the `\\eqref` rule reads for the \
416 reference point its label refers to",
417 )?;
418 // The value names belong to the references feature too, and are read the
419 // same way by the recomposition rule: a target an `\eqref` spliced at
420 // lowering names is written under the name its value gives it.
421 b.peer_table::<ValueSafeLabels>(
422 VALUE_SAFE_LABELS.name(),
423 "the references feature's value names table (`flm.labels.safe.value`), which the \
424 `\\eqref` recomposition rule reads for the safe label of a label that appears only inside a synthesized value",
425 )?;
426 // The label an `\eqref` holds is a reference's target, the role the
427 // references feature declares; declared as a peer, so that a registry
428 // without that feature still builds.
429 b.peer_argument_role(TARGET_ARG_ROLE)?;
430 b.element(
431 ElementDef::new(owner.clone(), ["eqref"], SyntaxDef::Macro { args: args() }, element())
432 .docs(
433 "Refers to an equation line and shows its number in parentheses. The label has \
434 the label type `eq`.",
435 ),
436 )?;
437 b.element_type_text(
438 EQREF,
439 "A reference to an equation line, shown as the line's number in parentheses.",
440 )?;
441 for rule in rules() {
442 b.lowering_rule(rule)?;
443 }
444 Ok(())
445}
446
447#[cfg(test)]
448mod tests {
449 use super::*;
450
451 #[test]
452 fn the_element_carries_the_referencing_aspect_and_is_one_shared_value() {
453 let element = element();
454 assert!(element.has_aspect::<dyn Referencing>());
455 assert!(element.value_as::<EqrefElement>().is_some());
456 assert!(ElementSpec::same_value(&super::element(), &super::element()));
457 }
458
459 #[test]
460 fn only_a_label_of_the_equation_type_names_an_equation() {
461 let target = |text: &str| RefTargetText {
462 text: String::from(text),
463 label: Label::parse(text),
464 };
465 assert!(names_an_equation(&target("eq:euler")));
466 assert!(!names_an_equation(&target("sec:intro")));
467 assert!(!names_an_equation(&target("euler")));
468 assert!(!names_an_equation(&target("")));
469 }
470}