flm_core/stdlib/features/userdefs/lowering.rs
1//! The `expand-in-tree` lowering rule that every user definition registers:
2//! the rule of the definition's element on every backend where the plan
3//! expands the definition's use sites before lowering.
4//!
5//! A lowering rule ([`LoweringRule`]) is written for one element and stages
6//! (builds into the lowered tree) that element's presentation for one backend.
7//! Every element an author can write needs a rule on each backend of a plan,
8//! unless the backend writes the element natively or the plan request accepts
9//! it as unrenderable; otherwise the plan build fails
10//! ([`PlanError::Incomplete`](crate::core::plan::PlanError::Incomplete)). A user
11//! definition's element is one an author can write, so it has a rule like
12//! any other: this one, the default on every backend
13//! ([`DefaultMark::Everywhere`]). The rule exists for two reasons.
14//!
15//! - **The element has a rule on every backend.** With this rule registered, a
16//! plan can be built for any backend over a registry that holds user
17//! definitions with no element left without a rule, although the expansion
18//! removes every use site before lowering.
19//! - **Selecting the rule puts the expansion into the plan.** The rule requires
20//! the trees table of the rewrite stage that expands its definition:
21//! [`EXPANDED`] for a definition whose expansion policy is `per-plan`,
22//! [`ALWAYS_EXPANDED`] for an `always` one. Every plan that lowers a
23//! registry holding an `always` definition therefore holds
24//! `flm.userdefs.expand-always`. A plan that demands `flm.userdefs.kept` on
25//! a backend where this rule is the one selected for a `per-plan` definition
26//! is refused when the plan is built, since the two alternatives of
27//! `flm.userdefs` exclude each other. On the `latex-recomposed` backend the
28//! rule selected for a `per-plan` definition is `emit-call` instead, which
29//! requires the other alternative ([`super::kept`]).
30//!
31//! # The rule never lowers a use site
32//!
33//! Every tree that the lowering stage of a backend lowers (a document tree, or
34//! a [synthesized value](crate::guide::concepts_overview#synthesized-values)
35//! brought up to date by [value
36//! catch-up](crate::guide::concepts_overview#value-catch-up)) has had the
37//! plan's rewrite stages run over it, the expansion this rule requires among
38//! them. No use site of the definition is left in such a tree: the expansion replaced each
39//! one by its instantiated template or, where it could not, by its literal
40//! source text with a diagnostic. The body of the rule ([`ExpandInTree`])
41//! therefore never receives a node. If it did, the expansion would have failed
42//! to keep that guarantee, and the rule returns a structure error
43//! ([`LowerError::structure`], reported as `flm.lowering.rule-failed`) rather
44//! than expanding the use site at lowering.
45//!
46//! # One rule per definition
47//!
48//! A rule targets one element, and every definition is an element of its own,
49//! so each definition has its own rule, named
50//! `flm.userdefs.<kind>.<name>.lower.expand-in-tree` ([`rule_name`]). The rule
51//! declares no presentation element, since it stages nothing.
52//! [`expand_in_tree_rule`] builds the rule of a definition of the `userdefs`
53//! feature; [`expand_in_tree_rule_for`] builds it for an element that another
54//! crate's feature registers for a definition of its own.
55
56use std::sync::Arc;
57
58use techy::core::node::NodeRef;
59
60use crate::core::lowering::{
61 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
62};
63use crate::model::names::{ElementName, RuleName};
64use crate::lang::Flm;
65use crate::lang::rewrites::userdefs::{Definition, ExpandPolicy};
66
67use super::{ALWAYS_EXPANDED, EXPANDED, element_name};
68
69/// The last segment of the name of every `expand-in-tree` rule,
70/// `expand-in-tree`.
71pub const EXPAND_IN_TREE: &str = "expand-in-tree";
72
73/// Returns the name of the `expand-in-tree` rule of `definition`:
74/// `flm.userdefs.<kind>.<name>.lower.expand-in-tree`, the definition's element
75/// name ([`element_name`]) followed by `.lower.` and
76/// [`EXPAND_IN_TREE`].
77///
78/// # Examples
79///
80/// ```
81/// use flm_core::stdlib::features::userdefs::{Definition, rule_name};
82///
83/// let definition = Definition::macro_("foo", Vec::new());
84/// assert_eq!(rule_name(&definition), "flm.userdefs.macro.foo.lower.expand-in-tree");
85/// ```
86pub fn rule_name(definition: &Definition) -> RuleName {
87 rule_name_of(&element_name(definition))
88}
89
90/// Returns the name of the `expand-in-tree` rule of the element `element`.
91fn rule_name_of(element: &ElementName) -> RuleName {
92 RuleName::from(format!("{element}.lower.{EXPAND_IN_TREE}"))
93}
94
95/// Returns the `expand-in-tree` rule of `definition`, a definition of the
96/// `userdefs` feature: the rule targets the definition's element
97/// ([`element_name`]), requires the trees table of the
98/// rewrite stage that expands definitions of its expansion policy, and is the
99/// default on every backend. See the module documentation.
100pub fn expand_in_tree_rule(definition: &Definition) -> LoweringRule {
101 expand_in_tree_rule_for(element_name(definition), definition)
102}
103
104/// Returns the `expand-in-tree` rule of `definition` for the element named
105/// `element`, under the rule name `<element>.lower.expand-in-tree`.
106/// [`expand_in_tree_rule`] calls it with the element name of the `userdefs`
107/// feature; a feature of another crate that registers an element of its own
108/// for a definition (named, for example, with
109/// [`element_name_under`](super::element_name_under)) calls it with that
110/// element's name.
111///
112/// The rule requires the trees table of the rewrite stage that expands
113/// definitions of the definition's expansion policy: [`ALWAYS_EXPANDED`] for
114/// an `always` definition, [`EXPANDED`] for a `per-plan` one. Selecting the
115/// rule therefore puts that stage into the plan. Only the `userdefs` feature
116/// declares these capabilities, so a registry that holds such a rule without
117/// the `userdefs` feature fails to build.
118///
119/// # Examples
120///
121/// ```
122/// use flm_core::lang::rewrites::userdefs::ExpandPolicy;
123/// use flm_core::stdlib::features::userdefs::{
124/// Definition, element_name_under, expand_in_tree_rule_for,
125/// };
126///
127/// let definition = Definition::macro_("ket", Vec::new()).expand(ExpandPolicy::Always);
128/// let rule = expand_in_tree_rule_for(element_name_under("mypack", &definition), &definition);
129/// assert_eq!(rule.name, "mypack.macro.ket.lower.expand-in-tree");
130/// ```
131pub fn expand_in_tree_rule_for(
132 element: impl Into<ElementName>,
133 definition: &Definition,
134) -> LoweringRule {
135 let element = element.into();
136 let (required, stage) = match definition.expand {
137 ExpandPolicy::Always => (ALWAYS_EXPANDED.name(), "flm.userdefs.expand-always"),
138 ExpandPolicy::PerPlan => (EXPANDED.name(), "flm.userdefs.expand"),
139 };
140 LoweringRule::new(
141 rule_name_of(&element),
142 element,
143 LoweringDecl::new().requires(required),
144 Arc::new(ExpandInTree),
145 DefaultMark::Everywhere,
146 )
147 .docs(format!(
148 "the use sites of `{}` are expanded in the tree by `{stage}` before lowering \
149 (requires `{required}`), so this rule never lowers a node",
150 definition.display_name()
151 ))
152}
153
154/// The body of every `expand-in-tree` rule. It never receives a node, because
155/// every use site was expanded before lowering (see the module
156/// documentation); if it receives one, it returns a structure error
157/// ([`LowerError::structure`]), since the expansion failed to keep that
158/// guarantee.
159#[derive(Debug, Default, Clone, Copy)]
160pub struct ExpandInTree;
161
162impl Lower for ExpandInTree {
163 fn lower(
164 &self,
165 node: NodeRef<'_, Flm>,
166 _cx: &mut LowerCx<'_>,
167 _lw: &mut dyn Lowerer,
168 ) -> Result<Lowering, LowerError> {
169 Err(LowerError::structure(format!(
170 "a use site of `{}` reached lowering unexpanded, although the expansion the rule \
171 requires runs over every tree lowered",
172 node.name().unwrap_or_default()
173 )))
174 }
175}
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180 use crate::model::names::CapName;
181
182 #[test]
183 fn a_per_plan_definitions_rule_requires_the_expanded_table() {
184 let rule = expand_in_tree_rule(&Definition::macro_("foo", Vec::new()).text("x"));
185 assert_eq!(rule.name, "flm.userdefs.macro.foo.lower.expand-in-tree");
186 assert_eq!(rule.element, "flm.userdefs.macro.foo");
187 assert_eq!(rule.decl.requires, [CapName::from("flm.userdefs.expanded")]);
188 assert!(rule.decl.produces.is_empty());
189 assert_eq!(rule.default, DefaultMark::Everywhere);
190 }
191
192 #[test]
193 fn an_always_definitions_rule_requires_the_always_expanded_table() {
194 let definition =
195 Definition::environment("foo", Vec::new()).text("x").expand(ExpandPolicy::Always);
196 let rule = expand_in_tree_rule(&definition);
197 assert_eq!(rule.name, "flm.userdefs.environment.foo.lower.expand-in-tree");
198 assert_eq!(rule.decl.requires, [CapName::from("flm.userdefs.always-expanded")]);
199 }
200}