Skip to main content

flm_core/core/
lowering.rs

1//! Lowering rules: what a lowering rule is, what it declares, and the
2//! interface through which it builds the presentation of one element for one
3//! backend.
4//!
5//! Lowering rewrites each frozen tree into a presentation tree for one
6//! backend, by applying the lowering rule selected for each element, in
7//! rounds, until only elements the backend writes natively remain; the result
8//! is computed data in the table `flm.lowered.<backend>` ([backends, lowering,
9//! and outputs](crate::guide::concepts_overview#backends-lowering-and-outputs)).
10//! A lowering rule is a named registry entity written for one element: it
11//! declares what it requires, reads and produces, and implements [`Lower`],
12//! which stages the element's presentation for one backend ([`LoweringRule`]).
13//! To *stage* a node is to build it into the tree that the rule is producing
14//! ([`Lowerer`] defines the term).
15//!
16//! This module defines what a rule is and what it may do. A feature registers
17//! a rule with
18//! [`FeatureBuilder::lowering_rule`](crate::core::registry::FeatureBuilder::lowering_rule).
19//! The lowering stage that calls the rules, the lowering driver that
20//! implements [`Lowerer`], and the presentation elements the rules build
21//! are in [`crate::stdlib::backends::lowering`] and
22//! [`crate::stdlib::backends::pres`].
23//!
24//! The items of this module:
25//!
26//! - [`Lower`], the trait a rule author implements, and [`Lowering`], what it
27//!   returns for one node;
28//! - [`LoweringDecl`], what a rule declares; [`DefaultMark`], on which
29//!   backends the rule is chosen by default; and [`LoweringRule`], the
30//!   registry entity that carries both together with the implementation;
31//! - [`Lowerer`], the interface a rule works through, and [`LowerCx`], the
32//!   tree under construction into which the rule stages nodes;
33//! - [`NodeRegion`] and [`RegionShape`], with which a rule lowers an argument
34//!   or a content slot of a node of another tree ([`Lowerer::lower_region`]);
35//! - [`LowerError`], the failure of a rule at one node;
36//! - [`chars_at_lowering`] and [`spelling_at_lowering`], the two ways a rule
37//!   reads content that may hold a placeholder of a user definition's
38//!   template: as characters, or as written.
39//!
40//! # How a rule is called
41//!
42//! A rule is written for one element. When a backend's lowering stage reaches
43//! a node of that element, and the plan selected the rule for that element on
44//! that backend, the stage calls [`Lower::lower`] with the frozen node. The
45//! rule returns either [`Lowering::Default`] (copy this node and lower its
46//! children) or [`Lowering::Emit`] with the nodes it built to replace the
47//! node. The rule builds nodes through two values it is handed: the
48//! [`Lowerer`], which lowers parts of the tree and builds presentation nodes,
49//! and the [`LowerCx`], the tree under construction. Every [`Lowerer`] method
50//! that builds something takes the [`LowerCx`] as an argument, because the
51//! [`Lowerer`] cannot hold it: its own operations lower parts of the node, which
52//! needs the same context, so the two are borrowed separately.
53//!
54//! # What a rule declares
55//!
56//! Plan construction reads a rule's [`LoweringDecl`] before any rule runs, and
57//! uses each part as follows:
58//!
59//! - `requires`, `reads`, `reads_opt` and `options` are added to the needs of
60//!   its backend's lowering stage; a rule that reads the table of resolved
61//!   references therefore causes the stage that writes that table to be
62//!   scheduled;
63//! - `produces` lists every presentation element the rule may build. Plan
64//!   construction follows these lists to check that the backend can, in the
65//!   end, write every element a document may contain, and the [`Lowerer`]
66//!   refuses to build an element the rule did not list;
67//! - `selection_requires` lists the requirements (identifiers of definitions
68//!   that the output needs, [`StyleDef`](crate::core::registry::StyleDef))
69//!   that the rule has merely because it was selected, whether or not it ever
70//!   runs;
71//! - `unchecked_output` lists the backends on which the rule writes output
72//!   that nothing checks before the program reading the output does; a plan
73//!   that selects the rule on such a backend keeps a
74//!   [`PlanWarning::UncheckedOutput`](crate::core::plan::PlanWarning::UncheckedOutput),
75//!   one per backend and feature, which every run of the plan reports as the
76//!   Warning `flm.run.unchecked-output`. The declaration is fixed when the
77//!   rule is registered, so the warning depends on the plan alone, not on a
78//!   document. The feature that registers a rule owns it: a rule of the
79//!   library registered by another feature under its own name
80//!   ([`math_rule_named`](crate::math_passthrough::math_rule_named)) keeps its
81//!   declaration, and the warning names that feature.
82//!
83//! # Which rule is chosen
84//!
85//! Several rules may target one element: the rule of the feature that
86//! declares the element, and a more specific one written for a particular backend. The plan
87//! chooses one rule per backend and element, in a fixed order: a rule the
88//! plan request prefers by name; otherwise no rule, if the backend writes the
89//! element natively; otherwise the rule marked [`DefaultMark::OnBackends`] for
90//! that backend; then the rule marked [`DefaultMark::Everywhere`]; then the
91//! only candidate, if there is exactly one. Several candidates and nothing to
92//! choose between them is a plan error that lists the candidates. See
93//! [`SelectedRules`](crate::core::plan::SelectedRules) for the rule selection
94//! order in full.
95
96use std::any::Any;
97use std::fmt;
98use std::sync::Arc;
99
100use techy::core::node::{BuildId, NodeRef, NodeSlice, NodeTree};
101use techy::error::{Diagnostic, DiagnosticInfo};
102use techy::transform::RestageContext;
103
104use crate::model::addr::{NodeAddr, TreeId};
105use crate::model::doc::FragmentLayout;
106use crate::model::names::{BackendName, CapName, ElementName, Name, RuleName, StageName};
107use crate::model::options::{DataValue, OptionError, OptionKey, OptionRef, Options};
108use serde_json::Value;
109use crate::core::data::store::AccessError;
110use crate::core::data::table::{TableKey, TableRef};
111use crate::lang::text::{NotCharacters, read_chars};
112use crate::lang::{BuiltLang, Flm, FlmCallableType, FlmDiagnostic, FlmSpan, PresPayload};
113
114/// The presentation tree under construction, into which a lowering rule
115/// stages nodes: techy's restaging context over the FLM language.
116///
117/// Every [`Lowerer`] method that builds something takes this context, and the
118/// [`BuildId`] values it returns are positions in it. Both type parameters
119/// after the language are the unit type, because FLM's trees carry no
120/// per-node annotation in the frozen tree or in the presentation tree.
121///
122/// A rule receives this context from the lowering stage and never creates
123/// one.
124pub type LowerCx<'a> = RestageContext<'a, Flm, (), ()>;
125
126/// What a lowering rule returns for one node: copy it, or replace it.
127///
128/// [`Lower::lower`] returns it.
129#[derive(Debug)]
130pub enum Lowering {
131    /// Copy this node into the presentation tree unchanged, and lower its
132    /// children.
133    ///
134    /// Return it for an element the backend writes natively. For an element
135    /// the backend does not write natively, the copied node is lowered again
136    /// in the next round by the same rule, until the tree exceeds the number
137    /// of rounds allowed and fails with `flm.lowering.rounds-exceeded`.
138    Default,
139    /// The nodes the rule built to replace this node, in their order among
140    /// its siblings. An empty list removes the node.
141    Emit(Vec<BuildId>),
142}
143
144/// What a lowering rule declares about itself: what it needs, what it may
145/// build, and what it requires merely by being selected.
146///
147/// Plan construction reads the declaration instead of calling the rule, so a
148/// rule takes part in ordering and scheduling before it has run; see the
149/// [module documentation](self#what-a-rule-declares) for what each part is
150/// used for.
151///
152/// Build one with [`LoweringDecl::new`] and the methods that take and return
153/// it, and pass it to [`LoweringRule::new`].
154///
155/// # Examples
156///
157/// ```
158/// use flm_core::core::lowering::LoweringDecl;
159///
160/// let decl = LoweringDecl::new()
161///     .requires("flm.refs.resolved")
162///     .produces("flm.pres.link")
163///     .produces("flm.text");
164///
165/// assert_eq!(decl.requires.len(), 1);
166/// assert_eq!(decl.produces.len(), 2);
167/// ```
168#[derive(Debug, Clone, Default)]
169pub struct LoweringDecl {
170    /// The capabilities the rule requires, which its backend's lowering stage
171    /// then also requires.
172    pub requires: Vec<CapName>,
173    /// The tables the rule reads. Reading a table also requires that table's
174    /// capability, so the plan schedules a stage that writes it.
175    pub reads: Vec<TableRef>,
176    /// The tables the rule reads if the run holds them. With such a read, the
177    /// rule states that it can do its work without the feature that owns the
178    /// table.
179    ///
180    /// The backend's lowering stage turns such a read into a *required* read
181    /// whenever the registry declares the table and some stage writes it, so
182    /// that the stage writing it is scheduled and the rule finds the values.
183    /// For a table that no stage writes (an [external
184    /// table](crate::core::run::Externals), which the caller installs when a
185    /// run is constructed), it stays an optional read. For a table that no
186    /// feature of the registry declares (a [peer
187    /// declaration](crate::core::registry::PeerName) that resolved to
188    /// nothing), it is left out of the stage's needs. In both of these cases
189    /// the rule reads the table when the run holds it, and reads `None`
190    /// otherwise.
191    pub reads_opt: Vec<TableRef>,
192    /// The option types the rule reads. A read of an option type the rule did
193    /// not declare here returns [`LowerError::Option`].
194    pub options: Vec<OptionRef>,
195    /// Every presentation element the rule may build. Building a node of an
196    /// element that is not listed here returns
197    /// [`LowerError::UndeclaredProduces`]; the only exception is a text node
198    /// ([`Lowerer::text`]) on a backend that writes text natively.
199    pub produces: Vec<ElementName>,
200    /// The requirements the rule records whenever it is selected, whether or
201    /// not it ever runs at a node: identifiers of definitions that the output
202    /// needs, such as a style definition on HTML
203    /// ([`StyleDef`](crate::core::registry::StyleDef)). For a requirement
204    /// recorded because of one particular node, see [`Lowerer::require`].
205    pub selection_requires: Vec<Name>,
206    /// The backends on which what the rule writes is checked by nothing that
207    /// reads the output after FLM, each with what is written and what reads
208    /// it ([`UncheckedOutputDecl`]). A plan that selects the rule on one of
209    /// these backends keeps one
210    /// [`PlanWarning::UncheckedOutput`](crate::core::plan::PlanWarning::UncheckedOutput)
211    /// per backend and feature.
212    pub unchecked_output: Vec<UncheckedOutputDecl>,
213}
214
215/// One backend on which a lowering rule writes output that nothing checks
216/// before the program reading that output does
217/// ([`LoweringDecl::unchecked_output`]).
218///
219/// The two texts complete the warning's message, which reads "Unchecked
220/// output for *reader*: feature ‘…’ writes *written* as is (backend ‘…’)":
221/// `written` is a noun phrase for what the rule writes ("each formula's
222/// LaTeX source"), and `reader` a noun phrase for what reads it ("LuaLaTeX",
223/// "the formula renderer in the reader's browser").
224///
225/// # Examples
226///
227/// ```
228/// use flm_core::core::lowering::LoweringDecl;
229///
230/// let decl = LoweringDecl::new().unchecked_output(
231///     "latex-rendered",
232///     "each formula's LaTeX source",
233///     "LuaLaTeX",
234/// );
235///
236/// assert_eq!(decl.unchecked_output[0].backend.as_str(), "latex-rendered");
237/// ```
238#[derive(Debug, Clone, PartialEq, Eq)]
239pub struct UncheckedOutputDecl {
240    /// The backend whose output holds what the rule writes.
241    pub backend: BackendName,
242    /// What the rule writes, as a noun phrase.
243    pub written: String,
244    /// What reads the output, as a noun phrase.
245    pub reader: String,
246}
247
248impl LoweringDecl {
249    /// Returns a declaration that needs nothing, produces nothing and records
250    /// no requirement.
251    pub fn new() -> LoweringDecl {
252        LoweringDecl::default()
253    }
254
255    /// Adds a required capability, and returns the declaration.
256    pub fn requires(mut self, capability: impl Into<CapName>) -> LoweringDecl {
257        self.requires.push(capability.into());
258        self
259    }
260
261    /// Adds a table the rule reads, which also requires that table's
262    /// capability, and returns the declaration.
263    pub fn reads(mut self, table: impl TableKey) -> LoweringDecl {
264        self.reads.push(table.table_ref());
265        self
266    }
267
268    /// Adds a table the rule reads if the run holds it, and returns the
269    /// declaration. The rule then works without the feature that owns the
270    /// table, and the stage writing the table is still scheduled wherever the
271    /// registry has one, as [`reads_opt`](LoweringDecl::reads_opt) describes.
272    pub fn reads_opt(mut self, table: impl TableKey) -> LoweringDecl {
273        self.reads_opt.push(table.table_ref());
274        self
275    }
276
277    /// Adds the option type `T` to the option types the rule reads, and
278    /// returns the declaration.
279    pub fn option<T: Options>(mut self) -> LoweringDecl {
280        self.options.push(OptionRef::of::<T>());
281        self
282    }
283
284    /// Adds the option type declared from data under the name `name` to the
285    /// option types the rule reads, and returns the declaration. The rule reads
286    /// it with `option_named`, defined on `dyn Lowerer`.
287    pub fn option_named(mut self, name: impl Into<Name>) -> LoweringDecl {
288        self.options.push(OptionRef::named(name));
289        self
290    }
291
292    /// Adds a presentation element the rule may build, and returns the
293    /// declaration.
294    pub fn produces(mut self, element: impl Into<ElementName>) -> LoweringDecl {
295        self.produces.push(element.into());
296        self
297    }
298
299    /// Adds a requirement the rule records whenever it is selected (see
300    /// [`selection_requires`](LoweringDecl::selection_requires)), and returns
301    /// the declaration.
302    pub fn selection_requires(mut self, id: impl Into<Name>) -> LoweringDecl {
303        self.selection_requires.push(id.into());
304        self
305    }
306
307    /// Adds a backend on which what the rule writes is checked by nothing
308    /// that reads the output after FLM, with what is written and what reads
309    /// it (see [`unchecked_output`](LoweringDecl::unchecked_output)), and
310    /// returns the declaration.
311    pub fn unchecked_output(
312        mut self,
313        backend: impl Into<BackendName>,
314        written: impl Into<String>,
315        reader: impl Into<String>,
316    ) -> LoweringDecl {
317        self.unchecked_output.push(UncheckedOutputDecl {
318            backend: backend.into(),
319            written: written.into(),
320            reader: reader.into(),
321        });
322        self
323    }
324}
325
326/// The default mark of a lowering rule: on which backends the rule is chosen
327/// for its element when the plan request does not prefer a rule by name.
328///
329/// The plan reads the mark after the plan request's preferences and before
330/// the case of a single candidate; see the [module
331/// documentation](self#which-rule-is-chosen) for the whole order. Usually the
332/// rule of the feature that declares the element is marked
333/// [`Everywhere`](DefaultMark::Everywhere), a rule written for one backend is
334/// marked [`OnBackends`](DefaultMark::OnBackends) with that backend, and an
335/// alternative that a caller must ask for by name is marked
336/// [`Never`](DefaultMark::Never).
337#[derive(Debug, Clone, PartialEq, Eq)]
338pub enum DefaultMark {
339    /// The element's default rule on every backend.
340    Everywhere,
341    /// The default on the listed backends only, ranked above a rule marked
342    /// [`Everywhere`](DefaultMark::Everywhere), and **never a candidate on any
343    /// other backend**: not as the only rule for its element, and not when a
344    /// plan request prefers it by name. The mark states where the rule
345    /// belongs, because a rule written for one backend stages that backend's
346    /// own elements.
347    OnBackends(Vec<BackendName>),
348    /// Never a default: chosen only when the plan request prefers it by name,
349    /// or when it is the element's only rule. The mark restricts precedence
350    /// and not place, so such a rule is a candidate on every backend.
351    Never,
352}
353
354impl DefaultMark {
355    /// Returns whether the mark is [`Everywhere`](DefaultMark::Everywhere):
356    /// the rule is the default on every backend.
357    pub fn is_general(&self) -> bool {
358        matches!(self, DefaultMark::Everywhere)
359    }
360
361    /// Returns whether the mark is [`OnBackends`](DefaultMark::OnBackends)
362    /// and lists `backend`.
363    pub fn is_specific_to(&self, backend: &BackendName) -> bool {
364        match self {
365            DefaultMark::OnBackends(backends) => backends.contains(backend),
366            _ => false,
367        }
368    }
369
370    /// Returns whether a rule with this mark may be chosen on `backend` at
371    /// all.
372    ///
373    /// [`OnBackends`](DefaultMark::OnBackends) states *where* the rule
374    /// belongs, not merely where it ranks first: a rule marked for listed
375    /// backends is never a candidate on another backend, not even as the
376    /// element's only rule and not even when a plan request prefers it by
377    /// name. A rule written for one backend produces that backend's own
378    /// elements, which are wrong on any other backend.
379    /// [`Never`](DefaultMark::Never) restricts precedence and not place, so
380    /// such a rule may be chosen on every backend as the only candidate.
381    pub fn takes_part_on(&self, backend: &BackendName) -> bool {
382        match self {
383            DefaultMark::OnBackends(backends) => backends.contains(backend),
384            DefaultMark::Everywhere | DefaultMark::Never => true,
385        }
386    }
387}
388
389/// A lowering rule: a named registry entity written for one element, which
390/// declares what it requires, reads and produces, and implements [`Lower`],
391/// which stages the element's presentation for one backend.
392///
393/// The value holds the rule's name, the element it lowers, its declaration,
394/// its implementation and its default mark. A feature registers it with
395/// [`FeatureBuilder::lowering_rule`](crate::core::registry::FeatureBuilder::lowering_rule).
396/// Rule names are dotted, and no two rules of a registry have the same name;
397/// a plan request that prefers a rule refers to it by this name. The standard
398/// features name a rule `<element>.lower.<variant>`, such as
399/// `flm.cells.cell.lower.default` or `flm.parbreak.lower.latex-recomposed`.
400#[derive(Clone)]
401pub struct LoweringRule {
402    /// The rule's name, which no other rule of the registry has.
403    pub name: RuleName,
404    /// The element whose nodes this rule lowers.
405    pub element: ElementName,
406    /// What the rule declares that it needs and may build.
407    pub decl: LoweringDecl,
408    /// The implementation that the lowering stage calls.
409    pub rule: Arc<dyn Lower>,
410    /// On which backends the rule is chosen when no rule is preferred by
411    /// name.
412    pub default: DefaultMark,
413    /// A one-line description of the rule for a person reading the registry.
414    pub docs: String,
415}
416
417impl LoweringRule {
418    /// Returns the rule `name`, which lowers `element` through `rule`, with
419    /// the declaration `decl`, the default mark `default` and no description.
420    pub fn new(
421        name: impl Into<RuleName>,
422        element: impl Into<ElementName>,
423        decl: LoweringDecl,
424        rule: Arc<dyn Lower>,
425        default: DefaultMark,
426    ) -> LoweringRule {
427        LoweringRule {
428            name: name.into(),
429            element: element.into(),
430            decl,
431            rule,
432            default,
433            docs: String::new(),
434        }
435    }
436
437    /// Sets the rule's one-line description, and returns the rule.
438    pub fn docs(mut self, docs: impl Into<String>) -> LoweringRule {
439        self.docs = crate::kept_docs(docs);
440        self
441    }
442}
443
444impl fmt::Debug for LoweringRule {
445    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
446        f.debug_struct("LoweringRule")
447            .field("name", &self.name)
448            .field("element", &self.element)
449            .field("decl", &self.decl)
450            .field("default", &self.default)
451            .finish()
452    }
453}
454
455/// The failure of a lowering rule at one node.
456///
457/// A rule returns this error from [`Lower::lower`], and every [`Lowerer`]
458/// method that can refuse something returns it too. The lowering stage
459/// handles it according to the variant
460/// ([`crate::stdlib::backends::lowering::error`] lists the conditions):
461///
462/// - Most variants fail the node only. The stage reports one Error diagnostic
463///   at the node, `flm.lowering.rule-failed`, whose message includes this
464///   error's text; [`RegionNotFound`](LowerError::RegionNotFound) is reported
465///   as `flm.lowering.region-not-found` instead, and
466///   [`Refused`](LowerError::Refused) reports the rule's own diagnostic. The
467///   node then lowers to a childless `flm.pres.unsupported` stand-in, as an
468///   element the backend cannot render does, and the rest of the tree lowers
469///   normally.
470/// - [`Build`](LowerError::Build) fails the lowering of the whole tree, with
471///   one `flm.lowering.failed` diagnostic; the tree then has no lowered form.
472/// - [`PlaceholderCharacters`](LowerError::PlaceholderCharacters) is not a
473///   failure of the node and is not reported: it is passed on to the rule that
474///   spliced the template it arose in.
475///
476/// A rule must return every error the [`Lowerer`] gives it, rather than
477/// continue: after a refused call the [`Lowerer`] has staged nothing, and a
478/// rule that continues as though it had breaks an invariant of the lowering.
479#[derive(Debug, Clone)]
480pub enum LowerError {
481    /// The rule read a table it did not declare, or read a table as the
482    /// wrong value type.
483    ///
484    /// The error is the store's own ([`AccessError`]), shared with stages; its
485    /// `stage` field holds the rule's name.
486    Access(AccessError),
487    /// The rule read an option type it did not declare. The error's `stage`
488    /// field holds the rule's name.
489    Option(OptionError),
490    /// The rule tried to build a node of an element that its declaration's
491    /// [`produces`](LoweringDecl::produces) does not list.
492    UndeclaredProduces {
493        /// The rule that tried.
494        rule: RuleName,
495        /// The element of the node it tried to build.
496        element: ElementName,
497        /// The elements the rule's declaration lists.
498        declared: Vec<ElementName>,
499    },
500    /// The node, or the nodes a rule passed to a [`Lowerer`] method, do not
501    /// have the structure the rule or the method requires: for example, a
502    /// node without the payload its element always carries, an argument that
503    /// is absent, or nodes of another tree.
504    Structure {
505        /// What was found, as a phrase that completes the error's message.
506        detail: String,
507    },
508    /// Building a node failed inside the parser toolkit (techy). The rule
509    /// cannot recover from it, and the lowering of the whole tree fails.
510    Build {
511        /// The toolkit's own text for the failure.
512        detail: String,
513    },
514    /// A synthesized value could not be brought up to date ([value
515    /// catch-up](crate::guide::concepts_overview#value-catch-up)), so it could
516    /// not be spliced; see [`Lowerer::splice`].
517    CatchUp {
518        /// The text of the failure.
519        detail: String,
520    },
521    /// Bringing a synthesized value up to date was refused because a stage,
522    /// run again over it, stated a fact about the document as a whole, such as
523    /// a label, which a synthesized value must not do; see [`Lowerer::splice`]
524    /// and [value catch-up](crate::guide::concepts_overview#value-catch-up).
525    ///
526    /// It is a variant of its own, rather than a
527    /// [`CatchUp`](LowerError::CatchUp) failure, so that a rule splicing a
528    /// value it built from what an author wrote can tell the author what to
529    /// change. The user-definitions feature does so for a kept definition
530    /// whose template declares a reference point
531    /// ([`KeptTemplateDeclaresPoint`](crate::stdlib::features::userdefs::kept::KeptTemplateDeclaresPoint)).
532    /// A rule that returns this error unchanged gets
533    /// `flm.lowering.rule-failed`, as for any other failure.
534    DocumentFactInValue {
535        /// The stage that stated the fact.
536        stage: StageName,
537        /// The table in which the fact was stated.
538        table: CapName,
539    },
540    /// The rule refuses the node for the reason that the carried diagnostic
541    /// states, in terms the author can act on.
542    ///
543    /// The lowering stage reports that diagnostic instead of
544    /// `flm.lowering.rule-failed`, and lowers the node to the same stand-in as
545    /// for any other failure. It does so at every node the rule refuses: a
546    /// refusal about something every use shares, such as a user definition,
547    /// is reported at each use.
548    Refused(Box<FlmDiagnostic>),
549    /// The node region that [`Lowerer::lower_region`] was asked to lower does
550    /// not exist: no tree of that identifier is reachable, the tree holds no
551    /// node at that address, or the node has no argument or content slot at
552    /// that position.
553    ///
554    /// The lowering stage reports it at the node whose rule asked, under a
555    /// condition of its own (`flm.lowering.region-not-found`) rather than as a
556    /// rule failure, and that node lowers to the same stand-in as for a rule
557    /// failure.
558    RegionNotFound {
559        /// The text saying what could not be found.
560        detail: String,
561    },
562    /// The rule needs the **characters** of some content (an address, a
563    /// reference key, verbatim content, or anything computed from them), and
564    /// the content holds a placeholder of a user definition's template, whose
565    /// characters are not known yet. A rule obtains characters through
566    /// [`chars_at_lowering`], which returns this error for it; a rule that
567    /// computes on the content as written rather than on its characters gets
568    /// it from [`spelling_at_lowering`].
569    ///
570    /// Only a template lowered unexpanded, placeholders included, holds a
571    /// placeholder. The recomposed LaTeX lowers the template of a kept
572    /// definition this way, once, to write it as a LaTeX definition in which
573    /// each placeholder is a parameter that LaTeX replaces at every call. A
574    /// parameter may be placed where the template typesets content, but not
575    /// where a rule needs characters, since those are known only at a call. So
576    /// the rule returns this error, and the lowering passes it on, unreported,
577    /// from rule to rule up to the rule that spliced the template, which acts
578    /// on it. The user-definitions feature then expands every use site of that
579    /// definition instead of writing a call. The lists feature, whose
580    /// recomposed LaTeX lowers a list's own label template with its number
581    /// formats written as placeholders, reports a number format placed where
582    /// characters are read. Wherever a template was expanded (on every other
583    /// output, and at every expanded use site), no placeholder of a user
584    /// definition remains, and this error does not occur.
585    ///
586    /// An error of this variant that reaches the lowering of a whole tree
587    /// fails that tree.
588    PlaceholderCharacters,
589    /// Any other failure the rule reports.
590    Other {
591        /// The text of the failure.
592        detail: String,
593    },
594}
595
596impl LowerError {
597    /// Returns a [`Structure`](LowerError::Structure) error: the nodes do not
598    /// have the structure required; `detail` says what was found.
599    pub fn structure(detail: impl Into<String>) -> LowerError {
600        LowerError::Structure { detail: detail.into() }
601    }
602
603    /// Returns an [`Other`](LowerError::Other) error described by `detail`.
604    pub fn other(detail: impl Into<String>) -> LowerError {
605        LowerError::Other { detail: detail.into() }
606    }
607}
608
609impl From<AccessError> for LowerError {
610    fn from(error: AccessError) -> LowerError {
611        LowerError::Access(error)
612    }
613}
614
615impl From<OptionError> for LowerError {
616    fn from(error: OptionError) -> LowerError {
617        LowerError::Option(error)
618    }
619}
620
621impl fmt::Display for LowerError {
622    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
623        match self {
624            LowerError::Access(error) => fmt::Display::fmt(error, f),
625            LowerError::Option(error) => fmt::Display::fmt(error, f),
626            LowerError::UndeclaredProduces { rule, element, declared } => write!(
627                f,
628                "rule `{rule}` builds a node of `{element}`, so it must list `{element}` among \
629                 the elements it produces; it lists: [{}]",
630                declared.iter().map(|e| e.as_str()).collect::<Vec<_>>().join(", ")
631            ),
632            LowerError::Structure { detail } => {
633                write!(
634                    f,
635                    "the content does not have the structure that lowering it requires: {detail}"
636                )
637            }
638            LowerError::Build { detail } => write!(f, "a node could not be built: {detail}"),
639            LowerError::CatchUp { detail } => {
640                write!(f, "content generated during processing could not be prepared: {detail}")
641            }
642            LowerError::DocumentFactInValue { stage, table } => write!(
643                f,
644                "content generated during processing must not state a fact about the whole \
645                 document, such as a label, but stage `{stage}` stated one in `{table}` when it \
646                 ran over that content"
647            ),
648            LowerError::Refused(diagnostic) => f.write_str(&diagnostic.message()),
649            LowerError::RegionNotFound { detail } => {
650                write!(f, "the argument or content slot to lower does not exist: {detail}")
651            }
652            LowerError::PlaceholderCharacters => f.write_str(
653                "a placeholder of a definition's template must not appear where the characters \
654                 of the content are read (such as an address or a reference key): its \
655                 characters are known only once the template is expanded",
656            ),
657            LowerError::Other { detail } => f.write_str(detail),
658        }
659    }
660}
661
662impl std::error::Error for LowerError {}
663
664/// Returns the characters of the run of nodes `nodes`, for a lowering rule
665/// that needs characters (an address, a reference key, verbatim content, a
666/// word) while lowering.
667///
668/// This is the only way a rule reads characters at lowering, and it relies on
669/// the only reader of content as characters ([`read_chars`]). The result is
670/// one of three:
671///
672/// - `Ok(Ok(text))`, the characters, when the content holds nothing but text,
673///   comments and groups other than mathematics;
674/// - `Ok(Err(NotCharacters))`, when the content holds a macro, an
675///   environment, a special character sequence or mathematics, which has no
676///   characters to give; the rule reports this in terms of its own and
677///   recovers;
678/// - `Err(`[`LowerError::PlaceholderCharacters`]`)`, when the content is
679///   characters and placeholders of a user definition's template, whose
680///   characters are not known until the template is expanded. The rule
681///   returns the error unchanged (`?`), and the rule that spliced the template
682///   acts on it (see [`LowerError::PlaceholderCharacters`]). Only a template
683///   lowered unexpanded holds a placeholder (the recomposed LaTeX of a kept
684///   definition, or of a list's own label template), so on every other path
685///   this result does not occur.
686///
687/// Content that holds both a placeholder and something that is not characters
688/// gives `Ok(Err(NotCharacters))`, since no argument of a call could make it
689/// characters.
690///
691/// # Errors
692///
693/// [`LowerError::PlaceholderCharacters`] as above.
694pub fn chars_at_lowering<'t>(
695    nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>,
696) -> Result<Result<String, NotCharacters>, LowerError> {
697    match read_chars(nodes) {
698        Ok(read) => read.text().map(Ok).ok_or(LowerError::PlaceholderCharacters),
699        Err(not) => Ok(Err(not)),
700    }
701}
702
703/// Checks whether a lowering rule may compute on the **spelling** of the run
704/// of nodes `nodes` while lowering, that is, on the content as written, markup
705/// included, rather than on its characters ([`chars_at_lowering`]). Returns
706/// `Ok(())` when no placeholder of a user definition's template occurs in the
707/// content, at any depth, and [`LowerError::PlaceholderCharacters`] when one
708/// does.
709///
710/// A rule that derives something from content as written cannot use
711/// [`chars_at_lowering`], which returns "not characters" for content holding a
712/// macro and so would not report the placeholder. Two examples: a defined
713/// term's label derived from the term (`\term[\emph{#1} chain]{it}`, whose
714/// target is computed from `\emph{…} chain`), and a list's number template
715/// read from the value of `label=`. The spelling of a placeholder is not the
716/// argument a call supplies, so what the rule would compute from it is known
717/// only at a call, wherever in the content the placeholder occurs: inside a
718/// group, in a macro's argument, anywhere. The rule returns the error
719/// unchanged (`?`) before it computes, and the rule that spliced the template
720/// acts on it as for [`chars_at_lowering`]. On every path where the template
721/// was expanded, no placeholder remains and the result is `Ok(())`.
722///
723/// # Errors
724///
725/// [`LowerError::PlaceholderCharacters`] as above.
726pub fn spelling_at_lowering<'t>(
727    nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>,
728) -> Result<(), LowerError> {
729    let placeholder = |node: NodeRef<'t, Flm>| node.callable_type() == Some(FlmCallableType::Placeholder);
730    let holds = nodes
731        .into_iter()
732        .any(|node| placeholder(node) || node.descendants().any(placeholder));
733    if holds { Err(LowerError::PlaceholderCharacters) } else { Ok(()) }
734}
735
736/// A node region: one argument or one content slot of a node, given by
737/// position, which a rule passes, with the node's address, to
738/// [`Lowerer::lower_region`] to have that region's content lowered.
739///
740/// A node's children are divided into node regions: one per argument the
741/// node's element declares, and one per content slot (a node slot in techy's
742/// sense, `ParsedSlot`: a part of a node's content outside its arguments; the
743/// body is one). Positions count from zero in the order in
744/// which the element declares them. An argument's position counts the
745/// optional arguments an author left out, so a position designates the same
746/// argument in every node of one element. [`NodeRegion::argument_named`] finds
747/// an argument's position from its name.
748#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
749pub enum NodeRegion {
750    /// The argument at this position.
751    Argument(usize),
752    /// The content slot at this position.
753    Slot(usize),
754}
755
756impl NodeRegion {
757    /// Returns the node region of `node`'s argument named `name`, or `None`
758    /// when `node`'s element declares no argument of that name.
759    pub fn argument_named(node: &NodeRef<'_, Flm>, name: &str) -> Option<NodeRegion> {
760        node.arguments()?
761            .iter()
762            .position(|argument| argument.name() == Some(name))
763            .map(NodeRegion::Argument)
764    }
765
766    /// Returns the content nodes of this node region of `node`, in the order
767    /// in which they are written: the argument's or the slot's content
768    /// without its delimiters, comments and whitespace included. An argument
769    /// that is absent ([`NodeRegion::is_absent`]) has no content, and the
770    /// result is empty.
771    ///
772    /// Returns `None` when `node` has no argument or no slot at this position.
773    pub fn content_nodes<'t>(&self, node: &NodeRef<'t, Flm>) -> Option<Vec<NodeRef<'t, Flm>>> {
774        match *self {
775            NodeRegion::Argument(index) => {
776                if index >= node.arguments()?.len() {
777                    return None;
778                }
779                let content = node.argument_content_nodes(index);
780                Some(content.map(|nodes| nodes.iter().collect()).unwrap_or_default())
781            }
782            NodeRegion::Slot(index) => Some(node.slot_content_nodes(index)?.iter().collect()),
783        }
784    }
785
786    /// Returns whether this node region is an argument of `node` that is
787    /// absent from the source: an optional argument the author left out, or a
788    /// mandatory one that the parser left out after reporting it. An argument
789    /// written with nothing in it is not absent. A content slot is never absent,
790    /// and neither is a node region that `node` does not have.
791    pub fn is_absent(&self, node: &NodeRef<'_, Flm>) -> bool {
792        match *self {
793            NodeRegion::Argument(index) => {
794                node.arguments().is_some_and(|arguments| index < arguments.len())
795                    && node.argument_content_nodes(index).is_none()
796            }
797            NodeRegion::Slot(_) => false,
798        }
799    }
800}
801
802impl fmt::Display for NodeRegion {
803    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
804        match self {
805            NodeRegion::Argument(index) => write!(f, "argument {index}"),
806            NodeRegion::Slot(index) => write!(f, "slot {index}"),
807        }
808    }
809}
810
811/// The function that [`Lowerer::lower_region`] calls to lower a node region's
812/// content, in the form the caller chooses.
813///
814/// It receives the [`LowerCx`], the [`Lowerer`] (both now working in the
815/// tree that holds the region), the node the region belongs to, and the
816/// region's content nodes ([`NodeRegion::content_nodes`]), and it returns the
817/// nodes it staged. Most callers lower the content nodes unchanged, as one
818/// run of siblings:
819/// [`lower_region_content`](crate::stdlib::backends::lowering::lower_region_content)
820/// does that. A caller that places nodes of its own among the content (for
821/// example, a link written at the end of the content's last paragraph) writes
822/// a function of its own, which passes the content nodes to the
823/// [`Lowerer`].
824pub type RegionShape<'f> = dyn FnMut(
825        &mut LowerCx<'_>,
826        &mut dyn Lowerer,
827        &NodeRef<'_, Flm>,
828        &[NodeRef<'_, Flm>],
829    ) -> Result<Vec<BuildId>, LowerError>
830    + 'f;
831
832/// The implementation of a lowering rule: what to do at a node of the rule's
833/// element.
834///
835/// Implement this trait and register the implementation as part of a
836/// [`LoweringRule`]. The implementation is registered once and may run over
837/// many nodes of many documents in parallel, so it holds only its own
838/// configuration and does not modify its own state when it runs. Everything it reads reaches it through
839/// the [`Lowerer`] it is handed, so every read can be checked against the
840/// rule's declaration.
841///
842/// See [`crate::stdlib::backends::lowering::rules`] for the default rules of
843/// the structural elements, which implement this trait.
844pub trait Lower: Send + Sync {
845    /// Lowers `node`, a node of this rule's element, and returns what replaces
846    /// it.
847    ///
848    /// Read the tables and option types the rule declared through `lw`, and
849    /// build the replacement nodes through `lw` as well, which stages them
850    /// into `cx`.
851    ///
852    /// # Errors
853    ///
854    /// Returns [`LowerError`] when the rule cannot lower the node: a read it
855    /// did not declare, an element it did not declare that it produces, a node
856    /// structure it does not handle. See [`LowerError`] for how the lowering
857    /// stage handles each variant.
858    fn lower(
859        &self,
860        node: NodeRef<'_, Flm>,
861        cx: &mut LowerCx<'_>,
862        lw: &mut dyn Lowerer,
863    ) -> Result<Lowering, LowerError>;
864}
865
866/// The interface a lowering rule works through.
867///
868/// To stage a node is to build it into the tree that a lowering rule or a
869/// rewrite hook is producing, through the context the rule or hook is handed
870/// (the [`LowerCx`] at lowering); the staged nodes exist in that tree only.
871///
872/// The `Lowerer` is the only interface a lowering rule has to the run: through
873/// it the rule lowers parts of its node, stages presentation nodes into the
874/// [`LowerCx`], splices a synthesized value and lowers a node region of
875/// another node; the lowering driver implements it
876/// ([`crate::stdlib::backends::lowering::driver`]). A rule author calls these
877/// methods and does not implement this trait.
878///
879/// Because a rule never reaches the run directly, its reads can be checked:
880/// every table and option read made here is checked against the rule's own
881/// [`LoweringDecl`], which is narrower than everything its backend's lowering
882/// stage declared.
883///
884/// The trait is object-safe (a rule receives it as `&mut dyn Lowerer`), so
885/// the methods that need a type parameter are type-erased here, and their
886/// typed forms (`get`, `option`, `pres_with`, `pres_slots_with`, `error`,
887/// `warning` and `note`) are defined on `dyn Lowerer`. Call the typed forms;
888/// the erased ones exist so that the typed forms can be written.
889///
890/// Every method that builds something also takes the [`LowerCx`], because the
891/// nodes are staged into it and this interface does not own it.
892///
893/// # Errors
894///
895/// Each method that can fail returns [`LowerError`], which a rule must return
896/// from [`Lower::lower`] instead of continuing.
897pub trait Lowerer {
898    /// Returns the name of the rule being applied.
899    fn rule(&self) -> &RuleName;
900
901    /// Returns the name of the backend for which the tree is lowered.
902    fn backend(&self) -> &BackendName;
903
904    /// Returns what starts a source comment under the parsing configuration
905    /// the registry was built with, as
906    /// [`FlmParsing::comment_start`](crate::lang::FlmParsing::comment_start)
907    /// does: `Some("%%")` by default, and `None` when the configuration
908    /// recognizes no comment, in which case no tree holds a comment node. A
909    /// rule that writes a comment back takes the prefix from here rather than
910    /// from the node, so that it writes the same prefix as the backend's
911    /// emitter.
912    fn comment_start(&self) -> Option<&str>;
913
914    /// Returns the language the registry was built with. A rule compiles
915    /// against it a text of the document that is written in a language of its
916    /// own rather than as content: for example, the label template an author
917    /// writes in a list's optional argument, which is compiled when the list
918    /// is lowered, since only the list's rule reads that text as a template.
919    fn lang(&self) -> &BuiltLang;
920
921    /// Returns the identifier of the tree being lowered: a document tree, or a
922    /// synthesized value while [`Lowerer::splice`] is lowering one.
923    fn tree_id(&self) -> TreeId;
924
925    /// Returns the region layout with which the block-structure pass laid out
926    /// the top level of the tree being lowered: for a document tree, the
927    /// layout of the fragment it was parsed from
928    /// ([`Fragment::layout`](crate::model::doc::Fragment::layout)); for a
929    /// synthesized value, the layout with which every synthesized value is
930    /// brought up to date, [`FragmentLayout::default`]. A rule passes it to
931    /// [`stands_in_blocks`](crate::lang::rewrites::blocks::stands_in_blocks)
932    /// to learn whether a node is laid out in blocks.
933    fn layout(&self) -> FragmentLayout;
934
935    /// Returns the address of the node being lowered, the key of the computed
936    /// data about that node.
937    fn addr(&self) -> NodeAddr;
938
939    /// Returns the address of another node of the same tree, for example an
940    /// ancestor the rule walked up to.
941    ///
942    /// # Errors
943    ///
944    /// Returns [`LowerError::Structure`] when `node` belongs to another tree
945    /// or has no address in the tree being lowered.
946    fn addr_of(&self, node: &NodeRef<'_, Flm>) -> Result<NodeAddr, LowerError>;
947
948    /// Returns the tree of the document that the node being lowered places,
949    /// or `None` when it places none, from the run's record of placements
950    /// ([`StageCx::placement_of`](crate::core::run::StageCx::placement_of)).
951    /// The rule of the element that places a tree reads it to identify the
952    /// tree in the node it builds.
953    fn placement(&self) -> Option<TreeId>;
954
955    /// Returns a table the rule declared that it reads, type-erased. Call
956    /// `get`, defined on `dyn Lowerer`, instead: it returns the table's value
957    /// type.
958    ///
959    /// `Ok(None)` means that the run holds no value for the table, which can
960    /// only happen for a table declared as an optional read.
961    ///
962    /// # Errors
963    ///
964    /// Returns [`AccessError`] when the rule did not declare this read, or
965    /// declared it under another value type.
966    fn get_erased(&self, table: &TableRef)
967    -> Result<Option<&(dyn Any + Send + Sync)>, AccessError>;
968
969    /// Returns the name of the stage the plan scheduled to write a table the
970    /// rule reads, or `None` when no scheduled stage writes it.
971    ///
972    /// Use it to identify that stage in a message about data the rule
973    /// expected and did not find.
974    fn producer_of(&self, table: &CapName) -> Option<StageName>;
975
976    /// Returns the value of an option type the rule declared that it reads,
977    /// type-erased. Call `option`, defined on `dyn Lowerer`, instead: it
978    /// returns the option type.
979    ///
980    /// # Errors
981    ///
982    /// Returns [`OptionError`] when the rule did not declare that option type.
983    fn option_erased(&self, key: OptionKey) -> Result<&(dyn Any + Send + Sync), OptionError>;
984
985    /// Lowers every child of `node`, and returns the nodes they became.
986    ///
987    /// # Errors
988    ///
989    /// Returns [`LowerError`] when lowering a child failed.
990    fn lower_children(
991        &mut self,
992        cx: &mut LowerCx<'_>,
993        node: &NodeRef<'_, Flm>,
994    ) -> Result<Vec<BuildId>, LowerError>;
995
996    /// Lowers the content of `node`'s body (the slot the element marks as its
997    /// body), and returns the nodes it became.
998    ///
999    /// # Errors
1000    ///
1001    /// Returns [`LowerError::Structure`] when the node has no body slot, and
1002    /// any [`LowerError`] the lowering of its content returned.
1003    fn lower_body(
1004        &mut self,
1005        cx: &mut LowerCx<'_>,
1006        node: &NodeRef<'_, Flm>,
1007    ) -> Result<Vec<BuildId>, LowerError>;
1008
1009    /// Lowers the content of `node`'s argument at position `index`, counting
1010    /// from zero, and returns the nodes it became.
1011    ///
1012    /// # Errors
1013    ///
1014    /// Returns [`LowerError::Structure`] when the node has no argument at that
1015    /// position or the argument is absent ([`NodeRegion::is_absent`]), and
1016    /// any [`LowerError`] the lowering of its content returned.
1017    fn lower_arg(
1018        &mut self,
1019        cx: &mut LowerCx<'_>,
1020        node: &NodeRef<'_, Flm>,
1021        index: usize,
1022    ) -> Result<Vec<BuildId>, LowerError>;
1023
1024    /// Lowers the content of `node`'s argument named `name`, and returns the
1025    /// nodes it became.
1026    ///
1027    /// # Errors
1028    ///
1029    /// Returns [`LowerError::Structure`] when the node has no argument of that
1030    /// name or the argument is absent, and any [`LowerError`] the lowering of
1031    /// its content returned.
1032    fn lower_arg_named(
1033        &mut self,
1034        cx: &mut LowerCx<'_>,
1035        node: &NodeRef<'_, Flm>,
1036        name: &str,
1037    ) -> Result<Vec<BuildId>, LowerError>;
1038
1039    /// Lowers a run of sibling nodes of the tree this `Lowerer` currently
1040    /// works in, and returns the nodes they became. That tree is the tree
1041    /// being lowered, the synthesized value being spliced
1042    /// ([`Lowerer::splice`]), or the tree that holds the node region being
1043    /// lowered ([`Lowerer::lower_region`]).
1044    ///
1045    /// Nodes of any other tree are refused, since their computed data would be
1046    /// read at addresses of the wrong tree. Lower a tree the rule builds
1047    /// itself by splicing it as a synthesized value, and another tree's
1048    /// content through [`Lowerer::lower_region`].
1049    ///
1050    /// # Errors
1051    ///
1052    /// Returns [`LowerError::Structure`] when the nodes belong to another
1053    /// tree, and any [`LowerError`] lowering one of the nodes returned.
1054    fn lower_nodes(
1055        &mut self,
1056        cx: &mut LowerCx<'_>,
1057        nodes: NodeSlice<'_, Flm>,
1058    ) -> Result<Vec<BuildId>, LowerError>;
1059
1060    /// Does what [`Lowering::Default`] asks for, and returns the result: the
1061    /// node copied, with its children lowered.
1062    ///
1063    /// Call it when the copy is one part of what the rule returns; return
1064    /// [`Lowering::Default`] when the copy is all the rule returns.
1065    ///
1066    /// # Errors
1067    ///
1068    /// Returns [`LowerError`] when the copy or a child's lowering failed.
1069    fn default(
1070        &mut self,
1071        cx: &mut LowerCx<'_>,
1072        node: &NodeRef<'_, Flm>,
1073    ) -> Result<Vec<BuildId>, LowerError>;
1074
1075    /// Builds a node of the presentation element `element`, carrying `payload`
1076    /// and holding `body` as its content, and returns its position.
1077    ///
1078    /// This is how a rule creates a presentation node: the method attaches the
1079    /// payload, the span, and everything else a node of that element needs.
1080    /// Call `pres_with`, defined on `dyn Lowerer`, instead: it takes the
1081    /// payload by value instead of behind a pointer.
1082    ///
1083    /// # Errors
1084    ///
1085    /// Returns [`LowerError::UndeclaredProduces`] when the rule's declaration
1086    /// does not list `element`, and [`LowerError::Build`] when the node could
1087    /// not be built.
1088    fn pres(
1089        &mut self,
1090        cx: &mut LowerCx<'_>,
1091        element: &ElementName,
1092        payload: Arc<dyn PresPayload>,
1093        body: Vec<BuildId>,
1094    ) -> Result<BuildId, LowerError>;
1095
1096    /// Builds a node of the presentation element `element` whose content is
1097    /// several named content slots rather than one body, and returns its
1098    /// position.
1099    ///
1100    /// Some presentation elements hold their content in parts: a list node
1101    /// has a `label` and an `item` content slot per list entry. `slots` gives
1102    /// those parts in order, each as a name and the nodes in it; a slot named
1103    /// `body` becomes the node's body slot. Everything else works as in
1104    /// [`Lowerer::pres`], including the refusal of an undeclared element. Call
1105    /// `pres_slots_with`, defined on `dyn Lowerer`, instead: it takes the
1106    /// payload by value.
1107    ///
1108    /// # Errors
1109    ///
1110    /// Returns [`LowerError::UndeclaredProduces`] when the rule's declaration
1111    /// does not list `element`, and [`LowerError::Build`] when the node could
1112    /// not be built. The default implementation of this method returns
1113    /// [`LowerError::Other`]: an implementation of [`Lowerer`] that does not
1114    /// override it cannot build a node with content slots.
1115    fn pres_slots(
1116        &mut self,
1117        cx: &mut LowerCx<'_>,
1118        element: &ElementName,
1119        payload: Arc<dyn PresPayload>,
1120        slots: Vec<(String, Vec<BuildId>)>,
1121    ) -> Result<BuildId, LowerError> {
1122        let _ = (cx, element, payload, slots);
1123        Err(LowerError::other("this lowerer cannot build a presentation node with content slots"))
1124    }
1125
1126    /// Builds a text node holding `text`, and returns its position.
1127    ///
1128    /// The text is not part of the document, so it is given a source of its
1129    /// own that identifies the node being lowered and the rule that produced
1130    /// the text. Following that provenance leads back to the document.
1131    ///
1132    /// # Errors
1133    ///
1134    /// Returns [`LowerError::UndeclaredProduces`] when the backend does not
1135    /// write text (`flm.text`) natively and the rule's declaration does not
1136    /// list it, and [`LowerError::Build`] when the node could not be built.
1137    fn text(&mut self, cx: &mut LowerCx<'_>, text: &str) -> Result<BuildId, LowerError>;
1138
1139    /// Splices the synthesized value `value`: lowers it where the node being
1140    /// lowered is placed, and returns the nodes it became.
1141    ///
1142    /// A synthesized value is a small tree that a stage builds while a run is
1143    /// under way, held outside the document's trees ([synthesized
1144    /// values](crate::guide::concepts_overview#synthesized-values)). It has
1145    /// been through none of the run's work, so this method first brings it up
1146    /// to date: the plan's rewrite stages run over it, then the per-tree
1147    /// stages the lowering stage depends on, so that the rules lowering its
1148    /// nodes read the same kinds of data as for a document node ([value
1149    /// catch-up](crate::guide::concepts_overview#value-catch-up),
1150    /// [`StageCx::resolve_value`](crate::core::run::StageCx::resolve_value)).
1151    ///
1152    /// Every diagnostic of the catch-up is reported, and so is every
1153    /// diagnostic of the value's lowering: a value spliced at several places
1154    /// (a kept definition's template, staged at each of its use sites) reports
1155    /// at each of them. Each such diagnostic keeps its own span, where the
1156    /// content was written, and gains one frame of its traceback
1157    /// ([`Diagnostic::frames`](techy::error::Diagnostic::frames)) whose span is
1158    /// the node being lowered, the place where the value is shown, and whose
1159    /// title is `a copy of this content, shown here`. A value spliced inside a
1160    /// value adds its own frame first, so the frames run innermost first.
1161    ///
1162    /// # Errors
1163    ///
1164    /// Returns [`LowerError::DocumentFactInValue`] when a stage run again over
1165    /// the value stated a fact about the document as a whole,
1166    /// [`LowerError::CatchUp`] when the value could not be brought up to date
1167    /// for any other reason, and any [`LowerError`] that the rules lowering
1168    /// the value returned. When that error is
1169    /// [`LowerError::PlaceholderCharacters`], the value's lowering is
1170    /// discarded entirely: the diagnostics it reported and the requirements it
1171    /// recorded ([`require`](Lowerer::require)) are dropped, so that what the
1172    /// rule writes in its place reports and records only its own.
1173    fn splice(
1174        &mut self,
1175        cx: &mut LowerCx<'_>,
1176        value: &Arc<NodeTree<Flm>>,
1177    ) -> Result<Vec<BuildId>, LowerError>;
1178
1179    /// Lowers the content of a node region of the node at `at` (its argument
1180    /// or its content slot at a position, [`NodeRegion`]) here, in the output being
1181    /// built, as content of that node's own tree, and returns the nodes it
1182    /// became.
1183    ///
1184    /// This is how a rule shows content written elsewhere without copying it.
1185    /// The rule of an element inside a synthesized value refers to a node of
1186    /// the document, or of another synthesized value, and that node's content
1187    /// is lowered where the element is placed. The content pointer
1188    /// ([`ContentPointer`](crate::stdlib::backends::lowering::ContentPointer))
1189    /// is built on this method. It is the counterpart of [`Lowerer::splice`],
1190    /// which lowers a synthesized value where the rule's node is placed in the
1191    /// document; this method is the only way to lower content of a tree other
1192    /// than the one being lowered.
1193    ///
1194    /// `at` designates a node of a document tree, or of a synthesized value
1195    /// this lowering holds: the value being lowered, or a value being spliced
1196    /// around the call. The region's content nodes are passed to `shape`,
1197    /// which lowers them in the form the caller wants; see [`RegionShape`].
1198    /// While `shape` runs, this `Lowerer` works in the tree that holds the
1199    /// region: [`Lowerer::tree_id`] and [`Lowerer::layout`] return that
1200    /// tree's, [`Lowerer::addr`] and [`Lowerer::addr_of`] return addresses in
1201    /// it, and each node lowered there keeps its own address as its origin, so
1202    /// that every later round of lowering reads the tables at that address
1203    /// too. A per-tree table is then read from that tree's own results: the
1204    /// run's store for a document tree, the synthesized value's own results
1205    /// for a synthesized value. The results of a synthesized value around the
1206    /// call are not read at another tree's address. A table computed for the
1207    /// whole document is read as everywhere else. The [recursion
1208    /// guard](crate::guide::concepts_overview#the-recursion-guard-and-worker-threads)
1209    /// applies as to any lowering: content that leads back to itself fails the tree
1210    /// with `flm.lowering.nesting-too-deep` instead of looping.
1211    ///
1212    /// **The caller must lower each node region once.** The lowering driver
1213    /// does not check it: a rule whose element passes one of its regions to
1214    /// this method elsewhere must not lower that region itself, and only one
1215    /// node may point at a given region. Content lowered twice is shown twice
1216    /// and reported twice.
1217    ///
1218    /// # Errors
1219    ///
1220    /// Returns [`LowerError::RegionNotFound`] when no tree of `at`'s
1221    /// identifier is reachable, when that tree holds no node at `at`, or when
1222    /// the node has no such region; nothing is staged then. Returns any
1223    /// [`LowerError`] `shape` returns.
1224    fn lower_region(
1225        &mut self,
1226        cx: &mut LowerCx<'_>,
1227        at: NodeAddr,
1228        region: NodeRegion,
1229        shape: &mut RegionShape<'_>,
1230    ) -> Result<Vec<BuildId>, LowerError>;
1231
1232    /// Records the requirement `id` for the tree being lowered: the
1233    /// identifier of a definition that its output needs, such as a style or
1234    /// script definition on HTML, or a package request or a definition piece
1235    /// on LaTeX ([`StyleDef`](crate::core::registry::StyleDef)). The backend
1236    /// that writes the output resolves the requirements recorded for each
1237    /// lowered tree.
1238    ///
1239    /// Use this for a requirement that comes from this particular node. A
1240    /// requirement the rule has whenever it is selected belongs in
1241    /// [`LoweringDecl::selection_requires`] instead.
1242    fn require(&mut self, id: &Name);
1243
1244    /// Records a diagnostic about the node being lowered.
1245    ///
1246    /// A rule reports at the node it is lowering, with that node's span. The
1247    /// methods `error`, `warning` and `note`, defined on `dyn Lowerer`, build
1248    /// the diagnostic from a condition and a span.
1249    fn diagnose(&mut self, diagnostic: FlmDiagnostic);
1250}
1251
1252/// The typed methods a rule calls on its [`Lowerer`].
1253///
1254/// These methods need a type parameter, which an object-safe trait cannot
1255/// have, so they are defined on `dyn Lowerer`, the form a rule is handed,
1256/// rather than on the trait. Each one calls the corresponding type-erased
1257/// method and converts the value.
1258impl dyn Lowerer + '_ {
1259    /// Reads a table the rule declared that it reads, as the table's value
1260    /// type.
1261    ///
1262    /// `Ok(None)` means that the run holds no value for the table, which can
1263    /// only happen for a table declared as an optional read.
1264    ///
1265    /// # Errors
1266    ///
1267    /// Returns [`AccessError`] when the rule did not declare this read, or
1268    /// declared it under another value type; see [`Lowerer::get_erased`].
1269    ///
1270    /// # Panics
1271    ///
1272    /// Panics if the [`Lowerer`] implementation's [`Lowerer::get_erased`]
1273    /// returns a value of a type other than the one the key designates. The
1274    /// implementation in this crate cannot: the registry compares the value
1275    /// type of the table with the key's before the read.
1276    pub fn get<K: TableKey>(&self, key: K) -> Result<Option<&K::Table>, AccessError> {
1277        Ok(self.get_erased(&key.table_ref())?.map(|table| {
1278            table
1279                .downcast_ref::<K::Table>()
1280                .expect("a table is stored under its declared type, which the key matched")
1281        }))
1282    }
1283
1284    /// Reads the value of an option type the rule declared that it reads.
1285    ///
1286    /// # Errors
1287    ///
1288    /// Returns [`OptionError`] when the rule did not declare that option type;
1289    /// see [`Lowerer::option_erased`].
1290    ///
1291    /// # Panics
1292    ///
1293    /// Panics if the [`Lowerer`] implementation's [`Lowerer::option_erased`]
1294    /// returns a value that is not of type `T`. The implementation in this
1295    /// crate cannot: an option value is stored under its own type.
1296    pub fn option<T: Options>(&self) -> Result<&T, OptionError> {
1297        Ok(self
1298            .option_erased(OptionKey::of::<T>())?
1299            .downcast_ref::<T>()
1300            .expect("a resolved option is stored under its own type"))
1301    }
1302
1303    /// Reads the value of the option type declared from data under the name
1304    /// `name`, which the rule declared that it reads
1305    /// ([`LoweringDecl::option_named`]): the data as written, or the empty map
1306    /// when no value is set.
1307    ///
1308    /// # Errors
1309    ///
1310    /// Returns [`OptionError`] when the rule did not declare that read; see
1311    /// [`Lowerer::option_erased`].
1312    ///
1313    /// # Panics
1314    ///
1315    /// Panics if the [`Lowerer`] implementation's [`Lowerer::option_erased`]
1316    /// returns a value that is not a [`DataValue`]. The implementation in this
1317    /// crate cannot: an option declared from data is stored as one.
1318    pub fn option_named(&self, name: &str) -> Result<&Value, OptionError> {
1319        Ok(&self
1320            .option_erased(OptionKey::named(name))?
1321            .downcast_ref::<DataValue>()
1322            .expect("an option declared from data is stored as a `DataValue`")
1323            .0)
1324    }
1325
1326    /// Builds a presentation node carrying `payload`, taken by value, and
1327    /// returns its position.
1328    ///
1329    /// The same as [`Lowerer::pres`] in every other respect.
1330    ///
1331    /// # Errors
1332    ///
1333    /// Exactly as [`Lowerer::pres`]:
1334    /// [`LowerError::UndeclaredProduces`] when the rule's declaration does not
1335    /// list `element`, and [`LowerError::Build`] when the node could not be
1336    /// built.
1337    pub fn pres_with<P: PresPayload>(
1338        &mut self,
1339        cx: &mut LowerCx<'_>,
1340        element: &ElementName,
1341        payload: P,
1342        body: Vec<BuildId>,
1343    ) -> Result<BuildId, LowerError> {
1344        self.pres(cx, element, Arc::new(payload), body)
1345    }
1346
1347    /// Builds a presentation node with content slots, carrying `payload` taken
1348    /// by value, and returns its position.
1349    ///
1350    /// The same as [`Lowerer::pres_slots`] in every other respect.
1351    ///
1352    /// # Errors
1353    ///
1354    /// Exactly as [`Lowerer::pres_slots`]:
1355    /// [`LowerError::UndeclaredProduces`] when the rule's declaration does not
1356    /// list `element`, [`LowerError::Build`] when the node could not be built,
1357    /// and [`LowerError::Other`] from an implementation that does not override
1358    /// [`Lowerer::pres_slots`].
1359    pub fn pres_slots_with<P: PresPayload>(
1360        &mut self,
1361        cx: &mut LowerCx<'_>,
1362        element: &ElementName,
1363        payload: P,
1364        slots: Vec<(String, Vec<BuildId>)>,
1365    ) -> Result<BuildId, LowerError> {
1366        self.pres_slots(cx, element, Arc::new(payload), slots)
1367    }
1368
1369    /// Records a diagnostic of Error severity reporting `condition` at `span`.
1370    ///
1371    /// An Error says that the document is wrong in a way that has no sensible
1372    /// rendering. See [`Lowerer::diagnose`].
1373    pub fn error(&mut self, condition: impl DiagnosticInfo, span: FlmSpan) {
1374        self.diagnose(Diagnostic::error(condition, span));
1375    }
1376
1377    /// Records a diagnostic of Warning severity reporting `condition` at
1378    /// `span`.
1379    ///
1380    /// A Warning says that something is probably wrong, and the rule still
1381    /// rendered it. See [`Lowerer::diagnose`].
1382    pub fn warning(&mut self, condition: impl DiagnosticInfo, span: FlmSpan) {
1383        self.diagnose(Diagnostic::warning(condition, span));
1384    }
1385
1386    /// Records a diagnostic of Note severity reporting `condition` at `span`.
1387    ///
1388    /// A Note gives information and reports no problem. See
1389    /// [`Lowerer::diagnose`].
1390    pub fn note(&mut self, condition: impl DiagnosticInfo, span: FlmSpan) {
1391        self.diagnose(Diagnostic::note(condition, span));
1392    }
1393}
1394
1395#[cfg(test)]
1396mod tests {
1397    use super::*;
1398
1399    #[test]
1400    fn a_default_mark_answers_per_backend() {
1401        assert!(DefaultMark::Everywhere.is_general());
1402        assert!(!DefaultMark::Never.is_general());
1403        let specific = DefaultMark::OnBackends(vec!["latex-rendered".into()]);
1404        assert!(specific.is_specific_to(&"latex-rendered".into()));
1405        assert!(!specific.is_specific_to(&"text".into()));
1406        assert!(!specific.is_general());
1407    }
1408}