Skip to main content

flm_core/stdlib/backends/lowering/
driver.rs

1//! The lowering driver: [`lower_tree`] and [`lower_value`], which turn one
2//! tree into one lowered tree, and the implementation of the [`Lowerer`]
3//! every lowering rule works through.
4//!
5//! A **lowering rule** is a named registry entity written for one element: it
6//! declares what it requires, reads and produces, and implements `Lower`,
7//! which stages (builds into the lowered tree) the element's presentation for
8//! one backend ([`LoweringRule`](crate::core::lowering::LoweringRule)). The
9//! [`Lowerer`] is the only interface a lowering rule has to the run: through
10//! it the rule lowers parts of its node, stages presentation nodes, splices a
11//! synthesized value and lowers a node region of another node. This module
12//! implements it.
13//!
14//! The lowering stage ([`super::stage`]) calls the driver once per frozen
15//! tree; the pieces stage calls it once per piece. Everything here runs on
16//! the caller's thread, which the runner has made a worker thread (a thread
17//! that declared its stack size; see
18//! [`on_worker_thread`](crate::lang::guard::on_worker_thread)).
19//!
20//! # Rounds
21//!
22//! **One round** is one pass over the tree, from the root down, each parent
23//! before its children. At each node, in this order:
24//!
25//! 1. If the backend writes the node's element natively, the node is copied
26//!    and its children are lowered in turn. If the element's content is
27//!    opaque source text ([`OpaqueContent`]), the subtree is copied unchanged
28//!    and nothing inside it is lowered, except a node carrying
29//!    [`ContentInOpaque`], which holds document content rather than source
30//!    text and is handled like any other node.
31//! 2. Otherwise, if the plan selected a rule for the element, that rule runs.
32//!    It returns [`Lowering::Default`] (make the copy just described) or
33//!    [`Lowering::Emit`] with the nodes it staged; an empty list removes the
34//!    node.
35//! 3. Otherwise the node lowers to a childless `flm.pres.unsupported`
36//!    stand-in and one Error diagnostic is reported ([`super::error`]).
37//!
38//! A rule may stage nodes of elements the backend does not write natively,
39//! so one round is not always enough: if the round's output still holds such
40//! an element (outside opaque content, which is examined only for the
41//! content of a [`ContentInOpaque`] node), another round runs over that
42//! output. The number of rounds allowed is [`rank`](super::rank), computed
43//! when the plan is built; beyond it the tree fails with
44//! `flm.lowering.rounds-exceeded` and gets no lowered form.
45//!
46//! # Provenance
47//!
48//! A copied node keeps its span. Everything a rule stages at a node is placed
49//! on one synthesized source per pair of visited node and rule, created at
50//! that node, so following the provenance of any lowered node leads back to
51//! the document. The lowered tree stores no map from its nodes back to the
52//! frozen nodes; provenance is the only link. For this reason
53//! [`LoweredAddr`](super::LoweredAddr) gives a position rather than a frozen
54//! node.
55//!
56//! # What the `Lowerer` enforces
57//!
58//! Everything a rule reads, lowers or stages goes through the [`Lowerer`].
59//! The driver's implementation decides the following:
60//!
61//! - **Decorations are moved into attached slots, always in the same way.** A
62//!   decoration is a node whose element carries the [`Decoration`] aspect.
63//!   When a rule stages a presentation node ([`Lowerer::pres`],
64//!   [`Lowerer::pres_slots`]), every decoration among the direct children of
65//!   one of its content slots is moved into an attached slot named after the
66//!   decoration's element, and a `flm.pres.deco-mark` node (the decoration
67//!   mark) giving the index of that slot is left at its former position (see
68//!   [decorations, roles and
69//!   kinds](crate::guide::concepts_overview#decorations-roles-and-kinds)).
70//!   The driver stages the mark itself, so a rule need not declare it in
71//!   `produces`. A backend that writes any decoration element natively must
72//!   write `flm.pres.deco-mark` natively too; the registry build checks this
73//!   through the native-set implication the `lowering` feature declares
74//!   ([`native_implications`](super::native_implications)).
75//! - **A rule must declare what it produces.** The `Lowerer` refuses to stage
76//!   any presentation element the rule's `produces` declaration does not
77//!   list. The only exception is `flm.text`: a rule may add text to its
78//!   output without declaring it when the backend writes `flm.text` natively.
79//! - **Inside a splice** ([`Lowerer::splice`]), [`Lowerer::addr`] returns the
80//!   address of the node of the spliced synthesized value, since the tables
81//!   that the rule may read there hold that value's results. The nodes staged
82//!   inside the splice are still recorded as coming from the splicing rule's
83//!   own node, so a later round never sees an address of the value.
84//! - **Inside a region lowering** ([`Lowerer::lower_region`]), the opposite
85//!   holds: the content of a node region of a node of another tree (a
86//!   document tree, when a synthesized value is being lowered) is lowered in
87//!   that tree's own terms. Its nodes return their own addresses and are
88//!   recorded with them as their origins, so every later round reads the
89//!   tables at the document's addresses too. A table read returns a
90//!   synthesized value's own results only at that value's addresses, in
91//!   every round.
92//!
93//! # Failure and recovery
94//!
95//! A rule's failure at one node (an undeclared table or option read, an
96//! undeclared element in `produces`, a node shape it did not expect, a failed
97//! [value catch-up](crate::guide::concepts_overview#value-catch-up)) is
98//! reported as `flm.lowering.rule-failed` at that node, and the node lowers
99//! to the childless `flm.pres.unsupported` stand-in. A rule that refuses the
100//! node with a diagnostic of its own ([`LowerError::Refused`]) gets the same
101//! stand-in, and its diagnostic is reported in place of
102//! `flm.lowering.rule-failed`, at every node it refuses. The driver stages
103//! that stand-in itself, without any rule declaring it, so every backend
104//! must write `flm.pres.unsupported` natively; the registry build checks
105//! this as well, through the second native-set implication the `lowering`
106//! feature declares.
107//!
108//! Two failures end the lowering of the whole tree instead: a node that could
109//! not be staged at all (`flm.lowering.failed`), and the recursion guard's
110//! refusal to descend further (`flm.lowering.nesting-too-deep`).
111//!
112//! One outcome is not a failure of the node and is passed on, unreported,
113//! from rule to rule up to the rule that spliced the synthesized value it
114//! arose in: a rule needing the characters of a template's placeholder
115//! ([`LowerError::PlaceholderCharacters`]), which the user-definitions
116//! feature handles by expanding the definition's use sites. The splice it
117//! passes through discards the value's diagnostics and requirements with it.
118//! If it reaches the lowering of a whole tree, it ends that lowering as
119//! `flm.lowering.failed`.
120//!
121//! A rule is expected to return every error the `Lowerer` gives it. The
122//! driver does not define what happens when a rule continues after one; for
123//! example, a refusal of the recursion guard that the rule ignored is still
124//! recorded, and if the tree's lowering later fails, that failure is reported
125//! as `flm.lowering.nesting-too-deep`.
126//!
127//! [`Lowering::Default`]: crate::core::lowering::Lowering::Default
128//! [`Lowering::Emit`]: crate::core::lowering::Lowering::Emit
129//! [`Lowerer`]: crate::core::lowering::Lowerer
130//! [`Lowerer::pres`]: crate::core::lowering::Lowerer::pres
131//! [`Lowerer::pres_slots`]: crate::core::lowering::Lowerer::pres_slots
132//! [`Lowerer::splice`]: crate::core::lowering::Lowerer::splice
133//! [`Lowerer::lower_region`]: crate::core::lowering::Lowerer::lower_region
134//! [`Lowerer::addr`]: crate::core::lowering::Lowerer::addr
135
136use std::collections::{BTreeMap, BTreeSet, HashMap};
137use std::convert::Infallible;
138use std::sync::Arc;
139
140use techy::core::node::{
141    BodySlotExt, BuildId, ChildRegion, ContentNodes, NodeKind, NodeRef, NodeSlice, NodeTree,
142    ParsedArguments, ParsedSlot, ParsedSlots, SlotRole,
143};
144use techy::core::{Lang, ParsingState};
145use techy::error::{Diagnostic, TraceFrame};
146use techy::latexlike::BodyMarker;
147use techy::source::{Source, SourceSpan};
148use techy::transform::{Restage, RestageContext, RestageError, RestageVisitor, RestagedArgument};
149
150use crate::model::addr::{NodeAddr, NodeId, TreeId};
151use crate::model::element::{ElementSpec, element_of};
152use crate::model::doc::FragmentLayout;
153use crate::core::lowering::{
154    LowerCx, LowerError, Lowerer, Lowering, NodeRegion, RegionShape, chars_at_lowering,
155};
156use crate::model::names::{BackendName, CapName, ElementName, Name, RuleName, StageName};
157use crate::model::options::{OptionError, OptionKey};
158use crate::core::plan::SelectedRules;
159use crate::core::registry::frozen::{FlmRegistry, RuleIdx};
160use crate::core::run::{CatchUpError, StageCx};
161use crate::core::data::store::{AccessError, Computed, StoreError};
162use crate::lang::copy::WrittenPiece;
163use crate::lang::guard::{self, GuardPolicy};
164use crate::lang::mint::FlmPresentationSpec;
165use crate::lang::{
166    BuiltLang, Flm, FlmCallableType, FlmDiagnostic, FlmDiagnostics, FlmOrigin, FlmSource, FlmSpan,
167    PresPayload,
168};
169use crate::stdlib::backends::pres::{
170    self, ContentInOpaque, DecoMarkPayload, Decoration, OpaqueContent, UnsupportedPayload,
171    recompose_source,
172};
173
174use super::error::{
175    ContentNotCharacters, LoweringFailed, NestingTooDeep, NoRule, RegionNotFound, RoundsExceeded, RuleFailed,
176    UnsupportedElement,
177};
178use super::table::LoweredTree;
179
180/// The name the `Lowerer` returns from `rule()` outside any rule, inside the
181/// driver's own default handling, which no rule observes.
182const DRIVER_RULE: &str = "flm.lowering.driver";
183
184/// The title of the frame added to a diagnostic raised inside a spliced
185/// synthesized value: the frame's span is the node at which the value is
186/// shown, as the title says.
187const SHOWN_HERE: &str = "a copy of this content, shown here";
188
189/// The decorations moved out of a content slot: each one's element (the
190/// attached slot's name) and its staged node.
191type Hoisted = Vec<(ElementName, BuildId)>;
192
193/// Everything one call of [`lower_tree`] or [`lower_value`] needs besides the
194/// tree itself: what the plan decided for one backend, and the limits the run
195/// imposes.
196///
197/// The lowering stage and the pieces stage build it from the plan and the
198/// registry; a caller that runs lowering by hand builds it the same way, with
199/// [`rank`](super::rank) and [`selection_requires`](super::selection_requires)
200/// for the computed fields.
201#[derive(Debug, Clone)]
202pub struct LoweringInputs<'r> {
203    /// The backend being lowered for.
204    pub backend: &'r BackendName,
205    /// The registry the selection's rule indices refer to.
206    pub registry: &'r FlmRegistry,
207    /// The rules the plan selected for this backend, by element.
208    pub selected: &'r SelectedRules,
209    /// The elements this backend writes natively under this plan: its native
210    /// set, minus any element for which the plan request prefers a rule over
211    /// the native writing.
212    pub native: &'r BTreeSet<ElementName>,
213    /// The accepted unrenderable elements of this backend: the elements the
214    /// plan request accepts that the backend cannot render
215    /// ([`PlanRequest::unsupported`](crate::core::plan::PlanRequest#structfield.unsupported)).
216    /// Each node of one lowers to a childless `flm.pres.unsupported` stand-in
217    /// with one Error diagnostic.
218    pub holes: &'r BTreeSet<ElementName>,
219    /// The recursion guard's policy, which every round over the tree follows.
220    pub guard: GuardPolicy,
221    /// How many rounds lowering may run; see [`rank`](super::rank). Values
222    /// below one are treated as one.
223    pub rank: u32,
224    /// The identifiers of the style and script definitions (on LaTeX, package
225    /// requests and definition pieces) that the selected rules require
226    /// whenever they are selected
227    /// ([`selection_requires`](super::selection_requires)). Every lowered
228    /// tree's requirements contain them, in addition to what the rules record
229    /// at their nodes.
230    pub selection_requires: &'r BTreeSet<Name>,
231}
232
233/// What lowering one tree produced: the lowered tree, if any, and the
234/// diagnostics.
235///
236/// A failed lowering returns no tree and an Error diagnostic that says why; no
237/// error is returned to the caller.
238#[derive(Debug)]
239pub struct LoweringOutcome {
240    /// The lowered tree; `None` when the tree's lowering failed.
241    pub lowered: Option<LoweredTree>,
242    /// The diagnostics raised, in the order they were raised.
243    pub diags: FlmDiagnostics,
244}
245
246/// Lowers one frozen tree for one backend: runs the rounds, calls the
247/// selected rules, and returns the lowered tree with the diagnostics raised
248/// (see the module documentation).
249///
250/// `cx` is the calling stage's context: the [`Lowerer`] reads the rules'
251/// declared tables and options through it, and brings a spliced synthesized
252/// value up to date through it. `tree_id` identifies the document tree of
253/// which `tree` is the frozen form; it becomes the tree part of every
254/// [`LoweredAddr`](super::LoweredAddr) into the result.
255///
256/// It never returns an error: a tree that cannot be lowered comes back with
257/// [`LoweringOutcome::lowered`] set to `None` and an Error diagnostic. Call it
258/// on a worker thread (the runner's stages already run on one), since the walk
259/// recurses as deeply as the tree nests.
260///
261/// # Panics
262///
263/// Panics if `inputs.selected` was built against a registry other than
264/// `inputs.registry`, so that a selected rule's index is out of range for that
265/// registry's rule list. The lowering stage and the pieces stage always pass a
266/// matching pair; only inputs assembled by hand from two registries can reach
267/// this.
268pub fn lower_tree(
269    cx: &StageCx<'_>,
270    inputs: &LoweringInputs<'_>,
271    tree_id: TreeId,
272    tree: &Arc<NodeTree<Flm>>,
273) -> LoweringOutcome {
274    let mut pass = Pass::new(cx, inputs, tree_id, tree.root().id());
275    lower_rounds(&mut pass, inputs, tree)
276}
277
278/// Lowers a synthesized value for one backend: brings it up to date, then
279/// runs the rounds over it exactly as [`lower_tree`] runs them over a document
280/// tree.
281///
282/// A **synthesized value** is a small tree that a stage builds while a run is
283/// under way, held outside the document's trees (see [synthesized
284/// values](crate::guide::concepts_overview#synthesized-values)). This
285/// function does for a whole value what a rule's [`Lowerer::splice`] does for
286/// a value inside the node it lowers; a backend's pieces stage lowers each
287/// [piece](crate::core::piece::Piece) with it.
288///
289/// The value is brought up to date by [value
290/// catch-up](crate::guide::concepts_overview#value-catch-up)
291/// ([`StageCx::resolve_value`]): the plan's rewrites run over it, then the
292/// per-tree stages the calling stage depends on, and what they compute goes
293/// into a catch-up store of the value's own. Every table read a rule makes at
294/// an address of the value reads that catch-up store first, so a per-tree
295/// table holds the value's own entries, and every table that no re-entered
296/// stage writes (the document-scope tables: anchors, counters, the label
297/// index) is the document's, unchanged. A reference inside a value therefore
298/// resolves to the document's labels. Content of the document that a rule
299/// inside the value lowers through [`Lowerer::lower_region`] is read at the
300/// document's addresses, in the run's store, never in the value's catch-up
301/// store.
302///
303/// The diagnostics the catch-up raised come first in the outcome, then the
304/// lowering's own, as a splice records them. A value whose lowering fails
305/// comes back with [`LoweringOutcome::lowered`] set to `None` and an Error
306/// diagnostic, as a tree does.
307///
308/// `cx` is the calling stage's context. The catch-up runs again the per-tree
309/// stages *that* stage depends on, so a stage calling this function must
310/// declare the needs of the rules it lowers with
311/// ([`rules_needs`](super::rules_needs)). Call it on a worker thread, as
312/// [`lower_tree`].
313///
314/// # Errors
315///
316/// Returns the [`CatchUpError`] when the value could not be brought up to
317/// date: a rewrite refused it, it nests too deeply, or a re-entered stage
318/// produced a fact about the document as a whole (a labeled reference point,
319/// for example), which a synthesized value may not state. Nothing was
320/// lowered then; the caller records the error's
321/// [diagnostic](CatchUpError::diagnostic), when it has one.
322///
323/// # Panics
324///
325/// Panics if `inputs.selected` was built against a registry other than
326/// `inputs.registry`, so that a selected rule's index is out of range for that
327/// registry's rule list. The lowering stage and the pieces stage always pass a
328/// matching pair; only inputs assembled by hand from two registries can reach
329/// this.
330///
331/// A rewrite or a re-entered stage that panics propagates out of this call,
332/// as it does out of [`StageCx::resolve_value`].
333pub fn lower_value(
334    cx: &StageCx<'_>,
335    inputs: &LoweringInputs<'_>,
336    value: &Arc<NodeTree<Flm>>,
337) -> Result<LoweringOutcome, CatchUpError> {
338    let caught = cx.resolve_value(value)?;
339    // The value is lowered as a tree of its own, since no node splices it in
340    // and lends its nodes an origin: its nodes answer the value's addresses
341    // from the first round on, and its scratch store stays the overlay of
342    // every read for all the rounds.
343    let mut pass = Pass::new(cx, inputs, caught.id, caught.tree.root().id());
344    pass.stores.push((caught.id, Arc::clone(&caught.tree), caught.scratch));
345    let lowered = lower_rounds(&mut pass, inputs, &caught.tree);
346    let mut diags = caught.diags;
347    for diagnostic in lowered.diags {
348        diags.push(diagnostic);
349    }
350    Ok(LoweringOutcome { lowered: lowered.lowered, diags })
351}
352
353/// The rounds over one tree, shared by [`lower_tree`] and [`lower_value`].
354fn lower_rounds(
355    pass: &mut Pass<'_>,
356    inputs: &LoweringInputs<'_>,
357    tree: &Arc<NodeTree<Flm>>,
358) -> LoweringOutcome {
359    let bound = inputs.rank.max(1);
360    let mut current = Arc::clone(tree);
361    let mut rounds: u32 = 0;
362    loop {
363        rounds += 1;
364        pass.mode = if rounds == 1 { Mode::Frozen } else { Mode::Chain };
365        pass.round_tree = Arc::as_ptr(&current) as usize;
366        let output = match guard::restager(&mut *pass, inputs.guard).restage(&current) {
367            Ok(output) => output,
368            Err(error) => {
369                let failure = pass.failure_of(error);
370                let mut diags = pass.take_diags();
371                diags.push(failure_diagnostic(failure, current.root().span().clone()));
372                return LoweringOutcome { lowered: None, diags };
373            }
374        };
375        pass.previous = std::mem::take(&mut pass.round_origins);
376        pass.origins.clear();
377        let remaining = non_native(&output, inputs.native);
378        if remaining.is_empty() {
379            let lowered =
380                LoweredTree { tree: Arc::new(output), requires: pass.requires.clone(), rounds };
381            return LoweringOutcome { lowered: Some(lowered), diags: pass.take_diags() };
382        }
383        if rounds >= bound {
384            let mut diags = pass.take_diags();
385            diags.push(Diagnostic::error(
386                RoundsExceeded {
387                    backend: inputs.backend.to_string(),
388                    rank: bound,
389                    remaining: remaining.iter().map(|e| e.as_str()).collect::<Vec<_>>().join(", "),
390                },
391                current.root().span().clone(),
392            ));
393            return LoweringOutcome { lowered: None, diags };
394        }
395        current = Arc::new(output);
396    }
397}
398
399/// The elements of `tree` that are not in `native`, in name order and
400/// without repetition. [`lower_tree`] runs another round while this list is
401/// not empty.
402///
403/// A node of an element with opaque content ([`OpaqueContent`]) is counted
404/// itself, but its content is not examined: everything inside a math or
405/// verbatim region is copied as source text and never lowered. The only
406/// exception is a node carrying [`ContentInOpaque`] (the argument of a text
407/// command inside a formula): it holds document content, so it and
408/// everything under it are counted like content anywhere else.
409pub fn non_native(tree: &NodeTree<Flm>, native: &BTreeSet<ElementName>) -> Vec<ElementName> {
410    let mut found: BTreeSet<ElementName> = BTreeSet::new();
411    // Each entry is a node and whether it stands inside opaque content.
412    let mut stack: Vec<(NodeRef<'_, Flm>, bool)> = vec![(tree.root(), false)];
413    while let Some((node, in_opaque)) = stack.pop() {
414        let element = element_of(&node);
415        // A node holding content ends the opaque stretch at itself.
416        let in_opaque = in_opaque && !element.has_aspect::<dyn ContentInOpaque>();
417        if !in_opaque && !native.contains(&element.name) {
418            found.insert(element.name.clone());
419        }
420        let below = in_opaque || element.has_aspect::<dyn OpaqueContent>();
421        stack.extend(node.children().iter().map(|child| (child, below)));
422    }
423    found.into_iter().collect()
424}
425
426/// Whether `node` is, or holds among its descendants, a node carrying
427/// [`ContentInOpaque`]: document content inside opaque content.
428///
429/// The walks that copy opaque content use it to decide whether they must
430/// descend into a subtree at all: without one of these nodes in it, an
431/// opaque subtree is entirely source text.
432fn holds_content(node: &NodeRef<'_, Flm>) -> bool {
433    element_of(node).has_aspect::<dyn ContentInOpaque>()
434        || node.descendants().any(|d| element_of(&d).has_aspect::<dyn ContentInOpaque>())
435}
436
437/// A visitor carrying every node over unchanged, for the verbatim copies of
438/// opaque content.
439struct Verbatim;
440
441impl RestageVisitor<Flm, (), ()> for Verbatim {
442    type Error = Infallible;
443
444    fn restage(
445        &mut self,
446        _node: NodeRef<'_, Flm>,
447        _cx: &mut RestageContext<'_, Flm, (), ()>,
448    ) -> Result<Restage<()>, Infallible> {
449        Ok(Restage::Descend(()))
450    }
451}
452
453/// Stages a copy of `node`'s whole subtree, every node copied unchanged with
454/// its kind, span, parsing state and extension, and returns the staged copy.
455///
456/// A rule uses it to place the content of an [opaque
457/// region](crate::guide::concepts_overview#opaque-regions) (a math group, a
458/// verbatim group) in a presentation node: nothing inside it is lowered, and
459/// an emitter writes it again as source text.
460///
461/// The copy must become the body of an element that carries the
462/// [`OpaqueContent`] aspect, such as `flm.pres.math-passthrough` or
463/// `flm.pres.verbatim`. Nothing checks this, and a mistake is reported far
464/// from its cause: the check that ends the rounds examines nothing inside an
465/// opaque subtree except the content of a [`ContentInOpaque`] node, and the
466/// number of rounds allowed counts only what a rule declares in `produces`.
467/// A copy of content the backend does not write natively, placed anywhere
468/// else, therefore needs rounds that neither of them counts, and the tree
469/// fails with `flm.lowering.rounds-exceeded`.
470///
471/// A rule that puts content inside such a body stages it as a node carrying
472/// the [`ContentInOpaque`] aspect and does not copy it through here.
473///
474/// # Errors
475///
476/// Returns a [`LowerError::Build`] when the subtree cannot be staged, or when
477/// staging it unexpectedly gives other than exactly one node.
478pub fn copy_subtree_verbatim(
479    cx: &mut LowerCx<'_>,
480    node: NodeRef<'_, Flm>,
481) -> Result<BuildId, LowerError> {
482    let ids = cx.restage_subtree(node, &mut Verbatim).map_err(infallible_restage)?;
483    match ids.as_slice() {
484        [id] => Ok(*id),
485        _ => Err(LowerError::Build {
486            detail: format!(
487                "verbatim copy of a node produced {} nodes, expected exactly one",
488                ids.len()
489            ),
490        }),
491    }
492}
493
494/// Stages unchanged copies of a run of nodes (a math group's children, a
495/// verbatim group's children) by applying [`copy_subtree_verbatim`] to each,
496/// and returns the copies in order.
497///
498/// The same restriction applies: the copies belong in the body of an
499/// [`OpaqueContent`] element and nowhere else.
500///
501/// # Errors
502///
503/// Returns the first [`LowerError`] [`copy_subtree_verbatim`] returns.
504pub fn copy_run_verbatim(
505    cx: &mut LowerCx<'_>,
506    nodes: NodeSlice<'_, Flm>,
507) -> Result<Vec<BuildId>, LowerError> {
508    let mut ids = Vec::with_capacity(nodes.len());
509    for node in nodes.iter() {
510        ids.push(copy_subtree_verbatim(cx, node)?);
511    }
512    Ok(ids)
513}
514
515/// The content of a verbatim region as [`read_verbatim_content`] returns it.
516#[derive(Debug)]
517pub enum VerbatimContent<'t> {
518    /// Characters: the nodes, to be copied unchanged
519    /// ([`copy_run_verbatim`]).
520    Characters(NodeSlice<'t, Flm>),
521    /// Content that is not characters, already reported: its source text,
522    /// which the region shows instead.
523    Spelled(String),
524}
525
526/// Reads the content `nodes` of a verbatim region as characters, and reports
527/// [`ContentNotCharacters`] at `owner` when it is not characters.
528///
529/// A **verbatim region** is a run of raw text in which no markup character
530/// means anything (see [verbatim
531/// regions](crate::guide::concepts_overview#verbatim-regions)): the content
532/// of a verbatim argument or of a verbatim environment body. What a document
533/// writes there is characters by construction. A user definition's template
534/// may place one of its arguments inside verbatim content, though, and the
535/// expansion substitutes the argument's content there unchanged: a command,
536/// a formula, anything the use site passed. Every rule that stages verbatim
537/// content reads it through this function, so every verbatim region is
538/// treated the same way: the default rule of a bare verbatim group
539/// ([`VerbatimRule`](super::VerbatimRule)) and the rules of the `verbatim`
540/// feature.
541///
542/// The content is read with [`chars_at_lowering`], the only reading of
543/// characters at lowering: text gives its characters, a comment nothing, a
544/// brace group its content without the braces. A command, an environment, a
545/// special character sequence or mathematics has no characters to give; then
546/// the Error is reported once, at `owner` (the command or environment that
547/// owns the region, whose name the condition carries), and the result is the
548/// whole content written as its source text ([`recompose_source`]), so that
549/// `\emph{x}` is shown as those seven characters.
550///
551/// # Errors
552///
553/// [`LowerError::PlaceholderCharacters`] when the content holds a placeholder
554/// of a template that is being lowered unexpanded: the recomposed LaTeX then
555/// expands the use sites of the definition, where the placeholder's content
556/// is known ([`chars_at_lowering`]).
557pub fn read_verbatim_content<'t>(
558    owner: &NodeRef<'_, Flm>,
559    nodes: NodeSlice<'t, Flm>,
560    lw: &mut dyn Lowerer,
561) -> Result<VerbatimContent<'t>, LowerError> {
562    // Content that is not characters is shown as its source spelling rather
563    // than dropped, so that the author sees what was passed there.
564    if chars_at_lowering(nodes.iter())?.is_ok() {
565        return Ok(VerbatimContent::Characters(nodes));
566    }
567    let name = match owner.name() {
568        Some(name) if owner.callable_type() == Some(FlmCallableType::Environment) => {
569            format!("{{{name}}}")
570        }
571        Some(name) => format!("\\{name}"),
572        None => String::from("a verbatim group"),
573    };
574    lw.diagnose(Diagnostic::error(ContentNotCharacters { name }, owner.span().clone()));
575    let nodes: Vec<NodeRef<'t, Flm>> = nodes.iter().collect();
576    Ok(VerbatimContent::Spelled(recompose_source(&nodes)))
577}
578
579/// Stages the content `nodes` of a verbatim region owned by `owner` for the
580/// body of a `flm.pres.verbatim` node, and returns the staged nodes: the
581/// nodes copied unchanged ([`copy_run_verbatim`]) or, for content that is not
582/// characters, its source text as one text node ([`read_verbatim_content`],
583/// which reports it).
584///
585/// # Errors
586///
587/// Returns the first [`LowerError`] staging the copies or the text node
588/// returns.
589pub fn stage_verbatim_content(
590    owner: &NodeRef<'_, Flm>,
591    nodes: NodeSlice<'_, Flm>,
592    cx: &mut LowerCx<'_>,
593    lw: &mut dyn Lowerer,
594) -> Result<Vec<BuildId>, LowerError> {
595    match read_verbatim_content(owner, nodes, lw)? {
596        VerbatimContent::Characters(nodes) => copy_run_verbatim(cx, nodes),
597        VerbatimContent::Spelled(text) => Ok(vec![lw.text(cx, &text)?]),
598    }
599}
600
601/// Lowers a run of sibling nodes through the rules, in order, and returns the
602/// nodes they became.
603///
604/// This is the counterpart of [`copy_run_verbatim`] for document content
605/// rather than source text: where that function copies a run of nodes
606/// unchanged, this one gives the run back to the lowering rules, so each node
607/// becomes what its own rule stages for it. A rule uses it when it has
608/// selected a run of nodes (the content of one argument, one node of an
609/// opaque region that holds document content rather than source text) and
610/// wants the ordinary treatment for it rather than a treatment of its own.
611///
612/// `nodes` must be **siblings of one tree**, in their order in the tree, with
613/// no gap between them: the content nodes of one argument, or the direct
614/// children of one node, or a single node. An empty run is allowed and
615/// stages nothing. Nothing checks the sibling requirement in advance; a run
616/// that does not meet it fails with the structure error below.
617///
618/// The run is lowered as a whole, so a rule that reads a slot's content and
619/// passes it here gets exactly what the driver would have produced for that
620/// content on its own.
621///
622/// # Errors
623///
624/// Returns [`LowerError::Structure`] when `nodes` is not a run of siblings of
625/// one tree, or belongs to another tree than the one the [`Lowerer`] is
626/// lowering ([`Lowerer::lower_nodes`]), and any error lowering the run
627/// returned.
628pub fn lower_run(
629    cx: &mut LowerCx<'_>,
630    lw: &mut dyn Lowerer,
631    nodes: &[NodeRef<'_, Flm>],
632) -> Result<Vec<BuildId>, LowerError> {
633    let (Some(first), Some(last)) = (nodes.first(), nodes.last()) else { return Ok(Vec::new()) };
634    let from = first.id().index() as u32;
635    let to = last.id().index() as u32;
636    let Some(slice) = first.tree().slice(from..to + 1) else {
637        return Err(LowerError::structure("the nodes to lower must be siblings in one tree"));
638    };
639    lw.lower_nodes(cx, slice)
640}
641
642/// Lowers the pieces of a key-value entry's value as the author wrote them
643/// ([`WrittenPiece`], as [`key_value_pieces`](crate::lang::copy::key_value_pieces)
644/// returns them), as ordinary content: a node through the rules ([`lower_run`]),
645/// characters as text; an empty text stages nothing.
646///
647/// The LaTeX rules that relay such a value use it: a float's reference to an
648/// unnumbered float with a caption's alternative text, a heading's
649/// alternative title.
650///
651/// # Errors
652///
653/// As [`lower_run`], and any error staging the text.
654pub(crate) fn lower_written_pieces(
655    cx: &mut LowerCx<'_>,
656    lw: &mut dyn Lowerer,
657    pieces: &[WrittenPiece<'_>],
658) -> Result<Vec<BuildId>, LowerError> {
659    let mut staged = Vec::new();
660    for piece in pieces {
661        match piece {
662            WrittenPiece::Node(node) => staged.extend(lower_run(cx, lw, std::slice::from_ref(node))?),
663            WrittenPiece::Text(text) if text.is_empty() => {}
664            WrittenPiece::Text(text) => staged.push(lw.text(cx, text)?),
665        }
666    }
667    Ok(staged)
668}
669
670/// The plain shape of a node region's content ([`RegionShape`]): the content
671/// nodes lowered unchanged, as one run of siblings ([`lower_run`]).
672///
673/// Pass it to [`Lowerer::lower_region`] to show a node region of another
674/// node where the rule's own node is placed, with nothing added by the rule:
675/// `lw.lower_region(cx, at, region, &mut lower_region_content)`. `_node`,
676/// the node the region belongs to, is not read.
677///
678/// # Errors
679///
680/// As [`lower_run`].
681pub fn lower_region_content(
682    cx: &mut LowerCx<'_>,
683    lw: &mut dyn Lowerer,
684    _node: &NodeRef<'_, Flm>,
685    content: &[NodeRef<'_, Flm>],
686) -> Result<Vec<BuildId>, LowerError> {
687    lower_run(cx, lw, content)
688}
689
690fn infallible_restage(error: RestageError<Infallible>) -> LowerError {
691    LowerError::Build { detail: error.to_string() }
692}
693
694/// How the visited node's address and origin are computed.
695#[derive(Debug, Clone, Copy, PartialEq, Eq)]
696enum Mode {
697    /// The first round, over the frozen tree: a node is its own address.
698    Frozen,
699    /// A later round, over the previous round's output: the node's origin is
700    /// what the previous round recorded for it.
701    Chain,
702    /// Inside a splice, over a caught-up value: the address is the value's,
703    /// the origin the splicing rule's node.
704    Value(TreeId),
705    /// Inside a region lowering ([`Lowerer::lower_region`]), over the tree the
706    /// region belongs to: a node is its own address and its own origin in
707    /// that tree.
708    Pointed(TreeId),
709}
710
711/// The per-visit state saved around the descent (techy's restager has no
712/// exit callback, so each visit restores what it changed).
713struct Visit {
714    current: Option<RuleIdx>,
715    origin: Option<NodeAddr>,
716    addr: Option<NodeAddr>,
717    trigger: Option<(FlmSpan, Arc<ParsingState<Flm>>)>,
718    synth: Option<Arc<FlmSource>>,
719}
720
721/// The pass: the visitor of every round and the [`Lowerer`] every rule
722/// receives.
723struct Pass<'r> {
724    cx: &'r StageCx<'r>,
725    backend: &'r BackendName,
726    registry: &'r FlmRegistry,
727    selected: &'r SelectedRules,
728    native: &'r BTreeSet<ElementName>,
729    holes: &'r BTreeSet<ElementName>,
730    doc_tree: TreeId,
731    /// The root of the document tree being lowered: the address every
732    /// fallback returns.
733    doc_root: NodeId,
734    driver_rule: RuleName,
735    specs: BTreeMap<ElementName, Arc<FlmPresentationSpec>>,
736    mode: Mode,
737    /// The tree the current round visits, as the address of its allocation:
738    /// outside a splice and a region lowering, a node of any other tree is
739    /// not the round's to lower.
740    round_tree: usize,
741    /// The origins of the previous round's output, by node index.
742    previous: Vec<NodeAddr>,
743    /// The origin recorded for nodes staged inside a splice.
744    inherit: Option<NodeAddr>,
745    depth: u32,
746    /// Whether the node being visited is inside opaque content whose copy is
747    /// under way: such a node is copied as the source text it is.
748    in_opaque: bool,
749    // per visit
750    current: Option<RuleIdx>,
751    origin: Option<NodeAddr>,
752    addr: Option<NodeAddr>,
753    trigger: Option<(FlmSpan, Arc<ParsingState<Flm>>)>,
754    synth: Option<Arc<FlmSource>>,
755    // values and entered trees
756    /// The values this pass holds, each with its own results: the value
757    /// [`lower_value`] lowers, and every value a splice is lowering, innermost
758    /// last. A table read at an address of one of them reads its results
759    /// first; a read at any other address never does.
760    stores: Vec<(TreeId, Arc<NodeTree<Flm>>, Computed)>,
761    /// The trees a splice or a region lowering has entered, innermost last:
762    /// the last one is the tree the `Lowerer` is lowering.
763    entered: Vec<(TreeId, Arc<NodeTree<Flm>>)>,
764    /// Where each value being spliced is shown, innermost last: the span of
765    /// the node whose rule spliced it. Every diagnostic added to the
766    /// collection meanwhile gets one frame per entry, innermost first.
767    shown_at: Vec<FlmSpan>,
768    // outputs
769    origins: HashMap<BuildId, NodeAddr>,
770    round_origins: Vec<NodeAddr>,
771    requires: BTreeSet<Name>,
772    diags: FlmDiagnostics,
773    nesting_refused: Option<String>,
774}
775
776impl<'r> Pass<'r> {
777    fn new(
778        cx: &'r StageCx<'r>,
779        inputs: &LoweringInputs<'r>,
780        doc_tree: TreeId,
781        doc_root: NodeId,
782    ) -> Pass<'r> {
783        Pass {
784            cx,
785            backend: inputs.backend,
786            registry: inputs.registry,
787            selected: inputs.selected,
788            native: inputs.native,
789            holes: inputs.holes,
790            doc_tree,
791            doc_root,
792            driver_rule: RuleName::from(DRIVER_RULE),
793            specs: BTreeMap::new(),
794            mode: Mode::Frozen,
795            round_tree: 0,
796            previous: Vec::new(),
797            inherit: None,
798            depth: 0,
799            in_opaque: false,
800            current: None,
801            origin: None,
802            addr: None,
803            trigger: None,
804            synth: None,
805            stores: Vec::new(),
806            entered: Vec::new(),
807            shown_at: Vec::new(),
808            origins: HashMap::new(),
809            round_origins: Vec::new(),
810            requires: inputs.selection_requires.clone(),
811            diags: FlmDiagnostics::new(),
812            nesting_refused: None,
813        }
814    }
815
816    /// Adds `diagnostic` to the pass's diagnostics. Inside a splice it first
817    /// gets one frame for each value being spliced, innermost first, titled
818    /// `SHOWN_HERE` and spanning the node at which the value is shown; its own
819    /// span, where the content was written, is unchanged.
820    fn report(&mut self, diagnostic: FlmDiagnostic) {
821        let frames = self.shown_at.iter().rev();
822        let frames = frames.map(|span| TraceFrame::new(SHOWN_HERE, span.clone())).collect();
823        self.diags.push(diagnostic.with_outer_frames(frames));
824    }
825
826    fn take_diags(&mut self) -> FlmDiagnostics {
827        std::mem::replace(&mut self.diags, FlmDiagnostics::new())
828    }
829
830    /// Puts the diagnostics back as they were when `(len, suppressed,
831    /// error_count)` was read from them: the diagnostics pushed since, stored
832    /// or only counted, are dropped. The counts read from the collection are
833    /// consistent with its first `len` diagnostics, so the rebuild succeeds.
834    fn restore_diags(&mut self, (len, suppressed, error_count): (usize, usize, usize)) {
835        let kept = self.diags.as_slice()[..len].to_vec();
836        if let Ok(restored) =
837            FlmDiagnostics::from_parts(kept, self.diags.limit(), suppressed, error_count)
838        {
839            self.diags = restored;
840        }
841    }
842
843    /// The condition that reports a failed round.
844    fn failure_of(&mut self, error: RestageError<LowerError>) -> FailedTree {
845        let backend = self.backend.to_string();
846        if let Some(detail) = self.nesting_refused.take() {
847            return FailedTree::Nesting(NestingTooDeep { backend, detail });
848        }
849        match error {
850            RestageError::DescentLimitExceeded { detail, .. } => {
851                FailedTree::Nesting(NestingTooDeep { backend, detail })
852            }
853            RestageError::Visitor(inner) => {
854                FailedTree::Failed(LoweringFailed { backend, detail: inner.to_string() })
855            }
856            other => FailedTree::Failed(LoweringFailed { backend, detail: other.to_string() }),
857        }
858    }
859
860    /// A context operation's failure as the `Lowerer`'s error: the visitor's
861    /// own error unwrapped, the guard's refusal remembered, anything else a
862    /// staging failure (fatal).
863    fn convert(&mut self, error: RestageError<LowerError>) -> LowerError {
864        match error {
865            RestageError::Visitor(inner) => inner,
866            RestageError::DescentLimitExceeded { detail, .. } => {
867                self.nesting_refused = Some(detail.clone());
868                LowerError::Build { detail }
869            }
870            other => LowerError::Build { detail: other.to_string() },
871        }
872    }
873
874    fn is_fatal(error: &LowerError) -> bool {
875        matches!(error, LowerError::Build { .. })
876    }
877
878    // --- per-visit context ---------------------------------------------------------------
879
880    fn rule_name(&self) -> &RuleName {
881        match self.current {
882            Some(idx) => &self.registry.rule(idx).rule.name,
883            None => &self.driver_rule,
884        }
885    }
886
887    /// The running rule's name as a stage name: the conditions raised where a
888    /// read is checked are the store's and identify a stage, so a rule's
889    /// undeclared read is shown as "stage `<rule>`". The data is right and the
890    /// word is the store's; a variant that identifies a rule would have to be
891    /// added to the store.
892    fn rule_as_stage(&self) -> StageName {
893        StageName::from(self.rule_name().as_str())
894    }
895
896    fn trigger(&self) -> Result<&(FlmSpan, Arc<ParsingState<Flm>>), LowerError> {
897        self.trigger
898            .as_ref()
899            .ok_or_else(|| {
900                LowerError::other(
901                    "the methods of ‘Lowerer’ may be called only while a node is \
902                     being lowered",
903                )
904            })
905    }
906
907    /// The synthesized source of the pair (visited node, rule): created once
908    /// per visit, at the node, labeled with the rule's name.
909    fn synth_source(&mut self) -> Result<Arc<FlmSource>, LowerError> {
910        if let Some(source) = &self.synth {
911            return Ok(Arc::clone(source));
912        }
913        let (span, _) = self.trigger()?;
914        let label = format!("lowering rule `{}`", self.rule_name());
915        let source = Arc::new(
916            Source::synthesized(format!("«{}»", self.rule_name()), label.clone(), span.clone())
917                .with_origin(FlmOrigin::synthetic(label)),
918        );
919        self.synth = Some(Arc::clone(&source));
920        Ok(source)
921    }
922
923    fn spec_for(&mut self, element: &ElementName) -> Result<Arc<FlmPresentationSpec>, LowerError> {
924        if let Some(spec) = self.specs.get(element) {
925            return Ok(Arc::clone(spec));
926        }
927        let entry = self.registry.presentation_element(element).ok_or_else(|| {
928            LowerError::other(format!("unknown presentation element ‘{element}’"))
929        })?;
930        let spec = Arc::new(FlmPresentationSpec::new(Arc::clone(&entry.element)));
931        self.specs.insert(element.clone(), Arc::clone(&spec));
932        Ok(spec)
933    }
934
935    fn record(&mut self, id: BuildId) -> BuildId {
936        if let Some(origin) = self.origin {
937            self.origins.insert(id, origin);
938        }
939        id
940    }
941
942    // --- dispatch --------------------------------------------------------------------------
943
944    fn dispatch(
945        &mut self,
946        node: NodeRef<'_, Flm>,
947        cx: &mut LowerCx<'_>,
948    ) -> Result<Vec<BuildId>, LowerError> {
949        let element = Arc::clone(element_of(&node));
950        // Inside opaque content, a node is the source it is and is carried
951        // over; a node carrying `ContentInOpaque` holds content instead, and
952        // is dispatched like a node anywhere else — it and everything under
953        // it.
954        if self.in_opaque {
955            if !element.has_aspect::<dyn ContentInOpaque>() {
956                return self.copy(cx, node);
957            }
958            let saved = std::mem::replace(&mut self.in_opaque, false);
959            let out = self.dispatch_content(node, cx, element);
960            self.in_opaque = saved;
961            return out;
962        }
963        self.dispatch_content(node, cx, element)
964    }
965
966    /// The dispatch itself, on a node that is document content: the three
967    /// steps of a round (see the [module documentation](self)).
968    fn dispatch_content(
969        &mut self,
970        node: NodeRef<'_, Flm>,
971        cx: &mut LowerCx<'_>,
972        element: Arc<ElementSpec>,
973    ) -> Result<Vec<BuildId>, LowerError> {
974        if self.native.contains(&element.name) {
975            if element.has_aspect::<dyn OpaqueContent>() {
976                // Source through and through: the subtree is copied in one
977                // step. Where content stands in it, the copy descends instead,
978                // so that the content is lowered where it stands.
979                if !node.children().iter().any(|child| holds_content(&child)) {
980                    let id = copy_subtree_verbatim(cx, node)?;
981                    return Ok(vec![self.record(id)]);
982                }
983                let saved = std::mem::replace(&mut self.in_opaque, true);
984                let out = self.copy(cx, node);
985                self.in_opaque = saved;
986                return out;
987            }
988            return self.copy(cx, node);
989        }
990        if let Some(idx) = self.selected.rule_for(&element.name) {
991            let registry = self.registry;
992            let rule = &registry.rule(idx).rule;
993            self.current = Some(idx);
994            let outcome = rule.rule.lower(node, cx, self);
995            self.current = None;
996            return match outcome {
997                Ok(Lowering::Emit(ids)) => Ok(ids),
998                Ok(Lowering::Default) => self.copy(cx, node),
999                Err(error) if Pass::is_fatal(&error) => Err(error),
1000                // Passed on unreported to the rule that spliced the template
1001                // the placeholder stands in, which acts on it.
1002                Err(LowerError::PlaceholderCharacters) => Err(LowerError::PlaceholderCharacters),
1003                Err(LowerError::Refused(diagnostic)) => {
1004                    self.report(*diagnostic);
1005                    self.unsupported(
1006                        cx,
1007                        node,
1008                        &element.name,
1009                        format!("rule `{}` failed", rule.name),
1010                    )
1011                }
1012                Err(LowerError::RegionNotFound { detail }) => {
1013                    self.report(Diagnostic::error(
1014                        RegionNotFound {
1015                            backend: self.backend.to_string(),
1016                            rule: rule.name.to_string(),
1017                            element: element.name.to_string(),
1018                            detail,
1019                        },
1020                        node.span().clone(),
1021                    ));
1022                    self.unsupported(
1023                        cx,
1024                        node,
1025                        &element.name,
1026                        format!("rule `{}` failed", rule.name),
1027                    )
1028                }
1029                Err(error) => {
1030                    self.report(Diagnostic::error(
1031                        RuleFailed {
1032                            backend: self.backend.to_string(),
1033                            rule: rule.name.to_string(),
1034                            element: element.name.to_string(),
1035                            detail: error.to_string(),
1036                        },
1037                        node.span().clone(),
1038                    ));
1039                    self.unsupported(
1040                        cx,
1041                        node,
1042                        &element.name,
1043                        format!("rule `{}` failed", rule.name),
1044                    )
1045                }
1046            };
1047        }
1048        if self.holes.contains(&element.name) {
1049            self.report(Diagnostic::error(
1050                UnsupportedElement {
1051                    backend: self.backend.to_string(),
1052                    element: element.name.to_string(),
1053                },
1054                node.span().clone(),
1055            ));
1056        } else {
1057            self.report(Diagnostic::error(
1058                NoRule { backend: self.backend.to_string(), element: element.name.to_string() },
1059                node.span().clone(),
1060            ));
1061        }
1062        let message = format!("backend `{}` cannot render `{}`", self.backend, element.name);
1063        self.unsupported(cx, node, &element.name, message)
1064    }
1065
1066    /// The childless stand-in for a node the backend cannot render.
1067    fn unsupported(
1068        &mut self,
1069        cx: &mut LowerCx<'_>,
1070        node: NodeRef<'_, Flm>,
1071        element: &ElementName,
1072        message: String,
1073    ) -> Result<Vec<BuildId>, LowerError> {
1074        let payload: Arc<dyn PresPayload> =
1075            Arc::new(UnsupportedPayload { element: element.clone(), message });
1076        let name = ElementName::from(pres::UNSUPPORTED);
1077        let label = format!("unsupported `{element}`");
1078        let source = Arc::new(
1079            Source::synthesized(format!("«{element}»"), label.clone(), node.span().clone())
1080                .with_origin(FlmOrigin::synthetic(label)),
1081        );
1082        let state = Arc::clone(node.parsing_state());
1083        let body = vec![(String::from(pres::BODY_SLOT), Vec::new())];
1084        let id = self.stage_node(cx, &name, payload, body, Vec::new(), source, state).map_err(
1085            // A registry without the vocabulary cannot recover a hole: fatal.
1086            |error| LowerError::Build { detail: error.to_string() },
1087        )?;
1088        Ok(vec![id])
1089    }
1090
1091    /// The driver's copy: the node added again over its children, lowered in
1092    /// turn. A leaf is copied unchanged; a group or a list over its lowered
1093    /// children; a callable is rebuilt argument by argument and slot by slot
1094    /// (techy's content-swap route, so the argument and slot records keep
1095    /// their meaning).
1096    fn copy(
1097        &mut self,
1098        cx: &mut LowerCx<'_>,
1099        node: NodeRef<'_, Flm>,
1100    ) -> Result<Vec<BuildId>, LowerError> {
1101        let id = match node.kind() {
1102            NodeKind::Chars { .. } | NodeKind::Comment(_) => cx
1103                .builder()
1104                .add(
1105                    node.kind().clone(),
1106                    node.span().clone(),
1107                    Arc::clone(node.parsing_state()),
1108                    Vec::new(),
1109                    node.ext().clone(),
1110                    (),
1111                )
1112                .map_err(|e| LowerError::Build { detail: e.to_string() })?,
1113            NodeKind::Group(_) | NodeKind::List => {
1114                let children = cx.restage_children(node, self).map_err(|e| self.convert(e))?;
1115                cx.builder()
1116                    .add(
1117                        node.kind().clone(),
1118                        node.span().clone(),
1119                        Arc::clone(node.parsing_state()),
1120                        children,
1121                        node.ext().clone(),
1122                        (),
1123                    )
1124                    .map_err(|e| LowerError::Build { detail: e.to_string() })?
1125            }
1126            NodeKind::Callable(data) => {
1127                let mut arguments = Vec::with_capacity(data.arguments.len());
1128                for (index, record) in data.arguments.iter().enumerate() {
1129                    if !record.is_provided() {
1130                        arguments.push(RestagedArgument::absent(Arc::clone(&record.spec)));
1131                        continue;
1132                    }
1133                    let content = self.lower_slice(cx, node.argument_content_nodes(index))?;
1134                    let bundle = cx
1135                        .restage_argument_with_content::<LowerError>(node, index, content, ())
1136                        .map_err(|e| self.convert(e))?;
1137                    arguments.push(bundle);
1138                }
1139                let mut slots = Vec::with_capacity(data.slots.len());
1140                for index in 0..data.slots.len() {
1141                    let content = self.lower_slice(cx, node.slot_content_nodes(index))?;
1142                    let bundle = cx
1143                        .restage_slot_with_content::<LowerError>(node, index, content, ())
1144                        .map_err(|e| self.convert(e))?;
1145                    slots.push(bundle);
1146                }
1147                cx.restage_invocation::<LowerError>(node, arguments, slots, ())
1148                    .map_err(|e| self.convert(e))?
1149            }
1150        };
1151        Ok(vec![self.record(id)])
1152    }
1153
1154    /// Lowers the content nodes of an argument or a slot (nothing when
1155    /// absent).
1156    fn lower_slice(
1157        &mut self,
1158        cx: &mut LowerCx<'_>,
1159        content: Option<NodeSlice<'_, Flm>>,
1160    ) -> Result<Vec<BuildId>, LowerError> {
1161        let Some(content) = content else { return Ok(Vec::new()) };
1162        // Another tree's nodes are lowered through `lower_region` alone,
1163        // which enters their tree; lowered here they would answer the
1164        // addresses of the tree being lowered.
1165        if content.iter().next().is_some_and(|first| !self.is_input_tree(&first)) {
1166            return Err(LowerError::structure(
1167                "the nodes to lower must belong to the tree being lowered; use \
1168                 ‘Lowerer::lower_region’ for the content of another tree",
1169            ));
1170        }
1171        let mut ids = Vec::new();
1172        for child in content.iter() {
1173            ids.extend(cx.restage_subtree(child, self).map_err(|e| self.convert(e))?);
1174        }
1175        Ok(ids)
1176    }
1177
1178    // --- synthesis -----------------------------------------------------------------------
1179
1180    /// Stages a presentation node of `element` over its content slots (in
1181    /// order; the one named `body` marked as the body) and `attached` (one
1182    /// attached slot per decoration moved out of a content slot, after the
1183    /// content slots), on the given source and state. The node extension is
1184    /// created by `Flm::make_node_ext` and the payload set here. techy
1185    /// requires the slots to cover the children in order, without gaps.
1186    #[allow(clippy::too_many_arguments)]
1187    fn stage_node(
1188        &mut self,
1189        cx: &mut LowerCx<'_>,
1190        element: &ElementName,
1191        payload: Arc<dyn PresPayload>,
1192        content: Vec<(String, Vec<BuildId>)>,
1193        attached: Hoisted,
1194        source: Arc<FlmSource>,
1195        state: Arc<ParsingState<Flm>>,
1196    ) -> Result<BuildId, LowerError> {
1197        let spec = self.spec_for(element)?;
1198        let mut children: Vec<BuildId> = Vec::new();
1199        let mut slots = Vec::with_capacity(content.len() + attached.len());
1200        for (name, nodes) in content {
1201            let start = children.len() as u32;
1202            let len = nodes.len() as u32;
1203            children.extend(nodes);
1204            let marker = if name == pres::BODY_SLOT {
1205                BodyMarker::make_body()
1206            } else {
1207                BodyMarker::not_body()
1208            };
1209            slots.push(ParsedSlot::new(
1210                ChildRegion::new(start..start + len, ContentNodes::InRegion(0..len)),
1211                name.as_str(),
1212                SlotRole::Content,
1213                marker,
1214            ));
1215        }
1216        for (name, node) in attached {
1217            let start = children.len() as u32;
1218            children.push(node);
1219            slots.push(ParsedSlot::new(
1220                ChildRegion::new(start..start + 1, ContentNodes::InRegion(0..1)),
1221                name.as_str(),
1222                SlotRole::Attached,
1223                BodyMarker::not_body(),
1224            ));
1225        }
1226        let kind = NodeKind::callable(
1227            spec.callable_data(ParsedArguments::empty(), ParsedSlots::new(slots)),
1228        );
1229        let span = SourceSpan::entire(&source);
1230        let builder = cx.builder();
1231        let ext = Flm::make_node_ext(&kind, &span, &state, builder.staged_children(&children))
1232            .map_err(|e| LowerError::Build { detail: e.to_string() })?
1233            .with_payload(payload);
1234        let id = builder
1235            .add(kind, span, state, children, ext, ())
1236            .map_err(|e| LowerError::Build { detail: e.to_string() })?;
1237        Ok(self.record(id))
1238    }
1239
1240    /// Splits the staged nodes of one content slot into its content, with a
1241    /// decoration mark at each decoration's former position, and moves the
1242    /// decorations into `attached`. A mark gives its decoration's attached
1243    /// slot by index in the node's slot list: the attached slots follow the
1244    /// `content_slots` content slots, in the order the decorations were
1245    /// moved.
1246    fn hoist(
1247        &mut self,
1248        cx: &mut LowerCx<'_>,
1249        nodes: Vec<BuildId>,
1250        content_slots: u32,
1251        attached: &mut Hoisted,
1252    ) -> Result<Vec<BuildId>, LowerError> {
1253        let decorations: Vec<(usize, ElementName)> = {
1254            let staged = cx.builder().staged_nodes();
1255            nodes
1256                .iter()
1257                .enumerate()
1258                .filter_map(|(index, id)| {
1259                    let element = &staged.get(*id)?.ext().element;
1260                    element.has_aspect::<dyn Decoration>().then(|| (index, element.name.clone()))
1261                })
1262                .collect()
1263        };
1264        if decorations.is_empty() {
1265            return Ok(nodes);
1266        }
1267        let mut content = Vec::with_capacity(nodes.len());
1268        for (index, id) in nodes.into_iter().enumerate() {
1269            match decorations.iter().find(|(at, _)| *at == index) {
1270                Some((_, name)) => {
1271                    let slot = content_slots + attached.len() as u32;
1272                    let origin = self.origins.get(&id).copied().or(self.origin);
1273                    attached.push((name.clone(), id));
1274                    content.push(self.deco_mark(cx, slot, origin)?);
1275                }
1276                None => content.push(id),
1277            }
1278        }
1279        Ok(content)
1280    }
1281
1282    /// The `Lowerer`'s staging of a presentation node for the running rule:
1283    /// the `produces` check, the move of decorations out of every content
1284    /// slot, the shared synthesized source and the node's state.
1285    fn stage_pres(
1286        &mut self,
1287        cx: &mut LowerCx<'_>,
1288        element: &ElementName,
1289        payload: Arc<dyn PresPayload>,
1290        slots: Vec<(String, Vec<BuildId>)>,
1291    ) -> Result<BuildId, LowerError> {
1292        let Some(idx) = self.current else {
1293            return Err(LowerError::other(
1294                "presentation nodes may be staged only while a lowering rule is running",
1295            ));
1296        };
1297        let decl = &self.registry.rule(idx).rule.decl;
1298        if !decl.produces.contains(element) {
1299            return Err(LowerError::UndeclaredProduces {
1300                rule: self.registry.rule(idx).rule.name.clone(),
1301                element: element.clone(),
1302                declared: decl.produces.clone(),
1303            });
1304        }
1305        let content_slots = slots.len() as u32;
1306        let mut attached = Vec::new();
1307        let mut content = Vec::with_capacity(slots.len());
1308        for (name, nodes) in slots {
1309            let nodes = self.hoist(cx, nodes, content_slots, &mut attached)?;
1310            content.push((name, nodes));
1311        }
1312        let source = self.synth_source()?;
1313        let (_, state) = self.trigger()?;
1314        let state = Arc::clone(state);
1315        self.stage_node(cx, element, payload, content, attached, source, state)
1316    }
1317
1318    /// The childless decoration mark left where a decoration was moved out;
1319    /// its origin is the decoration's, not the block's.
1320    fn deco_mark(
1321        &mut self,
1322        cx: &mut LowerCx<'_>,
1323        slot: u32,
1324        origin: Option<NodeAddr>,
1325    ) -> Result<BuildId, LowerError> {
1326        let name = ElementName::from(pres::DECO_MARK);
1327        let source = self.synth_source()?;
1328        let (_, state) = self.trigger()?;
1329        let state = Arc::clone(state);
1330        let payload: Arc<dyn PresPayload> = Arc::new(DecoMarkPayload { slot });
1331        let saved = self.origin;
1332        self.origin = origin;
1333        let body = vec![(String::from(pres::BODY_SLOT), Vec::new())];
1334        let result = self.stage_node(cx, &name, payload, body, Vec::new(), source, state);
1335        self.origin = saved;
1336        result
1337    }
1338
1339    // --- the origin chain ------------------------------------------------------------
1340
1341    /// After the root's visit: the origin of every node of the round's output
1342    /// in the tree's storage order — techy's breadth-first layout replayed
1343    /// over the staged graph — a node without a recorded origin inheriting
1344    /// its parent's.
1345    fn finish_round(&mut self, cx: &mut LowerCx<'_>, root: BuildId) {
1346        let staged = cx.builder().staged_nodes();
1347        let root_origin = self
1348            .origins
1349            .get(&root)
1350            .copied()
1351            .or(self.origin)
1352            .unwrap_or(NodeAddr::new(self.doc_tree, self.doc_root));
1353        let mut order: Vec<(BuildId, NodeAddr)> = vec![(root, root_origin)];
1354        let mut position = 0;
1355        while position < order.len() {
1356            let (id, origin) = order[position];
1357            if let Some(view) = staged.get(id) {
1358                for child in view.children() {
1359                    let own = self.origins.get(child).copied().unwrap_or(origin);
1360                    order.push((*child, own));
1361                }
1362            }
1363            position += 1;
1364        }
1365        self.round_origins = order.into_iter().map(|(_, origin)| origin).collect();
1366    }
1367
1368    /// The origin of a node of the tree being visited under the current mode.
1369    fn origin_of_input(&self, node: &NodeRef<'_, Flm>) -> Option<NodeAddr> {
1370        match self.mode {
1371            Mode::Frozen => Some(NodeAddr::new(self.doc_tree, node.id())),
1372            Mode::Chain => self.previous.get(node.id().index()).copied(),
1373            Mode::Value(_) => self.inherit,
1374            Mode::Pointed(id) => Some(NodeAddr::new(id, node.id())),
1375        }
1376    }
1377
1378    /// The address at which a node of the tree being visited reads tables.
1379    fn addr_of_input(&self, node: &NodeRef<'_, Flm>) -> Option<NodeAddr> {
1380        match self.mode {
1381            Mode::Frozen => Some(NodeAddr::new(self.doc_tree, node.id())),
1382            Mode::Chain => self.previous.get(node.id().index()).copied(),
1383            Mode::Value(id) | Mode::Pointed(id) => Some(NodeAddr::new(id, node.id())),
1384        }
1385    }
1386
1387    /// Whether `node` belongs to the tree currently being visited.
1388    fn is_input_tree(&self, node: &NodeRef<'_, Flm>) -> bool {
1389        let key = node.tree() as *const NodeTree<Flm> as usize;
1390        match self.mode {
1391            Mode::Value(id) | Mode::Pointed(id) => self
1392                .entered
1393                .last()
1394                .is_some_and(|(entered, tree)| *entered == id && Arc::as_ptr(tree) as usize == key),
1395            Mode::Frozen | Mode::Chain => self.round_tree == key,
1396        }
1397    }
1398
1399    /// The tree with the identifier `id` that a region lowering may lower
1400    /// content of: a frozen document tree, or a synthesized value this pass
1401    /// holds.
1402    fn reachable_tree(&self, id: TreeId) -> Option<Arc<NodeTree<Flm>>> {
1403        if id.is_document_tree() {
1404            return self.cx.frozen_tree(id).cloned();
1405        }
1406        self.stores
1407            .iter()
1408            .rev()
1409            .find(|(value, _, _)| *value == id)
1410            .map(|(_, tree, _)| Arc::clone(tree))
1411    }
1412}
1413
1414/// The condition that reports a tree whose lowering failed.
1415enum FailedTree {
1416    Nesting(NestingTooDeep),
1417    Failed(LoweringFailed),
1418}
1419
1420/// The Error diagnostic of a failed tree, at the tree's root.
1421fn failure_diagnostic(failure: FailedTree, span: FlmSpan) -> FlmDiagnostic {
1422    match failure {
1423        FailedTree::Nesting(condition) => Diagnostic::error(condition, span),
1424        FailedTree::Failed(condition) => Diagnostic::error(condition, span),
1425    }
1426}
1427
1428impl<'r> RestageVisitor<Flm, (), ()> for Pass<'r> {
1429    type Error = LowerError;
1430
1431    fn restage(
1432        &mut self,
1433        node: NodeRef<'_, Flm>,
1434        cx: &mut RestageContext<'_, Flm, (), ()>,
1435    ) -> Result<Restage<()>, LowerError> {
1436        self.depth += 1;
1437        let saved = Visit {
1438            current: self.current.take(),
1439            origin: self.origin,
1440            addr: self.addr,
1441            trigger: self.trigger.take(),
1442            synth: self.synth.take(),
1443        };
1444        self.origin = self.origin_of_input(&node);
1445        self.addr = self.addr_of_input(&node);
1446        self.trigger = Some((node.span().clone(), Arc::clone(node.parsing_state())));
1447
1448        let mut result = self.dispatch(node, cx);
1449        if self.depth == 1 {
1450            // The tree root is a container the backend claims natively, copied
1451            // as exactly one node; anything else would leave the next round's
1452            // origin chain empty, so it is a failure rather than a silent gap.
1453            let root = match result.as_deref() {
1454                Ok([root]) => Ok(Some(*root)),
1455                Ok(other) => Err(other.len()),
1456                Err(_) => Ok(None),
1457            };
1458            match root {
1459                Ok(Some(root)) => self.finish_round(cx, root),
1460                Ok(None) => {}
1461                Err(count) => {
1462                    result = Err(LowerError::Build {
1463                        detail: format!(
1464                            "the root of the tree lowered to {count} nodes, expected exactly one"
1465                        ),
1466                    });
1467                }
1468            }
1469        }
1470
1471        self.depth -= 1;
1472        self.current = saved.current;
1473        self.origin = saved.origin;
1474        self.addr = saved.addr;
1475        self.trigger = saved.trigger;
1476        self.synth = saved.synth;
1477        result.map(Restage::Emit)
1478    }
1479}
1480
1481impl<'r> Pass<'r> {
1482    /// [`Lowerer::splice`] once the node the value is shown at is recorded.
1483    fn splice_shown(
1484        &mut self,
1485        cx: &mut LowerCx<'_>,
1486        value: &Arc<NodeTree<Flm>>,
1487    ) -> Result<Vec<BuildId>, LowerError> {
1488        // What the value's lowering reports and requests is discarded when it
1489        // ends in a placeholder's outcome: the rule that spliced the value
1490        // writes something else in its place, which reports and requests its
1491        // own.
1492        let diags_on_entry = (self.diags.len(), self.diags.suppressed(), self.diags.error_count());
1493        let requires_on_entry = self.requires.clone();
1494        let caught = match self.cx.resolve_value(value) {
1495            Ok(caught) => caught,
1496            Err(CatchUpError::Store(StoreError::DocumentFactInValue { stage, table })) => {
1497                return Err(LowerError::DocumentFactInValue { stage, table });
1498            }
1499            Err(error) => {
1500                if let Some(diagnostic) = error.diagnostic() {
1501                    self.report(diagnostic.clone());
1502                }
1503                return Err(LowerError::CatchUp { detail: error.to_string() });
1504            }
1505        };
1506        for diagnostic in caught.diags {
1507            self.report(diagnostic);
1508        }
1509        let tree = Arc::clone(&caught.tree);
1510        self.stores.push((caught.id, Arc::clone(&tree), caught.scratch));
1511        self.entered.push((caught.id, Arc::clone(&tree)));
1512        let saved_mode = self.mode;
1513        let saved_inherit = self.inherit;
1514        self.mode = Mode::Value(caught.id);
1515        self.inherit = self.origin;
1516        let result = (|| {
1517            let root = tree.root();
1518            let mut ids = Vec::new();
1519            if root.is_list() {
1520                for child in root.children().iter() {
1521                    ids.extend(cx.restage_subtree(child, self).map_err(|e| self.convert(e))?);
1522                }
1523            } else {
1524                ids.extend(cx.restage_subtree(root, self).map_err(|e| self.convert(e))?);
1525            }
1526            Ok(ids)
1527        })();
1528        self.mode = saved_mode;
1529        self.inherit = saved_inherit;
1530        self.entered.pop();
1531        self.stores.pop();
1532        if let Err(LowerError::PlaceholderCharacters) = result {
1533            self.restore_diags(diags_on_entry);
1534            self.requires = requires_on_entry;
1535        }
1536        result
1537    }
1538}
1539
1540impl<'r> Lowerer for Pass<'r> {
1541    fn rule(&self) -> &RuleName {
1542        self.rule_name()
1543    }
1544
1545    fn backend(&self) -> &BackendName {
1546        self.backend
1547    }
1548
1549    fn comment_start(&self) -> Option<&str> {
1550        self.registry.lang().parsing().comment_start()
1551    }
1552
1553    fn lang(&self) -> &BuiltLang {
1554        self.registry.lang()
1555    }
1556
1557    fn tree_id(&self) -> TreeId {
1558        self.entered.last().map(|(id, _)| *id).unwrap_or(self.doc_tree)
1559    }
1560
1561    fn layout(&self) -> FragmentLayout {
1562        let id = self.tree_id();
1563        // A value is brought up to date under the default layout, both by a
1564        // splice and by `lower_value`; a document tree answers its fragment's,
1565        // which every tree the run lowers has — the tree being lowered and a
1566        // tree a region lowering entered alike.
1567        if id.is_value() { FragmentLayout::default() } else { self.cx.layout(id).unwrap_or_default() }
1568    }
1569
1570    fn addr(&self) -> NodeAddr {
1571        // The façade is handed to rules inside visits only, where the address
1572        // is set; the fallback (the document tree's root) is unreachable.
1573        self.addr.unwrap_or(NodeAddr::new(self.doc_tree, self.doc_root))
1574    }
1575
1576    fn addr_of(&self, node: &NodeRef<'_, Flm>) -> Result<NodeAddr, LowerError> {
1577        if !self.is_input_tree(node) {
1578            return Err(LowerError::structure("the node must belong to the tree being lowered"));
1579        }
1580        self.addr_of_input(node).ok_or_else(|| {
1581            LowerError::structure("missing address for the node in the tree being lowered")
1582        })
1583    }
1584
1585    fn placement(&self) -> Option<TreeId> {
1586        self.cx.placement_of(self.addr())
1587    }
1588
1589    fn get_erased(
1590        &self,
1591        table: &crate::core::data::table::TableRef,
1592    ) -> Result<Option<&(dyn std::any::Any + Send + Sync)>, AccessError> {
1593        let Some(idx) = self.current else {
1594            return Err(AccessError::UndeclaredRead {
1595                stage: self.rule_as_stage(),
1596                table: table.name.clone(),
1597                declared: Vec::new(),
1598            });
1599        };
1600        let decl = &self.registry.rule(idx).rule.decl;
1601        // The declared list is for the error arms only: a rule reading a
1602        // table at every node of its element does not pay for it.
1603        let declared = || {
1604            let mut names: Vec<CapName> =
1605                decl.reads.iter().chain(&decl.reads_opt).map(|r| r.name.clone()).collect();
1606            names.sort();
1607            names.dedup();
1608            names
1609        };
1610        let Some(read) = decl.reads.iter().chain(&decl.reads_opt).find(|r| r.name == table.name)
1611        else {
1612            return Err(AccessError::UndeclaredRead {
1613                stage: self.rule_as_stage(),
1614                table: table.name.clone(),
1615                declared: declared(),
1616            });
1617        };
1618        if read.type_id != table.type_id {
1619            return Err(AccessError::TypeMismatch {
1620                stage: self.rule_as_stage(),
1621                table: table.name.clone(),
1622                declared: read.short_type_name(),
1623                requested: table.short_type_name(),
1624            });
1625        }
1626        let Some(entry) = self.registry.table_named(&table.name) else {
1627            // A table no feature of this registry declares: the rule read it
1628            // optionally as a peer table that stayed unresolved, and sees it
1629            // as absent. The plan's stage does not name it either.
1630            return Ok(None);
1631        };
1632        // A value's results are read at that value's addresses only: a read
1633        // at a document address — a region of the document lowered inside a
1634        // value, in any round, which reads by the recorded origin — reads the
1635        // run's store.
1636        let at = self.addr.map(|addr| addr.tree);
1637        for (id, _, scratch) in self.stores.iter().rev() {
1638            if Some(*id) != at {
1639                continue;
1640            }
1641            if let Some(found) = scratch.get_erased(entry.id) {
1642                return Ok(Some(&**found));
1643            }
1644        }
1645        Ok(self.cx.view().get_erased(&table.name)?.map(|found| &**found))
1646    }
1647
1648    fn producer_of(&self, table: &CapName) -> Option<StageName> {
1649        self.cx.view().producer_of(table).cloned()
1650    }
1651
1652    fn option_erased(
1653        &self,
1654        key: OptionKey,
1655    ) -> Result<&(dyn std::any::Any + Send + Sync), OptionError> {
1656        // Outside a rule nothing is declared: refused, like `pres`.
1657        let Some(idx) = self.current else {
1658            return Err(OptionError::UndeclaredRead {
1659                stage: self.rule_as_stage(),
1660                option: key.short_name().to_string(),
1661                declared: Vec::new(),
1662            });
1663        };
1664        let decl = &self.registry.rule(idx).rule.decl;
1665        let declared: Vec<String> =
1666            decl.options.iter().map(|option| option.key().short_name().to_string()).collect();
1667        if !decl.options.iter().any(|option| option.key() == &key) {
1668            return Err(OptionError::UndeclaredRead {
1669                stage: self.rule_as_stage(),
1670                option: key.short_name().to_string(),
1671                declared,
1672            });
1673        }
1674        self.cx.options().get_erased(&key).ok_or_else(|| OptionError::UndeclaredRead {
1675            stage: self.rule_as_stage(),
1676            option: key.short_name().to_string(),
1677            declared,
1678        })
1679    }
1680
1681    fn lower_children(
1682        &mut self,
1683        cx: &mut LowerCx<'_>,
1684        node: &NodeRef<'_, Flm>,
1685    ) -> Result<Vec<BuildId>, LowerError> {
1686        cx.restage_children(*node, self).map_err(|e| self.convert(e))
1687    }
1688
1689    fn lower_body(
1690        &mut self,
1691        cx: &mut LowerCx<'_>,
1692        node: &NodeRef<'_, Flm>,
1693    ) -> Result<Vec<BuildId>, LowerError> {
1694        let body = node.body().ok_or_else(|| {
1695            LowerError::structure(format!("missing body of ‘{}’", element_of(node).name))
1696        })?;
1697        self.lower_slice(cx, Some(body))
1698    }
1699
1700    fn lower_arg(
1701        &mut self,
1702        cx: &mut LowerCx<'_>,
1703        node: &NodeRef<'_, Flm>,
1704        index: usize,
1705    ) -> Result<Vec<BuildId>, LowerError> {
1706        let content = node.argument_content_nodes(index).ok_or_else(|| {
1707            LowerError::structure(format!(
1708                "missing argument {index} of ‘{}’",
1709                element_of(node).name
1710            ))
1711        })?;
1712        self.lower_slice(cx, Some(content))
1713    }
1714
1715    fn lower_arg_named(
1716        &mut self,
1717        cx: &mut LowerCx<'_>,
1718        node: &NodeRef<'_, Flm>,
1719        name: &str,
1720    ) -> Result<Vec<BuildId>, LowerError> {
1721        let content = match node.argument_content_nodes_named(name) {
1722            Ok(Some(content)) => content,
1723            Ok(None) => {
1724                return Err(LowerError::structure(format!(
1725                    "missing argument ‘{name}’ of ‘{}’",
1726                    element_of(node).name
1727                )));
1728            }
1729            Err(error) => return Err(LowerError::structure(error.to_string())),
1730        };
1731        self.lower_slice(cx, Some(content))
1732    }
1733
1734    fn lower_nodes(
1735        &mut self,
1736        cx: &mut LowerCx<'_>,
1737        nodes: NodeSlice<'_, Flm>,
1738    ) -> Result<Vec<BuildId>, LowerError> {
1739        self.lower_slice(cx, Some(nodes))
1740    }
1741
1742    fn default(
1743        &mut self,
1744        cx: &mut LowerCx<'_>,
1745        node: &NodeRef<'_, Flm>,
1746    ) -> Result<Vec<BuildId>, LowerError> {
1747        self.copy(cx, *node)
1748    }
1749
1750    fn pres(
1751        &mut self,
1752        cx: &mut LowerCx<'_>,
1753        element: &ElementName,
1754        payload: Arc<dyn PresPayload>,
1755        body: Vec<BuildId>,
1756    ) -> Result<BuildId, LowerError> {
1757        self.stage_pres(cx, element, payload, vec![(String::from(pres::BODY_SLOT), body)])
1758    }
1759
1760    fn pres_slots(
1761        &mut self,
1762        cx: &mut LowerCx<'_>,
1763        element: &ElementName,
1764        payload: Arc<dyn PresPayload>,
1765        slots: Vec<(String, Vec<BuildId>)>,
1766    ) -> Result<BuildId, LowerError> {
1767        self.stage_pres(cx, element, payload, slots)
1768    }
1769
1770    fn text(&mut self, cx: &mut LowerCx<'_>, text: &str) -> Result<BuildId, LowerError> {
1771        let text_element = ElementName::from(crate::lang::structural::TEXT);
1772        if let Some(idx) = self.current {
1773            let rule = &self.registry.rule(idx).rule;
1774            if !self.native.contains(&text_element) && !rule.decl.produces.contains(&text_element) {
1775                return Err(LowerError::UndeclaredProduces {
1776                    rule: rule.name.clone(),
1777                    element: text_element,
1778                    declared: rule.decl.produces.clone(),
1779                });
1780            }
1781        }
1782        let source = self.synth_source()?;
1783        let (_, state) = self.trigger()?;
1784        let state = Arc::clone(state);
1785        let kind = NodeKind::chars(text);
1786        let span = SourceSpan::new(&source, 0..0);
1787        let builder = cx.builder();
1788        let ext = Flm::make_node_ext(&kind, &span, &state, builder.staged_children(&[]))
1789            .map_err(|e| LowerError::Build { detail: e.to_string() })?;
1790        let id = builder
1791            .add(kind, span, state, Vec::new(), ext, ())
1792            .map_err(|e| LowerError::Build { detail: e.to_string() })?;
1793        Ok(self.record(id))
1794    }
1795
1796    fn splice(
1797        &mut self,
1798        cx: &mut LowerCx<'_>,
1799        value: &Arc<NodeTree<Flm>>,
1800    ) -> Result<Vec<BuildId>, LowerError> {
1801        // Every diagnostic raised while the value is brought up to date and
1802        // lowered names the node it is shown at, the one being lowered.
1803        let (shown_at, _) = self.trigger()?;
1804        self.shown_at.push(shown_at.clone());
1805        let result = self.splice_shown(cx, value);
1806        self.shown_at.pop();
1807        result
1808    }
1809
1810    fn lower_region(
1811        &mut self,
1812        cx: &mut LowerCx<'_>,
1813        at: NodeAddr,
1814        region: NodeRegion,
1815        shape: &mut RegionShape<'_>,
1816    ) -> Result<Vec<BuildId>, LowerError> {
1817        let not_found = |detail: String| LowerError::RegionNotFound { detail };
1818        let tree = self
1819            .reachable_tree(at.tree)
1820            .ok_or_else(|| not_found(format!("missing tree ‘{}’", at.tree)))?;
1821        let node = tree.get(at.node).ok_or_else(|| {
1822            not_found(format!(
1823                "missing node {} in tree ‘{}’",
1824                at.node.index(),
1825                at.tree
1826            ))
1827        })?;
1828        let content = region.content_nodes(&node).ok_or_else(|| {
1829            not_found(format!(
1830                "missing {region} in node {} of tree ‘{}’ (element ‘{}’)",
1831                at.node.index(),
1832                at.tree,
1833                element_of(&node).name
1834            ))
1835        })?;
1836        // The pointed node is the one whose content is being lowered: until a
1837        // visit sets its own, the address and the origin are the node's.
1838        self.entered.push((at.tree, Arc::clone(&tree)));
1839        let saved_mode = std::mem::replace(&mut self.mode, Mode::Pointed(at.tree));
1840        let saved_addr = self.addr.replace(at);
1841        let saved_origin = self.origin.replace(at);
1842        let result = shape(cx, self, &node, &content);
1843        self.mode = saved_mode;
1844        self.addr = saved_addr;
1845        self.origin = saved_origin;
1846        self.entered.pop();
1847        result
1848    }
1849
1850    fn require(&mut self, id: &Name) {
1851        self.requires.insert(id.clone());
1852    }
1853
1854    fn diagnose(&mut self, diagnostic: FlmDiagnostic) {
1855        self.report(diagnostic);
1856    }
1857}
1858
1859#[cfg(test)]
1860mod tests {
1861    use super::*;
1862
1863    #[test]
1864    fn the_driver_rule_name_is_in_the_lowering_namespace() {
1865        assert!(DRIVER_RULE.starts_with("flm.lowering."));
1866    }
1867}