flm_core/stdlib/features/literals/latex.rs
1//! The recomposition rules of the [`literals`](super) feature for the
2//! `latex-recomposed` backend: every literal, and `\@`, written back as the
3//! author wrote it.
4//!
5//! Both rules stage (build into the lowered tree; see
6//! [`Lowerer`]) a raw node,
7//! [`flm.pres.latex.raw`](crate::stdlib::backends::latex::construct::RAW): a
8//! construct element whose text the emitter writes byte for byte, with no
9//! escaping ([`LatexRawPayload`]). A literal's spelling is LaTeX syntax that must
10//! reach LaTeX exactly as written; a raw node carries such text.
11//!
12//! - [`LITERAL_LATEX_RULE`] (`flm.literal.lower.latex-recomposed`) writes the
13//! literal's spelling ([`Literal::source`](super::Literal::source)): `\%`,
14//! `\#`, `\&`, `\$`, `\ `, `\{`, `\}`, `\textbackslash` or `~`, which LaTeX
15//! reads as the character the author meant.
16//! - [`SENTENCE_SPACING_LATEX_RULE`] (`flm.sentence-spacing.lower.latex-recomposed`)
17//! writes `\@`, LaTeX's hint about the space after a period.
18//!
19//! After the spelling, each rule writes the whitespace that the parse took after
20//! the command's name, exactly as written. Only a command whose name is made of
21//! letters takes such whitespace (`\textbackslash `), and it keeps the command
22//! apart from a letter written next (`\textbackslash x`); LaTeX reads it the same
23//! way the parse did.
24//!
25//! Without these rules, the backend would apply the default rules of the
26//! [`literals`](super) feature, and the recomposed LaTeX would differ from what
27//! the author wrote: each literal would become its character as text, so that
28//! the space of `\ ` would reach LaTeX as an ordinary space, which LaTeX merges
29//! with the spaces around it, `~` would be written as the character U+00A0 (or
30//! its LaTeX spelling, under the backend's `Replace` Unicode mode), a
31//! brace or a backslash would be written in the escaped form the backend
32//! chooses, and `\@` would be dropped. Both rules are the default on the
33//! `latex-recomposed` backend only.
34//!
35//! The feature does not own the backend or the raw construct. [`register`]
36//! declares both as peer declarations
37//! ([`PeerName`](crate::core::registry::PeerName)), so that a registry without
38//! the LaTeX features still builds; the two rules are then set aside (excluded
39//! from rule selection; see [`PeerName`](crate::core::registry::PeerName)).
40
41use std::sync::Arc;
42
43use techy::core::node::NodeRef;
44use techy::latexlike::InvocationSyntaxData;
45
46use crate::core::lowering::{
47 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
48};
49use crate::core::registry::{BuildError, FeatureBuilder};
50use crate::lang::Flm;
51use crate::model::element::element_value;
52use crate::model::names::ElementName;
53use crate::stdlib::backends::latex::LatexRawPayload;
54use crate::stdlib::backends::latex::construct::RAW;
55use crate::stdlib::backends::latex_recomposed::BACKEND;
56
57use super::{LITERAL, LiteralElement, SENTENCE_SPACING};
58
59/// The name of the recomposition rule of `flm.literal`,
60/// `flm.literal.lower.latex-recomposed`, whose body is
61/// [`LiteralLatexRule`].
62pub const LITERAL_LATEX_RULE: &str = "flm.literal.lower.latex-recomposed";
63
64/// The name of the recomposition rule of `\@` (`flm.sentence-spacing`),
65/// `flm.sentence-spacing.lower.latex-recomposed`, whose body is
66/// [`SentenceSpacingLatexRule`].
67pub const SENTENCE_SPACING_LATEX_RULE: &str = "flm.sentence-spacing.lower.latex-recomposed";
68
69/// The LaTeX written for `\@`: `\@`.
70pub const SENTENCE_SPACING_SOURCE: &str = "\\@";
71
72/// Stages a raw node holding `spelling` followed by the whitespace that the
73/// parse took after `node`'s command name, exactly as written (see the module
74/// documentation): what both rules stage.
75fn spelling_as_written(
76 cx: &mut LowerCx<'_>,
77 lw: &mut dyn Lowerer,
78 node: &NodeRef<'_, Flm>,
79 spelling: &str,
80) -> Result<Lowering, LowerError> {
81 let mut written = String::from(spelling);
82 if let Some(InvocationSyntaxData::Macro { post_space, .. }) = node.invocation_syntax() {
83 written.push_str(post_space.resolve(node.span().source()));
84 }
85 let raw = lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(written), Vec::new())?;
86 Ok(Lowering::Emit(vec![raw]))
87}
88
89/// The body of [`LITERAL_LATEX_RULE`]: a raw node holding the literal's
90/// spelling as written ([`Literal::source`](super::Literal::source)).
91///
92/// The rule returns a [`LowerError`] when the node carries no
93/// [`LiteralElement`] or when the raw node could not be staged.
94#[derive(Debug, Default, Clone, Copy)]
95pub struct LiteralLatexRule;
96
97impl Lower for LiteralLatexRule {
98 fn lower(
99 &self,
100 node: NodeRef<'_, Flm>,
101 cx: &mut LowerCx<'_>,
102 lw: &mut dyn Lowerer,
103 ) -> Result<Lowering, LowerError> {
104 let value = element_value::<LiteralElement>(&node)
105 .ok_or_else(|| LowerError::structure("a literal node without its element's data"))?;
106 spelling_as_written(cx, lw, &node, value.literal.source())
107 }
108}
109
110/// The body of [`SENTENCE_SPACING_LATEX_RULE`]: a raw node holding `\@`.
111#[derive(Debug, Default, Clone, Copy)]
112pub struct SentenceSpacingLatexRule;
113
114impl Lower for SentenceSpacingLatexRule {
115 fn lower(
116 &self,
117 node: NodeRef<'_, Flm>,
118 cx: &mut LowerCx<'_>,
119 lw: &mut dyn Lowerer,
120 ) -> Result<Lowering, LowerError> {
121 spelling_as_written(cx, lw, &node, SENTENCE_SPACING_SOURCE)
122 }
123}
124
125/// The two recomposition rules, ready to be registered: each produces
126/// `flm.pres.latex.raw` and is the default on the `latex-recomposed` backend
127/// only.
128pub fn latex_rules() -> Vec<LoweringRule> {
129 let on_this_backend = || DefaultMark::OnBackends(vec![BACKEND.into()]);
130 vec![
131 LoweringRule::new(
132 LITERAL_LATEX_RULE,
133 LITERAL,
134 LoweringDecl::new().produces(RAW),
135 Arc::new(LiteralLatexRule),
136 on_this_backend(),
137 )
138 .docs("a literal lowers to a raw node holding its spelling as written"),
139 LoweringRule::new(
140 SENTENCE_SPACING_LATEX_RULE,
141 SENTENCE_SPACING,
142 LoweringDecl::new().produces(RAW),
143 Arc::new(SentenceSpacingLatexRule),
144 on_this_backend(),
145 )
146 .docs("`\\@` lowers to a raw node holding `\\@`"),
147 ]
148}
149
150/// Registers what the `literals` feature contributes to the
151/// `latex-recomposed` backend: a peer declaration
152/// ([`PeerName`](crate::core::registry::PeerName)) of the backend and of the
153/// raw construct, with [`LatexRawPayload`] as its payload type, then
154/// [`latex_rules`].
155///
156/// In a registry without the LaTeX features the two peer declarations resolve
157/// to nothing and the rules are set aside (excluded from rule selection); the
158/// registry still builds.
159///
160/// # Errors
161///
162/// Returns the [`BuildError`] the feature builder raises, for instance for a
163/// rule already registered under the same name.
164pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
165 b.peer_backend(
166 BACKEND,
167 "the latex-recomposed backend, on which the recomposition rules of the literals are \
168 the default",
169 )?;
170 b.peer_element::<LatexRawPayload>(
171 RAW,
172 "the LaTeX family's raw construct, which the recomposition rules of the literals \
173 stage",
174 )?;
175 for rule in latex_rules() {
176 b.lowering_rule(rule)?;
177 }
178 Ok(())
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 #[test]
186 fn both_rules_produce_raw_pieces_on_the_recomposed_backend_only() {
187 let rules = latex_rules();
188 assert_eq!(rules[0].element, LITERAL);
189 assert_eq!(rules[1].element, SENTENCE_SPACING);
190 for rule in &rules {
191 assert_eq!(rule.decl.produces, [ElementName::from(RAW)]);
192 assert!(rule.default.is_specific_to(&BACKEND.into()));
193 }
194 }
195}