Skip to main content

flm_core/stdlib/features/userdefs/
mod.rs

1//! The `userdefs` feature: it registers every user definition of its
2//! configuration as an element, the rewrite stages that expand their use
3//! sites, and the lowering rules that write the use sites a plan keeps.
4//!
5//! # What the feature provides to an author
6//!
7//! A user definition ([`Definition`]) is a macro, environment or special
8//! character sequence that a document's author or the host defines by
9//! substitution: a name, an argument syntax, a template and the parsing modes
10//! it is defined for. Its template is FLM text with placeholders (`#1`,
11//! `#{name}`, `#{body}`) in the [template
12//! language](crate::lang::rewrites::userdefs::template). A *use site* of a
13//! definition is a place in a document where the document uses it, such as
14//! `\hi{World}` for a macro `\hi`; the use site is replaced by the definition's
15//! template, with the arguments written there in place of the placeholders. A
16//! document's body cannot define a macro: every user definition comes from this
17//! feature's configuration ([`UserdefsConfig`]), which an author writes as
18//! settings (the keys `macros`, `environments` and `specials`,
19//! [`UserdefsData`]), for example in a document's front matter when the `flm`
20//! program reads it. In settings, a definition gives its arguments under the
21//! key `args` ([`DefinitionData::args`]), each argument's syntax in one of two
22//! forms. The structured syntax is a map whose key `syntax` holds the name of
23//! a standard kind of argument and whose other keys hold the kind's
24//! parameters, beside the argument's own keys: `{syntax: delimited-group,
25//! delimiters: ["(", ")"], name: size}` declares a group in parentheses named
26//! `size`. An argument code is a shorthand for a structured syntax, written
27//! under the key `code` of the map or alone: `{code: "r()", name: size}`
28//! declares the same argument, and `"{"` a mandatory group. The language
29//! guide describes definitions for authors:
30//! [author definitions](crate::guide::language_syntax#author-definitions) and
31//! [when a definition is
32//! expanded](crate::guide::language_syntax#when-a-definition-is-expanded).
33//!
34//! A definition's *expansion policy* ([`ExpandPolicy`]) says when its use
35//! sites are expanded: `always`, in every plan, or `per-plan` (the default),
36//! as each plan decides. A plan for any backend other than
37//! `latex-recomposed` expands the use sites of every definition, unless its
38//! plan request selects another lowering rule by name. A plan for the
39//! `latex-recomposed` backend keeps the use sites of a `per-plan` definition in
40//! the tree and writes the definition once as a LaTeX definition in the [style
41//! file](crate::stdlib::backends::latex::style) and each use site as a call of
42//! it; when the definition cannot be written as one LaTeX definition, or its
43//! template needs the characters of an argument, it expands each use site at
44//! lowering instead ([user definitions in the recomposed
45//! LaTeX](crate::guide::rendering#user-definitions-in-the-recomposed-latex)).
46//! The module [`kept`] holds the rules that do this.
47//!
48//! # Definitions are elements
49//!
50//! Every definition of the configuration becomes an element declaration like
51//! any other ([`UserDefinition::element_def`]): an element named
52//! `flm.userdefs.<kind>.<name>` ([`element_name`]) that carries the definition
53//! as its value (a [`UserDefinition`]), the
54//! [`Expand`](crate::lang::rewrites::userdefs::Expand) aspect (an
55//! [aspect](crate::guide::concepts_overview#elements-and-aspects) is behavior
56//! attached to an element; this one is what the expand pass calls to expand a
57//! use site) and the block role the definition declares. An extension written
58//! in Rust registers the same things for an expandable element of its own
59//! ([`element_name_under`],
60//! [`expand_in_tree_rule_for`]); nothing about user definitions is special to
61//! the registry.
62//!
63//! - **The kind is part of the element name**, because an element is found by
64//!   its name: a macro and an environment may have the same written name, and
65//!   they must be two elements with two names.
66//! - **A definition is available in the parsing modes it is defined for, and
67//!   nowhere else** ([`DefinitionModes`]): its element is declared available in
68//!   those modes alone, so a use of it in another mode is an unknown command,
69//!   like any name the registry does not define (reported in running text; kept
70//!   as written without a report inside mathematics, where the `math` feature
71//!   accepts any unknown command). A definition for both modes
72//!   applies in each mode where its template parses; a use in a mode where the
73//!   template does not parse is an Error at that use.
74//! - **One name may be declared twice**, once for text mode and once for
75//!   mathematics mode, with a different template each time: the two never apply
76//!   in the same place, and each becomes an element of its own (the element of
77//!   a definition for mathematics mode alone has an extra `math` segment in its
78//!   name, [`element_name`]). Two definitions of one kind and one name whose
79//!   modes overlap make the registry build fail, since only one of them could
80//!   apply where they overlap.
81//! - **A definition that replaces another feature's command** (marked with
82//!   [`Definition::overriding`]) also registers an override declaration
83//!   ([`FeatureBuilder::override_callable`]). Without it, two features that
84//!   define one command in overlapping modes make the registry build fail with
85//!   an error that gives both, unless the feature order places the feature
86//!   registered last explicitly after the other (the chain
87//!   `mymacros < userdefs` lets a user definition replace a command of a
88//!   feature `mymacros`; see [`crate::core::registry::order`]). A command that
89//!   another feature declares weakly
90//!   ([`ElementDef::weak`](crate::lang::mint::ElementDef::weak)), as a math
91//!   processor declares its notation, needs neither: a user definition of
92//!   `\ket` applies in place of the processor's `\ket`.
93//!
94//! # Capabilities and stages
95//!
96//! A *capability* ([`CapabilityDef`]) is a registered dotted name for a state
97//! of processing that a stage brings about; a stage declares the capabilities
98//! it provides and requires, and a caller demands the capabilities it wants
99//! ([stages, capabilities and
100//! plans](crate::guide::concepts_overview#stages-capabilities-and-plans)). The
101//! feature registers:
102//!
103//! - [`USERDEFS`] (`flm.userdefs`), the parent capability: a decision about the
104//!   `per-plan` definitions has been made. Two capabilities *refine* it
105//!   ([refinement](crate::guide::pipeline#refinement)): each is one way of
106//!   satisfying it, and a plan that demands both is refused.
107//! - [`EXPAND`] (`flm.userdefs.expand`), the rewrite stage
108//!   ([`RewriteStage`](crate::core::stage::RewriteStage): a stage that turns
109//!   one tree into another before the trees are frozen) that expands the use
110//!   sites of the `per-plan` definitions. It publishes its trees in the trees
111//!   table [`EXPANDED`] (`flm.userdefs.expanded`; a [`TreesTable`], the table
112//!   in which a rewrite stage publishes the trees it produces), which is also
113//!   the
114//!   capability it provides, the refinement of `flm.userdefs` marked as the
115//!   default: a plan that demands `flm.userdefs` alone expands the use sites.
116//! - [`KEEP`] (`flm.userdefs.keep`), a marker stage that does nothing and
117//!   provides [`KEPT`] (`flm.userdefs.kept`), the other refinement: the use
118//!   sites stay in the tree for the lowering rules.
119//! - [`EXPAND_ALWAYS`] (`flm.userdefs.expand-always`), the rewrite stage that
120//!   expands the use sites of the `always` definitions. It publishes
121//!   [`ALWAYS_EXPANDED`] (`flm.userdefs.always-expanded`), a capability that
122//!   refines nothing, so it goes with either alternative; `flm.userdefs.expand`
123//!   is ordered after it whenever both are in a plan.
124//!
125//! Both rewrite stages run the expand pass
126//! ([`expand`](crate::lang::rewrites::userdefs::expand)) under the expansion
127//! depth limit of the configuration; the module `stages` holds them.
128//!
129//! # Lowering rules
130//!
131//! Every definition registers its `expand-in-tree` lowering rule
132//! ([`expand_in_tree_rule`], module [`lowering`]), the default on every
133//! backend. The rule requires the trees table of the rewrite stage that expands
134//! the definition (`flm.userdefs.expanded` for a `per-plan` definition,
135//! `flm.userdefs.always-expanded` for an `always` one) and never lowers a use
136//! site, since the stage has replaced every one before lowering. It has two
137//! purposes: the definition's element has a rule on every backend, so that a
138//! plan finds no element without a rule; and selecting the rule puts the
139//! expansion into the plan. Every plan that lowers a registry holding an
140//! `always` definition therefore holds `flm.userdefs.expand-always`.
141//!
142//! A `per-plan` definition registers two more rules, for its use sites kept in
143//! the tree (module [`kept`]): `emit-call` ([`emit_call_rule`]), the default on
144//! the `latex-recomposed` backend alone, which writes a kept use site as a call
145//! of the definition and the definition itself into the style file, or expands
146//! the use site instead when the definition is not recomposable or its template
147//! needs the characters of an argument; and
148//! `instantiate-at-lowering` ([`instantiate_at_lowering_rule`]), never a
149//! default, which a plan request selects by name to have each kept use site
150//! expanded at lowering on any backend. Both require `flm.userdefs.kept`, so
151//! selecting either puts the `flm.userdefs.keep` marker into the plan. The rule
152//! selection order ([`SelectedRules`](crate::core::plan::SelectedRules)) puts a
153//! rule marked default on one backend before a rule marked default everywhere,
154//! so the three rules of one definition never compete: `latex-recomposed` gets
155//! `emit-call` and every other backend gets `expand-in-tree`. A plan that
156//! demands `flm.userdefs.kept` on a backend where a `per-plan` definition's
157//! selected rule is `expand-in-tree` is refused when the plan is built, since
158//! that rule requires the other alternative.
159//!
160//! The function [`kept::register`] also registers, once, a peer declaration
161//! ([`PeerName`](crate::core::registry::PeerName)) of the `latex-recomposed`
162//! backend and of each LaTeX construct element that the `emit-call` rules
163//! stage (build into the lowered tree), so that a registry without the LaTeX
164//! features still builds; the `emit-call` rules are then set aside (excluded
165//! from rule selection).
166//!
167//! # Templates are compiled when the registry is built
168//!
169//! A template is parsed against the finished language, which exists only once
170//! every feature has registered. The feature therefore registers a
171//! late-initialization build hook ([`LateInit`](crate::core::registry::LateInit))
172//! that compiles the templates of every definition over one template language
173//! ([`TemplateLanguage`](crate::lang::rewrites::userdefs::TemplateLanguage))
174//! built for all of them. Every diagnostic of a compilation (the warnings of a
175//! definition that compiled, the errors of one that was refused) becomes a
176//! build diagnostic of the registry
177//! ([`FlmRegistry::build_diagnostics`](crate::core::registry::FlmRegistry::build_diagnostics)),
178//! so a mistake in a template is reported once, when the registry is built. A
179//! refused definition stays registered without compiled templates, and each of
180//! its use sites is replaced by its literal source text and reported with
181//! `flm.userdefs.bad-definition`. None of this makes the registry build fail.
182//!
183//! The same hook then records, on every definition, whether it is
184//! *recomposable* (whether a backend can write it as one definition of its own
185//! output language; [`NotRecomposable`] lists the reasons it may not be) and
186//! the arguments one call of it writes ([`kept::record_recomposability`]). The
187//! hook reports nothing about recomposability: a refused definition was
188//! reported when it was refused, and none of the other reasons that
189//! [`NotRecomposable`] lists is a mistake in the document.
190//!
191//! # Configuration
192//!
193//! [`UserdefsConfig`] holds the definitions and the expansion depth limit. It is
194//! the feature's configuration, the plain Rust value the feature is constructed
195//! from ([`Userdefs::new`]); it is fixed when the registry is built and cannot
196//! vary per document or per render ([settings, options and
197//! configuration](crate::guide::concepts_overview#settings-options-and-configuration)),
198//! because the trees a run freezes depend on it. The feature gives its
199//! configuration's canonical bytes ([`UserdefsConfig::digest_bytes`]) as an
200//! input of the [registry digest](crate::model::digest), a number computed
201//! from everything about a registry that can change what processing produces,
202//! so that two registries that differ in a template do not share cached trees.
203//! In settings written as data, the configuration is read as a
204//! [`UserdefsData`].
205//!
206//! The feature creates a new [`UserDefinition`] for every definition each time
207//! it registers, so one feature value may be registered into several
208//! registries, each of which compiles its own templates against its own
209//! language.
210//!
211//! # Interactions with other features
212//!
213//! - The [`blocks`](crate::stdlib::features::blocks) feature's structure stage
214//!   requires `flm.userdefs` and is ordered after `flm.userdefs.always-expanded`,
215//!   because a use site that is not yet expanded can hide a paragraph break;
216//!   its contract check reports a use site that remains in a tree the plan
217//!   expanded.
218//! - The [`math-passthrough`](crate::math_passthrough) feature's rules for the
219//!   `latex-recomposed` backend write mathematics from its nodes rather than
220//!   through the lowering rules, and write a use site of a user definition
221//!   inside mathematics through this feature's mathematics writer
222//!   ([`kept::write_math_run`]).
223//! - The LaTeX family ([`crate::stdlib::backends::latex`], the parts every
224//!   LaTeX backend shares) provides the rule that writes the placeholders of a
225//!   template written into the style file
226//!   ([`placeholder_rule`](crate::stdlib::backends::latex::placeholder_rule)).
227//!
228//! # Items
229//!
230//! - [`Userdefs`], the feature, constructed with [`Userdefs::new`] from a
231//!   [`UserdefsConfig`]; the configuration's data forms [`UserdefsData`],
232//!   [`NamedDefinition`], [`DefinitionData`], [`DefinitionContent`] and
233//!   [`ModeTemplates`].
234//! - [`element_name`] and [`element_name_under`], the name of a definition's
235//!   element.
236//! - [`FEATURE`], [`USERDEFS`], [`EXPAND`], [`EXPANDED`], [`KEEP`], [`KEPT`],
237//!   [`EXPAND_ALWAYS`] and [`ALWAYS_EXPANDED`], the names of the feature, its
238//!   capabilities, stages and trees tables.
239//! - [`lowering`]: the `expand-in-tree` rule ([`ExpandInTree`],
240//!   [`expand_in_tree_rule`], [`expand_in_tree_rule_for`], [`rule_name`]).
241//! - [`kept`]: the rules for kept use sites ([`EmitCall`],
242//!   [`InstantiateAtLowering`] and their constructors and names), the
243//!   recomposability computation, the condition
244//!   [`KeptTemplateDeclaresPoint`] and the mathematics writer.
245//! - Re-exported from [`crate::lang::rewrites::userdefs`]: [`Definition`],
246//!   [`DefinitionKind`], [`DefinitionModes`], [`ExpandPolicy`] and
247//!   [`NotRecomposable`].
248
249// Each definition is its own element, so that its block role, expansion policy,
250// documentation and rule selection are its own. Its name holds the feature's
251// segment, so that an author's name cannot become a standard element's. The
252// guard against two definitions of one name sits where the names are minted,
253// because the registry's own roster validation permits two element values under
254// one name and reports the ambiguity only when the name is resolved, far from
255// the definition at fault.
256
257mod config;
258pub mod kept;
259pub mod lowering;
260mod stages;
261
262use std::collections::BTreeSet;
263use std::sync::Arc;
264
265use crate::core::settings::SettingsDecl;
266use crate::model::names::{ElementName, Name};
267use crate::core::registry::{BuildError, CapabilityDef, FeatureBuilder, FeatureInfo, FlmFeature};
268use crate::core::stage::TreesTable;
269use crate::core::data::table::TableName;
270use crate::lang::mint::parsers::code_span;
271use crate::lang::rewrites::userdefs::UserDefinition;
272
273use self::stages::{CompileTemplates, ExpandStage, Expands, KeepMarker};
274
275pub use self::config::{
276    DefinitionContent, DefinitionData, ModeTemplates, NamedDefinition, UserdefsConfig, UserdefsData,
277};
278pub use self::kept::{
279    EMIT_CALL, EmitCall, INSTANTIATE_AT_LOWERING, InstantiateAtLowering, KeptTemplateDeclaresPoint,
280    emit_call_rule, emit_call_rule_name, instantiate_at_lowering_rule, instantiate_rule_name,
281};
282pub use self::lowering::{
283    EXPAND_IN_TREE, ExpandInTree, expand_in_tree_rule, expand_in_tree_rule_for, rule_name,
284};
285pub use crate::lang::rewrites::userdefs::{
286    Definition, DefinitionKind, DefinitionModes, ExpandPolicy, NotRecomposable,
287};
288
289/// The feature's registered name, `userdefs`. It is also the middle segment of
290/// the names of the feature's stages and diagnostics (`flm.userdefs.expand`,
291/// `flm.userdefs.recursion-limit`).
292pub const FEATURE: &str = "userdefs";
293
294/// The declaration of the feature's settings ([`crate::core::settings`]): the
295/// fields of [`UserdefsData`] are the settings keys, and the data read is
296/// converted to a [`UserdefsConfig`]. Each map of definitions is merged entry by
297/// entry across sources of settings, and the template texts and default values
298/// are marked as FLM markup.
299fn settings() -> SettingsDecl {
300    let mut decl = SettingsDecl::new(FEATURE).config_from::<UserdefsData, UserdefsConfig>(
301        "The user definitions (macros, environments and special character sequences \
302        defined by substitution), one map per kind, and the expansion depth limit. Fixed \
303        when the registry is built: it cannot vary per document or per render.",
304    );
305    // The feature defines nothing by default (`UserdefsConfig::default`), so
306    // each kind's default entries are the empty map.
307    for kind in ["macros", "environments", "specials"] {
308        decl = decl
309            .merge_entries(kind, || Ok(serde_json::Value::Object(serde_json::Map::new())))
310            .remove_false(kind)
311            .markup(format!("{kind}.*.content"))
312            .markup(format!("{kind}.*.defaults"));
313    }
314    decl
315}
316
317/// The parent capability `flm.userdefs`: a decision about the use sites of the
318/// `per-plan` definitions has been made. Two capabilities refine it,
319/// [`EXPANDED`] (the default) and [`KEPT`]; a plan that demands both is refused.
320/// See the module documentation.
321pub const USERDEFS: &str = "flm.userdefs";
322
323/// The name of the rewrite stage that expands the use sites of the `always`
324/// definitions, `flm.userdefs.expand-always`. It publishes its trees in
325/// [`ALWAYS_EXPANDED`].
326pub const EXPAND_ALWAYS: &str = "flm.userdefs.expand-always";
327
328/// The trees table `flm.userdefs.always-expanded`, in which the
329/// [`EXPAND_ALWAYS`] stage publishes its trees, and the capability of the same
330/// name that the stage provides. It refines nothing, so it goes with either
331/// alternative of [`USERDEFS`]. The `expand-in-tree` rule of every `always`
332/// definition requires it.
333pub const ALWAYS_EXPANDED: TableName<TreesTable> =
334    TableName::new("flm.userdefs.always-expanded");
335
336/// The name of the rewrite stage that expands the use sites of the `per-plan`
337/// definitions, `flm.userdefs.expand`. It publishes its trees in [`EXPANDED`]
338/// and is ordered after [`ALWAYS_EXPANDED`] whenever both are in a plan.
339pub const EXPAND: &str = "flm.userdefs.expand";
340
341/// The trees table `flm.userdefs.expanded`, in which the [`EXPAND`] stage
342/// publishes its trees, and the capability of the same name that the stage
343/// provides: the refinement of [`USERDEFS`] marked as the default. The
344/// `expand-in-tree` rule of every `per-plan` definition requires it.
345///
346/// A stage that declares an optional read of this table learns whether the
347/// plan expanded the use sites of the `per-plan` definitions: the table is
348/// written exactly where the stage ran.
349pub const EXPANDED: TableName<TreesTable> = TableName::new("flm.userdefs.expanded");
350
351/// The name of the marker stage `flm.userdefs.keep`: it does nothing and
352/// provides [`KEPT`], so that a plan can choose to keep the use sites of the
353/// `per-plan` definitions in the tree.
354pub const KEEP: &str = "flm.userdefs.keep";
355
356/// The capability `flm.userdefs.kept` that the [`KEEP`] stage provides: the
357/// refinement of [`USERDEFS`] under which the use sites of the `per-plan`
358/// definitions stay in the tree for the lowering rules. The `emit-call` and
359/// `instantiate-at-lowering` rules require it ([`kept`]).
360pub const KEPT: &str = "flm.userdefs.kept";
361
362/// Returns the name of the element of `definition`:
363/// `flm.userdefs.<kind>.<name>`, where the kind is `macro`, `environment` or
364/// `specials`, and `flm.userdefs.<kind>.math.<name>` for a definition that
365/// applies in mathematics mode alone.
366///
367/// The extra `math` segment makes a definition for text mode alone and a
368/// definition for mathematics mode alone of one name two elements with two
369/// names, as they must be, since an element is found by its name. Every
370/// definition that applies in text mode (alone or in both modes, the common
371/// case) has the name without the segment.
372///
373/// The characters of a special character sequence are written into the name
374/// as they are, dots included. The module documentation says why the kind is
375/// part of the name. [`element_name_under`] gives the same name under another
376/// prefix.
377///
378/// # Examples
379///
380/// ```
381/// use flm_core::stdlib::features::userdefs::{Definition, element_name};
382///
383/// let definition = Definition::macro_("foo", Vec::new());
384/// assert_eq!(element_name(&definition), "flm.userdefs.macro.foo");
385///
386/// let in_math = Definition::macro_("foo", Vec::new()).math("\\mathbf{f}");
387/// assert_eq!(element_name(&in_math), "flm.userdefs.macro.math.foo");
388/// ```
389pub fn element_name(definition: &Definition) -> ElementName {
390    element_name_under("flm.userdefs", definition)
391}
392
393/// Returns the name of the element of `definition` under the prefix `prefix`:
394/// `<prefix>.<kind>.<name>`, and `<prefix>.<kind>.math.<name>` for a
395/// definition that applies in mathematics mode alone. [`element_name`] is this
396/// function with the prefix `flm.userdefs`.
397///
398/// A feature of another crate that registers definitions as elements of its
399/// own calls this function with its own prefix, so that every definition
400/// element is named by one rule (the kind, then the `math` segment for a
401/// definition of mathematics mode alone). Such a feature registers each
402/// element's `expand-in-tree` rule with [`expand_in_tree_rule_for`].
403///
404/// # Examples
405///
406/// ```
407/// use flm_core::stdlib::features::userdefs::{Definition, element_name_under};
408///
409/// let in_math = Definition::macro_("ket", Vec::new()).math("\\lvert x\\rangle");
410/// assert_eq!(element_name_under("mypack.notation", &in_math), "mypack.notation.macro.math.ket");
411/// ```
412pub fn element_name_under(prefix: &str, definition: &Definition) -> ElementName {
413    let kind = definition.kind.token();
414    let restricted = match definition.modes {
415        DefinitionModes::Math => "math.",
416        _ => "",
417    };
418    ElementName::from(format!("{prefix}.{kind}.{restricted}{}", definition.name))
419}
420
421/// The `userdefs` feature ([`FlmFeature`]): it registers one element per user
422/// definition with its lowering rules (one for an `always` definition, three
423/// for a `per-plan` one), the capabilities, the two expansion rewrite stages,
424/// the keep marker stage, the peer declarations of the LaTeX constructs, the
425/// late-initialization build hook that compiles the templates, and the
426/// feature's settings. See the module documentation.
427///
428/// Construct it with [`Userdefs::new`] from a [`UserdefsConfig`]; the default
429/// value defines nothing. The standard features construct it from the
430/// `userdefs` field of [`StdlibConfig`](crate::stdlib::StdlibConfig).
431///
432/// Registering the feature fails ([`BuildError::Feature`]) when two
433/// definitions of one kind and one name apply in a common parsing mode, or when
434/// two definitions would have the same element name.
435#[derive(Debug, Clone, Default)]
436pub struct Userdefs {
437    config: UserdefsConfig,
438}
439
440impl Userdefs {
441    /// Returns the feature with the configuration `config` (the definitions and
442    /// the expansion depth limit), which stays fixed for the life of every
443    /// registry the feature is built into.
444    pub fn new(config: UserdefsConfig) -> Userdefs {
445        Userdefs { config }
446    }
447
448    /// Returns the configuration the feature was constructed with.
449    pub fn config(&self) -> &UserdefsConfig {
450        &self.config
451    }
452}
453
454impl FlmFeature for Userdefs {
455    fn info(&self) -> FeatureInfo {
456        FeatureInfo::new(FEATURE, "User definitions").docs(
457            "Macros, environments and special character sequences defined by substitution. \
458             Each definition is an element carrying the `Expand` aspect. The rewrite stages \
459             `flm.userdefs.expand-always` and `flm.userdefs.expand` expand the use sites of \
460             the `always` and of the `per-plan` definitions; the `flm.userdefs.keep` marker \
461             stage keeps the latter in the tree instead. Every definition's `expand-in-tree` \
462             rule gives its element a rule on every backend; a `per-plan` definition's \
463             `emit-call` and `instantiate-at-lowering` rules lower a use site kept in the \
464             tree. The templates are compiled when the registry is built, which also records \
465             whether each definition can be written as one LaTeX definition.",
466        )
467    }
468
469    fn settings(&self) -> Option<SettingsDecl> {
470        Some(settings())
471    }
472
473    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
474        let owner = b.feature().clone();
475        b.capability(CapabilityDef::new(USERDEFS).docs(
476            "A decision about the `per-plan` user definitions has been made: their use sites \
477             are expanded in the tree (`flm.userdefs.expanded`, the default) or kept in the \
478             tree for the lowering rules (`flm.userdefs.kept`).",
479        ))?;
480        b.capability(CapabilityDef::new(KEPT).refines(USERDEFS).docs(
481            "The use sites of the `per-plan` user definitions are kept in the tree, for a \
482             lowering rule to expand or to write as a call. The alternative to \
483             `flm.userdefs.expanded`; a plan that demands both is refused.",
484        ))?;
485        let mut values = Vec::with_capacity(self.config.definitions.len());
486        let mut names: BTreeSet<ElementName> = BTreeSet::new();
487        let mut declared: Vec<(&Name, DefinitionKind, DefinitionModes)> = Vec::new();
488        for definition in &self.config.definitions {
489            let name = element_name(definition);
490            // Two definitions of one name and kind are two definitions when the
491            // parsing modes they apply in do not overlap, and a mistake when
492            // they do: in an overlapping mode only one of the two could be in
493            // force.
494            let overlapping = declared.iter().any(|(earlier, kind, modes)| {
495                *earlier == &definition.name
496                    && *kind == definition.kind
497                    && modes.overlaps(definition.modes)
498            });
499            if overlapping {
500                return Err(BuildError::Feature {
501                    feature: owner.clone(),
502                    detail: format!(
503                        "two definitions of `{}` must not apply in the same parsing mode",
504                        definition.name
505                    ),
506                });
507            }
508            declared.push((&definition.name, definition.kind, definition.modes));
509            // Their elements must differ too: everything that resolves an
510            // element by its name trips over two element values under one name.
511            if !names.insert(name.clone()) {
512                return Err(BuildError::Feature {
513                    feature: owner.clone(),
514                    detail: format!(
515                        "the definition of `{}` declares the element `{name}`, which an earlier \
516                         definition declares too; two definitions must not declare the same \
517                         element",
518                        definition.name
519                    ),
520                });
521            }
522            let value = UserDefinition::new(definition.clone());
523            value.record_recursion_limit(self.config.recursion_limit);
524            // The builder stamps the feature on the declaration and on the
525            // override itself; the owner handed over here only fills the
526            // declarations' own fields.
527            b.element(value.element_def(owner.clone(), name.clone()))?;
528            b.element_type_text(
529                name,
530                format!(
531                    "A use of {}, which the user definitions of the document define: it stands \
532                     for the definition's text, with the arguments written in their places.",
533                    code_span(&definition.display_name())
534                ),
535            )?;
536            if let Some(over) = value.override_def(owner.clone()) {
537                b.override_callable(over.kind, over.name)?;
538            }
539            b.lowering_rule(expand_in_tree_rule(definition))?;
540            if definition.expand == ExpandPolicy::PerPlan {
541                b.lowering_rule(kept::instantiate_at_lowering_rule(definition))?;
542                b.lowering_rule(kept::emit_call_rule(definition))?;
543            }
544            values.push(value);
545        }
546        kept::register(b)?;
547        let recursion_limit = self.config.recursion_limit;
548        b.rewrite_stage(Arc::new(ExpandStage { expands: Expands::Always, recursion_limit }))?;
549        b.rewrite_stage(Arc::new(ExpandStage { expands: Expands::PerPlan, recursion_limit }))?;
550        b.stage(Arc::new(KeepMarker))?;
551        b.digest_input(&self.config.digest_bytes())?;
552        b.late_init(Arc::new(CompileTemplates { definitions: values }))?;
553        Ok(())
554    }
555}
556
557#[cfg(test)]
558mod tests {
559    use super::*;
560    use crate::core::stage::{RewriteStage, Stage};
561
562    #[test]
563    fn an_element_is_named_by_its_kind_and_name() {
564        assert_eq!(
565            element_name(&Definition::macro_("foo", Vec::new())),
566            "flm.userdefs.macro.foo"
567        );
568        assert_eq!(
569            element_name(&Definition::environment("foo", Vec::new())),
570            "flm.userdefs.environment.foo"
571        );
572        assert_eq!(
573            element_name(&Definition::specials("~", Vec::new())),
574            "flm.userdefs.specials.~"
575        );
576    }
577
578    #[test]
579    fn the_per_plan_stage_declares_the_default_refinement_of_userdefs() {
580        let decl = ExpandStage { expands: Expands::PerPlan, recursion_limit: 1 }.decl();
581        assert_eq!(decl.name, EXPAND);
582        assert_eq!(decl.publishes, EXPANDED.name());
583        assert_eq!(decl.refines.as_deref().map(|n| n.as_str()), Some(USERDEFS));
584        assert!(decl.default);
585    }
586
587    #[test]
588    fn the_always_stage_refines_nothing() {
589        let decl = ExpandStage { expands: Expands::Always, recursion_limit: 1 }.decl();
590        assert_eq!(decl.name, EXPAND_ALWAYS);
591        assert_eq!(decl.publishes, ALWAYS_EXPANDED.name());
592        assert!(decl.refines.is_none());
593        assert!(!decl.default);
594    }
595
596    #[test]
597    fn the_keep_marker_provides_kept_and_writes_nothing() {
598        let decl = KeepMarker.decl();
599        assert_eq!(decl.name, KEEP);
600        assert_eq!(decl.provides, [crate::model::names::CapName::from(KEPT)]);
601        assert!(decl.writes.is_empty());
602    }
603}