Skip to main content

flm_core/core/registry/
entities.rs

1//! The declaration values a feature passes to the [feature
2//! builder](super::FeatureBuilder), and the two build hooks through which a
3//! feature does work later in the registry build.
4//!
5//! A declaration value describes one entity that a feature contributes to a
6//! registry. Some declaration types are defined next to the code that uses
7//! them: element declarations in [`crate::lang::mint`], stage declarations in
8//! [`crate::core::stage`], table declarations in [`crate::core::data::table`]
9//! and lowering rules in [`crate::core::lowering`]. The others are defined
10//! here:
11//!
12//! - [`CapabilityDef`] declares a capability, a registered dotted name for a
13//!   state of processing that a stage brings about; [`CollectionDef`] declares
14//!   a collection, a name for a set of capabilities that any feature may add
15//!   to.
16//! - [`ArgumentRoleDef`] declares an argument role, a registered dotted name
17//!   for what an argument of a command holds (a label, a citation key, the
18//!   path of a file).
19//! - [`OrderingDef`] declares ordering edges, which place a stage (possibly
20//!   another feature's) after or before the stages that provide given
21//!   capabilities.
22//! - [`BackendDef`] declares a backend, the registration bundle for one output
23//!   format. [`OutputDef`] declares an output, a name a caller asks for to have
24//!   something produced; [`OutputEntry`] describes the output's entry
25//!   artifact.
26//! - [`WorkflowDef`] declares a workflow, a named set of demands together with
27//!   the choices that go with them; [`LoweringSelection`] is a workflow's
28//!   preference among the lowering rules of one backend.
29//! - [`StyleDef`] and [`ScriptDef`] declare a stylesheet or a script that a
30//!   feature's output depends on; [`DefContent`] is one part of such a
31//!   definition's content.
32//! - [`NativeImplication`] and [`NativeImplicationKind`] declare a requirement
33//!   on what every backend's native set must contain, checked when the
34//!   registry is built.
35//! - [`PeerName`] identifies a peer declaration: a feature's forward
36//!   declaration of an entity that another feature owns.
37//! - [`Finalizer`] and [`LateInit`] are the two build hooks: a finalizer runs
38//!   in the build's second registration round, and a late-initialization hook
39//!   runs after the language that documents are parsed with
40//!   ([`FlmRegistry::lang`](super::FlmRegistry::lang)) is built.
41//!
42//! Each declaration type is a plain value with a constructor and setters that
43//! return `Self`, so a declaration can be written as one expression. No
44//! declaration type holds the name of the feature that declares it: the
45//! builder attributes each declaration to the feature it was created for.
46//!
47//! See also [features and
48//! packages](crate::guide::concepts_overview#features-and-packages) and
49//! [stages, capabilities, and
50//! plans](crate::guide::concepts_overview#stages-capabilities-and-plans).
51
52use std::any::{Any, TypeId};
53use std::collections::BTreeMap;
54use std::fmt;
55use std::sync::Arc;
56
57use crate::model::element::ElementSpec;
58use crate::model::names::{
59    BackendName, CapName, ElementName, Name, OutputName, RuleName, StageName, WorkflowName,
60};
61use techy::serialize::SerialValue;
62
63use crate::core::data::table::{ProjectCx, Table};
64use crate::model::options::OptionValues;
65use crate::core::registry::builder::{BuildError, FeatureBuilder};
66use crate::core::stage::Stage;
67use crate::lang::{BuiltLang, FlmDiagnostics};
68
69/// A capability declaration. A **capability** is a registered dotted name for a
70/// state of processing that a stage brings about, such as
71/// `flm.blocks.structured`: a stage declares the capabilities it provides and
72/// the capabilities it requires, and a caller demands the capabilities it
73/// wants.
74///
75/// A caller demands capabilities ([`PlanRequest::demand`](crate::core::plan::PlanRequest::demand)),
76/// and the plan chooses stages that provide them, so nobody writes the
77/// sequence of stages by hand. A capability may **refine** another: it is a
78/// stronger form of the other one (`flm.blocks.structured` refines
79/// `flm.blocks`), and a stage that provides the refinement also satisfies a
80/// demand for the parent. At most one refinement of a parent may be marked as
81/// its default; a demand for the parent alone selects the default refinement
82/// when nothing else decides.
83///
84/// Every table's name is already a capability, declared together with the
85/// table. Declare a capability with this type only for a state that no table
86/// represents: a marker, the result of a check, or the parent of
87/// refinements. Register the declaration with
88/// [`FeatureBuilder::capability`](super::FeatureBuilder::capability).
89///
90/// It is written to data with `Serialize`; see [serialized
91/// forms](crate::core::registry#serialized-forms).
92///
93/// # Examples
94///
95/// ```
96/// use flm_core::core::registry::CapabilityDef;
97///
98/// let parent = CapabilityDef::new("flm.blocks").docs("Content is grouped into blocks.");
99/// let refined = CapabilityDef::new("flm.blocks.structured")
100///     .refines("flm.blocks")
101///     .default();
102/// assert_eq!(refined.refines, Some(parent.name));
103/// assert!(refined.default);
104/// ```
105#[derive(Debug, Clone, PartialEq, Eq)]
106#[derive(serde::Serialize, schemars::JsonSchema)]
107pub struct CapabilityDef {
108    /// The capability's dotted name.
109    pub name: CapName,
110    /// Documentation prose.
111    pub docs: String,
112    /// The capability this one refines, if any. Some feature of the same
113    /// registry must declare it, and a chain of refinements may not lead back
114    /// to a capability already in it; the registry build checks both.
115    pub refines: Option<CapName>,
116    /// Whether this capability is the default refinement of its parent. At
117    /// most one refinement of a parent may set it, and setting it on a
118    /// capability that refines nothing is a build error
119    /// ([`BuildError::DefaultWithoutParent`]).
120    pub default: bool,
121    /// What a plan error says, after the workflow it names, when a plan needs
122    /// this capability and no registered stage provides it, in place of the
123    /// generic text: the condition in the words of the feature that declares the
124    /// capability, with its fix when the fix is not obvious. `None` keeps the
125    /// generic text ([`PlanError::Unsatisfiable`](crate::core::plan::PlanError::Unsatisfiable)).
126    pub unprovided: Option<String>,
127}
128
129impl CapabilityDef {
130    /// A capability called `name`, refining nothing, with no documentation.
131    pub fn new(name: impl Into<CapName>) -> CapabilityDef {
132        CapabilityDef { name: name.into(), docs: String::new(), refines: None, default: false, unprovided: None }
133    }
134
135    /// Sets what a plan error says when no registered stage provides this
136    /// capability ([`unprovided`](CapabilityDef::unprovided)). Returns `self`,
137    /// for chaining.
138    ///
139    /// # Examples
140    ///
141    /// ```
142    /// use flm_core::core::registry::CapabilityDef;
143    ///
144    /// let checked = CapabilityDef::new("example.checked")
145    ///     .unprovided("no feature checks the examples; use a package that does");
146    /// assert!(checked.unprovided.is_some());
147    /// ```
148    pub fn unprovided(mut self, text: impl Into<String>) -> CapabilityDef {
149        self.unprovided = Some(text.into());
150        self
151    }
152
153    /// Sets the documentation prose. Returns `self`, for chaining.
154    pub fn docs(mut self, docs: impl Into<String>) -> CapabilityDef {
155        self.docs = crate::kept_docs(docs);
156        self
157    }
158
159    /// Makes this capability a refinement of `parent`, replacing any parent
160    /// set before. Returns `self`, for chaining.
161    pub fn refines(mut self, parent: impl Into<CapName>) -> CapabilityDef {
162        self.refines = Some(parent.into());
163        self
164    }
165
166    /// Marks this capability as its parent's default refinement. Returns
167    /// `self`, for chaining. Call [`refines`](CapabilityDef::refines) as well:
168    /// a default refinement without a parent is a build error.
169    pub fn default(mut self) -> CapabilityDef {
170        self.default = true;
171        self
172    }
173}
174
175/// A collection declaration. A **collection** is a name for a set of
176/// capabilities that any feature may add to, such as the standard features'
177/// `flm.validated` ([`VALIDATED`](crate::stdlib::VALIDATED)), which every
178/// check of the standard features joins.
179///
180/// Demanding a collection demands every one of its members. A feature uses a
181/// collection to join a set of demands it does not own: it declares its own
182/// check capability and adds it as a member with
183/// [`FeatureBuilder::collection_member`](super::FeatureBuilder::collection_member),
184/// and a caller that demands the collection then runs that check too.
185///
186/// Collections share one namespace with capabilities and tables, so a
187/// collection's name may not be a capability's or a table's. A collection can
188/// be demanded but never provided: a stage that lists a collection in its
189/// `provides` is a build error ([`BuildError::CollectionAsCapability`]).
190/// Register the declaration with
191/// [`FeatureBuilder::collection`](super::FeatureBuilder::collection).
192///
193/// It is written to data with `Serialize`; see [serialized
194/// forms](crate::core::registry#serialized-forms).
195///
196/// # Examples
197///
198/// ```
199/// use flm_core::core::registry::CollectionDef;
200///
201/// let def = CollectionDef::new("flm.validated").docs("Every registered check has run.");
202/// assert_eq!(def.name, "flm.validated");
203/// ```
204#[derive(Debug, Clone, PartialEq, Eq)]
205#[derive(serde::Serialize, schemars::JsonSchema)]
206pub struct CollectionDef {
207    /// The collection's name, in the namespace that capabilities and tables
208    /// share.
209    pub name: CapName,
210    /// Documentation prose.
211    pub docs: String,
212}
213
214impl CollectionDef {
215    /// A collection called `name`, with no documentation. Any feature adds
216    /// members separately, with
217    /// [`FeatureBuilder::collection_member`](super::FeatureBuilder::collection_member).
218    pub fn new(name: impl Into<CapName>) -> CollectionDef {
219        CollectionDef { name: name.into(), docs: String::new() }
220    }
221
222    /// Sets the documentation prose. Returns `self`, for chaining.
223    pub fn docs(mut self, docs: impl Into<String>) -> CollectionDef {
224        self.docs = crate::kept_docs(docs);
225        self
226    }
227}
228
229/// An argument role declaration. An **argument role** is a registered dotted
230/// name for what an argument of a command holds, beyond how the argument is
231/// written: `flm.refs.target` for the label a reference points to,
232/// `flm.graphics.path` for the path of an image file.
233///
234/// The syntax of an argument says how it is read (a group of characters, raw
235/// text up to a closing brace); its role says what the text is. Two commands
236/// whose arguments hold the same kind of thing set the same role on them
237/// ([`ArgDef::role`](crate::lang::mint::ArgDef::role)), so that a program
238/// that describes the language can say so. Parsing and processing do not
239/// read roles, and they are not inputs of the [registry
240/// digest](crate::model::digest).
241///
242/// Argument roles have a namespace of their own. A role's name follows the
243/// naming rules of every registry name: dotted, its first segment the owner
244/// (`flm` for the standard features, an extension's stem for an
245/// extension's). The standard features name theirs `flm.<feature>.<thing>`
246/// (`flm.refs.target`). Register the declaration with
247/// [`FeatureBuilder::argument_role`](super::FeatureBuilder::argument_role);
248/// a feature that sets another feature's role on its arguments declares the
249/// role as a peer when that feature may be absent
250/// ([`FeatureBuilder::peer_argument_role`](super::FeatureBuilder::peer_argument_role)).
251/// The frozen registry lists the roles
252/// ([`FlmRegistry::argument_roles`](super::FlmRegistry::argument_roles)).
253///
254/// The serialized form (`Serialize`, with the fields as keys) is read by
255/// `flm-info`'s description of the registry and is versioned by its
256/// `meta.format`.
257///
258/// # Examples
259///
260/// ```
261/// use flm_core::core::registry::ArgumentRoleDef;
262///
263/// let def = ArgumentRoleDef::new("flm.refs.target", "A label that a reference points to.");
264/// assert_eq!(def.name, "flm.refs.target");
265/// ```
266// A role is a name declared in the registry, not free text, so that it has an
267// owner, a documentation text and a listing, as every other dotted name has,
268// and a misspelled role is reported.
269#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, schemars::JsonSchema)]
270pub struct ArgumentRoleDef {
271    /// The role's dotted name, unique among the argument roles of a registry.
272    pub name: Name,
273    /// Documentation prose: what an argument of this role holds, written for
274    /// a person who reads the registry's declarations.
275    pub docs: String,
276}
277
278impl ArgumentRoleDef {
279    /// The argument role called `name`, described by `docs`.
280    pub fn new(name: impl Into<Name>, docs: impl Into<String>) -> ArgumentRoleDef {
281        ArgumentRoleDef { name: name.into(), docs: crate::kept_docs(docs) }
282    }
283}
284
285/// Ordering edges placed on a stage: the stage runs after the stages that
286/// provide the capabilities in `after`, and before those that provide the
287/// capabilities in `before`.
288///
289/// A stage normally gets its place in the order from what it requires and
290/// reads. Ordering edges serve a feature whose stage must run before or after
291/// another feature's work without needing that work's results. Any feature may
292/// place edges on any registered stage, its own or another feature's, in any
293/// order of registration.
294///
295/// Edges decide order only. An edge never makes a stage require a capability
296/// and never causes a stage to be scheduled: it constrains when a stage runs,
297/// if the plan runs it at all. In an edge, a capability that has refinements
298/// means whichever of its refinements the plan selected.
299///
300/// Register the edges with
301/// [`FeatureBuilder::ordering`](super::FeatureBuilder::ordering).
302///
303/// # Examples
304///
305/// ```
306/// use flm_core::model::names::CapName;
307/// use flm_core::core::registry::OrderingDef;
308///
309/// let edges = OrderingDef::new("flm.refs.resolve")
310///     .after("flm.headings.numbered")
311///     .before("flm.index.built");
312/// assert_eq!(edges.after, [CapName::from("flm.headings.numbered")]);
313/// ```
314#[derive(Debug, Clone, PartialEq, Eq)]
315pub struct OrderingDef {
316    /// The stage these edges apply to. Some feature of the registry must
317    /// register a stage of this name.
318    pub stage: StageName,
319    /// The stage runs after the stage that provides each of these
320    /// capabilities.
321    pub after: Vec<CapName>,
322    /// The stage runs before the stage that provides each of these
323    /// capabilities.
324    pub before: Vec<CapName>,
325}
326
327impl OrderingDef {
328    /// An empty set of edges on the stage `stage`.
329    pub fn new(stage: impl Into<StageName>) -> OrderingDef {
330        OrderingDef { stage: stage.into(), after: Vec::new(), before: Vec::new() }
331    }
332
333    /// Adds an edge that places the stage after the stage providing
334    /// `capability`. Returns `self`, for chaining.
335    pub fn after(mut self, capability: impl Into<CapName>) -> OrderingDef {
336        self.after.push(capability.into());
337        self
338    }
339
340    /// Adds an edge that places the stage before the stage providing
341    /// `capability`. Returns `self`, for chaining.
342    pub fn before(mut self, capability: impl Into<CapName>) -> OrderingDef {
343        self.before.push(capability.into());
344        self
345    }
346}
347
348/// A backend declaration. A **backend** is the registration bundle for one
349/// output format: the elements its emitter writes natively, a lowering stage,
350/// an emit stage and a final stage.
351///
352/// The three stages are ordinary stages of the declaring feature, scheduled
353/// like any other; this declaration groups them so that a plan recognizes them
354/// as one backend:
355///
356/// - the **lowering** stage rewrites the frozen trees into presentation trees,
357///   made of the elements this backend writes, and writes them to the table
358///   `flm.lowered.<backend>` (see [backends, lowering, and
359///   outputs](crate::guide::concepts_overview#backends-lowering-and-outputs));
360/// - the **emit** stage turns the presentation trees into the output's bytes,
361///   in the table `flm.output.<backend>`;
362/// - the **final** stage (see [output regions and the final
363///   stage](crate::guide::concepts_overview#output-regions-and-the-final-stage))
364///   assembles the artifact set the caller receives.
365///
366/// The **native set** (`native`) lists the elements the emit stage writes
367/// directly. Lowering rules turn every other element into these. When a plan
368/// is built, an element that may occur in a document and that no chain of
369/// lowering rules leads into the native set is refused, unless the plan
370/// request accepts it as unrenderable (for a workflow, with
371/// [`WorkflowDef::unsupported`]). The native set must also satisfy every
372/// [native-set implication](NativeImplication) of the registry (an element
373/// every backend must write natively, or one a backend must write natively
374/// because of another element it writes natively); otherwise the registry
375/// build fails with [`BuildError::NativeSetIncomplete`].
376///
377/// Register the declaration with
378/// [`FeatureBuilder::backend`](super::FeatureBuilder::backend). See
379/// [`OutputDef`] for how a caller asks for what a backend produces.
380#[derive(Clone)]
381pub struct BackendDef {
382    /// The backend's name; it is also the last segment of the names of its
383    /// tables (`flm.lowered.<backend>`, `flm.output.<backend>`).
384    pub name: BackendName,
385    /// The native set: the elements this backend's emit stage writes
386    /// directly, namely the presentation elements it understands and the
387    /// structural elements it writes without a lowering rule.
388    pub native: Vec<ElementName>,
389    /// The lowering stage, which builds the presentation trees.
390    pub lowering: Arc<dyn Stage>,
391    /// The emit stage, which turns the presentation trees into bytes.
392    pub emit: Arc<dyn Stage>,
393    /// The final stage, which assembles the artifact set.
394    pub final_stage: Arc<dyn Stage>,
395    /// Documentation prose.
396    pub docs: String,
397}
398
399impl BackendDef {
400    /// A backend called `name`, whose emit stage writes the elements of
401    /// `native` directly, with its lowering, emit and final stages, and with
402    /// no documentation.
403    pub fn new(
404        name: impl Into<BackendName>,
405        native: impl IntoIterator<Item = impl Into<ElementName>>,
406        lowering: Arc<dyn Stage>,
407        emit: Arc<dyn Stage>,
408        final_stage: Arc<dyn Stage>,
409    ) -> BackendDef {
410        BackendDef {
411            name: name.into(),
412            native: native.into_iter().map(Into::into).collect(),
413            lowering,
414            emit,
415            final_stage,
416            docs: String::new(),
417        }
418    }
419
420    /// Sets the documentation prose. Returns `self`, for chaining.
421    pub fn docs(mut self, docs: impl Into<String>) -> BackendDef {
422        self.docs = crate::kept_docs(docs);
423        self
424    }
425}
426
427impl fmt::Debug for BackendDef {
428    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
429        f.debug_struct("BackendDef")
430            .field("name", &self.name)
431            .field("native", &self.native)
432            .finish_non_exhaustive()
433    }
434}
435
436/// What is known about an output's entry artifact before anything is
437/// rendered: its media type and its file extension.
438///
439/// A run may produce several artifacts for one output (for example a page and
440/// the images it shows); the **entry artifact** is the one that represents the
441/// output as a whole ([`ArtifactSet`](crate::core::artifact::ArtifactSet)).
442/// With this value, a caller can choose a file name and a content type from
443/// the registry alone, before running anything.
444///
445/// It is written to data with `Serialize`; see [serialized
446/// forms](crate::core::registry#serialized-forms).
447#[derive(Debug, Clone, PartialEq, Eq)]
448#[derive(serde::Serialize, schemars::JsonSchema)]
449pub struct OutputEntry {
450    /// The entry artifact's media type, such as `text/plain`.
451    pub media_type: String,
452    /// The entry artifact's file extension, without a dot, such as `txt`.
453    pub extension: String,
454}
455
456/// An output declaration. An **output** is a name a caller asks for to have
457/// something produced, such as `text` or `html`, together with how to produce
458/// it.
459///
460/// An output ties three things together: the capability a plan must reach
461/// for the output to exist, the table that holds the produced artifacts, and
462/// the description of its entry artifact. A [`WorkflowDef`] lists outputs by
463/// name, and demanding an output means demanding its capability.
464///
465/// An output may be made from the files of other outputs: a stage that
466/// provides it reads their artifact sets, as an output of PDF files is made by
467/// compiling the files of a LaTeX output. The declaration lists those outputs
468/// in [`made_from`](OutputDef::made_from), so that a host preparing the output
469/// prepares them as well.
470///
471/// The registry build checks three requirements. The capability must be the
472/// table's own capability or a refinement of it, so that reaching the
473/// capability guarantees that the table is written
474/// ([`BuildError::OutputCapabilityMismatch`]). The table must hold an
475/// [artifact set](crate::core::artifact::ArtifactSet)
476/// ([`BuildError::OutputTableNotArtifactSet`]). Each output listed in
477/// [`made_from`](OutputDef::made_from) must be declared by a feature
478/// ([`BuildError::Undeclared`]).
479///
480/// Register the declaration with
481/// [`FeatureBuilder::output`](super::FeatureBuilder::output).
482///
483/// It is written to data with `Serialize`; see [serialized
484/// forms](crate::core::registry#serialized-forms).
485///
486/// # Examples
487///
488/// ```
489/// use flm_core::core::registry::OutputDef;
490///
491/// let def = OutputDef::new("text", "flm.artifacts.text", "flm.artifacts.text", "text/plain", "txt")
492///     .docs("Plain text, one file.");
493/// assert_eq!(def.entry.extension, "txt");
494///
495/// let pdf = OutputDef::new("pdf", "my.pdf", "my.pdf", "application/pdf", "pdf")
496///     .made_from("latex-rendered");
497/// assert_eq!(pdf.made_from[0].as_str(), "latex-rendered");
498/// ```
499#[derive(Debug, Clone, PartialEq, Eq)]
500#[derive(serde::Serialize, schemars::JsonSchema)]
501pub struct OutputDef {
502    /// The output's name, as a caller writes it.
503    pub name: OutputName,
504    /// The capability demanded to produce this output: the table's own
505    /// capability, or a refinement of it.
506    pub capability: CapName,
507    /// The name of the table that holds the output's artifacts, as an
508    /// artifact set.
509    pub table: CapName,
510    /// The media type and file extension of the entry artifact.
511    pub entry: OutputEntry,
512    /// The outputs whose files a stage providing this output reads to make it,
513    /// in the order they were added; empty for an output made from the
514    /// document alone.
515    ///
516    /// The list tells a host which other outputs the output depends on before
517    /// any plan is built: a host that sets up something per output for a
518    /// request, such as the compose template that assembles an output's main
519    /// file, sets it up for each output the requested outputs are made from,
520    /// and for each output those are made from in turn. The stage itself
521    /// declares its read of the other output's table among its needs, which is
522    /// what schedules the stages that write it. The registry build refuses a
523    /// name that no feature declares as an output ([`BuildError::Undeclared`]).
524    pub made_from: Vec<OutputName>,
525    /// Documentation prose.
526    pub docs: String,
527}
528
529impl OutputDef {
530    /// An output called `name`, produced by demanding `capability`, whose
531    /// artifacts are held in the table `table` and whose entry artifact has
532    /// the media type `media_type` and the file extension `extension`
533    /// (without a dot); made from no other output, with no documentation.
534    pub fn new(
535        name: impl Into<OutputName>,
536        capability: impl Into<CapName>,
537        table: impl Into<CapName>,
538        media_type: impl Into<String>,
539        extension: impl Into<String>,
540    ) -> OutputDef {
541        OutputDef {
542            name: name.into(),
543            capability: capability.into(),
544            table: table.into(),
545            entry: OutputEntry { media_type: media_type.into(), extension: extension.into() },
546            made_from: Vec::new(),
547            docs: String::new(),
548        }
549    }
550
551    /// Adds `output` after the outputs already listed in
552    /// [`made_from`](OutputDef::made_from): the output's stage reads the files
553    /// of `output` to make its own. Returns `self`, for chaining.
554    pub fn made_from(mut self, output: impl Into<OutputName>) -> OutputDef {
555        self.made_from.push(output.into());
556        self
557    }
558
559    /// Sets the documentation prose. Returns `self`, for chaining.
560    pub fn docs(mut self, docs: impl Into<String>) -> OutputDef {
561        self.docs = crate::kept_docs(docs);
562        self
563    }
564}
565
566/// The lowering rules a plan prefers on one backend, where several rules can
567/// lower the same element.
568///
569/// The rules are listed most preferred first. A rule not listed is still
570/// available: the list only decides between rules that compete for one
571/// element, and where it says nothing the plan follows the rest of the rule
572/// selection order ([`SelectedRules`](crate::core::plan::SelectedRules)).
573///
574/// A selection belongs to a plan, not to the registry: a [`WorkflowDef`] holds
575/// one per backend, and a caller may replace it in its plan request.
576///
577/// It is written to data with `Serialize`; see [serialized
578/// forms](crate::core::registry#serialized-forms).
579#[derive(Debug, Clone, Default, PartialEq, Eq)]
580#[derive(serde::Serialize, schemars::JsonSchema)]
581pub struct LoweringSelection {
582    /// The preferred rules, most preferred first.
583    pub prefer: Vec<RuleName>,
584}
585
586impl LoweringSelection {
587    /// A selection that prefers no rule.
588    pub fn new() -> LoweringSelection {
589        LoweringSelection::default()
590    }
591
592    /// Adds `rule` after the rules already listed, as less preferred than
593    /// them. Returns `self`, for chaining.
594    pub fn prefer(mut self, rule: impl Into<RuleName>) -> LoweringSelection {
595        self.prefer.push(rule.into());
596        self
597    }
598}
599
600/// A workflow declaration. A **workflow** is a named set of demands together
601/// with the choices that go with them: which outputs to produce, which other
602/// capabilities to demand, and how to make the choices a plan has to make.
603///
604/// A workflow is data held in the registry, so a caller chooses one by name
605/// instead of writing a plan request by hand (the `flm` program's option
606/// `-p html` does so, the profile `html` running the workflow `html`). A plan request built from a workflow demands the
607/// capability of each listed output and each extra capability, and carries the
608/// workflow's stage preferences, lowering selections, elements accepted as
609/// unrenderable and render option values.
610///
611/// A workflow may extend another (`extends`). The fields are then read along
612/// the chain from the workflow that extends none towards this one, and each
613/// field is taken from the nearest workflow along the chain that declares it
614/// (see [`replace_declared_fields`](WorkflowDef::replace_declared_fields)): a
615/// workflow that lists outputs replaces the inherited list instead of adding to
616/// it, and a workflow that lists none inherits the whole list. A chain may not
617/// lead back to a workflow already in it ([`BuildError::ExtendsCycle`]).
618///
619/// Register the declaration with
620/// [`FeatureBuilder::workflow`](super::FeatureBuilder::workflow). A feature can
621/// also change some fields of a workflow that another feature may declare, with
622/// [`FeatureBuilder::workflow_fields`](super::FeatureBuilder::workflow_fields).
623/// [`FlmRegistry::combined_workflow`](super::FlmRegistry::combined_workflow)
624/// returns a workflow with the fields it inherits.
625///
626/// It is written to data with `Serialize`; see [serialized
627/// forms](crate::core::registry#serialized-forms).
628///
629/// # Examples
630///
631/// ```
632/// use flm_core::core::registry::{LoweringSelection, WorkflowDef};
633///
634/// let base = WorkflowDef::new("check").demand("flm.validated");
635/// let text = WorkflowDef::new("text")
636///     .extends("check")
637///     .output("text")
638///     .lowering("text", LoweringSelection::new().prefer("flm.heading.lower.underline"));
639/// assert_eq!(text.extends.as_deref().map(|n| n.as_str()), Some("check"));
640/// ```
641#[derive(Debug, Clone)]
642#[derive(serde::Serialize, schemars::JsonSchema)]
643pub struct WorkflowDef {
644    /// The workflow's name, as a caller writes it.
645    pub name: WorkflowName,
646    /// The workflow this one extends, if any: the workflow whose fields this
647    /// one inherits where it does not declare its own.
648    pub extends: Option<WorkflowName>,
649    /// The outputs to produce; a plan built from the workflow demands the
650    /// capability of each.
651    pub outputs: Vec<OutputName>,
652    /// The capabilities demanded besides those of the outputs, typically the
653    /// checks to run as well. A collection may be listed here.
654    pub demands: Vec<CapName>,
655    /// The stages preferred where several stages could provide the same
656    /// capability, most preferred first.
657    pub prefer: Vec<StageName>,
658    /// The lowering rules preferred on each backend.
659    pub lowering: BTreeMap<BackendName, LoweringSelection>,
660    /// For each backend, the elements this workflow accepts as unrenderable:
661    /// elements with no lowering into the backend's native set. The plan is
662    /// built anyway, and each occurrence of such an element is lowered to a
663    /// `flm.pres.unsupported` node (see
664    /// [`PlanRequest::unsupported`](crate::core::plan::PlanRequest::unsupported)).
665    pub unsupported: BTreeMap<BackendName, Vec<ElementName>>,
666    /// The option values this workflow sets on the render request. The
667    /// registry build refuses a value whose option type no feature declares or
668    /// cannot be set on a render request (see
669    /// [`Bind`](crate::model::options::Bind)).
670    #[serde(skip)]
671    pub render_options: OptionValues,
672    /// Documentation prose.
673    pub docs: String,
674}
675
676impl WorkflowDef {
677    /// A workflow called `name` that extends nothing and declares no field.
678    pub fn new(name: impl Into<WorkflowName>) -> WorkflowDef {
679        WorkflowDef {
680            name: name.into(),
681            extends: None,
682            outputs: Vec::new(),
683            demands: Vec::new(),
684            prefer: Vec::new(),
685            lowering: BTreeMap::new(),
686            unsupported: BTreeMap::new(),
687            render_options: OptionValues::new(),
688            docs: String::new(),
689        }
690    }
691
692    /// Makes this workflow extend `workflow`, so that it inherits every field
693    /// it does not declare. Returns `self`, for chaining.
694    pub fn extends(mut self, workflow: impl Into<WorkflowName>) -> WorkflowDef {
695        self.extends = Some(workflow.into());
696        self
697    }
698
699    /// Adds an output to produce, after those already listed. Returns `self`,
700    /// for chaining.
701    pub fn output(mut self, output: impl Into<OutputName>) -> WorkflowDef {
702        self.outputs.push(output.into());
703        self
704    }
705
706    /// Adds a capability (or a collection) to demand besides those of the
707    /// outputs. Returns `self`, for chaining.
708    pub fn demand(mut self, capability: impl Into<CapName>) -> WorkflowDef {
709        self.demands.push(capability.into());
710        self
711    }
712
713    /// Adds a preferred stage, after those already listed, as less preferred
714    /// than them. Returns `self`, for chaining.
715    pub fn prefer(mut self, stage: impl Into<StageName>) -> WorkflowDef {
716        self.prefer.push(stage.into());
717        self
718    }
719
720    /// Sets the lowering selection for the backend `backend`, replacing any
721    /// selection already set for it. Returns `self`, for chaining.
722    pub fn lowering(
723        mut self,
724        backend: impl Into<BackendName>,
725        selection: LoweringSelection,
726    ) -> WorkflowDef {
727        self.lowering.insert(backend.into(), selection);
728        self
729    }
730
731    /// Accepts `element` as unrenderable on the backend `backend`: when the
732    /// element has no lowering into the backend's native set, the plan is
733    /// built anyway and each occurrence is lowered to a
734    /// `flm.pres.unsupported` node. Returns `self`, for chaining.
735    pub fn unsupported(
736        mut self,
737        backend: impl Into<BackendName>,
738        element: impl Into<ElementName>,
739    ) -> WorkflowDef {
740        self.unsupported.entry(backend.into()).or_default().push(element.into());
741        self
742    }
743
744    /// Sets the option values this workflow sets on the render request,
745    /// replacing any values already set. Returns `self`, for chaining.
746    pub fn render_options(mut self, options: OptionValues) -> WorkflowDef {
747        self.render_options = options;
748        self
749    }
750
751    /// Sets the documentation prose. Returns `self`, for chaining.
752    pub fn docs(mut self, docs: impl Into<String>) -> WorkflowDef {
753        self.docs = crate::kept_docs(docs);
754        self
755    }
756
757    /// Replaces each field of this workflow that `other` declares by `other`'s
758    /// value, and keeps this workflow's name and every field that `other`
759    /// does not declare.
760    ///
761    /// A field is declared when it is set: `extends` given, a list or a map
762    /// not empty, `docs` not empty. This is the rule by which a workflow
763    /// replaces the fields of the workflow it extends, and by which the fields
764    /// registered with
765    /// [`FeatureBuilder::workflow_fields`](super::FeatureBuilder::workflow_fields)
766    /// replace those of a workflow.
767    pub fn replace_declared_fields(&mut self, other: WorkflowDef) {
768        let WorkflowDef { name: _, extends, outputs, demands, prefer, lowering, unsupported, render_options, docs } =
769            other;
770        if extends.is_some() {
771            self.extends = extends;
772        }
773        if !outputs.is_empty() {
774            self.outputs = outputs;
775        }
776        if !demands.is_empty() {
777            self.demands = demands;
778        }
779        if !prefer.is_empty() {
780            self.prefer = prefer;
781        }
782        if !lowering.is_empty() {
783            self.lowering = lowering;
784        }
785        if !unsupported.is_empty() {
786            self.unsupported = unsupported;
787        }
788        if !render_options.is_empty() {
789            self.render_options = render_options;
790        }
791        if !docs.is_empty() {
792            self.docs = docs;
793        }
794    }
795}
796
797/// One part of the content of a style or script definition: the text itself,
798/// a file that the host reads, an address that the page loads, or the text a
799/// document-scope table holds for the document being written.
800///
801/// A definition's content is an ordered list of parts ([`StyleDef::content`],
802/// [`ScriptDef::content`]), so that one identifier can cover one concern even
803/// when the concern needs several parts. For example, the HTML backend's
804/// formula renderer is one script definition whose first part is its
805/// configuration, given as text, and whose second part is the address its
806/// program is loaded from.
807#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize)]
808#[derive(schemars::JsonSchema)]
809#[serde(rename_all = "kebab-case")]
810pub enum DefContent {
811    /// The content, given directly.
812    Inline(String),
813    /// A file, written the way the host writes file paths. This library never
814    /// opens it; the host does.
815    File(String),
816    /// An address the page loads, such as a stylesheet link or a script
817    /// source. This library never fetches it; it only writes it into the
818    /// page.
819    Url(String),
820    /// The text a document-scope table of the value type [`DefinitionText`]
821    /// holds, named here: content known only once the document is read (a
822    /// configuration listing what the document uses, a stylesheet computed
823    /// per document), written by a stage of the feature that declares the
824    /// definition and the table.
825    ///
826    /// The backend that resolves the definitions reads the table and puts its
827    /// text in the part's place, as an [`Inline`](DefContent::Inline) part, so
828    /// that nothing after the resolution meets this form; where the table is
829    /// absent or empty, the part is empty and the backend reports it. The
830    /// form names a table of the registry and is not something a host's
831    /// settings can give, so the settings do not read it.
832    #[serde(skip_deserializing)]
833    #[schemars(skip)]
834    Table(CapName),
835}
836
837/// The value type of a table that supplies a part of a style or script
838/// definition ([`DefContent::Table`]): one text, the part's content for the
839/// document being written.
840///
841/// The feature that declares the definition declares the table under this
842/// value type, at document scope, and a stage of its own writes it. A piece
843/// that holds a non-empty text replaces what the table held, so the table
844/// holds the text of the last stage that wrote one.
845#[derive(Debug, Clone, Default, PartialEq, Eq)]
846pub struct DefinitionText {
847    /// The part's text.
848    pub text: String,
849}
850
851impl DefinitionText {
852    /// The table value holding `text`.
853    pub fn new(text: impl Into<String>) -> DefinitionText {
854        DefinitionText { text: text.into() }
855    }
856}
857
858impl Table for DefinitionText {
859    fn absorb(&mut self, piece: DefinitionText) {
860        if !piece.text.is_empty() {
861            self.text = piece.text;
862        }
863    }
864
865    /// The text, as a string.
866    fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
867        SerialValue::Str(self.text.clone())
868    }
869}
870
871/// A style definition: a stylesheet that a feature's output depends on.
872///
873/// A **style definition** (`StyleDef`) or a **script definition**
874/// ([`ScriptDef`]) is a stylesheet or a script that a feature's output depends
875/// on, recorded in the registry under an identifier; a lowering rule or an
876/// emitter *requires* it by identifier, and the backend that writes the output
877/// decides its *delivery*: written into the output, loaded from an address, or
878/// left to the host.
879///
880/// A **requirement** is an identifier that a lowering rule or an emitter
881/// records to say that its output needs a definition. Two features that
882/// require the same definition therefore require it once, because both use
883/// its identifier. A backend that has no use for a stylesheet, such as the
884/// plain-text backend, records the requirements and reads none.
885///
886/// Register a style definition with
887/// [`FeatureBuilder::style_def`](super::FeatureBuilder::style_def); the
888/// finished registry lists them in
889/// [`FlmRegistry::styles`](super::FlmRegistry::styles). See also [style and
890/// script
891/// definitions](crate::guide::concepts_overview#style-and-script-definitions).
892#[derive(Debug, Clone, PartialEq, Eq)]
893pub struct StyleDef {
894    /// The definition's identifier, the one a requirement refers to; two
895    /// definitions with the same identifier are the same stylesheet.
896    pub id: Name,
897    /// The stylesheet, as an ordered list of parts ([`DefContent`]). An output
898    /// that includes the definition writes the parts in this order.
899    pub content: Vec<DefContent>,
900    /// Documentation prose.
901    pub docs: String,
902}
903
904/// A script definition: a script that a feature's output depends on, recorded
905/// in the registry under an identifier; the counterpart of [`StyleDef`] for
906/// scripts, with the same fields and the same rules.
907///
908/// Register a script definition with
909/// [`FeatureBuilder::script_def`](super::FeatureBuilder::script_def); the
910/// finished registry lists them in
911/// [`FlmRegistry::scripts`](super::FlmRegistry::scripts), and the backend that
912/// writes the output resolves the requirements against them.
913#[derive(Debug, Clone, PartialEq, Eq)]
914pub struct ScriptDef {
915    /// The definition's identifier, the one a requirement refers to; two
916    /// definitions with the same identifier are the same script.
917    pub id: Name,
918    /// The script, as an ordered list of parts ([`DefContent`]). An output
919    /// that includes the definition writes the parts in this order, so a
920    /// configuration can be written before the program it configures.
921    pub content: Vec<DefContent>,
922    /// Documentation prose.
923    pub docs: String,
924}
925
926/// A build hook that runs in the registry build's second registration round,
927/// after every feature has registered, so that a feature can declare things
928/// that depend on what other features contributed to service slots.
929///
930/// Registration has exactly two rounds. In the first round,
931/// [`FlmFeature::register`](super::FlmFeature::register), each feature
932/// declares what it can declare by itself. Between the rounds, the build
933/// assembles the service slots from the contributions (see [services and service
934/// slots](crate::guide::concepts_overview#services-and-service-slots)). In the
935/// second round, each finalizer reads the assembled services through
936/// [`FeatureBuilder::services`](super::FeatureBuilder::services) and declares
937/// further entities (an element, a stage, a lowering rule) derived from what it
938/// finds.
939///
940/// The service slots are complete by then, so a finalizer may not declare a
941/// service slot, contribute to one, require one, or register another
942/// finalizer; the builder refuses each of these with
943/// [`BuildError::ContributionAfterAssembly`]. There are exactly two rounds,
944/// instead of rounds repeated until nothing changes, so that the build always
945/// ends and its order is easy to follow.
946///
947/// Register a finalizer with
948/// [`FeatureBuilder::finalizer`](super::FeatureBuilder::finalizer).
949pub trait Finalizer: Send + Sync {
950    /// Declares, by calling methods of `b`, what this feature derives from the
951    /// assembled services.
952    ///
953    /// # Errors
954    ///
955    /// Return a [`BuildError`] to refuse the build. The build records it
956    /// attributed to the feature that registered this finalizer (an error
957    /// other than [`BuildError::Feature`] and
958    /// [`BuildError::ContributionAfterAssembly`] is wrapped in a
959    /// [`BuildError::Feature`]), runs the other finalizers, and then fails at
960    /// the end of the finalize phase.
961    fn finalize(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError>;
962}
963
964/// The error a [`LateInit`] hook returns when the hook itself cannot do its
965/// work.
966///
967/// A problem with the configuration the hook prepares (for example, a template
968/// that does not parse) is not a failure of the hook: the hook writes it to
969/// the build diagnostics instead (see [`LateInit::late_init`]).
970#[derive(Debug, Clone, PartialEq, Eq)]
971pub struct LateInitError {
972    /// What failed, as text for a person to read.
973    pub detail: String,
974}
975
976impl LateInitError {
977    /// An error whose text is `detail`.
978    pub fn new(detail: impl Into<String>) -> LateInitError {
979        LateInitError { detail: detail.into() }
980    }
981}
982
983impl fmt::Display for LateInitError {
984    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
985        f.write_str(&self.detail)
986    }
987}
988
989impl std::error::Error for LateInitError {}
990
991/// A build hook that runs once the language that documents are parsed with
992/// ([`FlmRegistry::lang`](super::FlmRegistry::lang)) is built, for the work a
993/// feature can do only with the finished language.
994///
995/// The usual work is compiling templates. A feature configured with
996/// author-written definitions cannot parse them while the language is still
997/// being built, because a definition may use commands that other features
998/// declare. This hook runs after the language is complete, so each template is
999/// parsed once, when the registry is built, instead of once per use.
1000///
1001/// The hook keeps two kinds of problem apart. A problem with the
1002/// *configuration* it prepares (a template that does not parse, or a warning
1003/// about one) is not a failure of the hook: the hook writes it to `diags`, and
1004/// the finished registry holds it among its **build diagnostics**
1005/// ([`FlmRegistry::build_diagnostics`](super::FlmRegistry::build_diagnostics)),
1006/// which the embedding program can report once per build. The registry is
1007/// still built. (The user-definitions feature, for example, reports a refused
1008/// definition again wherever a document uses it.) Returning `Err` means that the hook itself could not do its work, and the
1009/// registry build fails.
1010///
1011/// A value that the hook builds against the language (a compiled template, a
1012/// parsed tree) and that an element's data or aspect reads is stored in a
1013/// [`LangOwned`](crate::lang::LangOwned) cell, so that the language owns it.
1014///
1015/// Register a hook with
1016/// [`FeatureBuilder::late_init`](super::FeatureBuilder::late_init).
1017pub trait LateInit: Send + Sync {
1018    /// Prepares what needs the finished language `lang`, and writes every
1019    /// problem with the configuration to `diags`.
1020    ///
1021    /// # Errors
1022    ///
1023    /// A [`LateInitError`] when the hook itself fails. The build records it as
1024    /// a [`BuildError::LateInit`] attributed to the feature that registered
1025    /// the hook, runs the other hooks, and then fails at the end of the
1026    /// late-initialization phase.
1027    fn late_init(&self, lang: &BuiltLang, diags: &mut FlmDiagnostics) -> Result<(), LateInitError>;
1028}
1029
1030/// A native-set implication: a requirement on what a backend's native set must
1031/// contain, checked against every backend when the registry is built.
1032///
1033/// A backend's *native set* is the list of elements its emit stage writes
1034/// directly ([`BackendDef::native`]). Lowering rules turn every other element
1035/// into those elements, and plan construction follows the rules' `produces`
1036/// declarations to check that the backend can write everything a document may
1037/// contain. Two elements are outside that check, because the lowering driver
1038/// creates their nodes itself, with no rule declaring them:
1039/// `flm.pres.deco-mark`, the node left where a decoration was moved out of a
1040/// content run into an attached slot (see [decorations, roles and
1041/// kinds](crate::guide::concepts_overview#decorations-roles-and-kinds)), and
1042/// `flm.pres.unsupported`, the stand-in node for an element accepted as
1043/// unrenderable or for an element whose rule failed. A backend must still
1044/// write these elements natively. Without a declared requirement, a backend
1045/// that omits one would fail only at lowering, with a missing-rule error, at
1046/// the first document that needs the element. A native-set implication states
1047/// the requirement as data: the registry build checks it and fails with
1048/// [`BuildError::NativeSetIncomplete`], which identifies the backend, the
1049/// element it must also write natively and, where there is one, the native
1050/// element that made the implication apply.
1051///
1052/// An implication takes one of two forms, given by its
1053/// [`NativeImplicationKind`]:
1054///
1055/// - [`always`](NativeImplication::always): every backend of the registry must
1056///   write the element natively.
1057/// - [`aspect::<A>`](NativeImplication::aspect): a backend whose native set
1058///   holds any element carrying the aspect `A` must write the element natively
1059///   too. The aspect is given by its trait-object type, exactly as it is
1060///   attached with [`FeatureBuilder::attach`](super::FeatureBuilder::attach),
1061///   so the check compares the aspect's identity, not element names: every
1062///   element that carries the aspect counts, whichever feature registered it,
1063///   and the check runs after the aspects that features attach to other
1064///   features' elements have been merged in.
1065///
1066/// The standard feature `lowering` declares the two
1067/// implications described above. A feature whose lowering driver, emitter or
1068/// rules create nodes of an element without declaring it in a rule's
1069/// `produces` should declare an implication for it. Register one with
1070/// [`FeatureBuilder::native_implication`](super::FeatureBuilder::native_implication);
1071/// [`FlmRegistry::native_implications`](super::FlmRegistry::native_implications)
1072/// lists those a registry holds. An implication decides whether a registry
1073/// builds and never what a run produces, so it is not an input of the registry
1074/// digest.
1075///
1076/// # Examples
1077///
1078/// ```
1079/// use flm_core::core::registry::{NativeImplication, NativeImplicationKind};
1080/// use flm_core::stdlib::backends::pres::{self, Decoration};
1081///
1082/// let marker = NativeImplication::aspect::<dyn Decoration>(pres::DECO_MARK)
1083///     .docs("a backend claiming a decoration must claim the marker left in its place");
1084/// let stand_in = NativeImplication::always(pres::UNSUPPORTED);
1085/// assert_eq!(stand_in.kind, NativeImplicationKind::Always);
1086/// assert!(matches!(marker.kind, NativeImplicationKind::Aspect { .. }));
1087/// assert_eq!(marker.must_claim, pres::DECO_MARK);
1088/// ```
1089#[derive(Debug, Clone, PartialEq, Eq)]
1090pub struct NativeImplication {
1091    /// The element a backend must write natively when the implication
1092    /// applies to it. Some feature of the same registry must declare it.
1093    pub must_claim: ElementName,
1094    /// When the implication applies to a backend.
1095    pub kind: NativeImplicationKind,
1096    /// Documentation prose: why a backend must write the element natively.
1097    pub docs: String,
1098}
1099
1100/// When a [`NativeImplication`] applies to a backend.
1101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1102pub enum NativeImplicationKind {
1103    /// To every backend of the registry.
1104    Always,
1105    /// To a backend whose native set holds any element that carries the
1106    /// aspect identified here.
1107    Aspect {
1108        /// The identity of the aspect's trait-object type: `TypeId::of::<A>()`
1109        /// for an aspect attached as `dyn A`, the same key under which an
1110        /// element's aspect map holds the aspect.
1111        id: TypeId,
1112        /// The aspect's type name, for messages and documentation.
1113        name: &'static str,
1114    },
1115}
1116
1117impl NativeImplication {
1118    /// An implication that requires every backend to write `element`
1119    /// natively, with no documentation.
1120    pub fn always(element: impl Into<ElementName>) -> NativeImplication {
1121        NativeImplication {
1122            must_claim: element.into(),
1123            kind: NativeImplicationKind::Always,
1124            docs: String::new(),
1125        }
1126    }
1127
1128    /// An implication that requires a backend whose native set holds any
1129    /// element carrying the aspect `A` to write `element` natively as well;
1130    /// with no documentation.
1131    ///
1132    /// Write `A` as the aspect's trait-object type, as in
1133    /// `NativeImplication::aspect::<dyn Decoration>(pres::DECO_MARK)`, with
1134    /// the same bounds as
1135    /// [`FeatureBuilder::attach`](super::FeatureBuilder::attach). A concrete
1136    /// type fails to compile: an aspect is attached under its trait-object
1137    /// type, so an implication keyed by any other type would match no element
1138    /// and never apply.
1139    pub fn aspect<A: ?Sized + Any + Send + Sync>(
1140        element: impl Into<ElementName>,
1141    ) -> NativeImplication {
1142        const {
1143            assert!(
1144                size_of::<&A>() == 2 * size_of::<*const ()>(),
1145                "the aspect must be given as its trait-object type, as in \
1146                 NativeImplication::aspect::<dyn MyAspect>(…)"
1147            );
1148        }
1149        NativeImplication {
1150            must_claim: element.into(),
1151            kind: NativeImplicationKind::Aspect {
1152                id: TypeId::of::<A>(),
1153                name: std::any::type_name::<A>(),
1154            },
1155            docs: String::new(),
1156        }
1157    }
1158
1159    /// Sets the documentation prose. Returns `self`, for chaining.
1160    pub fn docs(mut self, docs: impl Into<String>) -> NativeImplication {
1161        self.docs = crate::kept_docs(docs);
1162        self
1163    }
1164
1165    /// Whether a backend whose native set holds `element` must satisfy this
1166    /// implication: always, for the [`Always`](NativeImplicationKind::Always)
1167    /// form; for the [`Aspect`](NativeImplicationKind::Aspect) form, when
1168    /// `element` carries the aspect.
1169    pub fn applies_to(&self, element: &ElementSpec) -> bool {
1170        match self.kind {
1171            NativeImplicationKind::Always => true,
1172            NativeImplicationKind::Aspect { id, .. } => {
1173                element.aspects.aspect_ids().any(|attached| attached == id)
1174            }
1175        }
1176    }
1177}
1178
1179/// The kind and name of the entity a peer declaration refers to.
1180///
1181/// A **peer declaration** is a feature's forward declaration of an element,
1182/// element type, table, service slot, scoped package, argument role or
1183/// backend that another feature owns,
1184/// with the element's payload type or the table's value type as the
1185/// signature; the registry build resolves it after every feature has
1186/// registered, and a lowering rule that depends on a name nobody declares is
1187/// set aside (excluded from rule selection, with one build Note).
1188///
1189/// It is written to data with `Serialize`; see [serialized
1190/// forms](crate::core::registry#serialized-forms).
1191///
1192/// # Why peer declarations exist
1193///
1194/// The registry build refuses a reference to an entity that no feature
1195/// declares. A feature may still ship lowering rules that use entities another
1196/// feature owns: for example, a content feature's rule that writes its element
1197/// back as LaTeX is the default rule on the LaTeX backend, builds that
1198/// backend's presentation elements, and reads a table that the references
1199/// feature computes. The feature declares each such entity as a peer
1200/// declaration, so that its own rules may refer to it. A peer declaration
1201/// registers nothing and counts for the declaring feature alone: another
1202/// feature that refers to the same entity makes its own declaration.
1203///
1204/// # The seven kinds
1205///
1206/// | Variant | Entity another feature owns | Declared with |
1207/// |---|---|---|
1208/// | [`Backend`](PeerName::Backend) | a backend a rule is the default on | [`FeatureBuilder::peer_backend`](super::FeatureBuilder::peer_backend) |
1209/// | [`Element`](PeerName::Element) | a presentation element a rule produces; its payload type is the signature | [`FeatureBuilder::peer_element`](super::FeatureBuilder::peer_element) |
1210/// | [`Table`](PeerName::Table) | a table a rule reads or a stage writes; its value type is the signature | [`FeatureBuilder::peer_table`](super::FeatureBuilder::peer_table) |
1211/// | [`Slot`](PeerName::Slot) | a service slot the feature contributes a value to | [`FeatureBuilder::peer_slot`](super::FeatureBuilder::peer_slot) |
1212/// | [`ScopedPackage`](PeerName::ScopedPackage) | a scoped package the feature's environment bodies or arguments refer to | [`FeatureBuilder::peer_scoped_package`](super::FeatureBuilder::peer_scoped_package) |
1213/// | [`ElementType`](PeerName::ElementType) | an element type of which the feature declares one more value, with the commands that produce it | [`FeatureBuilder::peer_element_value`](super::FeatureBuilder::peer_element_value) |
1214/// | [`ArgumentRole`](PeerName::ArgumentRole) | an argument role the feature sets on arguments of its own declarations | [`FeatureBuilder::peer_argument_role`](super::FeatureBuilder::peer_argument_role) |
1215///
1216/// A **peer contribution** (the `Slot` kind) and a peer element value (the
1217/// `ElementType` kind) carry something besides a name: a value for the service slot,
1218/// and an element declaration. A feature **declares an element type** when any
1219/// of its declarations other than a peer element value creates an element of
1220/// that name: an [`element`](super::FeatureBuilder::element) declaration, an
1221/// element of a scoped package, a fallback, a presentation element or a field;
1222/// that feature's rules and stages serve every value of the type.
1223///
1224/// # How the build resolves peer declarations
1225///
1226/// When the registry is built, after every feature has registered, each peer
1227/// declaration is **resolved** against the declarations of all features.
1228///
1229/// - **The name is declared.** The declaration resolves to that entity, and
1230///   the rules that refer to it take part like any other rule. For an element,
1231///   the payload type must match the signature
1232///   ([`BuildError::PeerElementMismatch`] otherwise); for a table, the value
1233///   type must match ([`BuildError::PeerTableMismatch`] otherwise). A
1234///   contribution fills the service slot; a scoped package is available in the bodies
1235///   and arguments that refer to it; an element value is kept as a plain
1236///   [`element`](super::FeatureBuilder::element) declaration would be; an
1237///   argument role is the declared role, described by its declaration.
1238/// - **No feature declares the name.** The declaration stays *unresolved*. The
1239///   build still succeeds, and one Note,
1240///   [`UnresolvedPeer`](super::UnresolvedPeer), joins the registry's
1241///   [build diagnostics](super::FlmRegistry::build_diagnostics) for each
1242///   feature and name (one per service slot or element type, however many values the
1243///   feature gave for it). What else happens depends on the kind:
1244///   - every lowering rule of the declaring feature that **depends** on the
1245///     name is **set aside**: excluded from rule selection and from the check
1246///     that a backend can write every element, as if it had not been
1247///     registered, while staying listed on the registry
1248///     ([`RuleEntry::set_aside`](super::RuleEntry::set_aside),
1249///     [`FlmRegistry::set_aside_rules`](super::FlmRegistry::set_aside_rules)).
1250///     A rule depends on a backend it is the default on, on an element it
1251///     produces, and on a table it reads as a hard dependency (`reads`). A rule
1252///     that reads the table only optionally (`reads_opt`) is not set aside: it
1253///     runs and finds the table absent, so it writes what it can without the
1254///     other feature;
1255///   - every stage of the declaring feature that writes an unresolved peer
1256///     table is set aside too, and is not registered at all, since it would
1257///     have nowhere to write;
1258///   - a contribution to an unresolved service slot is dropped;
1259///   - the bodies and arguments that refer to an unresolved scoped package get
1260///     no definitions from it, so a command the package would define is an
1261///     unknown command there;
1262///   - an element value of an unresolved element type is dropped, so its
1263///     commands are unknown commands;
1264///   - the arguments that have an unresolved argument role keep it, and the
1265///     registry holds no description of the role.
1266///
1267/// No rule depends on a service slot, a scoped package, an element type or an
1268/// argument role, so none is set aside for one of these.
1269///
1270/// The registry lists every peer declaration, resolved or not, so a
1271/// misspelled name can be found on any registry that holds the feature:
1272/// [`FlmRegistry::peer_backends`](super::FlmRegistry::peer_backends),
1273/// [`FlmRegistry::peer_elements`](super::FlmRegistry::peer_elements),
1274/// [`FlmRegistry::peer_tables`](super::FlmRegistry::peer_tables),
1275/// [`FlmRegistry::peer_slots`](super::FlmRegistry::peer_slots),
1276/// [`FlmRegistry::peer_scoped_packages`](super::FlmRegistry::peer_scoped_packages),
1277/// [`FlmRegistry::peer_element_values`](super::FlmRegistry::peer_element_values)
1278/// and
1279/// [`FlmRegistry::peer_argument_roles`](super::FlmRegistry::peer_argument_roles).
1280///
1281/// # Repeated declarations
1282///
1283/// A feature may declare one name more than once. A declaration registers
1284/// nothing, so an identical repeat (the same name and, for an element or a
1285/// table, the same signature type) is merged into the first declaration, whose
1286/// documentation text is kept. A function that declares on a feature's behalf
1287/// can therefore declare every name it needs without checking what the feature
1288/// declared already. A repeat with another signature is refused when the
1289/// registry is built, as [`BuildError::Duplicate`]. Two features may each
1290/// declare the same name, since a declaration counts for its own feature
1291/// alone.
1292///
1293/// # Peer declarations and external tables
1294///
1295/// A peer table is not an external table
1296/// ([`Externals`](crate::core::run::Externals)): an external table is a table
1297/// that no stage of the run writes, whose value the caller installs when the
1298/// run is constructed, and the feature that declares it registers it with
1299/// [`FeatureBuilder::external_table`](super::FeatureBuilder::external_table). A
1300/// peer declaration refers to an entity inside the pipeline that another
1301/// feature owns.
1302///
1303/// Peer declarations are not inputs of the registry digest, except that a
1304/// resolved peer element value is digested as the element declaration it
1305/// becomes: whether one resolves follows from which features the registry
1306/// holds, and the digest already covers those.
1307#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1308#[derive(serde::Serialize, schemars::JsonSchema)]
1309// The serialized kind is the word `PeerName::kind` gives, which the condition
1310// `flm.registry.unresolved-peer` also carries in its data: one spelling of
1311// each kind.
1312#[serde(tag = "kind", content = "name", rename_all = "lowercase")]
1313pub enum PeerName {
1314    /// A backend, declared as a peer with
1315    /// [`FeatureBuilder::peer_backend`](super::FeatureBuilder::peer_backend).
1316    Backend(BackendName),
1317    /// A presentation element, declared as a peer with
1318    /// [`FeatureBuilder::peer_element`](super::FeatureBuilder::peer_element).
1319    Element(ElementName),
1320    /// A table, declared as a peer with
1321    /// [`FeatureBuilder::peer_table`](super::FeatureBuilder::peer_table).
1322    Table(CapName),
1323    /// A service slot, given by the contribution a feature makes to it with
1324    /// [`FeatureBuilder::peer_slot`](super::FeatureBuilder::peer_slot). No
1325    /// rule depends on a service slot, so this kind never appears in a rule's
1326    /// [`set_aside`](super::RuleEntry::set_aside) list.
1327    Slot(Name),
1328    /// A scoped package, declared as a peer with
1329    /// [`FeatureBuilder::peer_scoped_package`](super::FeatureBuilder::peer_scoped_package).
1330    /// No rule depends on a scoped package, so this kind never appears in a
1331    /// rule's [`set_aside`](super::RuleEntry::set_aside) list.
1332    #[serde(rename = "scoped package")]
1333    ScopedPackage(Name),
1334    /// An element type, given by the element value a feature declares of it
1335    /// with
1336    /// [`FeatureBuilder::peer_element_value`](super::FeatureBuilder::peer_element_value).
1337    /// No rule depends on an element type through this declaration, so this
1338    /// kind never appears in a rule's
1339    /// [`set_aside`](super::RuleEntry::set_aside) list.
1340    #[serde(rename = "element type")]
1341    ElementType(ElementName),
1342    /// An argument role, declared as a peer with
1343    /// [`FeatureBuilder::peer_argument_role`](super::FeatureBuilder::peer_argument_role).
1344    /// No rule depends on an argument role, so this kind never appears in a
1345    /// rule's [`set_aside`](super::RuleEntry::set_aside) list.
1346    #[serde(rename = "argument role")]
1347    ArgumentRole(Name),
1348}
1349
1350impl PeerName {
1351    /// The word a message uses for this kind of entity: `backend`, `element`,
1352    /// `table`, `slot`, `scoped package`, `element type` or `argument role`.
1353    pub fn kind(&self) -> &'static str {
1354        match self {
1355            PeerName::Backend(_) => "backend",
1356            PeerName::Element(_) => "element",
1357            PeerName::Table(_) => "table",
1358            PeerName::Slot(_) => "slot",
1359            PeerName::ScopedPackage(_) => "scoped package",
1360            PeerName::ElementType(_) => "element type",
1361            PeerName::ArgumentRole(_) => "argument role",
1362        }
1363    }
1364
1365    /// The entity's name, for every kind.
1366    pub fn name(&self) -> &Name {
1367        match self {
1368            PeerName::Backend(backend) => backend.name(),
1369            PeerName::Element(element) => element.name(),
1370            PeerName::Table(table) => table.name(),
1371            PeerName::Slot(slot) => slot,
1372            PeerName::ScopedPackage(package) => package,
1373            PeerName::ElementType(element) => element.name(),
1374            PeerName::ArgumentRole(role) => role,
1375        }
1376    }
1377}
1378
1379impl fmt::Display for PeerName {
1380    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1381        write!(f, "{} `{}`", self.kind(), self.name())
1382    }
1383}