flm_core/stdlib/features/userdefs/kept.rs
1//! The lowering rules for a kept use site of a user definition: what a
2//! lowering rule does with a use site of a `per-plan` definition that a plan
3//! keeps in the tree (the capability `flm.userdefs.kept`) instead of
4//! expanding it.
5//!
6//! A *kept definition* is a user definition whose use sites a plan left in the
7//! tree (the `flm.userdefs.kept` alternative of the [`userdefs`](super)
8//! feature): a lowering rule either writes the use site as a canonical call
9//! beside the definition for the [style
10//! file](crate::stdlib::backends::latex::style) (the `.sty` file written
11//! beside the recomposed LaTeX document), or instantiates the template when
12//! the definition cannot be written back as LaTeX or a rule needs a
13//! placeholder's characters. A plan for the `latex-recomposed` backend keeps
14//! the use sites of every `per-plan` definition, so this module decides how an
15//! author's definitions appear in the recomposed LaTeX; the rendering guide
16//! describes the result for authors ([user definitions in the recomposed
17//! LaTeX](crate::guide::rendering#user-definitions-in-the-recomposed-latex)).
18//! Under the expanded alternative (the default) the expand pass replaces every
19//! use site before lowering, and the definition's `expand-in-tree` rule
20//! ([`super::lowering`]) only gives the element a rule.
21//!
22//! # The two rules
23//!
24//! Every `per-plan` definition registers one rule of each kind for its element:
25//!
26//! | rule | name | default | what it does |
27//! |---|---|---|---|
28//! | `instantiate-at-lowering` ([`InstantiateAtLowering`]) | `flm.userdefs.<kind>.<name>.lower.instantiate-at-lowering` | never; a plan request selects it by name | expands the use site through the expand pass and lowers the result in its place |
29//! | `emit-call` ([`EmitCall`]) | `flm.userdefs.<kind>.<name>.lower.emit-call` | on the `latex-recomposed` backend | writes the use site as a call of the definition, and the definition itself into the style file; instantiates the use site instead when the definition is not recomposable or a rule of its template needs a placeholder's characters |
30//!
31//! Both rules require `flm.userdefs.kept`, so selecting either puts the
32//! `flm.userdefs.keep` marker stage into the plan and excludes the expansion of
33//! the `per-plan` definitions. A definition whose expansion policy is `always`
34//! has neither rule: its use sites never reach a lowering rule.
35//!
36//! # How the rule of a definition is chosen
37//!
38//! A `per-plan` definition has three rules for its element: `expand-in-tree`,
39//! the default on every backend ([`DefaultMark::Everywhere`]); `emit-call`,
40//! the default on the `latex-recomposed` backend alone
41//! ([`DefaultMark::OnBackends`]); and `instantiate-at-lowering`, never a
42//! default ([`DefaultMark::Never`]). The rule selection order
43//! ([`SelectedRules`](crate::core::plan::SelectedRules)) decides between them
44//! without a conflict: a rule the plan request
45//! ([`PlanRequest`](crate::core::plan::PlanRequest)) prefers by name comes first,
46//! then a rule marked default on the backend, then a rule marked default
47//! everywhere. The recomposed LaTeX therefore gets `emit-call` and every other
48//! backend gets `expand-in-tree`: a plan for the `latex-recomposed` backend
49//! holds `flm.userdefs.keep` and not `flm.userdefs.expand`, and a plan for any
50//! other backend (`html`, `text`) the other way round, unless the plan request
51//! prefers `instantiate-at-lowering` by name, which keeps the use sites on that
52//! backend too.
53//!
54//! # How `instantiate-at-lowering` lowers a use site
55//!
56//! The rule copies the use site into a [synthesized
57//! value](crate::guide::concepts_overview#synthesized-values) of its own (a
58//! small tree built during the run, outside the document's trees;
59//! [`copy_run_into_value`]) and expands it with the expand pass ([`expand`])
60//! over every definition, the `always` ones included, under the definition's
61//! expansion depth limit ([`UserDefinition::recursion_limit`], the limit of the
62//! feature's configuration). The diagnostics of the expansion (a depth limit
63//! reached, a placeholder without a value) are reported through the
64//! [`Lowerer`]. The rule then splices the expanded value
65//! ([`Lowerer::splice`]): [value
66//! catch-up](crate::guide::concepts_overview#value-catch-up) runs the plan's
67//! rewrite stages and the per-tree stages over it, and its nodes are lowered
68//! through the rules. On a backend whose plan lays out the trees in paragraphs
69//! (`html`, `text`), the block-structure pass lays out the expanded value
70//! during that catch-up, so the use site is written exactly as in the expanded
71//! document.
72//!
73//! # Recomposable definitions
74//!
75//! `emit-call` writes a definition as one LaTeX definition only when it is
76//! *recomposable*: when a backend can write it as one definition of its own
77//! output language. [`NotRecomposable`] lists the reasons a definition may not
78//! be: its nature (a special character sequence), its author's choice (the
79//! expansion policy `always`), an error already reported (a refused
80//! definition), or the use, in its template or a default value, of a
81//! `per-plan` definition that is not recomposable; two further reasons exist
82//! only for definitions declared in Rust by an extension. Every other definition is recomposable:
83//!
84//! - arguments of every shape a definition can declare, at any position: a
85//! `{…}` group, an optional `[…]` group, a characters-only group, a
86//! key-value group, a verbatim argument, a `*` marker and a tack-on
87//! argument;
88//! - a template and default values that are content around their placeholders
89//! and their conditionals;
90//! - an environment's template, regardless of what it does with its body;
91//! - any number of arguments;
92//! - a definition that uses itself, directly or through other definitions,
93//! which becomes a LaTeX definition that calls itself, so that LaTeX runs the
94//! recursion;
95//! - a name declared once for text mode and once for mathematics mode, which
96//! becomes two LaTeX definitions under two names, the [per-mode
97//! definitions](crate::stdlib::backends::latex::names#per-mode-definitions);
98//! each call is written under the name for the parsing mode of its use
99//! site.
100//!
101//! All but one of the decisions about the shape of the LaTeX definition are
102//! taken when the registry is built: the `userdefs` feature's late-initialization build
103//! hook calls [`record_recomposability`], which records on each definition
104//! whether it is recomposable and the arguments its calls write
105//! ([`RegistryBuildFacts`], read back through
106//! [`UserDefinition::recomposable`] and
107//! [`UserDefinition::effective_signature`]). The remaining decision is taken
108//! when the template is lowered, and it is the same at every use site: whether a
109//! rule of the template needs the characters of a placeholder (next section).
110//! A use site of a recomposable definition is written as a call in every other
111//! case.
112//!
113//! *Verbatim blocks* (content that LaTeX reads character by character from the
114//! file it is written in) do not prevent recomposition. Wherever a verbatim
115//! block reaches LaTeX inside a group that LaTeX reads as tokens (an argument
116//! of a call, the body of a LaTeX definition), the `latex-recomposed` emitter
117//! writes it as a call of
118//! [`\flmVerbatimBlock`](crate::stdlib::backends::latex::preamble::VERBATIM_BLOCK_COMMAND),
119//! which rebuilds the block where it is called. The emitter decides this from
120//! where the block is written; the rules of this module do nothing for it.
121//!
122//! # Where a rule needs an argument's characters
123//!
124//! A placeholder becomes a LaTeX parameter **only where the template sets it
125//! as content**: a rule that sets content lowers the placeholder as content,
126//! and the placeholder rule of the LaTeX family (the parts every LaTeX backend
127//! shares, [`crate::stdlib::backends::latex`];
128//! [`PlaceholderLatexRule`](crate::stdlib::backends::latex::PlaceholderLatexRule))
129//! writes the parameter, which LaTeX
130//! replaces by what a call passes. A rule that needs the **characters** of
131//! content instead (a link's address, a reference's label, a term's target,
132//! verbatim content, anything computed from them) reads them through
133//! [`chars_at_lowering`](crate::core::lowering::chars_at_lowering), or, where it
134//! computes from content as written with its markup (a term's target, a list
135//! label template), through
136//! [`spelling_at_lowering`](crate::core::lowering::spelling_at_lowering). A
137//! placeholder has no characters until the template is expanded, so the rule
138//! returns [`LowerError::PlaceholderCharacters`].
139//!
140//! `emit-call` lowers the template as a synthesized value. When that lowering
141//! returns `PlaceholderCharacters`, the rule expands the use site instead of
142//! writing a call (as for a definition that is not recomposable) and stages
143//! nothing for the style file (to *stage* a node is to build it into the
144//! lowered tree through the [`Lowerer`]). The template is the same at every use site, so
145//! every use site of the definition is expanded, and the definition is never
146//! written as a LaTeX definition. For example, the use sites of a definition
147//! whose template is `\verbcode{#1}`, `\url{#1}`, `\href{https://doi.org/#1}{#1}`,
148//! `\ref{#1}`, `\ref{sec:#1}`, `\eqref{#1}`, `\hyperref[#1]{…}` or
149//! `\term[#1]{…}` are expanded, while a template `see #1`, `\emph{#1}` or
150//! `\ifblank{#1}{…}{…}` is written as a LaTeX definition. Nothing inspects the
151//! shape of the template, so an element that a later feature adds behaves the
152//! same way as long as it reads characters through those two functions. The
153//! mathematics writer does the same for a use site inside mathematics.
154//!
155//! The diagnostics and requirements of the discarded lowering are dropped with
156//! it ([`Lowerer::splice`]). Each use site of such a definition therefore
157//! lowers the template once, discards that lowering and then lowers its
158//! expansion: the lowering is done twice per use site.
159//!
160//! # A template that declares a reference point
161//!
162//! A reference point is one place in a document that can be referred to,
163//! numbered, or given an anchor ([`RefPoint`](crate::model::aspects::RefPoint)).
164//! `emit-call` lowers a kept definition's template as a synthesized value (the
165//! body of the LaTeX definition, which the style file holds once per name),
166//! and `instantiate-at-lowering` lowers each use site's expansion as one too. A
167//! synthesized value may state no fact about the document as a whole: its value
168//! catch-up refuses a [table piece](crate::core::data::table::PieceClass) (the
169//! part of a table one stage invocation produced) that declares a label. A template that
170//! declares a reference point carrying a label (a construct followed by
171//! `\label`, a labeled xnote, a defined term) therefore cannot be lowered there,
172//! and neither can a template holding a `\label` whose text a placeholder
173//! completes: value catch-up does not recognize that `\label` as a label, so
174//! this module refuses such a template itself, before lowering it.
175//!
176//! Every use site of such a definition is refused with the Error diagnostic
177//! [`KeptTemplateDeclaresPoint`], which gives the definition and the node of
178//! the template that declares the point, and lowers to a childless
179//! `flm.pres.unsupported` stand-in node, which the `latex-recomposed` backend
180//! writes as a comment. The remedy is the expansion policy
181//! [`Always`](ExpandPolicy::Always): the use sites are then expanded in the
182//! document before the labels are read, and each label is the document's own.
183//! Selecting `instantiate-at-lowering` is no remedy, because the instance is a
184//! synthesized value too and is refused in the same way.
185//!
186//! A reference in a template declares no reference point. A reference whose
187//! target is fixed is written as a reference anywhere is, and one whose target
188//! a placeholder completes needs that placeholder's characters, so the use
189//! sites are expanded (previous section).
190//!
191//! # The canonical call
192//!
193//! **A call is written as the definition's name followed by one brace group
194//! per effective argument, and nothing else.** FLM has already read the
195//! document, so at every use site the value of every argument, and whether the
196//! author wrote it, are known when the call is written. Written this way, the
197//! call leaves LaTeX nothing to parse: no bracket it could take for an optional
198//! argument, no star to look for, no default to fill in, and the LaTeX
199//! definition needs no interface for reading arguments.
200//!
201//! An *effective argument* is one brace group of a call, in the order of the
202//! definition's *effective signature* ([`EffectiveSignature`]):
203//!
204//! - first one **value** per declared argument a template can refer to (the
205//! declared arguments that are not tack-on arguments), in the order
206//! declared, holding what the expansion would substitute for a
207//! placeholder of that argument: the content the use site wrote; or, where
208//! the use site left the argument out, the argument's declared default
209//! value, instantiated at that use site
210//! ([`ModeVariant::instantiate_default`]) and lowered in its place; or
211//! nothing. The argument's declared shape plays no part: a key-value
212//! argument's value is the group the use site wrote, keys included, since
213//! FLM never reads the keys separately; a verbatim argument's value is the
214//! characters written between its delimiters, written as text like any other
215//! content, since the delimiters belong to the use site's syntax. The group a
216//! call passes is therefore always an ordinary brace group, and no LaTeX
217//! verbatim argument (`v`) is ever declared;
218//! - then one **flag** per declared argument the template asks a *provided*
219//! question about (whether the use site wrote it), in the order declared,
220//! holding `\BooleanTrue` where the use site wrote that argument and
221//! `\BooleanFalse` where it did not.
222//!
223//! A **tack-on argument** (the argument that absorbs the field macros, such
224//! as a `\label{…}`, written at its position in a call, after the arguments
225//! declared before it;
226//! [fields](crate::guide::concepts_overview#fields-data-a-construct-reads)) is
227//! neither. A template cannot refer to one: what the call absorbed is whole
228//! macros, which have no meaning as the value of a parameter, so a reference
229//! to one refuses the definition when it is compiled, on every backend
230//! ([`DefinitionProblem::TackOnPlaceholder`](crate::lang::rewrites::userdefs::DefinitionProblem::TackOnPlaceholder)).
231//! A definition may declare a tack-on argument and not refer to it: it is
232//! recomposed like any other, its calls write no group for that argument, and
233//! what they absorb is not written. A placeholder that would give a template
234//! access to the absorbed macros is not implemented.
235//!
236//! For example, where `\around` declares the arguments `[pre]{key}[post]` with
237//! the default value `p.` for `post`, `\around[see]{Knuth}` is written
238//! `\flmUDaround{see}{Knuth}{p.}`. The signature is computed once, when the
239//! registry is built, so that the definition and every call of it agree on the
240//! position of each group.
241//!
242//! # The definition written into the style file
243//!
244//! **A recomposed macro is a long, expandable macro over mandatory arguments**,
245//! written `\providecommand\<name>[<n>]{<body>}`, and a recomposed environment
246//! is a document environment with one `+m` per effective argument. Long, so an
247//! argument may hold a paragraph break; expandable, so a call works inside
248//! `\edef`, a PDF bookmark and a case change; guarded (`\providecommand`), so a
249//! definition of that name that the author's class or preamble made before the
250//! style file is loaded is the one used. Two render options of the
251//! `latex-recomposed` backend change this form, and nothing else does:
252//!
253//! - A definition whose name the render option
254//! [`bare_names`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::bare_names)
255//! lists is written under the name the document gives it, without a guard
256//! (`\long\def`), since the name is listed so that the document's definition
257//! replaces LaTeX's own.
258//! - A macro whose name the render option
259//! [`robust_names`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::robust_names)
260//! lists is written `\ProvideDocumentCommand\<name>{+m …}`, one `+m` per
261//! effective argument (`\DeclareDocumentCommand` where both options list
262//! it), which makes it a robust command, protected from expansion, rather than
263//! an expandable macro.
264//!
265//! The emitter of the `latex-recomposed` backend
266//! ([`crate::stdlib::backends::latex_recomposed::emit`]) writes these forms
267//! from the definition construct's payload.
268//!
269//! **An environment's body.** LaTeX sets an environment's body between the
270//! begin code and the end code. A template that refers to the body once, among
271//! its own top-level nodes, is cut in two there. A template that refers to the
272//! body anywhere else (inside a group, inside another command's argument, or in
273//! two places), or not at all, is written whole as the begin code, and the
274//! environment takes its body as a last argument `+b`; a template that does
275//! not refer to its body never writes that argument, so LaTeX reads the body
276//! and drops it, as FLM's expansion does. A call is the same either way.
277//!
278//! Every kept definition is written under a prefixed name of its own
279//! ([`recomposed_name`]), at the definition and at every call: the macro
280//! `\hello` as `\flmUDhello`, the environment `note` as `flmUEnote`, a macro
281//! whose name holds anything other than ASCII letters under an encoding in
282//! letters only ([the names of recomposed
283//! definitions](crate::guide::rendering#the-names-of-recomposed-definitions)).
284//! The definition therefore cannot replace a command that the
285//! `latex-recomposed` output or LaTeX relies on. A macro and an environment of
286//! one name are two definitions in FLM and remain two in the output, each under
287//! the prefix of its kind. Whether a definition overrides another element plays
288//! no part in any of this: the expansion policy alone decides whether a use
289//! site is expanded or kept.
290//!
291//! **More than nine effective arguments: the packed group.** A LaTeX macro body
292//! can refer to nine parameters, and values and flags count together, so a
293//! definition of six arguments that asks about five of them already has eleven
294//! effective arguments. Past nine ([`PLAIN_ARGUMENT_LIMIT`]), a call passes
295//! every effective argument in **one** brace group, one pair of braces around
296//! each, in the same order: `\flmUDbig{{a}{b}{c}…}`. The definition then takes
297//! one parameter, and its body reads effective argument *n* out of it with the
298//! style file's accessor: `\flmArg{<n>}{#1}` for a value, `\flmIfArgTF` for a
299//! flag and `\flmIfArgBlankTF` for a blank test, which the definition piece
300//! (a unit of LaTeX definitions registered under an identifier;
301//! [`LatexPreambleDef`](crate::stdlib::backends::latex::LatexPreambleDef))
302//! [`preamble::user_args_piece`] defines and a packed definition requires. A
303//! definition of nine effective arguments or fewer keeps the plain form, with
304//! `#1` to `#9`. No number of arguments prevents recomposition.
305//!
306//! # The conditionals of a template
307//!
308//! A template may ask about its own arguments with the conditional commands of
309//! the [template language](crate::lang::rewrites::userdefs::template), and
310//! what each conditional becomes is decided once, when the style file's
311//! definition is written, from the definition's arguments and its effective
312//! signature. **No conditional prevents recomposition.** Each becomes one of
313//! three things:
314//!
315//! - the branch its answer selects, where the answer cannot change from one use
316//! site to the next: a question about an argument that is always written, a
317//! question about an argument with a declared default value (which always
318//! has a value), a *value*, *no value* or *provided* question whose test
319//! argument is not exactly one placeholder, or a blank test whose test
320//! argument holds content other than placeholders, or nothing;
321//! - LaTeX's `\IfBooleanTF` over the flag the call passes, where the answer
322//! depends on whether the use site wrote the argument (a *provided*
323//! question, or a *value* or *no value* question about an argument that can
324//! be left out and has no default value);
325//! - the style file's blank test (`\flmIfBlankTF`, the definition piece
326//! [`IF_BLANK`](crate::stdlib::backends::latex::preamble::IF_BLANK)) over
327//! the values, for `\ifblank` and `\notblank`.
328//!
329//! What a conditional becomes is written into the copy of the template that
330//! `emit-call` lowers (section "The copy of the template" below), so a use
331//! site carries none of it.
332//!
333//! A placeholder is written as the LaTeX parameter of its argument's value,
334//! `#1` to `#9`. Every value group holds what FLM substitutes for that
335//! placeholder, so nothing needs a guard or a second form: the value group of a
336//! `*` marker holds the `*` the author wrote, LaTeX's `-NoValue-` marker never
337//! reaches a recomposed body, and a blank test over several placeholders is one
338//! test over their values together.
339//!
340//! # Use sites inside mathematics
341//!
342//! The `math-passthrough` feature's rules for the `latex-recomposed` backend write every
343//! mathematics region (`\(…\)`, `\[…\]`, each line of a display-math
344//! environment) from its nodes, through this module's mathematics writer
345//! ([`write_math_run`]): the source byte for byte, except at a use site of a
346//! user definition, a source comment and a text command (`\text{…}`, whose
347//! argument is document text). The mathematics itself is never lowered
348//! through the rules; a source comment and a text command are, so that the
349//! comment is written by the writer of LaTeX output that every LaTeX backend
350//! shares ([`LatexSink`](crate::stdlib::backends::latex::LatexSink)) and the
351//! text is escaped as
352//! text anywhere else is. A use site of a
353//! recomposable definition is written as its canonical call (the definition's
354//! recomposed name and one brace group per effective argument, the content of
355//! each group written by the same writer, so that a use site nested in an
356//! argument is handled too), and the definition construct is staged before it,
357//! exactly as `emit-call` stages it in text. A definition that applies in
358//! mathematics mode alone, and a definition used both in text and inside
359//! mathematics, therefore each reach the style file once. A use site of a
360//! definition that is not recomposable, or whose template needs a
361//! placeholder's characters, is written as its expansion, the one
362//! `instantiate-at-lowering` computes, written back as LaTeX source. A template for
363//! mathematics mode is written into its definition construct by the same
364//! writer, each placeholder as its parameter.
365//!
366//! # The copy of the template
367//!
368//! A placeholder node of a compiled template (`#1`, `#{name}`) carries only the
369//! reference as written; what it refers to is recorded beside the compiled
370//! template, keyed by the node, and value catch-up does not keep that key. So
371//! `emit-call` lowers a copy of the template's nodes, made by this module, in
372//! which every placeholder node is replaced by a childless copy whose element
373//! value is a [`LatexPoint`] (the LaTeX text that a copy of a template writes
374//! at one of its placeholders). The LaTeX family's placeholder rule
375//! ([`PlaceholderLatexRule`](crate::stdlib::backends::latex::PlaceholderLatexRule))
376//! writes that text and nothing else: the parameter of the argument's value,
377//! `#<i + 1>` for the argument at index `i` (in a packed definition, the
378//! accessor `\flmArg{<i + 1>}{#1}`), the same for a numbered and a named
379//! reference, since both refer to an argument index, with the definition's
380//! argument number offset applied. The same copy replaces each
381//! conditional by the parts of the LaTeX it becomes, each a `LatexPoint` node,
382//! with the branches it keeps between them. The body placeholder of an
383//! environment whose template is cut in two never reaches the rule: `emit-call`
384//! cuts the template at it before lowering the two halves.
385//!
386//! The copy belongs to this module rather than to the template compiler, so
387//! that the compiled template stays as the language layer made it (one element
388//! value shared by every placeholder), and every decision about what the
389//! definition's body says is taken in one place, where the copy is made.
390//!
391//! # Items
392//!
393//! - [`InstantiateAtLowering`] and [`instantiate_at_lowering_rule`], with
394//! [`INSTANTIATE_AT_LOWERING`] and [`instantiate_rule_name`].
395//! - [`EmitCall`] and [`emit_call_rule`], with [`EMIT_CALL`] and
396//! [`emit_call_rule_name`].
397//! - [`record_recomposability`], called by the `userdefs` feature when the
398//! registry is built.
399//! - [`KeptTemplateDeclaresPoint`], the condition of a template that declares
400//! a reference point.
401//! - [`write_math_run`], [`stage_math_run`] and [`MathPiece`], the mathematics
402//! writer that the `math` library's line writer and the `math-passthrough`
403//! feature's rules call.
404//! - [`register`], the peer declarations the `userdefs` feature registers once.
405
406// The rule selection order already ranks a backend's default above a general
407// one and a rule that is never a default below both, so it settles which of the
408// three rules applies with no mechanism of its own; `expand-in-tree` stays the
409// default everywhere, so a registry holding definitions renders on every
410// backend. Recomposability is decided once, when the registry is built, because
411// every use site needs the answer and it depends on the registry alone. Rules
412// keep no state, so the definition construct travels with each use site and the
413// emitter writes it once per name; its placeholders are stamped on this module's
414// copy of the template, so that the compiled template, the language layer's,
415// does not change for what one backend reads. Each conditional is classified on
416// its own, so that the common templates come out as one would write them in
417// LaTeX by hand.
418
419use std::cell::RefCell;
420use std::collections::BTreeSet;
421use std::sync::Arc;
422
423use techy::core::Lang;
424use techy::core::node::{BuildId, NodeKind, NodeRef, NodeTree};
425use techy::error::{Diagnostic, DiagnosticInfo};
426use techy::latexlike::{InvocationSyntaxData, Mode};
427use techy::source::SourceSpan;
428use techy::transform::{Restage, RestageContext, RestageError, RestageVisitor};
429
430use crate::core::lowering::{
431 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
432};
433use crate::core::registry::{BuildError, FeatureBuilder};
434use crate::lang::copy::{ValueContent, copy_run_into_value};
435use crate::lang::flm::FlmCallableType;
436use crate::lang::guard::{self, GuardPolicy};
437use crate::lang::mint::{DefinitionShape, FlmArgumentParser, is_math_text_command};
438use crate::lang::rewrites::userdefs::definition::{is_tack_on, substituted_argument_nodes};
439use crate::lang::rewrites::userdefs::instantiate::{is_blank_node, is_noise};
440use crate::lang::rewrites::userdefs::template::{Branches, Conditional, ConditionalTest};
441use crate::lang::rewrites::userdefs::{
442 CompiledTemplate, Definition, DefinitionKind, DefinitionModes, EffectiveSignature,
443 ExpandOptions, ExpandPolicy, ExpandSet, ModeVariant, NotRecomposable, PlaceholderTarget,
444 RegistryBuildFacts, UserDefinition, expand,
445};
446use crate::lang::mint::is_field_named;
447use crate::lang::text::read_chars;
448use crate::lang::{Flm, FlmDiagnostics};
449use crate::model::aspects::Referenceable;
450use crate::model::element::{element_of, element_value};
451use crate::model::names::{ElementName, Name, RuleName};
452use crate::stdlib::backends::latex::construct::{
453 ARG_SLOT, BEGIN_SLOT, DEFINITION, END_SLOT, ENVIRONMENT, MACRO, PLAIN_ARGUMENT_LIMIT, RAW,
454 stamp_point,
455};
456use crate::stdlib::backends::latex::preamble;
457use crate::stdlib::backends::latex::{
458 LatexArgShape, LatexDefinitionKind, LatexDefinitionMode, LatexDefinitionPayload,
459 LatexEnvironmentPayload, LatexMacroPayload, LatexPoint, LatexRawPayload, is_family_name,
460 recomposed_name,
461};
462use crate::stdlib::backends::latex_recomposed::{BACKEND, LatexRecomposedRenderOptions};
463use crate::stdlib::backends::lowering::lower_run;
464use crate::stdlib::backends::pres::{BODY_SLOT, recompose_source};
465use crate::stdlib::features::refs::{LABEL_FIELD, TARGET_ARG};
466
467use super::{KEPT, element_name};
468
469/// The last segment of the name of every `instantiate-at-lowering` rule,
470/// `instantiate-at-lowering`.
471pub const INSTANTIATE_AT_LOWERING: &str = "instantiate-at-lowering";
472
473/// The last segment of the name of every `emit-call` rule, `emit-call`.
474pub const EMIT_CALL: &str = "emit-call";
475
476/// What a canonical call writes for the flag of an argument the use site
477/// wrote: `\BooleanTrue`, LaTeX's own true value, which `\IfBooleanTF` reads.
478const BOOLEAN_TRUE: &str = "\\BooleanTrue";
479
480/// What a canonical call writes for the flag of an argument the use site did
481/// not write, `\BooleanFalse`.
482const BOOLEAN_FALSE: &str = "\\BooleanFalse";
483
484/// Returns the name of the rule of `definition` whose last segment is
485/// `variant`: `flm.userdefs.<kind>.<name>.lower.<variant>`, the definition's
486/// element name followed by `.lower.` and `variant`.
487fn variant_rule_name(definition: &Definition, variant: &str) -> RuleName {
488 RuleName::from(format!("{}.lower.{variant}", element_name(definition)))
489}
490
491/// Returns the name of the `instantiate-at-lowering` rule of `definition`:
492/// `flm.userdefs.<kind>.<name>.lower.instantiate-at-lowering`.
493///
494/// # Examples
495///
496/// ```
497/// use flm_core::stdlib::features::userdefs::{Definition, instantiate_rule_name};
498///
499/// let definition = Definition::macro_("foo", Vec::new());
500/// assert_eq!(
501/// instantiate_rule_name(&definition),
502/// "flm.userdefs.macro.foo.lower.instantiate-at-lowering"
503/// );
504/// ```
505pub fn instantiate_rule_name(definition: &Definition) -> RuleName {
506 variant_rule_name(definition, INSTANTIATE_AT_LOWERING)
507}
508
509/// Returns the name of the `emit-call` rule of `definition`:
510/// `flm.userdefs.<kind>.<name>.lower.emit-call`.
511///
512/// # Examples
513///
514/// ```
515/// use flm_core::stdlib::features::userdefs::{Definition, emit_call_rule_name};
516///
517/// let definition = Definition::environment("note", Vec::new());
518/// assert_eq!(emit_call_rule_name(&definition), "flm.userdefs.environment.note.lower.emit-call");
519/// ```
520pub fn emit_call_rule_name(definition: &Definition) -> RuleName {
521 variant_rule_name(definition, EMIT_CALL)
522}
523
524// --- recomposability -----------------------------------------------------------------------------
525
526/// Returns the compiled templates a definition is recomposed from: those for
527/// text mode, or those for mathematics mode when the definition applies in
528/// mathematics mode alone. `None` for a definition without compiled
529/// templates.
530fn recomposed_variant(definition: &UserDefinition) -> Option<Arc<ModeVariant>> {
531 let compiled = definition.compiled()?;
532 compiled.variant(Mode::Text).or_else(|| compiled.variant(Mode::Math)).cloned()
533}
534
535/// Returns the token of an argument shape that a recomposed definition cannot
536/// take, when the argument's parser reports that no LaTeX argument expresses it
537/// ([`DefinitionShape::NoShape`]); `None` otherwise.
538///
539/// **No standard argument parser is refused**: each returns
540/// [`DefinitionShape::Value`]. A canonical call writes one brace group per
541/// effective argument, so the form of an argument in the FLM source never
542/// reaches LaTeX: a key-value argument is a value like any other, since FLM
543/// never reads the keys separately, and a verbatim argument is the characters
544/// the use site wrote between its delimiters, lowered in its value group like
545/// any other content.
546///
547/// A *tack-on* argument (the argument that absorbs the field macros, such as a
548/// `\label{…}`, written at its position in a call) is not refused either: a
549/// definition may declare one and is still recomposed. It carries no effective
550/// argument, because no template may refer to it (see the module
551/// documentation), so a call writes no group for it.
552///
553/// The argument parser decides
554/// ([`FlmArgumentParser::definition_shape`]), so a parser that a later version
555/// adds gives its own answer, and a parser that no LaTeX argument expresses
556/// makes its definition expanded rather than written as a LaTeX definition.
557fn shape_token(kind: &dyn FlmArgumentParser) -> Option<&'static str> {
558 match kind.definition_shape() {
559 DefinitionShape::Value => None,
560 DefinitionShape::NoShape { token } => Some(token),
561 }
562}
563
564// --- the effective signature, and what each conditional becomes ------------------------------------
565
566/// Whether an argument parsed by `kind` can be left out at a use site, so that
567/// a template can meaningfully ask whether the use site wrote it. The parser
568/// decides ([`can_match_empty`](techy::core::constructs::ArgumentParser::can_match_empty)).
569///
570/// A mandatory argument, a characters-only argument and a verbatim argument
571/// are always written (a verbatim argument is delimited text the use site must
572/// write), so every question about one is decided when the style file is
573/// written. The three standard kinds that can be left out are an optional
574/// argument, a key-value argument (parsed exactly like an optional one) and a
575/// `*` marker. A tack-on argument is absent where the use site wrote no field
576/// macro at its position, but no template can ask about one (a reference to it
577/// refuses the definition, which is then not compiled), so the question is
578/// never asked about it.
579// techy's argument-parser trait already asks this question, so FLM's trait does
580// not ask it a second time: two answers to one question could disagree.
581fn can_be_absent(kind: &Arc<dyn FlmArgumentParser>) -> bool {
582 kind.can_match_empty()
583}
584
585/// Returns the one node of a conditional's test argument that a value test
586/// reads, when there is exactly one; `None` otherwise. Comments and whitespace
587/// around it are skipped, as the tests themselves skip them.
588fn single_test_node<'t>(node: &NodeRef<'t, Flm>) -> Option<NodeRef<'t, Flm>> {
589 let argument = node.argument_content_nodes(0)?;
590 let mut significant = argument.iter().filter(|child| !is_noise(child));
591 let first = significant.next()?;
592 significant.next().is_none().then_some(first)
593}
594
595/// Returns the argument that a placeholder node of `template` refers to, as an
596/// index in the order the arguments are written; `None` for any other node, a
597/// placeholder of the body included.
598fn placeholder_argument(template: &CompiledTemplate, node: &NodeRef<'_, Flm>) -> Option<usize> {
599 if node.callable_type() != Some(FlmCallableType::Placeholder) {
600 return None;
601 }
602 match template.placeholder(node.id())?.target {
603 PlaceholderTarget::Argument(index) => Some(index),
604 _ => None,
605 }
606}
607
608/// One definition as the recomposition writes it: its declaration, the
609/// compiled templates recomposed, and the effective signature its calls
610/// write.
611///
612/// Every decision about what the LaTeX definition's body says and what one
613/// call writes is made through this type: which effective argument holds an
614/// argument's value, which one holds its flag, and what each conditional of
615/// the template becomes.
616struct Recomposition<'t> {
617 definition: &'t Definition,
618 variant: &'t ModeVariant,
619 signature: &'t EffectiveSignature,
620}
621
622impl Recomposition<'_> {
623 /// Returns the parser the declared argument `index` was declared with;
624 /// `None` when the definition declares no such argument.
625 fn kind(&self, index: usize) -> Option<&Arc<dyn FlmArgumentParser>> {
626 self.definition.args.get(index).map(|arg| &arg.kind)
627 }
628
629 /// Whether the declared argument `index` has a default value, which is
630 /// written at every call whose use site leaves the argument out.
631 fn has_default(&self, index: usize) -> bool {
632 self.variant.default_of(index).is_some()
633 }
634
635 /// Returns the effective argument that holds the value of the declared
636 /// argument `index`, counting from one: the parameter by which the
637 /// definition's body refers to it.
638 fn value(&self, index: usize) -> Option<usize> {
639 self.signature.value_position(index)
640 }
641
642 /// Returns the effective argument that holds the flag of the declared
643 /// argument `index`, counting from one, when the template asks whether the
644 /// use site wrote that argument.
645 fn flag(&self, index: usize) -> Option<usize> {
646 self.signature.flag_position(index)
647 }
648
649 /// Whether a call of this definition **packs** its arguments: passes every
650 /// effective argument in one brace group, one pair of braces around each,
651 /// because there are more of them than a LaTeX macro body can refer to
652 /// ([`PLAIN_ARGUMENT_LIMIT`]).
653 fn packs(&self) -> bool {
654 self.signature.arity() > PLAIN_ARGUMENT_LIMIT
655 }
656
657 /// Returns how the definition's body reads the effective argument
658 /// `position`, counting from one: the parameter `#<position>`, or, when
659 /// the call packs its arguments, the style file's accessor over the one
660 /// parameter the call passes (`\flmArg{<position>}{#1}`).
661 fn read(&self, position: usize) -> String {
662 if self.packs() {
663 format!("\\{}{{{position}}}{{#1}}", preamble::ARG_COMMAND)
664 } else {
665 parameter_of(position)
666 }
667 }
668
669 /// Returns how many LaTeX parameters the definition declares for its
670 /// effective arguments: one each, or one for the group when the call packs
671 /// them ([`packs`](Recomposition::packs)). An environment that takes its
672 /// body as an argument declares one more, after these
673 /// ([`body_parameter`](Recomposition::body_parameter)).
674 ///
675 /// The emitter writes the definition's head from the same count, read from
676 /// the definition payload
677 /// ([`LatexDefinitionPayload::args`](crate::stdlib::backends::latex::LatexDefinitionPayload::args)
678 /// and its `packed` flag), so the two always agree.
679 fn latex_parameters(&self) -> usize {
680 if self.packs() { 1 } else { self.signature.arity() }
681 }
682
683 /// Returns how an environment's body reaches the LaTeX the definition is
684 /// written as ([`BodyForm`]); `None` for a macro, which has no body.
685 fn body_form(&self) -> Option<BodyForm> {
686 (self.definition.kind == DefinitionKind::Environment)
687 .then(|| body_form(self.variant.template()))
688 }
689
690 /// Returns the LaTeX parameter, counting from one, that holds the body of
691 /// an environment that takes its body as an argument; `None` when the body
692 /// is not an argument (a macro, or an environment whose template is cut in
693 /// two at its body placeholder).
694 ///
695 /// The body is declared after every effective argument
696 /// ([`latex_parameters`](Recomposition::latex_parameters)), so it is the
697 /// last parameter, and it is never part of a packed group: a packed
698 /// environment declares one parameter for the group and one for the body,
699 /// which is `#2`.
700 fn body_parameter(&self) -> Option<usize> {
701 (self.body_form()? == BodyForm::Argument).then(|| self.latex_parameters() + 1)
702 }
703
704 /// Whether a flag of the call carries the answer to the question `test`
705 /// about the declared argument `index`, rather than the answer being
706 /// decided when the style file is written.
707 ///
708 /// Both the flags of an effective signature ([`effective_signature`]) and
709 /// the LaTeX of a conditional ([`Recomposition::conditional_latex`]) are
710 /// computed with this function, so the two cannot disagree. An argument
711 /// that is always written needs no flag; a *provided* question ("did the use
712 /// site write it?") always needs one; and a *no value* or *value* question
713 /// needs one exactly when the argument has no declared default value,
714 /// because the question is then the same as *provided* (with a default
715 /// value there is always a value, regardless of what the use site wrote).
716 fn flag_answers(&self, test: ConditionalTest, index: usize) -> bool {
717 if !self.kind(index).is_some_and(can_be_absent) {
718 return false;
719 }
720 match test {
721 ConditionalTest::Boolean => true,
722 ConditionalTest::NoValue | ConditionalTest::Value => !self.has_default(index),
723 ConditionalTest::Blank | ConditionalTest::NotBlank => false,
724 }
725 }
726
727 /// Returns what the test argument of the conditional `node` holds
728 /// ([`TestArgument`]).
729 fn test_argument(&self, node: &NodeRef<'_, Flm>) -> TestArgument {
730 let template = self.variant.template();
731 let mut found = TestArgument::default();
732 if let Some(argument) = node.argument_content_nodes(0) {
733 for child in argument.iter() {
734 if is_blank_node(&child) {
735 continue;
736 }
737 match placeholder_argument(template, &child) {
738 Some(index) if self.signature.value_position(index).is_some() => {
739 found.placeholders.push(index);
740 }
741 _ => found.other_content = true,
742 }
743 }
744 }
745 found.single = found.placeholders.len() == 1
746 && single_test_node(node)
747 .is_some_and(|single| placeholder_argument(template, &single).is_some());
748 found
749 }
750
751 /// Returns what the recomposition writes for the conditional `conditional`
752 /// whose test argument holds `arg`.
753 ///
754 /// Three tests (*no value*, *value*, *provided*) read a test argument that
755 /// is exactly one placeholder, and give "no" (for *value*, "yes") for any
756 /// other test argument, so a test argument of any other form is decided
757 /// here rather than when LaTeX runs. Where the question is about an
758 /// argument the use site may or may not have written, the call carries the
759 /// answer as a flag, and the body reads it with LaTeX's `\IfBooleanTF`.
760 /// Where the answer cannot change from one use site to the next, the
761 /// conditional is replaced by the branch it selects and nothing of the test
762 /// is written. The blank test reads its whole test argument: anything that
763 /// is neither a comment nor a placeholder decides the answer as "not
764 /// blank". What is left is a run of placeholders, whose values the style
765 /// file's blank test tests together; this is correct, since the run of
766 /// value groups holds no token exactly when each of them holds none.
767 fn conditional_latex(
768 &self,
769 conditional: Conditional,
770 arg: &TestArgument,
771 ) -> ConditionalLatex {
772 match conditional.test {
773 ConditionalTest::NoValue | ConditionalTest::Value | ConditionalTest::Boolean => {
774 let single = arg.single.then(|| arg.placeholders.first().copied()).flatten();
775 let Some(index) = single else {
776 // Nothing to substitute is the one thing a test argument
777 // that is not a single placeholder cannot be, so *no value*
778 // fails, *value* holds, and *provided* fails.
779 return ConditionalLatex::Settled(conditional.test == ConditionalTest::Value);
780 };
781 let flag =
782 self.flag_answers(conditional.test, index).then(|| self.flag(index)).flatten();
783 match flag {
784 // The call wrote `\BooleanTrue` or `\BooleanFalse` there;
785 // *no value* is the question the other way round.
786 Some(parameter) => ConditionalLatex::Flag {
787 parameter,
788 invert: conditional.test == ConditionalTest::NoValue,
789 },
790 // A mandatory argument is always written, and an argument
791 // with a declared default always has a value: both answer
792 // "no" to *no value* and "yes" to the other two.
793 None => {
794 ConditionalLatex::Settled(conditional.test != ConditionalTest::NoValue)
795 }
796 }
797 }
798 ConditionalTest::Blank | ConditionalTest::NotBlank => {
799 let invert = conditional.test == ConditionalTest::NotBlank;
800 if arg.other_content {
801 // Anything that is not a comment and not a placeholder is
802 // content, so the test argument is not blank.
803 return ConditionalLatex::Settled(invert);
804 }
805 if arg.placeholders.is_empty() {
806 // Nothing at all, or nothing but comments.
807 return ConditionalLatex::Settled(!invert);
808 }
809 let parameters =
810 arg.placeholders.iter().filter_map(|index| self.value(*index)).collect();
811 ConditionalLatex::Blank { parameters, invert }
812 }
813 }
814 }
815
816 /// Whether the definition's LaTeX calls the style file's blank test, the
817 /// definition piece [`preamble::IF_BLANK`]: some conditional of the
818 /// template is written as a blank test rather than decided in advance or
819 /// read from a flag.
820 fn needs_blank_test(&self) -> bool {
821 self.variant.template().tree().root().descendants().any(|node| {
822 let Some(conditional) = element_value::<Conditional>(&node) else { return false };
823 matches!(
824 self.conditional_latex(*conditional, &self.test_argument(&node)),
825 ConditionalLatex::Blank { .. }
826 )
827 })
828 }
829}
830
831/// What one conditional's test argument holds, as far as the recomposition
832/// needs it.
833#[derive(Debug, Default)]
834struct TestArgument {
835 /// Every declared argument that a placeholder of the test argument refers
836 /// to, in order.
837 placeholders: Vec<usize>,
838 /// Whether the test argument is exactly one placeholder of a declared
839 /// argument, comments and whitespace aside. The three value tests require
840 /// this before they give any answer other than "no".
841 single: bool,
842 /// Whether the test argument holds a node that is neither a comment nor a
843 /// placeholder of a declared argument. Whitespace counts here, because
844 /// FLM's blank test treats whitespace as content, so such a node decides
845 /// that test's answer as "not blank".
846 other_content: bool,
847}
848
849/// Returns the effective signature of `definition` recomposed from `variant`:
850/// one value per declared argument a template can refer to, then one flag per
851/// argument whose question needs a flag ([`Recomposition::flag_answers`]).
852///
853/// A tack-on argument has neither: no template may refer to it, so it carries
854/// no value, and a question that cannot be asked needs no flag. The values are
855/// the declared arguments that are not tack-on arguments, in declared order,
856/// which is the order [`EffectiveSignature`] records.
857fn effective_signature(definition: &Definition, variant: &ModeVariant) -> EffectiveSignature {
858 let values: Vec<usize> = definition
859 .args
860 .iter()
861 .enumerate()
862 .filter(|(_, arg)| !is_tack_on(arg))
863 .map(|(index, _)| index)
864 .collect();
865 let plain = EffectiveSignature::new(values.iter().copied(), []);
866 let recomposition = Recomposition { definition, variant, signature: &plain };
867 let template = variant.template();
868 let mut flagged = BTreeSet::new();
869 for node in template.tree().root().descendants() {
870 let Some(conditional) = element_value::<Conditional>(&node) else { continue };
871 let Some(single) = single_test_node(&node) else { continue };
872 let Some(index) = placeholder_argument(template, &single) else { continue };
873 if recomposition.flag_answers(conditional.test, index) {
874 flagged.insert(index);
875 }
876 }
877 EffectiveSignature::new(values, flagged)
878}
879
880/// What the recomposition writes for one conditional of a template.
881#[derive(Debug, Clone, PartialEq, Eq)]
882enum ConditionalLatex {
883 /// The answer does not depend on the use site, so the conditional is
884 /// replaced by the branch this answer selects, or by nothing when the
885 /// conditional has no branch for it.
886 Settled(bool),
887 /// LaTeX's `\IfBooleanTF` over the flag the call wrote: the effective
888 /// argument that holds the flag, counting from one, and whether LaTeX's
889 /// answer is the negation of what FLM asks.
890 Flag {
891 /// The LaTeX parameter number of the flag, counting from one.
892 parameter: usize,
893 /// Whether LaTeX's answer is the negation of FLM's.
894 invert: bool,
895 },
896 /// The blank test over the values of the test argument's placeholders,
897 /// written with the style file's blank test (`\flmIfBlankTF`).
898 Blank {
899 /// The LaTeX parameter numbers whose content is tested together.
900 parameters: Vec<usize>,
901 /// Whether the conditional is `\notblank`.
902 invert: bool,
903 },
904}
905
906/// Returns the LaTeX command a conditional with the branches `branches` is
907/// written as, and which of the conditional's branch arguments follow the test,
908/// in the order they are written: the command name `family` with the letters
909/// of the branches the conditional has, and the branches exchanged when LaTeX's
910/// answer is the negation of FLM's.
911fn spelling(family: &str, branches: Branches, invert: bool) -> (String, Vec<usize>) {
912 match branches {
913 Branches::Both if invert => (format!("{family}TF"), vec![2, 1]),
914 Branches::Both => (format!("{family}TF"), vec![1, 2]),
915 Branches::True => (format!("{family}{}", if invert { "F" } else { "T" }), vec![1]),
916 Branches::False => (format!("{family}{}", if invert { "T" } else { "F" }), vec![1]),
917 }
918}
919
920/// One part of what the copy of a conditional writes, in order.
921#[derive(Debug, Clone, PartialEq, Eq)]
922enum ConditionalPart {
923 /// LaTeX of the recomposition's own, byte for byte.
924 Latex(String),
925 /// The content of one of the conditional's branch arguments, by its index
926 /// in invocation order.
927 Branch(usize),
928}
929
930/// Returns what the copy of the conditional `conditional` writes, in order,
931/// given `latex`, what the recomposition decided for it
932/// ([`Recomposition::conditional_latex`]).
933///
934/// A definition whose call packs its arguments ([`Recomposition::packs`])
935/// writes the style file's own tests instead of LaTeX's, because the arguments
936/// are parts of one group rather than parameters of their own: `\flmIfArgTF`
937/// for a flag and `\flmIfArgBlankTF` for a blank test
938/// ([`preamble::user_args_piece`]). Both take a *then* and an *else* branch
939/// regardless of the branches the template's conditional has, so a
940/// conditional with one branch writes an empty group for the other.
941fn conditional_parts(
942 recomposition: &Recomposition<'_>,
943 conditional: Conditional,
944 latex: &ConditionalLatex,
945) -> Vec<ConditionalPart> {
946 // `\<name>{<test>}{<branch>}…`, the last branch closed and no more.
947 let wrap = |name: String, test: String, order: Vec<usize>| {
948 let mut parts = vec![ConditionalPart::Latex(format!("\\{name}{{{test}}}{{"))];
949 for (at, branch) in order.iter().enumerate() {
950 parts.push(ConditionalPart::Branch(*branch));
951 let close = if at + 1 == order.len() { "}" } else { "}{" };
952 parts.push(ConditionalPart::Latex(String::from(close)));
953 }
954 parts
955 };
956 // `\<name>{<test>}{#1}{<then>}{<else>}`, the branch LaTeX's answer selects
957 // first and an empty group where the template's conditional has none.
958 let wrap_packed = |name: &str, test: String, invert: bool| {
959 let mut parts = vec![ConditionalPart::Latex(format!("\\{name}{{{test}}}{{#1}}{{"))];
960 for (at, holds) in [!invert, invert].into_iter().enumerate() {
961 if let Some(branch) = conditional.branch_index(holds) {
962 parts.push(ConditionalPart::Branch(branch));
963 }
964 let close = if at == 0 { "}{" } else { "}" };
965 parts.push(ConditionalPart::Latex(String::from(close)));
966 }
967 parts
968 };
969 match latex {
970 ConditionalLatex::Settled(holds) => conditional
971 .branch_index(*holds)
972 .map(|index| vec![ConditionalPart::Branch(index)])
973 .unwrap_or_default(),
974 ConditionalLatex::Flag { parameter, invert } => {
975 if recomposition.packs() {
976 return wrap_packed(preamble::IF_ARG_COMMAND, parameter.to_string(), *invert);
977 }
978 let (name, order) = spelling("IfBoolean", conditional.branches, *invert);
979 wrap(name, parameter_of(*parameter), order)
980 }
981 ConditionalLatex::Blank { parameters, invert } => {
982 if recomposition.packs() {
983 // The arguments tested together, as the comma-separated list
984 // the style file's blank test reads.
985 let test =
986 parameters.iter().map(usize::to_string).collect::<Vec<String>>().join(",");
987 return wrap_packed(preamble::IF_ARG_BLANK_COMMAND, test, *invert);
988 }
989 let (_, order) = spelling("", conditional.branches, *invert);
990 let test: String = parameters.iter().copied().map(parameter_of).collect();
991 wrap(String::from(preamble::BLANK_COMMAND), test, order)
992 }
993 }
994}
995
996/// Returns the LaTeX parameter `number`, counting from one: `#1`, `#2`. This
997/// is the only form of a parameter, for a placeholder of an argument and for
998/// the test of a conditional alike.
999fn parameter_of(number: usize) -> String {
1000 format!("#{number}")
1001}
1002
1003/// Checks that every placeholder of a compiled tree (a template or a default
1004/// value) is a placeholder of a declared argument or of the body, written
1005/// without a substitution argument, as recomposition requires; returns
1006/// [`NotRecomposable::HookPlaceholder`] otherwise.
1007///
1008/// Where a placeholder is placed plays no part here: one placed where a rule
1009/// needs its characters is found when the template is lowered, and the use
1010/// sites are expanded then (see the [module
1011/// documentation](self#where-a-rule-needs-an-arguments-characters)).
1012///
1013/// No conditional is refused here or anywhere else: each of the fourteen is
1014/// either decided when the style file is written, written as a LaTeX test over
1015/// a flag the call carries ([`Recomposition::conditional_latex`]), or, in a
1016/// default value, evaluated at the use site where the default value is
1017/// instantiated ([`resolved_default`]).
1018fn check_placeholders(template: &CompiledTemplate) -> Result<(), NotRecomposable> {
1019 for node in template.tree().root().descendants() {
1020 if node.callable_type() != Some(FlmCallableType::Placeholder) {
1021 continue;
1022 }
1023 // Neither branch below is reachable through a `UserDefinition` today,
1024 // so no test exercises them: its vocabulary holds the arguments and
1025 // the body and no hook-answered name, a substitution argument on a
1026 // base reference is refused at compilation (the definition is then
1027 // `NotCompiled`), and every placeholder node a compiled template
1028 // holds is in its placeholder map. They guard an `Expand`
1029 // implementation that answers placeholders of its own.
1030 let Some(reference) = template.placeholder(node.id()) else {
1031 return Err(NotRecomposable::HookPlaceholder {
1032 reference: node.name().unwrap_or("").to_string(),
1033 });
1034 };
1035 if reference.substitution || matches!(reference.target, PlaceholderTarget::Extra(_)) {
1036 return Err(NotRecomposable::HookPlaceholder { reference: reference.written.clone() });
1037 }
1038 }
1039 Ok(())
1040}
1041
1042/// Whether `node` is the body placeholder of `template`: the placeholder that
1043/// stands for what a use site of the environment writes between `\begin` and
1044/// `\end`.
1045fn is_body_placeholder(template: &CompiledTemplate, node: &NodeRef<'_, Flm>) -> bool {
1046 template
1047 .placeholder(node.id())
1048 .is_some_and(|reference| reference.target == PlaceholderTarget::Body)
1049}
1050
1051/// How a recomposed environment's body reaches the LaTeX the environment is
1052/// written as.
1053///
1054/// LaTeX sets an environment's body between the begin code and the end code.
1055/// A template that refers to the body once, among its own top-level nodes, is
1056/// cut in two at that place ([`BodyForm::Split`]). A template that refers to
1057/// the body anywhere else (inside a group, inside another command's argument,
1058/// or in two places) cannot be cut that way, so the environment takes the
1059/// body as an argument instead ([`BodyForm::Argument`]) and the template is
1060/// written whole. A template that does not refer to the body at all takes
1061/// the same argument form and never writes the argument, so LaTeX reads the
1062/// body and drops it, as FLM's own expansion does.
1063#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1064enum BodyForm {
1065 /// The template refers to the body exactly once among its top-level nodes:
1066 /// the template is cut there into the begin code and the end code, and
1067 /// LaTeX sets the body between them.
1068 Split,
1069 /// The template refers to the body somewhere else, more than once, or not
1070 /// at all: the environment declares LaTeX's body argument `+b` as its last
1071 /// argument, LaTeX passes the body in it, and the whole template is the
1072 /// begin code, with the body written as that argument's parameter. Where
1073 /// the template does not refer to the body, the begin code never writes
1074 /// that parameter, so LaTeX reads the body and drops it, as the expansion
1075 /// does; [`body_form`] states the one difference that remains.
1076 Argument,
1077}
1078
1079/// Returns how the body of an environment with the template `template`
1080/// reaches the LaTeX the environment is written as ([`BodyForm`]).
1081///
1082/// A template that does not refer to the body takes it as an argument too,
1083/// and the begin code never writes that argument: LaTeX reads the body, passes
1084/// it, and the definition drops it, as FLM's own expansion does. One difference
1085/// remains: LaTeX *reads* what it drops, so a body whose braces or
1086/// environments do not balance is a LaTeX error, where the expansion drops it
1087/// unread (such content would not have parsed in FLM in the first place).
1088///
1089/// This function is the only place where the form is decided, so that the
1090/// environment's argument specification, its begin and end code and the
1091/// parameter a body placeholder is written as cannot disagree.
1092fn body_form(template: &CompiledTemplate) -> BodyForm {
1093 let root = template.tree().root();
1094 let mut form = None;
1095 for node in root.descendants() {
1096 if !is_body_placeholder(template, &node) {
1097 continue;
1098 }
1099 let at_top_level = node.parent().is_some_and(|parent| parent.id() == root.id());
1100 form = match (form, at_top_level) {
1101 // The first body placeholder, at the top level: splitting is still
1102 // possible. A second one of any kind, or one anywhere else, settles
1103 // the answer at the body-grabbing form.
1104 (None, true) => Some(BodyForm::Split),
1105 _ => Some(BodyForm::Argument),
1106 };
1107 }
1108 // A template that names the body nowhere grabs it and drops it.
1109 form.unwrap_or(BodyForm::Argument)
1110}
1111
1112/// Checks that the template's own content allows recomposition: the check of
1113/// [`check_placeholders`], which applies to every compiled tree. Nothing about
1114/// an environment's body prevents recomposition: [`body_form`] gives a form
1115/// for every template, including one that does not refer to its body.
1116///
1117/// A *verbatim block* in the template's own content does not prevent it
1118/// either: it is written into the definition's body as a call of
1119/// `\flmVerbatimBlock`, an ordinary macro call over brace groups, which can be
1120/// written wherever any other call can.
1121fn check_template(template: &CompiledTemplate) -> Result<(), NotRecomposable> {
1122 check_placeholders(template)
1123}
1124
1125/// Returns the effective signature of the definition `value` when nothing in
1126/// the definition alone prevents recomposition, or the reason it cannot be
1127/// recomposed. The definition alone is its expansion policy, its compilation,
1128/// its kind, its arguments, its template and the default value of each of its
1129/// arguments.
1130///
1131/// Another definition of the same kind and name, declared for the other
1132/// parsing mode, is no reason: the two are per-mode definitions and are written
1133/// under two names of their own ([`another_definition_shares_its_name`],
1134/// [`latex_mode`]). Nor is a definition of the same name and the other kind (a
1135/// macro beside an environment), since each kind is written under a prefix of
1136/// its own, so the two names cannot collide.
1137///
1138/// The caller records the effective signature ([`effective_signature`]) on the
1139/// definition's element data: every call and the definition itself are written
1140/// from it.
1141fn intrinsic(value: &UserDefinition) -> Result<EffectiveSignature, NotRecomposable> {
1142 let definition = value.definition();
1143 if definition.expand == ExpandPolicy::Always {
1144 return Err(NotRecomposable::AlwaysExpanded);
1145 }
1146 let Some(variant) = recomposed_variant(value) else {
1147 return Err(NotRecomposable::NotCompiled);
1148 };
1149 if definition.kind == DefinitionKind::Specials {
1150 return Err(NotRecomposable::Specials);
1151 }
1152 for (index, arg) in definition.args.iter().enumerate() {
1153 if let Some(shape) = shape_token(&*arg.kind) {
1154 return Err(NotRecomposable::ArgumentShape { index, shape: String::from(shape) });
1155 }
1156 }
1157 check_template(variant.template())?;
1158 // A default is written at the call site, in its argument's own group,
1159 // wherever the use site left the argument out, and it is resolved there by
1160 // the use site's own bindings ([`resolved_default`]) — so a default
1161 // holding placeholders of other arguments or conditionals of its own is
1162 // written like any other content, and the only thing it may not hold is a
1163 // placeholder nothing at the use site answers. A verbatim block is no
1164 // reason here either: what the default resolves to is written into its
1165 // argument's own value group at the call, and a verbatim block in it is
1166 // written there as the escaped call, like any other value.
1167 for (_, default) in variant.defaults() {
1168 check_placeholders(default)?;
1169 }
1170 Ok(effective_signature(definition, &variant))
1171}
1172
1173/// Whether another definition of `roster` declares the same kind and name as
1174/// `value`. The two are then per-mode definitions, one for each parsing mode,
1175/// which FLM allows because their modes do not overlap.
1176///
1177/// The `latex-recomposed` backend writes each of them under a name of its own
1178/// ([`latex_mode`]), so this is a fact the recomposition needs, not a reason
1179/// against recomposition.
1180fn another_definition_shares_its_name(
1181 value: &UserDefinition,
1182 roster: &[Arc<UserDefinition>],
1183) -> bool {
1184 let definition = value.definition();
1185 roster.iter().any(|other| {
1186 !std::ptr::eq(&**other, value)
1187 && other.definition().kind == definition.kind
1188 && other.definition().name == definition.name
1189 })
1190}
1191
1192/// Returns the `per-plan` definitions of `roster` that `value`'s compiled
1193/// templates (the template and its default values) use, as indices into
1194/// `roster`, each once, in order of first use.
1195fn uses_of(value: &UserDefinition, roster: &[Arc<UserDefinition>]) -> Vec<usize> {
1196 let mut used = Vec::new();
1197 let Some(variant) = recomposed_variant(value) else { return used };
1198 let trees = std::iter::once(variant.template()).chain(variant.defaults().map(|(_, t)| t));
1199 for template in trees {
1200 for node in template.tree().root().descendants() {
1201 let Some(other) = element_value::<UserDefinition>(&node) else { continue };
1202 if other.definition().expand != ExpandPolicy::PerPlan {
1203 continue;
1204 }
1205 if let Some(index) = roster.iter().position(|entry| std::ptr::eq(&**entry, other)) {
1206 if !used.contains(&index) {
1207 used.push(index);
1208 }
1209 }
1210 }
1211 }
1212 used
1213}
1214
1215/// Computes, for each definition of `roster` (all the definitions the
1216/// `userdefs` feature registers), the facts the registry build decides about
1217/// it, and records them on the definition
1218/// ([`UserDefinition::record_registry_build_facts`]): whether one LaTeX
1219/// definition can express it (whether it is recomposable) and, if so, the
1220/// arguments its calls write ([`EffectiveSignature`]); and whether another
1221/// definition of the same kind and name is declared for the other parsing mode,
1222/// in which case the recomposition writes the two under two names.
1223///
1224/// Nothing is reported. A definition is not recomposable because of its nature
1225/// (a special character sequence), its author's choice (the expansion policy
1226/// `always`), a refusal already reported when the registry was built, or the
1227/// use, in its template or a default value, of a `per-plan` definition that is
1228/// not recomposable; two further reasons apply only to definitions declared in
1229/// Rust ([`NotRecomposable`]). None of these needs a report: a refusal was
1230/// reported when it happened, and the other reasons are not mistakes in the
1231/// document. A host that wants to know why a definition is written expanded
1232/// calls [`UserDefinition::recomposable`].
1233///
1234/// The `userdefs` feature calls this function from its late-initialization
1235/// build hook, after the templates are compiled, with all its definitions:
1236/// two of the facts involve two definitions (a definition of the same name for
1237/// the other parsing mode, and a use of a definition that is not
1238/// recomposable), so they need every definition. A definition that uses a
1239/// definition that is not recomposable is not recomposable itself, however
1240/// long the chain of uses. A definition that uses **itself**, directly or
1241/// through a chain of uses, remains recomposable: it is written as a LaTeX
1242/// definition that calls itself, and LaTeX runs the recursion.
1243///
1244/// The facts are recorded once per definition; a second call records nothing
1245/// new.
1246pub fn record_recomposability(roster: &[Arc<UserDefinition>]) {
1247 let uses: Vec<Vec<usize>> = roster.iter().map(|value| uses_of(value, roster)).collect();
1248 let mut outcomes: Vec<Result<EffectiveSignature, NotRecomposable>> = roster
1249 .iter()
1250 .map(|value| intrinsic(value))
1251 .collect();
1252 // A use of a non-recomposable definition spreads to the user, until
1253 // nothing changes.
1254 loop {
1255 let mut changed = false;
1256 for index in 0..roster.len() {
1257 if outcomes[index].is_err() {
1258 continue;
1259 }
1260 let failing = uses[index].iter().copied().find(|used| outcomes[*used].is_err());
1261 if let Some(used) = failing {
1262 outcomes[index] =
1263 Err(NotRecomposable::Uses { name: roster[used].definition().display_name() });
1264 changed = true;
1265 }
1266 }
1267 if !changed {
1268 break;
1269 }
1270 }
1271 for (value, outcome) in roster.iter().zip(outcomes) {
1272 value.record_registry_build_facts(RegistryBuildFacts {
1273 recomposition: outcome,
1274 shares_its_name: another_definition_shares_its_name(value, roster),
1275 });
1276 }
1277}
1278
1279// --- the stamped copy -----------------------------------------------------------------------------
1280
1281/// Returns the failure to copy a template as a [`LowerError`].
1282fn copy_failed(error: impl std::fmt::Display) -> LowerError {
1283 LowerError::other(format!("copying the template failed: {error}"))
1284}
1285
1286/// The visitor that copies a compiled template for a definition construct
1287/// (see "The copy of the template" in the module documentation).
1288///
1289/// It copies every node of the template unchanged, except a placeholder node,
1290/// which it replaces by a childless copy carrying the LaTeX the placeholder is
1291/// written as ([`LatexPoint`]), and a conditional node, which it replaces by
1292/// the parts of the LaTeX the conditional becomes, with the branches it keeps
1293/// copied between them.
1294struct Stamp<'r, 't> {
1295 recomposition: &'r Recomposition<'t>,
1296}
1297
1298impl Stamp<'_, '_> {
1299 /// Stages one [`LatexPoint`] node of the copy: a childless copy of `at`, a
1300 /// node of the template, carrying `text` as the LaTeX written there
1301 /// ([`stamp_point`]).
1302 fn point(
1303 &self,
1304 at: &NodeRef<'_, Flm>,
1305 text: String,
1306 cx: &mut RestageContext<'_, Flm, (), ()>,
1307 ) -> Result<BuildId, LowerError> {
1308 stamp_point(at, text, cx)
1309 }
1310
1311 /// Copies a conditional node: the parts of the LaTeX it becomes, with the
1312 /// branches it keeps copied between them. A conditional decided in advance
1313 /// keeps one branch and writes no LaTeX of its own; every other outcome
1314 /// writes LaTeX around the test, and each part of that LaTeX is staged as a
1315 /// copy of the test argument's placeholder.
1316 fn conditional(
1317 &mut self,
1318 node: NodeRef<'_, Flm>,
1319 conditional: Conditional,
1320 cx: &mut RestageContext<'_, Flm, (), ()>,
1321 ) -> Result<Restage<()>, LowerError> {
1322 let arg = self.recomposition.test_argument(&node);
1323 let latex = self.recomposition.conditional_latex(conditional, &arg);
1324 let parts = conditional_parts(self.recomposition, conditional, &latex);
1325 let at = node
1326 .argument_content_nodes(0)
1327 .and_then(|argument| {
1328 argument
1329 .iter()
1330 .find(|child| {
1331 placeholder_argument(self.recomposition.variant.template(), child).is_some()
1332 })
1333 });
1334 let mut ids = Vec::new();
1335 for part in parts {
1336 match part {
1337 ConditionalPart::Latex(text) => {
1338 let Some(at) = at else {
1339 return Err(LowerError::structure(
1340 "a conditional written as a LaTeX test without a placeholder to test",
1341 ));
1342 };
1343 ids.push(self.point(&at, text, cx)?);
1344 }
1345 ConditionalPart::Branch(index) => {
1346 if let Some(branch) = node.argument_content_nodes(index) {
1347 for child in branch.iter() {
1348 ids.extend(cx.restage_subtree(child, self).map_err(convert)?);
1349 }
1350 }
1351 }
1352 }
1353 }
1354 Ok(Restage::Emit(ids))
1355 }
1356}
1357
1358impl RestageVisitor<Flm, (), ()> for Stamp<'_, '_> {
1359 type Error = LowerError;
1360
1361 fn restage(
1362 &mut self,
1363 node: NodeRef<'_, Flm>,
1364 cx: &mut RestageContext<'_, Flm, (), ()>,
1365 ) -> Result<Restage<()>, LowerError> {
1366 if let Some(conditional) = element_value::<Conditional>(&node) {
1367 return self.conditional(node, *conditional, cx);
1368 }
1369 if node.callable_type() != Some(FlmCallableType::Placeholder) {
1370 return Ok(Restage::Descend(()));
1371 }
1372 let Some(index) = placeholder_argument(self.recomposition.variant.template(), &node) else {
1373 // The body placeholder of an environment that takes its body as an
1374 // argument: it is written as that argument's parameter, like any
1375 // other. The body placeholder of an environment whose template is
1376 // split at it never reaches here, the template being cut in two
1377 // there before it is copied.
1378 if is_body_placeholder(self.recomposition.variant.template(), &node) {
1379 if let Some(parameter) = self.recomposition.body_parameter() {
1380 let id = self.point(&node, parameter_of(parameter), cx)?;
1381 return Ok(Restage::Emit(vec![id]));
1382 }
1383 }
1384 return Err(LowerError::structure("a placeholder the template does not know"));
1385 };
1386 let Some(parameter) = self.recomposition.value(index) else {
1387 return Err(LowerError::structure("a placeholder of an argument that is not declared"));
1388 };
1389 let id = self.point(&node, self.recomposition.read(parameter), cx)?;
1390 Ok(Restage::Emit(vec![id]))
1391 }
1392}
1393
1394/// The visitor that produces the copied template as a synthesized value: it is
1395/// called once, at the root of the template's tree, and stages a new list node
1396/// over the copies of `nodes` ([`Stamp`]).
1397struct StampedCopy<'n, 'r, 't> {
1398 nodes: &'n [NodeRef<'t, Flm>],
1399 recomposition: &'r Recomposition<'t>,
1400}
1401
1402impl RestageVisitor<Flm, (), ()> for StampedCopy<'_, '_, '_> {
1403 type Error = LowerError;
1404
1405 fn restage(
1406 &mut self,
1407 root: NodeRef<'_, Flm>,
1408 cx: &mut RestageContext<'_, Flm, (), ()>,
1409 ) -> Result<Restage<()>, LowerError> {
1410 let mut stamp = Stamp { recomposition: self.recomposition };
1411 let mut children = Vec::with_capacity(self.nodes.len());
1412 for node in self.nodes {
1413 children.extend(cx.restage_subtree(*node, &mut stamp).map_err(convert)?);
1414 }
1415 let (span, state) = match (self.nodes.first(), self.nodes.last()) {
1416 (Some(first), Some(last)) if first.span().same_source(last.span()) => (
1417 SourceSpan::new(first.span().source(), first.span().start()..last.span().end()),
1418 Arc::clone(first.parsing_state()),
1419 ),
1420 (Some(first), _) => (first.span().clone(), Arc::clone(first.parsing_state())),
1421 _ => {
1422 let at = root.span();
1423 (
1424 SourceSpan::new(at.source(), at.start()..at.start()),
1425 Arc::clone(root.parsing_state()),
1426 )
1427 }
1428 };
1429 let kind = NodeKind::list();
1430 let ext = Flm::make_node_ext(&kind, &span, &state, cx.builder().staged_children(&children))
1431 .map_err(|error| LowerError::Build { detail: error.to_string() })?;
1432 let id = cx
1433 .builder()
1434 .add(kind, span, state, children, ext, ())
1435 .map_err(|error| LowerError::Build { detail: error.to_string() })?;
1436 Ok(Restage::Emit(vec![id]))
1437 }
1438}
1439
1440/// Returns a failure of the template copy as the rule's own failure: the
1441/// visitor's error as it is, or any other failure as text.
1442fn convert(error: RestageError<LowerError>) -> LowerError {
1443 match error {
1444 RestageError::Visitor(error) => error,
1445 other => copy_failed(other),
1446 }
1447}
1448
1449/// Returns a run of a compiled template's top-level nodes copied into a
1450/// synthesized value of its own ([`StampedCopy`]), with every placeholder and
1451/// conditional replaced as [`Stamp`] does: the value's root is a list over the
1452/// copies.
1453fn stamped_value<'t>(
1454 recomposition: &Recomposition<'t>,
1455 template: &'t CompiledTemplate,
1456 nodes: &[NodeRef<'t, Flm>],
1457) -> Result<NodeTree<Flm>, LowerError> {
1458 let mut copy = StampedCopy { nodes, recomposition };
1459 guard::restager(&mut copy, GuardPolicy::StackBudget).restage(template.tree()).map_err(convert)
1460}
1461
1462/// Stages the content of one content slot of a definition construct from a run
1463/// of a compiled template's top-level nodes, and returns the staged nodes.
1464///
1465/// For a template for text mode, the copy of the run is spliced
1466/// ([`Lowerer::splice`]): brought up to date by value catch-up and lowered
1467/// through the rules, so that anything the template holds is lowered as
1468/// document content is. For a template for mathematics mode, the copy is
1469/// written by the mathematics writer ([`write_math_run`]): the source byte for
1470/// byte, each placeholder as its parameter, each use site handled.
1471///
1472/// A run for text mode that declares a reference point is refused with
1473/// [`KeptTemplateDeclaresPoint`] (see the [module
1474/// documentation](self#a-template-that-declares-a-reference-point)): value
1475/// catch-up refuses a synthesized value that states a fact about the document,
1476/// and a `\label` whose text holds a placeholder, which value catch-up does not
1477/// see as a label, is refused before the splice.
1478fn template_run<'t>(
1479 cx: &mut LowerCx<'_>,
1480 lw: &mut dyn Lowerer,
1481 recomposition: &Recomposition<'t>,
1482 template: &'t CompiledTemplate,
1483 nodes: &[NodeRef<'t, Flm>],
1484) -> Result<Vec<BuildId>, LowerError> {
1485 let value = stamped_value(recomposition, template, nodes)?;
1486 if template.mode() == Mode::Math {
1487 let copies: Vec<NodeRef<'_, Flm>> = value.root().children().iter().collect();
1488 let mut writer = MathWriter::new(cx, lw, Nodes::Synthesized);
1489 writer.run(&copies)?;
1490 let pieces = writer.finish();
1491 stage_math_pieces(cx, lw, pieces)
1492 } else {
1493 // A label whose spelling a template substitution completes is a label
1494 // all the same, but it reads as no label, so the catch-up below sees no
1495 // fact in it: it is refused here, by the same condition.
1496 if nodes.iter().any(|node| holds_placeholder_label(node)) {
1497 return Err(refusal(recomposition.definition, template));
1498 }
1499 match lw.splice(cx, &Arc::new(value)) {
1500 Err(LowerError::DocumentFactInValue { .. }) => {
1501 Err(refusal(recomposition.definition, template))
1502 }
1503 other => other,
1504 }
1505 }
1506}
1507
1508// --- a template that declares a reference point ---------------------------------------------------
1509
1510/// Condition: the template of a user definition whose use sites are kept in
1511/// the tree (not expanded before lowering) declares a reference point that
1512/// carries a label: a construct followed by `\label`, a labeled xnote, a
1513/// defined term, or any construct whose reference point carries a label; or it
1514/// holds a `\label` whose text a placeholder completes.
1515///
1516/// A kept definition's template is lowered as a synthesized value: the body of
1517/// the LaTeX definition that `emit-call` writes, or the expansion that
1518/// `instantiate-at-lowering` builds for a use site. A label is a fact about
1519/// the document as a whole (other places refer to it), and a synthesized value
1520/// may state no such fact, so the template cannot be lowered there (see the
1521/// [module documentation](self#a-template-that-declares-a-reference-point)).
1522/// The remedy is the expansion policy [`Always`](ExpandPolicy::Always): the
1523/// definition's use sites are then expanded in the document before the labels
1524/// are read, and each label is the document's own. Selecting
1525/// `instantiate-at-lowering` is no remedy, since its expansion is a
1526/// synthesized value too.
1527///
1528/// Reported as an Error at the node of the template that declares the point
1529/// (at the start of the template when no node can be identified), once at each
1530/// use site of the definition. Recovery: the use site lowers to a childless
1531/// `flm.pres.unsupported` stand-in node ([`LowerError::Refused`]), which the
1532/// `latex-recomposed` backend writes as a comment.
1533#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
1534#[diagnostic(
1535 id = "flm.userdefs.kept-template-declares-point",
1536 message = "the template of `{definition}` declares a labeled place that other parts of the \
1537 document can refer to ({declared_by}), which is allowed only when the definition \
1538 is expanded in the document itself, before the output is produced; give the \
1539 definition the expansion policy `always` (`expand: always`), or remove the label \
1540 from its template"
1541)]
1542pub struct KeptTemplateDeclaresPoint {
1543 /// The definition, as an author writes it (`\titled`).
1544 pub definition: String,
1545 /// The node of the template that declares the point, as written and in
1546 /// backquotes (`` `\section` ``, `` `\label` ``), or the words "somewhere in
1547 /// its template" when no node can be identified.
1548 pub declared_by: String,
1549}
1550
1551/// Whether `node`, or a node under it, is a `\label` whose text holds a
1552/// placeholder of the template.
1553fn holds_placeholder_label(node: &NodeRef<'_, Flm>) -> bool {
1554 std::iter::once(*node).chain(node.descendants()).any(|node| {
1555 is_field_named(&node, LABEL_FIELD)
1556 && node
1557 .argument_content_nodes_named(TARGET_ARG)
1558 .ok()
1559 .flatten()
1560 .and_then(|content| read_chars(content.iter()).ok())
1561 .is_some_and(|read| read.has_placeholder())
1562 })
1563}
1564
1565/// Returns the first node of `template`, in document order, that declares a
1566/// labeled reference point: a construct whose point carries a label, or a
1567/// `\label` field (the label of a construct whose own point does not show it,
1568/// because its text holds a placeholder).
1569fn declaring_node<'t>(template: &'t CompiledTemplate) -> Option<NodeRef<'t, Flm>> {
1570 template.tree().root().descendants().find(|node| {
1571 let labeled = element_of(node).aspect::<dyn Referenceable>().is_some_and(|aspect| {
1572 aspect.points(node).iter().any(|point| !point.labels.is_empty())
1573 });
1574 labeled || is_field_named(node, LABEL_FIELD)
1575 })
1576}
1577
1578/// Returns how a node of a template is written in
1579/// [`KeptTemplateDeclaresPoint`]: a macro or a field as `\name`, an environment
1580/// as `\begin{name}`.
1581fn spelled(node: &NodeRef<'_, Flm>) -> String {
1582 let name = node.name().unwrap_or_default();
1583 match node.callable_type() {
1584 Some(FlmCallableType::Environment) => format!("\\begin{{{name}}}"),
1585 _ => format!("\\{name}"),
1586 }
1587}
1588
1589/// Returns the refusal of a definition whose template declares a labeled
1590/// reference point: [`KeptTemplateDeclaresPoint`] at the node that declares
1591/// it, or at the start of the template when no node can be identified. The
1592/// lowering stage reports it at each use site the rule refuses
1593/// ([`LowerError::Refused`]).
1594fn refusal(definition: &Definition, template: &CompiledTemplate) -> LowerError {
1595 let (span, declared_by) = match declaring_node(template) {
1596 Some(node) => (node.span().clone(), format!("`{}`", spelled(&node))),
1597 None => (
1598 SourceSpan::new(template.source(), 0..0),
1599 String::from("somewhere in its template"),
1600 ),
1601 };
1602 let condition = KeptTemplateDeclaresPoint { definition: definition.display_name(), declared_by };
1603 LowerError::Refused(Box::new(Diagnostic::error(condition, span)))
1604}
1605
1606// --- instantiating a use site ---------------------------------------------------------------------
1607
1608/// Returns the expansion of the use site `node` as a synthesized value of its
1609/// own: the use site copied into a value and expanded over every definition,
1610/// the `always` ones included (a use site inside a template has had no
1611/// rewrite stage run over it), under the definition's expansion depth limit
1612/// ([`UserDefinition::recursion_limit`]). The diagnostics of the expansion (a
1613/// depth limit reached, a placeholder without a value) are reported through
1614/// `lw`. [`instantiate`] splices the result, and the mathematics writer
1615/// writes it as source.
1616fn expansion_of(
1617 node: NodeRef<'_, Flm>,
1618 value: &UserDefinition,
1619 lw: &mut dyn Lowerer,
1620) -> Result<Arc<NodeTree<Flm>>, LowerError> {
1621 // The copy and the expansion run under the stack budget, the
1622 // policy every registry outside a test runs under: the lowering façade
1623 // exposes no guard policy, and the use site is one subtree on the
1624 // lowering stage's worker thread.
1625 let copied = copy_run_into_value(&[node], &node, ValueContent::Own, GuardPolicy::StackBudget)
1626 .map_err(|error| LowerError::other(format!("copying the use site failed: {error}")))?;
1627 let options =
1628 ExpandOptions { recursion_limit: value.recursion_limit(), guard: GuardPolicy::StackBudget };
1629 let mut diags = FlmDiagnostics::new();
1630 let expanded = expand(&copied, lw.lang(), &options, ExpandSet::Both, &mut diags)
1631 .map_err(|failure| LowerError::other(failure.to_string()))?;
1632 for diagnostic in diags.iter() {
1633 lw.diagnose(diagnostic.clone());
1634 }
1635 Ok(expanded)
1636}
1637
1638/// Returns the data of the element of the use site `node`
1639/// ([`UserDefinition`]), which every use site of a user definition carries; a
1640/// structure error for any other node.
1641fn value_of<'t>(node: &NodeRef<'t, Flm>) -> Result<&'t UserDefinition, LowerError> {
1642 element_value::<UserDefinition>(node)
1643 .ok_or_else(|| LowerError::structure("a user-definition node without its element's data"))
1644}
1645
1646/// Instantiates one use site: expands it ([`expansion_of`]) and splices the
1647/// expansion in its place. This is the body of `instantiate-at-lowering`, and
1648/// of `emit-call` for a definition that is not recomposable or whose template
1649/// needs a placeholder's characters (see the module documentation).
1650///
1651/// An expansion that declares a labeled reference point is refused with
1652/// [`KeptTemplateDeclaresPoint`], as a template written as a LaTeX definition
1653/// is.
1654fn instantiate(
1655 node: NodeRef<'_, Flm>,
1656 cx: &mut LowerCx<'_>,
1657 lw: &mut dyn Lowerer,
1658) -> Result<Lowering, LowerError> {
1659 let value = value_of(&node)?;
1660 let expanded = expansion_of(node, value, lw)?;
1661 match lw.splice(cx, &expanded) {
1662 Ok(ids) => Ok(Lowering::Emit(ids)),
1663 Err(LowerError::DocumentFactInValue { stage, table }) => match recomposed_variant(value) {
1664 Some(variant) => Err(refusal(value.definition(), variant.template())),
1665 None => Err(LowerError::DocumentFactInValue { stage, table }),
1666 },
1667 Err(error) => Err(error),
1668 }
1669}
1670
1671/// The body of every `instantiate-at-lowering` rule: it expands the use site
1672/// with the expand pass and lowers the expansion in its place (see the module
1673/// documentation). The expansion depth limit is the definition's
1674/// ([`UserDefinition::recursion_limit`]).
1675///
1676/// Build the rule of a definition with [`instantiate_at_lowering_rule`].
1677#[derive(Debug, Default, Clone, Copy)]
1678pub struct InstantiateAtLowering;
1679
1680impl Lower for InstantiateAtLowering {
1681 fn lower(
1682 &self,
1683 node: NodeRef<'_, Flm>,
1684 cx: &mut LowerCx<'_>,
1685 lw: &mut dyn Lowerer,
1686 ) -> Result<Lowering, LowerError> {
1687 instantiate(node, cx, lw)
1688 }
1689}
1690
1691/// Returns the `instantiate-at-lowering` rule of `definition`, a definition
1692/// whose expansion policy is `per-plan`: the rule targets the definition's
1693/// element, requires `flm.userdefs.kept`, declares no presentation element of
1694/// its own (the rules of the expansion's elements stage what it becomes) and
1695/// is never a default, so a plan request selects it by name. See the module
1696/// documentation.
1697pub fn instantiate_at_lowering_rule(definition: &Definition) -> LoweringRule {
1698 LoweringRule::new(
1699 instantiate_rule_name(definition),
1700 element_name(definition),
1701 LoweringDecl::new().requires(KEPT),
1702 Arc::new(InstantiateAtLowering),
1703 DefaultMark::Never,
1704 )
1705 .docs(format!(
1706 "a use site of `{}` kept in the tree is expanded at lowering and the expansion is \
1707 lowered in its place (requires `flm.userdefs.kept`); never a default, a plan request \
1708 selects it by name",
1709 definition.display_name()
1710 ))
1711}
1712
1713// --- emitting a call ------------------------------------------------------------------------------
1714
1715/// Returns which of a name's definitions `value` is, for the name it is
1716/// recomposed under ([`LatexDefinitionMode`]).
1717///
1718/// A definition declared once is *single*, regardless of the parsing modes it
1719/// applies in. Where the same kind and name are declared twice
1720/// ([`UserDefinition::shares_its_name`]), each of the two per-mode definitions
1721/// takes the name for the mode it applies in, and the recomposition writes the
1722/// one for the use site's mode: `emit-call` runs in text and the mathematics
1723/// writer inside mathematics, and each finds only the definition available in
1724/// its own mode.
1725///
1726/// A definition that applies in *both* modes is single here, and this cannot
1727/// put two definitions under one name: two declarations of one name whose modes
1728/// overlap make the registry build fail, so a pair that reaches this function
1729/// declares text mode and mathematics mode, one each. No document reaches that
1730/// branch; it exists because the type allows the value.
1731fn latex_mode(value: &UserDefinition) -> LatexDefinitionMode {
1732 if !value.shares_its_name() {
1733 return LatexDefinitionMode::Single;
1734 }
1735 match value.definition().modes {
1736 DefinitionModes::Text => LatexDefinitionMode::Text,
1737 DefinitionModes::Math => LatexDefinitionMode::Mathematics,
1738 DefinitionModes::Both => LatexDefinitionMode::Single,
1739 }
1740}
1741
1742/// Returns the LaTeX kind a definition is recomposed as. This function is the
1743/// only place where FLM's kinds of definitions are mapped to LaTeX's. A special
1744/// character sequence has no LaTeX kind and is never recomposed, so it gives a
1745/// structure error here rather than being written as a macro.
1746fn latex_kind(definition: &Definition) -> Result<LatexDefinitionKind, LowerError> {
1747 match definition.kind {
1748 DefinitionKind::Macro => Ok(LatexDefinitionKind::Macro),
1749 DefinitionKind::Environment => Ok(LatexDefinitionKind::Environment),
1750 DefinitionKind::Specials => {
1751 Err(LowerError::structure(
1752 "a definition of a special character sequence is never written as a LaTeX \
1753 definition",
1754 ))
1755 }
1756 }
1757}
1758
1759/// Whether the definition of kind `kind` declared as `name` is written as a
1760/// **robust** command rather than as the expandable macro every recomposed
1761/// definition otherwise becomes: the render option
1762/// [`robust_names`](LatexRecomposedRenderOptions::robust_names) lists the name,
1763/// the definition is a macro, and the name does not belong to the library's
1764/// own LaTeX (it does not begin with `flm`).
1765///
1766/// An environment is robust regardless of how it is written, so listing one
1767/// changes nothing, as the option's documentation states; listing every name a
1768/// document declares is therefore accepted. A listed name beginning with `flm`
1769/// is reported once per document by the backend's regions stage
1770/// (`flm.latex-recomposed.definition-name-refused`); here it just does not make
1771/// the definition robust.
1772fn asks_for_robustness(
1773 kind: LatexDefinitionKind,
1774 name: &str,
1775 robust_names: &std::collections::BTreeSet<String>,
1776) -> bool {
1777 kind == LatexDefinitionKind::Macro && !is_family_name(name) && robust_names.contains(name)
1778}
1779
1780/// Stages the definition construct (`flm.pres.latex.definition`) of a
1781/// recomposable definition, which the emitter writes into the style file (see
1782/// the module documentation), and returns it.
1783///
1784/// The construct holds the compiled template's content: in the `body` slot
1785/// for a macro; cut at its body placeholder into the `begin` and `end` slots
1786/// for an environment LaTeX sets the body of; or whole in the `begin` slot,
1787/// with an empty `end` slot, for an environment that takes its body as an
1788/// argument ([`BodyForm::Argument`]). Each slot's content comes from the
1789/// template through [`template_run`]. The construct carries the definition's
1790/// recomposed name ([`recomposed_name`]), the name the document declared (for
1791/// the comment line of the style file), and the number of effective arguments
1792/// every call writes. `emit-call` stages it at a use site in text and the
1793/// mathematics writer at a use site inside mathematics; the emitter writes it
1794/// once per name.
1795///
1796/// The definition holds no default values: a default value is written at every
1797/// call whose use site left the argument out, in that argument's own group, so
1798/// the definition finds a value there like any other.
1799///
1800/// Returns `None` when the definition's own construct is already being staged
1801/// further up this call, which happens for a definition that uses **itself**,
1802/// directly or through a chain of definitions. The use site of the definition
1803/// inside its own template is written as a call like any other, and the
1804/// construct being staged further up is the definition that call calls;
1805/// staging a second one would write the same definition into the style file
1806/// twice and would never stop. The recomposed definition then calls itself and
1807/// LaTeX runs the recursion. The thread-local set [`BEING_STAGED`] records the
1808/// names being staged, through the guard [`Staging`].
1809fn definition_construct(
1810 cx: &mut LowerCx<'_>,
1811 lw: &mut dyn Lowerer,
1812 value: &UserDefinition,
1813) -> Result<Option<BuildId>, LowerError> {
1814 let name = {
1815 let options = lw.option::<LatexRecomposedRenderOptions>()?;
1816 recomposed_name(
1817 latex_kind(value.definition())?,
1818 value.definition().name.as_str(),
1819 latex_mode(value),
1820 &options.bare_names,
1821 )
1822 };
1823 // The recursion guard: a definition that uses itself is written as a LaTeX
1824 // definition that calls itself, since a recomposed definition is LaTeX's to
1825 // expand and a recursion is LaTeX's to run; its template's use site of it
1826 // must not start a second staging of the same construct.
1827 let Some(_staging) = Staging::begin(name) else {
1828 return Ok(None);
1829 };
1830 definition_body(cx, lw, value).map(Some)
1831}
1832
1833thread_local! {
1834 /// The recomposed names whose definition construct this thread is staging
1835 /// ([`definition_construct`]).
1836 ///
1837 /// This set is the only state a rule of this backend keeps across nodes,
1838 /// and it is held by the thread because the lowering interface gives a rule
1839 /// no other place for it. [`LowerCx`] is techy's
1840 /// `RestageContext<'_, Flm, (), ()>`, whose two state type parameters are
1841 /// both the unit type (`crate::core::lowering`), and [`Lowerer`] has no
1842 /// per-run store, so neither has a place for state kept during one run. The
1843 /// only other thread-local state of this kind in this crate is the
1844 /// worker-thread marker of `crate::lang::guard`. Lowering runs one tree at
1845 /// a time on a worker thread, so "per thread" means "per run" in practice.
1846 /// If a second rule needs state of its own, the state should be passed
1847 /// through the lowering interface instead.
1848 ///
1849 /// Names are added and removed only through [`Staging`], so that a panic
1850 /// that unwinds cannot leave a name in the set for the next run on this
1851 /// thread.
1852 static BEING_STAGED: RefCell<BTreeSet<String>> = const { RefCell::new(BTreeSet::new()) };
1853}
1854
1855/// One recomposed name in the set [`BEING_STAGED`], removed when this value is
1856/// dropped.
1857///
1858/// The name must be removed from the set on **every** way out of
1859/// [`definition_construct`], the unwinding of a panic included: lowering runs
1860/// on a worker thread that the pool reuses, so a name left in the set would
1861/// make [`definition_construct`] return `None` for that definition in the next
1862/// document lowered on that thread, and that document's style file would lack
1863/// the definition without any error. The `Drop` implementation guarantees the
1864/// removal.
1865struct Staging {
1866 name: String,
1867}
1868
1869impl Staging {
1870 /// Adds `name` to the set [`BEING_STAGED`] and returns the guard that
1871 /// removes it; returns `None` when the name is already in the set, which
1872 /// is the recursion this guard detects.
1873 fn begin(name: String) -> Option<Self> {
1874 BEING_STAGED
1875 .with(|names| names.borrow_mut().insert(name.clone()))
1876 .then(|| Self { name })
1877 }
1878}
1879
1880impl Drop for Staging {
1881 fn drop(&mut self) {
1882 BEING_STAGED.with(|names| names.borrow_mut().remove(&self.name));
1883 }
1884}
1885
1886/// Stages the definition construct of `value` and returns it; the caller
1887/// ([`definition_construct`]) has already added its recomposed name to the
1888/// set [`BEING_STAGED`].
1889fn definition_body(
1890 cx: &mut LowerCx<'_>,
1891 lw: &mut dyn Lowerer,
1892 value: &UserDefinition,
1893) -> Result<BuildId, LowerError> {
1894 let definition = value.definition();
1895 let variant = recomposed_variant(value)
1896 .ok_or_else(|| LowerError::structure("a recomposable definition without a template"))?;
1897 let signature = value.effective_signature().ok_or_else(|| {
1898 LowerError::structure("a recomposable definition without its effective signature")
1899 })?;
1900 let recomposition = Recomposition { definition, variant: &variant, signature };
1901 let template = variant.template();
1902 let root = template.tree().root();
1903 let children: Vec<NodeRef<'_, Flm>> = root.children().iter().collect();
1904 let mut slots = Vec::new();
1905 let kind = latex_kind(definition)?;
1906 match kind {
1907 // A user definition is a macro or an environment ([`latex_kind`]).
1908 LatexDefinitionKind::Declaration => {
1909 return Err(LowerError::structure("a user definition recomposed as a declaration"));
1910 }
1911 LatexDefinitionKind::Macro => {
1912 slots.push((
1913 String::from(BODY_SLOT),
1914 template_run(cx, lw, &recomposition, template, &children)?,
1915 ));
1916 }
1917 LatexDefinitionKind::Environment => match recomposition.body_form() {
1918 Some(BodyForm::Split) => {
1919 let at = children
1920 .iter()
1921 .position(|child| is_body_placeholder(template, child))
1922 .ok_or_else(|| {
1923 LowerError::structure(
1924 "a recomposable environment without its body placeholder",
1925 )
1926 })?;
1927 slots.push((
1928 String::from(BEGIN_SLOT),
1929 template_run(cx, lw, &recomposition, template, &children[..at])?,
1930 ));
1931 slots.push((
1932 String::from(END_SLOT),
1933 template_run(cx, lw, &recomposition, template, &children[at + 1..])?,
1934 ));
1935 }
1936 // The body arrives as the last argument, so the whole template is
1937 // the begin code — the body written where the template puts it, as
1938 // that argument's parameter — and the end code is empty.
1939 Some(BodyForm::Argument) => {
1940 slots.push((
1941 String::from(BEGIN_SLOT),
1942 template_run(cx, lw, &recomposition, template, &children)?,
1943 ));
1944 slots.push((String::from(END_SLOT), Vec::new()));
1945 }
1946 // A macro has no body form; an environment always has one.
1947 None => {
1948 return Err(LowerError::structure(
1949 "an environment whose template has no body form",
1950 ));
1951 }
1952 },
1953 }
1954 // Required once the template is lowered, which may yet expand the use
1955 // sites instead (see the module documentation).
1956 if recomposition.packs() {
1957 // A packed definition's body reads its arguments out of the one group
1958 // the call hands over, with the style file's accessor and its two
1959 // tests; nothing else needs that piece, and a definition of nine
1960 // effective arguments or fewer names its parameters directly. The
1961 // blank-test piece comes with it whether or not this definition asks a
1962 // blank test, since the packed blank test calls `\flmIfBlankTF`:
1963 // `preamble::user_args_piece` requires `preamble::IF_BLANK`.
1964 lw.require(&Name::from(preamble::USER_ARGS));
1965 } else if recomposition.needs_blank_test() {
1966 lw.require(&Name::from(preamble::IF_BLANK));
1967 }
1968 let (recomposed, robust) = {
1969 let options = lw.option::<LatexRecomposedRenderOptions>()?;
1970 let name = recomposed_name(
1971 kind,
1972 definition.name.as_str(),
1973 latex_mode(value),
1974 &options.bare_names,
1975 );
1976 (name, asks_for_robustness(kind, definition.name.as_str(), &options.robust_names))
1977 };
1978 let mut payload = LatexDefinitionPayload::new(kind, recomposed, signature.arity())
1979 .with_source_name(definition.name.as_str());
1980 if recomposition.packs() {
1981 payload = payload.packed();
1982 }
1983 if robust {
1984 payload = payload.robust();
1985 }
1986 if recomposition.body_parameter().is_some() {
1987 payload = payload.body_argument();
1988 }
1989 lw.pres_slots_with(cx, &ElementName::from(DEFINITION), payload, slots)
1990}
1991
1992/// Returns what the use site `node` substitutes for the declared argument
1993/// `index` when the use site left that argument out: the argument's declared
1994/// default value from the recomposed templates, instantiated at the use site
1995/// ([`ModeVariant::instantiate_default`]), with every placeholder in it
1996/// replaced by what the use site wrote and every conditional in it evaluated.
1997/// The same function computes what the expansion of that use site would
1998/// substitute there, so the two are identical. `None` when the argument has no
1999/// declared default value: the call then writes an empty group in its place.
2000///
2001/// The call writes the result as that argument's value, like any other value:
2002/// lowered through the rules in text, and written from its nodes inside
2003/// mathematics ([`MathWriter::arguments`]).
2004fn resolved_default(
2005 node: &NodeRef<'_, Flm>,
2006 variant: &ModeVariant,
2007 index: usize,
2008) -> Result<Option<NodeTree<Flm>>, LowerError> {
2009 // The instantiation runs under the stack budget, the policy every
2010 // registry outside a test runs under: the lowering façade exposes no
2011 // guard policy, and the use site is one subtree on the lowering stage's
2012 // worker thread.
2013 //
2014 // A failure here is not a user's mistake, which is why it is a
2015 // `LowerError` with prose rather than a diagnostic of its own: the two
2016 // ways a default could fail to resolve are both refused when the registry
2017 // is built. A default holding a placeholder no use site can answer is
2018 // refused by `check_placeholders` above (`HookPlaceholder`; a placeholder
2019 // written with a substitution argument refuses the definition earlier
2020 // still, at compilation, leaving it `NotCompiled`), and defaults that
2021 // refer to each other in a circle are refused by the default-cycle check
2022 // of `lang::rewrites::userdefs::definition`. What can still reach this arm
2023 // is a guard refusal or an implementation failure.
2024 variant.instantiate_default(*node, index, GuardPolicy::StackBudget).transpose().map_err(
2025 |error| {
2026 LowerError::other(format!(
2027 "resolving the default of the argument at index {index} failed: {error}"
2028 ))
2029 },
2030 )
2031}
2032
2033/// The body of every `emit-call` rule: it writes a use site as a canonical call
2034/// of the definition and stages the definition construct for the style file,
2035/// or instantiates the use site when the definition is not recomposable or its
2036/// template needs a placeholder's characters (see the module documentation).
2037/// The expansion depth limit of the use sites it instantiates is the
2038/// definition's ([`UserDefinition::recursion_limit`]).
2039///
2040/// Build the rule of a definition with [`emit_call_rule`].
2041#[derive(Debug, Default, Clone, Copy)]
2042pub struct EmitCall;
2043
2044impl EmitCall {
2045 /// Stages the call construct of the use site `node` and returns it: the
2046 /// macro or environment construct under the definition's recomposed name,
2047 /// with one mandatory argument slot per effective argument, in the order of
2048 /// the effective signature. This is the *canonical call*, one brace group
2049 /// per effective argument and nothing else, so that LaTeX parses nothing of
2050 /// its own at a call. An environment's body follows in its body slot.
2051 ///
2052 /// Each value slot holds what the expansion would substitute for a
2053 /// placeholder of its declared argument: the content the use site wrote, or
2054 /// the argument's declared default value lowered in its place, or nothing.
2055 /// A tack-on argument has no slot, because no template may refer to it, so
2056 /// the field macros the use site wrote at its position are not written.
2057 /// Each flag slot holds `\BooleanTrue` where the use site wrote that
2058 /// argument and `\BooleanFalse` where it did not, which the body's
2059 /// `\IfBooleanTF` reads.
2060 fn call_construct(
2061 cx: &mut LowerCx<'_>,
2062 lw: &mut dyn Lowerer,
2063 node: &NodeRef<'_, Flm>,
2064 value: &UserDefinition,
2065 ) -> Result<BuildId, LowerError> {
2066 let definition = value.definition();
2067 let variant = recomposed_variant(value)
2068 .ok_or_else(|| LowerError::structure("a recomposable definition without a template"))?;
2069 let signature = value.effective_signature().ok_or_else(|| {
2070 LowerError::structure("a recomposable definition without its effective signature")
2071 })?;
2072 let recomposition = Recomposition { definition, variant: &variant, signature };
2073 let mut shapes = Vec::new();
2074 let mut slots = Vec::new();
2075 for &index in signature.values() {
2076 shapes.push(LatexArgShape::Mandatory);
2077 let content = match substituted_argument_nodes(node, index) {
2078 Some(nodes) => lw.lower_nodes(cx, nodes)?,
2079 None => match resolved_default(node, &variant, index)? {
2080 Some(resolved) => lw.splice(cx, &Arc::new(resolved))?,
2081 None => Vec::new(),
2082 },
2083 };
2084 slots.push((String::from(ARG_SLOT), content));
2085 }
2086 for index in signature.flagged() {
2087 shapes.push(LatexArgShape::Mandatory);
2088 let written = node.argument_content_nodes(*index).is_some();
2089 slots.push((String::from(ARG_SLOT), vec![flag_group(cx, lw, written)?]));
2090 }
2091 let kind = latex_kind(definition)?;
2092 let name = {
2093 let bare = &lw.option::<LatexRecomposedRenderOptions>()?.bare_names;
2094 recomposed_name(kind, definition.name.as_str(), latex_mode(value), bare)
2095 };
2096 let packs = recomposition.packs();
2097 match kind {
2098 // A user definition is a macro or an environment ([`latex_kind`]).
2099 LatexDefinitionKind::Declaration => {
2100 Err(LowerError::structure("a user definition recomposed as a declaration"))
2101 }
2102 LatexDefinitionKind::Macro => {
2103 let mut payload = LatexMacroPayload::new(name, shapes);
2104 if packs {
2105 payload = payload.packed();
2106 }
2107 lw.pres_slots_with(cx, &ElementName::from(MACRO), payload, slots)
2108 }
2109 LatexDefinitionKind::Environment => {
2110 let body = if node.body().is_some() { lw.lower_body(cx, node)? } else { Vec::new() };
2111 slots.push((String::from(BODY_SLOT), body));
2112 let mut payload = LatexEnvironmentPayload::new(name, shapes);
2113 if packs {
2114 payload = payload.packed();
2115 }
2116 // The call says what the definition says: whether LaTeX hands
2117 // the body over as an argument, read from the same `body_form`
2118 // the definition is written from. The emitter needs it at the
2119 // call, where the body is written — a body LaTeX *sets* stands
2120 // on lines of the file, and a body handed over as an argument
2121 // is a group of tokens, which is what decides how verbatim
2122 // content inside it is written.
2123 if recomposition.body_parameter().is_some() {
2124 payload = payload.body_argument();
2125 }
2126 lw.pres_slots_with(cx, &ElementName::from(ENVIRONMENT), payload, slots)
2127 }
2128 }
2129 }
2130}
2131
2132/// Stages the content of one flag of a canonical call as a raw node
2133/// (`flm.pres.latex.raw`, raw LaTeX written byte for byte) and returns it:
2134/// `\BooleanTrue` where the use site wrote the argument, `\BooleanFalse`
2135/// where it did not. LaTeX's `\IfBooleanTF`, with which the definition's body
2136/// asks the question, reads exactly these two values.
2137fn flag_group(
2138 cx: &mut LowerCx<'_>,
2139 lw: &mut dyn Lowerer,
2140 written: bool,
2141) -> Result<BuildId, LowerError> {
2142 let text = if written { BOOLEAN_TRUE } else { BOOLEAN_FALSE };
2143 lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
2144}
2145
2146impl Lower for EmitCall {
2147 fn lower(
2148 &self,
2149 node: NodeRef<'_, Flm>,
2150 cx: &mut LowerCx<'_>,
2151 lw: &mut dyn Lowerer,
2152 ) -> Result<Lowering, LowerError> {
2153 let value = value_of(&node)?;
2154 if value.recomposable().is_err() {
2155 return instantiate(node, cx, lw);
2156 }
2157 // A rule of the template needs the characters of a placeholder: the
2158 // definition cannot be written for LaTeX, so the use site is expanded,
2159 // as every use site of it is, since its template is the same at each.
2160 // Only the rule reading a placeholder knows whether it needs the
2161 // characters, so the answer comes from lowering the template, not from
2162 // a test of the template's shape.
2163 let definition_node = match definition_construct(cx, lw, value) {
2164 Err(LowerError::PlaceholderCharacters) => return instantiate(node, cx, lw),
2165 other => other?,
2166 };
2167 let call = Self::call_construct(cx, lw, &node, value)?;
2168 // A definition that uses itself meets its own construct while that
2169 // construct is being staged, and stages nothing a second time: the
2170 // definition the outer staging is writing is the one this call calls.
2171 Ok(Lowering::Emit(match definition_node {
2172 Some(definition_node) => vec![definition_node, call],
2173 None => vec![call],
2174 }))
2175 }
2176}
2177
2178/// Returns the `emit-call` rule of `definition`, a definition whose expansion
2179/// policy is `per-plan`. The rule targets the definition's element, requires
2180/// `flm.userdefs.kept`, reads the render options of the `latex-recomposed`
2181/// backend ([`LatexRecomposedRenderOptions`]), and is the default on that
2182/// backend alone. It declares the LaTeX constructs it produces: the definition
2183/// construct, the call construct of the definition's kind (the macro construct
2184/// for a macro, the environment construct for an environment) and the raw
2185/// node that holds a flag; for a special character sequence, which is never
2186/// recomposable, it declares none. A definition that is not recomposable
2187/// stages nothing of its own: its use sites are instantiated, and the rules of
2188/// the elements its template holds stage what the expansion becomes. See the
2189/// module documentation.
2190pub fn emit_call_rule(definition: &Definition) -> LoweringRule {
2191 let decl = LoweringDecl::new().requires(KEPT).option::<LatexRecomposedRenderOptions>();
2192 let decl = match definition.kind {
2193 DefinitionKind::Macro => decl.produces(DEFINITION).produces(MACRO).produces(RAW),
2194 DefinitionKind::Environment => {
2195 decl.produces(DEFINITION).produces(ENVIRONMENT).produces(RAW)
2196 }
2197 DefinitionKind::Specials => decl,
2198 };
2199 LoweringRule::new(
2200 emit_call_rule_name(definition),
2201 element_name(definition),
2202 decl,
2203 Arc::new(EmitCall),
2204 DefaultMark::OnBackends(vec![BACKEND.into()]),
2205 )
2206 .docs(format!(
2207 "a use site of `{}` kept in the tree is written as a call, and the definition \
2208 itself into the style file (requires `flm.userdefs.kept`); the use site is expanded \
2209 instead when the definition cannot be written as one LaTeX definition or its \
2210 template needs the characters of an argument",
2211 definition.display_name()
2212 ))
2213}
2214
2215// --- mathematics ----------------------------------------------------------------------------------
2216
2217/// One part of the mathematics that [`write_math_run`] writes for the output:
2218/// LaTeX to write byte for byte, a source comment the writer staged, or
2219/// another node the writer staged, such as the definition construct
2220/// ([`flm.pres.latex.definition`](DEFINITION)) of a recomposable definition
2221/// used in the run, which the emitter writes into the style file.
2222#[derive(Debug)]
2223pub enum MathPiece {
2224 /// LaTeX to write byte for byte.
2225 Text(String),
2226 /// A source comment, staged as its comment node: the emitter writes it
2227 /// and ends its line, or writes nothing for it, whitespace included,
2228 /// under the render option
2229 /// [`drop_comments`](LatexRecomposedRenderOptions::drop_comments). A
2230 /// writer of lines needs to know where a line ends (see the `math`
2231 /// library's [newline
2232 /// rule](crate::stdlib::features::math::latex#the-newline-rule)).
2233 Comment(BuildId),
2234 /// Any other node the writer staged, to be written at its place in the
2235 /// run.
2236 Node(BuildId),
2237}
2238
2239/// Writes a run of nodes in mathematics mode for the `latex-recomposed` output
2240/// (see "Mathematics" in the module documentation), and returns the parts
2241/// written ([`MathPiece`]).
2242///
2243/// The nodes' source is written byte for byte, except for:
2244///
2245/// - a use site of a recomposable user definition, written as its canonical
2246/// call (the definition's recomposed name and one brace group per effective
2247/// argument, their content written by the same writer), preceded by the
2248/// definition construct for the style file;
2249/// - a use site of any other user definition, written as its expansion,
2250/// written back as LaTeX source, with the use sites inside the expansion handled in
2251/// turn;
2252/// - a [`LatexPoint`] node of a copied template, written as the LaTeX it
2253/// carries;
2254/// - a source comment and a text command (`\text{…}`), lowered through the
2255/// rules and returned as staged nodes ([`MathPiece::Comment`] for a
2256/// comment).
2257///
2258/// A node that holds one of these inside it is written from its source with
2259/// the inner node's span cut out and the inner node written in its place. The
2260/// mathematics itself is never lowered through the rules.
2261///
2262/// The callers are the `math` library's line writer of the display-math
2263/// environments
2264/// ([`stage_lines`](crate::stdlib::features::math::latex::stage_lines)), the
2265/// `math-passthrough` feature's rule for `flm.math` on the `latex-recomposed`
2266/// backend and, for a template for mathematics mode, this module's staging of
2267/// a definition construct. [`stage_math_run`] writes the run and
2268/// stages the result.
2269///
2270/// # Errors
2271///
2272/// A [`LowerError`] when a use site cannot be copied or expanded, or a
2273/// construct cannot be staged.
2274pub fn write_math_run(
2275 cx: &mut LowerCx<'_>,
2276 lw: &mut dyn Lowerer,
2277 nodes: &[NodeRef<'_, Flm>],
2278) -> Result<Vec<MathPiece>, LowerError> {
2279 let mut writer = MathWriter::new(cx, lw, Nodes::OfTheTree);
2280 writer.run(nodes)?;
2281 Ok(writer.finish())
2282}
2283
2284/// Stages the parts [`write_math_run`] wrote, in order: each text part as a
2285/// raw node ([`flm.pres.latex.raw`](RAW)), each node as it is. Returns the
2286/// staged nodes.
2287///
2288/// # Errors
2289///
2290/// A [`LowerError`] when a raw node cannot be staged.
2291fn stage_math_pieces(
2292 cx: &mut LowerCx<'_>,
2293 lw: &mut dyn Lowerer,
2294 pieces: Vec<MathPiece>,
2295) -> Result<Vec<BuildId>, LowerError> {
2296 pieces
2297 .into_iter()
2298 .map(|piece| match piece {
2299 MathPiece::Text(text) => {
2300 lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
2301 }
2302 MathPiece::Comment(id) | MathPiece::Node(id) => Ok(id),
2303 })
2304 .collect()
2305}
2306
2307/// Writes a run of nodes in mathematics mode with [`write_math_run`] and stages
2308/// the result: each text part as a raw node (`flm.pres.latex.raw`), each staged
2309/// node as it is. Returns the staged nodes, in order.
2310///
2311/// # Errors
2312///
2313/// A [`LowerError`] when [`write_math_run`] fails, or when a raw node cannot
2314/// be staged.
2315pub fn stage_math_run(
2316 cx: &mut LowerCx<'_>,
2317 lw: &mut dyn Lowerer,
2318 nodes: &[NodeRef<'_, Flm>],
2319) -> Result<Vec<BuildId>, LowerError> {
2320 let pieces = write_math_run(cx, lw, nodes)?;
2321 stage_math_pieces(cx, lw, pieces)
2322}
2323
2324/// Whether the mathematics writer must write `node` itself rather than copy it
2325/// as source: a use site of a user definition, a [`LatexPoint`] node of a
2326/// copied template, a source comment, or a construct that reads an argument of
2327/// its own as text ([`is_math_text_command`]).
2328///
2329/// A source comment is in this list because a comment reaches the recomposed
2330/// output through a single writer, the LaTeX family's sink, which ends the
2331/// comment's line itself; the writer therefore stages the comment node for the
2332/// emitter instead of copying its `%` into text that nothing would end.
2333///
2334/// A construct that reads an argument of its own as text (a text command
2335/// inside a formula, `\text{…}`) is in this list because that argument is
2336/// document text, not notation: it goes through the lowering rules, which
2337/// escape it, write a user definition used in it as its call, and write
2338/// mathematics nested in it from its nodes, as they do for text anywhere
2339/// else.
2340fn is_written(node: &NodeRef<'_, Flm>) -> bool {
2341 node.comment().is_some()
2342 || element_value::<UserDefinition>(node).is_some()
2343 || element_value::<LatexPoint>(node).is_some()
2344 || is_math_text_command(node)
2345}
2346
2347/// Whether `node`, or one of its descendants, is something the mathematics
2348/// writer must write itself ([`is_written`]).
2349fn needs_writing(node: &NodeRef<'_, Flm>) -> bool {
2350 is_written(node) || node.descendants().any(|descendant| is_written(&descendant))
2351}
2352
2353/// The mathematics writer behind [`write_math_run`]: it collects text and
2354/// adds it as one text part before each staged node.
2355struct MathWriter<'a, 'c> {
2356 cx: &'a mut LowerCx<'c>,
2357 lw: &'a mut dyn Lowerer,
2358 pieces: Vec<MathPiece>,
2359 text: String,
2360 nodes: Nodes,
2361}
2362
2363/// Which tree the nodes being written belong to, which decides how the
2364/// mathematics writer has a node lowered through the rules.
2365#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2366enum Nodes {
2367 /// The tree being lowered: a node is lowered in place.
2368 OfTheTree,
2369 /// A tree that the writer's caller built (a template's copy, a use site's
2370 /// expansion), which the lowering does not hold: a node is copied into a
2371 /// synthesized value of its own and spliced, since only the nodes of the
2372 /// tree being lowered, of a spliced value, or of a lowered node region can
2373 /// be lowered.
2374 Synthesized,
2375}
2376
2377impl<'a, 'c> MathWriter<'a, 'c> {
2378 fn new(cx: &'a mut LowerCx<'c>, lw: &'a mut dyn Lowerer, nodes: Nodes) -> Self {
2379 MathWriter { cx, lw, pieces: Vec::new(), text: String::new(), nodes }
2380 }
2381
2382 /// Returns the parts written, the text collected last included.
2383 fn finish(mut self) -> Vec<MathPiece> {
2384 self.flush();
2385 self.pieces
2386 }
2387
2388 fn flush(&mut self) {
2389 if !self.text.is_empty() {
2390 self.pieces.push(MathPiece::Text(std::mem::take(&mut self.text)));
2391 }
2392 }
2393
2394 /// Writes a run of nodes: each stretch of nodes that need no writing of
2395 /// their own is written back as LaTeX source, and every other node is written
2396 /// ([`write`](MathWriter::write)).
2397 fn run<'t>(&mut self, nodes: &[NodeRef<'t, Flm>]) -> Result<(), LowerError> {
2398 let mut stretch: Vec<NodeRef<'t, Flm>> = Vec::new();
2399 for node in nodes {
2400 if needs_writing(node) {
2401 self.text.push_str(&recompose_source(&stretch));
2402 stretch.clear();
2403 self.write(*node)?;
2404 } else {
2405 stretch.push(*node);
2406 }
2407 }
2408 self.text.push_str(&recompose_source(&stretch));
2409 Ok(())
2410 }
2411
2412 /// Writes one node that is, or holds, a use site, a [`LatexPoint`] node, a
2413 /// source comment or a construct that reads an argument of its own as
2414 /// text.
2415 fn write(&mut self, node: NodeRef<'_, Flm>) -> Result<(), LowerError> {
2416 if node.comment().is_some() {
2417 return self.lowered(node);
2418 }
2419 if is_math_text_command(&node) {
2420 return self.lowered(node);
2421 }
2422 if let Some(value) = element_value::<UserDefinition>(&node) {
2423 return self.use_site(node, value);
2424 }
2425 if let Some(point) = element_value::<LatexPoint>(&node) {
2426 self.text.push_str(&point.text);
2427 return Ok(());
2428 }
2429 if let Some((open, close)) = node.group_delimiters() {
2430 let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
2431 self.text.push_str(open);
2432 self.run(&children)?;
2433 self.text.push_str(close);
2434 return Ok(());
2435 }
2436 if node.is_list() {
2437 let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
2438 return self.run(&children);
2439 }
2440 self.with_holes(node)
2441 }
2442
2443 /// Writes a node that holds a use site among its descendants without being
2444 /// a group or a list (a command whose argument or body holds one): its
2445 /// source with each child's span cut out and the child written in its
2446 /// place, byte for byte where the children's spans lie in order inside the
2447 /// node's own span. Where they do not (a child inserted from another
2448 /// source, or a span that does not cut the source at a character
2449 /// boundary), the whole node is written back as LaTeX source, with every use site
2450 /// inside it written as the author typed it, after the definition construct
2451 /// of each recomposable definition used inside it has been staged, so that
2452 /// the recomposed LaTeX still compiles ([`whole`](MathWriter::whole)).
2453 fn with_holes(&mut self, node: NodeRef<'_, Flm>) -> Result<(), LowerError> {
2454 let span = node.span();
2455 let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
2456 let tiles = children.iter().all(|child| {
2457 child.span().same_source(span)
2458 && child.span().start() >= span.start()
2459 && child.span().end() <= span.end()
2460 }) && children.windows(2).all(|pair| pair[0].span().end() <= pair[1].span().start());
2461 let content = span.source().content();
2462 let mut pieces = Vec::with_capacity(children.len() + 1);
2463 let mut at = span.start();
2464 let mut cut = tiles;
2465 for child in &children {
2466 match content.get(at..child.span().start()) {
2467 Some(gap) if cut => pieces.push(gap),
2468 _ => cut = false,
2469 }
2470 at = child.span().end();
2471 }
2472 let tail = content.get(at..span.end());
2473 if !cut || tail.is_none() {
2474 return self.whole(node);
2475 }
2476 for (gap, child) in pieces.iter().zip(&children) {
2477 self.text.push_str(gap);
2478 self.run(std::slice::from_ref(child))?;
2479 }
2480 self.text.push_str(tail.unwrap_or_default());
2481 Ok(())
2482 }
2483
2484 /// The fallback of [`with_holes`](Self::with_holes): stages the definition
2485 /// construct of every recomposable definition used inside `node`, then
2486 /// writes the whole node back as LaTeX source.
2487 fn whole(&mut self, node: NodeRef<'_, Flm>) -> Result<(), LowerError> {
2488 for descendant in node.descendants() {
2489 if let Some(value) = element_value::<UserDefinition>(&descendant) {
2490 if value.recomposable().is_ok() {
2491 if let Some(construct) = definition_construct(self.cx, self.lw, value)? {
2492 self.flush();
2493 self.pieces.push(MathPiece::Node(construct));
2494 }
2495 }
2496 }
2497 }
2498 self.text.push_str(&recompose_source(&[node]));
2499 Ok(())
2500 }
2501
2502 /// Has one node lowered through the rules and adds the staged nodes as parts
2503 /// of their own, rather than copying the node as source.
2504 ///
2505 /// Two kinds of node take this route. A **source comment**, so that the
2506 /// emitter writes it through the sink's comment writer (the prefix, the
2507 /// text, the newline that ends the comment's line, and the whitespace that
2508 /// followed it in the source except that newline), or writes nothing for
2509 /// it where comments are dropped. A **text command**, so that its argument
2510 /// is written as the document text it is; the `math` feature's rule for the
2511 /// element writes the command back and lowers the argument.
2512 fn lowered(&mut self, node: NodeRef<'_, Flm>) -> Result<(), LowerError> {
2513 let ids = match self.nodes {
2514 Nodes::OfTheTree => lower_run(self.cx, self.lw, std::slice::from_ref(&node))?,
2515 Nodes::Synthesized => {
2516 let value = copy_run_into_value(&[node], &node, ValueContent::Own, GuardPolicy::StackBudget)
2517 .map_err(|error| LowerError::other(format!("copying the node failed: {error}")))?;
2518 self.lw.splice(self.cx, &value)?
2519 }
2520 };
2521 self.flush();
2522 let comment = node.comment().is_some();
2523 for id in ids {
2524 self.pieces.push(if comment { MathPiece::Comment(id) } else { MathPiece::Node(id) });
2525 }
2526 Ok(())
2527 }
2528
2529 /// Writes a use site: the definition construct and the canonical call for
2530 /// a recomposable definition; the expansion, written back as LaTeX source, for any
2531 /// other definition and for one whose template needs a placeholder's
2532 /// characters.
2533 fn use_site(&mut self, node: NodeRef<'_, Flm>, value: &UserDefinition) -> Result<(), LowerError> {
2534 if value.recomposable().is_err() {
2535 return self.expansion(node, value);
2536 }
2537 // As `emit-call` does: a template whose rules need the characters of
2538 // a placeholder has its use sites expanded.
2539 let construct = match definition_construct(self.cx, self.lw, value) {
2540 Err(LowerError::PlaceholderCharacters) => return self.expansion(node, value),
2541 other => other?,
2542 };
2543 if let Some(construct) = construct {
2544 self.flush();
2545 self.pieces.push(MathPiece::Node(construct));
2546 }
2547 let definition = value.definition();
2548 let kind = latex_kind(definition)?;
2549 let name = {
2550 let bare = &self.lw.option::<LatexRecomposedRenderOptions>()?.bare_names;
2551 recomposed_name(kind, definition.name.as_str(), latex_mode(value), bare)
2552 };
2553 match kind {
2554 // A user definition is a macro or an environment ([`latex_kind`]).
2555 LatexDefinitionKind::Declaration => {
2556 return Err(LowerError::structure("a user definition recomposed as a declaration"));
2557 }
2558 LatexDefinitionKind::Macro => {
2559 self.text.push('\\');
2560 self.text.push_str(&name);
2561 // The call's own groups follow the name directly. Where it
2562 // writes none — the effective signature is empty, the
2563 // definition declaring no argument or only a tack-on argument,
2564 // which carries neither a value nor a flag — the space the
2565 // writer left after the name is written back, so that a letter
2566 // after it does not extend the name.
2567 if value.effective_signature().is_some_and(|signature| signature.arity() == 0) {
2568 if let Some(InvocationSyntaxData::Macro { post_space, .. }) =
2569 node.invocation_syntax()
2570 {
2571 self.text.push_str(post_space.resolve(node.span().source()));
2572 }
2573 }
2574 self.arguments(&node, value)?;
2575 }
2576 LatexDefinitionKind::Environment => {
2577 self.text.push_str(&format!("\\begin{{{name}}}"));
2578 self.arguments(&node, value)?;
2579 if let Some(body) = node.body() {
2580 let nodes: Vec<NodeRef<'_, Flm>> = body.iter().collect();
2581 self.run(&nodes)?;
2582 }
2583 self.text.push_str(&format!("\\end{{{name}}}"));
2584 }
2585 }
2586 Ok(())
2587 }
2588
2589 /// Writes a use site as its expansion, written back as LaTeX source, with the use
2590 /// sites inside the expansion handled in turn.
2591 fn expansion(&mut self, node: NodeRef<'_, Flm>, value: &UserDefinition) -> Result<(), LowerError> {
2592 let expanded = expansion_of(node, value, self.lw)?;
2593 let children: Vec<NodeRef<'_, Flm>> = expanded.root().children().iter().collect();
2594 let nodes = std::mem::replace(&mut self.nodes, Nodes::Synthesized);
2595 let written = self.run(&children);
2596 self.nodes = nodes;
2597 written
2598 }
2599
2600 /// Writes the use site's effective arguments, in the order of the
2601 /// definition's effective signature: one brace group per declared argument
2602 /// that carries a value (every one except a tack-on argument), holding what
2603 /// the expansion would substitute there (the content the use site wrote,
2604 /// written by this writer so that a use site inside an argument is handled
2605 /// too; or the argument's declared default value; or nothing), then one
2606 /// brace group per flag. When the call packs its arguments, one more pair
2607 /// of braces surrounds them all. This is the same canonical call that
2608 /// `emit-call` stages in text, written here as text.
2609 fn arguments(
2610 &mut self,
2611 node: &NodeRef<'_, Flm>,
2612 value: &UserDefinition,
2613 ) -> Result<(), LowerError> {
2614 let definition = value.definition();
2615 let variant = recomposed_variant(value)
2616 .ok_or_else(|| LowerError::structure("a recomposable definition without a template"))?;
2617 let signature = value.effective_signature().ok_or_else(|| {
2618 LowerError::structure("a recomposable definition without its effective signature")
2619 })?;
2620 let packs = Recomposition { definition, variant: &variant, signature }.packs();
2621 if packs {
2622 self.text.push('{');
2623 }
2624 for &index in signature.values() {
2625 self.text.push('{');
2626 match substituted_argument_nodes(node, index) {
2627 Some(content) => {
2628 let nodes: Vec<NodeRef<'_, Flm>> = content.iter().collect();
2629 self.run(&nodes)?;
2630 }
2631 None => {
2632 if let Some(resolved) = resolved_default(node, &variant, index)? {
2633 let nodes: Vec<NodeRef<'_, Flm>> =
2634 resolved.root().children().iter().collect();
2635 self.run(&nodes)?;
2636 }
2637 }
2638 }
2639 self.text.push('}');
2640 }
2641 for index in signature.flagged() {
2642 let written = node.argument_content_nodes(*index).is_some();
2643 let flag = if written { BOOLEAN_TRUE } else { BOOLEAN_FALSE };
2644 self.text.push_str(&format!("{{{flag}}}"));
2645 }
2646 if packs {
2647 self.text.push('}');
2648 }
2649 Ok(())
2650 }
2651}
2652
2653/// Registers, through the feature builder `b`, what the `userdefs` feature
2654/// contributes once for the `latex-recomposed` backend, regardless of the
2655/// definitions it holds: a peer declaration
2656/// ([`PeerName`](crate::core::registry::PeerName)) of the backend and of each
2657/// of the four LaTeX constructs the `emit-call` rules stage, with the
2658/// construct's payload type as its signature.
2659///
2660/// The `userdefs` feature registers neither the backend nor the construct
2661/// elements, which the LaTeX features own. Because they are peer
2662/// declarations, a registry without the LaTeX features still builds: the
2663/// `emit-call` rules are then set aside (excluded from rule selection; see
2664/// [`PeerName`](crate::core::registry::PeerName)).
2665///
2666/// The rules of each definition are created beside its element by the
2667/// feature's own registration; the rule that writes the placeholders of a
2668/// recomposed template belongs to the LaTeX family
2669/// ([`placeholder_rule`](crate::stdlib::backends::latex::placeholder_rule)).
2670///
2671/// # Errors
2672///
2673/// Never fails: the builder's peer declarations report their problems when
2674/// the registry is built.
2675pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
2676 b.peer_backend(
2677 BACKEND,
2678 "the `latex-recomposed` backend, on which the `emit-call` rules of the user \
2679 definitions are the default",
2680 )?;
2681 b.peer_element::<LatexDefinitionPayload>(
2682 DEFINITION,
2683 "the LaTeX definition construct, which the `emit-call` rules produce for the style \
2684 file",
2685 )?;
2686 b.peer_element::<LatexMacroPayload>(
2687 MACRO,
2688 "the LaTeX macro-call construct, which the `emit-call` rules produce for a call of a \
2689 macro",
2690 )?;
2691 b.peer_element::<LatexEnvironmentPayload>(
2692 ENVIRONMENT,
2693 "the LaTeX environment construct, which the `emit-call` rules produce for a call of \
2694 an environment",
2695 )?;
2696 b.peer_element::<LatexRawPayload>(
2697 RAW,
2698 "the raw LaTeX construct, which the `emit-call` rules produce for the flags of a \
2699 call",
2700 )?;
2701 Ok(())
2702}
2703
2704#[cfg(test)]
2705mod tests {
2706 use super::*;
2707 use crate::lang::mint::{ArgDef, ArgStdKind, TackOnField};
2708 use crate::lang::rewrites::userdefs::{BadDefinition, DefinitionProblem};
2709 use crate::lang::{LangInputs, build_language};
2710 use crate::model::names::CapName;
2711
2712 #[test]
2713 fn the_two_rules_of_a_definition_require_kept_and_differ_in_their_default_mark() {
2714 let definition = Definition::macro_("foo", vec![ArgDef::mandatory("x")]).content("#1");
2715 let instantiate = instantiate_at_lowering_rule(&definition);
2716 assert_eq!(instantiate.name, "flm.userdefs.macro.foo.lower.instantiate-at-lowering");
2717 assert_eq!(instantiate.element, "flm.userdefs.macro.foo");
2718 assert_eq!(instantiate.decl.requires, [CapName::from(KEPT)]);
2719 assert!(instantiate.decl.produces.is_empty());
2720 assert_eq!(instantiate.default, DefaultMark::Never);
2721 let emit = emit_call_rule(&definition);
2722 assert_eq!(emit.name, "flm.userdefs.macro.foo.lower.emit-call");
2723 assert_eq!(emit.decl.requires, [CapName::from(KEPT)]);
2724 assert_eq!(
2725 emit.decl.produces,
2726 [ElementName::from(DEFINITION), ElementName::from(MACRO), ElementName::from(RAW)]
2727 );
2728 assert!(emit.default.is_specific_to(&BACKEND.into()));
2729 let environment = Definition::environment("env", Vec::new()).content("#{body}");
2730 assert_eq!(
2731 emit_call_rule(&environment).decl.produces,
2732 [ElementName::from(DEFINITION), ElementName::from(ENVIRONMENT), ElementName::from(RAW)]
2733 );
2734 let specials = Definition::specials("@", Vec::new()).content("at");
2735 assert!(emit_call_rule(&specials).decl.produces.is_empty());
2736 }
2737
2738 #[test]
2739 fn a_math_only_definition_names_its_rules_with_the_math_segment() {
2740 let definition = Definition::macro_("calN", Vec::new()).math("\\mathcal{N}");
2741 assert_eq!(emit_call_rule_name(&definition), "flm.userdefs.macro.math.calN.lower.emit-call");
2742 }
2743
2744 /// The roster compiled against a language holding nothing but the
2745 /// definitions themselves, recomposability recorded.
2746 fn roster(definitions: Vec<Definition>) -> Vec<Arc<UserDefinition>> {
2747 let values: Vec<Arc<UserDefinition>> =
2748 definitions.into_iter().map(UserDefinition::new).collect();
2749 let mut inputs = LangInputs::new();
2750 inputs.elements = values
2751 .iter()
2752 .map(|value| value.element_def("userdefs", element_name(value.definition())))
2753 .collect();
2754 let lang = build_language(inputs);
2755 for value in &values {
2756 let _ = value.compile(&lang);
2757 }
2758 record_recomposability(&values);
2759 values
2760 }
2761
2762 fn reason(value: &UserDefinition) -> Option<NotRecomposable> {
2763 value.recomposable().err()
2764 }
2765
2766 /// A tack-on argument named `fields`, accepting one field `\mark`: the
2767 /// shape the `refs` feature's `\label` field takes.
2768 fn tack_on_arg() -> ArgDef {
2769 ArgDef::named(
2770 "fields",
2771 ArgStdKind::TackOn {
2772 fields: vec![TackOnField::new("mark", Vec::new())],
2773 },
2774 )
2775 }
2776
2777 #[test]
2778 fn a_template_naming_a_tack_on_argument_is_refused_when_the_definition_is_compiled() {
2779 // Naming a tack-on argument is a definition error at registry build,
2780 // on every backend rather than in this one's recomposition: what the
2781 // call absorbed is whole macros, which have no meaning as the value of
2782 // a parameter. The refusal is raised where the definition is compiled,
2783 // so a template that names one never reaches a recomposability
2784 // outcome at all.
2785 let definition =
2786 Definition::macro_("tack", vec![ArgDef::mandatory("a"), tack_on_arg()])
2787 .content("#1#{fields}");
2788 let value = UserDefinition::new(definition);
2789 let mut inputs = LangInputs::new();
2790 inputs.elements =
2791 vec![value.element_def("userdefs", element_name(value.definition()))];
2792 let lang = build_language(inputs);
2793 let errors = value.compile(&lang).expect_err("the definition is refused");
2794 // The definition declares both modes and its text is compiled once per
2795 // mode, so the same placeholder is refused in each compilation.
2796 assert_eq!(errors.len(), 2, "{errors:?}");
2797 for error in &errors {
2798 assert_eq!(error.identifier(), "flm.userdefs.bad-definition");
2799 let problem = error.data().downcast_ref::<BadDefinition>().map(|bad| &bad.problem);
2800 assert!(
2801 matches!(problem, Some(DefinitionProblem::TackOnPlaceholder { .. })),
2802 "{problem:?}"
2803 );
2804 }
2805 // The same template, with the placeholder inside a conditional's test
2806 // rather than written plainly, is refused by the same rule.
2807 let conditional =
2808 Definition::macro_("tack", vec![ArgDef::mandatory("a"), tack_on_arg()])
2809 .content("#1\\IfProvidedT{#{fields}}{!}");
2810 let value = UserDefinition::new(conditional);
2811 let mut inputs = LangInputs::new();
2812 inputs.elements =
2813 vec![value.element_def("userdefs", element_name(value.definition()))];
2814 let lang = build_language(inputs);
2815 let errors = value.compile(&lang).expect_err("the definition is refused");
2816 assert!(
2817 errors.iter().any(|error| error.identifier() == "flm.userdefs.bad-definition"),
2818 "{errors:?}"
2819 );
2820 }
2821
2822 #[test]
2823 fn a_plain_macro_and_environment_are_recomposable() {
2824 let values = roster(vec![
2825 Definition::macro_("hello", vec![ArgDef::optional("greeting"), ArgDef::mandatory("name")])
2826 .content("#{greeting}, #2!")
2827 .default("greeting", "Hello"),
2828 Definition::environment("note", Vec::new()).content("[Note: #{body}]"),
2829 ]);
2830 assert_eq!(values[0].recomposable(), Ok(()));
2831 assert_eq!(values[1].recomposable(), Ok(()));
2832 }
2833
2834 #[test]
2835 fn every_intrinsic_reason_is_found() {
2836 let values = roster(vec![
2837 Definition::specials("@", Vec::new()).content("[at]"),
2838 // Every argument shape is recomposable: a key-value argument's
2839 // group is written as the use site wrote it, and a verbatim
2840 // argument's characters as the content they are. Two declared
2841 // arguments, two values.
2842 Definition::macro_(
2843 "s",
2844 vec![
2845 ArgDef::new(ArgStdKind::KeyVals),
2846 ArgDef::new(ArgStdKind::Verbatim { delimiters: None }),
2847 ],
2848 )
2849 .content("#1#2"),
2850 // An optional argument at any position is recomposable: every
2851 // argument is a value group at the call.
2852 Definition::macro_("o", vec![ArgDef::mandatory("a"), ArgDef::optional("b")]).content("#1#2"),
2853 // A conditional asking whether an argument with a declared
2854 // default was *written*: the call carries the answer as a flag, so
2855 // this is recomposable and its effective signature is two.
2856 Definition::macro_("c", vec![ArgDef::optional("a")])
2857 .content("\\IfProvidedTF{#1}{x}{y}")
2858 .default("a", "dflt"),
2859 // A default that holds a placeholder of another argument is
2860 // resolved at the use site, by the use site's own bindings, and
2861 // written there: it is recomposable, and so is a default holding
2862 // a conditional.
2863 Definition::macro_(
2864 "d",
2865 vec![ArgDef::optional("a"), ArgDef::mandatory("b"), ArgDef::optional("c")],
2866 )
2867 .content("#1#2#3")
2868 .default("c", "#2")
2869 .default("a", "\\IfProvidedTF{#3}{#3}{none}"),
2870 // An environment whose template never names its body: recomposable,
2871 // taking the body as an argument its begin code never writes.
2872 Definition::environment("e0", Vec::new()).content("no body"),
2873 // An environment that names its body twice, and one that names it
2874 // inside a group: both recomposable, each taking its body as an
2875 // argument of its own.
2876 Definition::environment("e2", Vec::new()).content("#{body}#{body}"),
2877 Definition::environment("en", Vec::new()).content("{#{body}}"),
2878 // A placeholder inside mathematics is written as a parameter, so
2879 // this one is recomposable. Where a placeholder stands elsewhere
2880 // plays no part here either (verbatim content, an address): that
2881 // is found when the template is lowered, an integration test.
2882 Definition::macro_("v", vec![ArgDef::mandatory("a")]).content("\\(#1\\)"),
2883 // One name declared twice, once per parsing mode: two definitions,
2884 // both recomposable, each written under a twin name of its own.
2885 Definition::macro_("twin", Vec::new()).text("t"),
2886 Definition::macro_("twin", Vec::new()).math("m"),
2887 Definition::macro_("always", Vec::new()).content("a").expand(ExpandPolicy::Always),
2888 Definition::macro_("refused", Vec::new()).content("#1"),
2889 // Ten arguments is one more than a LaTeX macro body can name, and
2890 // is recomposable all the same: the call packs.
2891 Definition::macro_("ten", (0..10).map(|i| ArgDef::mandatory(format!("a{i}"))).collect())
2892 .content("x"),
2893 Definition::macro_("pair", Vec::new()).content("m"),
2894 Definition::environment("pair", Vec::new()).content("#{body}"),
2895 // A `*` marker is an argument like any other: its value group
2896 // holds the star the writer wrote, its declared default where they
2897 // wrote none, and a question about it reads the flag.
2898 Definition::macro_("star", vec![ArgDef::new(ArgStdKind::Star), ArgDef::mandatory("x")])
2899 .content("\\IfBooleanTF{#1}{S}{s}#2"),
2900 Definition::macro_("stardflt", vec![ArgDef::new(ArgStdKind::Star)])
2901 .content("#1")
2902 .default("1", "d"),
2903 // A blank test over two arguments at once, one of which a value
2904 // test also asks about: every value group holds plain content, so
2905 // the one test stands over the run of them.
2906 Definition::macro_("blank", vec![ArgDef::optional("a"), ArgDef::mandatory("b")])
2907 .content("\\IfNoValueTF{#1}{x}{y}\\ifblank{#1#2}{b}{n}"),
2908 // Ten effective arguments: five declared, five of them asked
2909 // about. Values and flags count together, so this is one more than
2910 // a LaTeX macro body can name, and the call packs.
2911 Definition::macro_(
2912 "flagged",
2913 (0..5).map(|i| ArgDef::optional(format!("a{i}"))).collect(),
2914 )
2915 .content(
2916 "\\IfProvidedT{#1}{a}\\IfProvidedT{#2}{b}\\IfProvidedT{#3}{c}\\IfProvidedT{#4}{d}\\IfProvidedT{#5}{e}#5",
2917 ),
2918 // A default on a *mandatory* argument is written at the call site
2919 // like any other — at a use site recovered with the argument
2920 // missing — and is resolved there like any other too.
2921 Definition::macro_("dm", vec![ArgDef::mandatory("a"), ArgDef::mandatory("b")])
2922 .content("#1#2")
2923 .default("b", "#1"),
2924 // A definition may declare a tack-on argument — the macros a call
2925 // absorbs after it — and not name it in its template. It is
2926 // recomposable, and the tack-on argument carries no effective
2927 // argument at all: one value for `a` and nothing else.
2928 Definition::macro_("tack", vec![ArgDef::mandatory("a"), tack_on_arg()])
2929 .content("#1!"),
2930 ]);
2931 let reasons: Vec<Option<NotRecomposable>> = values.iter().map(|v| reason(v)).collect();
2932 assert_eq!(reasons[0], Some(NotRecomposable::Specials));
2933 assert_eq!(reasons[1], None);
2934 assert_eq!(reasons[2], None);
2935 assert_eq!(reasons[3], None);
2936 assert_eq!(reasons[4], None);
2937 // An environment whose template never names its body grabs the body
2938 // and drops it, exactly as FLM's own expansion does.
2939 assert_eq!(reasons[5], None);
2940 assert_eq!(reasons[6], None);
2941 assert_eq!(reasons[7], None);
2942 assert_eq!(reasons[8], None);
2943 assert_eq!(reasons[9], None);
2944 assert_eq!(reasons[10], None);
2945 assert!(values[9].shares_its_name());
2946 assert!(values[10].shares_its_name());
2947 // A name the document declares once shares nothing, whichever modes it
2948 // applies in.
2949 assert!(!values[8].shares_its_name());
2950 assert_eq!(reasons[11], Some(NotRecomposable::AlwaysExpanded));
2951 assert_eq!(reasons[12], Some(NotRecomposable::NotCompiled));
2952 assert_eq!(reasons[13], None);
2953 // A macro and an environment of one name are both recomposable: each
2954 // kind is written under a prefix of its own.
2955 assert_eq!(reasons[14], None);
2956 assert_eq!(reasons[15], None);
2957 assert_eq!(reasons[16], None);
2958 assert_eq!(reasons[17], None);
2959 assert_eq!(reasons[18], None);
2960 assert_eq!(reasons[19], None);
2961 assert_eq!(reasons[20], None);
2962 assert_eq!(reasons[21], None);
2963 // The effective signature of a recomposable definition: one value per
2964 // declared argument, then one flag per argument a conditional asks a
2965 // *provided* question about. A key-value and a verbatim argument each
2966 // carry one value like any other.
2967 assert_eq!(values[1].effective_signature(), Some(&EffectiveSignature::new(0..2, [])));
2968 assert_eq!(values[3].effective_signature(), Some(&EffectiveSignature::new(0..1, [0])));
2969 assert_eq!(values[16].effective_signature(), Some(&EffectiveSignature::new(0..2, [0])));
2970 assert_eq!(values[18].effective_signature(), Some(&EffectiveSignature::new(0..2, [0])));
2971 // More effective arguments than a macro body has parameters is no
2972 // reason: ten values, and five values with five flags.
2973 assert_eq!(values[13].effective_signature(), Some(&EffectiveSignature::new(0..10, [])));
2974 assert_eq!(values[19].effective_signature(), Some(&EffectiveSignature::new(0..5, 0..5)));
2975 assert_eq!(values[19].effective_signature().unwrap().arity(), 10);
2976 // The declared tack-on argument carries neither a value nor a flag:
2977 // one value, for the mandatory argument, and nothing else.
2978 assert_eq!(values[21].effective_signature(), Some(&EffectiveSignature::new([0], [])));
2979 // A definition that is not recomposable carries none.
2980 assert_eq!(values[0].effective_signature(), None);
2981 // Three of this roster are written expanded, one of each class that a
2982 // document can reach: the specials by its nature, the `always`
2983 // definition by the author's choice, the refused one by its own
2984 // error. Every other definition here is recomposed.
2985 let expanded: Vec<Option<NotRecomposable>> =
2986 reasons.iter().filter(|reason| reason.is_some()).cloned().collect();
2987 assert_eq!(
2988 expanded,
2989 [
2990 Some(NotRecomposable::Specials),
2991 Some(NotRecomposable::AlwaysExpanded),
2992 Some(NotRecomposable::NotCompiled),
2993 ]
2994 );
2995 }
2996
2997 #[test]
2998 fn a_use_of_a_non_recomposable_definition_spreads_and_a_cycle_is_no_reason() {
2999 let values = roster(vec![
3000 Definition::macro_("a", Vec::new()).content("\\b"),
3001 Definition::macro_("b", Vec::new()).content("\\c"),
3002 // A definition the registry build refuses — its template names an
3003 // argument it does not declare — is the leaf that cannot be
3004 // recomposed, and the refusal spreads up the chain.
3005 Definition::macro_("c", Vec::new()).content("#1"),
3006 // A cycle of definitions, and a definition that uses itself: both
3007 // are recomposed as LaTeX definitions that call each other and
3008 // itself. Whether such a chain ever stops is the document's
3009 // business, and LaTeX's to find where it does not.
3010 Definition::macro_("p", Vec::new()).content("\\q"),
3011 Definition::macro_("q", Vec::new()).content("\\p"),
3012 Definition::macro_("self", Vec::new()).content("\\self"),
3013 Definition::macro_("fine", Vec::new()).content("\\alwaysfine"),
3014 Definition::macro_("alwaysfine", Vec::new()).content("y").expand(ExpandPolicy::Always),
3015 ]);
3016 assert_eq!(reason(&values[0]), Some(NotRecomposable::Uses { name: "\\b".into() }));
3017 assert_eq!(reason(&values[1]), Some(NotRecomposable::Uses { name: "\\c".into() }));
3018 assert_eq!(values[3].recomposable(), Ok(()));
3019 assert_eq!(values[4].recomposable(), Ok(()));
3020 assert_eq!(values[5].recomposable(), Ok(()));
3021 assert_eq!(values[6].recomposable(), Ok(()));
3022 }
3023}