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