flm_core/stdlib/backends/latex/construct.rs
1//! The four LaTeX construct elements (a macro call, an environment, raw LaTeX
2//! text and a definition) with their typed payloads, and the placeholder rule
3//! of the recomposed LaTeX.
4//!
5//! A construct element is a presentation element that mirrors one construct
6//! of an output format, so that format-specific output is structured data in
7//! the lowered tree rather than a string ([construct
8//! element](crate::guide::concepts_overview#backends-lowering-and-outputs)). A
9//! lowering rule stages one of these four elements to write LaTeX that no
10//! shared presentation element ([`crate::stdlib::backends::pres`]) can
11//! express: the shared elements include no catch-all element and no element
12//! that carries raw bytes for a named format. The four are named
13//! `flm.pres.latex.<name>`, and every LaTeX backend writes them natively.
14//! Like every presentation element, each node carries exactly one typed
15//! payload on the node's extension ([`FlmNodeExt`]),
16//! and holds its content only in its content slots (the named groups of a
17//! presentation node's children;
18//! [`read`](crate::stdlib::backends::pres::read)). A content slot of these
19//! nodes is a node slot in techy's sense (techy's `ParsedSlot`): a part of a
20//! node's content outside its arguments, such as an environment's body.
21//!
22//! | element | payload | content slots |
23//! |---|---|---|
24//! | [`MACRO`] (`flm.pres.latex.macro`) | [`LatexMacroPayload`]: the command name, the shape of each argument written, and whether the arguments are handed over in one group | one [`ARG_SLOT`] per argument that has content (a star has none), in order |
25//! | [`ENVIRONMENT`] (`flm.pres.latex.environment`) | [`LatexEnvironmentPayload`]: the environment name, the argument shapes, whether the body is verbatim, whether the arguments are handed over in one group, whether the environment takes its body as an argument | the argument slots, then the `body` slot ([`BODY_SLOT`](crate::stdlib::backends::pres::BODY_SLOT)) |
26//! | [`RAW`] (`flm.pres.latex.raw`) | [`LatexRawPayload`]: LaTeX text written byte for byte | none |
27//! | [`DEFINITION`] (`flm.pres.latex.definition`) | [`LatexDefinitionPayload`]: a macro or environment definition's name, how many arguments it takes, and how it is written; or a feature's declaration and the name it is guarded on | `body` for a macro and a declaration, [`BEGIN_SLOT`] and [`END_SLOT`] for an environment |
28//!
29//! An emitter writes every construct from its payload and normalizes the
30//! call syntax: a mandatory argument is always braced, no space follows a
31//! command name, and `\begin{name}` is followed directly by its arguments and
32//! body. The content of each content slot is the document's own and is written through
33//! the emitter's sink ([`super::sink`]). A definition node is never written
34//! where it occurs in the tree: the emitter records the definition for the
35//! style file ([`super::style`]).
36//!
37//! # Projections
38//!
39//! Every payload implements [`PresPayload`] with a self-contained projection
40//! (the value written when a lowered tree is serialized,
41//! [`crate::dump::session`], and printed by the projection,
42//! [`crate::dump::project`]) and has
43//! a registered reader that rebuilds the payload from that projection
44//! ([`payload_readers`]). The projections are: `macro`:
45//! `{name, args?, packed?}`; `environment`: `{name, args?, verbatim, packed?,
46//! body?}`; `raw`: `{text}`; `definition`: `{kind, name, source?, args?,
47//! packed?, robust?, body?, feature?}`. The optional keys are written only when
48//! they hold something:
49//!
50//! - `args`: on a call, the list of shape names ([`LatexArgShape::as_str`]),
51//! one per argument the call writes, present when the list is not empty; on
52//! a definition, how many arguments the definition takes, present when it
53//! takes at least one.
54//! - `packed`: the arguments are handed over in one brace group, one pair of
55//! braces around each ([`LatexMacroPayload::packed`],
56//! [`LatexDefinitionPayload::packed`]); a call and the definition it calls
57//! agree on it.
58//! - `robust`: a macro definition is written as a robust command rather than
59//! as an expandable macro ([`LatexDefinitionPayload::robust`]); only a
60//! macro definition carries it.
61//! - `body`: the environment takes what is written between `\begin` and
62//! `\end` as its last argument rather than letting LaTeX set it between the
63//! begin code and the end code
64//! ([`LatexDefinitionPayload::body_argument`],
65//! [`LatexEnvironmentPayload::body_argument`]); only an environment carries
66//! it, its definition and its calls alike, with the same value.
67//! - `source`: the name the document declared, where it differs from `name`.
68//! - `feature`: the feature that wrote the definition from its configuration
69//! ([`LatexDefinitionPayload::feature`]).
70//!
71//! # Reading a node's content slots
72//!
73//! Two readers at the end of the module ([`arg_slots`], [`slot_named`]) pair
74//! a node's content slots with its payload for an emitter.
75//!
76//! # The placeholder rule
77//!
78//! When a lowering rule of the `latex-recomposed` backend copies a template
79//! (the template of a kept user definition,
80//! [`kept`](crate::stdlib::features::userdefs::kept), or a list label
81//! template), it records on the copy of each placeholder a [`LatexPoint`]
82//! value: the LaTeX text written at that placeholder. The placeholder rule
83//! ([`placeholder_rule`], `flm.placeholder.lower.latex-recomposed`), which
84//! the `latex` feature registers, writes that text.
85
86use std::fmt;
87use std::sync::Arc;
88
89use techy::core::node::{
90 BuildId, CallableData, NodeKind, NodeRef, NodeSlice, ParsedArguments, ParsedSlots,
91};
92use techy::serialize::{DeserializeContext, DeserializeError, SerialValue};
93use techy::transform::RestageContext;
94
95use crate::core::lowering::{
96 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
97};
98use crate::core::registry::{BuildError, FeatureBuilder};
99use crate::dump::session::PayloadReaders;
100use crate::lang::structural::PLACEHOLDER;
101use crate::lang::{Flm, FlmNodeExt, PresPayload};
102use crate::model::element::{element_of, element_value};
103use crate::model::names::ElementName;
104use crate::stdlib::backends::latex_recomposed::BACKEND as RECOMPOSED_BACKEND;
105use crate::stdlib::backends::pres::payload::{bad, entries, field, map, text};
106
107/// `flm.pres.latex.macro` — a macro call: `\name` followed by its arguments,
108/// one content slot per argument that has content.
109pub const MACRO: &str = "flm.pres.latex.macro";
110/// `flm.pres.latex.environment` — an environment: `\begin{name}`, its
111/// arguments, its body, `\end{name}`.
112pub const ENVIRONMENT: &str = "flm.pres.latex.environment";
113/// `flm.pres.latex.raw` — raw LaTeX text written byte for byte; the node has
114/// no children.
115pub const RAW: &str = "flm.pres.latex.raw";
116/// `flm.pres.latex.definition` — a macro or environment definition, or a
117/// feature's declaration, written into the style file and never where the node
118/// occurs in the tree.
119pub const DEFINITION: &str = "flm.pres.latex.definition";
120
121/// The four construct elements, in registration order.
122pub const ALL: [&str; 4] = [MACRO, ENVIRONMENT, RAW, DEFINITION];
123
124/// The name of every argument's content slot on a macro or environment node.
125/// The name repeats once per argument, so these content slots are read by
126/// index ([`arg_slots`]).
127pub const ARG_SLOT: &str = "arg";
128/// The name of the content slot holding an environment definition's begin
129/// code.
130pub const BEGIN_SLOT: &str = "begin";
131/// The name of the content slot holding an environment definition's end
132/// code.
133pub const END_SLOT: &str = "end";
134
135// --- projection helpers ---------------------------------------------------------------
136//
137// `text`, `map`, `bad`, `entries` and `field` are the presentation payloads'
138// own helpers, shared from `crate::stdlib::backends::pres::payload`; the
139// ones below know something about these payloads in particular.
140
141/// A required string field.
142fn string(
143 element: &str,
144 entries: &[(String, SerialValue)],
145 key: &str,
146) -> Result<String, DeserializeError> {
147 match field(entries, key) {
148 Some(SerialValue::Str(s)) => Ok(s.clone()),
149 Some(other) => Err(bad(element, format!("`{key}` must be a string, found {other:?}"))),
150 None => Err(bad(element, format!("`{key}` is missing"))),
151 }
152}
153
154/// A required boolean field.
155fn boolean(
156 element: &str,
157 entries: &[(String, SerialValue)],
158 key: &str,
159) -> Result<bool, DeserializeError> {
160 match field(entries, key) {
161 Some(SerialValue::Bool(b)) => Ok(*b),
162 Some(other) => Err(bad(element, format!("`{key}` must be a boolean, found {other:?}"))),
163 None => Err(bad(element, format!("`{key}` is missing"))),
164 }
165}
166
167/// The list of argument shapes under `key`; an absent or null key reads as no
168/// arguments.
169fn shapes(
170 element: &str,
171 entries: &[(String, SerialValue)],
172 key: &str,
173) -> Result<Vec<LatexArgShape>, DeserializeError> {
174 match field(entries, key) {
175 None | Some(SerialValue::Null) => Ok(Vec::new()),
176 Some(SerialValue::List(items)) => items
177 .iter()
178 .map(|item| match item {
179 SerialValue::Str(s) => LatexArgShape::parse(s)
180 .ok_or_else(|| bad(element, format!("unknown argument shape `{s}`"))),
181 other => Err(bad(element, format!("`{key}` holds a non-string {other:?}"))),
182 })
183 .collect(),
184 Some(other) => Err(bad(element, format!("`{key}` must be a list, found {other:?}"))),
185 }
186}
187
188/// The argument shapes as serial data under `key`, pushed only when there is
189/// at least one.
190fn push_shapes(
191 entries: &mut Vec<(&'static str, SerialValue)>,
192 key: &'static str,
193 args: &[LatexArgShape],
194) {
195 if !args.is_empty() {
196 entries.push((key, SerialValue::List(args.iter().map(|a| text(a.as_str())).collect())));
197 }
198}
199
200// --- the argument shapes --------------------------------------------------------------
201
202/// One optional boolean key of a projection, read by name — `packed`, `body`:
203/// an absent or null key reads as `false`, and anything but a boolean is an
204/// error that identifies `element` and the key.
205fn optional_flag(
206 element: &str,
207 entries: &[(String, SerialValue)],
208 key: &str,
209) -> Result<bool, DeserializeError> {
210 match field(entries, key) {
211 None | Some(SerialValue::Null) => Ok(false),
212 Some(SerialValue::Bool(b)) => Ok(*b),
213 Some(other) => Err(bad(element, format!("`{key}` must be a boolean, found {other:?}"))),
214 }
215}
216
217/// One optional boolean key as serial data, pushed only when it is set.
218fn push_flag(entries: &mut Vec<(&'static str, SerialValue)>, key: &'static str, set: bool) {
219 if set {
220 entries.push((key, SerialValue::Bool(true)));
221 }
222}
223
224/// The shape of one argument of a macro or environment construct: how the
225/// emitter writes the argument, and whether the argument has a content slot.
226///
227/// The shapes are the syntactic forms LaTeX has for an argument. A `*` and a
228/// `[…]` are what an author writes for a starred variant and an optional
229/// argument; a `{…}` is a mandatory argument. The fourth shape, [`EscVerb`],
230/// is a mandatory argument whose content is verbatim text written in the
231/// encoding that the `\EscVerb` command of the `fvextra` package reads (a
232/// backslash before every printable ASCII character that is not a letter or a
233/// digit), so that verbatim content survives inside a moving argument such as
234/// a section title. With this shape a lowering rule only declares the shape,
235/// and the sink does the encoding ([`super::sink::LatexSink::escverb`]).
236///
237/// [`EscVerb`]: LatexArgShape::EscVerb
238#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
239pub enum LatexArgShape {
240 /// A star: written as `*`; no content slot.
241 Star,
242 /// An optional argument: written as `[…]`, or `[{…}]` when the content
243 /// could be misread — the emitter decides from the slot's nodes.
244 Optional,
245 /// A mandatory argument: always written as `{…}`.
246 Mandatory,
247 /// A mandatory argument holding verbatim content, written as `{…}` in the
248 /// `\EscVerb` encoding; its slot holds the verbatim text as text nodes.
249 EscVerb,
250}
251
252impl LatexArgShape {
253 /// Every shape, in declaration order.
254 pub const ALL: [LatexArgShape; 4] =
255 [LatexArgShape::Star, LatexArgShape::Optional, LatexArgShape::Mandatory, LatexArgShape::EscVerb];
256
257 /// The shape's stable name, the projected spelling: `star`, `optional`,
258 /// `mandatory`, `escverb`.
259 pub fn as_str(self) -> &'static str {
260 match self {
261 LatexArgShape::Star => "star",
262 LatexArgShape::Optional => "optional",
263 LatexArgShape::Mandatory => "mandatory",
264 LatexArgShape::EscVerb => "escverb",
265 }
266 }
267
268 /// The shape of a stable name, if any.
269 pub fn parse(name: &str) -> Option<LatexArgShape> {
270 LatexArgShape::ALL.into_iter().find(|shape| shape.as_str() == name)
271 }
272
273 /// Whether an argument of this shape has a content slot on the node: every
274 /// shape but [`Star`](LatexArgShape::Star).
275 pub fn has_slot(self) -> bool {
276 !matches!(self, LatexArgShape::Star)
277 }
278}
279
280impl fmt::Display for LatexArgShape {
281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282 f.write_str(self.as_str())
283 }
284}
285
286/// How many of the given shapes have a content slot.
287fn slot_bearing(args: &[LatexArgShape]) -> usize {
288 args.iter().filter(|shape| shape.has_slot()).count()
289}
290
291// --- the payloads ---------------------------------------------------------------------
292
293/// The payload of `flm.pres.latex.macro`: the command's name and the shape of
294/// each of its arguments, in the order they are written.
295///
296/// The node carries one content slot named [`ARG_SLOT`] per argument whose
297/// shape [has a slot](LatexArgShape::has_slot), in argument order; a
298/// [`Star`](LatexArgShape::Star) contributes no slot. The emitter writes
299/// `\<name>` and then each argument in its shape — or, under
300/// [`packed`](Self::packed), every argument inside one brace group.
301#[derive(Debug, Clone, PartialEq, Eq, Default)]
302pub struct LatexMacroPayload {
303 /// The command's name without the backslash (`emph`, `section`).
304 pub name: String,
305 /// The shape of each argument, in order.
306 pub args: Vec<LatexArgShape>,
307 /// Whether the call hands every argument over in **one** brace group,
308 /// `\<name>{{first}{second}…}`, instead of writing each argument in its
309 /// own shape.
310 ///
311 /// This is how a call of a definition of more than
312 /// [`PLAIN_ARGUMENT_LIMIT`] arguments is written, since a LaTeX macro body
313 /// can refer to only nine parameters
314 /// ([`LatexDefinitionPayload::packed`], which the definition carries).
315 /// Every argument then has a brace group of its own inside the one group,
316 /// in order, regardless of its shape, so every argument of a packed call
317 /// has a shape with a content slot.
318 pub packed: bool,
319}
320
321impl LatexMacroPayload {
322 /// A macro call with the given name and argument shapes, writing every
323 /// argument the command takes, each in its own shape.
324 pub fn new(name: impl Into<String>, args: impl IntoIterator<Item = LatexArgShape>) -> Self {
325 LatexMacroPayload { name: name.into(), args: args.into_iter().collect(), packed: false }
326 }
327
328 /// The same call with every argument handed over in one brace group
329 /// ([`packed`](Self::packed)).
330 pub fn packed(mut self) -> Self {
331 self.packed = true;
332 self
333 }
334
335 /// How many content slots the node carries: the arguments whose shape has
336 /// one.
337 pub fn slot_count(&self) -> usize {
338 slot_bearing(&self.args)
339 }
340
341 /// The payload rebuilt from its projection, the value
342 /// [`project`](PresPayload::project) produced.
343 ///
344 /// # Errors
345 ///
346 /// Returns a [`DeserializeError`] that identifies `flm.pres.latex.macro`
347 /// when the projection is not a map, when `name` is missing or is not a
348 /// string,
349 /// when `args` is present and is not a list of shape names, or when
350 /// `packed` is present and is not a boolean.
351 pub fn from_projection(value: &SerialValue) -> Result<LatexMacroPayload, DeserializeError> {
352 let e = entries(MACRO, value)?;
353 Ok(LatexMacroPayload {
354 name: string(MACRO, e, "name")?,
355 args: shapes(MACRO, e, "args")?,
356 packed: optional_flag(MACRO, e, "packed")?,
357 })
358 }
359}
360
361impl PresPayload for LatexMacroPayload {
362 fn project(&self) -> SerialValue {
363 let mut entries = vec![("name", text(&self.name))];
364 push_shapes(&mut entries, "args", &self.args);
365 push_flag(&mut entries, "packed", self.packed);
366 map(entries)
367 }
368}
369
370/// The payload of `flm.pres.latex.environment`: the environment's name, the
371/// shape of each of its arguments, whether its body is verbatim, and whether
372/// the environment takes its body as an argument of its own.
373///
374/// The node carries one [`ARG_SLOT`] per argument whose shape has one, in
375/// order, then the `body` slot ([`BODY_SLOT`](crate::stdlib::backends::pres::BODY_SLOT)) holding the lowered
376/// body. The emitter writes `\begin{<name>}`, the arguments, the body and
377/// `\end{<name>}`. When [`verbatim`](Self::verbatim) is set the body is
378/// verbatim text: the emitter writes it byte for byte, on lines of its own —
379/// a newline after `\begin{…}` and its arguments, and the `\end{…}` on a line
380/// of its own — because a verbatim environment discards the rest of the line
381/// that holds its `\begin`.
382#[derive(Debug, Clone, PartialEq, Eq, Default)]
383pub struct LatexEnvironmentPayload {
384 /// The environment's name (`align`, `flmVerbatimCode`).
385 pub name: String,
386 /// The shape of each argument written after `\begin{<name>}`, in order.
387 pub args: Vec<LatexArgShape>,
388 /// Whether the body is verbatim text written byte for byte with the
389 /// newline discipline described on the type.
390 pub verbatim: bool,
391 /// Whether the arguments are handed over in **one** brace group after
392 /// `\begin{<name>}`, one pair of braces around each, as
393 /// [`LatexMacroPayload::packed`] describes for a macro call.
394 pub packed: bool,
395 /// Whether the environment **takes its body as an argument** — it was
396 /// declared with `+b` ([`LatexDefinitionPayload::body_argument`]) — so
397 /// that LaTeX hands what is written between `\begin` and `\end` to the
398 /// definition as a trailing argument instead of setting it between the
399 /// begin code and the end code.
400 ///
401 /// The body then reaches LaTeX as a **token group**: its characters are
402 /// read, once, as LaTeX reads that argument, long before the definition
403 /// can say anything about what they mean. Content whose meaning depends
404 /// on being read out of the file, such as a verbatim block, must therefore
405 /// be written in a form that survives being read as tokens; the emitter
406 /// reads this field to choose that form.
407 ///
408 /// A call is staged with this field set from the same value the
409 /// definition itself is written from, so a call and its definition cannot
410 /// disagree about it.
411 pub body_argument: bool,
412}
413
414impl LatexEnvironmentPayload {
415 /// An environment with the given name and argument shapes, its body
416 /// ordinary lowered content, writing every argument the environment
417 /// takes.
418 pub fn new(name: impl Into<String>, args: impl IntoIterator<Item = LatexArgShape>) -> Self {
419 LatexEnvironmentPayload {
420 name: name.into(),
421 args: args.into_iter().collect(),
422 verbatim: false,
423 packed: false,
424 body_argument: false,
425 }
426 }
427
428 /// The same environment with a verbatim body.
429 pub fn verbatim(mut self) -> Self {
430 self.verbatim = true;
431 self
432 }
433
434 /// The same environment with every argument handed over in one brace
435 /// group ([`packed`](Self::packed)).
436 pub fn packed(mut self) -> Self {
437 self.packed = true;
438 self
439 }
440
441 /// The same environment taking its body as an argument
442 /// ([`body_argument`](Self::body_argument)).
443 pub fn body_argument(mut self) -> Self {
444 self.body_argument = true;
445 self
446 }
447
448 /// How many argument slots precede the body slot.
449 pub fn arg_slot_count(&self) -> usize {
450 slot_bearing(&self.args)
451 }
452
453 /// The payload rebuilt from its projection, the value
454 /// [`project`](PresPayload::project) produced.
455 ///
456 /// # Errors
457 ///
458 /// Returns a [`DeserializeError`] that identifies
459 /// `flm.pres.latex.environment` when the projection is not a map, when
460 /// `name` is missing or is not a string,
461 /// when `args` is present and is not a list of shape names, when
462 /// `verbatim` is missing or is not a boolean, or when `packed` or `body`
463 /// is present and is not a boolean.
464 pub fn from_projection(
465 value: &SerialValue,
466 ) -> Result<LatexEnvironmentPayload, DeserializeError> {
467 let e = entries(ENVIRONMENT, value)?;
468 Ok(LatexEnvironmentPayload {
469 name: string(ENVIRONMENT, e, "name")?,
470 args: shapes(ENVIRONMENT, e, "args")?,
471 verbatim: boolean(ENVIRONMENT, e, "verbatim")?,
472 packed: optional_flag(ENVIRONMENT, e, "packed")?,
473 body_argument: optional_flag(ENVIRONMENT, e, "body")?,
474 })
475 }
476}
477
478impl PresPayload for LatexEnvironmentPayload {
479 fn project(&self) -> SerialValue {
480 let mut entries = vec![("name", text(&self.name))];
481 push_shapes(&mut entries, "args", &self.args);
482 entries.push(("verbatim", SerialValue::Bool(self.verbatim)));
483 push_flag(&mut entries, "packed", self.packed);
484 push_flag(&mut entries, "body", self.body_argument);
485 map(entries)
486 }
487}
488
489/// The LaTeX text that a copy of a template writes at one of the template's
490/// placeholders: for a kept user definition, the parameter (`#1`) that a
491/// placeholder of one of its arguments becomes, or a part of the test that a
492/// conditional becomes; for a list label template, the `enumitem`
493/// command that a number format becomes.
494///
495/// It is not a construct payload. It is the element value carried by a copy
496/// of a template node, made when a lowering rule copies the template, and it
497/// says what LaTeX the copy writes without the node becoming a construct at
498/// that point. Two readers act on it, which is why it belongs to the LaTeX
499/// family rather than to one of the features that create it:
500///
501/// - the placeholder rule ([`placeholder_rule`]), which stages a raw LaTeX
502/// node ([`LatexRawPayload`]) holding the text;
503/// - the emitter, for a copy inside **verbatim content**, which a backend
504/// copies character for character rather than lowering it, so that no
505/// rule ever reaches the copy. Inside verbatim content the text is written
506/// as LaTeX, not as verbatim characters, as a template requires when it
507/// refers to one of its arguments inside a verbatim block or an inline
508/// verbatim command.
509#[derive(Debug, Clone, PartialEq, Eq)]
510pub struct LatexPoint {
511 /// The LaTeX to write at the point.
512 pub text: String,
513}
514
515impl LatexPoint {
516 /// The value that writes `text`.
517 pub fn new(text: impl Into<String>) -> LatexPoint {
518 LatexPoint { text: text.into() }
519 }
520}
521
522/// Stages one copy of a template node that carries LaTeX text: a childless
523/// copy of `at` (a placeholder node of a compiled template, or a node that
524/// represents a part of the LaTeX that a placeholder or a part of a
525/// conditional of the template becomes) carrying `text`
526/// as a [`LatexPoint`].
527///
528/// The node's own argument nodes (the braces of `#{name}`, a conditional's
529/// branches) are not copied: the rule that lowers the copy reads the carried
530/// text and nothing else. The node extension is built directly rather than
531/// through the language's usual constructor (`Flm::make_node_ext`), because
532/// that constructor resolves the element from the node's specification and
533/// would return the element every compiled template shares, without the
534/// `LatexPoint` value.
535pub(crate) fn stamp_point(
536 at: &NodeRef<'_, Flm>,
537 text: impl Into<String>,
538 cx: &mut RestageContext<'_, Flm, (), ()>,
539) -> Result<BuildId, LowerError> {
540 let Some(data) = at.callable() else {
541 return Err(LowerError::structure(
542 "a template node that is to carry LaTeX text must be a command, an environment or a \
543 special character sequence such as `~`, and this one is none of these",
544 ));
545 };
546 let kind = NodeKind::callable(CallableData {
547 callable_type: data.callable_type,
548 name: data.name.clone(),
549 spec: Arc::clone(&data.spec),
550 arguments: ParsedArguments::empty(),
551 slots: ParsedSlots::empty(),
552 invocation_syntax: data.invocation_syntax.clone(),
553 });
554 let mut element = (**element_of(at)).clone();
555 element.value = Some(Arc::new(LatexPoint::new(text)));
556 let ext = FlmNodeExt::new(Arc::new(element));
557 cx.builder()
558 .add(kind, at.span().clone(), Arc::clone(at.parsing_state()), Vec::new(), ext, ())
559 .map_err(|error| LowerError::Build { detail: error.to_string() })
560}
561
562/// The name of the placeholder rule, `flm.placeholder.lower.latex-recomposed`.
563pub const PLACEHOLDER_LATEX_RULE: &str = "flm.placeholder.lower.latex-recomposed";
564
565/// The implementation of [`PLACEHOLDER_LATEX_RULE`]: it lowers a copy of a
566/// template node that carries a [`LatexPoint`] to a raw LaTeX node
567/// ([`LatexRawPayload`]) holding the carried text: the parameter that a
568/// placeholder of a kept user definition becomes, a part of the test that a
569/// conditional becomes, or the `enumitem` command that a number format of a
570/// list's own label template becomes.
571///
572/// A placeholder node that carries no `LatexPoint` means that the rule which
573/// copied the template broke its invariant; the rule then fails with a
574/// structure error ([`LowerError`]).
575#[derive(Debug, Default, Clone, Copy)]
576pub struct PlaceholderLatexRule;
577
578impl Lower for PlaceholderLatexRule {
579 fn lower(
580 &self,
581 node: NodeRef<'_, Flm>,
582 cx: &mut LowerCx<'_>,
583 lw: &mut dyn Lowerer,
584 ) -> Result<Lowering, LowerError> {
585 let point = element_value::<LatexPoint>(&node).ok_or_else(|| {
586 LowerError::structure(
587 "a placeholder lowered for the latex-recomposed backend must be a copy of a \
588 template node that carries its LaTeX text",
589 )
590 })?;
591 let written = lw.pres_with(
592 cx,
593 &ElementName::from(RAW),
594 LatexRawPayload::new(point.text.clone()),
595 Vec::new(),
596 )?;
597 Ok(Lowering::Emit(vec![written]))
598 }
599}
600
601/// The placeholder rule ([`PlaceholderLatexRule`]), ready to be registered by
602/// the `latex` feature ([`super::LatexFamily`]). It is written for the
603/// language's placeholder element, produces `flm.pres.latex.raw`, and is the
604/// default on the `latex-recomposed` backend only, the only backend for which
605/// templates are copied with `LatexPoint` values.
606pub fn placeholder_rule() -> LoweringRule {
607 LoweringRule::new(
608 PLACEHOLDER_LATEX_RULE,
609 PLACEHOLDER,
610 LoweringDecl::new().produces(RAW),
611 Arc::new(PlaceholderLatexRule),
612 DefaultMark::OnBackends(vec![RECOMPOSED_BACKEND.into()]),
613 )
614 .docs(
615 "a placeholder of a template copy, or a part of one of its conditionals, lowers to the \
616 LaTeX text the copy carries for it",
617 )
618}
619
620/// The payload of `flm.pres.latex.raw`: LaTeX text the emitter writes byte
621/// for byte. The node is childless.
622///
623/// A rule uses a raw node only where the bytes are LaTeX syntax that no other
624/// construct expresses and that need no escaping: a blank line that writes a
625/// paragraph break, a parameter (`#1`) inside a recomposed definition, a line
626/// of a display-math environment rebuilt from its equation lines, a literal
627/// character's spelling as the author wrote it (`\%`, `\textbackslash`).
628/// Document text never goes here: it goes through the emitter's escaping as a
629/// text node. Neither does any structure that a macro or environment construct
630/// can carry, because a raw node carries no structure, no source position for
631/// its parts and no escaping, so the lowered output loses everything that
632/// makes it inspectable.
633///
634/// The text must not hold a `%` that starts a LaTeX comment: the sink refuses
635/// such a text ([`super::sink::LatexSink::raw`]).
636#[derive(Debug, Clone, PartialEq, Eq, Default)]
637pub struct LatexRawPayload {
638 /// The LaTeX text, written as it is.
639 pub text: String,
640}
641
642impl LatexRawPayload {
643 /// A raw node's payload holding `text`.
644 pub fn new(text: impl Into<String>) -> LatexRawPayload {
645 LatexRawPayload { text: text.into() }
646 }
647
648 /// The payload rebuilt from its projection, the value
649 /// [`project`](PresPayload::project) produced.
650 ///
651 /// # Errors
652 ///
653 /// Returns a [`DeserializeError`] that identifies `flm.pres.latex.raw`
654 /// when the projection is not a map or `text` is missing or is not a
655 /// string.
656 pub fn from_projection(value: &SerialValue) -> Result<LatexRawPayload, DeserializeError> {
657 let e = entries(RAW, value)?;
658 Ok(LatexRawPayload { text: string(RAW, e, "text")? })
659 }
660}
661
662impl PresPayload for LatexRawPayload {
663 fn project(&self) -> SerialValue {
664 map(vec![("text", text(&self.text))])
665 }
666}
667
668/// The largest number of arguments a definition written into the style file
669/// takes one by one: nine, because a LaTeX macro body can refer to nine
670/// parameters (`#1` to `#9`).
671///
672/// A definition of more arguments takes them all in one group instead, one
673/// pair of braces around each ([`LatexDefinitionPayload::packed`]), and its
674/// body reads them out of that group. The number is a threshold, not a cap:
675/// a definition of any number of arguments can be written.
676pub const PLAIN_ARGUMENT_LIMIT: usize = 9;
677
678/// What a `flm.pres.latex.definition` node defines: a macro, an
679/// environment, or a feature's declaration.
680#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
681pub enum LatexDefinitionKind {
682 /// A macro: `\providecommand\<name>[<n>]{<body>}`, or `\long\def` where
683 /// the definition is written under the document's own name
684 /// ([`is_bare`](LatexDefinitionPayload::is_bare)), or
685 /// `\ProvideDocumentCommand\<name>{+m …}` — `\DeclareDocumentCommand`
686 /// under the document's own name — where the definition is asked to be
687 /// robust ([`robust`](field@LatexDefinitionPayload::robust)).
688 Macro,
689 /// An environment:
690 /// `\ProvideDocumentEnvironment{<name>}{+m …}{<begin>}{<end>}`, or
691 /// `\DeclareDocumentEnvironment` where the definition is written under the
692 /// document's own name.
693 Environment,
694 /// A **declaration**: LaTeX that makes something other than a command
695 /// definition — `\newtheorem{lemma}[theorem]{Lemma}`, `\newcounter{…}` —
696 /// written as `\ifcsname <name>\endcsname\else <body>\fi`, so that
697 /// it runs only where the control sequence `\<name>` is not defined yet.
698 ///
699 /// A declaration defines no command of its own that a guard such as
700 /// `\providecommand` could test, so the definition gives the control
701 /// sequence it is guarded on ([`name`](field@LatexDefinitionPayload::name)):
702 /// the environment it declares (`lemma` tests `\lemma`), or the
703 /// counter's register (`c@theorem`). Something of that name defined
704 /// before the style file is loaded (by the document class, a package or
705 /// the author's own preamble) is kept, and the declaration does nothing.
706 /// It takes no argument, its whole text is its `body` slot, and it is
707 /// always written by a feature from its own configuration
708 /// ([`feature`](field@LatexDefinitionPayload::feature)).
709 Declaration,
710}
711
712impl LatexDefinitionKind {
713 /// The kind's stable name: `macro`, `environment` or `declaration`.
714 pub fn as_str(self) -> &'static str {
715 match self {
716 LatexDefinitionKind::Macro => "macro",
717 LatexDefinitionKind::Environment => "environment",
718 LatexDefinitionKind::Declaration => "declaration",
719 }
720 }
721
722 /// The kind of a stable name, if any.
723 pub fn parse(name: &str) -> Option<LatexDefinitionKind> {
724 match name {
725 "macro" => Some(LatexDefinitionKind::Macro),
726 "environment" => Some(LatexDefinitionKind::Environment),
727 "declaration" => Some(LatexDefinitionKind::Declaration),
728 _ => None,
729 }
730 }
731}
732
733impl fmt::Display for LatexDefinitionKind {
734 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
735 f.write_str(self.as_str())
736 }
737}
738
739/// The payload of `flm.pres.latex.definition`: a macro or environment
740/// definition, or a feature's declaration
741/// ([`LatexDefinitionKind::Declaration`]), that the style file must hold for
742/// the recomposed LaTeX to compile.
743///
744/// The content slots hold the definition's LaTeX as lowered content: `body`
745/// ([`BODY_SLOT`](crate::stdlib::backends::pres::BODY_SLOT)) for a macro and
746/// a declaration, or [`BEGIN_SLOT`] and [`END_SLOT`] for an environment. The
747/// definition takes [`args`](Self::args) arguments, all of them mandatory, and
748/// the body refers to them as `#1` to `#<args>`; every call writes exactly that
749/// many groups, in that order, and nothing else, so LaTeX reads no argument
750/// syntax of its own at a call. An environment may take one more argument, its
751/// own body ([`body_argument`](Self::body_argument)); a call writes no group
752/// for that one, since what a call writes between `\begin` and `\end` is
753/// already the body.
754///
755/// The lowering rule that recomposes a kept user definition
756/// ([`kept`](crate::stdlib::features::userdefs::kept)) stages a definition
757/// node at every use site of the definition, since rules keep no state. The
758/// emitter writes nothing in the node's place: it records the definition for
759/// the style file once per name, so that the style file holds it exactly
760/// once.
761#[derive(Debug, Clone, PartialEq, Eq)]
762pub struct LatexDefinitionPayload {
763 /// What the node defines: a macro, an environment or a feature's
764 /// declaration ([`LatexDefinitionKind`]).
765 pub kind: LatexDefinitionKind,
766 /// The name defined, without a backslash (`flmUDhello`, `flmUEnote`);
767 /// for a declaration, the name of the control sequence it is guarded on
768 /// (`lemma`, `c@theorem`).
769 pub name: String,
770 /// The name the document declared, without a backslash (`hello`,
771 /// `note`), where it differs from [`name`](Self::name) — a recomposed
772 /// user definition is renamed under a prefix of its own
773 /// ([`recomposed_name`](super::names::recomposed_name)). The style
774 /// file writes it in the comment line above the definition, so that an
775 /// author reading the file recognizes their own definition. Equal to
776 /// [`name`](Self::name) unless
777 /// [`with_source_name`](Self::with_source_name) said otherwise, which is
778 /// how a definition written under the document's own name is told from one
779 /// written under a prefix ([`is_bare`](Self::is_bare)).
780 pub source_name: String,
781 /// How many arguments the definition takes. Any number: past
782 /// [`PLAIN_ARGUMENT_LIMIT`] the call hands them over in one group
783 /// ([`packed`](field@Self::packed)) rather than one group each.
784 pub args: usize,
785 /// Whether the call hands the arguments over in **one** group instead of
786 /// one group each: `\<name>{{first}{second}…}`, one pair of braces around
787 /// each argument, in argument order.
788 ///
789 /// This is how a definition of more than [`PLAIN_ARGUMENT_LIMIT`]
790 /// arguments is written, since a LaTeX macro body can refer to only nine
791 /// parameters. The definition then takes one LaTeX parameter regardless of
792 /// [`args`](field@Self::args), and its body reads argument *n* out of
793 /// it with the style file's accessor
794 /// ([`ARG_COMMAND`](super::preamble::ARG_COMMAND), `\flmArg{<n>}{#1}`).
795 /// A definition of nine effective arguments or fewer keeps the plain
796 /// form, where the body refers to `#1` to `#<args>` directly.
797 pub packed: bool,
798 /// Whether the definition is written as a **robust** command rather than
799 /// as a plain expandable macro: the render option
800 /// [`robust_names`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::robust_names)
801 /// lists the name the document declared.
802 ///
803 /// A *robust* command is one LaTeX writes into a file of its own — the
804 /// table of contents, the auxiliary file — as the call itself rather than
805 /// as what the call stands for, and runs when that file is read back. The
806 /// macro is then written with the document command interface,
807 /// `\ProvideDocumentCommand\<name>{+m …}` with one `+m` per argument
808 /// (`\DeclareDocumentCommand` where the definition is written under the
809 /// document's own name, [`is_bare`](Self::is_bare)), where an expandable
810 /// one is `\providecommand\<name>[<n>]`. The `+` makes each argument
811 /// long, so it may hold a paragraph break, as `\providecommand` does of
812 /// itself.
813 ///
814 /// Only a macro carries this. An environment is robust however it is
815 /// written — `\begin` opens a group, runs the begin code, sets the body
816 /// and runs the end code, none of which expansion alone could produce — so
817 /// the option changes nothing for one, and the projection refuses a payload
818 /// that claims it ([`from_projection`](Self::from_projection)).
819 pub robust: bool,
820 /// Whether the definition takes what is written between `\begin` and `\end`
821 /// as an **argument** of its own rather than letting LaTeX set it between
822 /// the begin and the end code: the environment's argument specification
823 /// ends with `+b`, after one `+m` per argument, and the body is the last
824 /// parameter — `#<args + 1>`, or `#2` where the arguments are
825 /// [`packed`](field@Self::packed) into one group.
826 ///
827 /// An environment written this way carries its whole definition in the
828 /// [`BEGIN_SLOT`], with the body's parameter written where the definition
829 /// wants the body, and its [`END_SLOT`] is empty. This is how a definition
830 /// is written that wants the body somewhere a begin code and an end code
831 /// cannot put it — inside a command's argument, or in two places.
832 ///
833 /// Only an environment can take one: a macro's `body` slot is its whole
834 /// definition already, so [`LatexDefinitionKind::Macro`] leaves this
835 /// `false`.
836 pub body_argument: bool,
837 /// The feature that writes this definition from its own configuration,
838 /// where the definition is not one the document declared: `defterm` for
839 /// the environment of a defined term, whose begin code is the configured
840 /// lead-in. `None` for a recomposed user definition.
841 ///
842 /// Such a definition is written under the name it is given and always
843 /// **guarded** — `\providecommand`, `\ProvideDocumentEnvironment`, the
844 /// test `\ifcsname` around a declaration — like
845 /// a definition piece, so that a definition of that name the user made
846 /// before the style file is loaded wins; the style file writes it before
847 /// the document's own definitions, under a comment line that gives the
848 /// feature's name ([`RecomposedDefinition::feature`](super::RecomposedDefinition::feature)).
849 /// A feature stages one where the definition's text must be lowered — a
850 /// template of its configuration, written through the ordinary rules —
851 /// which a definition piece, fixed text, cannot hold.
852 pub feature: Option<String>,
853}
854
855impl LatexDefinitionPayload {
856 /// A definition of `kind` named `name` taking `args` arguments, declared
857 /// in the document under that same name and calling them one group each.
858 pub fn new(kind: LatexDefinitionKind, name: impl Into<String>, args: usize) -> Self {
859 let name = name.into();
860 LatexDefinitionPayload {
861 kind,
862 source_name: name.clone(),
863 name,
864 args,
865 packed: false,
866 robust: false,
867 body_argument: false,
868 feature: None,
869 }
870 }
871
872 /// The same definition written by the feature `feature` from its own
873 /// configuration ([`feature`](field@Self::feature)): guarded, under the
874 /// name it is given.
875 pub fn of_feature(mut self, feature: impl Into<String>) -> Self {
876 self.feature = Some(feature.into());
877 self
878 }
879
880 /// The same definition declared in the document under `source_name`, the
881 /// author's own spelling, which the style file writes in the comment line
882 /// above the definition ([`source_name`](Self::source_name)).
883 pub fn with_source_name(mut self, source_name: impl Into<String>) -> Self {
884 self.source_name = source_name.into();
885 self
886 }
887
888 /// The same definition with its arguments handed over in one group
889 /// ([`packed`](Self::packed)).
890 pub fn packed(mut self) -> Self {
891 self.packed = true;
892 self
893 }
894
895 /// The same definition written as a robust command
896 /// ([`robust`](field@Self::robust)). A macro only: an environment is robust
897 /// however it is written, and the projection refuses one that claims it.
898 pub fn robust(mut self) -> Self {
899 self.robust = true;
900 self
901 }
902
903 /// The same definition taking its body as its last argument
904 /// ([`body_argument`](Self::body_argument)). An environment only: a macro
905 /// has no body of its own to take, and the projection refuses one that
906 /// claims it ([`from_projection`](Self::from_projection)).
907 pub fn body_argument(mut self) -> Self {
908 self.body_argument = true;
909 self
910 }
911
912 /// Whether the definition is written under the name the document spelled
913 /// rather than under a prefix of its own. The render option
914 /// [`bare_names`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::bare_names)
915 /// asked for it, so the definition is meant to replace any definition that
916 /// LaTeX or a package makes under that name, and the emitter writes it
917 /// unconditionally rather than guarded. A feature's definition
918 /// ([`feature`](field@Self::feature)) is never bare.
919 pub fn is_bare(&self) -> bool {
920 self.feature.is_none() && self.name == self.source_name
921 }
922
923 /// The payload rebuilt from its projection, the value
924 /// [`project`](PresPayload::project) produced.
925 ///
926 /// # Errors
927 ///
928 /// Returns a [`DeserializeError`] that identifies
929 /// `flm.pres.latex.definition` when the projection is not a map, when
930 /// `kind` is missing or is not the name of a kind
931 /// ([`LatexDefinitionKind::parse`]), when `name` is missing or is not a
932 /// string, when `source` or `feature` is present and is not a string, when
933 /// a declaration gives no `feature`, takes arguments or is `packed`, when
934 /// `args` is present and is not a whole number of arguments, when `packed`,
935 /// `robust` or `body` is present and is not a boolean, when `body` is set
936 /// on anything but an environment (a macro's `body` slot is already its
937 /// whole definition), or when `robust` is set on anything but a macro (an
938 /// environment is robust however it is written). Any number of arguments
939 /// is accepted: past [`PLAIN_ARGUMENT_LIMIT`] the call hands them over in
940 /// one group.
941 pub fn from_projection(
942 value: &SerialValue,
943 ) -> Result<LatexDefinitionPayload, DeserializeError> {
944 let e = entries(DEFINITION, value)?;
945 let kind = string(DEFINITION, e, "kind")?;
946 let kind = LatexDefinitionKind::parse(&kind)
947 .ok_or_else(|| bad(DEFINITION, format!("unknown kind `{kind}`")))?;
948 let args = definition_arity(e, "args")?;
949 let packed = optional_flag(DEFINITION, e, "packed")?;
950 let robust = optional_flag(DEFINITION, e, "robust")?;
951 let body_argument = optional_flag(DEFINITION, e, "body")?;
952 if body_argument && kind != LatexDefinitionKind::Environment {
953 return Err(bad(DEFINITION, String::from("`body` is only for an environment")));
954 }
955 if robust && kind != LatexDefinitionKind::Macro {
956 return Err(bad(DEFINITION, String::from("`robust` is only for a macro")));
957 }
958 let name = string(DEFINITION, e, "name")?;
959 let source_name = match field(e, "source") {
960 None => name.clone(),
961 Some(SerialValue::Str(s)) => s.clone(),
962 Some(other) => {
963 return Err(bad(DEFINITION, format!("`source` must be a string, found {other:?}")));
964 }
965 };
966 let feature = match field(e, "feature") {
967 None | Some(SerialValue::Null) => None,
968 Some(SerialValue::Str(s)) => Some(s.clone()),
969 Some(other) => {
970 return Err(bad(DEFINITION, format!("`feature` must be a string, found {other:?}")));
971 }
972 };
973 if kind == LatexDefinitionKind::Declaration && (feature.is_none() || args != 0 || packed) {
974 return Err(bad(
975 DEFINITION,
976 String::from(
977 "a declaration must give `feature`, take no argument and not be packed",
978 ),
979 ));
980 }
981 Ok(LatexDefinitionPayload {
982 kind,
983 name,
984 source_name,
985 args,
986 packed,
987 robust,
988 body_argument,
989 feature,
990 })
991 }
992}
993
994impl PresPayload for LatexDefinitionPayload {
995 fn project(&self) -> SerialValue {
996 let mut entries = vec![("kind", text(self.kind.as_str())), ("name", text(&self.name))];
997 if self.source_name != self.name {
998 entries.push(("source", text(&self.source_name)));
999 }
1000 if self.args != 0 {
1001 entries.push(("args", SerialValue::Int(self.args as i64)));
1002 }
1003 push_flag(&mut entries, "packed", self.packed);
1004 push_flag(&mut entries, "robust", self.robust);
1005 push_flag(&mut entries, "body", self.body_argument);
1006 if let Some(feature) = &self.feature {
1007 entries.push(("feature", text(feature)));
1008 }
1009 map(entries)
1010 }
1011}
1012
1013/// How many arguments a definition takes, read from the key `name`, `args`;
1014/// an absent or null key reads as none.
1015fn definition_arity(
1016 entries: &[(String, SerialValue)],
1017 name: &str,
1018) -> Result<usize, DeserializeError> {
1019 match field(entries, name) {
1020 None | Some(SerialValue::Null) => Ok(0),
1021 Some(SerialValue::Int(count)) => usize::try_from(*count)
1022 .map_err(|_| bad(DEFINITION, format!("`{name}` must not be negative, found {count}"))),
1023 Some(other) => {
1024 Err(bad(DEFINITION, format!("`{name}` must be a whole number, found {other:?}")))
1025 }
1026 }
1027}
1028
1029// --- readers and registration ---------------------------------------------------------
1030
1031/// Registers `parse` as the reader of `element`'s payload.
1032fn reader<P: PresPayload>(
1033 readers: &mut PayloadReaders,
1034 element: &'static str,
1035 parse: fn(&SerialValue) -> Result<P, DeserializeError>,
1036) {
1037 readers.register(element, move |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
1038 parse(value).map(|payload| Arc::new(payload) as Arc<dyn PresPayload>)
1039 });
1040}
1041
1042/// The payload readers of the four construct elements: what a reading session
1043/// ([`reader_with`](crate::dump::session::reader_with)) needs, beside the
1044/// shared vocabulary's own ([`payload_readers`](crate::stdlib::backends::pres::payload_readers)), to read a stored
1045/// lowered tree of a LaTeX backend back into typed payloads.
1046///
1047/// # Examples
1048///
1049/// ```
1050/// use flm_core::stdlib::backends::latex::construct::{ALL, payload_readers};
1051///
1052/// assert_eq!(payload_readers().len(), ALL.len());
1053/// ```
1054pub fn payload_readers() -> PayloadReaders {
1055 let mut readers = PayloadReaders::new();
1056 reader(&mut readers, MACRO, LatexMacroPayload::from_projection);
1057 reader(&mut readers, ENVIRONMENT, LatexEnvironmentPayload::from_projection);
1058 reader(&mut readers, RAW, LatexRawPayload::from_projection);
1059 reader(&mut readers, DEFINITION, LatexDefinitionPayload::from_projection);
1060 readers
1061}
1062
1063/// Registers the four construct elements with their payload types. The
1064/// `latex` feature ([`super::LatexFamily`]) calls this from its own
1065/// registration; a second registration in one registry declares the elements
1066/// twice and fails the build.
1067///
1068/// # Errors
1069///
1070/// Returns the [`BuildError`] the feature builder raises for a presentation
1071/// element already declared in this registry.
1072pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
1073 b.presentation_element::<LatexMacroPayload>(
1074 MACRO,
1075 "a LaTeX macro call: the command name and one content slot per argument",
1076 )?;
1077 b.presentation_element::<LatexEnvironmentPayload>(
1078 ENVIRONMENT,
1079 "a LaTeX environment: the content slots of its arguments, then the body",
1080 )?;
1081 b.presentation_element::<LatexRawPayload>(RAW, "LaTeX text written byte for byte")?;
1082 b.presentation_element::<LatexDefinitionPayload>(
1083 DEFINITION,
1084 "a macro or environment definition, or a feature's declaration, written to the style \
1085 file and never where the node occurs",
1086 )?;
1087 Ok(())
1088}
1089
1090/// The content of the content slot named `name` on `node`, the first one of
1091/// that name when the name repeats; `None` when the node has no such slot.
1092pub fn slot_named<'t>(node: &NodeRef<'t, Flm>, name: &str) -> Option<NodeSlice<'t, Flm>> {
1093 let slots = node.slots()?;
1094 let index = slots.iter().position(|slot| slot.name() == Some(name))?;
1095 node.slot_content_nodes(index)
1096}
1097
1098/// The arguments of a macro or environment node paired with their content
1099/// slots: for each shape in `args`, the shape and the content of its content
1100/// slot — `None` for a [`Star`](LatexArgShape::Star), which has no content
1101/// slot, and for an argument the node carries no content slot for (a
1102/// hand-built node; a node a rule built always has them).
1103///
1104/// The content slots named [`ARG_SLOT`] are taken in order and matched to the
1105/// shapes that have a content slot, in order; any other content slot (an
1106/// environment's `body`) is skipped.
1107pub fn arg_slots<'t>(
1108 node: &NodeRef<'t, Flm>,
1109 args: &[LatexArgShape],
1110) -> Vec<(LatexArgShape, Option<NodeSlice<'t, Flm>>)> {
1111 let mut arg_indexes = node
1112 .slots()
1113 .map(|slots| {
1114 slots
1115 .iter()
1116 .enumerate()
1117 .filter(|(_, slot)| slot.name() == Some(ARG_SLOT))
1118 .map(|(index, _)| index)
1119 .collect::<Vec<_>>()
1120 })
1121 .unwrap_or_default()
1122 .into_iter();
1123 args.iter()
1124 .map(|shape| {
1125 let content = if shape.has_slot() {
1126 arg_indexes.next().and_then(|index| node.slot_content_nodes(index))
1127 } else {
1128 None
1129 };
1130 (*shape, content)
1131 })
1132 .collect()
1133}
1134
1135#[cfg(test)]
1136mod tests {
1137 use super::*;
1138
1139 #[test]
1140 fn the_placeholder_rule_requires_nothing_and_is_marked_for_the_recomposed_backend() {
1141 // The placeholder rule is marked for the recomposed backend, so the
1142 // plan's ladder offers it on no other; it requires nothing, so its
1143 // selection demands nothing of a plan.
1144 let placeholder = placeholder_rule();
1145 assert_eq!(placeholder.element, PLACEHOLDER);
1146 assert!(placeholder.decl.requires.is_empty());
1147 assert_eq!(placeholder.decl.produces, [ElementName::from(RAW)]);
1148 assert!(placeholder.default.is_specific_to(&RECOMPOSED_BACKEND.into()));
1149 }
1150
1151 #[test]
1152 fn a_macro_projection_omits_an_empty_argument_list() {
1153 let payload = LatexMacroPayload::new("relax", []);
1154 assert_eq!(payload.project(), map(vec![("name", text("relax"))]));
1155 let payload = LatexMacroPayload::new(
1156 "section",
1157 [LatexArgShape::Star, LatexArgShape::Optional, LatexArgShape::Mandatory],
1158 );
1159 assert_eq!(payload.slot_count(), 2);
1160 assert_eq!(
1161 payload.project(),
1162 map(vec![
1163 ("name", text("section")),
1164 ("args", SerialValue::List(vec![text("star"), text("optional"), text("mandatory")])),
1165 ])
1166 );
1167 }
1168
1169 #[test]
1170 fn a_definition_projects_its_arity_and_omits_an_empty_one() {
1171 let payload = LatexDefinitionPayload::new(LatexDefinitionKind::Macro, "flmUDplain", 0);
1172 assert!(payload.is_bare());
1173 assert_eq!(
1174 payload.project(),
1175 map(vec![("kind", text("macro")), ("name", text("flmUDplain"))])
1176 );
1177 // Three arguments, under a prefix: the name the document declared is
1178 // projected beside the name defined, and the definition is not bare.
1179 let payload = LatexDefinitionPayload::new(LatexDefinitionKind::Macro, "flmUDaround", 3)
1180 .with_source_name("around");
1181 assert!(!payload.is_bare());
1182 assert_eq!(
1183 payload.project(),
1184 map(vec![
1185 ("kind", text("macro")),
1186 ("name", text("flmUDaround")),
1187 ("source", text("around")),
1188 ("args", SerialValue::Int(3)),
1189 ])
1190 );
1191 }
1192
1193 #[test]
1194 fn every_payload_reads_back_from_its_projection() {
1195 let macro_ = LatexMacroPayload::new("verbcode", [LatexArgShape::EscVerb]);
1196 assert_eq!(LatexMacroPayload::from_projection(¯o_.project()).unwrap(), macro_);
1197 let env = LatexEnvironmentPayload::new("flmVerbatimCode", [LatexArgShape::Optional])
1198 .verbatim();
1199 assert_eq!(LatexEnvironmentPayload::from_projection(&env.project()).unwrap(), env);
1200 let raw = LatexRawPayload::new("\n\n");
1201 assert_eq!(LatexRawPayload::from_projection(&raw.project()).unwrap(), raw);
1202 let def = LatexDefinitionPayload::new(LatexDefinitionKind::Environment, "flmUEnote", 4)
1203 .with_source_name("note");
1204 assert_eq!(LatexDefinitionPayload::from_projection(&def.project()).unwrap(), def);
1205 // A definition of no arguments, and one whose call packs them.
1206 let none = LatexDefinitionPayload::new(LatexDefinitionKind::Macro, "flmUDplain", 0);
1207 assert_eq!(LatexDefinitionPayload::from_projection(&none.project()).unwrap(), none);
1208 let packed = LatexDefinitionPayload::new(LatexDefinitionKind::Macro, "flmUDbig", 12).packed();
1209 assert_eq!(LatexDefinitionPayload::from_projection(&packed.project()).unwrap(), packed);
1210 // A packed call carries the same flag, so the call and the definition
1211 // agree about the one group.
1212 let call = LatexMacroPayload::new("flmUDbig", [LatexArgShape::Mandatory; 12]).packed();
1213 assert_eq!(LatexMacroPayload::from_projection(&call.project()).unwrap(), call);
1214 let env = LatexEnvironmentPayload::new("flmUEbig", [LatexArgShape::Mandatory; 12]).packed();
1215 assert_eq!(LatexEnvironmentPayload::from_projection(&env.project()).unwrap(), env);
1216 // An environment call that says its definition takes the body as an
1217 // argument: the same `body` key as the definition's, so a call and its
1218 // definition cannot disagree about what the body reaches LaTeX as.
1219 let grabbed = LatexEnvironmentPayload::new("flmUEwrap", [LatexArgShape::Mandatory])
1220 .body_argument();
1221 assert_eq!(LatexEnvironmentPayload::from_projection(&grabbed.project()).unwrap(), grabbed);
1222 assert_eq!(
1223 grabbed.project(),
1224 map(vec![
1225 ("name", text("flmUEwrap")),
1226 ("args", SerialValue::List(vec![text("mandatory")])),
1227 ("verbatim", SerialValue::Bool(false)),
1228 ("body", SerialValue::Bool(true)),
1229 ])
1230 );
1231 // An environment that takes its body as its last argument, plain and
1232 // packed: the flag belongs to the definition alone, a call writing the
1233 // body where it always did.
1234 let body = LatexDefinitionPayload::new(LatexDefinitionKind::Environment, "flmUEwrap", 1)
1235 .with_source_name("wrap")
1236 .body_argument();
1237 assert_eq!(LatexDefinitionPayload::from_projection(&body.project()).unwrap(), body);
1238 let both = LatexDefinitionPayload::new(LatexDefinitionKind::Environment, "flmUEbig", 12)
1239 .packed()
1240 .body_argument();
1241 assert_eq!(LatexDefinitionPayload::from_projection(&both.project()).unwrap(), both);
1242 // A macro asked to be robust, alone and packed: the flag says the
1243 // definition is written through the document command interface, which
1244 // is a property of the definition's head and of nothing a call writes.
1245 let declaration = LatexDefinitionPayload::new(LatexDefinitionKind::Declaration, "lemma", 0)
1246 .of_feature("theorems");
1247 assert_eq!(LatexDefinitionPayload::from_projection(&declaration.project()).unwrap(), declaration);
1248 // A declaration is a feature's and takes no argument.
1249 let orphan = LatexDefinitionPayload::new(LatexDefinitionKind::Declaration, "lemma", 0);
1250 assert!(LatexDefinitionPayload::from_projection(&orphan.project()).is_err());
1251 let with_args = LatexDefinitionPayload::new(LatexDefinitionKind::Declaration, "lemma", 1)
1252 .of_feature("theorems");
1253 assert!(LatexDefinitionPayload::from_projection(&with_args.project()).is_err());
1254 let robust = LatexDefinitionPayload::new(LatexDefinitionKind::Macro, "flmUDhello", 1)
1255 .with_source_name("hello")
1256 .robust();
1257 assert_eq!(LatexDefinitionPayload::from_projection(&robust.project()).unwrap(), robust);
1258 let robust_packed = LatexDefinitionPayload::new(LatexDefinitionKind::Macro, "flmUDbig", 12)
1259 .packed()
1260 .robust();
1261 assert_eq!(
1262 LatexDefinitionPayload::from_projection(&robust_packed.project()).unwrap(),
1263 robust_packed
1264 );
1265 }
1266
1267 #[test]
1268 fn a_macro_definition_that_claims_a_body_argument_is_refused() {
1269 // Only an environment has a body to take as an argument: a macro's own
1270 // `body` slot is its whole definition already.
1271 let refused = LatexDefinitionPayload::from_projection(&map(vec![
1272 ("kind", text("macro")),
1273 ("name", text("flmUDwrap")),
1274 ("body", SerialValue::Bool(true)),
1275 ]));
1276 assert!(refused.is_err());
1277 }
1278
1279 #[test]
1280 fn an_environment_definition_that_claims_robustness_is_refused() {
1281 // An environment is robust however it is written — `\begin` opens a
1282 // group and runs code, which expansion alone could not do — so there
1283 // is nothing for the flag to ask for, and a payload carrying it is a
1284 // structure error rather than an author's mistake.
1285 let refused = LatexDefinitionPayload::from_projection(&map(vec![
1286 ("kind", text("environment")),
1287 ("name", text("flmUEnote")),
1288 ("robust", SerialValue::Bool(true)),
1289 ]));
1290 assert!(refused.is_err());
1291 }
1292
1293 #[test]
1294 fn a_malformed_projection_is_refused() {
1295 let refused = LatexMacroPayload::from_projection(&map(vec![("name", SerialValue::Int(1))]));
1296 assert!(refused.is_err());
1297 let refused = LatexMacroPayload::from_projection(&map(vec![
1298 ("name", text("x")),
1299 ("args", SerialValue::List(vec![text("braced")])),
1300 ]));
1301 assert!(refused.is_err());
1302 // Any number of arguments is accepted: past nine the call packs
1303 // ([`PLAIN_ARGUMENT_LIMIT`]), so there is no cap left to refuse.
1304 let many = LatexDefinitionPayload::from_projection(&map(vec![
1305 ("kind", text("macro")),
1306 ("name", text("x")),
1307 ("args", SerialValue::Int(20)),
1308 ("packed", SerialValue::Bool(true)),
1309 ]))
1310 .unwrap();
1311 assert_eq!(many.args, 20);
1312 assert!(many.packed);
1313 let refused = LatexDefinitionPayload::from_projection(&map(vec![
1314 ("kind", text("macro")),
1315 ("name", text("x")),
1316 ("args", SerialValue::Int(3)),
1317 ("packed", SerialValue::Int(1)),
1318 ]));
1319 assert!(refused.is_err());
1320 let refused = LatexDefinitionPayload::from_projection(&map(vec![
1321 ("kind", text("macro")),
1322 ("name", text("x")),
1323 ("args", SerialValue::Str(String::from("three"))),
1324 ]));
1325 assert!(refused.is_err());
1326 }
1327
1328 #[test]
1329 fn the_shape_names_round_trip_and_only_the_star_has_no_slot() {
1330 for shape in LatexArgShape::ALL {
1331 assert_eq!(LatexArgShape::parse(shape.as_str()), Some(shape));
1332 assert_eq!(shape.has_slot(), shape != LatexArgShape::Star);
1333 }
1334 assert_eq!(LatexArgShape::parse("braced"), None);
1335 }
1336}