flm_core/lang/rewrites/userdefs/hook.rs
1//! The [`Expand`] aspect, the [`Expander`] interface through which an `Expand`
2//! implementation works, and the [`PlaceholderBindings`] that say what each
3//! placeholder of a template is replaced by at one use site.
4//!
5//! An element whose use sites the [expand pass](super::expand) rewrites carries
6//! the [`Expand`] aspect (an
7//! [aspect](crate::guide::concepts_overview#elements-and-aspects) is a piece of
8//! behavior attached to an element and read back through a trait object). The
9//! pass visits every node of the tree, from the root down. At a node whose
10//! element carries the aspect, and whose expansion policy ([`ExpandPolicy`]) is
11//! among the policies this run of the pass expands ([`ExpandSet`]), the pass
12//! calls [`Expand::expand`]. The implementation works through the [`Expander`]
13//! it is handed: it instantiates a compiled template at the use site, or it
14//! replaces the use site by its literal source text and reports a problem. It
15//! then returns either the nodes that replace the use site
16//! ([`Expansion::Emit`]), which the pass inserts in place of the use site
17//! without a wrapper node, or the decision to leave the node as it is
18//! ([`Expansion::Default`]).
19//!
20//! The standard implementation of the aspect is
21//! [`UserDefinition`](super::UserDefinition), which instantiates the
22//! definition's template with the placeholder bindings of the use site
23//! ([`DefinitionBindings`](super::DefinitionBindings)). An extension crate may
24//! write its own implementation over the same interface, for example to compute
25//! the content of placeholder names of its own, with placeholder bindings that
26//! pass every other placeholder to `DefinitionBindings`: the values it computed,
27//! held in [`ExtraValues`](super::ExtraValues) and laid over
28//! `DefinitionBindings`, or bindings of its own. A template that refers
29//! to no argument of a use site (a value a feature compiled and fills by name)
30//! is instantiated with [`ValueBindings`](super::ValueBindings), which give each
31//! extra placeholder a finished tree, through the public
32//! [`instantiate`](fn@super::instantiate), from an expansion hook or from a
33//! lowering rule.
34
35use std::fmt;
36
37use techy::core::node::{BuildId, NodeBuildError, NodeRef, NodeSlice, NodeTree};
38use techy::transform::{RestageContext, RestageError};
39
40use crate::lang::flm::Flm;
41use crate::lang::BuiltLang;
42use crate::lang::origin::FlmDiagnostic;
43use crate::lang::rewrites::userdefs::template::{CompiledTemplate, PlaceholderTarget};
44
45/// The context through which the expand pass, and an [`Expand`]
46/// implementation, build nodes into the expanded tree (to *stage* them, in
47/// techy's terms; see [`Lowerer`](crate::core::lowering::Lowerer)): techy's
48/// restage context over the FLM language. The two unit type parameters say that
49/// FLM trees carry no annotations.
50pub type ExpandCx<'t> = RestageContext<'t, Flm, (), ()>;
51
52/// When a definition's use sites are expanded: `always`, in every plan, or
53/// `per-plan`, as each plan decides.
54///
55/// The `flm.userdefs.expand-always` stage expands the `always` definitions in
56/// every plan. The `flm.userdefs.expand` stage expands the `per-plan`
57/// definitions in a plan that asks for expanded definitions
58/// (`flm.userdefs.expanded`, the default choice); in a plan that asks for kept
59/// definitions (`flm.userdefs.kept`), their use sites stay in the tree, and a
60/// lowering rule either writes each one to the output as a call of the
61/// definition or writes the instantiated template in its place.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Deserialize)]
63#[derive(schemars::JsonSchema)]
64#[serde(rename_all = "kebab-case")]
65pub enum ExpandPolicy {
66 /// Expanded in every plan.
67 Always,
68 /// Expanded or kept, as each plan decides: expanded unless the plan asks
69 /// for kept definitions. This is the default.
70 #[default]
71 PerPlan,
72}
73
74/// Which definitions one run of the [expand pass](super::expand) expands, by
75/// their expansion policy.
76///
77/// The two rewrite stages of the
78/// [`userdefs` feature](crate::stdlib::features::userdefs) differ in this
79/// alone: `flm.userdefs.expand-always` runs the pass with
80/// [`Always`](ExpandSet::Always), and `flm.userdefs.expand` with
81/// [`PerPlan`](ExpandSet::PerPlan). A caller outside these stages, such as a
82/// lowering rule that expands one kept use site, uses [`Both`](ExpandSet::Both).
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
84pub enum ExpandSet {
85 /// The definitions whose policy is [`ExpandPolicy::Always`].
86 Always,
87 /// The definitions whose policy is [`ExpandPolicy::PerPlan`].
88 PerPlan,
89 /// Every definition.
90 Both,
91}
92
93impl ExpandSet {
94 /// Whether this set expands a definition whose expansion policy is `policy`.
95 pub fn includes(self, policy: ExpandPolicy) -> bool {
96 match self {
97 ExpandSet::Always => policy == ExpandPolicy::Always,
98 ExpandSet::PerPlan => policy == ExpandPolicy::PerPlan,
99 ExpandSet::Both => true,
100 }
101 }
102}
103
104/// What an [`Expand`] implementation decided about one use site.
105#[derive(Debug)]
106pub enum Expansion {
107 /// Leave the node as it is: it is copied into the expanded tree, and the pass
108 /// continues into its children.
109 Default,
110 /// These nodes, which the implementation built through the [`ExpandCx`],
111 /// replace the use site: the pass inserts them, in order, in place of the use
112 /// site. An empty list removes the use site.
113 Emit(Vec<BuildId>),
114}
115
116/// A failure of an [`Expand`] implementation, or of the [`Expander`] it works
117/// through: the error type of the expand pass's traversal. The boxed
118/// [`Restage`](ExpandError::Restage) variant follows techy's pattern for errors
119/// of a recursive traversal.
120///
121/// Every variant is an implementation failure, never a problem in the document:
122/// a problem in the document is reported as a diagnostic, and the use site is
123/// replaced by its literal source text ([`Expander::recover`]). An
124/// `ExpandError` that reaches the pass ends it with no tree, reported as
125/// `flm.userdefs.expansion-failed`, or as `flm.blocks.nesting-too-deep` for a
126/// refusal of the recursion guard ([`ExpandFailure`](super::ExpandFailure)).
127#[derive(Debug)]
128pub enum ExpandError {
129 /// An operation of the restage context failed: a region of a node could not be
130 /// attached to its new nodes, the [recursion guard](crate::lang::guard)
131 /// refused, or a node could not be built.
132 Restage(Box<RestageError<ExpandError>>),
133 /// Building a node directly through the context's node builder failed.
134 Build(NodeBuildError),
135 /// A placeholder that the placeholder bindings could not give a value. The
136 /// substitution pass returns it, and [`Expander::instantiate`] turns it into the
137 /// use site's recovery; an implementation receives this error only if it
138 /// instantiates a template by other means.
139 BadPlaceholder {
140 /// The placeholder as written.
141 reference: String,
142 },
143 /// A failure of the implementation's own code (an operational error in
144 /// extension code).
145 Hook {
146 /// The failure, as text.
147 detail: String,
148 },
149}
150
151impl ExpandError {
152 /// The detail of a refusal of the [recursion guard](crate::lang::guard), when
153 /// this error, or a restage error it wraps at any depth, is one.
154 pub fn descent_refusal(&self) -> Option<&str> {
155 match self {
156 ExpandError::Restage(error) => match &**error {
157 RestageError::DescentLimitExceeded { detail, .. } => Some(detail),
158 RestageError::Visitor(inner) => inner.descent_refusal(),
159 _ => None,
160 },
161 _ => None,
162 }
163 }
164
165 /// The placeholder that could not be given a value, when this error is a
166 /// [`BadPlaceholder`](ExpandError::BadPlaceholder) or wraps one, at any depth,
167 /// inside a restage error. A placeholder inside a conditional's branch or inside
168 /// a default value reaches the pass through the restage driver's own wrapping.
169 pub fn bad_placeholder(&self) -> Option<&str> {
170 match self {
171 ExpandError::BadPlaceholder { reference } => Some(reference),
172 ExpandError::Restage(error) => match &**error {
173 RestageError::Visitor(inner) => inner.bad_placeholder(),
174 _ => None,
175 },
176 _ => None,
177 }
178 }
179}
180
181impl From<RestageError<ExpandError>> for ExpandError {
182 fn from(error: RestageError<ExpandError>) -> ExpandError {
183 ExpandError::Restage(Box::new(error))
184 }
185}
186
187impl From<NodeBuildError> for ExpandError {
188 fn from(error: NodeBuildError) -> ExpandError {
189 ExpandError::Build(error)
190 }
191}
192
193impl fmt::Display for ExpandError {
194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195 match self {
196 ExpandError::Restage(error) => write!(f, "{error}"),
197 ExpandError::Build(error) => write!(f, "building the expanded nodes failed: {error}"),
198 ExpandError::BadPlaceholder { reference } => {
199 write!(f, "placeholder ‘#{reference}’ has no value")
200 }
201 ExpandError::Hook { detail } => {
202 write!(f, "the expansion code of a definition failed: {detail}")
203 }
204 }
205 }
206}
207
208impl std::error::Error for ExpandError {}
209
210/// The expansion aspect: the behavior of an element whose use sites are
211/// rewritten during the [expand pass](super::expand). It is attached by its trait-object type, like
212/// every aspect: `.with::<dyn Expand>(Arc::new(definition))`.
213///
214/// [`UserDefinition`](super::UserDefinition) is the standard implementation.
215pub trait Expand: Send + Sync {
216 /// When this element's use sites are expanded ([`ExpandPolicy`]): per plan,
217 /// unless the implementation says otherwise.
218 fn policy(&self) -> ExpandPolicy {
219 ExpandPolicy::PerPlan
220 }
221
222 /// Expands one use site. The pass calls this, from the root of the tree down,
223 /// at every node of this element whose policy is among the policies the run
224 /// expands ([`ExpandSet`]). `node` is the use site in the input tree; `cx` is
225 /// the context through which the replacement nodes are built; `xp` is the
226 /// [`Expander`] through which the implementation instantiates a compiled
227 /// template or reports a problem.
228 ///
229 /// # Errors
230 ///
231 /// An [`ExpandError`] ends the pass and leaves no tree, so it is for an
232 /// implementation failure only ([`ExpandError::Hook`] for the implementation's
233 /// own). A problem in the *document* is reported by replacing the use site
234 /// through [`Expander::recover`], which returns normally.
235 fn expand(
236 &self,
237 node: NodeRef<'_, Flm>,
238 cx: &mut ExpandCx<'_>,
239 xp: &mut dyn Expander,
240 ) -> Result<Expansion, ExpandError>;
241}
242
243/// The operations an [`Expand`] implementation uses at a use site: instantiate a
244/// compiled template, replace the use site by its literal source text with a
245/// diagnostic, or record a diagnostic. The expand pass implements this trait,
246/// and an implementation never sees the pass itself.
247pub trait Expander {
248 /// The current expansion depth: 0 at the top level of the tree, one more inside
249 /// each instantiated template.
250 fn depth(&self) -> usize;
251
252 /// The expansion depth limit that applies
253 /// ([`ExpandOptions::recursion_limit`](super::ExpandOptions::recursion_limit)).
254 fn recursion_limit(&self) -> usize;
255
256 /// Instantiates `template` at the use site `site`, and returns the nodes that
257 /// replace the use site.
258 ///
259 /// Each placeholder is replaced by the value that `bindings` gives it (already
260 /// parsed nodes, never parsed again), the conditionals are evaluated, and the
261 /// template's nodes are copied onto a new source created for this use: a
262 /// source with the template's text that records the use site's position as
263 /// the place where it was created; each copied node keeps its byte range in
264 /// that text. The result then goes
265 /// through the pass one level deeper, so that definitions used in the template
266 /// or in the substituted arguments are expanded in turn.
267 ///
268 /// The expansion depth limit is checked here, before any work: at the limit,
269 /// the use site is replaced by its literal source text and reported with
270 /// `flm.userdefs.recursion-limit`. A placeholder that `bindings` cannot give a
271 /// value, wherever it is (at the template's top level, inside a conditional's
272 /// branch, inside a default value), is a problem in the document: the use site
273 /// is replaced by its literal source text and reported with
274 /// `flm.userdefs.bad-placeholder`, and the replacement node is returned.
275 ///
276 /// # Errors
277 ///
278 /// An [`ExpandError`] for an implementation failure only: a broken invariant
279 /// while building nodes, a refusal of the recursion guard, or a failure of an
280 /// expansion hook reached inside the instantiated template. Every problem in the
281 /// document is handled by replacing the use site instead.
282 fn instantiate(
283 &mut self,
284 cx: &mut ExpandCx<'_>,
285 site: NodeRef<'_, Flm>,
286 template: &CompiledTemplate,
287 bindings: &dyn PlaceholderBindings,
288 ) -> Result<Vec<BuildId>, ExpandError>;
289
290 /// Reports a problem in the document at the use site `site`: records
291 /// `diagnostic` and builds a text node holding the use site's literal source
292 /// text, spanned into the use site's own source so that its origin is unchanged.
293 /// Returns that node, as the replacement of the use site.
294 ///
295 /// # Errors
296 ///
297 /// [`ExpandError::Build`] when building the text node fails, which is an
298 /// implementation failure and ends the pass.
299 fn recover(
300 &mut self,
301 cx: &mut ExpandCx<'_>,
302 site: NodeRef<'_, Flm>,
303 diagnostic: FlmDiagnostic,
304 ) -> Result<Vec<BuildId>, ExpandError>;
305
306 /// Records `diagnostic` without replacing anything: what an implementation that
307 /// keeps its node ([`Expansion::Default`]) uses to report a condition there.
308 fn diagnose(&mut self, diagnostic: FlmDiagnostic);
309
310 /// The built language the expansion runs under: what a hook compiles a
311 /// template it computed at the use site against
312 /// ([`compile_template_with`](super::compile_template_with)).
313 fn lang(&self) -> &BuiltLang;
314}
315
316/// The value of a placeholder at one use site, as
317/// [`PlaceholderBindings::value`] returns it.
318#[derive(Debug, Clone, Copy)]
319pub enum PlaceholderValue<'a> {
320 /// The placeholder refers to an argument that was not written and has no
321 /// default value (the `-NoValue-` of LaTeX's `xparse` package): nothing is
322 /// substituted, and `\IfNoValue…` holds.
323 NoValue,
324 /// Content written at the use site (an argument's or the body's content
325 /// nodes), or any other nodes the bindings can lend for the lifetime `'a`,
326 /// such as the nodes of a tree an expansion hook built. They are substituted as they are,
327 /// with their own positions in their sources.
328 Provided(NodeSlice<'a, Flm>),
329 /// The argument was not written, and its declared default value applies: a
330 /// compiled template, with placeholders of its own, instantiated in place.
331 Default(&'a CompiledTemplate),
332 /// Content an expansion hook computed, as **finished content**: the children of
333 /// the tree's root are substituted. They go through the substitution pass, so
334 /// that no placeholder node remains in the expanded tree. A placeholder node
335 /// among them belongs to no compiled template the pass entered, so the use site
336 /// is replaced by its literal source text and reported with
337 /// `flm.userdefs.bad-placeholder`; a conditional among them is evaluated. A hook
338 /// that wants placeholders given values returns a compiled template through
339 /// [`Default`](PlaceholderValue::Default) instead. The tree's nodes keep their
340 /// own positions in their sources (they are not the template's).
341 Tree(&'a NodeTree<Flm>),
342 /// The placeholder's own substitution argument (the bracketed content of
343 /// `#[…]{name}`, as parsed in the template) is the value: its nodes are the
344 /// template's, copied like content written at the use site, so they carry this
345 /// use's own source in the expanded tree. Written without a substitution
346 /// argument, the placeholder substitutes nothing.
347 ///
348 /// [`PlaceholderBindings::value`] receives these nodes for reading only (they
349 /// exist for the duration of the call, not as long as the returned value), which
350 /// is why returning them takes this variant rather than
351 /// [`Provided`](PlaceholderValue::Provided).
352 Substitution,
353 /// The placeholder has no value here (an expansion hook does not compute it).
354 /// The use site is replaced by its literal source text and reported with
355 /// `flm.userdefs.bad-placeholder`.
356 Unresolvable,
357}
358
359/// What the placeholders of a template are replaced by at one use site.
360///
361/// The template compiler resolves each placeholder to its target
362/// ([`PlaceholderTarget`]) in a fixed order: a name an expansion hook computes
363/// first, then the body, then a declared argument name, then an argument number
364/// ([`PlaceholderVocabulary::resolve`](super::PlaceholderVocabulary::resolve)).
365/// At each use, the bindings give each target its value.
366/// [`DefinitionBindings`](super::DefinitionBindings) are the bindings of a user
367/// definition's use site; an extension's [`Expand`] implementation supplies its
368/// own, usually built on top of them: either the values it computed for the
369/// extra placeholders, held in [`ExtraValues`](super::ExtraValues) and laid
370/// over them, or an implementation of this trait.
371/// [`ValueBindings`](super::ValueBindings)
372/// are the bindings of a template that has no use site's arguments: they give
373/// each extra placeholder a finished tree held by name, for a feature that
374/// instantiates a template it compiled itself
375/// ([`instantiate`](fn@super::instantiate)).
376pub trait PlaceholderBindings {
377 /// The value of `target` at this use site. `substitution` is the placeholder's
378 /// substitution argument (`#[…]{…}`) as parsed in the template, when one is
379 /// written: the data that a computed placeholder name reads. The arguments and
380 /// the body take none (the template compiler refuses one on them).
381 ///
382 /// **The substitution nodes** are nodes of the compiled template being
383 /// instantiated, before they are copied onto the use's own source, and they are
384 /// lent for this call alone: they do not exist as long as the returned value, so
385 /// they cannot be returned as [`Provided`](PlaceholderValue::Provided). An
386 /// implementation that wants them substituted returns
387 /// [`Substitution`](PlaceholderValue::Substitution); the pass copies them, and
388 /// they carry this use's own source in the expanded tree.
389 fn value<'a>(
390 &'a self,
391 target: &PlaceholderTarget,
392 substitution: Option<NodeSlice<'_, Flm>>,
393 ) -> PlaceholderValue<'a>;
394}
395
396#[cfg(test)]
397mod tests {
398 use super::*;
399
400 #[test]
401 fn the_per_plan_set_excludes_always_definitions() {
402 assert!(!ExpandSet::PerPlan.includes(ExpandPolicy::Always));
403 assert!(ExpandSet::PerPlan.includes(ExpandPolicy::PerPlan));
404 }
405
406 #[test]
407 fn the_both_set_includes_every_policy() {
408 assert!(ExpandSet::Both.includes(ExpandPolicy::Always));
409 assert!(ExpandSet::Both.includes(ExpandPolicy::PerPlan));
410 }
411
412 #[test]
413 fn the_default_policy_is_per_plan() {
414 assert_eq!(ExpandPolicy::default(), ExpandPolicy::PerPlan);
415 }
416}